title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Node.js URL() Method
18 Aug, 2020 The ‘url’ module provides utilities for URL resolution and parsing. The getters and setters implement the properties of URL objects on the class prototype, and the URL class is available on the global object. The new URL() (Added in v7.0.0, v6.13.0) method is an inbuilt application programming interface of the URL module which creates a new URL object by parsing the input relative to the base. If the base is passed as a string, it will be parsed equivalent to new URL(base). Syntax: new URL(input[, base]) The ‘url’ module can be accessed using: const url = require('url'); Parameters: This method accepts two parameters as mentioned above and described below: input <string>: It is the input which is string type that is used to parse the absolute or relative input URL. The base is required if the input is relative and ignored if the input is absolute. base <string> | <URL>: It is the base URL which is either of string type or URL, used to resolve against if the input is absolute or not. Return Value: It returns the new URL generated along with an array of data like hostname, protocol, pathname, etc. Example 1: Filename: index.js Javascript // Node.js program to demonstrate the // new URL() method // Using require to access url module const url = require('url'); const newUrl = new URL( 'https://geeksforgeeks.org/p/a/t/h?query=string#hash'); // url array in JSON Formatconsole.log(newUrl); const myUR = url.parse( 'https://geeksforgeeks.org/:3000/p/a/t/h?query=string#hash');console.log(myUR);console.log(URL === require('url').URL); const myURL1 = new URL( { toString: () => 'https://geeksforgeeks.org/' }); console.log(myURL1.href) Output: URL {href: ‘https://geeksforgeeks.org/p/a/t/h?query=string#hash’,origin: ‘https://geeksforgeeks.org’,protocol: ‘https:’,username: ”,password: ”,host: ‘geeksforgeeks.org’,hostname: ‘geeksforgeeks.org’,port: ”,pathname: ‘/p/a/t/h’,search: ‘?query=string’,searchParams: URLSearchParams { ‘query’ => ‘string’ },hash: ‘#hash’}Url {protocol: ‘https:’,slashes: true,auth: null,host: ‘geeksforgeeks.org’,port: null,hostname: ‘geeksforgeeks.org’,hash: ‘#hash’,search: ‘?query=string’,query: ‘query=string’,pathname: ‘/:3000/p/a/t/h’,path: ‘/:3000/p/a/t/h?query=string’,href: ‘https://geeksforgeeks.org/:3000/p/a/t/h?query=string#hash’}truehttps://geeksforgeeks.org/ Example 2: Filename: index.js Javascript // Node.js program to demonstrate the // new URL() method // Using require to access url module const url = require('url');const parseURL = url.parse('https://geeksforgeeks.org:3000/p/a/t/h?query=string#hash'); console.log("1 =>", parseURL) // Prints parsed URLconst newUrl1 = new URL('https://gfg.com'); // prints https://xn--g6w251d/console.log("2 =>", newUrl1.href) const myURL = new URL('/alfa', 'https://akash.org/');console.log("3 =>", myURL.href) // https://akash.org/alfalet newUrl3 = new URL('http://Gfg.com/', 'https://gfg.org/'); // Prints http://gfg.com/console.log("4 =>", newUrl3.href) newUrl4 = new URL('https://Gfg.com/', 'https://gfg.org/'); // Prints https://gfg.com/console.log("5 =>", newUrl4.href) newUrl5 = new URL('foo://Geekyworld.com/', 'https://geekyworld.org/');// prints foo://Geekyworld.com/console.log("6 =>", newUrl5.href) newUrl6 = new URL('http:Akash.com/', 'https://akash.org/');// prints http://akash.com/console.log("7 =>", newUrl6.href) newUrl10 = new URL('http:Chota.com/', 'https://bong.org/');// prints http://bong.com/console.log("8 =>", newUrl10.href) newUrl7 = new URL('https:Chota.com/', 'https://bong.org/');// prints https://bong.org/Chota.com/console.log("9 =>", newUrl7.href) newUrl8 = new URL('foo:ALfa.com/', 'https://alfa.org/'); // Prints foo:ALfa.com/console.log("10 =>", newUrl8.href) Run index.js file using the following command: node index.js Output: 1 => Url {protocol: ‘https:’,slashes: true,auth: null,host: ‘geeksforgeeks.org:3000’,port: ‘3000’,hostname: ‘geeksforgeeks.org’,hash: ‘#hash’,search: ‘?query=string’,query: ‘query=string’,pathname: ‘/p/a/t/h’,path: ‘/p/a/t/h?query=string’,href: ‘https://geeksforgeeks.org:3000/p/a/t/h?query=string#hash’}2 => https://gfg.com/3 => https://akash.org/alfa4 => http://gfg.com/5 => https://gfg.com/6 => foo://Geekyworld.com/7 => http://akash.com/8 => http://chota.com/9 => https://bong.org/Chota.com/10 => foo:ALfa.com/ Reference: https://nodejs.org/api/url.html#url_new_url_input_base Node-URL Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Node.js fs.readFileSync() Method Node.js Date.format() API Difference between spawn() and fork() methods in Node.js Convert xml data into json using Node.js How to download a file using Node.js? 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": "\n18 Aug, 2020" }, { "code": null, "e": 237, "s": 28, "text": "The ‘url’ module provides utilities for URL resolution and parsing. The getters and setters implement the properties of URL objects on the class prototype, and the URL class i...
Thread hardware_concurrency() function in C++
30 Oct, 2018 Thread::hardware_concurrency is an in-built function in C++ std::thread. It is an observer function which means it observes a state and then returns the corresponding output. This function returns the number of concurrent threads supported by the available hardware implementation. This value might not always be accurate. Syntax: thread::hardware_concurrency() Parameters: This function does not accept any parameters. Return Value: It returns a non-negative integer denoting the number of concurrent threads supported by the system. If the value is either not computable or not well defined it returns 0. Below program demonstrate the use of std::thread::joinable() Note: On the online IDE this program will show error. To compile this, use the flag “-pthread” on g++ compilers compilation with the help of command “g++ –std=c++14 -pthread file.cpp”. // C++ program to demonstrate the use of// std::thread::hardware_concurrency() #include <chrono>#include <iostream>#include <thread>using namespace std; int main(){ unsigned int con_threads; // calculating number of concurrent threads // supported in the hardware implementation con_threads = thread::hardware_concurrency(); cout << "Number of concurrent threads supported are: " << con_threads << endl; return 0;} Possible Output Number of concurrent threads supported are: 4 cpp-multithreading STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sorting a vector in C++ Polymorphism in C++ Friend class and function in C++ Pair in C++ Standard Template Library (STL) std::string class in C++ Queue in C++ Standard Template Library (STL) Unordered Sets in C++ Standard Template Library std::find in C++ List in C++ Standard Template Library (STL) Inline Functions in C++
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Oct, 2018" }, { "code": null, "e": 351, "s": 28, "text": "Thread::hardware_concurrency is an in-built function in C++ std::thread. It is an observer function which means it observes a state and then returns the corresponding output. ...
How to Change the Color of Status Bar in an Android App?
23 Feb, 2021 A Status Bar in Android is an eye-catching part of the screen, all of the notification indication, battery life, time, connection strength, and plenty of things shows here. An Android user may look at a status bar multiple times while using an Android application. It is a very essential part of the design that the color of the status bar should follow the color combination of the layout. You can look out to many android apps on your phone and can see how they changed it according to its primary colors. There can be multiple ways for changing the status bar color but we are going to tell you about the best hand-picked two methods which you can use either in Java or Kotlin. You can follow this method in apps that are built with Kotlin or Java. It will work in both. Step 1: Open Android Studio and start a new project by selecting an empty activity. Give it a name of your choice, then select your language and API level. At last click on finish. Step 2: Find an XML file called styles.xml by navigating res/values/styles.xml. Step 3: Find another XML file by navigating res/values/colors.xml, and also add that color here which you want to change for the status bar. Step 4: Now in the style.xml file, add the below code just before the </resources> tag and change the colors of it as your choice. ColorPrimaryDark is always going to be responsible for your status bar color. XML <!-- Defined a new style with three items of color. --><style name="DemoTheme" parent="Theme.AppCompat.Light.NoActionBar"><!-- Customize your theme here. --><item name="colorPrimary">@color/colorPrimary</item> <!-- Defining that new color in ColorPrimaryDark --><item name="colorPrimaryDark">@color/colorOfStatusBar</item><item name="colorAccent">@color/colorAccent</item></style> You can do the same with android:statusBarColor but it will work only in above API Level 21. ColorPrimaryDark for the status bar will also not support in API Level 19. By default in most of the API Levels, ColorPrimaryDark will be the default color for statusBarColor, So it is good to go with changing ColorPrimaryDark. Tip: You can create multiple themes and you can use them in any activity. In any theme, There is a set of colors that needs to be defined, you can also create new colors in the colors.xml file in the same directory and use it on the styles.xml file. Step 6: Now go to the manifest/AndroidManifest.xml and here search the activity for which you want to apply that theme or change the color of the status bar. and add an attribute android:theme=”@style/DemoTheme”. That’s done! Check your application by running it on an emulator or a physical device. This method can be only used in the above API Level 21. Officially status bar color is not supporting below API Level 21. Although, Here we added an if condition, because in case if you haven’t selected above or equal to API 21 then it will check the android API Version, and then it will execute the code. It will not change the color of the status bar is below API Level 21 but the rest code will work well. Step 1: After opening the android studio and creating a new project with an empty activity. Step 2: Navigate to res/values/colors.xml, and add a color that you want to change for the status bar. Step 3: In your MainActivity, add this code in your onCreate method. Don’t forget to replace your desired color with colorName. Java Kotlin if (Build.VERSION.SDK_INT >= 21) { Window window = this.getWindow(); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); window.setStatusBarColor(this.getResources().getColor(R.color.colorPrimaryDark)); } if (Build.VERSION.SDK_INT >= 21) { val window = this.window window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) window.statusBarColor = this.resources.getColor(R.color.colorPrimaryDark) } Step 4: Try running your application on an android emulator or a physical device. See the changes. Android-Bars Android Java Kotlin Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Add Views Dynamically and Store Data in Arraylist in Android? Android RecyclerView in Kotlin Broadcast Receiver in Android With Example Android SDK and it's Components How to Create and Add Data to SQLite Database in Android? Arrays in Java Reverse a string in Java Split() String method in Java with examples Object Oriented Programming (OOPs) Concept in Java For-each loop in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n23 Feb, 2021" }, { "code": null, "e": 735, "s": 54, "text": "A Status Bar in Android is an eye-catching part of the screen, all of the notification indication, battery life, time, connection strength, and plenty of things shows here. A...
JavaScript Logical AND assignment (&&=) Operator
25 Feb, 2021 This operator is represented by x &&= y, and it is called the logical AND assignment operator. It assigns the value of y into x only if x is a truthy value. We use this operator x &&= y like this. Now break this expression into two parts, x && (x = y). If the value of x is truth, then the statement (x = y) executes and the value of y gets stored into x but if the value of x is a falsy value then the statement (x = y) does not get executed. Syntax : x &&= y is equivalent to x && (x = y) Example: Javascript <script> let name = { firstName: "Ram", lastName: "", }; console.log(name.firstName); // Changing the value using logical // AND assignment operator name.firstName &&= "Shyam"; // Here the value changed because // name.firstName is truthy console.log(name.firstName); console.log(name.lastName); // Changing the value using logical // AND assignment operator name.lastName &&= "Kumar"; // Here the value remains unchanged // because name.lastName is falsy console.log(name.lastName);</script> Output : "Ram" "Shyam" "" "" Example 2: HTML <!DOCTYPE html><html> <body> <h1>Hello Geeksforgeeks</h1> <p id="print_arr"></p> <script> let arr = [1, 2, "apple", null, undefined, []] // Replace each truthy values with "gfg" arr.forEach((item, index)=>{ arr[index] &&= "gfg" }) document.getElementById("print_arr").innerText = arr.toString(); //console.log(arr) </script> </body></html> Output : Supported Browsers: Chrome 85 Edge 85 Firefox 79 Safari 14 javascript-operators JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array JavaScript String includes() Method Implementation of LinkedList in Javascript DOM (Document Object Model) Installation of Node.js on Linux How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to create footer to stay at the bottom of a Web page? How to set the default value for an HTML <select> element ?
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Feb, 2021" }, { "code": null, "e": 185, "s": 28, "text": "This operator is represented by x &&= y, and it is called the logical AND assignment operator. It assigns the value of y into x only if x is a truthy value." }, { "cod...
How To Code A Fair Coin Flip In Python — Regina Of Tech | by ReginaOfTech | Towards Data Science
To master anything, you need to start at the beginning, understanding the basics. Coding a fair coin flip is kind of a right of passage when it comes to python. It seems like a simple project, but it can be done in many different ways. You may even get an insight into your coding habits. Being able to critique your code is a critical programmer skill, but that is another post. Let’s get into what you clicked for, coding a fair coin flip in python. Before we start tapping away, creating a program that makes a computer do a mundane task such as flipping a coin, let’s fly up 10,000 feet and get our bearings. Programmers have an amazing amount of creative freedom (well depending on your (micro)manager, I empathize with you if you are in that boat ❤), you can start to lose focus on what the main focus is on a project. Yes, even with a simple project like this, habits are made in and out of the public eye. Your standard is only as high as when no one is looking. Ok. Now that we have a bird’s eye view of our project lets dissect it. We know that we will be doing a fair coin flip. A coin is made up of two halves, head and tails. Since ‘fair’ is used in the project description we know that the probability will be a 50% chance of getting either side. If the description mentioned biased or weighted coin then the probability would be adjusted. How are we going to simulate a coin flip? We can’t give the computer a bitcoin and tell it to flip it. Since we are using python, a mathematically focused language, we will use probability. Specifically numpy’s binomial distribution, np.random.binomial(n,p). This is a method in the random class and it takes in the number of trials (n) and the probability of the event occurring (p). Binomial distribution, as its name suggests, can perform a ‘coin flip’ of two events happening. The call returns a 0 or 1 to represent one of the two events. Here is the equation that it uses: p is the probability, n is the number of trials ran, and N is the number of successes. We know now that for the binomial distribution to work we need two variables, n and p. This opens the question, do we want to see each flip and track it or are we satisfied with just the number of times a positive (1) event occurred? I’m on board with seeing an array of events, just for fun. So we will need an array to store the results in. Thank goodness numpy can do all of that! Let’s come back down to the ground and get coding. First things first, we need to import numpy. import numpy as np Next, we’ll create the n and p variables. We know that we will need those since we will be using np.random.binomial and that requires the number of trials and the probability. '''Main Area'''#probability of heads vs. tails. This can be changed.probability = .5#num of flips required. This can be changed.n = 10 In my code, I like to mark where the main area is for easy searching just in case there are several methods created in that program. Marking any variables that can be safely changed without any negative effects is a great practice to get into as well. We also know that we will need to initiate an array to store the flips. Using np.arange will create an array with 10 elements filled with 0 to 9 value in ascending order. #initiate arrayfullResults = np.arange(n) This is the point where we can go down two paths. One that requires us to create a function that does the ‘flip’ or does the ‘flip’ in the for loop. Since we are about code re-usability we will create a function that houses the binomial distribution. This will allow for easy access if we decide to build upon the program in the future. With that decision, let’s create the method. We will call it coinFlip and it will need to take in the probability for the events. It will return the result from the binomial. Be sure to place this before the main area. The program needs to define it before it can be used. def coinFlip(p): #perform the binomial distribution (returns 0 or 1) result = np.random.binomial(1,p) #return flip to be added to numpy array return result As you can see, the number of trials will be set to 1. This will return only a 0 or 1, false or true. Now the for loop can be created that will call coinFlip. #perform desired numbered of flips at required probability set abovefor i in range(0, n): fullResults[i] = coinFlip(probability) i+=1 For loops are basic code structures, but just in case lets walk through what is happening. The i in the header will be the index that controls whether or not the loop is done again. range(0,n) are the values that i can be. We use n so that we do not exceed our array size. When the program can step into the loop the coinFlip that we created is called and the result is saved to the element in our array. The index, i, is then incremented. We are almost done. The final step will be to count and print the results. This part is pretty easy. For the print part, we will print the probability that was used for verification that the proper one was used, along with the fullResult array. Numpy has many different functions that are targeted towards arrays. We will be using np.count_nonzero() which will iterate through the array and count the number of occurrences of the number that we give it. In this case, we will be checking for the number of times 1 and 0 occur. #print resultsprint("probability is set to ", probability)print("Tails = 0, Heads = 1: ", fullResults)#Total up heads and tails for easy user experience print("Head Count: ", np.count_nonzero(fullResults == 1))print("Tail Count: ", np.count_nonzero(fullResults == 0)) That’s it! We have created a program that will simulate a fair coin flip. Here is what the code should look like: import numpy as npdef coinFlip(p): #perform the binomial distribution (returns 0 or 1) result = np.random.binomial(1,p)#return flip to be added to numpy array return result'''Main Area'''#probability of heads vs. tails. This can be changed.probability = .5#num of flips required. This can be changed.n = 10#initiate arrayfullResults = np.arange(n)#perform desired numbered of flips at required probability set abovefor i in range(0, n): fullResults[i] = coinFlip(probability) i+=1#print resultsprint("probability is set to ", probability)print("Tails = 0, Heads = 1: ", fullResults)#Total up heads and tails for easy user experience print("Head Count: ", np.count_nonzero(fullResults == 1))print("Tail Count: ", np.count_nonzero(fullResults == 0)) That was fun! Doing simple projects like a fair coin flip is a great way to understand a library such as numpy. Numpy is a powerful library and can do plenty more than just simulating a coin flip and creating an array. If you are interested in learning more, check out Learn The Basics Of Pythons Numpy. The article will give a broader understanding of numpy. Thank you for reading! Until we learn again, Originally published on https://reginaoftech.com
[ { "code": null, "e": 624, "s": 172, "text": "To master anything, you need to start at the beginning, understanding the basics. Coding a fair coin flip is kind of a right of passage when it comes to python. It seems like a simple project, but it can be done in many different ways. You may even get an...
Java Constructors
A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes: Create a constructor: // Create a Main class public class Main { int x; // Create a class attribute // Create a class constructor for the Main class public Main() { x = 5; // Set the initial value for the class attribute x } public static void main(String[] args) { Main myObj = new Main(); // Create an object of class Main (This will call the constructor) System.out.println(myObj.x); // Print the value of x } } // Outputs 5 Try it Yourself » Note that the constructor name must match the class name, and it cannot have a return type (like void). Also note that the constructor is called when the object is created. All classes have constructors by default: if you do not create a class constructor yourself, Java creates one for you. However, then you are not able to set initial values for object attributes. Constructors can also take parameters, which is used to initialize attributes. The following example adds an int y parameter to the constructor. Inside the constructor we set x to y (x=y). When we call the constructor, we pass a parameter to the constructor (5), which will set the value of x to 5: public class Main { int x; public Main(int y) { x = y; } public static void main(String[] args) { Main myObj = new Main(5); System.out.println(myObj.x); } } // Outputs 5 Try it Yourself » You can have as many parameters as you want: public class Main { int modelYear; String modelName; public Main(int year, String name) { modelYear = year; modelName = name; } public static void main(String[] args) { Main myCar = new Main(1969, "Mustang"); System.out.println(myCar.modelYear + " " + myCar.modelName); } } // Outputs 1969 Mustang Try it Yourself » We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 204, "s": 0, "text": "A constructor in Java is a special method that is used to initialize objects. \nThe constructor is called when an object of a class is created. It can be used to \nset initial values for object attributes:" }, { "code": null, "e": 226, "s": ...
Brand Identity & Positioning
In today’s market, the customer has a very wide choice of products. When it comes to brands, he chooses brands but he tends to compare the products of different brands. Products increase customer’s choice whereas brands simplify decision making. To influence the customer’s buying decision and to get hold of the competitor’s market share, brand identity and positioning are essential. Brand management works with these two fundamental tools, brand identity and brand positioning. Let us understand these terms − It specifies that a brand has a goal that is different from the goals of other parallel brands in the same market segment and it has resistance to change. It is defined clearly and does not change over time. Brand identity is fixed in nature being tied to the fixed parameters such as brand’s vision, objective, field of competence, and overall brand charter. Brand positioning is emphasizing on the distinguishing characteristics of the brand, those that make the brand appealing to the consumers and stand out among its competitors. It specifies how the products of a brand penetrate the market to grow their market share while dealing with the competitor brands. Brand positioning is competition oriented and hence dynamic over a period of time. Brand identity can be represented by six faces of a hexagon or a prism as shown below − Brand Physique − It is the tangible and physical added value, as well as the backbone of a brand. It considers physical aspect of brand: How does it look, what does it do, the flagship product of the brand, which represents its qualities. For example, the dark color of Coke and colorless Sprite. Brand Physique − It is the tangible and physical added value, as well as the backbone of a brand. It considers physical aspect of brand: How does it look, what does it do, the flagship product of the brand, which represents its qualities. For example, the dark color of Coke and colorless Sprite. Brand Personality − If a brand were a person, what kind of person it would be? Would it be sincere (TATA Salt), exciting (Perk), rugged (Woodland), sophisticated (Mercedes), elite (Versace)? The brand has personality which speaks for its products and services. When a famous character, spokesperson, or a figurehead is used for branding, it gives the brand an instant personality. Brand Personality − If a brand were a person, what kind of person it would be? Would it be sincere (TATA Salt), exciting (Perk), rugged (Woodland), sophisticated (Mercedes), elite (Versace)? The brand has personality which speaks for its products and services. When a famous character, spokesperson, or a figurehead is used for branding, it gives the brand an instant personality. Culture − It is the set of values that governs and inspires the brand. Countries of origin, presence of brand over geographically diverse regions, changing society, etc., play an important role in building a brand’s culture. Culture − It is the set of values that governs and inspires the brand. Countries of origin, presence of brand over geographically diverse regions, changing society, etc., play an important role in building a brand’s culture. Customer Self-Image − It is what the brand is able to create in the customer’s mind and how the customers perceive about themselves after purchasing the product of a brand. Customer Self-Image − It is what the brand is able to create in the customer’s mind and how the customers perceive about themselves after purchasing the product of a brand. Customer Reflection − It is the perception of a customer about the brand after using the brand. For example, “The Thunderbird I purchased is value for price. It is giving me pleasure of leisure riding. Thanks to Royale Enfield.” Customer Reflection − It is the perception of a customer about the brand after using the brand. For example, “The Thunderbird I purchased is value for price. It is giving me pleasure of leisure riding. Thanks to Royale Enfield.” Relationship − Brands communicate, interact, transact with the consumer. It is the mode of conduct that defines the brand. This factor is vital for service brands. For example, banking where the cordial relationship develops faith in the customers when it comes to handling their money with respect. Relationship − Brands communicate, interact, transact with the consumer. It is the mode of conduct that defines the brand. This factor is vital for service brands. For example, banking where the cordial relationship develops faith in the customers when it comes to handling their money with respect. Let us consider the example of brand identity prism for Garnier’s BB cream − Keller defines brand image as awareness of brand name (whether and when customers know the brand and can recall it) and belief about brand image (customer’s associations with the brand). If either of both is created successfully while leaving the other one in poor state, it brings down the brand drastically. For example, Salman Khan is a brand in himself with very high awareness. But his image went bad due to the hit-and-run case and that spoiled his reputation. Creation of Brand knowledge is a collective effort of consumer, marketer, researchers, distributors, and ad agencies. Creating brand knowledge is extremely important for the company’s stakeholders. There can be a single brand portfolio or multiple brand portfolios. The companies decide courageously to create a new brand for its growth when the existing brand does not perform satisfactorily. There is a wide variety of consumers in terms of their behavior, economic status, tastes, genders, age groups, and preferences. If the market segmentation is too diverse, it becomes hard for a single brand to meet the demand of maximum consumers. Thus, the main objective of creating a multi-brand portfolio is to meet the demands of the segmented market in a better way. To avoid the conflicts with the existing brand and the market segment, the companies are inclined towards creating a new brand each time it ventures into a new market segment. A multi-brand portfolio covers large market segment and can stop entry of any new competitor in the market. Place and operate the brands within a portfolio with strong coordination. Place and operate the brands within a portfolio with strong coordination. Set clear and precise charter and identity for each brand. Set clear and precise charter and identity for each brand. Build strong brand architecture. Position the brands to increase their appropriateness and target market. Build strong brand architecture. Position the brands to increase their appropriateness and target market. Focus on a particular competitor for each brand. Focus on a particular competitor for each brand. Keep corporate organization and brand portfolio matched. Keep corporate organization and brand portfolio matched. Brand stays in the minds of consumers and helps the company to grow their market share and revenue. Here are few basic steps to build a strong brand − Study the market, need of the hour, competitors, and target audience. Study the purpose of what you wish to accomplish through the brand. Study the market, need of the hour, competitors, and target audience. Study the purpose of what you wish to accomplish through the brand. Decide brand personality, culture, and profile. Think of distinctive features to stand out from the competitors. Decide brand personality, culture, and profile. Think of distinctive features to stand out from the competitors. Identify how the stakeholders perceive the brand. Bridge the perception gaps. Identify how the stakeholders perceive the brand. Bridge the perception gaps. Decide where you want the brand to position in the market. Decide where you want the brand to position in the market. Create a plan and work on strategies where you want to place the brand. Create a plan and work on strategies where you want to place the brand. Communicate the brand to consumers via TV ads, social media, online marketing, etc. Communicate the brand to consumers via TV ads, social media, online marketing, etc. Make sure the consumers remember the brand. Make sure the consumers remember the brand. Evaluate if the consumers are influenced in a right way and if you have accomplished the purpose. Evaluate if the consumers are influenced in a right way and if you have accomplished the purpose. To identify brand positioning, the brand manager needs to study the market segment of venture. To establish a strong brand positioning, you need to get clear answers to the following questions − Brand for what benefit? For example, The Body Shop uses natural ingredients in its products and is environment-friendly. Tropicana packs real fruit juices in tetra packs, etc. Brand for what benefit? For example, The Body Shop uses natural ingredients in its products and is environment-friendly. Tropicana packs real fruit juices in tetra packs, etc. Brand for whom? It is the target audience of the brand grouped as gender, age, economic bracket, etc. For example, while Nike is top clothing brand for all income group, Gucci and Fossil remain high income handbags brands. Brand for whom? It is the target audience of the brand grouped as gender, age, economic bracket, etc. For example, while Nike is top clothing brand for all income group, Gucci and Fossil remain high income handbags brands. Brand for what reason? These are the facts that support claimed benefits. Brand for what reason? These are the facts that support claimed benefits. Brand against whom? This defines the way to attack competitors’ market share. Brand against whom? This defines the way to attack competitors’ market share. There is a standard formula to achieve brand positioning − For ... (target market of potential buyers or consumers) Brand X is ... (definition of frame of reference and category) Which gives the most ... (promise or consumer benefit) Because of ... (reason to believe) Where, The target market is the psychological and social profile of the consumers a brand aims to influence. The target market is the psychological and social profile of the consumers a brand aims to influence. Frame of reference is the nature of competition. Frame of reference is the nature of competition. Promise or consumer benefit is the feature that creates preference and drives decision after making choice. For example, Cadbury promises its Silk chocolate bars to be the smoothest ones among other Cadbury chocolate bars. Promise or consumer benefit is the feature that creates preference and drives decision after making choice. For example, Cadbury promises its Silk chocolate bars to be the smoothest ones among other Cadbury chocolate bars. The reason to believe is reinforcement of promise or consumer benefit. For example, Tropicana Products, the producer and marketer (a division of PepsiCo), promises to be delivering 100% pure fruit juices in its Pure Premium juices range. The reason to believe is reinforcement of promise or consumer benefit. For example, Tropicana Products, the producer and marketer (a division of PepsiCo), promises to be delivering 100% pure fruit juices in its Pure Premium juices range. Let us take an example of brand positioning conducted by Shoppers Stop, the retail chain in India that sells retail clothing, handbags, jewelry, perfumes, toys, home furnishing, and accessories. It has business of 20 billion dollars. It was founded in 1991 with first store at Mumbai and expanded rapidly across the country soon. The consumers perceived it as mass market brand and it started losing its shine in the retail competition in 2008. The brand managers and company management together carried out a store audit at all outlets, studied customer experiences, updated brand identity, and came up with new tagline, “Start something new”. It then repositioned the brand as premium, accessibleluxury sector. This position of bridge-to-luxury appealed young, middle-class consumers in India, who had their own money to spend at a young age. The new repositioning also added the credibility of Shoppers Stop to preset itself as a potential partner for international brands who were looking to enter the Indian market. The impact was, its share price grew 450% from 52-week low, sales rose more than 10%, and as newly acquired strength of positioning the brand, it started co-branding with international brands such as Chanel, Dior, Armani, Esprit, Tommy Hilfiger, Mothercare, Mustang, Austin Reed, and so on. Consumers are interested in brand values. When the consumer understands the brand value, he can interact with the business in a particular way. For defining and establishing brand values, you need to take an honest look at the product or service. You can proceed by using the following steps − Step 1 − Find out the answers for the following questions − What unique and competing feature my product/service has? Why should the target audience take interest in my product/service? What is my passion being a product manufacturer/service provider? Step 2 − Compile a list of values related to the product/service, such as − Simplicity Quality Affordability Timeliness Politeness Integrity Creativity Innovation Commitment Step 3 − Narrow down the list of values. Bring down the list of values which are absolutely indisputable for execution of your business. Recommended number of values is three to four. For example, if your brand’s value is timeliness then make sure you keep the promise of shipping and delivery of products always on time, handle and reply to your customer inquiries in timely manner, attend the customer’s call in the shortest possible time etc. Make sure that the value is always consistently honored, despite any internal or external situation. Step 4 − Use the list as a reference. Use the list of brand values while creating new products or services, dealing with clients, consumers, and partners. Venturing into global markets is inevitable for brands. A brand is global when it is visible and sold at every possible place in the world. The consumer around the world become aware of various international brands if they travel worldwide or just watch a satellite television at home. Before you take the brand in the global market, you need to cater to various aspects of the global consumer such as − Culture of Consumers − The values the consumers follow The customs they observe Particular symbols and language they use The tone of their behavior Consumer’s level of income and buying power Economic status of the country in terms of − Power supply Infrastructure Communication systems Distribution systems Laws and Regulations enforced − Is it lawful there too? Political stability of the country When the brand transits from local to global, it competes with other global brands. For example, Nokia battles Motorola and Samsung. The brand managers must manage the transnational brand to remain superior on the essentials such as the brand’s price, performance, features, and imagery. 9 Lectures 47 mins Aleksandar Cucukovic 18 Lectures 2 hours Rob Cubbon 10 Lectures 1 hours Bernard Kelvin Clive 24 Lectures 1 hours J Aatish Rao 31 Lectures 2.5 hours Being Commerce 31 Lectures 2.5 hours Being Commerce Print Add Notes Bookmark this page
[ { "code": null, "e": 2436, "s": 2050, "text": "In today’s market, the customer has a very wide choice of products. When it comes to brands, he chooses brands but he tends to compare the products of different brands. Products increase customer’s choice whereas brands simplify decision making. To infl...
Previous greater element - GeeksforGeeks
13 May, 2021 Given an array of distinct elements, find previous greater element for every element. If previous greater element does not exist, print -1.Examples: Input : arr[] = {10, 4, 2, 20, 40, 12, 30} Output : -1, 10, 4, -1, -1, 40, 40 Input : arr[] = {10, 20, 30, 40} Output : -1, -1, -1, -1 Input : arr[] = {40, 30, 20, 10} Output : -1, 40, 30, 20 Expected time complexity : O(n) A simple solution is to run two nested loops. The outer loop picks an element one by one. The inner loop, find the previous element that is greater. C++ Java Python 3 C# PHP Javascript // C++ program previous greater element// A naive solution to print previous greater// element for every element in an array.#include <bits/stdc++.h>using namespace std; void prevGreater(int arr[], int n){ // Previous greater for first element never // exists, so we print -1. cout << "-1, "; // Let us process remaining elements. for (int i = 1; i < n; i++) { // Find first element on left side // that is greater than arr[i]. int j; for (j = i-1; j >= 0; j--) { if (arr[i] < arr[j]) { cout << arr[j] << ", "; break; } } // If all elements on left are smaller. if (j == -1) cout << "-1, "; }}// Driver codeint main(){ int arr[] = { 10, 4, 2, 20, 40, 12, 30 }; int n = sizeof(arr) / sizeof(arr[0]); prevGreater(arr, n); return 0;} // Java program previous greater element// A naive solution to print// previous greater element// for every element in an array.import java.io.*;import java.util.*;import java.lang.*; class GFG{static void prevGreater(int arr[], int n){ // Previous greater for // first element never // exists, so we print -1. System.out.print("-1, "); // Let us process // remaining elements. for (int i = 1; i < n; i++) { // Find first element on // left side that is // greater than arr[i]. int j; for (j = i-1; j >= 0; j--) { if (arr[i] < arr[j]) { System.out.print(arr[j] + ", "); break; } } // If all elements on // left are smaller. if (j == -1) System.out.print("-1, "); }} // Driver Codepublic static void main(String[] args){ int arr[] = {10, 4, 2, 20, 40, 12, 30}; int n = arr.length; prevGreater(arr, n);}} # Python 3 program previous greater element# A naive solution to print previous greater# element for every element in an array.def prevGreater(arr, n) : # Previous greater for first element never # exists, so we print -1. print("-1",end = ", ") # Let us process remaining elements. for i in range(1, n) : flag = 0 # Find first element on left side # that is greater than arr[i]. for j in range(i-1, -1, -1) : if arr[i] < arr[j] : print(arr[j],end = ", ") flag = 1 break # If all elements on left are smaller. if j == 0 and flag == 0: print("-1",end = ", ") # Driver codeif __name__ == "__main__" : arr = [10, 4, 2, 20, 40, 12, 30] n = len(arr) prevGreater(arr, n) # This code is contributed by ANKITRAI1 // C# program previous greater element// A naive solution to print// previous greater element// for every element in an array. using System;class GFG{static void prevGreater(int[] arr, int n){ // Previous greater for // first element never // exists, so we print -1. Console.Write("-1, "); // Let us process // remaining elements. for (int i = 1; i < n; i++) { // Find first element on // left side that is // greater than arr[i]. int j; for (j = i-1; j >= 0; j--) { if (arr[i] < arr[j]) { Console.Write(arr[j] + ", "); break; } } // If all elements on // left are smaller. if (j == -1) Console.Write("-1, "); }} // Driver Codepublic static void Main(){ int[] arr = {10, 4, 2, 20, 40, 12, 30}; int n = arr.Length; prevGreater(arr, n);}} <?php// php program previous greater element// A naive solution to print previous greater// element for every element in an array. function prevGreater(&$arr,$n){ // Previous greater for first element never // exists, so we print -1. echo( "-1, "); // Let us process remaining elements. for ($i = 1; $i < $n; $i++) { // Find first element on left side // that is greater than arr[i]. for ($j = $i-1; $j >= 0; $j--) { if ($arr[$i] < $arr[$j]) { echo($arr[$j]); echo( ", "); break; } } // If all elements on left are smaller. if ($j == -1) echo("-1, "); }} // Driver code$arr = array(10, 4, 2, 20, 40, 12, 30);$n = sizeof($arr) ;prevGreater($arr, $n); //This code is contributed by Shivi_Aggarwal. ?> <script>// Javascript program previous greater element// A naive solution to print// previous greater element// for every element in an array. function prevGreater(arr,n) { // Previous greater for // first element never // exists, so we print -1. document.write("-1, "); // Let us process // remaining elements. for (let i = 1; i < n; i++) { // Find first element on // left side that is // greater than arr[i]. let j; for (j = i-1; j >= 0; j--) { if (arr[i] < arr[j]) { document.write(arr[j] + ", "); break; } } // If all elements on // left are smaller. if (j == -1) document.write("-1, "); } } // Driver Code let arr=[10, 4, 2, 20, 40, 12, 30]; let n = arr.length; prevGreater(arr, n); // This code is contributed by avanitrachhadiya2155</script> -1, 10, 4, -1, -1, 40, 40 An efficient solution is to use stack data structure. If we take a closer look, we can notice that this problem is a variation of stock span problem. We maintain previous greater element in a stack. C++ Java Python3 C# Javascript // C++ program previous greater element// An efficient solution to print previous greater// element for every element in an array.#include <bits/stdc++.h>using namespace std; void prevGreater(int arr[], int n){ // Create a stack and push index of first element // to it stack<int> s; s.push(arr[0]); // Previous greater for first element is always -1. cout << "-1, "; // Traverse remaining elements for (int i = 1; i < n; i++) { // Pop elements from stack while stack is not empty // and top of stack is smaller than arr[i]. We // always have elements in decreasing order in a // stack. while (s.empty() == false && s.top() < arr[i]) s.pop(); // If stack becomes empty, then no element is greater // on left side. Else top of stack is previous // greater. s.empty() ? cout << "-1, " : cout << s.top() << ", "; s.push(arr[i]); }}// Driver codeint main(){ int arr[] = { 10, 4, 2, 20, 40, 12, 30 }; int n = sizeof(arr) / sizeof(arr[0]); prevGreater(arr, n); return 0;} // Java program previous greater element// An efficient solution to// print previous greater// element for every element// in an array.import java.io.*;import java.util.*;import java.lang.*; class GFG{static void prevGreater(int arr[], int n){ // Create a stack and push // index of first element // to it Stack<Integer> s = new Stack<Integer>(); s.push(arr[0]); // Previous greater for // first element is always -1. System.out.print("-1, "); // Traverse remaining elements for (int i = 1; i < n; i++) { // Pop elements from stack // while stack is not empty // and top of stack is smaller // than arr[i]. We always have // elements in decreasing order // in a stack. while (s.empty() == false && s.peek() < arr[i]) s.pop(); // If stack becomes empty, then // no element is greater on left // side. Else top of stack is // previous greater. if (s.empty() == true) System.out.print("-1, "); else System.out.print(s.peek() + ", "); s.push(arr[i]); }} // Driver Codepublic static void main(String[] args){ int arr[] = { 10, 4, 2, 20, 40, 12, 30 }; int n = arr.length; prevGreater(arr, n);}} # Python3 program to print previous greater element# An efficient solution to print previous greater# element for every element in an array.import math as mt def prevGreater(arr, n): # Create a stack and push index of # first element to it s = list(); s.append(arr[0]) # Previous greater for first element # is always -1. print("-1, ", end = "") # Traverse remaining elements for i in range(1, n): # Pop elements from stack while stack is # not empty and top of stack is smaller # than arr[i]. We always have elements in # decreasing order in a stack. while (len(s) > 0 and s[-1] < arr[i]): s.pop() # If stack becomes empty, then no element # is greater on left side. Else top of stack # is previous greater. if len(s) == 0: print("-1, ", end = "") else: print(s[-1], ", ", end = "") s.append(arr[i]) # Driver codearr = [ 10, 4, 2, 20, 40, 12, 30 ]n = len(arr)prevGreater(arr, n) # This code is contributed by# mohit kumar 29 // C# program previous greater element// An efficient solution to// print previous greater// element for every element// in an array.using System;using System.Collections.Generic; class GFG{static void prevGreater(int []arr, int n){ // Create a stack and push // index of first element // to it Stack<int> s = new Stack<int>(); s.Push(arr[0]); // Previous greater for // first element is always -1. Console.Write("-1, "); // Traverse remaining elements for (int i = 1; i < n; i++) { // Pop elements from stack // while stack is not empty // and top of stack is smaller // than arr[i]. We always have // elements in decreasing order // in a stack. while (s.Count != 0 && s.Peek() < arr[i]) s.Pop(); // If stack becomes empty, then // no element is greater on left // side. Else top of stack is // previous greater. if (s.Count == 0) Console.Write("-1, "); else Console.Write(s.Peek() + ", "); s.Push(arr[i]); }} // Driver Codepublic static void Main(String[] args){ int []arr = { 10, 4, 2, 20, 40, 12, 30 }; int n = arr.Length; prevGreater(arr, n);}} // This code is contributed by PrinciRaj1992 <script>// Javascript program previous greater element// An efficient solution to// print previous greater// element for every element// in an array. function prevGreater(arr,n) { // Create a stack and push // index of first element // to it let s = []; s.push(arr[0]); // Previous greater for // first element is always -1. document.write("-1, "); // Traverse remaining elements for (let i = 1; i < n; i++) { // Pop elements from stack // while stack is not empty // and top of stack is smaller // than arr[i]. We always have // elements in decreasing order // in a stack. while (s.length!=0 && s[s.length-1] < arr[i]) s.pop(); // If stack becomes empty, then // no element is greater on left // side. Else top of stack is // previous greater. if (s.length==0) document.write("-1, "); else document.write(s[s.length-1] + ", "); s.push(arr[i]); } } // Driver Code let arr=[10, 4, 2, 20, 40, 12, 30]; let n = arr.length; prevGreater(arr, n); // This code is contributed by rag2127</script> -1, 10, 4, -1, -1, 40, 40 Time Complexity: O(n). It seems more than O(n) at first look. If we take a closer look, we can observe that every element of array is added and removed from stack at most once. So there are total 2n operations at most. Assuming that a stack operation takes O(1) time, we can say that the time complexity is O(n).Auxiliary Space: O(n) in worst case when all elements are sorted in decreasing order. Shivi_Aggarwal ankthon ukasp mohit kumar 29 princiraj1992 avanitrachhadiya2155 rag2127 Arrays Searching Stack Arrays Searching Stack Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Trapping Rain Water Program to find sum of elements in a given array Reversal algorithm for array rotation Window Sliding Technique Find duplicates in O(n) time and O(1) extra space | Set 1 Binary Search Median of two sorted arrays of different sizes Most frequent element in an array Find the index of an array element in Java Count number of occurrences (or frequency) in a sorted array
[ { "code": null, "e": 24742, "s": 24714, "text": "\n13 May, 2021" }, { "code": null, "e": 24893, "s": 24742, "text": "Given an array of distinct elements, find previous greater element for every element. If previous greater element does not exist, print -1.Examples: " }, { ...
How to find left position of element in horizontal scroll container using jQuery?
To find the left position of element in horizontal scroll container using jQuery, use the animate() function with the scrollLeft() function. You can try to run the following code to learn how to find left position of an element in horizontal scroll container: Live Demo <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function() { var scrollArea = $('#box'); var toScroll = $('#box .myclass'); function myScroll() { toScroll.each(function() { var self = $(this); $(this).css('cursor', 'pointer'); $(this).on('click', function () { var leftOffset = self.offset().left - scrollArea.offset().left + scrollArea.scrollLeft(); scrollArea.animate({ scrollLeft: leftOffset }); alert(leftOffset); }); }); }; myScroll(); }); </script> <style> #box { width: 250px; height: 300px; margin-left: 20px; border: 1px solid black; overflow-x: scroll; white-space: nowrap; } .myclass { width: 250px; height: 100px; margin: 35px; display: inline-block; background: -webkit-linear-gradient(left, red , blue); background: -o-linear-gradient(right, red, blue); background: -moz-linear-gradient(right, red, blue); background: linear-gradient(to right, red , blue); } </style> </head> <body> <p>Get left position of element.</p> <div id="box"> <div class="myclass">First (Click Me)</div> <div class="myclass">Second (Click Me)</div> <div class="myclass">Third (Click Me)</div> </div> </body> </html>
[ { "code": null, "e": 1203, "s": 1062, "text": "To find the left position of element in horizontal scroll container using jQuery, use the animate() function with the scrollLeft() function." }, { "code": null, "e": 1322, "s": 1203, "text": "You can try to run the following code to ...
Topological Sorting
The topological sorting for a directed acyclic graph is the linear ordering of vertices. For every edge U-V of a directed graph, the vertex u will come before vertex v in the ordering. As we know that the source vertex will come after the destination vertex, so we need to use a stack to store previous elements. After completing all nodes, we can simply display them from the stack. Input: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 1 0 0 0 0 1 0 1 0 0 0 Output: Nodes after topological sorted order: 5 4 2 3 1 0 topoSort(u, visited, stack) Input − The start vertex u, An array to keep track of which node is visited or not. A stack to store nodes.Output − Sorting the vertices in topological sequence in the stack. Begin mark u as visited for all vertices v which is adjacent with u, do if v is not visited, then topoSort(c, visited, stack) done push u into a stack End performTopologicalSorting(Graph) Input − The given directed acyclic graph.Output − Sequence of nodes. Begin initially mark all nodes as unvisited for all nodes v of the graph, do if v is not visited, then topoSort(i, visited, stack) done pop and print all elements from the stack End. #include<iostream> #include<stack> #define NODE 6 using namespace std; int graph[NODE][NODE] = { {0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0}, {0, 0, 0, 1, 0, 0}, {0, 1, 0, 0, 0, 0}, {1, 1, 0, 0, 0, 0}, {1, 0, 1, 0, 0, 0} }; void topoSort(int u, bool visited[], stack<int>&stk) { visited[u] = true; //set as the node v is visited for(int v = 0; v<NODE; v++) { if(graph[u][v]) { //for allvertices v adjacent to u if(!visited[v]) topoSort(v, visited, stk); } } stk.push(u); //push starting vertex into the stack } void performTopologicalSort() { stack<int> stk; bool vis[NODE]; for(int i = 0; i<NODE; i++) vis[i] = false; //initially all nodes are unvisited for(int i = 0; i<NODE; i++) if(!vis[i]) //when node is not visited topoSort(i, vis, stk); while(!stk.empty()) { cout << stk.top() << " "; stk.pop(); } } main() { cout << "Nodes after topological sorted order: "; performTopologicalSort(); } Nodes after topological sorted order: 5 4 2 3 1 0
[ { "code": null, "e": 1247, "s": 1062, "text": "The topological sorting for a directed acyclic graph is the linear ordering of vertices. For every edge U-V of a directed graph, the vertex u will come before vertex v in the ordering." }, { "code": null, "e": 1446, "s": 1247, "text"...
3Sum Closest in C++
Suppose we have an array nums with n integers and one target. We have to find three integers in nums such that the sum is closest to the target. We will return the sum of the three integers. We can take one assumption that each input would have exactly one solution. So if the given array is like [-1,2,1,-4] and the target is 1, then the triplet will be [-1,2,1] this has the closest sum, that is 2. To solve this, we will follow these steps − Sort the array nums, ans := 0, diff := Infinity, n := size of nums for i in range 0 to n – 1left := i + 1, right := n – 1while left < righttemp := nums[left] + nums[right] + nums[i]if |target – temp| < diff, then ans := temp and diff := |target – temp|if temp = target, then return temp, otherwise when temp > target, then decrease right by 1, else increase left by 1 left := i + 1, right := n – 1 while left < righttemp := nums[left] + nums[right] + nums[i]if |target – temp| < diff, then ans := temp and diff := |target – temp|if temp = target, then return temp, otherwise when temp > target, then decrease right by 1, else increase left by 1 temp := nums[left] + nums[right] + nums[i] if |target – temp| < diff, then ans := temp and diff := |target – temp| if temp = target, then return temp, otherwise when temp > target, then decrease right by 1, else increase left by 1 return ans Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class Solution { public: int threeSumClosest(vector<int>& nums, int target) { sort(nums.begin(), nums.end()); int ans = 0; int diff = INT_MAX; int n = nums.size(); for(int i = 0; i < n; i++){ int left = i + 1; int right = n - 1; while(left < right){ int temp = nums[left] + nums[right] + nums[i]; if(abs(target - temp) < diff){ ans = temp; diff = abs(target - temp); } if(temp == target)return temp; else if(temp > target) right--; else left++; } } return ans; } }; main(){ Solution ob; vector<int> v = {-1,2,1,-4}; cout << ob.threeSumClosest(v, 1); } [-1,2,1,-4] 1 2
[ { "code": null, "e": 1463, "s": 1062, "text": "Suppose we have an array nums with n integers and one target. We have to find three integers in nums such that the sum is closest to the target. We will return the sum of the three integers. We can take one assumption that each input would have exactly ...
Find the sum of the all amicable numbers up to N - GeeksforGeeks
02 Jun, 2021 Given a number N. FInd the sum of he all amicable numbers up to N. If A and B are Amicable pairs (Two numbers are amicable if the first is equal to the sum of divisors of the second) then A and B are called as Amicable numbers. Examples: Input : 284 Output : 504 Explanation : 220 and 284 are two amicable numbers upto 284Input : 250 Output : 220 Explanation : 220 is the only amicable number Approach : An efficient approach is to store all amicable numbers in a set and for a given N sum all the numbers in the set which are less than equals to N.Below code is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // CPP program to find sum of all// amicable numbers up to n#include <bits/stdc++.h>using namespace std; #define N 100005 // Function to return all amicable numbersset<int> AMICABLE(){ int sum[N]; memset(sum, 0, sizeof sum); for (int i = 1; i < N; i++) { // include 1 sum[i]++; for (int j = 2; j * j <= i; j++) { // j is proper divisor of i if (i % j == 0) { sum[i] += j; // if i is not a perfect square if (i / j != j) sum[i] += i / j; } } } set<int> s; for (int i = 2; i < N; i++) { // insert amicable numbers if (i != sum[i] and sum[i] < N and i == sum[sum[i]] and !s.count(i) and !s.count(sum[i])) { s.insert(i); s.insert(sum[i]); } } return s;} // function to find sum of all// amicable numbers up to Nint SumOfAmicable(int n){ // to store required sum int sum = 0; // to store all amicable numbers set<int> s = AMICABLE(); // sum all amicable numbers upto N for (auto i = s.begin(); i != s.end(); ++i) { if (*i <= n) sum += *i; else break; } // required answer return sum;} // Driver code to test above functionsint main(){ int n = 284; cout << SumOfAmicable(n); return 0;} // Java program to find sum of all// amicable numbers up to nimport java.util.*;class GFG{ static final int N=100005; // Function to return all amicable numbersstatic Set<Integer> AMICABLE(){ int sum[] = new int[N]; for(int i = 0; i < N; i++) sum[i]=0; for (int i = 1; i < N; i++) { // include 1 sum[i]++; for (int j = 2; j * j <= i; j++) { // j is proper divisor of i if (i % j == 0) { sum[i] += j; // if i is not a perfect square if (i / j != j) sum[i] += i / j; } } } Set<Integer> s = new HashSet<Integer>(); for (int i = 2; i < N; i++) { // insert amicable numbers if (i != sum[i] && sum[i] < N && i == sum[sum[i]]) { s.add(i); s.add(sum[i]); } } return s;} // function to find sum of all// amicable numbers up to Nstatic int SumOfAmicable(int n){ // to store required sum int sum = 0; // to store all amicable numbers Set<Integer> s = AMICABLE(); // sum all amicable numbers upto N for (Integer x : s) { if (x <= n) sum += x; } // required answer return sum;} // Driver codepublic static void main(String args[]){ int n = 284; System.out.println( SumOfAmicable(n));}} // This code is contributed by Arnab Kundu # Python3 program to findSum of all# amicable numbers up to nimport math as mt N = 100005 # Function to return all amicable numbersdef AMICABLE(): Sum = [0 for i in range(N)] for i in range(1, N): Sum[i] += 1 for j in range(2, mt.ceil(mt.sqrt(i))): # j is proper divisor of i if (i % j == 0): Sum[i] += j # if i is not a perfect square if (i // j != j): Sum[i] += i // j s = set() for i in range(2, N): if(i != Sum[i] and Sum[i] < N and i == Sum[Sum[i]] and i not in s and Sum[i] not in s): s.add(i) s.add(Sum[i]) return s # function to findSum of all amicable# numbers up to Ndef SumOfAmicable(n): # to store requiredSum Sum = 0 # to store all amicable numbers s = AMICABLE() #Sum all amicable numbers upto N s = sorted(s) for i in s: if (i <= n): Sum += i else: break # required answer return Sum # Driver Coden = 284print(SumOfAmicable(n)) # This code is contributed by# mohit kumar 29 // C# program to find sum of all// amicable numbers up to nusing System;using System.Collections.Generic; class GFG{ static readonly int N = 100005; // Function to return all amicable numbersstatic HashSet<int> AMICABLE(){ int []sum = new int[N]; for(int i = 0; i < N; i++) sum[i] = 0; for (int i = 1; i < N; i++) { // include 1 sum[i]++; for (int j = 2; j * j <= i; j++) { // j is proper divisor of i if (i % j == 0) { sum[i] += j; // if i is not a perfect square if (i / j != j) sum[i] += i / j; } } } HashSet<int> s = new HashSet<int>(); for (int i = 2; i < N; i++) { // insert amicable numbers if (i != sum[i] && sum[i] < N && i == sum[sum[i]]) { s.Add(i); s.Add(sum[i]); } } return s;} // function to find sum of all// amicable numbers up to Nstatic int SumOfAmicable(int n){ // to store required sum int sum = 0; // to store all amicable numbers HashSet<int> s = AMICABLE(); // sum all amicable numbers upto N foreach (int x in s) { if (x <= n) sum += x; } // required answer return sum;} // Driver codepublic static void Main(){ int n = 284; Console.WriteLine( SumOfAmicable(n));}} /* This code contributed by PrinciRaj1992 */ <?php// PHP program to find sum of all// amicable numbers up to n$N = 10005; // Function to return all amicable// numbersfunction AMICABLE(){ global $N; $sum = array_fill(0, $N, 0); for ($i = 1; $i < $N; $i++) { // include 1 $sum[$i]++; for ($j = 2; $j * $j <= $i; $j++) { // j is proper divisor of i if ($i % $j == 0) { $sum[$i] += $j; // if i is not a perfect square if ($i / $j != $j) $sum[$i] += $i / $j; } } } $s = array(); for ($i = 2; $i < $N; $i++) { // insert amicable numbers if ($i != $sum[$i] and $sum[$i] < $N and $i == $sum[$sum[$i]] and !in_array($i, $s) and !in_array($sum[$i], $s)) { array_push($s, $i); array_push($s, $sum[$i]); } } return $s;} // function to find sum of all// amicable numbers up to Nfunction SumOfAmicable($n){ // to store required sum $sum = 0; // to store all amicable numbers $s = AMICABLE(); $s = array_unique($s); sort($s); // sum all amicable numbers upto N for ($i = 0; $i != count($s); ++$i) { if ($s[$i] <= $n) $sum += $s[$i]; else break; } // required answer return $sum;} // Driver code$n = 284; echo SumOfAmicable($n); // This code is contributed by mits?> <script> // JavaScript program to find sum of all// amicable numbers up to n let N=100005; // Function to return all amicable numbersfunction AMICABLE(){ let sum = new Array(N); for(let i = 0; i < N; i++) sum[i]=0; for (let i = 1; i < N; i++) { // include 1 sum[i]++; for (let j = 2; j * j <= i; j++) { // j is proper divisor of i if (i % j == 0) { sum[i] += j; // if i is not a perfect square if (i / j != j) sum[i] += i / j; } } } let s = new Set(); for (let i = 2; i < N; i++) { // insert amicable numbers if (i != sum[i] && sum[i] < N && i == sum[sum[i]]) { s.add(i); s.add(sum[i]); } } return s;} // function to find sum of all// amicable numbers up to Nfunction SumOfAmicable(n){ // to store required sum let sum = 0; // to store all amicable numbers let s = AMICABLE(); // sum all amicable numbers upto N for (let x of s.values()) { if (x <= n) sum += x; } // required answer return sum;} // Driver codelet n = 284;document.write( SumOfAmicable(n)); // This code is contributed by unknown2108 </script> 504 mohit kumar 29 andrew1234 princiraj1992 Mithun Kumar unknown2108 divisors Competitive Programming Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Pairs with same Manhattan and Euclidean distance Breadth First Traversal ( BFS ) on a 2D array Multistage Graph (Shortest Path) Shortest path in a directed graph by Dijkstra’s algorithm Most important type of Algorithms Program for Fibonacci numbers C++ Data Types Write a program to print all permutations of a given string Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 25022, "s": 24994, "text": "\n02 Jun, 2021" }, { "code": null, "e": 25262, "s": 25022, "text": "Given a number N. FInd the sum of he all amicable numbers up to N. If A and B are Amicable pairs (Two numbers are amicable if the first is equal to the sum of divi...
Download Email Attachment from Microsoft Exchange Web Services Automatically | by Joshua Yeung | Towards Data Science
Did you need to download email attachments regularly? Do you want to automate this boring process? I know that feel bro. When I first come to my job, I was assigned a daily task: download the attached report from the email sent to our team every day. It’s not a difficult task, but it’s extremely boring and I often forget to do so. How can I get rid of this dummy task: Downloading email attachments regularly. After researching the internet I discovered that a little Python script could take over my work. Let’s explore what Python can help us. Exchangelib, a Python library that provides a simple interface that allows Python scripts to interact with Microsoft Exchange or Exchange Web Services (EWS) github.com You can install this package from PyPI: pip install exchangelib And then you import package following the instruction of the official site. You may not use all of them, #import pytzfrom exchangelib import DELEGATE, IMPERSONATION, Account, Credentials, ServiceAccount, EWSDateTime, EWSTimeZone, Configuration, NTLM, GSSAPI, CalendarItem, Message, Mailbox, Attendee, Q, ExtendedProperty, FileAttachment, ItemAttachment, HTMLBody, Build, Version, FolderCollection The next step is to specify your credentials, that is the login username and the password credentials = Credentials(username='john@example.com', password='topsecret') You have to config the mail server of course. Exchangelib should be able to identify the authentication type used by your email server, but in my case, it failed and I specified the authentication type to NTLM. ews_url = 'mail.example.com'ews_auth_type = 'NTLM'primary_smtp_address = 'john@example.com'config = Configuration(service_endpoint=ews_url, credentials=credentials, auth_type=ews_auth_type)# An Account is the account on the Exchange server that you want to connect to.account = Account(primary_smtp_address=primary_smtp_address,config=config, autodiscover=False,access_type=DELEGATE) Now you have an Account object and you can navigator through it. It just follows your email account folder structure. For example, if you want to operate on the inbox folder, just use this simple syntax: account.inbox. To operate a folder inside the inbox, just put a backslash and single quote like this: account.inbox / 'some_folder'. If you just want to download all the attachments in a folder, this shortcode would help. You may require os package to process local directory. some_folder = account.inbox / 'some_folder'for item in some_folder.all(): for attachment in item.attachments: if isinstance(attachment, FileAttachment): local_path = os.path.join(local_path, attachment.name) with open(local_path, 'wb') as f: f.write(attachment.content) That’s it! If I just want to download the files that I haven’t downloaded before, what can I do further? I need a mechanism to check if the attachment exists locally. Our team uses an FTP server to store all the attached reports. Thus in my Python script, first of all, I log in to the FTP server and list all files with the specified prefix. A checking is added to the script to determine whether this file exists in the current file list or not. To do so, I used ftplib, a library of FTP protocol client. docs.python.org The following code logins to the FTP server (ftp.login()), navigate the target folder (ftp.cwd()) and list all files (ftp.nlst()) that matched the specified prefix (file.startswith()) from ftplib import FTPftp_server_ip = FTP_SERVER_IPusername = 'username'password = 'password'remote_path = 'remote_path'local_path = 'local_path'with FTP(ftp_server_ip) as ftp: ftp.login(user=username, passwd=password) ftp.cwd(remote_path + '/copied data') filelist = [file for file in ftp.nlst() if file.startswith('YOUR_FILE_PREFIX')] After downloading the attachments locally, I upload the files to the FTP server. I use storbinary to send STOR command to upload the attachments. if attachment.name not in filelist:# Check if the attachment downloaded before local_path = os.path.join(local_path, attachment.name) with open(local_path, 'wb') as f: f.write(attachment.content)with FTP(ftp_server_ip) as ftp: ftp.login(user=username, passwd=password) ftp.cwd(remote_path) file = open(local_path, 'rb') ftp.storbinary('STOR {}'.format(attachment.name), file) file.close() I automated this daily routine using a simple Python script that can be scheduled to run regularly. The script automates the workflow that downloads missing attachments from the mail server and uploads them to the FTP server.
[ { "code": null, "e": 505, "s": 172, "text": "Did you need to download email attachments regularly? Do you want to automate this boring process? I know that feel bro. When I first come to my job, I was assigned a daily task: download the attached report from the email sent to our team every day. It’s...
Fragment Tutorial with Example in Android Studio?
This example demonstrate about Fragment Tutorial with Example in Android Studio Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns: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" android:orientation = "vertical"> <Button android:id = "@+id/fragment1" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:layout_alignParentTop = "true" android:layout_centerHorizontal = "true" android:layout_marginTop = "27dp" android:text = "fragment1"/> <Button android:id = "@+id/fragment2" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:layout_alignParentTop = "true" android:layout_centerHorizontal = "true" android:layout_marginTop = "27dp" android:text = "fragment2"/> <LinearLayout android:id = "@+id/layout" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:orientation = "vertical"> </LinearLayout> </LinearLayout> In the above code, we have taken button views and linear layout to show different fragments. Step 3 − Add the following code to src /MainActivity.java package com.example.myapplication; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.view.View; public class MainActivity extends AppCompatActivity { @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final android.support.v4.app.Fragment first = new FirstFragment(); final android.support.v4.app.Fragment second = new SecondFragment(); findViewById(R.id.fragment1).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { android.support.v4.app.FragmentManager fm = getSupportFragmentManager(); android.support.v4.app.FragmentTransaction fragmentTransaction = fm.beginTransaction(); fragmentTransaction.replace(R.id.layout, first); fragmentTransaction.commit(); } }); findViewById(R.id.fragment2).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { FragmentManager fm = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fm.beginTransaction(); fragmentTransaction.replace(R.id.layout, second); fragmentTransaction.commit(); } }); } } Step 4 − Add the following code to src / FirstFragment.java package com.example.myapplication; import android.annotation.SuppressLint; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; @SuppressLint("ValidFragment") public class FirstFragment extends Fragment { TextView textView; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment, container, false); textView = view.findViewById(R.id.text); textView.setText("first"); return view; } } Step 5 − Add the following code to src / SecondFragment.java package com.example.myapplication; import android.annotation.SuppressLint; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class SecondFragment extends Fragment { TextView textView; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment, container, false); textView = view.findViewById(R.id.text); textView.setText("Second"); return view; } } Step 6 − Add the following code to res/layout/ fragment.xml. <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" android:layout_width = "match_parent" android:gravity = "center" android:layout_height = "match_parent"> <TextView android:id = "@+id/text" android:textSize = "30sp" android:layout_width = "match_parent" android:layout_height = "match_parent" /> </LinearLayout> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – Now click on buttons, it will show the result as shown below – Click here to download the project code
[ { "code": null, "e": 1142, "s": 1062, "text": "This example demonstrate about Fragment Tutorial with Example in Android Studio" }, { "code": null, "e": 1271, "s": 1142, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required detail...
How to insert a Python tuple in a MySQL database?
Assuming that MySQL database named as test is present on server and a table named employee is also created. The table has five fields fname, lname, age, gender, and salary. A tuple object containing data of a record is defined as t1=('Mac', 'Mohan', 20, 'M', 2000) To establish interface between MySQL and Python 3, you need to install PyMySQL module. Then you can set up the connection using following statements import PyMySQL # Open database connection db = PyMySQL.connect("localhost","root","","test" ) # prepare a cursor object using cursor() method cursor = db.cursor() Next step is to set up the insert query using data in the tuple sql="insert into employee values(%s,%s,%d,%s,%d)" %t1 Now this query is executed using execute() method of cursor object cursor.execute(sql) If you check contents of employee table, it will show new record added in it.
[ { "code": null, "e": 1235, "s": 1062, "text": "Assuming that MySQL database named as test is present on server and a table named employee is also created. The table has five fields fname, lname, age, gender, and salary." }, { "code": null, "e": 1292, "s": 1235, "text": "A tuple o...
Exploring Moving Averages to Build Trend Following Strategies in Python | by Runar Aadnesen Østhaug | Towards Data Science
“Buy low, sell high” is a common goal everyone in finance wants to achieve. This however is more difficult than appears, since we don’t know where the top or bottom will be. We only know where we are right now, and where we have been. Many investors that sit and wait for the next recession in order to get a good entry point, miss out on the fantastic return in the bull market leading up, and the ones sitting in indices receive the benefits of the bull market but also the harsh reality of the bear market. It is easier to follow the trend than to predict the top and bottom. So in this article, we will cover some basic methods of tracking market trend and try to achieve solid returns both during the bull markets and the bear markets. The simple moving average (SMA) is a smoothing function that calculates the average of the past observations. It is a common technical indicator that is used to signal a price reversal. If we have 1000 days of daily pricing data, the 100 day moving average is calculated by averaging the first 100 days and subsequently averaging 100 days at a time by shifting the range one day at a time. Simple moving average based strategies revolve around using the relationship between the asset price and the moving average as a way of capturing the trend. We will use the point where the price and the MA cross over to determine our position. We can either download the data from a website such as Yahoo finance and load it onto a DataFrame, or use an API to read it directly from an external server onto the Python memory. import pandas as pddf = pd.read_csv("your_data.csv") Quandl is an online database for financial data with a free and a premium account. The number of requests for non-users is limited, while users can get 300 calls every 10 seconds. More than enough for basic use. We use our favorite stock of choice Apple, and download price data from the period 2009 through 2018. myquandlkey = "myquandlkey"import quandlaapl = quandl.get("WIKI/AAPL", start_date="2009-01-01", end_date="2018-12-31", api_key=myquandlkey) Another popular choice is the pandas_datareader, which is the one that will be used this time. import pandas_datareader as webaapl = web.get_data_yahoo('AAPL', start=datetime.datetime(2009, 1, 1), end=datetime.datetime(2018, 12, 31)) After importing the data, let’s take a look at the DataFrame to check that everything looks correct aapl.head() For now, only keep the adjusted close, but the volume can be interesting to look at in further analysis. Remove the first row as we accidentally included New Year’s Eve 2008. # New DataFrame only containing the Adj Close columnaapl = aapl[["Adj Close"]]# Rename the adjusted close column to Priceaapl.rename(columns={"Adj Close":"Price"}, inplace=True)# Remove the first row,aapl = aapl.iloc[1:]aapl.head() Use the pandas rolling function for calculating the moving average, and add the result as a new column to the DataFrame. aapl["100MA"] = aapl["Price"].rolling(window=100).mean()aapl The 99 first moving average values show as NaN. This is because we needed the first 100 price observations to calculate the MA. # import plotting packagesimport matplotlib.pyplot as pltimport matplotlib as mpl# Set color styleplt.style.use('seaborn-dark')plt.style.use("tableau-colorblind10")fig = plt.figure(figsize=(20,12))ax1 = plt.plot(aapl["Adj Close"])ax1 = plt.plot(aapl["100MA"])ax1 = plt.title("Apple daily ajusted close from 2009 through 2018", fontsize=22)ax1 = plt.xlabel("Date", fontsize=18)ax1 = plt.ylabel("Price", fontsize=18)ax1 = plt.legend(["Price", "100 day SMA"],prop={"size":20}, loc="upper left")plt.grid(True)plt.show() The 100 day MA is a way of viewing the trend of the price by smoothing out the price. Since it is a lagging indicator it tells us what happened in the past, and although it is interesting to have a look it may not be used as a good strategy in and of itself. Let’s explore and see the outcome. We will use two different strategies Buy when the price exceeds the moving average, short sell when the price drops below the moving average.As an alternative we can replace the short position with cash position, making the strategy long only. Buy when the price exceeds the moving average, short sell when the price drops below the moving average. As an alternative we can replace the short position with cash position, making the strategy long only. We could improve strategy 2 by holding low risk securities such as bonds instead of cash with just a small increase in volatility, but for simplicity, cash is king today. We hope to catch the ride when the asset is trending upwards, gaining similar returns. When it trends downwards choose to sell out and wait, or short sell in order to benefit from the fall. There can be several problems with a simple strategy like this. If the trend doesn’t manifest itself but gives a false positive, our strategy can end up buying or selling in the wrong direction and lose money. A lot of crossovers in a short time can pile up transaction costs. A solution to this can be to set a minimum distance between the price and the moving average before we trade, which can be explored further later. Let’s create a new column containing “Long” or “Short” following strategy 1. Position = []for i in range(0,apple.shape[0]): if apple[“Adj Close”].iloc[i] > apple[“100MA”].iloc[i]: Position.append(“Long”) else: Position.append(“Short”)apple[“Position”] = Positionapple.head() Create a new column of price returns and add it to the DataFrame apple[“return”] = (apple[“Adj Close”] — apple[“Adj Close”].shift())/apple[“Adj Close”].shift()# The first return is defined from the 2. row, so drop the firstapple.dropna(inplace=True)apple.head() At day 1, set the value of each strategy equal to the price of Apple so it will be easy to compare how the value of the strategies moves compares to the price of Apple. Compare the price with the moving average and set a position “Long” or “Short”. The return at day 1 will be set using the percentage change from day 0. We can’t place a position yet because we only have the daily close, and need to wait until tomorrow. At day 2 we go long or short based on the position from day 1, since we didn’t add or remove any value from day 1 to 2, the strategies will have the same value as day 1. At day 3 we multiply the return, or change in Apple price from day 2 to 3, which is the return in row nr. 3, by each strategy. edit: Keep in mind that the LongHold strategy is strategy 2 which is holding cash. A better name would be LongCash. LongShort = [0]*apple.shape[0]LongHold = [0]*apple.shape[0]LongShort[0] = apple[“Adj Close”].iloc[0]LongShort[1] = apple[“Adj Close”].iloc[0]LongHold[0] = apple[“Adj Close”].iloc[0] LongHold[1] = apple[“Adj Close”].iloc[0]for i in range(0, apple.shape[0]-2): if apple[“Position”].iloc[i] == “Long”: LongShort[i+2] = LongShort[i+1]*(1+apple[“return”][i+2]) else: LongShort[i+2] = LongShort[i+1]/(1+apple[“return”][i+2]) for i in range(0, apple.shape[0]-2): if apple[“Position”].iloc[i] == “Long”: LongHold[i+2] = LongHold[i+1]*(1+apple[“return”][i+2]) else: LongHold[i+2] = LongHold[i+1]apple[“LongShort”] = LongShortapple[“LongHold”] = LongHoldapple.drop(apple.tail(1).index,inplace=True)apple.head() Now plot the strategies together with the 100 day SMA fig = plt.figure(figsize=(20,12))ax1 = plt.plot(apple[“Adj Close”])ax1 = plt.plot(apple[“100MA”])ax1 = plt.plot(apple[“LongShort”], color=”green”)ax1 = plt.plot(apple[“LongHold”], color=”brown”)ax1 = plt.title(“Apple daily ajusted close and strategy from 2009 through 2018”, fontsize=18)ax1 = plt.xlabel(“Date”, fontsize=18)ax1 = plt.ylabel(“Price”, fontsize=18)ax1 = plt.legend([“Price”, “100 day SMA”, “SMA crossover long/short strategy”, “SMA crossover long/cash strategy”],prop={“size”:22}, loc=”upper left”)plt.grid(True)plt.show() In the last 10 years Apple experiences a very healthy growth. Because the SMA is lagging, the shorts ends up hurting us. A slight down-movement which causes a SMA crossover quickly turns into a sharp increase without the SMA graph catching up quick enough, leaving us shorting when the asset price is increasing. As can be seen, Long/Short strategy is crushed by the price process, while the Long/Hold strategy stays in the middle. In 2012/2013 the shorting strategy works, increasing the value when Apple price is falling. The price is smooth, manifesting the trend easily. In 2015/2016 the strategy doesn’t work well. The price trend doesn’t manifest itself and exhibits high volatility. Instead of the SMA, a more appropriate weighting function will give a higher vote to more recent observations. A popular version of this is the exponential moving average (EMA), which uses an exponentially decaying weighting. Since old observations have very little say, we may use the entire dataset as a lookback period to calculate the EMA. The formula is given by Implement the EMA with the same strategies as earlier. Simply compare the price with the EMA instead of the SMA. At least for Apple, the EMA performs better then the SMA. This might be because it reacts quicker to sudden changes in the asset price. It still doesn’t overperform simply holding the asset. Instead of using a single moving average, we can compare the relationship between two moving averages with different time periods. This is known as the moving average convergence divergence, or MACD. The hypothesis is to buy or sell the asset depending on the trend captured by the MACD indicator. When the short term MA exceeds the long term, we go long, and when the long term MA exceeds the short term, we go short. In this analysis I have used the 21 day EMA and the 126 day EMA, representing one and six months of trading days. Since the backtests are run over a long time horizon I try to avoid using too short lookback periods. To write the code, calculate the 26 and 126 day EMA, and compare them instead of comparing the price with the MA. Similarly to the EMA, we plot the and look at the results This particular version of the MACD doesn’t perform well on this data. We will soon look at all the strategies on a variety of data sets and time frames too see how they have in different situations. To generalize from the above analysis, I have used functions to make it easier to select which data we want to analyze, and what models we want to include. I have also incorporating a summary statistics script to see how each of the strategies are performing in terms of max drawdown, sharpe, volatility, and annualized return, VaR, etc. Now write a main function that will use the above functions, as well as a function that plots the result. Let’s run the main function strategy() and the plot function plot_strategy(), as well as displaying the table of summary statistics. We calculate and plot the 3 MA variations and both the Long/Short and the Long/Hold for all. Apple from 2009 through 2018, as done earlier S&P 500 in the same period start = datetime.date(2009, 1, 1)end = datetime.date(2018, 12, 31)ticker = “AAPL”days = 100df, table, df_return_of_strategy, df_positions, df_price_of_strategy = strategy(ticker, start, end, days=days, MA=True, EMA=True, MACD=True, LongHold=True, LongShort=True)plot_strategy(ticker=ticker, start=str(start), end=str(end), df=df_price_of_strategy)table The moving average strategies doesn’t do well in the bull market. Shorting when the market is going up and still produce excess return is hard. The maximum drawdown and volatility is lowest among the cash portfolios as we can expect, which actually gives a higher Sharpe ratio in Apple than holding the stock in the period. Let’s look at two market crashes, leading up and during the fall. S&P 500 from 2006 through 2010, “the global financial crisis” NASDAQ Composite from 1998 through 2001, “Tech bubble” Nikkei 225 during the 1990’s, “the lost decade” There is no surprise that shorting during a bear market produces good results, but we initiated the positions a good while before the top, which doesn’t harm return too bad during the lead up. In the downfall however, the short positions benefits massively. One drawdown of this strategy is that we can’t detect sudden drops in price. In “black friday” 1987, the Dow Jones Industrial Average fell with 22.6% and the S&P 500 with over 18%. These strategies can’t protect us against such falls, and should be implemented in conjunction with other methods. General motors from 2014 through 2019 Microsoft from 2002 through 2017 Sideways never manifest a trend, when the lagging MA catches up to the price, it is already too late. The trend is too short, which suggests a shorter MA could be a better choice. One thing to notice is that the EMA have higher returns in all but the last graph, and volatilities similar or lower. This version of the MACD doesn’t give very good results, although the most common version uses 12 days for the fast EMA, and 26 days for the slow. The moving average crossover strategy for trend following is a well known simple approach for tracking the trend that in the period tested and with the data used, performs better in a bear market than a bull market. Although high volatile and stagnant markets can compromise its quality. We have made several assumptions. There is no slippage or transaction fees. We only use adjusted daily close and can only make a transaction at that time. We don’t consider dividends or shorting restrictions. We re-balance daily, which is not always feasible for some funds that have to move a large volume. They might be too late to the party. We also buy and sell simply based on the crossover, not considering a high oscillation between price and MA before they diverge. For further analysis, it would be interesting to compare a variety of asset classes with contrasting behavior, for instance, high volatility vs. low volatility. It would be interesting to run through a set of assets each day, looking at the percentage distance between the price and the MA to see if trading those with a larger distance can reduce the number of false positives, and capture more solid trends better. It would also be useful to perform more rigorous backtesting using an appropriate time series cross-validation approach. Stability in the model is very important. If we change a few parameters and the results changes drastically, we should scrap the model and start again. A backtest doesn’t prove anything, but using cross-validation and limit look-ahead bias can improve our confidence. Disclaimer: If you find any mistakes please let me know. Also, note that this is just an exploration of some methods on some historic data. Past performance doesn’t guarantee future results. Update (19/02/2020): this is a rewritten edition. I have revised a calculation error from the first version. Github repository: https://github.com/RunarOesthaug/MA-crossover_strategies Thanks for reading! Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details.
[ { "code": null, "e": 682, "s": 172, "text": "“Buy low, sell high” is a common goal everyone in finance wants to achieve. This however is more difficult than appears, since we don’t know where the top or bottom will be. We only know where we are right now, and where we have been. Many investors that ...
How to concatenate fields in MySQL?
To concatenate fields in MySQL, you can use GROUP_CONCAT() along with GROUP BY. Let us first create a table − mysql> create table DemoTable ( StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, StudentName varchar(30), StudentScore int ); Query OK, 0 rows affected (0.51 sec) Insert records in the table using insert command − mysql> insert into DemoTable( StudentName,StudentScore) values('Bob',80); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable( StudentName,StudentScore) values('Bob',80); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable( StudentName,StudentScore) values('Chris',90); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable( StudentName,StudentScore) values('Chris',70); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable( StudentName,StudentScore) values('Bob',50); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable( StudentName,StudentScore) values('David',60); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable( StudentName,StudentScore) values('Chris',99); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable( StudentName,StudentScore) values('David',88); Query OK, 1 row affected (0.18 sec) Display all records from the table using select statement − mysql> select * from DemoTable; This will produce the following output − +-----------+-------------+--------------+ | StudentId | StudentName | StudentScore | +-----------+-------------+--------------+ | 1 | Bob | 80 | | 2 | Bob | 80 | | 3 | Chris | 90 | | 4 | Chris | 70 | | 5 | Bob | 50 | | 6 | David | 60 | | 7 | Chris | 99 | | 8 | David | 88 | +-----------+-------------+--------------+ 8 rows in set (0.00 sec) Following is the query to concatenate fields in MySQL − mysql> select StudentName, group_concat(StudentScore separator ',') as Score from DemoTable group by StudentName; This will produce the following output − +-------------+----------+ | StudentName | Score | +-------------+----------+ | Bob | 80,80,50 | | Chris | 90,70,99 | | David | 60,88 | +-------------+----------+ 3 rows in set (0.24 sec)
[ { "code": null, "e": 1172, "s": 1062, "text": "To concatenate fields in MySQL, you can use GROUP_CONCAT() along with GROUP BY. Let us first create a table −" }, { "code": null, "e": 1352, "s": 1172, "text": "mysql> create table DemoTable\n (\n StudentId int NOT NULL AUTO_INCR...
A Guide To Interpretable Machine Learning— Part 1 | by Abhijit Roy | Towards Data Science
Machine learning models are becoming popular at a huge rate currently. They are now being used to solve various problems in various fields. At this point of increasing popularity and consequently, importance in our daily lives, there is a silent hazard, that is also very important to take care of now: the interpretability of the machine learning model. In recent times, we have seen how image processing is used in security sectors and health sectors, regression, and classification models are used in stock markets and investment sectors. If we observe closely, we are depending on machine learning to make essential decisions that will affect us for sure. So, the question arises, why should we trust models? In other words, why should we depend on a decision taken by an intelligence algorithm without even knowing how it operate? Well, you can say that there are various algorithms like decision trees and linear regression which are very easy to understand and are interpretable. But, in the current world, researchers and data scientists are constantly trying to solve challenging problems, which can’t be solved by interpretable models efficiently and thus, need very complicated algorithms or customized neural network-based ones. If we look around us, we will find that most instances, use complex and black box models and it is very hard for us to answer the question “How is the algorithm doing it?” It proves to be a valid question. Often while designing a model, data scientists focus on a few questions or a few regulations on some features, that they expect the model to learn and use for prediction. For example, I may feed the population to predict, “Whether to set up a shop in the region or not”.The reason being that I may think that if the population is high my sales will be high, so there will be a very high correlation between these two, so my model will learn this feature and the feature’s importance will be high. I train my model, it gives me high accuracy but it may turn out that it didn’t learn the way it was planned to learn. So, we need to be sure about these things in several cases to increase the accuracy and be sure of our predictions. I will illustrate a classic example, in an image classification of a “Siberian Husky” and a “Wolf”, a model was designed. It gave very high accuracy. When the model was analyzed, it was discovered that the model never classified the husky and the wolf. It classified “Snow” or “No Snow”. The snow was predicted as husky and no snow as a wolf. Most husky images had snow the accuracy was very good. So, from the above examples we can understand, how important is it to actually interpret our models. Numerous methods to deal with the interpretation of machine learning models have evolved over the years. Different methods use different logic and theories to interpret the hard to understand “black box” algorithms like neural networks, Xgboost, and random forests. Two of the most important and popular methods are LIME and SHAP. They are used to interpret local or observation-wise predictions. In other words, they give us a clear intuition of how a given feature affects a prediction in our model and how important is that feature for our model. We will talk about LIME in detail and briefly on SHAP in this article. We will try to explain using the famous Titanic Dataset available here. The sinking of the Titanic is one of the most infamous shipwrecks in history. On April 15, 1912, during her maiden voyage, the widely considered “unsinkable” RMS Titanic sank after colliding with an iceberg. Unfortunately, there weren’t enough lifeboats for everyone on board, resulting in the death of 1502 out of 2224 passengers and crew. While there was some element of luck involved in surviving, it seems some groups of people were more likely to survive than others. In this challenge, we ask you to build a predictive model that answers the question: “what sorts of people were more likely to survive?” using passenger data (ie name, age, gender, socio-economic class, etc). Now lets first talk about the dataset a bit and then move to our objective. The dataset looks like this, it has 12 columns. “Survived” is our target column and others are feature columns. Now, the feature columns will need some preprocessing. Dataset extraction snippet: import pandas as pddf1=pd.read_csv('train.csv')df2=pd.read_csv('test.csv')df=pd.concat([df1,df2],axis=0) We will drop PassengerID as it won’t have any correlation. Next, we will take the “Name” column, and based on their title will assign them, class, like “Mrs”, will be class 1, “Mr” class 2, and so on. We can do this using the following snippet. i=0name=[]while i<len(df): #print(df.iloc[i]['Name'].type) if "Mrs." in df.iloc[i]['Name']: name.append(str(1)) print("a") elif 'Mr.' in df.iloc[i]['Name']: name.append(str(2)) print("b") elif "Miss." in df.iloc[i]['Name']: name.append(str(3)) print("c") elif "Master." in df.iloc[i]["Name"]: name.append(str(4)) print("d") else: name.append(str(5)) i+=1df=df.drop(['Name'],axis=1)df['name']=name Now, we go for the SibSp, here also we will create a feature having two classes, having siblings denoted by one and not having siblings denoted by 0, and include it in the feature set dropping the original feature. One thing we need to take care of is most of these features have NaN’s so we need to fill the NULL values first to avoid errors. Code snippet: i=0siblings=[]df.fillna(0)while i<len(df): if df.iloc[i]['SibSp']>0: siblings.append(str(1)) else: siblings.append(str(0)) i+=1df=df.drop(["SibSp"],axis=1)df["Siblings"]=siblings Next, we do the same for the Parch feature, we design two classes, having parent represented by 1 and not having parents represented by 0 and use the column as a feature. i=0parent=[]df.fillna(0)while i<len(df): if df.iloc[i]['Parch']>0: parent.append(str(1)) else: parent.append(str(0)) i+=1df=df.drop(["Parch"],axis=1)df["Parent"]=parent We go for the “age” feature, there are also a few NaNs which we will fill using the mean value of the age column. df['Age'].fillna(df['Age'].mean()) We will then create a new feature column having 5 classes to classify and remove the variable nature of the age. I have used the given class boundaries: Age<15: Class 1 15≤Age<30: Class 2 30≤Age<45: Class 3 45≤Age<60: Class 4 Age≥60: Class 5 “Age” below 15 is classified as 1 and so on. Code: i=0age=[]while i<len(df): if df.iloc[i]['Age']<15: age.append(str(1)) elif df.iloc[i]['Age']<30: age.append(str(2)) elif df.iloc[i]['Age']<45: age.append(str(3)) elif df.iloc[i]['Age']<60: age.append(str(4)) else: age.append(str(5)) i+=1df['age']=agedf=df.drop(['Age'],axis=1) For the “Fare” feature, we will do the same as the “age” feature. We will fill NaN with mean and classify them into some fixed buckets. Here are my estimations or bucket boundaries. Fare<15: Class 1 15≤Fare<55: Class 2 55≤Fare<120: Class 3 120≤Fare<190: Class 4 Fare≥190: Class 5 Next, if we check the “Tickets” column, we will see a few special tickets with letters, and others are numeric. I have labeled the completely numeric ones 1 else 0. Snippet: i=0ticket=[]while i<len(df): if df.iloc[i]['Ticket'].isnumeric(): ticket.append(str(1)) else: ticket.append(str(0)) i+=1df['ticket']=ticketdf=df.drop(['Ticket'],axis=1) Next, we do something similar to the cabin feature. Most of the entries in the “Cabin” feature are empty. We label the empty ones as 0 and others as 1. z=0df['Cabin'].fillna("NA")cabin=[]while z<len(df): print(df.iloc[z]['Cabin']) if 'NA' in str(df.iloc[z]['Cabin']): cabin.append(str(0)) else: cabin.append(str(1)) z+=1 Now, our preprocessing is complete. After the preprocessing our data looks like this. We will now drop the Survived column and apply encoding on the categorical features. After application, we will obtain a Feature set X, of 31 columns i.e 31 features and a target set Y, of 1 column, Survived. Index(['Survived', 'Pclass_1', 'Pclass_2', 'Pclass_3', 'Sex_female', 'Sex_male', 'Embarked_C', 'Embarked_Q', 'Embarked_S', 'name_1', 'name_2', 'name_3', 'name_4', 'name_5', 'Siblings_0', 'Siblings_1', 'Parent_0', 'Parent_1', 'age_1', 'age_2', 'age_3', 'age_4', 'age_5', 'fare_1', 'fare_2', 'fare_3', 'fare_4', 'fare_5', 'ticket_0', 'ticket_1', 'cabin_0', 'cabin_1'], dtype='object') These are our 31 features. We split our dataset in X_train, Y_train, X_test, and Y_test. from sklearn.model_selection import train_test_splitX_train,X_test,Y_train,Y_test=train_test_split(X,Y,test_size=0.3, random_state=42) Thus we have processed our dataset and are ready for operations. We go back to our application. LIME stands for Linear Model Agnostic Explanation. It is used for local interpretation. It is used to analyze and interpret the underlying Black box model’s decision and its prediction based on a particular observation, say a particular row of the training or testing dataset. Now, the question arises how does it do that? As we have noticed earlier, there are several models that are very easy to interpret. LIME uses these interpretable models to predict the black box models. LIME uses models like Decision Tree and Logistic Regression to create a clone of the predictions given by the Black box model. It takes in a single observation and creates a set of observations by changing the feature values by some amount. Thus, after trying all combinations, LIME obtains a totally new feature set. This feature set is then passed to the black-box model and the corresponding predictions are obtained. Now, these predictions become the Y_training or target set and the Feature set becomes X_training set for the interpretable models. Now, LIME has several models like Decision Trees, Linear Regression, Lasso Regression, and Logistic regression. The target interpretable model is the one that produces minimum Loss among all the interpretable models. This is due to the fact, that minimum loss function implies the model that had maximum accuracy that is the model that cloned the black-box model the best. Now as the interpretable model behaves like the Black-box model, interpreting it will give the results for the Black box model. This is the interpreting formula of LIME. Here the explanation of the observation x is shown by the one of the models f, or g, depending upon which will produce the minimum loss function and the sigma(g) depicts the complexity of the interpreting model kept as low as possible. Now the variation of data produced by LIME also gives the interpreting model liberty to get the boundaries of a feature, like if the value of a feature is less than the value x it is class A else it is class B. There are a few disadvantages also. The problem with LIME is that it is a local algorithm, so its explanation is not true for the entire dataset. Some of the best interpreting Algorithms are Decision Trees and Logistic regression. We will talk about these two algorithms here. Decision Trees: It is used for non-linear datasets. Now, here the tree takes in a dataset and keeps on splitting the datasets based on the boundary values of different features. It splits the dataset multiple times and creates several data subsets. The final subsets are the leaf nodes. They are classified classes. The internal nodes are the splitting nodes. Training helps the tree to judge the boundary values of every feature and their impact on the decision path. So, each node represents a feature and a value corresponding to that feature that acts as a boundary. Now, every Decision tree wants to minimize the Gini Coefficient. The Gini Coefficient is the difference between the actual value and the predicted value. So, after each node, if we try to judge how much the coefficient decreases compared to the parent, we will gain a clear insight into the weight of the node. The weight of the node depicts the feature’s importance. Logistic Regression: It is a classification based on a linear regression algorithm. This does not work for Non-linear models. In linear regression, we use an equation to represent an n-dimensional hyperplane to predict the values. Y=b0+b1x1+b2x2+..........+bnxn Here b0 is the intercept and the b{i} for a feature ‘i’ is the coefficient or the weight of the feature in the regression. It produces interpolation values using linear regression. In classification, we predict probabilities so we squeeze the value between 0 and 1 using a logistic function. which looks like this, So, we obtain probability as Now, we deal with the ratio of the probability of an event happening and the probability of the event, not happening. P(y=1)/P(y=0). This ratio is called the odds. This is our equation. Now here p(y=1)/p(y=0) =n means that the chance of the event occurring is n times then the chance of the event not occurring. Now if we increase the value of the feature j (xj) by 1, then the equation becomes, which results in, So, if we increase a feature by 1 unit its effect on the odds will be exponential of its weight. So, its contribution is a function of its weight. So we can easily get the feature contributions using the weights in logistic regression. In the next portion, we will see applications and practical implementations of interpretable models. We will also see the SHAP application.
[ { "code": null, "e": 527, "s": 172, "text": "Machine learning models are becoming popular at a huge rate currently. They are now being used to solve various problems in various fields. At this point of increasing popularity and consequently, importance in our daily lives, there is a silent hazard, t...
C# program to check for a string that contains all vowels
To check for all vowels, firstly set the condition to check − string res = str.Where(chk =< "aeiouAEIOU".Contains(chk)).Distinct(); Above, we have used the string − string str = "the quick brown fox jumps over the lazy dog"; Now, using the Any() method checks whether the string has any vowels or not − if(!res.Any()) Console.WriteLine("No vowels!"); Loop through the string to get the vowels − Live Demo using System; using System.Linq; public class Program { public static void Main() { string str = "the quick brown fox jumps over the lazy dog"; var res = str.Where(chk =< "aeiouAEIOU".Contains(chk)).Distinct(); if(!res.Any()) Console.WriteLine("No vowels!"); foreach(var vowel in res) Console.WriteLine("Your phrase contains vowel = {0}", vowel); } } Your phrase contains vowel = e Your phrase contains vowel = u Your phrase contains vowel = i Your phrase contains vowel = o Your phrase contains vowel = a
[ { "code": null, "e": 1124, "s": 1062, "text": "To check for all vowels, firstly set the condition to check −" }, { "code": null, "e": 1194, "s": 1124, "text": "string res = str.Where(chk =< \"aeiouAEIOU\".Contains(chk)).Distinct();" }, { "code": null, "e": 1227, "...
Kill Process in C++
Suppose we have n processes, here each process has a unique id called PID or process id and its PPID (parent process id) is also there. Each process only has one parent process, but may have one or more child processes. This is just like a tree structure. Only one process has the PPID = 0, which means this process has no parent process. All the PIDs will be unique positive integers. We will use two list of integers to represent a list of processes, where the first list contains PID for each process and the second list contains the corresponding PPID. So, if we have two lists, and a PID representing a process we want to kill, then we have to find a list of PIDs of processes that will be killed in the end. And we should assume that when a process is killed, all its children processes will be killed. So, if the input is like pid = [1, 3, 10, 5] ppid = [3, 0, 5, 3] kill = 5, then the output will be [5,10], Kill 5 will also kill 10. To solve this, we will follow these steps − Define one map child Define one map child n := size of pid n := size of pid Define an array ret Define an array ret for initialize i := 0, when i < n, update (increase i by 1), do −u := ppid[i]v := pid[i]insert v at the end of child[u] for initialize i := 0, when i < n, update (increase i by 1), do − u := ppid[i] u := ppid[i] v := pid[i] v := pid[i] insert v at the end of child[u] insert v at the end of child[u] Define one queue q Define one queue q insert kill into q insert kill into q while (not q is empty), do −curr := first element of qdelete element from qinsert curr at the end of retfor initialize i := 0, when i < size of child[curr], update (increase i by 1), do −insert child[curr, i] into q while (not q is empty), do − curr := first element of q curr := first element of q delete element from q delete element from q insert curr at the end of ret insert curr at the end of ret for initialize i := 0, when i < size of child[curr], update (increase i by 1), do −insert child[curr, i] into q for initialize i := 0, when i < size of child[curr], update (increase i by 1), do − insert child[curr, i] into q insert child[curr, i] into q return ret return ret Let us see the following implementation to get a better understanding − Live Demo #include <bits/stdc++.h> using namespace std; void print_vector(vector<auto> v){ cout << "["; for(int i = 0; i<v.size(); i++){ cout << v[i] << ", "; } cout << "]"<<endl; } class Solution { public: vector<int> killProcess(vector<int>& pid, vector<int>& ppid, int kill) { map<int, vector<int> > child; int n = pid.size(); vector<int> ret; for (int i = 0; i < n; i++) { int u = ppid[i]; int v = pid[i]; child[u].push_back(v); } queue<int> q; q.push(kill); while (!q.empty()) { int curr = q.front(); q.pop(); ret.push_back(curr); for (int i = 0; i < child[curr].size(); i++) { q.push(child[curr][i]); } } return ret; } }; main(){ Solution ob; vector<int> v = {1,3,10,5}, v1 = {3,0,5,3}; print_vector(ob.killProcess(v, v1, 5)); } {1,3,10,5},{3,0,5,3},5 [5, 10, ]
[ { "code": null, "e": 1198, "s": 1062, "text": "Suppose we have n processes, here each process has a unique id called PID or process id and its PPID (parent process id) is also there." }, { "code": null, "e": 1282, "s": 1198, "text": "Each process only has one parent process, but ...
Check whether a given matrix is orthogonal or not - GeeksforGeeks
18 Aug, 2021 We are given a matrix, we need to check whether it is an orthogonal matrix or not. An orthogonal matrix is a square matrix and satisfies the following condition: A*At = I Examples : Input: 1 0 0 0 1 0 0 0 1 Output: Yes Given Matrix is an orthogonal matrix. When we multiply it with its transpose, we get identity matrix. Input: 1 2 3 4 5 6 7 8 9 Output: No Given Matrix Is Not An Orthogonal Matrix Simple Solution : The idea is simple, we first find transpose of matrix. Then we multiply the transpose with given matrix. Finally we check if the matrix obtained is identity or not. C++ Java Python3 C# PHP Javascript // C++ code to check whether// a matrix is orthogonal or not#include <bits/stdc++.h>using namespace std; #define MAX 100 bool isOrthogonal(int a[][MAX], int m, int n){if (m != n) return false; // Find transposeint trans[n][n];for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) trans[i][j] = a[j][i]; // Find product of a[][]// and its transposeint prod[n][n];for (int i = 0; i < n; i++){ for (int j = 0; j < n; j++) { int sum = 0; for (int k = 0; k < n; k++) { // Since we are multiplying with // transpose of itself. We use sum = sum + (a[i][k] * a[j][k]); } prod[i][j] = sum; }} // Check if product is identity matrixfor (int i = 0; i < n; i++){ for (int j = 0; j < n; j++) { if (i != j && prod[i][j] != 0) return false; if (i == j && prod[i][j] != 1) return false; }} return true;} // Driver Codeint main(){ int a[][MAX] = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}};if (isOrthogonal(a, 3, 3)) cout << "Yes";else cout << "No";return 0;} // Java code to check whether// a matrix is orthogonal or notimport java .io.*;class GFG { //static int MAX =100; static boolean isOrthogonal(int [][]a, int m, int n) { if (m != n) return false; // Find transpose int [][]trans = new int[n][n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) trans[i][j] = a[j][i]; // Find product of a[][] // and its transpose int [][]prod = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { int sum = 0; for (int k = 0; k < n; k++) { // Since we are multiplying // transpose of itself. We use sum = sum + (a[i][k] * a[j][k]); } prod[i][j] = sum; } } // Check if product is // identity matrix for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i != j && prod[i][j] != 0) return false; if (i == j && prod[i][j] != 1) return false; } } return true; } // Driver code static public void main (String[] args) { int [][]a = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}; if (isOrthogonal(a, 3, 3)) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed by anuj_67. # Python code to check# whether a matrix is# orthogonal or not def isOrthogonal(a, m, n) : if (m != n) : return False trans = [[0 for x in range(n)] for y in range(n)] # Find transpose for i in range(0, n) : for j in range(0, n) : trans[i][j] = a[j][i] prod = [[0 for x in range(n)] for y in range(n)] # Find product of a[][] # and its transpose for i in range(0, n) : for j in range(0, n) : sum = 0 for k in range(0, n) : # Since we are multiplying # with transpose of itself. # We use sum = sum + (a[i][k] * a[j][k]) prod[i][j] = sum # Check if product is # identity matrix for i in range(0, n) : for j in range(0, n) : if (i != j and prod[i][j] != 0) : return False if (i == j and prod[i][j] != 1) : return False return True # Driver Codea = [[1, 0, 0], [0, 1, 0], [0, 0, 1]] if (isOrthogonal(a, 3, 3)) : print ("Yes")else : print ("No") # This code is contributed by# Manish Shaw(manishshaw1) // C# code to check whether// a matrix is orthogonal or notusing System; class GFG{ //static int MAX =100; static bool isOrthogonal(int [,]a, int m, int n) { if (m != n) return false; // Find transpose int [,]trans = new int[n, n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) trans[i, j] = a[j, i]; // Find product of a[][] // and its transpose int [,]prod = new int[n, n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { int sum = 0; for (int k = 0; k < n; k++) { // Since we are multiplying // transpose of itself. We use sum = sum + (a[i, k] * a[j, k]); } prod[i, j] = sum; } } // Check if product is // identity matrix for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i != j && prod[i, j] != 0) return false; if (i == j && prod[i, j] != 1) return false; } } return true; } // Driver code static public void Main () { int [,]a = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}; if (isOrthogonal(a, 3, 3)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by vt_m <?php// PHP code to check whether// a matrix is orthogonal or not function isOrthogonal($a, $m, $n){ if ($m != $n) return false; // Find transpose for($i = 0; $i < $n; $i++) for ($j = 0; $j < $n; $j++) $trans[$i][$j] = $a[$j][$i]; // Find product of a[][] // and its transpose for($i = 0; $i < $n; $i++) { for ($j = 0; $j < $n; $j++) { $sum = 0; for ($k = 0; $k < $n; $k++) { // Since we are multiplying with // transpose of itself. We use $sum = $sum + ($a[$i][$k] * $a[$j][$k]); } $prod[$i][$j] = $sum; } } // Check if product is // identity matrix for($i = 0; $i < $n; $i++) { for ($j = 0; $j < $n; $j++) { if ($i != $j && $prod[$i][$j] != 0) return false; if ($i == $j && $prod[$i][$j] != 1) return false; } } return true;} // Driver Code $a = array(array(1, 0, 0), array(0, 1, 0), array(0, 0, 1)); if (isOrthogonal($a, 3, 3)) echo "Yes"; else echo "No"; // This code is contributed by ajit.?> <script> // Javascript code to check whether// a matrix is orthogonal or not // static int MAX =100;function isOrthogonal(a, m, n){ if (m != n) return false; // Find transpose let trans = new Array(n); for(let i = 0; i < n; i++) { trans[i] = new Array(n); for(let j = 0; j < n; j++) trans[i][j] = a[j][i]; } // Find product of a[][] // and its transpose let prod = new Array(n); for(let i = 0; i < n; i++) { prod[i] = new Array(n); for(let j = 0; j < n; j++) { let sum = 0; for(let k = 0; k < n; k++) { // Since we are multiplying // transpose of itself. We use sum = sum + (a[i][k] * a[j][k]); } prod[i][j] = sum; } } // Check if product is // identity matrix for(let i = 0; i < n; i++) { for(let j = 0; j < n; j++) { if (i != j && prod[i][j] != 0) return false; if (i == j && prod[i][j] != 1) return false; } } return true;} // Driver codelet a = [ [ 1, 0, 0 ], [ 0, 1, 0 ], [ 0, 0, 1 ] ]; if (isOrthogonal(a, 3, 3)) document.write("Yes");else document.write("No"); // This code is contributed by divyesh072019 </script> Yes An efficient solution is to combine three traversals into one. Instead of explicitly finding transpose, we use a[j][k] instead of a[k][j]. Also, instead of explicitly computing product, we check identity while computing product. C++ Java Python3 C# PHP Javascript // C++ code to check whether// a matrix is orthogonal or not#include <bits/stdc++.h>using namespace std; #define MAX 100 bool isOrthogonal(int a[][MAX], int m, int n){if (m != n) return false; // Multiply A*A^tfor (int i = 0; i < n; i++){ for (int j = 0; j < n; j++) { int sum = 0; for (int k = 0; k < n; k++) { // Since we are multiplying with // transpose of itself. We use // a[j][k] instead of a[k][j] sum = sum + (a[i][k] * a[j][k]); } if (i == j && sum != 1) return false; if (i != j && sum != 0) return false; }} return true;} // Driver Codeint main(){ int a[][MAX] = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}};if (isOrthogonal(a, 3, 3)) cout << "Yes";else cout << "No";return 0;} // C# code to check whether// a matrix is orthogonal or notusing System; class GFG{ //static int MAX =100; static bool isOrthogonal(int[,]a, int m, int n) { if (m != n) return false; // Multiply A*A^t for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { int sum = 0; for (int k = 0; k < n; k++) { // Since we are multiplying // with transpose of itself. // We use a[j][k] instead // of a[k][j] sum = sum + (a[i, k] * a[j, k]); } if (i == j && sum != 1) return false; if (i != j && sum != 0) return false; } } return true; } // Driver code public static void Main () { int [,]a = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}; if (isOrthogonal(a, 3, 3)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by vt_m # Python code to check# whether a matrix is# orthogonal or not def isOrthogonal(a, m, n) : if (m != n) : return False # Multiply A*A^t for i in range(0, n) : for j in range(0, n) : sum = 0 for k in range(0, n) : # Since we are multiplying # with transpose of itself. # We use a[j][k] instead # of a[k][j] sum = sum + (a[i][k] * a[j][k]) if (i == j and sum != 1) : return False if (i != j and sum != 0) : return False return True # Driver Codea = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]if (isOrthogonal(a, 3, 3)) : print ("Yes")else : print ("No") # This code is contributed by# Manish Shaw(manishshaw1) // C# code to check whether// a matrix is orthogonal or notusing System; public class GFG{ //static int MAX =100; static bool isOrthogonal(int[,]a, int m, int n) { if (m != n) return false; // Multiply A*A^t for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { int sum = 0; for (int k = 0; k < n; k++) { // Since we are multiplying with // transpose of itself. We use // a[j][k] instead of a[k][j] sum = sum + (a[i,k] * a[j,k]); } if (i == j && sum != 1) return false; if (i != j && sum != 0) return false; } } return true; } // Driver code public static void Main () { int [,]a = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}; if (isOrthogonal(a, 3, 3)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by vt_m <?php// PHP code to check whether// a matrix is orthogonal or not //$MAX = 100; function isOrthogonal($a, $m, $n){if ($m != $n) return false; // Multiply A*A^tfor ( $i = 0; $i < $n; $i++){ for ( $j = 0; $j < $n; $j++) { $sum = 0; for ( $k = 0; $k < $n; $k++) { // Since we are multiplying // with transpose of itself. // We use a[j][k] instead // of a[k][j] $sum = $sum + ($a[$i][$k] * $a[$j][$k]); } if ($i == $j and $sum != 1) return false; if ($i != $j and $sum != 0) return false; }} return true;} // Driver Code$a = array(array(1, 0, 0), array(0, 1, 0), array(0, 0, 1));if (isOrthogonal($a, 3, 3)) echo "Yes";else echo "No"; // This code is contributed by anuj_67.?> <script> // Javascript code to check whether// a matrix is orthogonal or not MAX=100 function isOrthogonal(a, m, n){if (m != n) return false; // Multiply A*A^tfor (var i = 0; i < n; i++){ for (var j = 0; j < n; j++) { var sum = 0; for (var k = 0; k < n; k++) { // Since we are multiplying with // transpose of itself. We use // a[j][k] instead of a[k][j] sum = sum + (a[i][k] * a[j][k]); } if (i == j && sum != 1) return false; if (i != j && sum != 0) return false; }} return true;} // Driver Codevar a = [[1, 0, 0], [0, 1, 0], [0, 0, 1]];if (isOrthogonal(a, 3, 3)) document.write( "Yes");else document.write( "No"); // This code is contributed by noob2000.</script> Yes YouTubeGeeksforGeeks500K subscribersCheck whether a given matrix is orthogonal or not | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:14•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=ui4OQJjViMs" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> KRV vt_m jit_t manishshaw1 noob2000 divyesh072019 adnanirshad158 Mathematical Matrix Mathematical Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Program to convert a given number to words Modular multiplicative inverse Algorithm to solve Rubik's Cube Program to multiply two matrices Count ways to reach the n'th stair Matrix Chain Multiplication | DP-8 Program to find largest element in an array Sudoku | Backtracking-7 Divide and Conquer | Set 5 (Strassen's Matrix Multiplication) Rat in a Maze | Backtracking-2
[ { "code": null, "e": 24638, "s": 24610, "text": "\n18 Aug, 2021" }, { "code": null, "e": 24801, "s": 24638, "text": "We are given a matrix, we need to check whether it is an orthogonal matrix or not. An orthogonal matrix is a square matrix and satisfies the following condition: "...
T-SQL - Sub-Queries
A sub-query or Inner query or Nested query is a query within another SQL Server query and embedded within the WHERE clause. A sub query is used to return data that will be used in the main query as a condition to further restrict the data to be retrieved. Sub queries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along with the operators like =, <, >, >=, <=, IN, BETWEEN, etc. There are a few rules that sub queries must follow − You must enclose a subquery in parenthesis. You must enclose a subquery in parenthesis. A subquery must include a SELECT clause and a FROM clause. A subquery must include a SELECT clause and a FROM clause. A subquery can include optional WHERE, GROUP BY, and HAVING clauses. A subquery can include optional WHERE, GROUP BY, and HAVING clauses. A subquery cannot include COMPUTE or FOR BROWSE clauses. A subquery cannot include COMPUTE or FOR BROWSE clauses. You can include an ORDER BY clause only when a TOP clause is included. You can include an ORDER BY clause only when a TOP clause is included. You can nest sub queries up to 32 levels. You can nest sub queries up to 32 levels. Subqueries are most frequently used with the SELECT statement. Following is the basic syntax. SELECT column_name [, column_name ] FROM table1 [, table2 ] WHERE column_name OPERATOR (SELECT column_name [, column_name ] FROM table1 [, table2 ] [WHERE]) Consider the CUSTOMERS table having the following records. ID NAME AGE ADDRESS SALARY 1 Ramesh 32 Ahmedabad 2000.00 2 Khilan 25 Delhi 1500.00 3 kaushik 23 Kota 2000.00 4 Chaitali 25 Mumbai 6500.00 5 Hardik 27 Bhopal 8500.00 6 Komal 22 MP 4500.00 7 Muffy 24 Indore 10000.00 Let us apply the following subquery with SELECT statement. SELECT * FROM CUSTOMERS WHERE ID IN (SELECT ID FROM CUSTOMERS WHERE SALARY > 4500) The above command will produce the following output. ID NAME AGE ADDRESS SALARY 4 Chaitali 25 Mumbai 6500.00 5 Hardik 27 Bhopal 8500.00 7 Muffy 24 Indore 10000.00 Sub queries also can be used with INSERT statements. The INSERT statement uses the data returned from the subquery to insert into another table. The selected data in the subquery can be modified with any of the character, date, or number functions. Following is the basic syntax. INSERT INTO table_name [ (column1 [, column2 ]) ] SELECT [ *|column1 [, column2 ] FROM table1 [, table2 ] [ WHERE VALUE OPERATOR ] Consider a table CUSTOMERS_BKP with similar structure as CUSTOMERS table. Following is the syntax to copy complete CUSTOMERS table into CUSTOMERS_BKP. INSERT INTO CUSTOMERS_BKP SELECT * FROM CUSTOMERS WHERE ID IN (SELECT ID FROM CUSTOMERS) The subquery can be used in conjunction with the UPDATE statement. Either single or multiple columns in a table can be updated when using a subquery with the UPDATE statement. Following is the basic syntax. UPDATE table SET column_name = new_value [ WHERE OPERATOR [ VALUE ] (SELECT COLUMN_NAME FROM TABLE_NAME) [ WHERE) ] Let us assume we have CUSTOMERS_BKP table available which is backup of CUSTOMERS table. Following command example updates SALARY by 0.25 times in CUSTOMERS table for all the customers whose AGE is greater than or equal to 27. UPDATE CUSTOMERS SET SALARY = SALARY * 0.25 WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP WHERE AGE >= 27 ) This will impact two rows and finally CUSTOMERS table will have the following records. ID NAME AGE ADDRESS SALARY 1 Ramesh 32 Ahmedabad 500.00 2 Khilan 25 Delhi 1500.00 3 kaushik 23 Kota 2000.00 4 Chaitali 25 Mumbai 6500.00 5 Hardik 27 Bhopal 2125.00 6 Komal 22 MP 4500.00 7 Muffy 24 Indore 10000.00 The subquery can be used in conjunction with the DELETE statement like with any other statements mentioned above. Following is the basic syntax. DELETE FROM TABLE_NAME [ WHERE OPERATOR [ VALUE ] (SELECT COLUMN_NAME FROM TABLE_NAME) [ WHERE) ] Let us assume we have CUSTOMERS_BKP table available which is backup of CUSTOMERS table. Following command example deletes records from CUSTOMERS table for all the customers whose AGE is greater than or equal to 27. DELETE FROM CUSTOMERS WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP WHERE AGE >=27 ) This would impact two rows and finally CUSTOMERS table will have the following records. ID NAME AGE ADDRESS SALARY 2 Khilan 25 Delhi 1500.00 3 kaushik 23 Kota 2000.00 4 Chaitali 25 Mumbai 6500.00 6 Komal 22 MP 4500.00 7 Muffy 24 Indore 10000.00 12 Lectures 2 hours Nishant Malik 10 Lectures 1.5 hours Nishant Malik 12 Lectures 2.5 hours Nishant Malik 20 Lectures 2 hours Asif Hussain 10 Lectures 1.5 hours Nishant Malik 48 Lectures 6.5 hours Asif Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2316, "s": 2060, "text": "A sub-query or Inner query or Nested query is a query within another SQL Server query and embedded within the WHERE clause. A sub query is used to return data that will be used in the main query as a condition to further restrict the data to be retrieve...
Functional Programming - Polymorphism
Polymorphism, in terms of programming, means reusing a single code multiple times. More specifically, it is the ability of a program to process objects differently depending on their data type or class. Polymorphism is of two types − Compile-time Polymorphism − This type of polymorphism can be achieved using method overloading. Compile-time Polymorphism − This type of polymorphism can be achieved using method overloading. Run-time Polymorphism − This type of polymorphism can be achieved using method overriding and virtual functions. Run-time Polymorphism − This type of polymorphism can be achieved using method overriding and virtual functions. Polymorphism offers the following advantages − It helps the programmer to reuse the codes, i.e., classes once written, tested and implemented can be reused as required. Saves a lot of time. It helps the programmer to reuse the codes, i.e., classes once written, tested and implemented can be reused as required. Saves a lot of time. Single variable can be used to store multiple data types. Single variable can be used to store multiple data types. Easy to debug the codes. Easy to debug the codes. Polymorphic data-types can be implemented using generic pointers that store a byte address only, without the type of data stored at that memory address. For example, function1(void *p, void *q) where p and q are generic pointers which can hold int, float (or any other) value as an argument. The following program shows how to use polymorphic functions in C++, which is an object oriented programming language. #include <iostream> Using namespace std: class A { public: void show() { cout << "A class method is called/n"; } }; class B:public A { public: void show() { cout << "B class method is called/n"; } }; int main() { A x; // Base class object B y; // Derived class object x.show(); // A class method is called y.show(); // B class method is called return 0; } It will produce the following output − A class method is called B class method is called The following program shows how to use polymorphic functions in Python, which is a functional programming language. class A(object): def show(self): print "A class method is called" class B(A): def show(self): print "B class method is called" def checkmethod(clasmethod): clasmethod.show() AObj = A() BObj = B() checkmethod(AObj) checkmethod(BObj) It will produce the following output − A class method is called B class method is called 32 Lectures 3.5 hours Pavan Lalwani 11 Lectures 1 hours Prof. Paul Cline, Ed.D 72 Lectures 10.5 hours Arun Ammasai 51 Lectures 2 hours Skillbakerystudios 43 Lectures 4 hours Mohammad Nauman 8 Lectures 1 hours Santharam Sivalenka Print Add Notes Bookmark this page
[ { "code": null, "e": 2024, "s": 1821, "text": "Polymorphism, in terms of programming, means reusing a single code multiple times. More specifically, it is the ability of a program to process objects differently depending on their data type or class." }, { "code": null, "e": 2055, "s"...
How to call a JavaScript function from an onClick event?
The onClick event is the most frequently used event type, which occurs when a user clicks the left button of the mouse. You can put your validation, warning etc., against this event type. You can try to run the following code to call a JavaScript function from an onClick event Live Demo <html> <head> <script> <!-- function display() { alert("Hello World") } //--> </script> </head> <body> <p>Click the following button and see result</p> <form> <input type="button" onclick="display()" value="Click me" /> </form> </body> </html>
[ { "code": null, "e": 1250, "s": 1062, "text": "The onClick event is the most frequently used event type, which occurs when a user clicks the left button of the mouse. You can put your validation, warning etc., against this event type." }, { "code": null, "e": 1340, "s": 1250, "te...
Count unset bits of a number in C++
We are given an integer number let’s say, num and the task is to firstly calculate the binary digit of a number and then calculate the total unset bits of a number. Unset bits in a binary number is represented by 0. Whenever we calculate the binary number of an integer value then it is formed as the combination of 0’s and 1’s. So, the digit 0 is known as unset bit in the terms of the computer. Input − int number = 50 Output − Count of total unset bits in a number are − 3 Explanation − Binary representation of a number 50 is 110010 and if we calculate it in 8-digit number then two 0’s will be appended in the beginning. So, the total unset bits in a number are 3. Input − int number = 10 Output − Count of total unset bits in a number are: 6 Explanation − Binary representation of a number 10 is 00001010 and if we calculate it in 8-digit number then four 0’s will be appended in the beginning. So, the total unset bits in a number are 6. Input the number in a variable of integer type Input the number in a variable of integer type Declare a variable count to store the total count of set bits of type unsigned int Declare a variable count to store the total count of set bits of type unsigned int Start loop FOR from i to 1<<7 and i > 0 and i to i / 2 Start loop FOR from i to 1<<7 and i > 0 and i to i / 2 Inside the loop, check num & 1 == TRUE then print 1 else print 0 Inside the loop, check num & 1 == TRUE then print 1 else print 0 Inside the loop, increment the value of total digits in a number. Inside the loop, increment the value of total digits in a number. Start loop while to calculate the total count of bits till number isn’t 0 Start loop while to calculate the total count of bits till number isn’t 0 Inside the loop, set count = count + number & 1 and also set number >>=1 Inside the loop, set count = count + number & 1 and also set number >>=1 Set count as total digits in a number - total set bits in a number. Set count as total digits in a number - total set bits in a number. Print the count Print the count Live Demo #include<iostream> using namespace std; //Count total unset bits in a number unsigned int unset_bits(unsigned int number){ unsigned int total_digits = 0; unsigned int count = 0; unsigned i; //display the total 8-bit number cout<<"8-bit digits of "<<number<<" is: "; for (i = 1 << 7; i > 0; i = i / 2){ (number & i)? cout<<"1": cout<<"0"; total_digits++; } //calculate the total unset bits in a number while (number){ count += number & 1; number >>= 1; } count = total_digits - count; cout<<"\nCount of total unset bits in a number are: "<<count; } int main(){ int number = 50; unset_bits(number); return 0; } If we run the above code it will generate the following output − 8-bit digits of 50 is: 00110010 Count of total set bits in a number are: 5
[ { "code": null, "e": 1227, "s": 1062, "text": "We are given an integer number let’s say, num and the task is to firstly calculate the binary digit of a number and then calculate the total unset bits of a number." }, { "code": null, "e": 1459, "s": 1227, "text": "Unset bits in a b...
What is if/then directives for debug vs release in C#?
In Visual Studio Debug mode and Release mode are different configurations for building your .Net project. Select the Debug mode for debugging step by step their .Net project and select the Release mode for the final build of Assembly file (.dll or .exe). To change the build configuration − From the Build menu, select Configuration Manager, then select Debug or Release. Or On the toolbar, choose either Debug or Release from the Solution Configurations list. The code which is written inside the #if debug will be executed only if the code is running inside the debug mode. If the code is running in the release mode, then the #if Debug will be false and it will not execute the code present inside this. class Program{ static void Main(string[] args){ #if DEBUG Console.WriteLine("Mode=Debug"); #else Console.WriteLine("Mode=Release"); #endif Console.ReadLine(); } } if in Debug Mode Mode=Debug if in Release Mode Mode=Release
[ { "code": null, "e": 1168, "s": 1062, "text": "In Visual Studio Debug mode and Release mode are different configurations for\nbuilding your .Net project." }, { "code": null, "e": 1317, "s": 1168, "text": "Select the Debug mode for debugging step by step their .Net project and sel...
How to get form data using JavaScript/jQuery? - GeeksforGeeks
03 Aug, 2021 The serializeArray() method creates an array of objects (name and value) by serializing form values. This method can be used to get the form data. Syntax: $(selector).serializeArray() Parameter: It does not accept any parameter. Return Value: It returns all the value that is inside the inputs fields. Example: <!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> <script> $(document).ready(function() { $("button").click(function() { var x = $("form").serializeArray(); $.each(x, function(i, field) { $("#output").append(field.name + ":" + field.value + " "); }); }); }); </script> <style> #GFG { width: 300px; padding: 50px; height: 150px; border: 2px solid green; } </style></head> <body> <div id="GFG"> <form action="#"> Name: <input type="text" style="margin: 10px;" name="Name"> <br> </form> <button>Submit</button> </div> <div id="output"></div></body> </html> Output: Before clicking the button: After clicking the button: 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. Comments Old Comments Form validation using jQuery How to Dynamically Add/Remove Table Rows using jQuery ? Scroll to the top of the page using JavaScript/jQuery How to get the ID of the clicked button using JavaScript / jQuery ? jQuery | children() with Examples Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24443, "s": 24415, "text": "\n03 Aug, 2021" }, { "code": null, "e": 24590, "s": 24443, "text": "The serializeArray() method creates an array of objects (name and value) by serializing form values. This method can be used to get the form data." }, { "c...
How to get specific columns in SQLAlchemy with filter? - GeeksforGeeks
04 Jan, 2022 In this article, we will see how to query and select specific columns using SQLAlchemy in Python. For our examples, we have already created a Students table which we will be using: Students Table To select specific column in SQLAlchemy Syntax: sqlalchemy.select(*entities) entities: Entities to SELECT from. This is typically a series of ColumnElement for Core usage and ORM-mapped classes for ORM usage. To filter records in SQLAlchemy Syntax: sqlalchemy.query.filter(*criterion) criterion: Criterion is one or more criteria for selecting the records. Python import sqlalchemy as dbfrom sqlalchemy.orm import sessionmakerfrom sqlalchemy.ext.declarative import declarative_base Base = declarative_base() # DEFINE THE ENGINE (CONNECTION OBJECT)engine = db.create_engine("mysql+pymysql://\root:password@localhost/Geeks4Geeks") # CREATE THE TABLE MODEL TO USE IT FOR QUERYINGclass Students(Base): __tablename__ = 'students' first_name = db.Column(db.String(50), primary_key=True) last_name = db.Column(db.String(50), primary_key=True) course = db.Column(db.String(50)) score = db.Column(db.Float) # CREATE THE SESSION OBJECTSession = sessionmaker(bind=engine)session = Session() # SELECTING COLUMN `first_name`, `last_name` WHERE `score > 80`result = session.query(Students) \ .with_entities(Students.first_name, Students.last_name) \ .filter(Students.score > 80).all() for r in result: print(r.first_name, r.last_name) Output: Output – Example 1 Python3 import sqlalchemy as dbfrom sqlalchemy.orm import sessionmakerfrom sqlalchemy.ext.declarative import declarative_base Base = declarative_base() # DEFINE THE ENGINE (CONNECTION OBJECT)engine = db.create_engine("mysql+pymysql://\root:password@localhost/Geeks4Geeks") # CREATE THE TABLE MODEL TO USE IT FOR QUERYINGclass Students(Base): __tablename__ = 'students' first_name = db.Column(db.String(50), primary_key=True) last_name = db.Column(db.String(50), primary_key=True) course = db.Column(db.String(50)) score = db.Column(db.Float) # CREATE THE SESSION OBJECTSession = sessionmaker(bind=engine)session = Session() # SELECTING COLUMN `first_name`, `score`# WHERE `score > 80` AND `course` is STATISTICSresult = session.query(Students) \ .with_entities(Students.first_name, Students.score) \ .filter(Students.score > 80, Students.course.like('Statistics')).all() for r in result: print(r.first_name, r.score) Output: Output – Example 2 Picked Python-SQLAlchemy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe Python OOPs Concepts Python | Get unique values from a list Check if element exists in list in Python Python Classes and Objects Python | os.path.join() method How To Convert Python Dictionary To JSON? Python | Pandas dataframe.groupby() Create a directory in Python
[ { "code": null, "e": 24212, "s": 24184, "text": "\n04 Jan, 2022" }, { "code": null, "e": 24310, "s": 24212, "text": "In this article, we will see how to query and select specific columns using SQLAlchemy in Python." }, { "code": null, "e": 24393, "s": 24310, "...
crypto.randomBytes() Method in Node.js
The crypto.randomBytes() generates cyprtographically strong pseudo-random data. This method will not be completed until there is sufficient entropy in the bytes created. But even after this it does not takes more than a few milliseconds. This method basically creates a few random bytes which are further used. crypto.randomBytes(size, [callback]) The above parameters are described as below − size – This argument defines the number of bytes to be generated. Size must not be greater than 2**31 – 1. size – This argument defines the number of bytes to be generated. Size must not be greater than 2**31 – 1. callback – The callback is called if any error occurs in the method. callback – The callback is called if any error occurs in the method. Create a file with name – randomBytes.js and copy the below code snippet. After creating file, use the following command to run this code as shown in the example below − node randomBytes.js randomBytes.js Live Demo // crypto.randomBytes() Asynchronous demo example // Importing the crypto module const crypto = require('crypto'); crypto.randomBytes(64, (err, buf) => { if (err) throw err; console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`); }); C:\home\node>> node randomBytes.js 64 bytes of random data: eb2bcebb999407286caea729998e7fa0c089178f8ca43857e73ea3ff66dbe1852af24a4b0199be 9192798a3f8ad6d6475db3621cfacf38dcb0fba5d77d73aaf5 Let's take a look at one more example. Live Demo // crypto.randomBytes() Synchronous demo example // Importing the crypto module const crypto = require('crypto'); const buffer = crypto.randomBytes(256); console.log( `${buffer.length} bytes of random data: ${buffer.toString('base64')}`); C:\home\node>> node randomBytes.js 256 bytes of random data: n7yfRMo/ujHfBWSF2VFdevG4WRbBoG9Fqwu51+/9ZBUV6Qo88YG7IbcEaIer+g+OgjMv4RyNQ6/67a F5xWmkOR3oA6J6bdAJ1pbstTuhIfItF1PQfP26YXk1QlaoKy/YJxPUngyK4kNG9O04aret4D+2qIq9 BUaQcv+R9Xi014VKNUDZ+YQKEaLHBhJMq6JgehJ56iNbdNJ4+PN7SQwjNdZ8gS76izAwYsSZ7Kuyx2 VzdXIKsLmjleuJ2DZ7/6Yyn8WM9463dhuh0KQ5nwFbgzucvjmdvDjBlGFZBGlKs6AXqYh+0Oe6Ckkv 3OpnXOJs+GExbmnvjaeDQ03khpdJfA==
[ { "code": null, "e": 1373, "s": 1062, "text": "The crypto.randomBytes() generates cyprtographically strong pseudo-random data. This method will not be completed until there is sufficient entropy in the bytes created. But even after this it does not takes more than a few milliseconds. This method bas...
What is a JavaScript call() Method?
JavaScript call() method is used to call a function with another object as the first argument. You can try to run the following code to learn how to implement call() method in JavaScript − <html> <head> <script> var person = { Name:"John", Department: "Finance", fullName: function() { return this.Name + " is from " + this.Department + " Department"; } } var myObject = { Name: "Amit", Department: "Marketing", } x = person.fullName.call(myObject); document.write(x); </script> </head> <body> </body> </html>
[ { "code": null, "e": 1157, "s": 1062, "text": "JavaScript call() method is used to call a function with another object as the first argument." }, { "code": null, "e": 1251, "s": 1157, "text": "You can try to run the following code to learn how to implement call() method in JavaSc...
Addition of tuples in Python
When it is required to add the tuples, the 'amp' and lambda functions can be used. The map function applies a given function/operation to every item in an iterable (such as list, tuple). It returns a list as the result. Anonymous function is a function which is defined without a name. In general, functions in Python are defined using 'def' keyword, but anonymous function is defined with the help of 'lambda' keyword. It takes a single expression, but can take any number of arguments. It uses the expression and returns the result of it. Below is a demonstration of the same − Live Demo my_tuple_1 = (11, 14, 54, 56, 87) my_tuple_2 = (98, 0, 10, 13, 76) print("The first tuple is : ") print(my_tuple_1) print("The second tuple is : ") print(my_tuple_2) my_result = tuple(map(lambda i, j: i + j, my_tuple_1, my_tuple_2)) print("The tuple after addition is: ") print(my_result) The first tuple is : (11, 14, 54, 56, 87) The second tuple is : (98, 0, 10, 13, 76) The tuple after addition is: (109, 14, 64, 69, 163) Two tuples are defined, and are displayed on the console. The lambda function is applied on every element of both the tuples, and the 'map' method is used to map the process of addition. It is then converted to a tuple. This is assigned to a value. It is displayed on the console.
[ { "code": null, "e": 1145, "s": 1062, "text": "When it is required to add the tuples, the 'amp' and lambda functions can be used." }, { "code": null, "e": 1282, "s": 1145, "text": "The map function applies a given function/operation to every item in an iterable (such as list, tup...
Array - GeeksforGeeks
06 May, 2017 A program P reads in 500 integers in the range [0..100] representing the scores of 500 students. It then prints the frequency of each score above 50. What would be the best way for P to store the frequencies? (GATE CS 2005) An array of 50 numbers An array of 100 numbers An array of 500 numbers A dynamically allocated array of 550 numbers See question 1 of http://www.geeksforgeeks.org/data-structures-and-algorithms-set-22/ The First occurence of an element can be found out in O(log(n)) time using divide and conquer technique,lets say it is i.The Last occurrence of an element can be found out in O(log(n)) time using divide and conquer technique,lets say it is j.Now number of occuerence of that element(count) is (j-i+1). Overall time complexity = log n +log n +1 = O(logn) The First occurence of an element can be found out in O(log(n)) time using divide and conquer technique,lets say it is i. The Last occurrence of an element can be found out in O(log(n)) time using divide and conquer technique,lets say it is j. Now number of occuerence of that element(count) is (j-i+1). Overall time complexity = log n +log n +1 = O(logn) For unsorted array, we can always insert an element at end and do insert in O(1) timeFor Min Heap, insertion takes O(Log n) time. Refer Binary Heap operations for details.For sorted array, insert takes O(n) time as we may have to move all elements worst case.For sorted doubly linked list, insert takes O(n) time to find position of element to be inserted. For unsorted array, we can always insert an element at end and do insert in O(1) time For Min Heap, insertion takes O(Log n) time. Refer Binary Heap operations for details. For sorted array, insert takes O(n) time as we may have to move all elements worst case. For sorted doubly linked list, insert takes O(n) time to find position of element to be inserted. Option A is correct. Int is the data type used,geeks is the name of the array and [20] is the size of the array. Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between sh and bash What is "network ID" and "host ID" in IP Addresses? Primer CSS Flexbox Flex Direction Converting an image to a Torch Tensor in Python Prime CSS Marketing Buttons Animated Arrow Symbol How to Calculate Cosine Similarity in Python? Python Program for Breadth First Search or BFS for a Graph 10 Best C and C++ Books For Beginners & Advanced Programmers Show all columns of Pandas DataFrame in Jupyter Notebook How to split a Dataset into Train and Test Sets using Python
[ { "code": null, "e": 41092, "s": 41064, "text": "\n06 May, 2017" }, { "code": null, "e": 41317, "s": 41092, "text": "A program P reads in 500 integers in the range [0..100] representing the scores of 500 students. It then prints the frequency of each score above 50. What would be...
Understanding ReLU: The Most Popular Activation Function in 5 Minutes! | by Bharath K | Towards Data Science
Activation functions in neural networks and deep learning play a significant role in the ignition of the hidden nodes to produce a more desirable output. The main purpose of the activation function is to introduce the property of non-linearity into the model. In artificial neural networks, the activation function of a node defines the output of that node given an input or set of inputs. A standard integrated circuit can be seen as a digital network of activation functions that can be “ON” or “OFF,” depending on the input. Sigmoid and tanh were monotonous, differentiable, and previously more popular activation functions. However, these functions suffer saturation over time, and this leads to problems occurring with vanishing gradients. An alternative and the most popular activation function to overcome this issue is the Rectified Linear Unit (ReLU). The above diagram with the blue line is the representation of the Rectified Linear Unit (ReLU) whereas, the green line is a variant of ReLU called Softplus. The other variants of ReLU include Leaky ReLU, ELU, SiLU, etc., which are used for better performance in some tasks. In this article, we will only consider the Rectified Linear Unit (ReLU) because it is still the most used activation function by default for performing a majority of the deep learning tasks. Its variants are usually used for specific purposes where they might have a slight edge over the ReLU. This activation function was first introduced to a dynamical network by Hahnloser et al. in 2000 with strong biological motivations and mathematical justifications. It was demonstrated for the first time in 2011 to enable better training of deeper networks, compared to the widely used activation functions prior to 2011, e.g., the logistic sigmoid (which is inspired by probability theory and logistic regression) and its more practical counterpart, the hyperbolic tangent. The rectifier is, as of 2017, the most popular activation function for deep neural networks. A unit employing the rectifier is also called a rectified linear unit (ReLU). The main reason ReLU, despite being one of the best activation functions was not frequently used before recently. The reason for this was because it was not differentiable at the point 0. Researchers tended to use differentiable functions like sigmoid and tanh. However, it is now found that ReLU is the best activation function for deep learning. The ReLU activation function is differentiable at all points except at 0. For values greater than 0, we just consider the max of the function. This can be written as: f(x) = max{0, z} In simple terms, this can also be written as follows: if input > 0: return inputelse: return 0 All the negative values default to 0, and the maximum for the positive number is taken into consideration. For the computation of the backpropagation of neural networks, the differentiation for the ReLU is relatively easy. The only assumption we will make is the derivative at the point 0, which will also be considered as 0. This is usually not such a big concern, and it works well for the most part. The derivative of the function is the value of the slope. The slope for negative values is 0.0, and the slope for positive values is 1.0. The main advantages of the ReLU activation function are: 1. Convolutional layers and deep learning: They are the most popular activation functions for training convolutional layers and deep learning models. 2. Computational Simplicity: The rectifier function is trivial to implement, requiring only a max() function. 3. Representational Sparsity: An important benefit of the rectifier function is that it is capable of outputting a true zero value. 4. Linear Behavior: A neural network is easier to optimize when its behavior is linear or close to linear. However, The main issue with the Rectified Linear Unit is that all the negative values become zero immediately, which decreases the ability of the model to fit or train from the data properly. That means any negative input given to the ReLU activation function turns the value into zero immediately in the graph, which in turn affects the resulting graph by not mapping the negative values appropriately. This can however be easily fixed by using the different variants of the ReLU activation function like the Leaky ReLU and other functions discussed previously. This was a short introduction to understanding the Rectified Linear Unit and its importance in deep learning technology as of today. It is way more popular than all the other activation functions, and for good reason as explained in this article. I would highly recommend checking out the references to learn more about this concept. Feel free to check out some of my other articles from the links provided below. Thank you all for sticking on till the end, and have a wonderful day!
[ { "code": null, "e": 431, "s": 171, "text": "Activation functions in neural networks and deep learning play a significant role in the ignition of the hidden nodes to produce a more desirable output. The main purpose of the activation function is to introduce the property of non-linearity into the mo...
How to change Button Border in Java Swing
For Button border, use createLineBorder() method in Java, which allows you to set the color of the Border as well: JButton button = new JButton("Demo Button!"); Border border = BorderFactory.createLineBorder(Color.BLUE); The following is an example to change button border in Java: import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.border.Border; public class SwingDemo { public static void main(String args[]) { JFrame frame = new JFrame("Button Border"); Container container = frame.getContentPane(); JButton button = new JButton("Demo Button!"); Border border = BorderFactory.createLineBorder(Color.BLUE); button.setBorder(border); container.add(button, BorderLayout.CENTER); frame.setSize(550, 300); frame.setVisible(true); } }
[ { "code": null, "e": 1177, "s": 1062, "text": "For Button border, use createLineBorder() method in Java, which allows you to set the color of the Border as well:" }, { "code": null, "e": 1283, "s": 1177, "text": "JButton button = new JButton(\"Demo Button!\");\nBorder border = Bo...
Computer Programming - Loops
Let's consider a situation when you want to print Hello, World! five times. Here is a simple C program to do the same − #include <stdio.h> int main() { printf( "Hello, World!\n"); printf( "Hello, World!\n"); printf( "Hello, World!\n"); printf( "Hello, World!\n"); printf( "Hello, World!\n"); } When the above program is executed, it produces the following result − Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! It was simple, but again, let's consider another situation when you want to write Hello, World! a thousand times. We can certainly not write printf() statements a thousand times. Almost all the programming languages provide a concept called loop, which helps in executing one or more statements up to a desired number of times. All high-level programming languages provide various forms of loops, which can be used to execute one or more statements repeatedly. Let's write the above C program with the help of a while loop and later, we will discuss how this loop works #include <stdio.h> int main() { int i = 0; while ( i < 5 ) { printf( "Hello, World!\n"); i = i + 1; } } When the above program is executed, it produces the following result − Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! The above program makes use of a while loop, which is being used to execute a set of programming statements enclosed within {....}. Here, the computer first checks whether the given condition, i.e., variable "a" is less than 5 or not and if it finds the condition is true, then the loop body is entered to execute the given statements. Here, we have the following two statements in the loop body − First statement is printf() function, which prints Hello World! First statement is printf() function, which prints Hello World! Second statement is i = i + 1, which is used to increase the value of variable i Second statement is i = i + 1, which is used to increase the value of variable i After executing all the statements given in the loop body, the computer goes back to while( i < 5) and the given condition, (i < 5), is checked again, and the loop is executed again if the condition holds true. This process repeats till the given condition remains true which means variable "a" has a value less than 5. To conclude, a loop statement allows us to execute a statement or group of statements multiple times. Given below is the general form of a loop statement in most of the programming languages − This tutorial has been designed to present programming's basic concepts to non-programmers, so let's discuss the two most important loops available in C programming language. Once you are clear about these two loops, then you can pick-up C programming tutorial or a reference book and check other loops available in C and the way they work. A while loop available in C Programming language has the following syntax − while ( condition ) { /*....while loop body ....*/ } The above code can be represented in the form of a flow diagram as shown below − The following important points are to be noted about a while loop − A while loop starts with a keyword while followed by a condition enclosed in ( ). A while loop starts with a keyword while followed by a condition enclosed in ( ). Further to the while() statement, you will have the body of the loop enclosed in curly braces {...}. Further to the while() statement, you will have the body of the loop enclosed in curly braces {...}. A while loop body can have one or more lines of source code to be executed repeatedly. A while loop body can have one or more lines of source code to be executed repeatedly. If the body of a while loop has just one line, then its optional to use curly braces {...}. If the body of a while loop has just one line, then its optional to use curly braces {...}. A while loop keeps executing its body till a given condition holds true. As soon as the condition becomes false, the while loop comes out and continues executing from the immediate next statement after the while loop body. A while loop keeps executing its body till a given condition holds true. As soon as the condition becomes false, the while loop comes out and continues executing from the immediate next statement after the while loop body. A condition is usually a relational statement, which is evaluated to either true or false. A value equal to zero is treated as false and any non-zero value works like true. A condition is usually a relational statement, which is evaluated to either true or false. A value equal to zero is treated as false and any non-zero value works like true. A while loop checks a given condition before it executes any statements given in the body part. C programming provides another form of loop, called do...while that allows to execute a loop body before checking a given condition. It has the following syntax − do { /*....do...while loop body ....*/ } while ( condition ); The above code can be represented in the form of a flow diagram as shown below − If you will write the above example using do...while loop, then Hello, World will produce the same result − #include <stdio.h> int main() { int i = 0; do { printf( "Hello, World!\n"); i = i + 1; } while ( i < 5 ); } When the above program is executed, it produces the following result − Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! When the break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop. The syntax for a break statement in C is as follows − break; A break statement can be represented in the form of a flow diagram as shown below − Following is a variant of the above program, but it will come out after printing Hello World! only three times − #include <stdio.h> int main() { int i = 0; do { printf( "Hello, World!\n"); i = i + 1; if( i == 3 ) { break; } } while ( i < 5 ); } When the above program is executed, it produces the following result − Hello, World! Hello, World! Hello, World! The continue statement in C programming language works somewhat like the break statement. Instead of forcing termination, continue forces the next iteration of the loop to take place, skipping any code in between. The syntax for a continue statement in C is as follows − continue; A continue statement can be represented in the form of a flow diagram as shown below − Following is a variant of the above program, but it will skip printing when the variable has a value equal to 3 − #include <stdio.h> int main() { int i = 0; do { if( i == 3 ) { i = i + 1; continue; } printf( "Hello, World!\n"); i = i + 1; } while ( i < 5 ); } When the above program is executed, it produces the following result − Hello, World! Hello, World! Hello, World! Hello, World! Following is the equivalent program written in Java that too supports while and do...while loops. The following program prints Hello, World! five times as we did in the case of C Programming − You can try to execute the following program to see the output, which must be identical to the result generated by the above example. public class DemoJava { public static void main(String []args) { int i = 0; while ( i < 5 ) { System.out.println("Hello, World!"); i = i + 1; } } } The break and continue statements in Java programming work quite the same way as they work in C programming. Following is the equivalent program written in Python. Python too supports while and do...while loops. The following program prints Hello, World! five times as we did in case of C Programming. Here you must note that Python does not make use of curly braces for the loop body, instead it simply identifies the body of the loop using indentation of the statements. You can try to execute the following program to see the output. To show the difference, we have used one more print statement, which will be executed when the loop will be over. i = 0 while (i < 5): print "Hello, World!" i = i + 1 print "Loop ends" When the above program is executed, it produces the following result − Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Loop ends The break and continue statements in Python work quite the same way as they do in C programming. 107 Lectures 13.5 hours Arnab Chakraborty 106 Lectures 8 hours Arnab Chakraborty 99 Lectures 6 hours Arnab Chakraborty 46 Lectures 2.5 hours Shweta 70 Lectures 9 hours Abhilash Nelson 52 Lectures 7 hours Abhishek And Pukhraj Print Add Notes Bookmark this page
[ { "code": null, "e": 2260, "s": 2140, "text": "Let's consider a situation when you want to print Hello, World! five times. Here is a simple C program to do the same −" }, { "code": null, "e": 2450, "s": 2260, "text": "#include <stdio.h>\n\nint main() {\n printf( \"Hello, World!...
Are you still not using Version Control for Data? | by Roman Orac | Towards Data Science
Recently, in a company meeting, one of my colleagues asked: Do we use some kind of version control for data? I gave him an astonished look. Do you mean version control for code? No for data, my colleague insisted. I never heard or thought about version control for data, but it got me thinking so I did a bit of research on this topic. At the end of the post, I also share my opinion. Here are a few links that might interest you: - Labeling and Data Engineering for Conversational AI and Analytics- Data Science for Business Leaders [Course]- Intro to Machine Learning with PyTorch [Course]- Become a Growth Product Manager [Course]- Deep Learning (Adaptive Computation and ML series) [Ebook]- Free skill tests for Data Scientists & Machine Learning Engineers Some of the links above are affiliate links and if you go through them to make a purchase I’ll earn a commission. Keep in mind that I link courses because of their quality and not because of the commission I receive from your purchases. Is there a product that offers version control for data? Is there a need for it? Let’s find out. Any game-changing product idea that I type into Google, there are already ten mature products on the market for it — what a time to be alive. There was no difference in googling for Version Control for Data. The product that caught my eye is dolt. Dolt is the true Git for data experience in a SQL database, providing version control for schema and cell-wise for data, all optimized for collaboration. With Dolt, you can view a human-readable diff of the data you received last time versus the data you received this time. You can easily see updates you did not expect and fix the problem before you deploy the new data. Authors say that it is like Git but for data. It is an open-source SQL database with Git-style versioning. When working on Data Science projects, we version datasets by ourselves. Many times we don’t remember what is the difference between v5 and v6. Dolt stores commit logs when we commit the code to the repository so it is easier to go back and see the changes. Like Github is to Git, DoltHub is to Dolt. DoltHub is only free for datasets that are public on DoltHub. The price is 50$ per month, to host private repositories. This is the million-dollar question, that I’ve been asking myself. The authors claim that the guiding use case was sharing data on the Internet. Dolt allows you to share the database instead, including schema and views, allowing you to delete all the code used to transfer data. DoltHub allows you to “try before you buy” data. You can run SQL queries on the web to see if the data matches your needs. The data provider can even build sample queries to guide the consumer’s exploration. Via the commit log, you can see how often the data is updated. You can see who changed the data and why. DoltHub is free for public datasets. You can sign in with Google’s Account. I created a new public repository called iris (data scientists know the dataset I am talking about). Then you can clone the repository like wit Git — It all feels so familiar. But, before you can clone the repo, you need to install dolt CLI. Developers thought about this, so they put the install command right next to clone. sudo curl -L https://github.com/liquidat After you install dolt, you need to login in with the CLI tool to associate the key with your account. This will open the page in a web browser. dolt login Now, you can clone the repository. dolt clone romanorac/iris Let’s put some data in it. I took the iris dataset from sklearn, converted it into pandas DataFrame and saved it to CSV. import numpy as npimport pandas as pdfrom sklearn import datasetsiris = datasets.load_iris()df = pd.DataFrame(data=np.c_[iris['data'], iris['target']], columns=iris['feature_names'] + ['target'])df.target = df.target.astype(int)df = df.reset_index()df = df.rename( columns={ 'index': 'identifier', 'sepal length (cm)': 'sepal_length', 'sepal width (cm)': 'sepal_width', 'petal length (cm)': 'petal_length', 'petal width (cm)': 'petal_width' })df.to_csv('~/Downloads/iris/iris.csv', index=False) To put the CSV file into Dolt, you need to create SQL table. dolt sql -q "create table iris ( identifier int, sepal_length float, sepal_width float,petal_length float ,petal_width float, target int, primary key (identifier) )" Then you simply import the table. dolt table import -u -pk=identifier iris iris.csv After the table is imported, you need to add the files, write a commit message and push it to the repository — like with Git. git add .dolt commit -m "Initial commit"dolt remote add origin romanorac/irisdolt push origin master Let’s check how the data looks in DoltHub. We see the familiar iris dataset. Now, let’s change an iris sample to see the diff in action. dolt sql --query 'UPDATE iris SET target=0 where identifier = 100'git add .dolt commit -m "Change sample 100"dolt push origin master As a Data Scientist, I know that managing multiple versions of datasets can be messy. Especially for models that are already in production and multiple Data Scientists are working on it. Here I see a potential for Dolt. The diff functionality looks useful with smaller datasets, but I am not sure how it could be helpful with bigger datasets, where each row changes. I would also have to stress test Dolt with a bigger dataset (a few gigs of data). Does it get slower over time? I think the real-world use case for Dolt and DoltHub is sharing data. Companies that sell the data can log each change, so customers have a transparent way of observing changes. DoltHub also showed its usability during the coronavirus epidemic, as you can manage feeds of a different quality that have the same schema using branches. Follow me on Twitter, where I regularly tweet about Data Science and Machine Learning.
[ { "code": null, "e": 557, "s": 172, "text": "Recently, in a company meeting, one of my colleagues asked: Do we use some kind of version control for data? I gave him an astonished look. Do you mean version control for code? No for data, my colleague insisted. I never heard or thought about version co...
How to check the version of ReactJS ? - GeeksforGeeks
30 Sep, 2021 React is a Javascript front-end library that is used to build single-page applications (SPA). If we want to know which react version we are using to build a project then there are some easy ways to find it. In this article, we are going to discuss three ways to find out the React version. Using package.json fileUsing command lineUsing version property of default import from React Using package.json file Using command line Using version property of default import from React Using package.json file The package.json contains metadata about our project. It is created by default when we create our React project. We can create a react app using the command mentioned below. npx create-react-app name_of_the_app The package.json file contains a lot of information in the name/value pairs in JSON format. We can easily check our React version under the list of dependencies as shown in the image given below. Using command line We can easily check the React version by using the command mentioned below on our command line. npm view react version The output demonstrating the use of the above command on the command line is mentioned below. Using version property of default import from React The default import from React library is an object that has version property on it. We can use this property inside our JSX elements in our desired manner. Syntax: The syntax to use the version property is mentioned below. import React from 'react'; let a = React.version To follow along with the article create a react project using the command that was discussed above in the article. Filename: App.js The content of the App.js file is mentioned in the code given below in which we have demonstrated the use of version property on React object. Javascript import React from 'react'; const App = () => { return <h1> We are currently using react version {React.version} </h1>;} export default App; Step to run the application: Use the following command on the command line to start the application. npm start Output: Open the browser and go to http://localhost:3000, you will see the following output. Picked React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments React-Router Hooks How to set background images in ReactJS ? How to create a table in ReactJS ? How to navigate on path by button click in react router ? ReactJS useNavigate() Hook Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? Convert a string to an integer in JavaScript
[ { "code": null, "e": 24812, "s": 24784, "text": "\n30 Sep, 2021" }, { "code": null, "e": 25019, "s": 24812, "text": "React is a Javascript front-end library that is used to build single-page applications (SPA). If we want to know which react version we are using to build a projec...
Laravel - Quick Guide
Laravel is an open-source PHP framework, which is robust and easy to understand. It follows a model-view-controller design pattern. Laravel reuses the existing components of different frameworks which helps in creating a web application. The web application thus designed is more structured and pragmatic. Laravel offers a rich set of functionalities which incorporates the basic features of PHP frameworks like CodeIgniter, Yii and other programming languages like Ruby on Rails. Laravel has a very rich set of features which will boost the speed of web development. If you are familiar with Core PHP and Advanced PHP, Laravel will make your task easier. It saves a lot time if you are planning to develop a website from scratch. Moreover, a website built in Laravel is secure and prevents several web attacks. Laravel offers you the following advantages, when you are designing a web application based on it − The web application becomes more scalable, owing to the Laravel framework. The web application becomes more scalable, owing to the Laravel framework. Considerable time is saved in designing the web application, since Laravel reuses the components from other framework in developing web application. Considerable time is saved in designing the web application, since Laravel reuses the components from other framework in developing web application. It includes namespaces and interfaces, thus helps to organize and manage resources. It includes namespaces and interfaces, thus helps to organize and manage resources. Composer is a tool which includes all the dependencies and libraries. It allows a user to create a project with respect to the mentioned framework (for example, those used in Laravel installation). Third party libraries can be installed easily with help of composer. All the dependencies are noted in composer.json file which is placed in the source folder. Command line interface used in Laravel is called Artisan. It includes a set of commands which assists in building a web application. These commands are incorporated from Symphony framework, resulting in add-on features in Laravel 5.1 (latest version of Laravel). Laravel offers the following key features which makes it an ideal choice for designing web applications − Laravel provides 20 built in libraries and modules which helps in enhancement of the application. Every module is integrated with Composer dependency manager which eases updates. Laravel includes features and helpers which helps in testing through various test cases. This feature helps in maintaining the code as per the requirements. Laravel provides a flexible approach to the user to define routes in the web application. Routing helps to scale the application in a better way and increases its performance. A web application designed in Laravel will be running on different environments, which means that there will be a constant change in its configuration. Laravel provides a consistent approach to handle the configuration in an efficient way. Laravel incorporates a query builder which helps in querying databases using various simple chain methods. It provides ORM (Object Relational Mapper) and ActiveRecord implementation called Eloquent. Schema Builder maintains the database definitions and schema in PHP code. It also maintains a track of changes with respect to database migrations. Laravel uses the Blade Template engine, a lightweight template language used to design hierarchical blocks and layouts with predefined blocks that include dynamic content. Laravel includes a mail class which helps in sending mail with rich content and attachments from the web application. User authentication is a common feature in web applications. Laravel eases designing authentication as it includes features such as register, forgot password and send password reminders. Laravel uses Redis to connect to an existing session and general-purpose cache. Redis interacts with session directly. Laravel includes queue services like emailing large number of users or a specified Cron job. These queues help in completing tasks in an easier manner without waiting for the previous task to be completed. Laravel 5.1 includes Command Bus which helps in executing commands and dispatch events in a simple way. The commands in Laravel act as per the application’s lifecycle. For managing dependencies, Laravel uses composer. Make sure you have a Composer installed on your system before you install Laravel. In this chapter, you will see the installation process of Laravel. You will have to follow the steps given below for installing Laravel onto your system − Step 1 − Visit the following URL and download composer to install it on your system. https://getcomposer.org/download/ Step 2 − After the Composer is installed, check the installation by typing the Composer command in the command prompt as shown in the following screenshot. Step 3 − Create a new directory anywhere in your system for your new Laravel project. After that, move to path where you have created the new directory and type the following command there to install Laravel. composer create-project laravel/laravel –-prefer-dist Now, we will focus on installation of version 5.7. In Laravel version 5.7, you can install the complete framework by typing the following command − composer create-project laravel/laravel test dev-develop The output of the command is as shown below − The Laravel framework can be directly installed with develop branch which includes the latest framework. Step 4 − The above command will install Laravel in the current directory. Start the Laravel service by executing the following command. php artisan serve Step 5 − After executing the above command, you will see a screen as shown below − Step 6 − Copy the URL underlined in gray in the above screenshot and open that URL in the browser. If you see the following screen, it implies Laravel has been installed successfully. The application structure in Laravel is basically the structure of folders, sub-folders and files included in a project. Once we create a project in Laravel, we get an overview of the application structure as shown in the image here. The snapshot shown here refers to the root folder of Laravel namely laravel-project. It includes various sub-folders and files. The analysis of folders and files, along with their functional aspects is given below − It is the application folder and includes the entire source code of the project. It contains events, exceptions and middleware declaration. The app folder comprises various sub folders as explained below − Console includes the artisan commands necessary for Laravel. It includes a directory named Commands, where all the commands are declared with the appropriate signature. The file Kernal.php calls the commands declared in Inspire.php. If we need to call a specific command in Laravel, then we should make appropriate changes in this directory. This folder includes all the events for the project. Events are used to trigger activities, raise errors or necessary validations and provide greater flexibility. Laravel keeps all the events under one directory. The default file included is event.php where all the basic events are declared. This folder contains all the methods needed to handle exceptions. It also contains the file handle.php that handles all the exceptions. The Http folder has sub-folders for controllers, middleware and application requests. As Laravel follows the MVC design pattern, this folder includes model, controllers and views defined for the specific directories. The Middleware sub-folder includes middleware mechanism, comprising the filter mechanism and communication between response and request. The Requests sub-folder includes all the requests of the application. The Jobs directory maintains the activities queued for Laravel application. The base class is shared among all the Jobs and provides a central location to place them under one roof. Listeners are event-dependent and they include methods which are used to handle events and exceptions. For example, the login event declared includes a LoginListener event. Policies are the PHP classes which includes the authorization logic. Laravel includes a feature to create all authorization logic within policy classes inside this sub folder. This folder includes all the service providers required to register events for core servers and to configure a Laravel application. This folder encloses all the application bootstrap scripts. It contains a sub-folder namely cache, which includes all the files associated for caching a web application. You can also find the file app.php, which initializes the scripts necessary for bootstrap. The config folder includes various configurations and associated parameters required for the smooth functioning of a Laravel application. Various files included within the config folder are as shown in the image here. The filenames work as per the functionality associated with them. As the name suggests, this directory includes various parameters for database functionalities. It includes three sub-directories as given below − Seeds − This contains the classes used for unit testing database. Seeds − This contains the classes used for unit testing database. Migrations − This folder helps in queries for migrating the database used in the web application. Migrations − This folder helps in queries for migrating the database used in the web application. Factories − This folder is used to generate large number of data records. Factories − This folder is used to generate large number of data records. It is the root folder which helps in initializing the Laravel application. It includes the following files and folders − .htaccess − This file gives the server configuration. .htaccess − This file gives the server configuration. javascript and css − These files are considered as assets. javascript and css − These files are considered as assets. index.php − This file is required for the initialization of a web application. index.php − This file is required for the initialization of a web application. Resources directory contains the files which enhances your web application. The sub-folders included in this directory and their purpose is explained below − assets − The assets folder include files such as LESS and SCSS, that are required for styling the web application. assets − The assets folder include files such as LESS and SCSS, that are required for styling the web application. lang − This folder includes configuration for localization or internalization. lang − This folder includes configuration for localization or internalization. views − Views are the HTML files or templates which interact with end users and play a primary role in MVC architecture. views − Views are the HTML files or templates which interact with end users and play a primary role in MVC architecture. Observe that the resources directory will be flattened instead of having an assets folder. The pictorial representation of same is shown below − This is the folder that stores all the logs and necessary files which are needed frequently when a Laravel project is running. The sub-folders included in this directory and their purpose is given below − app − This folder contains the files that are called in succession. app − This folder contains the files that are called in succession. framework − It contains sessions, cache and views which are called frequently. framework − It contains sessions, cache and views which are called frequently. Logs − All exceptions and error logs are tracked in this sub folder. Logs − All exceptions and error logs are tracked in this sub folder. All the unit test cases are included in this directory. The naming convention for naming test case classes is camel_case and follows the convention as per the functionality of the class. Laravel is completely based on Composer dependencies, for example to install Laravel setup or to include third party libraries, etc. The Vendor folder includes all the composer dependencies. In addition to the above mentioned files, Laravel also includes some other files which play a primary role in various functionalities such as GitHub configuration, packages and third party libraries. The files included in the application structure are shown below − In the previous chapter, we have seen that the basic configuration files of Laravel are included in the config directory. In this chapter, let us discuss the categories included in the configuration. Environment variables are those which provide a list of web services to your web application. All the environment variables are declared in the .env file which includes the parameters required for initializing the configuration. By default, the .env file includes following parameters − APP_ENV = local APP_DEBUG = true APP_KEY = base64:ZPt2wmKE/X4eEhrzJU6XX4R93rCwYG8E2f8QUA7kGK8 = APP_URL = http://localhost DB_CONNECTION = mysql DB_HOST = 127.0.0.1 DB_PORT = 3306 DB_DATABASE = homestead DB_USERNAME = homestead DB_PASSWORD = secret CACHE_DRIVER = file SESSION_DRIVER = file QUEUE_DRIVER = sync REDIS_HOST = 127.0.0.1 REDIS_PASSWORD = null REDIS_PORT = 6379 MAIL_DRIVER = smtp MAIL_HOST = mailtrap.ioMAIL_PORT = 2525 MAIL_USERNAME = null MAIL_PASSWORD = null MAIL_ENCRYPTION = null While working with basic configuration files of Laravel, the following points are to be noted − The .env file should not be committed to the application source control, since each developer or user has some predefined environment configuration for the web application. The .env file should not be committed to the application source control, since each developer or user has some predefined environment configuration for the web application. For backup options, the development team should include the .env.example file, which should contain the default configuration. For backup options, the development team should include the .env.example file, which should contain the default configuration. All the environment variables declared in the .env file can be accessed by env-helper functions which will call the respective parameter. These variables are also listed into $_ENV global variable whenever application receives a request from the user end. You can access the environment variable as shown below − 'env' => env('APP_ENV', 'production'), env-helper functions are called in the app.php file included in the config folder. The above given example is calling for the basic local parameter. You can easily access the configuration values anywhere in the application using the global config helper function. In case if the configuration values are not initialized, default values are returned. For example, to set the default time zone, the following code is used − config(['app.timezone' => 'Asia/Kolkata']); To increase the performance and to boost the web application, it is important to cache all the configuration values. The command for caching the configuration values is − config:cache The following screenshot shows caching in a systematic approach − Sometimes you may need to update some configuration values or perform maintenance on your website. In such cases, keeping it in maintenance mode, makes it easier for you. Such web applications which are kept in maintenance mode, throw an exception namely MaintenanceModeException with a status code of 503. You can enable the maintenance mode on your Laravel web application using the following command − php artisan down The following screenshot shows how the web application looks when it is down − Once you finish working on updates and other maintenance, you can disable the maintenance mode on your web application using following command − php artisan up Now, you can find that the website shows the output with proper functioning and depicting that the maintenance mode is now removed as shown below − In Laravel, all requests are mapped with the help of routes. Basic routing routes the request to the associated controllers. This chapter discusses routing in Laravel. Routing in Laravel includes the following categories − Basic Routing Route parameters Named Routes All the application routes are registered within the app/routes.php file. This file tells Laravel for the URIs it should respond to and the associated controller will give it a particular call. The sample route for the welcome page can be seen as shown in the screenshot given below − Route::get ('/', function () { return view('welcome');}); Observe the following example to understand more about Routing − app/Http/routes.php <?php Route::get('/', function () { return view('welcome'); }); resources/view/welcome.blade.php <!DOCTYPE html> <html> <head> <title>Laravel</title> <link href = "https://fonts.googleapis.com/css?family=Lato:100" rel = "stylesheet" type = "text/css"> <style> html, body { height: 100%; } body { margin: 0; padding: 0; width: 100%; display: table; font-weight: 100; font-family: 'Lato'; } .container { text-align: center; display: table-cell; vertical-align: middle; } .content { text-align: center; display: inline-block; } .title { font-size: 96px; } </style> </head> <body> <div class = "container"> <div class = "content"> <div class = "title">Laravel 5.1</div> </div> </div> </body> </html> The routing mechanism is shown in the image given below − Let us now understand the steps involved in routing mechanism in detail − Step 1 − Initially, we should execute the root URL of the application. Step 2 − Now, the executed URL should match with the appropriate method in the route.php file. In the present case, it should match the method and the root (‘/’) URL. This will execute the related function. Step 3 − The function calls the template file resources/views/welcome.blade.php. Next, the function calls the view() function with argument ‘welcome’ without using the blade.php. This will produce the HTML output as shown in the image below − Sometimes in the web application, you may need to capture the parameters passed with the URL. For this, you should modify the code in routes.php file. You can capture the parameters in routes.php file in two ways as discussed here − These parameters are those which should be mandatorily captured for routing the web application. For example, it is important to capture the user’s identification number from the URL. This can be possible by defining route parameters as shown below − Route::get('ID/{id}',function($id) { echo 'ID: '.$id; }); Sometimes developers can produce parameters as optional and it is possible with the inclusion of ? after the parameter name in URL. It is important to keep the default value mentioned as a parameter name. Look at the following example that shows how to define an optional parameter − Route::get('user/{name?}', function ($name = 'TutorialsPoint') { return $name;}); The example above checks if the value matches to TutorialsPoint and accordingly routes to the defined URL. Named routes allow a convenient way of creating routes. The chaining of routes can be specified using name method onto the route definition. The following code shows an example for creating named routes with controller − Route::get('user/profile', 'UserController@showProfile')->name('profile'); The user controller will call for the function showProfile with parameter as profile. The parameters use name method onto the route definition. Middleware acts as a bridge between a request and a response. It is a type of filtering mechanism. This chapter explains you the middleware mechanism in Laravel. Laravel includes a middleware that verifies whether the user of the application is authenticated or not. If the user is authenticated, it redirects to the home page otherwise, if not, it redirects to the login page. Middleware can be created by executing the following command − php artisan make:middleware <middleware-name> Replace the <middleware-name> with the name of your middleware. The middleware that you create can be seen at app/Http/Middleware directory. Observe the following example to understand the middleware mechanism − Step 1 − Let us now create AgeMiddleware. To create that, we need to execute the following command − php artisan make:middleware AgeMiddleware Step 2 − After successful execution of the command, you will receive the following output − Step 3 − AgeMiddleware will be created at app/Http/Middleware. The newly created file will have the following code already created for you. <?php namespace App\Http\Middleware; use Closure; class AgeMiddleware { public function handle($request, Closure $next) { return $next($request); } } We need to register each and every middleware before using it. There are two types of Middleware in Laravel. Global Middleware Route Middleware The Global Middleware will run on every HTTP request of the application, whereas the Route Middleware will be assigned to a specific route. The middleware can be registered at app/Http/Kernel.php. This file contains two properties $middleware and $routeMiddleware. $middleware property is used to register Global Middleware and $routeMiddleware property is used to register route specific middleware. To register the global middleware, list the class at the end of $middleware property. protected $middleware = [ \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class, \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \App\Http\Middleware\VerifyCsrfToken::class, ]; To register the route specific middleware, add the key and value to $routeMiddleware property. protected $routeMiddleware = [ 'auth' => \App\Http\Middleware\Authenticate::class, 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, ]; We have created AgeMiddleware in the previous example. We can now register it in route specific middleware property. The code for that registration is shown below. The following is the code for app/Http/Kernel.php − <?php namespace App\Http; use Illuminate\Foundation\Http\Kernel as HttpKernel; class Kernel extends HttpKernel { protected $middleware = [ \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class, \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \App\Http\Middleware\VerifyCsrfToken::class, ]; protected $routeMiddleware = [ 'auth' => \App\Http\Middleware\Authenticate::class, 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, 'Age' => \App\Http\Middleware\AgeMiddleware::class, ]; } We can also pass parameters with the Middleware. For example, if your application has different roles like user, admin, super admin etc. and you want to authenticate the action based on role, this can be achieved by passing parameters with middleware. The middleware that we create contains the following function and we can pass our custom argument after the $next argument. public function handle($request, Closure $next) { return $next($request); } Step 1 − Create RoleMiddleware by executing the following command − php artisan make:middleware RoleMiddleware Step 2 − After successful execution, you will receive the following output − Step 3 − Add the following code in the handle method of the newly created RoleMiddlewareat app/Http/Middleware/RoleMiddleware.php. <?php namespace App\Http\Middleware; use Closure; class RoleMiddleware { public function handle($request, Closure $next, $role) { echo "Role: ".$role; return $next($request); } } Step 4 − Register the RoleMiddleware in app\Http\Kernel.php file. Add the line highlighted in gray color in that file to register RoleMiddleware. Step 5 − Execute the following command to create TestController − php artisan make:controller TestController --plain Step 6 − After successful execution of the above step, you will receive the following output − Step 7 − Copy the following lines of code to app/Http/TestController.php file. app/Http/TestController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; class TestController extends Controller { public function index() { echo "<br>Test Controller."; } } Step 8 − Add the following line of code in app/Http/routes.php file. app/Http/routes.php Route::get('role',[ 'middleware' => 'Role:editor', 'uses' => 'TestController@index', ]); Step 9 − Visit the following URL to test the Middleware with parameters http://localhost:8000/role Step 10 − The output will appear as shown in the following image. Terminable middleware performs some task after the response has been sent to the browser. This can be accomplished by creating a middleware with terminate method in the middleware. Terminable middleware should be registered with global middleware. The terminate method will receive two arguments $request and $response. Terminate method can be created as shown in the following code. Step 1 − Create TerminateMiddleware by executing the below command. php artisan make:middleware TerminateMiddleware Step 2 − The above step will produce the following output − Step 3 − Copy the following code in the newly created TerminateMiddleware at app/Http/Middleware/TerminateMiddleware.php. <?php namespace App\Http\Middleware; use Closure; class TerminateMiddleware { public function handle($request, Closure $next) { echo "Executing statements of handle method of TerminateMiddleware."; return $next($request); } public function terminate($request, $response) { echo "<br>Executing statements of terminate method of TerminateMiddleware."; } } Step 4 − Register the TerminateMiddleware in app\Http\Kernel.php file. Add the line highlighted in gray color in that file to register TerminateMiddleware. Step 5 − Execute the following command to create ABCController. php artisan make:controller ABCController --plain Step 6 − After the successful execution of the URL, you will receive the following output − Step 7 − Copy the following code to app/Http/ABCController.php file. app/Http/ABCController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; class ABCController extends Controller { public function index() { echo "<br>ABC Controller."; } } Step 8 − Add the following line of code in app/Http/routes.php file. app/Http/routes.php Route::get('terminate',[ 'middleware' => 'terminate', 'uses' => 'ABCController@index', ]); Step 9 − Visit the following URL to test the Terminable Middleware. http://localhost:8000/terminate Step 10 − The output will appear as shown in the following image. Namespaces can be defined as a class of elements in which each element has a unique name to that associated class. It may be shared with elements in other classes. The use keyword allows the developers to shorten the namespace. use <namespace-name>; The default namespace used in Laravel is App, however a user can change the namespace to match with web application. Creating user defined namespace with artisan command is mentioned as follows − php artisan app:name SocialNet The namespace once created can include various functionalities which can be used in controllers and various classes. In the MVC framework, the letter ‘C’ stands for Controller. It acts as a directing traffic between Views and Models. In this chapter, you will learn about Controllers in Laravel. Open the command prompt or terminal based on the operating system you are using and type the following command to create controller using the Artisan CLI (Command Line Interface). php artisan make:controller <controller-name> --plain Replace the <controller-name> with the name of your controller. This will create a plain constructor as we are passing the argument — plain. If you don’t want to create a plain constructor, you can simply ignore the argument. The created constructor can be seen at app/Http/Controllers. You will see that some basic coding has already been done for you and you can add your custom coding. The created controller can be called from routes.php by the following syntax. Route::get(‘base URI’,’controller@method’); Step 1 − Execute the following command to create UserController. php artisan make:controller UserController --plain Step 2 − After successful execution, you will receive the following output. Step 3 − You can see the created controller at app/Http/Controller/UserController.php with some basic coding already written for you and you can add your own coding based on your need. <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; class UserController extends Controller { // } We have seen middleware before and it can be used with controller also. Middleware can also be assigned to controller’s route or within your controller’s constructor. You can use the middleware method to assign middleware to the controller. The registered middleware can also be restricted to certain method of the controller. Route::get('profile', [ 'middleware' => 'auth', 'uses' => 'UserController@showProfile' ]); Here we are assigning auth middleware to UserController in profile route. <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; class UserController extends Controller { public function __construct() { $this->middleware('auth'); } } Here we are assigning auth middleware using the middleware method in the UserController constructor. Step 1 − Add the following lines of code to the app/Http/routes.php file and save it. routes.php <?php Route::get('/usercontroller/path',[ 'middleware' => 'First', 'uses' => 'UserController@showPath' ]); Step 2 − Create a middleware called FirstMiddleware by executing the following line of code. php artisan make:middleware FirstMiddleware Step 3 − Add the following code into the handle method of the newly created FirstMiddleware at app/Http/Middleware. FirstMiddleware.php <?php namespace App\Http\Middleware; use Closure; class FirstMiddleware { public function handle($request, Closure $next) { echo '<br>First Middleware'; return $next($request); } } Step 4 − Create a middleware called SecondMiddleware by executing the following command. php artisan make:middleware SecondMiddleware Step 5 − Add the following code in the handle method of the newly created SecondMiddleware at app/Http/Middleware. SecondMiddleware.php <?php namespace App\Http\Middleware; use Closure; class SecondMiddleware { public function handle($request, Closure $next) { echo '<br>Second Middleware'; return $next($request); } } Step 6 − Create a controller called UserController by executing the following line. php artisan make:controller UserController --plain Step 7 − After successful execution of the URL, you will receive the following output − Step 8 − Copy the following code to app/Http/UserController.php file. app/Http/UserController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; class UserController extends Controller { public function __construct() { $this->middleware('Second'); } public function showPath(Request $request) { $uri = $request->path(); echo '<br>URI: '.$uri; $url = $request->url(); echo '<br>'; echo 'URL: '.$url; $method = $request->method(); echo '<br>'; echo 'Method: '.$method; } } Step 9 − Now launch the php’s internal web server by executing the following command, if you haven’t executed it yet. php artisan serve Step 10 − Visit the following URL. http://localhost:8000/usercontroller/path Step 11 − The output will appear as shown in the following image. Often while making an application we need to perform CRUD (Create, Read, Update, Delete) operations. Laravel makes this job easy for us. Just create a controller and Laravel will automatically provide all the methods for the CRUD operations. You can also register a single route for all the methods in routes.php file. Step 1 − Create a controller called MyController by executing the following command. php artisan make:controller MyController Step 2 − Add the following code in app/Http/Controllers/MyController.php file. app/Http/Controllers/MyController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; class MyController extends Controller { public function index() { echo 'index'; } public function create() { echo 'create'; } public function store(Request $request) { echo 'store'; } public function show($id) { echo 'show'; } public function edit($id) { echo 'edit'; } public function update(Request $request, $id) { echo 'update'; } public function destroy($id) { echo 'destroy'; } } Step 3 − Add the following line of code in app/Http/routes.php file. app/Http/routes.php Route::resource('my','MyController'); Step 4 − We are now registering all the methods of MyController by registering a controller with resource. Below is the table of actions handled by resource controller. Step 5 − Try executing the URLs shown in the following table. Implicit Controllers allow you to define a single route to handle every action in the controller. You can define it in route.php file with Route:controller method as shown below. Route::controller(‘base URI’,’<class-name-of-the-controller>’); Replace the <class-name-of-the-controller> with the class name that you have given to your controller. The method name of the controller should start with HTTP verb like get or post. If you start it with get, it will handle only get request and if it starts with post then it will handle the post request. After the HTTP verb you can, you can give any name to the method but it should follow the title case version of the URI. Step 1 − Execute the below command to create a controller. We have kept the class name ImplicitController. You can give any name of your choice to the class. php artisan make:controller ImplicitController --plain Step 2 − After successful execution of step 1, you will receive the following output − Step 3 − Copy the following code to app/Http/Controllers/ImplicitController.php file. app/Http/Controllers/ImplicitController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; class ImplicitController extends Controller { /** * Responds to requests to GET /test */ public function getIndex() { echo 'index method'; } /** * Responds to requests to GET /test/show/1 */ public function getShow($id) { echo 'show method'; } /** * Responds to requests to GET /test/admin-profile */ public function getAdminProfile() { echo 'admin profile method'; } /** * Responds to requests to POST /test/profile */ public function postProfile() { echo 'profile method'; } } Step 4 − Add the following line to app/Http/routes.php file to route the requests to specified controller. app/Http/routes.php Route::controller('test','ImplicitController'); The Laravel service container is used to resolve all Laravel controllers. As a result, you are able to type-hint any dependencies your controller may need in its constructor. The dependencies will automatically be resolved and injected into the controller instance. Step 1 − Add the following code to app/Http/routes.php file. app/Http/routes.php class MyClass{ public $foo = 'bar'; } Route::get('/myclass','ImplicitController@index'); Step 2 − Add the following code to app/Http/Controllers/ImplicitController.php file. app/Http/Controllers/ImplicitController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; class ImplicitController extends Controller { private $myclass; public function __construct(\MyClass $myclass) { $this->myclass = $myclass; } public function index() { dd($this->myclass); } } Step 3 − Visit the following URL to test the constructor injection. http://localhost:8000/myclass Step 4 − The output will appear as shown in the following image. In addition to constructor injection, you may also type — hint dependencies on your controller's action methods. Step 1 − Add the following code to app/Http/routes.php file. app/Http/routes.php class MyClass{ public $foo = 'bar'; } Route::get('/myclass','ImplicitController@index'); Step 2 − Add the following code to app/Http/Controllers/ImplicitController.php file. app/Http/Controllers/ImplicitController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; class ImplicitController extends Controller { public function index(\MyClass $myclass) { dd($myclass); } } Step 3 − Visit the following URL to test the constructor injection. http://localhost:8000/myclass It will produce the following output − In this chapter, you will learn in detail about Requests in Laravel. The “path” method is used to retrieve the requested URI. The is method is used to retrieve the requested URI which matches the particular pattern specified in the argument of the method. To get the full URL, we can use the url method. Step 1 − Execute the below command to create a new controller called UriController. php artisan make:controller UriController –plain Step 2 − After successful execution of the URL, you will receive the following output − Step 3 − After creating a controller, add the following code in that file. app/Http/Controllers/UriController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; class UriController extends Controller { public function index(Request $request) { // Usage of path method $path = $request->path(); echo 'Path Method: '.$path; echo '<br>'; // Usage of is method $pattern = $request->is('foo/*'); echo 'is Method: '.$pattern; echo '<br>'; // Usage of url method $url = $request->url(); echo 'URL method: '.$url; } } Step 4 − Add the following line in the app/Http/route.php file. app/Http/route.php Route::get('/foo/bar','UriController@index'); Step 5 − Visit the following URL. http://localhost:8000/foo/bar Step 6 − The output will appear as shown in the following image. The input values can be easily retrieved in Laravel. No matter what method was used “get” or “post”, the Laravel method will retrieve input values for both the methods the same way. There are two ways we can retrieve the input values. Using the input() method Using the properties of Request instance The input() method takes one argument, the name of the field in form. For example, if the form contains username field then we can access it by the following way. $name = $request->input('username'); Like the input() method, we can get the username property directly from the request instance. $request->username Observe the following example to understand more about Requests − Step 1 − Create a Registration form, where user can register himself and store the form at resources/views/register.php <html> <head> <title>Form Example</title> </head> <body> <form action = "/user/register" method = "post"> <input type = "hidden" name = "_token" value = "<?php echo csrf_token() ?>"> <table> <tr> <td>Name</td> <td><input type = "text" name = "name" /></td> </tr> <tr> <td>Username</td> <td><input type = "text" name = "username" /></td> </tr> <tr> <td>Password</td> <td><input type = "text" name = "password" /></td> </tr> <tr> <td colspan = "2" align = "center"> <input type = "submit" value = "Register" /> </td> </tr> </table> </form> </body> </html> Step 2 − Execute the below command to create a UserRegistration controller. php artisan make:controller UserRegistration --plain Step 3 − After successful execution of the above step, you will receive the following output − Step 4 − Copy the following code in app/Http/Controllers/UserRegistration.php controller. app/Http/Controllers/UserRegistration.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; class UserRegistration extends Controller { public function postRegister(Request $request) { //Retrieve the name input field $name = $request->input('name'); echo 'Name: '.$name; echo '<br>'; //Retrieve the username input field $username = $request->username; echo 'Username: '.$username; echo '<br>'; //Retrieve the password input field $password = $request->password; echo 'Password: '.$password; } } Step 5 − Add the following line in app/Http/routes.php file. app/Http/routes.php Route::get('/register',function() { return view('register'); }); Route::post('/user/register',array('uses'=>'UserRegistration@postRegister')); Step 6 − Visit the following URL and you will see the registration form as shown in the below figure. Type the registration details and click Register and you will see on the second page that we have retrieved and displayed the user registration details. http://localhost:8000/register Step 7 − The output will look something like as shown in below the following images. Cookies play an important role while dealing a user’s session on a web application. In this chapter, you will learn about working with cookies in Laravel based web applications. Cookie can be created by global cookie helper of Laravel. It is an instance of Symfony\Component\HttpFoundation\Cookie. The cookie can be attached to the response using the withCookie() method. Create a response instance of Illuminate\Http\Response class to call the withCookie() method. Cookie generated by the Laravel are encrypted and signed and it can’t be modified or read by the client. Here is a sample code with explanation. //Create a response instance $response = new Illuminate\Http\Response('Hello World'); //Call the withCookie() method with the response method $response->withCookie(cookie('name', 'value', $minutes)); //return the response return $response; Cookie() method will take 3 arguments. First argument is the name of the cookie, second argument is the value of the cookie and the third argument is the duration of the cookie after which the cookie will get deleted automatically. Cookie can be set forever by using the forever method as shown in the below code. $response->withCookie(cookie()->forever('name', 'value')); Once we set the cookie, we can retrieve the cookie by cookie() method. This cookie() method will take only one argument which will be the name of the cookie. The cookie method can be called by using the instance of Illuminate\Http\Request. Here is a sample code. //’name’ is the name of the cookie to retrieve the value of $value = $request->cookie('name'); Observe the following example to understand more about Cookies − Step 1 − Execute the below command to create a controller in which we will manipulate the cookie. php artisan make:controller CookieController --plain Step 2 − After successful execution, you will receive the following output − Step 3 − Copy the following code in app/Http/Controllers/CookieController.php file. app/Http/Controllers/CookieController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Http\Response; use App\Http\Requests; use App\Http\Controllers\Controller; class CookieController extends Controller { public function setCookie(Request $request) { $minutes = 1; $response = new Response('Hello World'); $response->withCookie(cookie('name', 'virat', $minutes)); return $response; } public function getCookie(Request $request) { $value = $request->cookie('name'); echo $value; } } Step 4 − Add the following line in app/Http/routes.php file. app/Http/routes.php Route::get('/cookie/set','CookieController@setCookie'); Route::get('/cookie/get','CookieController@getCookie'); Step 5 − Visit the following URL to set the cookie. http://localhost:8000/cookie/set Step 6 − The output will appear as shown below. The window appearing in the screenshot is taken from firefox but depending on your browser, cookie can also be checked from the cookie option. Step 7 − Visit the following URL to get the cookie from the above URL. http://localhost:8000/cookie/get Step 8 − The output will appear as shown in the following image. A web application responds to a user’s request in many ways depending on many parameters. This chapter explains you in detail about responses in Laravel web applications. Laravel provides several different ways to return response. Response can be sent either from route or from controller. The basic response that can be sent is simple string as shown in the below sample code. This string will be automatically converted to appropriate HTTP response. Step 1 − Add the following code to app/Http/routes.php file. app/Http/routes.php Route::get('/basic_response', function () { return 'Hello World'; }); Step 2 − Visit the following URL to test the basic response. http://localhost:8000/basic_response Step 3 − The output will appear as shown in the following image. The response can be attached to headers using the header() method. We can also attach the series of headers as shown in the below sample code. return response($content,$status) ->header('Content-Type', $type) ->header('X-Header-One', 'Header Value') ->header('X-Header-Two', 'Header Value'); Observe the following example to understand more about Response − Step 1 − Add the following code to app/Http/routes.php file. app/Http/routes.php Route::get('/header',function() { return response("Hello", 200)->header('Content-Type', 'text/html'); }); Step 2 − Visit the following URL to test the basic response. http://localhost:8000/header Step 3 − The output will appear as shown in the following image. The withcookie() helper method is used to attach cookies. The cookie generated with this method can be attached by calling withcookie() method with response instance. By default, all cookies generated by Laravel are encrypted and signed so that they can't be modified or read by the client. Observe the following example to understand more about attaching cookies − Step 1 − Add the following code to app/Http/routes.php file. app/Http/routes.php Route::get('/cookie',function() { return response("Hello", 200)->header('Content-Type', 'text/html') ->withcookie('name','Virat Gandhi'); }); Step 2 − Visit the following URL to test the basic response. http://localhost:8000/cookie Step 3 − The output will appear as shown in the following image. JSON response can be sent using the json method. This method will automatically set the Content-Type header to application/json. The json method will automatically convert the array into appropriate json response. Observe the following example to understand more about JSON Response − Step 1 − Add the following line in app/Http/routes.php file. app/Http/routes.php Route::get('json',function() { return response()->json(['name' => 'Virat Gandhi', 'state' => 'Gujarat']); }); Step 2 − Visit the following URL to test the json response. http://localhost:8000/json Step 3 − The output will appear as shown in the following image. In MVC framework, the letter “V” stands for Views. It separates the application logic and the presentation logic. Views are stored in resources/views directory. Generally, the view contains the HTML which will be served by the application. Observe the following example to understand more about Views − Step 1 − Copy the following code and save it at resources/views/test.php <html> <body> <h1>Hello, World</h1> </body> </html> Step 2 − Add the following line in app/Http/routes.php file to set the route for the above view. app/Http/routes.php Route::get('/test', function() { return view('test'); }); Step 3 − Visit the following URL to see the output of the view. http://localhost:8000/test Step 4 − The output will appear as shown in the following image. While building application it may be required to pass data to the views. Pass an array to view helper function. After passing an array, we can use the key to get the value of that key in the HTML file. Observe the following example to understand more about passing data to views − Step 1 − Copy the following code and save it at resources/views/test.php <html> <body> <h1><?php echo $name; ?></h1> </body> </html> Step 2 − Add the following line in app/Http/routes.php file to set the route for the above view. app/Http/routes.php Route::get('/test', function() { return view('test',[‘name’=>’Virat Gandhi’]); }); Step 3 − The value of the key name will be passed to test.php file and $name will be replaced by that value. Step 4 − Visit the following URL to see the output of the view. http://localhost:8000/test Step 5 − The output will appear as shown in the following image. We have seen how we can pass data to views but at times, there is a need to pass data to all the views. Laravel makes this simpler. There is a method called share() which can be used for this purpose. The share() method will take two arguments, key and value. Typically share() method can be called from boot method of service provider. We can use any service provider, AppServiceProvider or our own service provider. Observe the following example to understand more about sharing data with all views − Step 1 − Add the following line in app/Http/routes.php file. app/Http/routes.php Route::get('/test', function() { return view('test'); }); Route::get('/test2', function() { return view('test2'); }); Step 2 − Create two view files — test.php and test2.php with the same code. These are the two files which will share data. Copy the following code in both the files. resources/views/test.php & resources/views/test2.php <html> <body> <h1><?php echo $name; ?></h1> </body> </html> Step 3 − Change the code of boot method in the file app/Providers/AppServiceProvider.php as shown below. (Here, we have used share method and the data that we have passed will be shared with all the views.) app/Providers/AppServiceProvider.php <?php namespace App\Providers; use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider { /** * Bootstrap any application services. * * @return void */ public function boot() { view()->share('name', 'Virat Gandhi'); } /** * Register any application services. * * @return void */ public function register() { // } } Step 4 − Visit the following URLs. http://localhost:8000/test http://localhost:8000/test2 Step 5 − The output will appear as shown in the following image. Laravel 5.1 introduces the concept of using Blade, a templating engine to design a unique layout. The layout thus designed can be used by other views, and includes a consistent design and structure. When compared to other templating engines, Blade is unique in the following ways − It does not restrict the developer from using plain PHP code in views. It does not restrict the developer from using plain PHP code in views. The blade views thus designed, are compiled and cached until they are modified. The blade views thus designed, are compiled and cached until they are modified. The complete directory structure of Laravel is shown in the screenshot given here. You can observe that all views are stored in the resources/views directory and the default view for Laravel framework is welcome.blade.php. Please note that other blade templates are also created similarly. You will have to use the following steps to create a blade template layout − Create a layout folder inside the resources/views folder. We are going to use this folder to store all layouts together. Create a layout folder inside the resources/views folder. We are going to use this folder to store all layouts together. Create a file name master.blade.php which will have the following code associated with it − Create a file name master.blade.php which will have the following code associated with it − <html> <head> <title>DemoLaravel - @yield('title')</title> </head> <body> @yield('content') </body> </html> In this step, you should extend the layout. Extending a layout involves defining the child elements. Laravel uses the Blade @extends directive for defining the child elements. When you are extending a layout, please note the following points − Views defined in the Blade Layout injects the container in a unique way. Views defined in the Blade Layout injects the container in a unique way. Various sections of view are created as child elements. Various sections of view are created as child elements. Child elements are stored in layouts folder as child.blade.php Child elements are stored in layouts folder as child.blade.php An example that shows extending the layout created above is shown here − @extends('layouts.app') @section('title', 'Page Title') @section('sidebar') @parent <p>This refers to the master sidebar.</p> @endsection @section('content') <p>This is my body content.</p> @endsection To implement the child elements in views, you should define the layout in the way it is needed. Observe the screenshot shown here. You can find that each of links mentioned in the landing page are hyperlinks. Please note that you can also create them as child elements with the help of blade templates by using the procedure given above. Named route is used to give specific name to a route. The name can be assigned using the “as” array key. Route::get('user/profile', ['as' => 'profile', function () { // }]); Note − Here, we have given the name profile to a route user/profile. Observe the following example to understand more about Redirecting to named routes − Step 1 − Create a view called test.php and save it at resources/views/test.php. <html> <body> <h1>Example of Redirecting to Named Routes</h1> </body> </html> Step 2 − In routes.php, we have set up the route for test.php file. We have renamed it to testing. We have also set up another route redirect which will redirect the request to the named route testing. app/Http/routes.php Route::get('/test', ['as'=>'testing',function() { return view('test2'); }]); Route::get('redirect',function() { return redirect()->route('testing'); }); Step 3 − Visit the following URL to test the named route example. http://localhost:8000/redirect Step 4 − After execution of the above URL, you will be redirected to http://localhost:8000/test as we are redirecting to the named route testing. Step 5 − After successful execution of the URL, you will receive the following output − Not only named route but we can also redirect to controller actions. We need to simply pass the controller and name of the action to the action method as shown in the following example. If you want to pass a parameter, you can pass it as the second argument of the action method. return redirect()->action(‘NameOfController@methodName’,[parameters]); Step 1 − Execute the following command to create a controller called RedirectController. php artisan make:controller RedirectController --plain Step 2 − After successful execution, you will receive the following output − Step 3 − Copy the following code to file app/Http/Controllers/RedirectController.php. app/Http/Controllers/RedirectController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; class RedirectController extends Controller { public function index() { echo "Redirecting to controller's action."; } } Step 4 − Add the following lines in app/Http/routes.php. app/Http/routes.php Route::get('rr','RedirectController@index'); Route::get('/redirectcontroller',function() { return redirect()->action('RedirectController@index'); }); Step 5 − Visit the following URL to test the example. http://localhost:8000/redirectcontroller Step 6 − The output will appear as shown in the following image. Laravel has made processing with database very easy. Laravel currently supports following 4 databases − MySQL Postgres SQLite SQL Server The query to the database can be fired using raw SQL, the fluent query builder, and the Eloquent ORM. To understand the all CRUD (Create, Read, Update, Delete) operations with Laravel, we will use simple student management system. Configure the database in config/database.php file and create the college database with structure in MySQL as shown in the following table. Database: College Table: student We will see how to add, delete, update and retrieve records from database using Laravel in student table. We can insert the record using the DB facade with insert method. After configuring the database, we can retrieve the records using the DB facade with select method. We can update the records using the DB facade with update method. We can delete the record using the DB facade with the delete method. This chapter deals with errors and logging in Laravel projects and how to work on them. A project while underway, is borne to have a few errors. Errors and exception handling is already configured for you when you start a new Laravel project. Normally, in a local environment we need to see errors for debugging purposes. We need to hide these errors from users in production environment. This can be achieved with the variable APP_DEBUG set in the environment file .env stored at the root of the application. For local environment the value of APP_DEBUG should be true but for production it needs to be set to false to hide errors. Note − After changing the APP_DEBUG variable, you should restart the Laravel server. Logging is an important mechanism by which system can log errors that are generated. It is useful to improve the reliability of the system. Laravel supports different logging modes like single, daily, syslog, and errorlog modes. You can set these modes in config/app.php file. 'log' => 'daily' You can see the generated log entries in storage/logs/laravel.log file. Laravel provides various in built tags to handle HTML forms easily and securely. All the major elements of HTML are generated using Laravel. To support this, we need to add HTML package to Laravel using composer. Step 1 − Execute the following command to proceed with the same. composer require illuminate/html Step 2 − This will add HTML package to Laravel as shown in the following image. Step 3 − Now, we need to add the package shown above to Laravel configuration file which is stored at config/app.php. Open this file and you will see a list of Laravel service providers as shown in the following image. Add HTML service provider as indicated in the outlined box in the following image. Step 4 − Add aliases in the same file for HTML and Form. Notice the two lines indicated in the outlined box in the following image and add those two lines. Step 5 − Now everything is setup. Let’s see how we can use various HTML elements using Laravel tags. {{ Form::open(array('url' => 'foo/bar')) }} // {{ Form::close() }} echo Form::label('email', 'E-Mail Address'); echo Form::text('username'); echo Form::text('email', 'example@gmail.com'); echo Form::password('password'); echo Form::file('image'); echo Form::checkbox('name', 'value'); echo Form::radio('name', 'value'); echo Form::checkbox('name', 'value', true); echo Form::radio('name', 'value', true); echo Form::select('size', array('L' => 'Large', 'S' => 'Small')); echo Form::submit('Click Me!'); Step 1 − Copy the following code to create a view called resources/views/form.php. resources/views/form.php <html> <body> <?php echo Form::open(array('url' => 'foo/bar')); echo Form::text('username','Username'); echo '<br/>'; echo Form::text('email', 'example@gmail.com'); echo '<br/>'; echo Form::password('password'); echo '<br/>'; echo Form::checkbox('name', 'value'); echo '<br/>'; echo Form::radio('name', 'value'); echo '<br/>'; echo Form::file('image'); echo '<br/>'; echo Form::select('size', array('L' => 'Large', 'S' => 'Small')); echo '<br/>'; echo Form::submit('Click Me!'); echo Form::close(); ?> </body> </html> Step 2 − Add the following line in app/Http/routes.php to add a route for view form.php app/Http/routes.php Route::get('/form',function() { return view('form'); }); Step 3 − Visit the following URL to see the form. http://localhost:8000/form Step 4 − The output will appear as shown in the following image. Localization feature of Laravel supports different language to be used in application. You need to store all the strings of different language in a file and these files are stored at resources/views directory. You should create a separate directory for each supported language. All the language files should return an array of keyed strings as shown below. <?php return [ 'welcome' => 'Welcome to the application' ]; Step 1 − Create 3 files for languages − English, French, and German. Save English file at resources/lang/en/lang.php <?php return [ 'msg' => 'Laravel Internationalization example.' ]; ?> Step 2 − Save French file at resources/lang/fr/lang.php. <?php return [ 'msg' => 'Exemple Laravel internationalisation.' ]; ?> Step 3 − Save German file at resources/lang/de/lang.php. <?php return [ 'msg' => 'Laravel Internationalisierung Beispiel.' ]; ?> Step 4 − Create a controller called LocalizationController by executing the following command. php artisan make:controller LocalizationController --plain Step 5 − After successful execution, you will receive the following output − Step 6 − Copy the following code to file app/Http/Controllers/LocalizationController.php app/Http/Controllers/LocalizationController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; class LocalizationController extends Controller { public function index(Request $request,$locale) { //set’s application’s locale app()->setLocale($locale); //Gets the translated message and displays it echo trans('lang.msg'); } } Step 7 − Add a route for LocalizationController in app/Http/routes.php file. Notice that we are passing {locale} argument after localization/ which we will use to see output in different language. app/Http/routes.php Route::get('localization/{locale}','LocalizationController@index'); Step 8 − Now, let us visit the different URLs to see all different languages. Execute the below URL to see output in English language. http://localhost:8000/localization/en Step 9 − The output will appear as shown in the following image. Step 10 − Execute the below URL to see output in French language. http://localhost:8000/localization/fr Step 11 − The output will appear as shown in the following image. Step 12 − Execute the below URL to see output in German language http://localhost:8000/localization/de Step 13 − The output will appear as shown in the following image. Sessions are used to store information about the user across the requests. Laravel provides various drivers like file, cookie, apc, array, Memcached, Redis, and database to handle session data. By default, file driver is used because it is lightweight. Session can be configured in the file stored at config/session.php. To access the session data, we need an instance of session which can be accessed via HTTP request. After getting the instance, we can use the get() method, which will take one argument, “key”, to get the session data. $value = $request->session()->get('key'); You can use all() method to get all session data instead of get() method. Data can be stored in session using the put() method. The put() method will take two arguments, the “key” and the “value”. $request->session()->put('key', 'value'); The forget() method is used to delete an item from the session. This method will take “key” as the argument. $request->session()->forget('key'); Use flush() method instead of forget() method to delete all session data. Use the pull() method to retrieve data from session and delete it afterwards. The pull() method will also take key as the argument. The difference between the forget() and the pull() method is that forget() method will not return the value of the session and pull() method will return it and delete that value from session. Step 1 − Create a controller called SessionController by executing the following command. php artisan make:controller SessionController --plain Step 2 − After successful execution, you will receive the following output − Step 3 − Copy the following code in a file at app/Http/Controllers/SessionController.php. app/Http/Controllers/SessionController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; class SessionController extends Controller { public function accessSessionData(Request $request) { if($request->session()->has('my_name')) echo $request->session()->get('my_name'); else echo 'No data in the session'; } public function storeSessionData(Request $request) { $request->session()->put('my_name','Virat Gandhi'); echo "Data has been added to session"; } public function deleteSessionData(Request $request) { $request->session()->forget('my_name'); echo "Data has been removed from session."; } } Step 4 − Add the following lines at app/Http/routes.php file. app/Http/routes.php Route::get('session/get','SessionController@accessSessionData'); Route::get('session/set','SessionController@storeSessionData'); Route::get('session/remove','SessionController@deleteSessionData'); Step 5 − Visit the following URL to set data in session. http://localhost:8000/session/set Step 6 − The output will appear as shown in the following image. Step 7 − Visit the following URL to get data from session. http://localhost:8000/session/get Step 8 − The output will appear as shown in the following image. Step 9 − Visit the following URL to remove session data. http://localhost:8000/session/remove Step 10 − You will see a message as shown in the following image. Validation is the most important aspect while designing an application. It validates the incoming data. By default, base controller class uses a ValidatesRequests trait which provides a convenient method to validate incoming HTTP requests with a variety of powerful validation rules. Laravel will always check for errors in the session data, and automatically bind them to the view if they are available. So, it is important to note that a $errors variable will always be available in all of your views on every request, allowing you to conveniently assume the $errors variable is always defined and can be safely used. The following table shows all available validation rules in Laravel. The $errors variable will be an instance of Illuminate\Support\MessageBag. Error message can be displayed in view file by adding the code as shown below. @if (count($errors) > 0) <div class = "alert alert-danger"> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif Step 1 − Create a controller called ValidationController by executing the following command. php artisan make:controller ValidationController --plain Step 2 − After successful execution, you will receive the following output − Step 3 − Copy the following code in app/Http/Controllers/ValidationController.php file. app/Http/Controllers/ValidationController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; class ValidationController extends Controller { public function showform() { return view('login'); } public function validateform(Request $request) { print_r($request->all()); $this->validate($request,[ 'username'=>'required|max:8', 'password'=>'required' ]); } } Step 4 − Create a view file called resources/views/login.blade.php and copy the following code in that file. resources/views/login.blade.php <html> <head> <title>Login Form</title> </head> <body> @if (count($errors) > 0) <div class = "alert alert-danger"> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif <?php echo Form::open(array('url'=>'/validation')); ?> <table border = '1'> <tr> <td align = 'center' colspan = '2'>Login</td> </tr> <tr> <td>Username</td> <td><?php echo Form::text('username'); ?></td> </tr> <tr> <td>Password</td> <td><?php echo Form::password('password'); ?></td> </tr> <tr> <td align = 'center' colspan = '2' ><?php echo Form::submit('Login'); ? ></td> </tr> </table> <?php echo Form::close(); ?> </body> </html> Step 5 − Add the following lines in app/Http/routes.php. app/Http/routes.php Route::get('/validation','ValidationController@showform'); Route::post('/validation','ValidationController@validateform'); Step 6 − Visit the following URL to test the validation. http://localhost:8000/validation Step 7 − Click the “Login” button without entering anything in the text field. The output will be as shown in the following image. Uploading Files in Laravel is very easy. All we need to do is to create a view file where a user can select a file to be uploaded and a controller where uploaded files will be processed. In a view file, we need to generate a file input by adding the following line of code. Form::file('file_name'); In Form::open(), we need to add ‘files’=>’true’ as shown below. This facilitates the form to be uploaded in multiple parts. Form::open(array('url' => '/uploadfile','files'=>'true')); Step 1 − Create a view file called resources/views/uploadfile.php and copy the following code in that file. resources/views/uploadfile.php <html> <body> <?php echo Form::open(array('url' => '/uploadfile','files'=>'true')); echo 'Select the file to upload.'; echo Form::file('image'); echo Form::submit('Upload File'); echo Form::close(); ?> </body> </html> Step 2 − Create a controller called UploadFileController by executing the following command. php artisan make:controller UploadFileController --plain Step 3 − After successful execution, you will receive the following output − Step 4 − Copy the following code in app/Http/Controllers/UploadFileController.php file. app/Http/Controllers/UploadFileController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; class UploadFileController extends Controller { public function index() { return view('uploadfile'); } public function showUploadFile(Request $request) { $file = $request->file('image'); //Display File Name echo 'File Name: '.$file->getClientOriginalName(); echo '<br>'; //Display File Extension echo 'File Extension: '.$file->getClientOriginalExtension(); echo '<br>'; //Display File Real Path echo 'File Real Path: '.$file->getRealPath(); echo '<br>'; //Display File Size echo 'File Size: '.$file->getSize(); echo '<br>'; //Display File Mime Type echo 'File Mime Type: '.$file->getMimeType(); //Move Uploaded File $destinationPath = 'uploads'; $file->move($destinationPath,$file->getClientOriginalName()); } } Step 5 − Add the following lines in app/Http/routes.php. app/Http/routes.php Route::get('/uploadfile','UploadFileController@index'); Route::post('/uploadfile','UploadFileController@showUploadFile'); Step 6 − Visit the following URL to test the upload file functionality. http://localhost:8000/uploadfile Step 7 − You will receive a prompt as shown in the following image. Laravel uses free feature-rich library SwiftMailer to send emails. Using the library function, we can easily send emails without too many hassles. The e-mail templates are loaded in the same way as views, which means you can use the Blade syntax and inject data into your templates. The following table shows the syntax and attributes of send function − $view(string|array) − name of the view that contains email message $view(string|array) − name of the view that contains email message $data(array) − array of data to pass to view $data(array) − array of data to pass to view $callback − a Closure callback which receives a message instance, allowing you to customize the recipients, subject, and other aspects of the mail message $callback − a Closure callback which receives a message instance, allowing you to customize the recipients, subject, and other aspects of the mail message In the third argument, the $callback closure received message instance and with that instance we can also call the following functions and alter the message as shown below. $message → subject('Welcome to the Tutorials Point'); $message → from('email@example.com', 'Mr. Example'); $message → to('email@example.com', 'Mr. Example'); Some of the less common methods include − $message → sender('email@example.com', 'Mr. Example'); $message → returnPath('email@example.com'); $message → cc('email@example.com', 'Mr. Example'); $message → bcc('email@example.com', 'Mr. Example'); $message → replyTo('email@example.com', 'Mr. Example'); $message → priority(2); To attach or embed files, you can use the following methods − $message → attach('path/to/attachment.txt'); $message → embed('path/to/attachment.jpg'); Mail can be sent as HTML or text. You can indicate the type of mail that you want to send in the first argument by passing an array as shown below. The default type is HTML. If you want to send plain text mail then use the following syntax. Mail::send([‘text’=>’text.view’], $data, $callback); In this syntax, the first argument takes an array. Use text as the key name of the view as value of the key. Step 1 − We will now send an email from Gmail account and for that you need to configure your Gmail account in Laravel environment file - .env file. Enable 2-step verification in your Gmail account and create an application specific password followed by changing the .env parameters as shown below. MAIL_DRIVER = smtp MAIL_HOST = smtp.gmail.com MAIL_PORT = 587 MAIL_USERNAME = your-gmail-username MAIL_PASSWORD = your-application-specific-password MAIL_ENCRYPTION = tls Step 2 − After changing the .env file execute the below two commands to clear the cache and restart the Laravel server. php artisan config:cache Step 3 − Create a controller called MailController by executing the following command. php artisan make:controller MailController --plain Step 4 − After successful execution, you will receive the following output − Step 5 − Copy the following code in app/Http/Controllers/MailController.php file. app/Http/Controllers/MailController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Mail; use App\Http\Requests; use App\Http\Controllers\Controller; class MailController extends Controller { public function basic_email() { $data = array('name'=>"Virat Gandhi"); Mail::send(['text'=>'mail'], $data, function($message) { $message->to('abc@gmail.com', 'Tutorials Point')->subject ('Laravel Basic Testing Mail'); $message->from('xyz@gmail.com','Virat Gandhi'); }); echo "Basic Email Sent. Check your inbox."; } public function html_email() { $data = array('name'=>"Virat Gandhi"); Mail::send('mail', $data, function($message) { $message->to('abc@gmail.com', 'Tutorials Point')->subject ('Laravel HTML Testing Mail'); $message->from('xyz@gmail.com','Virat Gandhi'); }); echo "HTML Email Sent. Check your inbox."; } public function attachment_email() { $data = array('name'=>"Virat Gandhi"); Mail::send('mail', $data, function($message) { $message->to('abc@gmail.com', 'Tutorials Point')->subject ('Laravel Testing Mail with Attachment'); $message->attach('C:\laravel-master\laravel\public\uploads\image.png'); $message->attach('C:\laravel-master\laravel\public\uploads\test.txt'); $message->from('xyz@gmail.com','Virat Gandhi'); }); echo "Email Sent with attachment. Check your inbox."; } } Step 6 − Copy the following code in resources/views/mail.blade.php file. resources/views/mail.blade.php <h1>Hi, {{ $name }}</h1> l<p>Sending Mail from Laravel.</p> Step 7 − Add the following lines in app/Http/routes.php. app/Http/routes.php Route::get('sendbasicemail','MailController@basic_email'); Route::get('sendhtmlemail','MailController@html_email'); Route::get('sendattachmentemail','MailController@attachment_email'); Step 8 − Visit the following URL to test basic email. http://localhost:8000/sendbasicemail Step 9 − The output screen will look something like this. Check your inbox to see the basic email output. Step 10 − Visit the following URL to test the HTML email. http://localhost:8000/sendhtmlemail Step 11 − The output screen will look something like this. Check your inbox to see the html email output. Step 12 − Visit the following URL to test the HTML email with attachment. http://localhost:8000/sendattachmentemail Step 13 − You can see the following output Note − In the MailController.php file the email address in the from method should be the email address from which you can send email address. Generally, it should be the email address configured on your server. Ajax (Asynchronous JavaScript and XML) is a set of web development techniques utilizing many web technologies used on the client-side to create asynchronous Web applications. Import jquery library in your view file to use ajax functions of jquery which will be used to send and receive data using ajax from the server. On the server side you can use the response() function to send response to client and to send response in JSON format you can chain the response function with json() function. json(string|array $data = array(), int $status = 200, array $headers = array(), int $options) Step 1 − Create a view file called resources/views/message.php and copy the following code in that file. <html> <head> <title>Ajax Example</title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script> function getMessage() { $.ajax({ type:'POST', url:'/getmsg', data:'_token = <?php echo csrf_token() ?>', success:function(data) { $("#msg").html(data.msg); } }); } </script> </head> <body> <div id = 'msg'>This message will be replaced using Ajax. Click the button to replace the message.</div> <?php echo Form::button('Replace Message',['onClick'=>'getMessage()']); ?> </body> </html> Step 2 − Create a controller called AjaxController by executing the following command. php artisan make:controller AjaxController --plain Step 3 − After successful execution, you will receive the following output − Step 4 − Copy the following code in app/Http/Controllers/AjaxController.php file. app/Http/Controllers/AjaxController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; class AjaxController extends Controller { public function index() { $msg = "This is a simple message."; return response()->json(array('msg'=> $msg), 200); } } Step 5 − Add the following lines in app/Http/routes.php. app/Http/routes.php Route::get('ajax',function() { return view('message'); }); Route::post('/getmsg','AjaxController@index'); Step 6 − Visit the following URL to test the Ajax functionality. http://localhost:8000/ajax Step 7 − You will be redirected to a page where you will see a message as shown in the following image. Step 8 − The output will appear as shown in the following image after clicking the button. Most web applications have specific mechanisms for error handling. Using these, they track errors and exceptions, and log them to analyze the performance. In this chapter, you will read about error handling in Laravel applications. Before proceeding further to learn in detail about error handling in Laravel, please note the following important points − For any new project, Laravel logs errors and exceptions in the App\Exceptions\Handler class, by default. They are then submitted back to the user for analysis. For any new project, Laravel logs errors and exceptions in the App\Exceptions\Handler class, by default. They are then submitted back to the user for analysis. When your Laravel application is set in debug mode, detailed error messages with stack traces will be shown on every error that occurs within your web application. When your Laravel application is set in debug mode, detailed error messages with stack traces will be shown on every error that occurs within your web application. By default, debug mode is set to false and you can change it to true. This enables the user to track all errors with stack traces. By default, debug mode is set to false and you can change it to true. This enables the user to track all errors with stack traces. The configuration of Laravel project includes the debug option which determines how much information about an error is to be displayed to the user. By default in a web application, the option is set to the value defined in the environment variables of the .env file. The value is set to true in a local development environment and is set to false in a production environment. If the value is set to true in a production environment, the risk of sharing sensitive information with the end users is higher. The configuration of Laravel project includes the debug option which determines how much information about an error is to be displayed to the user. By default in a web application, the option is set to the value defined in the environment variables of the .env file. The value is set to true in a local development environment and is set to false in a production environment. The value is set to true in a local development environment and is set to false in a production environment. If the value is set to true in a production environment, the risk of sharing sensitive information with the end users is higher. If the value is set to true in a production environment, the risk of sharing sensitive information with the end users is higher. Logging the errors in a web application helps to track them and in planning a strategy for removing them. The log information can be configured in the web application in config/app.php file. Please note the following points while dealing with Error Log in Laravel − Laravel uses monolog PHP logging library. Laravel uses monolog PHP logging library. The logging parameters used for error tracking are single, daily, syslog and errorlog. The logging parameters used for error tracking are single, daily, syslog and errorlog. For example, if you wish to log the error messages in log files, you should set the log value in your app configuration to daily as shown in the command below − For example, if you wish to log the error messages in log files, you should set the log value in your app configuration to daily as shown in the command below − 'log' => env('APP_LOG',’daily’), If the daily log mode is taken as the parameter, Laravel takes error log for a period of 5 days, by default. If you wish to change the maximum number of log files, you have to set the parameter of log_max_files in the configuration file to a desired value. If the daily log mode is taken as the parameter, Laravel takes error log for a period of 5 days, by default. If you wish to change the maximum number of log files, you have to set the parameter of log_max_files in the configuration file to a desired value. ‘log_max_files’ => 25; As Laravel uses monolog PHP logging library, there are various parameters used for analyzing severity levels. Various severity levels that are available are error, critical, alert and emergency messages. You can set the severity level as shown in the command below − 'log_level' => env('APP_LOG_LEVEL', 'error') Events provide a simple observer implementation which allows a user to subscribe and listen to various events triggered in the web application. All the event classes in Laravel are stored in the app/Events folder and the listeners are stored in the app/Listeners folder. The artisan command for generating events and listeners in your web application is shown below − php artisan event:generate This command generates the events and listeners to the respective folders as discussed above. Events and Listeners serve a great way to decouple a web application, since one event can have multiple listeners which are independent of each other. The events folder created by the artisan command includes the following two files: event.php and SomeEvent.php. They are shown here − <?php namespace App\Events; abstract class Event{ // } As mentioned above, event.php includes the basic definition of class Event and calls for namespace App\Events. Please note that the user defined or custom events are created in this file. <?php namespace App\Events; use App\Events\Event; use Illuminate\Queue\SerializesModels; use Illuminate\Contracts\Broadcasting\ShouldBroadcast; class SomeEvent extends Event{ use SerializesModels; /** * Create a new event instance. * * @return void */ public function __construct() { // } /** * Get the channels the event should be broadcast on. * * @return array */ public function broadcastOn() { return []; } } Observe that this file uses serialization for broadcasting events in a web application and that the necessary parameters are also initialized in this file. For example, if we need to initialize order variable in the constructor for registering an event, we can do it in the following way − public function __construct(Order $order) { $this->order = $order; } Listeners handle all the activities mentioned in an event that is being registered. The artisan command event:generate creates all the listeners in the app/listeners directory. The Listeners folder includes a file EventListener.php which has all the methods required for handling listeners. <?php namespace App\Listeners; use App\Events\SomeEvent; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; class EventListener{ /** * Create the event listener. * * @return void */ public function __construct() { // } /** * Handle the event. * * @param SomeEvent $event * @return void */ public function handle(SomeEvent $event) { // } } As mentioned in the code, it includes handle function for managing various events. We can create various independent listeners that target a single event. Facades provide a static interface to classes that are available in the application's service container. Laravel facades serve as static proxies to underlying classes in the service container, providing the benefit of a terse, expressive syntax while maintaining more testability and flexibility than traditional static methods. The following are the steps to create Facade in Laravel − Step 1 − Create PHP Class File. Step 1 − Create PHP Class File. Step 2 − Bind that class to Service Provider. Step 2 − Bind that class to Service Provider. Step 3 − Register that ServiceProvider to Config\app.php as providers. Step 3 − Register that ServiceProvider to Config\app.php as providers. Step 4 − Create Class which is this class extends to lluminate\Support\Facades\Facade. Step 4 − Create Class which is this class extends to lluminate\Support\Facades\Facade. Step 5 − Register point 4 to Config\app.php as aliases. Step 5 − Register point 4 to Config\app.php as aliases. Laravel ships with many Facades. The following table show the in-built Facade class references − Step 1 − Create a service provider called TestFacadesServiceProvider by executing the following command. php artisan make:provider TestFacadesServiceProvider Step 2 − After successful execution, you will receive the following output − Step 3 − Create a class called TestFacades.php at App/Test. App/Test/TestFacades.php <?php namespace App\Test; class TestFacades{ public function testingFacades() { echo "Testing the Facades in Laravel."; } } ?> Step 4 − Create a Facade class called “TestFacades.php” at “App/Test/Facades”. App/Test/Facades/TestFacades.php <?php namespace app\Test\Facades; use Illuminate\Support\Facades\Facade; class TestFacades extends Facade { protected static function getFacadeAccessor() { return 'test'; } } Step 5 − Create a Facade class called TestFacadesServiceProviders.php at App/Test/Facades. App/Providers/TestFacadesServiceProviders.php <?php namespace App\Providers; use App; use Illuminate\Support\ServiceProvider; class TestFacadesServiceProvider extends ServiceProvider { public function boot() { // } public function register() { App::bind('test',function() { return new \App\Test\TestFacades; }); } } Step 6 − Add a service provider in a file config/app.php as shown in the below figure. config/app.php Step 7 − Add an alias in a file config/app.php as shown in the below figure. config/app.php Step 8 − Add the following lines in app/Http/routes.php. app/Http/routes.php Route::get('/facadeex', function() { return TestFacades::testingFacades(); }); Step 9 − Visit the following URL to test the Facade. http://localhost:8000/facadeex Step 10 − After visiting the URL, you will receive the following output − Laravel contracts are a set of interfaces with various functionalities and core services provided by the framework. For example, Illuminate\Contracts\Queue\Queue contract uses a method which is needed for queuing jobs and Illuminate\Contracts\Mail\Mailer uses the method for sending emails. Every contract defined includes corresponding implementation of the framework. All the Laravel contracts are available in the GitHub repository as mentioned below − https://github.com/illuminate/contracts This repository provides a variety of contracts available in the Laravel framework which can be downloaded and used accordingly. While working with Laravel contracts, please note the following important points − It is mandatory to define facades in the constructor of a class. It is mandatory to define facades in the constructor of a class. Contracts are explicitly defined in the classes and you need not define the contracts in constructors. Contracts are explicitly defined in the classes and you need not define the contracts in constructors. Consider the contract used for Authorization in Laravel which is mentioned below − <?php namespace Illuminate\Contracts\Auth\Access; interface Authorizable{ /** * Determine if the entity has a given ability. * * @param string $ability * @param array|mixed $arguments * @return bool */ public function can($ability, $arguments = []); } The contract uses a function can which includes a parameter named ability and arguments which uses the user identification in the form of an array. You will have to define a contract as shown in the syntax below − interface <contract-name> Contracts are used like facades for creating robust, well-tested Laravel applications. There are various practical differences with usage of contracts and facades. The following code shows using a contract for caching a repository − <?php namespace App\Orders; use Illuminate\Contracts\Cache\Repository as Cache; class Repository{ /** * The cache instance. */ protected $cache; /** * Create a new repository instance. * * @param Cache $cache * @return void */ public function __construct(Cache $cache) { $this->cache = $cache; } } Contract contains no implementation and new dependencies; it is easy to write an alternative implementation of a specified contract, thus a user can replace cache implementation without modifying any code base. CSRF refers to Cross Site Forgery attacks on web applications. CSRF attacks are the unauthorized activities which the authenticated users of the system perform. As such, many web applications are prone to these attacks. Laravel offers CSRF protection in the following way − Laravel includes an in built CSRF plug-in, that generates tokens for each active user session. These tokens verify that the operations or requests are sent by the concerned authenticated user. The implementation of CSRF protection in Laravel is discussed in detail in this section. The following points are notable before proceeding further on CSRF protection − CSRF is implemented within HTML forms declared inside the web applications. You have to include a hidden validated CSRF token in the form, so that the CSRF protection middleware of Laravel can validate the request. The syntax is shown below − CSRF is implemented within HTML forms declared inside the web applications. You have to include a hidden validated CSRF token in the form, so that the CSRF protection middleware of Laravel can validate the request. The syntax is shown below − <form method = "POST" action="/profile"> {{ csrf_field() }} ... </form> You can conveniently build JavaScript driven applications using JavaScript HTTP library, as this includes CSRF token to every outgoing request. You can conveniently build JavaScript driven applications using JavaScript HTTP library, as this includes CSRF token to every outgoing request. The file namely resources/assets/js/bootstrap.js registers all the tokens for Laravel applications and includes meta tag which stores csrf-token with Axios HTTP library. The file namely resources/assets/js/bootstrap.js registers all the tokens for Laravel applications and includes meta tag which stores csrf-token with Axios HTTP library. Consider the following lines of code. They show a form which takes two parameters as input: email and message. <form> <label> Email </label> <input type = "text" name = "email"/> <br/> <label> Message </label> <input type="text" name = "message"/> <input type = ”submit” name = ”submitButton” value = ”submit”> </form> The result of the above code is the form shown below which the end user can view − The form shown above will accept any input information from an authorized user. This may make the web application prone to various attacks. Please note that the submit button includes functionality in the controller section. The postContact function is used in controllers for that associated views. It is shown below − public function postContact(Request $request) { return $request-> all(); } Observe that the form does not include any CSRF tokens so the sensitive information shared as input parameters are prone to various attacks. The following lines of code shows you the form re-designed using CSRF tokens − <form method = ”post” > {{ csrf_field() }} <label> Email </label> <input type = "text" name = "email"/> <br/> <label> Message </label> <input type = "text" name = "message"/> <input type = ”submit” name = ”submitButton” value = ”submit”> </form> The output achieved will return JSON with a token as given below − { "token": "ghfleifxDSUYEW9WE67877CXNVFJKL", "name": "TutorialsPoint", "email": "contact@tutorialspoint.com" } This is the CSRF token created on clicking the submit button. Authentication is the process of identifying the user credentials. In web applications, authentication is managed by sessions which take the input parameters such as email or username and password, for user identification. If these parameters match, the user is said to be authenticated. Laravel uses the following command to create forms and the associated controllers to perform authentication − php artisan make:auth This command helps in creating authentication scaffolding successfully, as shown in the following screenshot − The controller which is used for the authentication process is HomeController. <?php namespace App\Http\Controllers; use App\Http\Requests; use Illuminate\Http\Request; class HomeController extends Controller{ /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('auth'); } /** * Show the application dashboard. * * @return \Illuminate\Http\Response */ public function index() { return view('home'); } } As a result, the scaffold application generated creates the login page and the registration page for performing authentication. They are as shown below − Laravel uses the Auth façade which helps in manually authenticating the users. It includes the attempt method to verify their email and password. Consider the following lines of code for LoginController which includes all the functions for authentication − <?php // Authentication mechanism namespace App\Http\Controllers; use Illuminate\Support\Facades\Auth; class LoginController extends Controller{ /** * Handling authentication request * * @return Response */ public function authenticate() { if (Auth::attempt(['email' => $email, 'password' => $password])) { // Authentication passed... return redirect()->intended('dashboard'); } } } In the previous chapter, we have studied about authentication process in Laravel. This chapter explains you the authorization process in Laravel. Before proceeding further into learning about the authorization process in Laravel, let us understand the difference between authentication and authorization. In authentication, the system or the web application identifies its users through the credentials they provide. If it finds that the credentials are valid, they are authenticated, or else they are not. In authorization, the system or the web application checks if the authenticated users can access the resources that they are trying to access or make a request for. In other words, it checks their rights and permissions over the requested resources. If it finds that they can access the resources, it means that they are authorized. Thus, authentication involves checking the validity of the user credentials, and authorization involves checking the rights and permissions over the resources that an authenticated user has. Laravel provides a simple mechanism for authorization that contains two primary ways, namely Gates and Policies. Gates are used to determine if a user is authorized to perform a specified action. They are typically defined in App/Providers/AuthServiceProvider.php using Gate facade. Gates are also functions which are declared for performing authorization mechanism. Policies are declared within an array and are used within classes and methods which use authorization mechanism. The following lines of code explain you how to use Gates and Policies for authorizing a user in a Laravel web application. Note that in this example, the boot function is used for authorizing the users. <?php namespace App\Providers; use Illuminate\Contracts\Auth\Access\Gate as GateContract; use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider; class AuthServiceProvider extends ServiceProvider{ /** * The policy mappings for the application. * * @var array */ protected $policies = [ 'App\Model' => 'App\Policies\ModelPolicy', ]; /** * Register any application authentication / authorization services. * * @param \Illuminate\Contracts\Auth\Access\Gate $gate * @return void */ public function boot(GateContract $gate) { $this->registerPolicies($gate); // } } Laravel framework provides three primary tools for interaction through command-line namely: Artisan, Ticker and REPL. This chapter explains about Artisan in detail. Artisan is the command line interface frequently used in Laravel and it includes a set of helpful commands for developing a web application. Here is a list of few commands in Artisan along with their respective functionalities − To start Laravel project php artisan serve To enable caching mechanism php artisan route:cache To view the list of available commands supported by Artisan php artisan list To view help about any command and view the available options and arguments php artisan help serve The following screenshot shows the output of the commands given above − In addition to the commands listed in Artisan, a user can also create a custom command which can be used in the web application. Please note that commands are stored in app/console/commands directory. The default command for creating user defined command is shown below − php artisan make:console <name-of-command> Once you type the above given command, you can see the output as shown in the screenshot given below − The file created for DefaultCommand is named as DefaultCommand.php and is shown below − <?php namespace App\Console\Commands; use Illuminate\Console\Command; class DefaultCommand extends Command{ /** * The name and signature of the console command. * * @var string */ protected $signature = 'command:name'; /** * The console command description. * * @var string */ protected $description = 'Command description'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { // } } This file includes the signature and description for the command that user defined. The public function named handle executes the functionalities when the command is executed. These commands are registered in the file Kernel.php in the same directory. You can also create the schedule of tasks for the user defined command as shown in the following code − <?php namespace App\Console; use Illuminate\Console\Scheduling\Schedule; use Illuminate\Foundation\Console\Kernel as ConsoleKernel; class Kernel extends ConsoleKernel { /** * The Artisan commands provided by your application. * * @var array */ protected $commands = [ // Commands\Inspire::class, Commands\DefaultCommand::class ]; /** * Define the application's command schedule. * * @param \Illuminate\Console\Scheduling\Schedule $schedule * @return void */ protected function schedule(Schedule $schedule) { // $schedule->command('inspire') // ->hourly(); } } Note that the schedule of tasks for the given command is defined in the function named schedule, which includes a parameter for scheduling the tasks which takes hourly parameter. The commands are registered in the array of commands, which includes the path and name of the commands. Once the command is registered, it is listed in Artisan commands. The values included in the signature and description section will be displayed when you call for the help attribute of the specified command. Let us see how to view the attributes of our command DefaultCommand. You should use the command as shown below − php artisan help DefaultCommand Encryption is a process of converting a plain text to a message using some algorithms such that any third user cannot read the information. This is helpful for transmitting sensitive information because there are fewer chances for an intruder to target the information transferred. Encryption is performed using a process called Cryptography. The text which is to be encrypted is termed as Plain Text and the text or the message obtained after the encryption is called Cipher Text. The process of converting cipher text to plain text is called Decryption. Laravel uses AES-256 and AES-128 encrypter, which uses Open SSL for encryption. All the values included in Laravel are signed using the protocol Message Authentication Code so that the underlying value cannot be tampered with once it is encrypted. The command used to generate the key in Laravel is shown below − php artisan key:generate Please note that this command uses the PHP secure random bytes’ generator and you can see the output as shown in the screenshot given below − The command given above helps in generating the key which can be used in web application. Observe the screenshot shown below − The values for encryption are properly aligned in the config/app.php file, which includes two parameters for encryption namely key and cipher. If the value using this key is not properly aligned, all the values encrypted in Laravel will be insecure. Encryption of a value can be done by using the encrypt helper in the controllers of Laravel class. These values are encrypted using OpenSSL and AES-256 cipher. All the encrypted values are signed with Message Authentication code (MAC) to check for any modifications of the encrypted string. The code shown below is mentioned in a controller and is used to store a secret or a sensitive message. <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class DemoController extends Controller{ ** * Store a secret message for the user. * * @param Request $request * @param int $id * @return Response */ public function storeSecret(Request $request, $id) { $user = User::findOrFail($id); $user->fill([ 'secret' => encrypt($request->secret) ])->save(); } } Decryption of the values is done with the decrypt helper. Observe the following lines of code − use Illuminate\Contracts\Encryption\DecryptException; // Exception for decryption thrown in facade try { $decrypted = decrypt($encryptedValue); } catch (DecryptException $e) { // } Please note that if the process of decryption is not successful because of invalid MAC being used, then an appropriate exception is thrown. Hashing is the process of transforming a string of characters into a shorter fixed value or a key that represents the original string. Laravel uses the Hash facade which provides a secure way for storing passwords in a hashed manner. The following screenshot shows how to create a controller named passwordController which is used for storing and updating passwords − The following lines of code explain the functionality and usage of the passwordController − <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; use App\Http\Controllers\Controller class passwordController extends Controller{ /** * Updating the password for the user. * * @param Request $request * @return Response */ public function update(Request $request) { // Validate the new password length... $request->user()->fill([ 'password' => Hash::make($request->newPassword) // Hashing passwords ])->save(); } } The hashed passwords are stored using make method. This method allows managing the work factor of the bcrypt hashing algorithm, which is popularly used in Laravel. You should verify the password against hash to check the string which was used for conversion. For this you can use the check method. This is shown in the code given below − if (Hash::check('plain-text', $hashedPassword)) { // The passwords match... } Note that the check method compares the plain-text with the hashedPassword variable and if the result is true, it returns a true value. Every web application framework has its own version history and it is always being updated and maintained. Every latest version brings new functionality and functions which are either changed or deprecated, so it is important that you know which version will be suitable for your projects. When it comes to Laravel, there are two active versions as given below − Laravel 4- released in May 2013 Laravel 5.1- released in February 2015 Laravel 5.1 also includes various releases with the latest version of Laravel 5.1.5 which includes all the robust features for web development. The roadmap of Laravel or the version release is shown in the image below − The following points are worth notable in the context of understanding the release process of Laravel − The old directory of app/models is removed in Laravel 5.1. The old directory of app/models is removed in Laravel 5.1. All the controllers, middleware and requests are grouped within a directory under the app/Http folder. All the controllers, middleware and requests are grouped within a directory under the app/Http folder. A new folder namely Providers directory is replaced with the app/start files in the previous versions of Laravel 4.x. A new folder namely Providers directory is replaced with the app/start files in the previous versions of Laravel 4.x. All the language files and views are moved to the resources directory. All the language files and views are moved to the resources directory. New artisan command route:cache is used for registration of new routes and is included with the release of Laravel 5.1 and further versions. New artisan command route:cache is used for registration of new routes and is included with the release of Laravel 5.1 and further versions. Laravel supports HTTP middleware and also includes CSRF tokens and authentication model. Laravel supports HTTP middleware and also includes CSRF tokens and authentication model. All the authentication models are located under one directory namely resources/views/auth. It includes user registration, authentication and password controllers. All the authentication models are located under one directory namely resources/views/auth. It includes user registration, authentication and password controllers. Note that the highlighted version marks the latest release. The Guest User Gates feature is an add-on to the latest 5.7 version released in September 2018. This feature is used to initiate the authorization process for specific users. In Laravel 5.6, there was a procedure where it used to return false for unauthenticated users. In Laravel 5.7, we can allow guests to go authorization checks by using the specific nullable type hint within the specified controller as given below − <?php Gate::define('view-post', function (?User $user) { // Guests }); By using a nullable type hint the $user variable will be null when a guest user is passed to the gate. You can then make decisions about authorizing the action. If you allow nullable types and return true, then the guest will have authorization. If you don’t use a nullable type hint, guests will automatically get the 403 response for Laravel 5.7, which is displayed below − The difference between 403 and 404 error is that 404 is displayed when user tries to access the unknown resource or URL and 403 error as mentioned in the snapshot above is displayed if unauthorized user accesses the website. Laravel 5.7 comes with new way of treating and testing new commands. It includes a new feature of testing artisan commands and the demonstration is mentioned below − class ArtisanCommandTest extends TestCase{ public function testBasicTest() { $this->artisan('nova:create', [ 'name' => 'My New Admin panel' ]) ->expectsQuestion('Please enter your API key', 'apiKeySecret') ->expectsOutput('Authenticating...') ->expectsQuestion('Please select a version', 'v1.0') ->expectsOutput('Installing...') ->expectsQuestion('Do you want to compile the assets?', 'yes') ->expectsOutput('Compiling assets...') ->assertExitCode(0); } } Here a new class named “ArtisanCommandTest” is created under test cases module. It includes a basic function testBasicTest which includes various functionalities of assertions. The artisan command expectsQuestion includes two attributes. One with question and other with an apiKeySecret. Here, the artisan validates the apiKeySecret and verifies the input sent by user. The same scenario applies for the question “Please select a version” where a user is expected to mention a specific version. Laravel includes a feature of pagination which helps a user or a developer to include a pagination feature. Laravel paginator is integrated with the query builder and Eloquent ORM. The paginate method automatically takes care of setting the required limit and the defined offset. It accepts only one parameter to paginate i.e. the number of items to be displayed in one page. Laravel 5.7 includes a new pagination method to customize the number of pages on each side of the paginator. The new method no longer needs a custom pagination view. The custom pagination view code demonstration is mentioned below − <?php namespace App\Http\Controllers; use Illuminate\Support\Facades\DB; use App\Http\Controllers\Controller; class UserController extends Controller{ /** * Show all of the users for the application. * * @return Response */ public function index() { $users = DB::table('users')->paginate(15); return view('user.index', ['users' => $users]); } } The new pagination customization as per Laravel standards is mentioned below − <?php User::paginate(10)->onEachSide(5); Note that onEachSide refers to the subdivision of each pagination records with 10 and subdivision of 5. Laravel dump server comes with the version of Laravel 5.7. The previous versions do not include any dump server. Dump server will be a development dependency in laravel/laravel composer file. With release of version 5.7, you’ll get this command which includes a concept out-of-thebox which allows user to dump data to the console or an HTML file instead of to the browser. The command execution is mentioned below − php artisan dump-server # Or send the output to an HTML file php artisan dump-server --format=html > dump.html The command runs a server in the background which helps in collection of data sent from the application, that sends the output through the console. When the command is not running in the foreground, the dump() function is expected to work by default. Laravel 5.7 introduces a new feature called “callable action URL”. This feature is similar to the one in Laravel 5.6 which accepts string in action method. The main purpose of the new syntax introduced Laravel 5.7 is to directly enable you access the controller. The syntax used in Laravel 5.6 version is as shown − <?php $url = action('UserController@profile', ['id' => 1]); The similar action called in Laravel 5.7 is mentioned below − <?php $url = action([PostsController::class, 'index']); One advantage with the new callable array syntax format is the feature of ability to navigate to the controller directly if a developer uses a text editor or IDE that supports code navigation. 13 Lectures 3 hours Sebastian Sulinski 35 Lectures 3.5 hours Antonio Papa 7 Lectures 1.5 hours Sebastian Sulinski 42 Lectures 1 hours Skillbakerystudios 165 Lectures 13 hours Paul Carlo Tordecilla 116 Lectures 13 hours Hafizullah Masoudi Print Add Notes Bookmark this page
[ { "code": null, "e": 2778, "s": 2472, "text": "Laravel is an open-source PHP framework, which is robust and easy to understand. It follows a model-view-controller design pattern. Laravel reuses the existing components of different frameworks which helps in creating a web application. The web applica...
How to link jQuery from my local machine?
You can add jQuery using CDN or through downloading it on local machine. For Local Installation, download jQuery library on your local machine and include it in your HTML code. The following are the steps: Go to the jQuery website to download the latest version available. Now put downloaded jquery-3.2.1.min.js file in a directory of your website, e.g. /jquery. You can try to run the following code to learn how to link jQuery from local machine: Live Demo <html> <head> <title>jQuery Example</title> <script src = "/jquery/jquery-3.2.1.min.js"></script> <script> $(document).ready(function(){ document.write("Hello, World!"); }); </script> </head> <body> <h1>Hello</h1> </body> </html>
[ { "code": null, "e": 1268, "s": 1062, "text": "You can add jQuery using CDN or through downloading it on local machine. For Local Installation, download jQuery library on your local machine and include it in your HTML code. The following are the steps:" }, { "code": null, "e": 1335, ...
Converting Medium Posts to Markdown for Your Blog | by Will Koehrsen | Towards Data Science
If like me, you got your start blogging on Medium, but also want to build your own website to display your articles, you’ll need a way to move articles from Medium to the Markdown language. Markdown is a lightweight language meant to be converted into HTML for the web, and there are several tools that allow you to go from existing Medium articles to Markdown for a blog. (If you don’t yet have a blog, then follow this guide to build your own website in five minutes using Jekyll and GitHub pages.) There is both a Chrome Extension and a command line tool for taking your Medium posts to Markdown. Unfortunately, I’ve found the Chrome Extension to be unreliable, and if it does work, it makes a number of formatting errors that require correcting. If you can get the chrome extension to work and you aren’t comfortable at the command line, then that is probably the best choice for you. However, I’ve found the command line tool to be better for my use because it works every time, and requires fewer re-adjustments to the text after running. The medium-to-markdown command line package is written in Javascript which means you’ll need node to run and npm to install the package. If you’re on Windows, use this page to install both (it takes about 3 minutes). Then, install the package using npm install medium-to-markdown. The actual script you’ll need to run is available here, and also shown below. To run, save the script as medium-to-markdown.js, change the "<medium post url"> to the address of your published post, and type node medium-to-markdown.js at the command line (making sure the script is in your directory. This will output the entire post as Markdown in your console. To redirect the output to a file, you can type node medium-to-markdown.js >> file.md If you’re using GitHub Pages + Jekyll for your blog, you’ll want to save the md file in the _posts/ directory of your repository as date-title.md . For example, my latest post file is _posts/2018-09-16-Five-Minutes-to-Your-Own-Website.md . Once the article has been converted to a properly named Markdown file, it can be published by pushing the repository to GitHub. Personally, I found that process of manually renaming the file tedious, so I wrote a Python script that accepts a url of a published Medium post along a date, calls the medium-to-markdown.js conversion script with the url, and saves the resulting markdown with the correct file name. The script can be found here, and the command line usage is below: Overall, it takes 15 seconds to run the script and about 5 minutes for the website to update! Go to your blog to see the article rendered. Both the Chrome Extension and Command line tool create minor issues in the Markdown that you’ll have to fix. I do all my editing in the Prose online editor and like to pull up the editor and the original Medium article side-by-side.(I also frequently use the Chrome development tools — right click and inspect — on my blog to adjust the css and see the changes immediately. ) Following are a few of the issues I’ve noticed and how to fix them. I’ll assume you’re working with GitHub Pages and Jekyll for your blog (follow this guide to get started) although these tips may work with other frameworks. These solutions are not exhaustive, so if you run into any more problems, let me know in the comments or on Twitter. As you can see above, the default conversion to Markdown renders image captions left-justified below the image. To center the captions, add the following to your styles.scss file (in the repository root directory): // Captions for imagesimg + em { font-style: italic; font-weight: 600; margin-bottom: 20px; margin-top: 8px; display: block; text-align: center; font-size: 14px; color: black;} Then, in the Markdown itself, change the caption text from the default shown on top to the bottom. Make sure the caption is on a separate line: The caption will now be centered below the image. If you don’t like this styling, change the css listed above. To render images side by side in markdown, you can use a two-column table. I’ve found that you have to include the headers or the table does not show correctly. There are a couple other options, but the table works well. Here’s the blank code for a table so just replace the image_link and header: Header Left | Header Right:--------:|:-------:![](image_link) | ![](image_link) If you write a lot about programming, then you want your code to look great! Fortunately, unlike on Medium, you can use syntax highlighting to make your code blocks pop out on your blog. Jekyll natively supports the rouge language highlighter which has numerous styles to choose between (view them here). In the Markdown for the article, surround code blocks using backticks and specify the language for highlighting: ```pythonfrom sklearn.ensemble import RandomForestClassifier # Create the model with 100 treesmodel = RandomForestClassifier(n_estimators=100, bootstrap = True, max_features = 'sqrt')# Fit on training datamodel.fit(train, train_labels)``` The default syntax highlighting looks like this: Using a custom defined theme, the highlighting comes out like so: To set your own code theme, refer to this article, or if you like the look of mine, you can copy and paste my code style sheet code-highlighting.scss (link) into your _sass/ directory. Then change the line in style.scss that reads @import “highlights” to @import “code-highlighting" (this should be near the bottom) to import the new style instead. Another common part of my Medium posts are GitHub gists. To properly show these in your posts, start by going to the original medium article, right click on the Gist, and select inspect frame . This will bring up a page of what looks like incomprehensible code. However, all you need to do is copy what’s between the <script> tags as below: Simply copy and paste this line into the Markdown as shown below and it will be properly rendered on your blog. Of course, like any other element on your website, you can style the block using css however you like! By default, Jekyll will only show the first paragraph of your post on the main page of your blog with a button showing Read More to access the rest. If you have a picture at the top of your post, this is all that will be displayed. To extend the excerpt, add the following line to _config.yaml: # Specifies end of excerptexcerpt_separator: <!--more--> Then put the <!--more--> tag in the post markdown wherever you want the excerpt to end. There are still numerous options I haven’t explored. If you want to do something on your blog, chances are there’s a way to get it done. For example, you can add comments to all of your posts by making a Disqus account and adding it to your _config.yaml file (guide here). If you have a lot of posts and want to limit the number that appear on one page, you can specify that as well using pagination in the config file (instructions). Building a website is exciting because you are able to make it look however you want! Although this might not seem amazing to most people, I still appreciate when I make a minor update to my site and I can see the changes online just as I intended. You can’t imagine how enthusiastic I was when I finally got a live code editor running on my about page! At the end of the day, yes, building a website is about putting yourself out there for the world to see, but it’s also about taking pride in something you created. Going from an existing Medium article to Markdown can be done quickly using a command line tool. There are a few minor errors that need to be addressed after converting to Markdown, but this also gives you the chance to customize the post exactly how you want. If you are still stuck on any points, take a look through my website repository to see if you can find a solution there, or get in contact with me. Moreover, if you find something cool that you can do with a Jekyll blog, I’d enjoy hearing about it. Now get out there and start writing. As always, I welcome comments and constructive criticism. I can be reached on Twitter @koehrsen_will or through my website willk.online
[ { "code": null, "e": 545, "s": 172, "text": "If like me, you got your start blogging on Medium, but also want to build your own website to display your articles, you’ll need a way to move articles from Medium to the Markdown language. Markdown is a lightweight language meant to be converted into HTM...
Elixir - Errors Handling
Elixir has three error mechanisms: errors, throws and exits. Let us explore each mechanism in detail. Errors (or exceptions) are used when exceptional things happen in the code. A sample error can be retrieved by trying to add a number into a string − IO.puts(1 + "Hello") When the above program is run, it produces the following error − ** (ArithmeticError) bad argument in arithmetic expression :erlang.+(1, "Hello") This was a sample inbuilt error. We can raise errors using the raise functions. Let us consider an example to understand the same − #Runtime Error with just a message raise "oops" # ** (RuntimeError) oops Other errors can be raised with raise/2 passing the error name and a list of keyword arguments #Other error type with a message raise ArgumentError, message: "invalid argument foo" You can also define your own errors and raise those. Consider the following example − defmodule MyError do defexception message: "default message" end raise MyError # Raises error with default message raise MyError, message: "custom message" # Raises error with custom message We do not want our programs to abruptly quit but rather the errors need to be handled carefully. For this we use error handling. We rescue errors using the try/rescue construct. Let us consider the following example to understand the same − err = try do raise "oops" rescue e in RuntimeError -> e end IO.puts(err.message) When the above program is run, it produces the following result − oops We have handled errors in the rescue statement using pattern matching. If we do not have any use of the error, and just want to use it for identification purposes, we can also use the form − err = try do 1 + "Hello" rescue RuntimeError -> "You've got a runtime error!" ArithmeticError -> "You've got a Argument error!" end IO.puts(err) When running above program, it produces the following result − You've got a Argument error! NOTE − Most functions in the Elixir standard library are implemented twice, once returning tuples and the other time raising errors. For example, the File.read and the File.read! functions. The first one returned a tuple if the file was read successfully and if an error was encountered, this tuple was used to give the reason for the error. The second one raised an error if an error was encountered. If we use the first function approach, then we need to use case for pattern matching the error and take action according to that. In the second case, we use the try rescue approach for error prone code and handle errors accordingly. In Elixir, a value can be thrown and later be caught. Throw and Catch are reserved for situations where it is not possible to retrieve a value unless by using throw and catch. The instances are quite uncommon in practice except when interfacing with libraries. For example, let us now assume that the Enum module did not provide any API for finding a value and that we needed to find the first multiple of 13 in a list of numbers − val = try do Enum.each 20..100, fn(x) -> if rem(x, 13) == 0, do: throw(x) end "Got nothing" catch x -> "Got #{x}" end IO.puts(val) When the above program is run, it produces the following result − Got 26 When a process dies of “natural causes” (for example, unhandled exceptions), it sends an exit signal. A process can also die by explicitly sending an exit signal. Let us consider the following example − spawn_link fn -> exit(1) end In the example above, the linked process died by sending an exit signal with value of 1. Note that exit can also be “caught” using try/catch. For example − val = try do exit "I am exiting" catch :exit, _ -> "not really" end IO.puts(val) When the above program is run, it produces the following result − not really Sometimes it is necessary to ensure that a resource is cleaned up after some action that can potentially raise an error. The try/after construct allows you to do that. For example, we can open a file and use an after clause to close it–even if something goes wrong. {:ok, file} = File.open "sample", [:utf8, :write] try do IO.write file, "olá" raise "oops, something went wrong" after File.close(file) end When we run this program, it will give us an error. But the after statement will ensure that the file descriptor is closed upon any such event. 35 Lectures 3 hours Pranjal Srivastava 54 Lectures 6 hours Pranjal Srivastava, Harshit Srivastava 80 Lectures 9.5 hours Pranjal Srivastava 43 Lectures 4 hours Mohammad Nauman Print Add Notes Bookmark this page
[ { "code": null, "e": 2284, "s": 2182, "text": "Elixir has three error mechanisms: errors, throws and exits. Let us explore each mechanism in detail." }, { "code": null, "e": 2434, "s": 2284, "text": "Errors (or exceptions) are used when exceptional things happen in the code. A sa...
Prototype - update() Method
This method replaces the content of the element with the provided newContent argument and returns the element. Given newContent can be a plain text, an HTML snippet, or any JavaScript object, which has a toString() method. If it contains any <script> tags, these will be evaluated after element has been updated. If no argument is provided, Element.update will simply clear element of its content. element.update( newContent ); Updated HTML element. <html> <head> <title>Prototype examples</title> <script type = "text/javascript" src = "/javascript/prototype.js"></script> <script> function showResult() { $('movies').update("Spider Man, USV-315"); } </script> </head> <body> <p>Click the button to see the result</p> <div id = "movies"> Speed, Titanic, Brave Heart </div> <input type = "button" value = "Click" onclick = "showResult();"/> </body> </html> Click the button to see the result 127 Lectures 11.5 hours Aleksandar Cucukovic Print Add Notes Bookmark this page
[ { "code": null, "e": 2172, "s": 2061, "text": "This method replaces the content of the element with the provided newContent argument and returns the element." }, { "code": null, "e": 2374, "s": 2172, "text": "Given newContent can be a plain text, an HTML snippet, or any JavaScrip...
AutoML is Overhyped. AutoML as an idea of automating a... | by Denis Vorotyntsev | Towards Data Science
I used AutoML in my work, in several ML competitions for blending with my main models and participated in two AutoML competitions. I think AutoML as an idea of automating a modeling process is excellent, yet the field is too overhyped. Some key concepts, like features engineering or meta-learning for hyperparameters optimization, will unleash its potential, but for now, boxed AutoML as a tool is just a waste of money. Any Data Science project consists of several essential steps: formulation the problem from a business perspective (selecting the task and metric of success), gathering the data (collecting, cleaning, exploring), building a model and evaluating its performance, deploying model in production and observing model’s performance in production. Each part of the process is vital for the project success. However, from the perspective of Machine Learning adept, the modeling part is essential because well developed ML model could potentially bring a lot of value to the company. During the modeling stage, Data Scientist is solving optimization task: with a given dataset, targets — maximize selected metric. The process is complicated an, it requires different types of skills: Feature engineering sometimes treated as art, not a science;Hyperparameters optimization requires a deep understanding of algorithms and core ML concepts;Software engineering skills are needed to make output code easy to understand and deploy. Feature engineering sometimes treated as art, not a science; Hyperparameters optimization requires a deep understanding of algorithms and core ML concepts; Software engineering skills are needed to make output code easy to understand and deploy. AutoML is aimed to help us here. The input of AutoML is data and task (classification, regression, recommendations, etc.), output — production-ready model, which is capable of predicting unseen data. Every decision in the data-driven pipeline is a hyperparameter. The very idea of AutoML is to find such hyperparameters, which could give a good score in a reasonable amount of time. AutoML picks a strategy for preprocessing the data: how to deal with imbalanced data; how to fill missing values; remove, replace or keep outliers; how to encode categories and multicategories columns; how to avoid target leakage; how to prevent memory errors; etc. AutoML generates new features and selects meaningful ones; AutoML selects model (Linear models, K-Nearest Neighbors, Gradient Boosting, Neural Nets, etc.); AutoML tune hyperparameters of model chosen (for example, number of trees and subsampling for tree-based models or architecture, learning rate and number of epochs for Neural Nets); AutoML makes a stable ensemble of models to increase the score if it’s possible. More companies nowadays either start collecting data, or they want to realize the potential of collected data: they want to get a value from it. On the other hand, there are no too many Data Scientists with a propper background to fulfill the demand, so the gap arises. AutoML could potentially fill this gap. But could boxed solutions bring any value to a company? In my opinion, the answer is “No.” These companies need a process, but AutoML is just a tool. Advanced tools couldn’t fill the absence of strategy. Before starting using AutoML, consider a project with a consulting firm, which could help you develop a Data Science strategy at first. It is not a coincidence that most of the AutoML solution providers are doing consulting. Some sort foot-in-the-door over here. According to 2018 Kaggle ML and Data Science Survey 15–26% of the time of a typical data science project, time is devoted to model building or model selection. It’s demanding task both in terms of “man-hours” and computational hours. If the objective or data changes (for example, new features will be added), the process should be repeated. AutoML could help Data Scientists within a company to save time and spend it more on more important stuff (like sword fighting on chairs). However, if the modeling part for the Data Science team is not the most critical task, you have an apparent problem in processes in your company. Commonly, even a small increase in the model’s performance could potentially earn tons of money for your firm, the modeling time in such case is well-spent time: Oversimplified rules:if (Gain from model > Costs of DS team time) → Time savings are not needed.if (Gain from model <= Costs of DS team time) → Are you solving the right problem? 🤔 It’s a good idea to write scripts for everyday tasks of your DS team and save time in the future instead of using boxed solutions. I’ve written several scripts for automation of routine tasks: automatic feature generation, feature selection, model training, and hyperparameters tuning, which I’m using every day now. Unfortunately, we don’t have any useful benchmarks “Tabular AutoML vs. Humans”, except “An Open Source AutoML Benchmark”. The authors of papers compared the performance of several AutoML libraries with a performance of tuned Random Forest. It was published several months ago, on the 1st of July 2019. I was curious and decided to do my benchmarks. I compared my performance with a performance of AutoML solutions on three datasets of binary classification: credit, KDD Upselling, and mortgages. I split dataset in train (random 60% of the data with stratification by target) and test part (remaining 40% of data). My baseline solution was relatively simple. I didn’t dig into the data, nor create any advanced features: 5-StratifiedKFold;Catboost Encoder for categorical columns (if you aren’t familiar with CatBoost encoder, check my previous post: Benchmarking Categorical Encoders);Mathematical operations (+-*/) for numerical columns pairs. New features limit: 500;Model: LightGBM with defaults parameters;Blending OOF ranked predictions. 5-StratifiedKFold; Catboost Encoder for categorical columns (if you aren’t familiar with CatBoost encoder, check my previous post: Benchmarking Categorical Encoders); Mathematical operations (+-*/) for numerical columns pairs. New features limit: 500; Model: LightGBM with defaults parameters; Blending OOF ranked predictions. I used two standard libraries for AutoML: H2O and TPOT. I trained them for several time intervals: starting from 15 minutes up to 6 hours. With the following metric, I got surprising results: Score = (ROC AUC / ROC AUC of my baseline) * 100% Firstly, in nearly all cases, my baseline beat AutoML. I was a little bit sad because I’ve planned to chill a little bit in office, while AutoML was doing all the dirty work, but whatever 😒 Secondly, the scores of AutoML weren’t improving over time, which means that it doesn’t matter how long we wait: it will have the same low scores in 15 minutes as in 6 hours. AutoML is not about high scores. UPD 16.10.2019: I want to add that my benchmark is not the final point in the “Human vs AutoML” competition. We clearly need more discussion on metric (should it be only scores? scores + time? amount of CO2 emissions during meta-learning, etc) and also more benchmarks on different datasets and tasks. If your company wants to play with its data, for the first time, consider hiring a consultant.You should automate your work as much as possible...... yet boxed solutions don’t seem like the right choice because of relatively low scores. If your company wants to play with its data, for the first time, consider hiring a consultant. You should automate your work as much as possible... ... yet boxed solutions don’t seem like the right choice because of relatively low scores. In this post, I was talking about tools, yet it’s important to remember that the modeling part is just a part of the whole data science project pipeline. I like the analogy in which project is treated like a car. In such a way, the output of the modeling part — Machine Learning model — is an engine. Engine, no doubts, is essential, but it is not the whole car. You may spend a lot of time engineering incredible, thoughtful, and sophisticated features, selecting architecture of your Neural Net or tuning parameters of Random Forest and, as a result, create powerful engine. But if you haven’t paid attention to other parts of your car, all your work might be useless. The model itself could show high score, but it won’t be used because you were solving the wrong problem (business understanding), or data was biased, and you have to retrain it (data exploration) or model is too complex, so it couldn’t be used in production (deployment stage). In the end, you may find yourself in a silly situation: after days or weeks of hard modeling work, you are driving a slow robust bike with a sports car engine in the basket. Tools are essential; strategy is vital.
[ { "code": null, "e": 594, "s": 172, "text": "I used AutoML in my work, in several ML competitions for blending with my main models and participated in two AutoML competitions. I think AutoML as an idea of automating a modeling process is excellent, yet the field is too overhyped. Some key concepts, ...
Introducing Transformers Interpret — Explainable AI for Transformers | by Charles Pierse | Towards Data Science
TL:DR: Transformers Interpret brings explainable AI to the transformers package with just 2 lines of code. It allows you to get word attributions and visualizations for those attributions simply. Right now the package supports all transformer models with a sequence classification head. Check out the project here: https://github.com/cdpierse/transformers-interpret Model explainability and state-of-the-art research seem to constantly be engaged in a tug of war. Complex models are difficult to interpret and simple models are often much easier to understand. Explainable AI is one of the most vital emerging subfields in machine learning today. For both ethical, practical, and - in the corporate world — legal reasons we must be able to explain the inner workings of so called “black box” models, it’s vital to the long term success of AI’s adoption into our lives. Research in explainable AI is ongoing and there are a number of fantastic projects and groups out there doing work. The library on which transformers interpret is built is called Captum which is a package designed for model interpretability in pytorch. What I love about Captum is that it effectively combines all the leading research in explainable AI into a single package, and of course it is optimized for pytorch which is a big plus. While transformers interpret is focused solely on NLP, Captum is multi modal and works with text, computer vision, and tabular data. The team at Captum have also done a fantastic job giving write ups of all the algorithms they are using throughout the package, it’s certainly worth checking out if you are interested in understanding the internals of transformers interpret. Much like the design philosophy behind Hugging Faces Transformers package transformers interpret was designed with ease of use at the forefront. It is opinionated in its selection of attribution methods and how it summarizes attributions. All of this allows end users to get word attributions and visualizations for their model’s output in just 2 lines of code. Right now the package has support for all models with sequence classification heads — so (should) work for all classification models. Support for question answering models and NER models is planned. Let’s jump into a hands on example. To install the package: pip install transformers-interpret With the package installed we are going to start by instantiating a transformers model and tokenizer. I’ve chosen to go with distilbert-base-uncased-finetuned-sst-2-english it’s a distilbert model finetuned on a sentiment analysis task, I chose this model mostly because it is popular and lightweight compared to some of the other behemoths out there. from transformers import AutoModelForSequenceClassification, AutoTokenizermodel_name = "distilbert-base-uncased-finetuned-sst-2-english"model = AutoModelForSequenceClassification.from_pretrained(model_name)tokenizer = AutoTokenizer.from_pretrained(model_name) With both the model and tokenizer in hand we can now go about creating an explainer, and it’s pretty simple: from transformers_interpret import SequenceClassificationExplainercls_explainer = SequenceClassificationExplainer("I love you, I like you", model, tokenizer) That’s all it takes. To get the attributions for the sentence “I love you, I like you” we simply call: attributions = cls_explainer() If we want to know which class was predicted: >>> cls_explainer.predicted_class_name'POSITIVE' To see the raw numeric attributions: >>> attributions.word_attributions[('BOS_TOKEN', 0.0),('I', 0.46820529249283205),('love', 0.46061853275727177),('you', 0.566412765400519),(',', -0.017154456486408547),('I', -0.053763869433472),('like', 0.10987746237531228),('you', 0.48221682341218103),('EOS_TOKEN', 0.0)] This is interesting we can see that the model is placing a significant amount of attention on “I love you” while “I like you” is not as important. Given how self-attention works this seems to fit with the intuition that the word “love” is increasing the importance of the words surrounding it’s context. The numeric attributions can be difficult to read especially for much longer sentences. The package also has an inbuilt visualize method built on top of Captums’ visualization to give easy to interpret visual explanations of word attributions. If you are working in a jupyter notebook calling the method will display the visualization in-line, if you are running from a script simply pass a html filename and you can view the output file in your browser. cls_explainer.visualize("distilbert_example.html") This will produce an output that looks like this: If you want to generate further attributions there is no need to create another explainer, you can simply pass some new text to the existing explainer and new attributions will be created attributions = cls_explainer("I hate you, I dislike you") You are not limited to generating attributions for the predicted class, this is the default behavior but can be overridden by passing either a class name or index of the class you would like attributions for: attributions = cls_explainer(class_name="NEGATIVE") This is particularly useful for multiclass classification models. For a more detailed example of this check out this multiclass classification notebook Below is a full working example of the above code. At the time of writing the package only supports classification models. However question answering models are also very possible to implement as are NER models and both of these are currently planned features. I’m also interested in exploring the feasibility of explanations for causal language models and multiple choice models. Captum has a variety of attributions methods, the default in transformers interpret is Layer Integrated Gradients, with the attribution scores effectively being a summary or average of each layers’ attributions. Captum recently added support for performing Layer Integrated Gradients on specific layer(s) of the transformer, so I am hoping to add the option for users to get attributions on a layer by layer basis which would allow even deeper inspection of a models’ internals. Check out the repo for any updates regarding future releases. If you have any questions, suggestions, or would like to make a contribution (please do 😁) please get in touch. I’d also highly suggest checking out Captum if you find model explainability and interpretability interesting. They are doing amazing and important work. Thanks for reading!
[ { "code": null, "e": 459, "s": 172, "text": "TL:DR: Transformers Interpret brings explainable AI to the transformers package with just 2 lines of code. It allows you to get word attributions and visualizations for those attributions simply. Right now the package supports all transformer models with ...
D3.js brushSelection() Function - GeeksforGeeks
31 Jul, 2020 The d3.brushSelection() function in D3.js is used to get the brush selection for a given node. Syntax: d3.brushSelection(this); Parameters: this: used to get the bounds for the current brush. Return Value: This function returns the array containing the bounds of the brush element. Example: In this example, we will create a brush and will get its selection bound sides using this method. <!DOCTYPE html><html> <head> <title> D3.js | d3.brushSelection() Function </title> <script src="https://d3js.org/d3.v4.min.js"> </script> </head> <body> <h1 style="color: green; text-align: center;"> Geeksforgeeks </h1> <p style="text-align: center;"> D3.js | d3.brushSelection() Function <br /> Dimensions are:<br /> </p> <p style="text-align: center;" id="p"></p> <svg width="600" height="600" id="brush"></svg> <script> // Selecting SVG element d3.select("#brush") // Creating a brush .call( d3 .brush() // Calling a function on brush change .on("brush", brushed) /* Initialise the brush area: start at 0, 0 and finishes at given width, height*/ .extent([ [0, 0], [600, 600], ]) ); function brushed() {// Using d3.brushSelection to get bounds of the brush const sel = d3.brushSelection(this); console.log(sel); var p = document.getElementById("p"); p.innerHTML = "side1 : " + sel[0][1] + `<br>` + "side2 : " + sel[1][1] + `<br>` + "side3 : " + sel[0][0] + `<br>` + "side4 : " + sel[1][0] + `<br>`; } </script> </body></html> Output: D3.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request Remove elements from a JavaScript Array How to get character array from string in JavaScript? How to filter object array based on attributes? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25300, "s": 25272, "text": "\n31 Jul, 2020" }, { "code": null, "e": 25395, "s": 25300, "text": "The d3.brushSelection() function in D3.js is used to get the brush selection for a given node." }, { "code": null, "e": 25403, "s": 25395, "tex...
The Art of Data Visualization — Weather Data Visualization Using Matplotlib and Ggplot2 | by Benjamin Obi Tayo Ph.D. | Towards Data Science
Data Visualization is more of an Art than Science. To produce a good visualization, you need to put several pieces of code together for an excellent end result. This tutorial demonstrates how a good data visualization can be produced by analyzing weather data. In Section I, we produce a visualization using matplotlib package. In Section II, we attempt to reproduce the visualization using ggplot2. Before delving into the art of data visualization, lets first discuss the essential components of a good data visualization. A good data visualization is made up of several components that have to be pieced up together to produce an end product: a) Data Component: An important first step in deciding how to visualize data is to know what type of data it is, e.g. categorical data, discrete data, continuous data, time series data, etc. b) Geometric Component: Here is where you decide what kind of visualization is suitable for your data, e.g. scatter plot, line graphs, barplots, histograms, qqplots, smooth densities, boxplots, pairplots, heatmaps, etc. c) Mapping Component: Here you need to decide what variable to use as your x-variable and what to use as your y-variable. This is important especially when your dataset is multi-dimensional with several features. d) Scale Component: Here you decide what kind of scales to use, e.g. linear scale, log scale, etc. e) Labels Component: This include things like axes labels, titles, legends, font size to use, etc. f) Ethical Component: Here, you want to make sure your visualization tells the true story. You need to be aware of your actions when cleaning, summarizing, manipulating and producing a data visualization and ensure you aren’t using your visualization to mislead or manipulate your audience. This article will compare the strengths of Python’s Matplotlib and R’s ggplot2 package for analyzing and visualizing weather data. The code will perform the following data visualization tasks: It returns a line graph of the record high and records low temperatures by day of the year over the period 2005–2014. The area between the record high and record low temperatures for each day of the year is shaded.Overlays a scatter of the 2015 data for any points (highs and lows) for which the ten-year record (2005–2014) record high or record low was broken in 2015. It returns a line graph of the record high and records low temperatures by day of the year over the period 2005–2014. The area between the record high and record low temperatures for each day of the year is shaded. Overlays a scatter of the 2015 data for any points (highs and lows) for which the ten-year record (2005–2014) record high or record low was broken in 2015. Dataset: The NOAA dataset used for this project is stored in the file weather_data.csv. This data comes from a subset of the National Centers for Environmental Information (NCEI) Daily Global Historical Climatology Network (GHCN-Daily). The GHCN-Daily is comprised of daily climate records from thousands of land surface stations across the globe. The data was collected from data stations near Ann Arbor, Michigan, United States. The complete code for this article can be downloaded from this repository: https://github.com/bot13956/weather_pattern. import matplotlib.pyplot as pltimport pandas as pdimport numpy as npdf=pd.read_csv('weather_data.csv')df.head() #convert temperature from tenths of degree C to degree Cdf['Data_Value']=0.1*df.Data_Valuedays=list(map(lambda x: x.split('-')[-2]+'-'+x.split('-')[-1], df.Date))years=list(map(lambda x: x.split('-')[0], df.Date))df['Days']=days df['Years']=yearsdf_2005_to_2014=df[(df.Days!='02-29')&(df.Years!='2015')]df_2015=df[(df.Days!='02-29')&(df.Years=='2015')]df_max=df_2005_to_2014.groupby(['Element','Days']).max()df_min = df_2005_to_2014.groupby(['Element','Days']).min()df_2015_max=df_2015.groupby(['Element','Days']).max()df_2015_min = df_2015.groupby(['Element','Days']).min()record_max=df_max.loc['TMAX'].Data_Valuerecord_min=df_min.loc['TMIN'].Data_Valuerecord_2015_max=df_2015_max.loc['TMAX'].Data_Valuerecord_2015_min=df_2015_min.loc['TMIN'].Data_Value plt.figure(figsize=(10,7))plt.plot(np.arange(len(record_max)),record_max, '--k', label="record high")plt.plot(np.arange(len(record_max)),record_min, '-k',label="record low")plt.scatter(np.where(record_2015_min < record_min.values), record_2015_min[record_2015_min < record_min].values,c='b',label='2015 break low')plt.scatter(np.where(record_2015_max > record_max.values), record_2015_max[record_2015_max > record_max].values,c='r',label='2015 break high')plt.xlabel('month',size=14)plt.ylabel('temperature($^\circ C$ )',size=14)plt.xticks(np.arange(0,365,31), ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug', 'Sep','Oct','Nov','Dec'])ax=plt.gca()ax.axis([0,365,-40,40])plt.gca().fill_between(np.arange(0,365), record_min, record_max, facecolor='blue', alpha=0.25)plt.title('Record temperatures for different months between 2005-2014',size=14)plt.legend(loc=0)plt.show() I was wondering, can I produce a similar visualization of the figure above using R’s ggplot2 package? So I decided to perform a similar analysis to see how close I can get with ggplot2. library(tidyverse)library(readr)df<-read.csv("weather_data.csv") #convert temperature from tenths of degree C to degree Cdf$Data_Value = 0.1*df$Data_Value #functions to split date split_function<-function(x)unlist(strsplit(x,'-'))year_function<-function(x)split_function(x)[1]day_function<-function(x)paste(split_function(x[2], split_function(x)[3],sep='-') #create Day and Year columns day<-sapply(as.vector(df$Date),day_function)year<-sapply(as.vector(df$Date),year_function)df<-df%>%mutate(Day=day,Year=year ) #filter leap year and select 10 year observation period: 2005-2014 df_2005_to_2014<-df%>%filter((df$Day!='02-29') (df$Year!='2015'))df_2015<-df%>%filter((df$Day!='02-29')&(df$Year=='2015')) #record min and max for each day of the year for the 2005-2014 period record_max<-df_2005_to_2014%>%group_by(Day)%>%summarize(Max = max(Data_Value),Min=min(Data_Value))%>%.$Maxrecord_min<-df_2005_to_2014%>%group_by(Day)%>%summarize(Max = max(Data_Value),Min=min(Data_Value))%>%.$Min #record min and max for each day of the year for 2015 record_2015_max<-df_2015%>%group_by(Day)%>%summarize(Max = max(Data_Value),Min=min(Data_Value))%>%.$Maxrecord_2015_min<-df_2015%>%group_by(Day)%>%summarize(Max = max(Data_Value),Min=min(Data_Value))%>%.$Min #data frame for the 2005-2014 temperatures y<-c(seq(1,1,length=365),seq(2,2,length=365))y<-replace(replace(y, seq(1,365),'max'),seq(366,730),'min')values<-data.frame(day=c(seq(1,365), seq(1,365)),element=sort(y),Temp=c(record_max,record_min))q<-values%>%mutate(element=factor(element))#data frame for the 2015 temperatures max_index<-which(record_2015_max>record_max)min_index<-which(record_2015_min < record_min)dat15_max<data.frame(max_index=max_index, Tmax=record_2015_max[max_index])dat15_min<-data.frame(min_ndex=min_index, Tmin=record_2015_min[min_index]) q%>%ggplot(aes(day,Temp,color=element))+ geom_line(size=1,show.legend = TRUE)+ geom_point(data=dat15_max, aes(max_index,Tmax,color='max_index'), size=2,show.legend = TRUE)+ geom_point(data=dat15_min, aes(min_index,Tmin,color='min_index'), size=2,show.legend = TRUE)+ scale_colour_manual(labels=c("record high","2015 break high","record low","2015 break low"), values=c('red','purple','blue','green'))+ xlab('Month')+ ylab('Temperature (C)')+ scale_x_continuous(breaks = as.integer(seq(1,335,length=12)), labels=c('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug', 'Sep','Oct','Nov','Dec'))+ ggtitle("Record temperatures between 2005-2014")+ theme( plot.title = element_text(color="black", size=12, hjust=0.5, face="bold"), axis.title.x = element_text(color="black", size=12, face="bold"), axis.title.y = element_text(color="black", size=12, face="bold"), legend.title = element_blank()) Here is the output using R’s ggplot2: I tried my best to produce a visualization using R’s ggplot2 package that is very similar to that produced with Python’s Matplotlib. It seems to me that for this particular project, Matplotlib produces a better and more beautiful visualization compared to R’s ggplot2 package. Using matplotlib, the visualization was produced with fewer effort (lines of code), compared to ggplot2. If you are interested in downloading the source code for Matplotlib and ggplot2 executions, please visit the following Github repository: https://github.com/bot13956/weather_pattern. Please leave feedback comments for suggestions on how to improve the ggplot2 visualization. I am pretty sure the quality could be improved.
[ { "code": null, "e": 433, "s": 172, "text": "Data Visualization is more of an Art than Science. To produce a good visualization, you need to put several pieces of code together for an excellent end result. This tutorial demonstrates how a good data visualization can be produced by analyzing weather ...
Python | Maximum and Minimum value from two lists
28 Feb, 2019 The problem of finding a maximum and minimum values in a list is quite common. But sometimes this problem can be extended in two lists and hence becomes a modified problem. This article discusses shorthands by which this task can be performed easily. Let’s discuss certain ways in which this problem can be solved. Method #1 : Using max() + min() + “+” operatorThe maximum and minimum values can be determined by the conventional max and min function of python and the extension of one to two lists can be dealt using the “+” operator. # Python3 code to demonstrate# maximum and minimum values in two lists # using max() + min() + "+" operator # initializing liststest_list1 = [1, 3, 4, 5, 2, 6]test_list2 = [3, 4, 8, 3, 10, 1] # printing the original listsprint ("The original list 1 is : " + str(test_list1))print ("The original list 2 is : " + str(test_list2)) # using max() + min() + "+" operator# maximum and minimum values in two lists max_all = max(test_list1 + test_list2)min_all = min(test_list1 + test_list2) # printing resultprint ("The maximum of both lists is : " + str(max_all))print ("The minimum of both lists is : " + str(min_all)) The original list 1 is : [1, 3, 4, 5, 2, 6] The original list 2 is : [3, 4, 8, 3, 10, 1] The maximum of both lists is : 10 The minimum of both lists is : 1 Method #2 : Using max() + min() + chain()Another method to perform this particular task is by using the chain function which performs the task similar to the “+” operator but using an iterator, hence faster. # Python3 code to demonstrate# maximum and minimum values in two lists # using max() + min() + "+" operatorfrom itertools import chain # initializing liststest_list1 = [1, 3, 4, 5, 2, 6]test_list2 = [3, 4, 8, 3, 10, 1] # printing the original listsprint ("The original list 1 is : " + str(test_list1))print ("The original list 2 is : " + str(test_list2)) # using max() + min() + "+" operator# maximum and minimum values in two lists max_all = max(chain(test_list1, test_list2))min_all = min(chain(test_list1, test_list2)) # printing resultprint ("The maximum of both lists is : " + str(max_all))print ("The minimum of both lists is : " + str(min_all)) The original list 1 is : [1, 3, 4, 5, 2, 6] The original list 2 is : [3, 4, 8, 3, 10, 1] The maximum of both lists is : 10 The minimum of both lists is : 1 Python list-programs python-list Python Python Programs python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Feb, 2019" }, { "code": null, "e": 343, "s": 28, "text": "The problem of finding a maximum and minimum values in a list is quite common. But sometimes this problem can be extended in two lists and hence becomes a modified problem. Th...
Using Data-Attributes (data-*) in CSS
We can store extra information about elements using data-* attribute. The following examples illustrate CSS data-* attribute. Live Demo <!DOCTYPE html> <html> <head> <style> dl { margin: 2%; } p { width: 60%; background-color: lightgreen; padding: 2%; color: white; text-align: center; } dt { font-weight: bold; } dt:hover { cursor: pointer; } dd { font-style: italic; } </style> </head> <body> <dl> <dt onmouseover="showDescription(this)" data-food-type="beverages">Tea</dt> <dd>Hot Spicy Tea or Ice Lemon Tea </dd> <dt onmouseover="showDescription(this)" data-food-type="snacks">Toast</dt> <dd>Hot Garlic Butter Toast</dd> </dl> <p>(hover over food item)</p> </body> <script> function showDescription(food) { let foodType = food.getAttribute("data-food-type"); document.querySelector('p').textContent = ("We have " + food.innerHTML + " in " + foodType + "."); } </script> </html> This will produce the following result − Live Demo <!DOCTYPE html> <html> <head> <style> section { margin: 8%; box-shadow: inset 0 0 20px red; width: 300px; padding: 2%; } section[data-number='77'] { height: 120px; border-radius: 15px; } section::before { content: attr(data-user); font-size: 1.2em; } section::after { content: attr(data-number); } </style> </head> <body> <section data-number="77" data-user="Client"> <p>Demo Text</p> </section> </body> </html> This will produce the following result −
[ { "code": null, "e": 1313, "s": 1187, "text": "We can store extra information about elements using data-* attribute. The following examples illustrate CSS data-* attribute." }, { "code": null, "e": 1324, "s": 1313, "text": " Live Demo" }, { "code": null, "e": 2103, ...
Z score for Outlier Detection – Python
27 Aug, 2020 Z score is an important concept in statistics. Z score is also called standard score. This score helps to understand if a data value is greater or smaller than mean and how far away it is from the mean. More specifically, Z score tells how many standard deviations away a data point is from the mean. Z score = (x -mean) / std. deviation A normal distribution is shown below and it is estimated that68% of the data points lie between +/- 1 standard deviation.95% of the data points lie between +/- 2 standard deviation99.7% of the data points lie between +/- 3 standard deviation Z score and Outliers:If the z score of a data point is more than 3, it indicates that the data point is quite different from the other data points. Such a data point can be an outlier.For example, in a survey, it was asked how many children a person had.Suppose the data obtained from people is 1, 2, 2, 2, 3, 1, 1, 15, 2, 2, 2, 3, 1, 1, 2 Clearly, 15 is an outlier in this dataset. Let us use calculate the Z score using Python to find this outlier.Step 1: Import necessary libraries import numpy as np Step 2: Calculate mean, standard deviation data = [1, 2, 2, 2, 3, 1, 1, 15, 2, 2, 2, 3, 1, 1, 2]mean = np.mean(data)std = np.std(data)print('mean of the dataset is', mean)print('std. deviation is', std) Output: mean of the dataset is 2.6666666666666665 std. deviation is 3.3598941782277745 Step 3: Calculate Z score. If Z score>3, print it as an outlier. threshold = 3outlier = []for i in data: z = (i-mean)/std if z > threshold: outlier.append(i)print('outlier in dataset is', outlier) Output: outlier in dataset is [15] Conclusion: Z score helps us identify outliers in the data. nidhi_biet statistical-algorithms Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Linear Regression Reinforcement learning Supervised and Unsupervised learning Decision Tree Introduction with example Search Algorithms in AI 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": 54, "s": 26, "text": "\n27 Aug, 2020" }, { "code": null, "e": 355, "s": 54, "text": "Z score is an important concept in statistics. Z score is also called standard score. This score helps to understand if a data value is greater or smaller than mean and how f...
Precision Handling in Python
05 Jul, 2022 Python in its definition allows handling the precision of floating-point numbers in several ways using different functions. Most of them are defined under the “math” module. In this article, we will use high-precision calculations in Python with Decimal in Python. In this example, we will cover some math methods. such as trunc() method, ceil() method, and floor() method. trunc(): This function is used to eliminate all decimal parts of the floating-point number and return the integer without the decimal part. ceil(): This function is used to print the least integer greater than the given number. floor(): This function is used to print the greatest integer smaller than the given integer. Python3 # importing "math" for precision functionimport math # initializing valuea = 3.4536 # using trunc() to print integer after truncatingprint("The integral value of number is : ", end="")print(math.trunc(a)) # using ceil() to print number after ceilingprint("The smallest integer greater than number is : ", end="")print(math.ceil(a)) # using floor() to print number after flooringprint("The greatest integer smaller than number is : ", end="")print(math.floor(a)) Output: The integral value of number is : 3 The smallest integer greater than number is : 4 The greatest integer smaller than number is : 3 In this example, we will see How to Limit Floats to Two Decimal Points in Python. In python float precision to 2 floats in python, and python float precision to 3. There are many ways to set the precision of the floating-point values. Some of them are discussed below. Using “%”:- “%” operator is used to format as well as set precision in python. This is similar to “printf” statement in C programming. Using format():- This is yet another way to format the string for setting precision. Using round(x,n):- This function takes 2 arguments, number, and the number till which we want decimal part rounded. Using “%”:- “%” operator is used to format as well as set precision in python. This is similar to “printf” statement in C programming. Using format():- This is yet another way to format the string for setting precision. Using round(x,n):- This function takes 2 arguments, number, and the number till which we want decimal part rounded. Python3 # Python code to demonstrate precision# and round() # initializing valuea = 3.4536 # using "%" to print value till 2 decimal placesprint("The value of number till 2 decimal place(using %) is : ", end="")print('%.2f' % a) # using format() to print value till 3 decimal placesprint("The value of number till 2 decimal place(using format()) is : ", end="")print("{0:.3f}".format(a)) # using round() to print value till 2 decimal placesprint("The value of number till 2 decimal place(using round()) is : ", end="")print(round(a, 2)) Output : The value of number till 2 decimal place(using %) is : 3.45 The value of number till 2 decimal place(using format()) is : 3.453 The value of number till 2 decimal place(using round()) is : 3.45 rishabk2000 surajkumarguptaintern Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n05 Jul, 2022" }, { "code": null, "e": 317, "s": 52, "text": "Python in its definition allows handling the precision of floating-point numbers in several ways using different functions. Most of them are defined under the “math” module. ...
Count occurrences of a prime number in the prime factorization of every element from the given range
18 Mar, 2022 Given three integers L, R, and P where P is prime, the task is to count the number of times P occurs in the prime factorization of all numbers in the range [L, R].Examples: Input: L = 2, R = 8, P = 2 Output: 7 1 + 0 + 2 + 0 + 1 + 0 + 3 = 7Input: L = 5, R = 25, P = 7 Output: 3 Naive approach: Simply iterate over the range and for each value count how many times P divides that value and sum them up for the result. Time complexity O(R – L).Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <iostream>using namespace std; // Function to return the highest// power of p that divides nint countFactors(int n, int p){ int pwr = 0; while (n > 0 && n % p == 0) { n /= p; pwr++; } return pwr;} // Function to return the count of times p// appears in the prime factors of the// elements from the range [l, r]int getCount(int l, int r, int p){ // To store the required count int cnt = 0; // For every element of the range for (int i = l; i <= r; i++) { // Add the highest power of // p that divides i cnt += countFactors(i, p); } return cnt;} // Driver codeint main(){ int l = 2, r = 8, p = 2; cout << getCount(l, r, p); return 0;} // Java implementation of the approachclass GFG{ // Function to return the highest// power of p that divides nstatic int countFactors(int n, int p){ int pwr = 0; while (n > 0 && n % p == 0) { n /= p; pwr++; } return pwr;} // Function to return the count of times p// appears in the prime factors of the// elements from the range [l, r]static int getCount(int l, int r, int p){ // To store the required count int cnt = 0; // For every element of the range for (int i = l; i <= r; i++) { // Add the highest power of // p that divides i cnt += countFactors(i, p); } return cnt;} // Driver codepublic static void main(String[] args){ int l = 2, r = 8, p = 2; System.out.println(getCount(l, r, p));}} // This code is contributed by Rajput-Ji # Python3 implementation of the approach # Function to return the highest# power of p that divides ndef countFactors(n, p) : pwr = 0; while (n > 0 and n % p == 0) : n //= p; pwr += 1; return pwr; # Function to return the count of times p# appears in the prime factors of the# elements from the range [l, r]def getCount(l, r, p) : # To store the required count cnt = 0; # For every element of the range for i in range(l, r + 1) : # Add the highest power of # p that divides i cnt += countFactors(i, p); return cnt; # Driver codeif __name__ == "__main__" : l = 2; r = 8; p = 2; print(getCount(l, r, p)); # This code is contributed by AnkitRai01 // C# implementation of the approachusing System; class GFG{ // Function to return the highest// power of p that divides nstatic int countFactors(int n, int p){ int pwr = 0; while (n > 0 && n % p == 0) { n /= p; pwr++; } return pwr;} // Function to return the count of times p// appears in the prime factors of the// elements from the range [l, r]static int getCount(int l, int r, int p){ // To store the required count int cnt = 0; // For every element of the range for (int i = l; i <= r; i++) { // Add the highest power of // p that divides i cnt += countFactors(i, p); } return cnt;} // Driver codepublic static void Main(String[] args){ int l = 2, r = 8, p = 2; Console.WriteLine(getCount(l, r, p));}} // This code is contributed by 29AjayKumar <script> // Javascript implementation of the approach // Function to return the highest// power of p that divides nfunction countFactors(n, p){ let pwr = 0; while (n > 0 && n % p == 0) { n /= p; pwr++; } return pwr;} // Function to return the count of times p// appears in the prime factors of the// elements from the range [l, r]function getCount(l, r, p){ // To store the required count let cnt = 0; // For every element of the range for (let i = l; i <= r; i++) { // Add the highest power of // p that divides i cnt += countFactors(i, p); } return cnt;} // Driver code let l = 2, r = 8, p = 2; document.write(getCount(l, r, p)); </script> 7 Auxiliary Space: O(1) Efficient approach: Count the values which are divisible by P, P2, P3, ..., Px in the range [L, R] where x is the largest power of P such that Px lies within the upper bound (Px ≤ N). Each iteration cost O(1) time thus time complexity becomes O(x) where x = (log(R) / log(P)).Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <iostream>using namespace std; // Function to return the count of times p// appears in the prime factors of the// elements from the range [l, r]int getCount(int l, int r, int p){ // To store the required count int cnt = 0; int val = p; while (1) { // Number of values in the range [0, r] // that are divisible by val int a = r / val; // Number of values in the range [0, l - 1] // that are divisible by val int b = (l - 1) / val; // Increment the power of the val val *= p; // (a - b) is the count of numbers in the // range [l, r] that are divisible by val if (a - b) { cnt += (a - b); } // No values that are divisible by val // thus exiting from the loop else break; } return cnt;} // Driver codeint main(){ int l = 2, r = 8, p = 2; cout << getCount(l, r, p); return 0;} // Java implementation of the approachimport java.util.*; class GFG{ // Function to return the count of times p// appears in the prime factors of the// elements from the range [l, r]static int getCount(int l, int r, int p){ // To store the required count int cnt = 0; int val = p; while (true) { // Number of values in the range [0, r] // that are divisible by val int a = r / val; // Number of values in the range [0, l - 1] // that are divisible by val int b = (l - 1) / val; // Increment the power of the val val *= p; // (a - b) is the count of numbers in the // range [l, r] that are divisible by val if ((a - b) > 0) { cnt += (a - b); } // No values that are divisible by val // thus exiting from the loop else break; } return cnt;} // Driver codepublic static void main(String[] args){ int l = 2, r = 8, p = 2; System.out.println(getCount(l, r, p));}} // This code is contributed by 29AjayKumar # Python3 implementation of the approach # Function to return the count of times p# appears in the prime factors of the# elements from the range [l, r]def getCount(l, r, p): # To store the required count cnt = 0; val = p; while (True): # Number of values in the range [0, r] # that are divisible by val a = r // val; # Number of values in the range [0, l - 1] # that are divisible by val b = (l - 1) // val; # Increment the power of the val val *= p; # (a - b) is the count of numbers in the # range [l, r] that are divisible by val if (a - b): cnt += (a - b); # No values that are divisible by val # thus exiting from the loop else: break; return int(cnt); # Driver Codel = 2;r = 8;p = 2; print(getCount(l, r, p)); # This code is contributed by princiraj // C# implementation of the approachusing System; class GFG{ // Function to return the count of times p// appears in the prime factors of the// elements from the range [l, r]static int getCount(int l, int r, int p){ // To store the required count int cnt = 0; int val = p; while (true) { // Number of values in the range [0, r] // that are divisible by val int a = r / val; // Number of values in the range [0, l - 1] // that are divisible by val int b = (l - 1) / val; // Increment the power of the val val *= p; // (a - b) is the count of numbers in the // range [l, r] that are divisible by val if ((a - b) > 0) { cnt += (a - b); } // No values that are divisible by val // thus exiting from the loop else break; } return cnt;} // Driver codepublic static void Main(String[] args){ int l = 2, r = 8, p = 2; Console.WriteLine(getCount(l, r, p));}} // This code is contributed by PrinciRaj1992 <script>// Javascript implementation of the approach // Function to return the count of times p// appears in the prime factors of the// elements from the range [l, r]function getCount(l, r, p){ // To store the required count let cnt = 0; let val = p; while (1) { // Number of values in the range [0, r] // that are divisible by val let a = parseInt(r / val); // Number of values in the range [0, l - 1] // that are divisible by val let b = parseInt((l - 1) / val); // Increment the power of the val val *= p; // (a - b) is the count of numbers in the // range [l, r] that are divisible by val if (a - b) { cnt += (a - b); } // No values that are divisible by val // thus exiting from the loop else break; } return cnt;} // Driver code let l = 2, r = 8, p = 2; document.write(getCount(l, r, p)); </script> 7 Auxiliary Space: O(1) ankthon Rajput-Ji 29AjayKumar princiraj1992 souravmahato348 rishavmahato348 gabaa406 manikarora059 abhishek0719kadiyan subhamkumarm348 Prime Number prime-factor Competitive Programming Mathematical Mathematical Prime Number Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Mar, 2022" }, { "code": null, "e": 202, "s": 28, "text": "Given three integers L, R, and P where P is prime, the task is to count the number of times P occurs in the prime factorization of all numbers in the range [L, R].Examples: " ...
SQL Injection
18 Jan, 2018 SQL injection is a technique used to exploit user data through web page inputs by injecting SQL commands as statements. Basically, these statements can be used to manipulate the application’s web server by malicious users. SQL injection is a code injection technique that might destroy your database. SQL injection is one of the most common web hacking techniques. SQL injection is the placement of malicious code in SQL statements, via web page input. Exploitation of SQL Injection in Web Applications Web servers communicate with database servers anytime they need to retrieve or store user data. SQL statements by the attacker are designed so that they can be executed while the web-server is fetching content from the application server.It compromises the security of a web application. Example of SQL InjectionSuppose we have an application based on student records. Any student can view only his or her own records by entering a unique and private student ID. Suppose we have a field like below:Student id: And the student enters the following in the input field:12222345 or 1=1. So this basically translates to : SELECT * from STUDENT where STUDENT-ID == 12222345 or 1 = 1 Now this 1=1 will return all records for which this holds true. So basically, all the student data is compromised. Now the malicious user can also delete the student records in a similar fashion. Consider the following SQL query. SELECT * from USER where USERNAME = “” and PASSWORD=”” Now the malicious can use the ‘=’ operator in a clever manner to retrieve private and secure user information. So instead of the above-mentioned query the following query when executed, retrieves protected data, not intended to be shown to users. Select * from User where (Username = “” or 1=1) AND (Password=”” or 1=1). Since 1=1 always holds true, user data is compromised. Impact of SQL InjectionThe hacker can retrieve all the user-data present in the database such as user details, credit card information, social security numbers and can also gain access to protected areas like the administrator portal. It is also possible to delete the user data from the tables.Nowadays, all online shopping applications, bank transactions use back-end database servers. So in-case the hacker is able to exploit SQL injection, the entire server is compromised. Preventing SQL Injection User Authentication: Validating input from the user by pre-defining length, type of input, of the input field and authenticating the user. Restricting access privileges of users and defining as to how much amount of data any outsider can access from the database. Basically, user should not be granted permission to access everything in the database. Do not use system administrator accounts. Basic SQL Injection and Mitigation with Example DBMS-SQL sql-injection DBMS SQL Web technologies Questions DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. CTE in SQL Difference between Clustered and Non-clustered index Introduction of B-Tree Data Preprocessing in Data Mining SQL | Views SQL | DDL, DQL, DML, DCL and TCL Commands How to find Nth highest salary from a table CTE in SQL SQL | ALTER (RENAME) How to Update Multiple Columns in Single Update Statement in SQL?
[ { "code": null, "e": 52, "s": 24, "text": "\n18 Jan, 2018" }, { "code": null, "e": 275, "s": 52, "text": "SQL injection is a technique used to exploit user data through web page inputs by injecting SQL commands as statements. Basically, these statements can be used to manipulate ...
How to run Python functions from command line?
To run this function from the command line we can use the -c (command) argument as follows: $ python -c 'import foobar; print foobar.sayHello()' Alternatively, we can also write: $ python -c 'from foobar import *; print sayHello()' Or like this $ python -c 'from foobar import sayHello; print sayHello()' OUTPUT Hello
[ { "code": null, "e": 1279, "s": 1187, "text": "To run this function from the command line we can use the -c (command) argument as follows:" }, { "code": null, "e": 1332, "s": 1279, "text": "$ python -c 'import foobar; print foobar.sayHello()'" }, { "code": null, "e": ...
How to Convert From BLOB to Text in MySQL?
28 Nov, 2021 In this article, we will see the conversion of a BLOB to TEXT in MySQL. BLOB: It stands for Binary Large Object. It is a kind of data type in MySQL that can store files or images in the database in binary format. It has four types i.e TINYBLOB, BLOB, MEDIUMBLOB, and LONGBLOB. All four types are similar, the only difference among them is the amount of data they can hold. AS the name suggests, LONGBLOB can hold the maximum amount of data and TINYBLOB can hold the least amount of data among the four types. TEXT datatype in MySQL is used for storing long text strings in the database. It is just like VARCHAR. In order to convert BLOB to TEXT, we will use the CONVERT statement. Syntax: CONVERT( column_name using utf8); utf8 is the way of encoding Unicode characters. It is recommended to use ut8 while creating web pages and databases. For demonstration, follow the below steps: Step 1: Create a database we can use the following command to create a database called geeks. Query: CREATE DATABASE geeks; Step 2: Use database Use the below SQL statement to switch the database context to geeks: Query: USE geeks; Step 3: Table definition We have demo_table in our geek’s database. Query: CREATE TABLE demo_table( NAME VARCHAR(20), AGE INT, CITY VARCHAR(20), FILE BLOB); Step 4: Insert data into a table Query: INSERT INTO demo_table VALUES ('Romy', 21, 'Delhi', 'My name is romy kumari, I am 21 yrs old'), ('Pushkar', 22, 'Delhi', 'My name is Pushkar jha, I am 22 yrs old'), ('Rinkle', 22, 'Punjab', 'My name is Rinkle Arora, I am 22 yrs old'), ('Ayushi', 22, 'Patna', 'My name is Ayushi choudhary, I am 22 yrs old'); Step 5: View the content Execute the below query to see the content of the table Query: SELECT * FROM demo_table; Output: We can see that content of the FILE column is in encoded format. Step 6: Conversion from BLOB to TEXT. Query: SELECT convert(File using utf8) from demo_table; If you want to update the BLOB datatype column to the TEXT datatype column. Follow these steps: Alter the table and add a column having data type TEXT. Add content to that column after converting BLOB data to TEXT date. Drop BLOB column. Step 1: Add column Syntax: ALTER Table demo_table ADD COLUMN AFTER_CONERSION TEXT; Step 2: Add content to column UPDATE demo_table SET AFTER_CONERSION = CONVERT (FILE using utf8); Step 3: Drop BLOB column ALTER TABLE demo_table DROP COLUMN FILE; mysql Picked SQL-Query SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? Window functions in SQL What is Temporary Table in SQL? SQL using Python SQL | Sub queries in From Clause SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter RANK() Function in SQL Server SQL Query to Convert VARCHAR to INT SQL Query to Compare Two Dates SQL | DROP, TRUNCATE
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Nov, 2021" }, { "code": null, "e": 100, "s": 28, "text": "In this article, we will see the conversion of a BLOB to TEXT in MySQL." }, { "code": null, "e": 403, "s": 100, "text": "BLOB: It stands for Binary Large O...
SQL – ALTERNATE KEY
21 Jul, 2021 Keys are an important part of any Relational Database. There are various types of keys and among one of these is the Alternate Key. The keys that contain all the properties needed to become a Candidate Key are known as Alternate Keys. These are basically secondary Candidate Keys that can uniquely identify a row in a table. So, Alternate Keys are also sometimes known as “Secondary Keys”. In other words, we can define the Alternate key as the set of Candidate Keys other than the Primary Key. There can be many Candidate Keys for a given table and out of all these the Database Administrators selects only one of these as the Primary Key. Hence, the other Candidate Keys which are not used as a Primary Key are the “Alternate Keys”. Some important points about Alternate Keys are as follows : A Primary Key can’t be an Alternate Key. For a table with a single Candidate Key which has to be the Primary Key will not contain any Alternate Key.A Foreign Key can’t be an Alternate Key as it is only used to reference another table.The alternate Key should be unique.An Alternate Key can be a set of a single attribute or multiple attributes.It can be NULL as well. A Primary Key can’t be an Alternate Key. For a table with a single Candidate Key which has to be the Primary Key will not contain any Alternate Key. A Foreign Key can’t be an Alternate Key as it is only used to reference another table. The alternate Key should be unique. An Alternate Key can be a set of a single attribute or multiple attributes. It can be NULL as well. In this article, we are going to see how to create an ALTERNATE Key in SQL using sample tables as shown. Sample Input : Consider the Table Customer Information which consists data about customers who bought products from an E-Commerce site. This table is referencing the Product Information table to know about the details of the product bought by a customer. The common attribute used for referencing is “Product ID” which is also termed as Foreign Key. In the Customer Information Table, Customer ID, Pan Number, Email Address are unique as it can uniquely identify a row in the given table. PAN Number is unique for every person and Customer ID is also a unique number provided by E-Commerce sites to distinguish among tons of customers registered in their shopping site. A user can register on the shopping site using only a single E-Mail Address. If he/she wants to create another account using the same E-Mail will show a message, “An account with this E-Mail Address already exists, Please Login”. So, every consumer will have a unique E-Mail Address. Hence, all these attributes can uniquely identify a row in a table. The candidate key set for the above table is : { Customer ID, Pan Number, Email Address } Say, the Data Base Administrator of this E-Commerce site picked Customer ID as the Primary Key. Therefore, PAN Number and E-Mail Address will be Alternate Keys or Secondary Keys. Alternate Key has all the properties to become a Primary Key and so is an alternate option. ALTERNATE Keys in SQL are defined using the SQL constraint UNIQUE. UNIQUE(col_name(s)) col_name(s): The name of the column(s) in the table which need to be unique. BASIC SQL QUERY : 1. Creating a Database CREATE DATABASE database_name 2. Creating a Table CREATE TABLE Table_name( col_1 TYPE col_1_constraint, col_2 TYPE col_2 constraint, col_3 TYPE UNIQUE, col_4 TYPE REFERENCES Table_Name(col_name), ..... ) col: The name of the columns. TYPE: Data type whether an integer, variable character, etc col_constraint: Constraints in SQL like PRIMARY KEY, NOT NULL, UNIQUE, REFERENCES, etc. col_3: Definining an ALTERNATE KEY using constraint UNIQUE col_4: Definining an FOREIGN KEY using constraint REFERENCES 3. Inserting into a Table INSERT INTO Table_name VALUES(val_1, val_2, val_3, ..........) val: Values in particular column 4. View The Table SELECT * FROM Table_name Output : Product Table Customer Table A pictorial view of all the keys present in the table is shown below : KEYS sagar0719kumar Picked SQL-Functions SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n21 Jul, 2021" }, { "code": null, "e": 444, "s": 54, "text": "Keys are an important part of any Relational Database. There are various types of keys and among one of these is the Alternate Key. The keys that contain all the properties n...
Longest subarray with all elements same
14 May, 2021 Given an array arr[] of size N, the task is to find the largest subarray which consists of all equal elements.Examples: Input: arr[] = {1, 1, 2, 2, 2, 3, 3}; Output: 3 Explanation: Longest subarray with equal elements is {2, 2, 2}Input: arr[] = {1, 1, 2, 2, 2, 3, 3, 3, 3}; Output: 4 Explanation: Longest subarray with equal elements is {3, 3, 3, 3} Approach: The idea is to traverse the array and check that the current element is equal to the previous element or not. If yes then increment the length of the longest subarray by 1. Otherwise, the current longest subarray is equal to 1. Also, update the longest subarray with equal elements at each step of the iteration.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to find largest// subarray with all equal elements. #include <bits/stdc++.h>using namespace std; // Function to find largest sub// array with all equal elements.int subarray(int arr[], int n){ int ans = 1, temp = 1; // Traverse the array for (int i = 1; i < n; i++) { // If element is same as // previous increment temp value if (arr[i] == arr[i - 1]) { ++temp; } else { ans = max(ans, temp); temp = 1; } } ans = max(ans, temp); // Return the required answer return ans;} // Driver codeint main(){ int arr[] = { 2, 2, 1, 1, 2, 2, 2, 3, 3 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call cout << subarray(arr, n); return 0;} // Java program to find largest// subarray with all equal elements.import java.util.*; class GFG{ // Function to find largest sub// array with all equal elements.static int subarray(int arr[], int n){ int ans = 1, temp = 1; // Traverse the array for(int i = 1; i < n; i++) { // If element is same as // previous increment temp value if (arr[i] == arr[i - 1]) { ++temp; } else { ans = Math.max(ans, temp); temp = 1; } } ans = Math.max(ans, temp); // Return the required answer return ans;} // Driver codepublic static void main(String[] args){ int arr[] = { 2, 2, 1, 1, 2, 2, 2, 3, 3 }; int n = arr.length; // Function call System.out.print(subarray(arr, n));}} // This code is contributed by AbhiThakur # Python3 program to find largest# subarray with all equal elements. # Function to find largest sub# array with all equal elements.def subarray(arr, n): ans, temp = 1, 1 # Traverse the array for i in range(1, n): # If element is same as previous # increment temp value if arr[i] == arr[i - 1]: temp = temp + 1 else: ans = max(ans, temp) temp = 1 ans = max(ans, temp) # Return the required answer return ans # Driver codearr = [ 2, 2, 1, 1, 2, 2, 2, 3, 3 ]n = len(arr) # Function callprint(subarray(arr, n)) # This code is contributed by jrishabh99 // C# program to find largest// subarray with all equal elements.using System;class GFG{ // Function to find largest sub// array with all equal elements.static int subarray(int[] arr, int n){ int ans = 1, temp = 1; // Traverse the array for(int i = 1; i < n; i++) { // If element is same as // previous increment temp value if (arr[i] == arr[i - 1]) { ++temp; } else { ans = Math.Max(ans, temp); temp = 1; } } ans = Math.Max(ans, temp); // Return the required answer return ans;} // Driver codepublic static void Main(){ int[] arr = { 2, 2, 1, 1, 2, 2, 2, 3, 3 }; int n = arr.Length; // Function call Console.Write(subarray(arr, n));}} // This code is contributed by Nidhi_biet <script> // Javascript program to find largest// subarray with all equal elements. // Function to find largest sub// array with all equal elements.function subarray(arr, n){ var ans = 1, temp = 1; // Traverse the array for (var i = 1; i < n; i++) { // If element is same as // previous increment temp value if (arr[i] == arr[i - 1]) { ++temp; } else { ans = Math.max(ans, temp); temp = 1; } } ans = Math.max(ans, temp); // Return the required answer return ans;} // Driver codevar arr = [ 2, 2, 1, 1, 2, 2, 2, 3, 3 ];var n = arr.length; // Function calldocument.write( subarray(arr, n)); </script> 3 Time Complexity: O(N) abhaysingh290895 nidhi_biet jrishabh99 rrrtnx sweetyty subsequence Arrays Mathematical Arrays Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n14 May, 2021" }, { "code": null, "e": 176, "s": 54, "text": "Given an array arr[] of size N, the task is to find the largest subarray which consists of all equal elements.Examples: " }, { "code": null, "e": 408, "s": 1...
Number guessing game in C
01 Jul, 2022 Given an integer N. A number guessing game is a simple guessing game where a user is supposed to guess a number between 0 and N in a maximum of 10 attempts. The game will end after 10 attempts and if the player failed to guess the number, and then he loses the game. Examples: N = 100Number chosen: 20 Machine: Guess a number between 1 and NPlayer: 30Machine: Lower number please!Player: 15Machine: Higher number please!Player: 20Machine: You guessed the number in 3 attemptsNow, terminate the game. Approach: The following steps can be followed to design the game: Generate a random number between 0 and N. Then iterate from 1 to 10 and check if the input number is equal to the assumed number or not. If yes, then the player wins the game. Otherwise, terminate the game after 10 attempts. Below is the implementation of the above approach: C // C program for the above approach#include <math.h>#include <stdio.h>#include <stdlib.h>#include <time.h> // Function that generate a number in// the range [1, N] and checks if the// generated number is the same as the// guessed number or notvoid guess(int N){ int number, guess, numberofguess = 0; //Seed random number generator srand(time(NULL)); // Generate a random number number = rand() % N; printf("Guess a number between" " 1 and %d\n", N); // Using a do-while loop that will // work until user guesses // the correct number do { if (numberofguess > 9) { printf("\nYou Loose!\n"); break; } // Input by user scanf("%d", &guess); // When user guesses lower // than actual number if (guess > number) { printf("Lower number " "please!\n"); numberofguess++; } // When user guesses higher // than actual number else if (number > guess) { printf("Higher number" " please!\n"); numberofguess++; } // Printing number of times // user has taken to guess // the number else printf("You guessed the" " number in %d " "attempts!\n", numberofguess); } while (guess != number);} // Driver Codeint main(){ int N = 100; // Function call guess(N); return 0;} Output: 7nf2fq8bwubgskh2p1tqxqqmxy2m1q0lln34anu2 Numbers Technical Scripter 2020 C Language C Programs Randomized Technical Scripter Numbers Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n01 Jul, 2022" }, { "code": null, "e": 321, "s": 54, "text": "Given an integer N. A number guessing game is a simple guessing game where a user is supposed to guess a number between 0 and N in a maximum of 10 attempts. The game will end...
Printing pre and post visited times in DFS of a graph
27 Sep, 2021 Depth First Search (DFS) marks all the vertices of a graph as visited. So for making DFS useful, some additional information can also be stored. For instance, the order in which the vertices are visited while running DFS. Pre-visit and Post-visit numbers are the extra information that can be stored while running a DFS on a graph and which turns out to be really useful. Pre-visit number tells the time at which the node gets into the recursion stack and Post-visit number tells the time at which the node comes out from recursion stack of DFS. Example: The numbers written in brackets denote [Pre-visit number, Post-visit number]. Pre and Post numbers are widely used in graph algorithms. For example, they can be used to find out whether a particular node lies in the sub-tree of another node. To find whether u lies in the sub-tree of v or not we just compare the pre and post number of u and v. If pre[u] > pre[v] and post[u] < post[v] then u lies in the sub-tree of v otherwise not. You can see above example for more clarification. Pre-visit and Post-visit numbers can be found out by simple DFS. We will take two arrays one for storing pre numbers and one for post numbers and by taking a variable which will keep track of the time. The implementation of the same is given below: C++ Java Python3 C# Javascript #include <bits/stdc++.h>using namespace std; // Variable to keep track of timeint Time = 1; // Function to perform DFS starting from node uvoid dfs(int u, vector<vector<int>> aList, vector<int> &pre, vector<int> &post, vector<int> &vis){ // Storing the pre number whenever // the node comes into recursion stack pre[u] = Time; // Increment time Time++; vis[u] = 1; for(int v : aList[u]) { if (vis[v] == 0) dfs(v, aList, pre, post, vis); } // Storing the post number whenever // the node goes out of recursion stack post[u] = Time; Time++;} // Driver Code int main(){ // Number of nodes in graph int n = 6; // Adjacency list vector<vector<int>> aList(n + 1); vector<int> pre(n + 1); vector<int> post(n + 1); // Visited array vector<int> vis(n + 1); // Edges aList[1].push_back(2); aList[2].push_back(1); aList[2].push_back(4); aList[4].push_back(2); aList[1].push_back(3); aList[3].push_back(1); aList[3].push_back(4); aList[4].push_back(3); aList[3].push_back(5); aList[5].push_back(3); aList[5].push_back(6); aList[6].push_back(5); // DFS starting at Node 1 dfs(1, aList, pre, post, vis); // Number of nodes in graph for(int i = 1; i <= n; i++) cout << "Node " << i << " Pre number " << pre[i] << " Post number " << post[i] << endl; return 0;} // This code is contributed by divyesh072019 import java.util.*;public class GFG { // Variable to keep track of time static int time = 1; // Function to perform DFS starting from node u static void dfs(int u, ArrayList<ArrayList<Integer> > aList, int pre[], int post[], int vis[]) { // Storing the pre number whenever // the node comes into recursion stack pre[u] = time; // Increment time time++; vis[u] = 1; for (int v : aList.get(u)) { if (vis[v] == 0) dfs(v, aList, pre, post, vis); } // Storing the post number whenever // the node goes out of recursion stack post[u] = time; time++; } // Driver code public static void main(String args[]) { // Number of nodes in graph int n = 6; // Adjacency list ArrayList<ArrayList<Integer> > aList = new ArrayList<ArrayList<Integer> >(n + 1); for (int i = 1; i <= n; i++) { ArrayList<Integer> list = new ArrayList<>(); aList.add(list); } aList.add(new ArrayList<Integer>()); int pre[] = new int[n + 1]; int post[] = new int[n + 1]; // Visited array int vis[] = new int[n + 1]; // Edges aList.get(1).add(2); aList.get(2).add(1); aList.get(2).add(4); aList.get(4).add(2); aList.get(1).add(3); aList.get(3).add(1); aList.get(3).add(4); aList.get(4).add(3); aList.get(3).add(5); aList.get(5).add(3); aList.get(5).add(6); aList.get(6).add(5); // DFS starting at Node 1 dfs(1, aList, pre, post, vis); // Number of nodes in graph for (int i = 1; i <= n; i++) System.out.println("Node " + i + " Pre number " + pre[i] + " Post number " + post[i]); }} # Variable to keep track of timetime = 1 # Function to perform DFS starting# from node udef dfs(u, aList, pre, post, vis): global time # Storing the pre number whenever # the node comes into recursion stack pre[u] = time # Increment time time += 1 vis[u] = 1 for v in aList[u]: if (vis[v] == 0): dfs(v, aList, pre, post, vis) # Storing the post number whenever # the node goes out of recursion stack post[u] = time time += 1 # Driver codeif __name__=='__main__': # Number of nodes in graph n = 6 # Adjacency list aList = [[] for i in range(n + 1)] pre = [0 for i in range(n + 1)] post = [0 for i in range(n + 1)] # Visited array vis = [0 for i in range(n + 1)] # Edges aList[1].append(2) aList[2].append(1) aList[2].append(4) aList[4].append(2) aList[1].append(3) aList[3].append(1) aList[3].append(4) aList[4].append(3) aList[3].append(5) aList[5].append(3) aList[5].append(6) aList[6].append(5) # DFS starting at Node 1 dfs(1, aList, pre, post, vis) # Number of nodes in graph for i in range(1, n + 1): print("Node " + str(i) + " Pre number " + str(pre[i]) + " Post number " + str(post[i])) # This code is contributed by rutvik_56 using System;using System.Collections;using System.Collections.Generic; class GFG{ // Variable to keep track of timestatic int time = 1; // Function to perform DFS starting from node ustatic void dfs(int u, ArrayList aList, int []pre, int []post, int []vis){ // Storing the pre number whenever // the node comes into recursion stack pre[u] = time; // Increment time time++; vis[u] = 1; foreach(int v in (ArrayList)aList[u]) { if (vis[v] == 0) dfs(v, aList, pre, post, vis); } // Storing the post number whenever // the node goes out of recursion stack post[u] = time; time++;} // Driver codepublic static void Main(string []args){ // Number of nodes in graph int n = 6; // Adjacency list ArrayList aList = new ArrayList(n + 1); for(int i = 1; i <= n; i++) { ArrayList list = new ArrayList(); aList.Add(list); } aList.Add(new ArrayList()); int []pre = new int[n + 1]; int []post = new int[n + 1]; // Visited array int []vis = new int[n + 1]; // Edges ((ArrayList)aList[1]).Add(2); ((ArrayList)aList[2]).Add(1); ((ArrayList)aList[2]).Add(4); ((ArrayList)aList[4]).Add(2); ((ArrayList)aList[1]).Add(3); ((ArrayList)aList[3]).Add(1); ((ArrayList)aList[3]).Add(4); ((ArrayList)aList[4]).Add(3); ((ArrayList)aList[3]).Add(5); ((ArrayList)aList[5]).Add(3); ((ArrayList)aList[5]).Add(6); ((ArrayList)aList[6]).Add(5); // DFS starting at Node 1 dfs(1, aList, pre, post, vis); // Number of nodes in graph for(int i = 1; i <= n; i++) Console.WriteLine("Node " + i + " Pre number " + pre[i] + " Post number " + post[i]);}} // This code is contributed by pratham76 <script> // Variable to keep track of time let time = 1; // Function to perform DFS starting // from node u function dfs(u, aList, pre, post, vis) { // Storing the pre number whenever // the node comes into recursion stack pre[u] = time; // Increment time time += 1; vis[u] = 1; for(let v = 0; v < aList[u].length; v++) { if (vis[aList[u][v]] == 0) dfs(aList[u][v], aList, pre, post, vis); } // Storing the post number whenever // the node goes out of recursion stack post[u] = time; time += 1; } // Number of nodes in graph let n = 6; // Adjacency list let aList = []; for(let i = 0; i < (n + 1); i++) { aList.push([]); } let pre = new Array(n+1); let post = new Array(n+1); pre.fill(0); post.fill(0); // Visited array let vis = new Array(n+1); vis.fill(0); // Edges aList[1].push(2); aList[2].push(1); aList[2].push(4); aList[4].push(2); aList[1].push(3); aList[3].push(1); aList[3].push(4); aList[4].push(3); aList[3].push(5); aList[5].push(3); aList[5].push(6); aList[6].push(5); // DFS starting at Node 1 dfs(1, aList, pre, post, vis); // Number of nodes in graph for(let i = 1; i < n + 1; i++) { document.write("Node " + i + " Pre number " + pre[i] + " Post number " + post[i] + "</br>") } // This code is contributed by suresh07.</script> Node 1 Pre number 1 Post number 12 Node 2 Pre number 2 Post number 11 Node 3 Pre number 4 Post number 9 Node 4 Pre number 3 Post number 10 Node 5 Pre number 5 Post number 8 Node 6 Pre number 6 Post number 7 rutvik_56 pratham76 divyesh072019 suresh07 DFS Competitive Programming Graph Java Programs DFS Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n27 Sep, 2021" }, { "code": null, "e": 277, "s": 54, "text": "Depth First Search (DFS) marks all the vertices of a graph as visited. So for making DFS useful, some additional information can also be stored. For instance, the order in wh...
GATE | GATE-CS-2007 | Question 85
27 Sep, 2021 Define the connective * for the Boolean variables X and Y as: X * Y = XY + X’ Y’. Let Z = X * Y. Consider the following expressions P, Q and R. P: X = Y⋆Z Q: Y = X⋆Z R: X⋆Y⋆Z=1 Which of the following is TRUE?(A) Only P and Q are valid(B) Only Q and R are valid.(C) Only P and R are valid.(D) All P, Q, R are valid.Answer: (D)Explanation: * is nothing but working as EX NOR here.Explanation: P: X= Y * Z =(Y XOR Z)’ =YZ + Y’Z’ =Y(XY + X’Y’)+Y’(XY+X’Y’)’ =XY+Y’((Y XOR X)’)’ =XY+Y’(Y XOR X) =XY+Y’(Y’X+X’Y) =XY+Y’X =X(Y+Y’) =X Q: Y=X*Z =(X XOR Z)’ =X(XY + X’Y’) + X’(XY + X’Y’)’ =XY+X’(X’Y+XY’) =XY+X’Y =Y R: X * Y *Z WE HAVE SEEN FROM P Y*Z =X SO X * X NOT(X XOR X)=X’X’+XX 1 NOT(X XOR X)=X’X’+XX 1 SO ALL P,Q,R ARE CORRECT ANS IS (D) Boolean Algebra and Identities | GATE PYQs with Rishabh Setiya | GeeksforGeeks GATE - YouTubeGeeksforGeeks GATE Computer Science17.5K subscribersBoolean Algebra and Identities | GATE PYQs with Rishabh Setiya | GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0015:57 / 22:24•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=mDkgr_tIfYc" 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 GATE-CS-2007 GATE-GATE-CS-2007 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n27 Sep, 2021" }, { "code": null, "e": 151, "s": 54, "text": "Define the connective * for the Boolean variables X and Y as: X * Y = XY + X’ Y’. Let Z = X * Y." }, { "code": null, "e": 233, "s": 151, "text": "Consider...
Java Program to Find the Normal and Trace of a Matrix
23 May, 2022 For a given 2D matrix, the purpose is to find the Trace and Normal of the matrix. Normal of a matrix is defined as the square root of the sum of squares of all the elements of the matrix. Trace of a given square matrix is defined as the sum of all the elements in the diagonal. Examples : Input : matrix[][] = {{1, 4, 4}, {2, 3, 7}, {0, 5, 1}}; Output : Normal = 11 Trace = 5 Explanation : Normal = sqrt(1*1+ 4*4 + 4*4 + 2*2 + 3*3 + 7*7 + 0*0 + 5*5 + 1*1) = 11 Trace = 1+3+1 = 5 Input :matrix[][] = {{8, 9, 11}, {0, 1, 15}, {4, 10, -7}}; Output : Normal = 25 Trace = 2 Explanation : Normal = sqrt(8*8 +9*9 + 11*11 + 0*0 + 1*1 + 15*15 + 4*4 + 10*10 + -7*-7) = 25 Trace = (8+1-7) = 2 Example: Java // Java program to find the trace// and normal of the given matrix import java.io.*; class geeksforgeeks { // Dimension of the given matrix static int max = 50; // Finds Normal of the given // matrix of size N x N static int Normal(int matrix[][], int N) { // Initializing sum int s = 0; for (int j = 0; j < N; j++) for (int k = 0; k < N; k++) s += matrix[j][k] * matrix[j][k]; return (int)Math.sqrt(s); } // Finds trace of the given // matrix of size N x N static int Trace(int matrix[][], int N) { int s = 0; for (int j = 0; j < N; j++) s += matrix[j][j]; return s; } // The Driver code public static void main(String[] args) { int matrix[][] = { { 2, 3, 5, 6, 7 }, { 8, 9, 10, 11, 12 }, { 13, 14, 15, 16, 17 }, { 18, 1, 3, 0, 6 }, { 7, 8, 11, 8, 11 }, }; System.out.println("Trace of the Matrix is: " + Trace(matrix, 5)); System.out.println("Normal of the Matrix is: " + Normal(matrix, 5)); }} Trace of the Matrix is: 37 Normal of the Matrix is: 50 Time Complexity: O(N*N), as we are using nested loops for traversing the matrix. Auxiliary Space: O(1), as we are not using any extra space. rohitsingh07052 java-basics Java Java Programs Mathematical Mathematical 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 Stream In Java Initializing a List in Java Java Programming Examples Convert a String to Character Array in Java Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 28, "s": 0, "text": "\n23 May, 2022" }, { "code": null, "e": 110, "s": 28, "text": "For a given 2D matrix, the purpose is to find the Trace and Normal of the matrix." }, { "code": null, "e": 216, "s": 110, "text": "Normal of a matrix is de...
How to Adjust the Position of a Matplotlib Colorbar?
23 Nov, 2021 A colorbar is a bar that has various colors in it and is placed along the sides of the Matplotlib chart. It is the legend for colors shown in the chart. By default, the position of the Matplotlib color bar is on the right side. The position of the Matplotlib color bar can be changed according to our choice by using the functions from Matplotlib AxesGrid Toolkit. The placing of inset axes is similar to that of legend, the position is modified by providing location options concerning the parent box. Syntax: fig.colorbar(cm.ScalarMappable(norm=norm, cmap=cmap), ax=ax) To install the matplotlib colorbar directly execute the following command on Jupyter Notebook or Visual Studio Code to get the results, Matplotlib-colorbar package is installed in order to generate using the colorbar argument. Here, matplotlib.pyplot is used to create a colorbar in a simpler way. pip install matplotlib-colorbar Installation of Matplotlib Colorbar Another way to create a colorbar using Matplotlib is by importing the matplotlib package and then creating the colorbar. Python3 # Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LogNorm # specify dimensions of colorbar using random moduleZ = np.random.rand(5, 20) fig, ax0 = plt.subplots()ax0.pcolor(Z) ax0.set_title('Matplotlib-colorbar')plt.show() Output: Example 1: Position of Matplotlib colorbar on Right Side Generating a matplotlib chart where the colorbar is positioned on the right side of the chart. Python3 # Import packages necessary to create colorbarimport numpy as npimport matplotlib.pyplot as pltfrom mpl_toolkits.axes_grid1 import make_axes_locatable # make this example reproduciblenp.random.seed(2) #create chartfig, ax = plt.subplots()im = ax.imshow(np.random.rand(10,10))ax.set_xlabel('x-axis label') #add color barfig.colorbar(im) plt.show() Output: Example 2: Position of Matplotlib colorbar on Left Generating a Matplotlib chart where the colorbar is positioned on the left of the chart. Here, the axes locations are set manually and the colorbar is linked to the existing plot axis using the keyword ‘location’. Location argument is used on color bars that reference multiple axes in a list, if you put your one axis in a list then the argument can be used here. Python3 #import matplotlib.pyplot to create chartimport matplotlib.pyplot as pltimport numpy as np #create subplotfig = plt.figure()ax = fig.add_subplot(111)axp = ax.imshow(np.random.randint(0, 10,( 10, 10)))ax.set_title('Colorbar on left') #adding colorbar and its positioncb = plt.colorbar(axp ,ax = [ax], location = 'left')plt.show() Output: This is a simple way to generate a colorbar and ensure it is on its own axis. Then the position of colorbar is specified using ‘cax’ parameter where axes are given for the color bar to be drawn. Python3 import numpy as npimport matplotlib.pyplot as pltfrom mpl_toolkits.axes_grid1 import make_axes_locatable # make this example reproduciblenp.random.seed(1) # create chartfig = plt.figure()ax = fig.add_subplot(111)axp = ax.imshow(np.random.randint(0, 10, (10, 10)))ax.set_title('Colorbar on left') # Adding the colorbarcbaxes = fig.add_axes([0.1, 0.1, 0.03, 0.8]) # position for the colorbarcb = plt.colorbar(axp, cax = cbaxes)plt.show() Output: Example 3: Position of Matplotlib colorbar below the Chart To position, the Matplotlib Colorbar below the chart then execute the following command, Python3 import numpy as npimport matplotlib.pyplot as pltfrom mpl_toolkits.axes_grid1 import make_axes_locatable # make this reproduciblenp.random.seed(2) # create chartfig, ax = plt.subplots()im = ax.imshow(np.random.rand(10,10))ax.set_xlabel('x-axis label') # add color bar below chartdivider = make_axes_locatable(ax)cax = divider.new_vertical(size='5%', pad=0.6, pack_start = True)fig.add_axes(cax)fig.colorbar(im, cax = cax, orientation = 'horizontal') plt.show() Output: Pad argument creates padding between the x-axis of the chart and colorbar. Higher the value for the pad, the colorbar is away from the x-axis. To move colorbar relative to the subplot use the pad argument to fig.colorbar. Python3 # import matplotlib packagesimport matplotlib.pyplot as pltimport numpy as np; np.random.seed(1) # create chartfig, ax = plt.subplots(figsize=(4,4))im = ax.imshow(np.random.rand(11,16))ax.set_xlabel("x label") # pad argument to set colorbar away from x-axisfig.colorbar(im, orientation="horizontal", pad = 0.4)plt.show() Output: Use the instance of make_axes_locatable to divide axes and create new axes which are aligned to the image plot. Pad argument will allow setting space between two axes: Python3 # import matplotlib packagesimport matplotlib.pyplot as pltfrom mpl_toolkits.axes_grid1 import make_axes_locatableimport numpy as np; np.random.seed(1) fig, ax = plt.subplots(figsize = (4,4))im = ax.imshow(np.random.rand(11,16))ax.set_xlabel("x label") # instance is used to divide axesdivider = make_axes_locatable(ax)cax = divider.new_vertical(size = "5%", pad = 0.7, pack_start = True)fig.add_axes(cax) # creating colorbarfig.colorbar(im, cax = cax, orientation = "horizontal") plt.show() Output: Example 4: Position of Colorbar above Chart To position, the Matplotlib Colorbar below the chart then execute the following command, Python3 import numpy as npimport matplotlib.pyplot as pltfrom mpl_toolkits.axes_grid1 import make_axes_locatable # make this example reproduciblenp.random.seed(1) # create chartfig, ax = plt.subplots()im = ax.imshow(np.random.rand(15, 15))ax.set_xlabel('x-axis label')ax.set_title('Colorbar above chart') # add color bar below chartdivider = make_axes_locatable(ax)cax = divider.new_vertical(size = '5%', pad = 0.5)fig.add_axes(cax)fig.colorbar(im, cax = cax, orientation = 'horizontal') plt.show() Output: ddeevviissaavviittaa Picked Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Nov, 2021" }, { "code": null, "e": 531, "s": 28, "text": "A colorbar is a bar that has various colors in it and is placed along the sides of the Matplotlib chart. It is the legend for colors shown in the chart. By default, the positi...
Byte intValue() method in Java with examples
05 Dec, 2018 The intValue() method of Byte class is a built in method in Java which is used to return the value of this Byte object as int. Syntax ByteObject.intValue() Return Value: It returns the value of ByteObject as int. Below is the implementation of intValue() method in Java: Example 1: // Java code to demonstrate// Byte intValue() method class GFG { public static void main(String[] args) { // byte value byte a = 17; // wrapping the byte value // in the wrapper class Byte Byte b = new Byte(a); // intValue of the Byte Object int output = b.intValue(); // printing the output System.out.println("Integer value of " + a + " is : " + output); }} Integer value of 17 is : 17 Example 2: // Java code to demonstrate// Byte intValue() method class GFG { public static void main(String[] args) { String value = "17"; // wrapping the byte value // in the wrapper class Byte Byte b = new Byte(value); // intValue of the Byte Object int output = b.intValue(); // printing the output System.out.println("Integer value of " + b + " is : " + output); }} Integer value of 17 is : 17 Java - util package Java-Byte Java-Functions java-lang-reflect-package 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": 28, "s": 0, "text": "\n05 Dec, 2018" }, { "code": null, "e": 155, "s": 28, "text": "The intValue() method of Byte class is a built in method in Java which is used to return the value of this Byte object as int." }, { "code": null, "e": 162, "s...
How to change the background color after clicking the button in JavaScript ? - GeeksforGeeks
03 Aug, 2021 Given an HTML document and the task is to change the background color of the document using JavaScript and jQuery. Approach 1: This approach uses JavaScript to change the background color after clicking the button.Use HTML DOM Style backgroundColor Property to change the background color after clicking the button. This property is used to set the background-color of an element. Example: This example changes the background color with the help of JavaScript. <!DOCTYPE HTML> <html> <head> <title> How to change the background color after clicking the button ? </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 16px; font-weight: bold;"> </p> <button onclick = "gfg_Run()"> Click here </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var str = "Click on button to change the background color"; el_up.innerHTML = str; function changeColor(color) { document.body.style.background = color; } function gfg_Run() { changeColor('yellow'); el_down.innerHTML = "Background Color changed"; } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: Approach 2: This approach uses jQuery to change the background color after clicking the button. The text() method is used to set the text content to the selected element. The on() method is used as event handlers for the selected elements and child elements. The css() method is used to change/set the background color of the element. Example: This example changes the background color with the help of JQuery. <!DOCTYPE HTML> <html> <head> <title> How to change the background color after clicking the button in jQuery ? </title> <script src ="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 16px; font-weight: bold;"> </p> <button> Click here </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> $('#GFG_UP').text("Click on button to change the background color"); $('button').on('click', function() { $('body').css('background', '#ccc'); $('#GFG_DOWN').text("Background Color Changed!"); }); </script> </body> </html> Output: Before clicking on the button: After clicking on the button: JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples. 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. JavaScript-Misc JavaScript JQuery Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? JQuery | Set the value of an input text field Form validation using jQuery How to change selected value of a drop-down list using jQuery? How to fetch data from JSON file and display in HTML table using jQuery ? How to Dynamically Add/Remove Table Rows using jQuery ?
[ { "code": null, "e": 26640, "s": 26612, "text": "\n03 Aug, 2021" }, { "code": null, "e": 26755, "s": 26640, "text": "Given an HTML document and the task is to change the background color of the document using JavaScript and jQuery." }, { "code": null, "e": 27021, ...
Find the minimum cost to reach destination using a train - GeeksforGeeks
24 Feb, 2022 There are N stations on route of a train. The train goes from station 0 to N-1. The ticket cost for all pair of stations (i, j) is given where j is greater than i. Find the minimum cost to reach the destination.Consider the following example: Input: cost[N][N] = { {0, 15, 80, 90}, {INF, 0, 40, 50}, {INF, INF, 0, 70}, {INF, INF, INF, 0} }; There are 4 stations and cost[i][j] indicates cost to reach j from i. The entries where j < i are meaningless. Output: The minimum cost is 65 The minimum cost can be obtained by first going to station 1 from 0. Then from station 1 to station 3. The minimum cost to reach N-1 from 0 can be recursively written as following: minCost(0, N-1) = MIN { cost[0][n-1], cost[0][1] + minCost(1, N-1), minCost(0, 2) + minCost(2, N-1), ........, minCost(0, N-2) + cost[N-2][n-1] } The following is the implementation of above recursive formula. C++ Java Python3 C# PHP Javascript // A naive recursive solution to find min cost path from station 0// to station N-1#include<iostream>#include<climits>using namespace std; // infinite value#define INF INT_MAX // Number of stations#define N 4 // A C++ recursive function to find the shortest path from// source 's' to destination 'd'.int minCostRec(int cost[][N], int s, int d){ // If source is same as destination // or destination is next to source if (s == d || s+1 == d) return cost[s][d]; // Initialize min cost as direct ticket from // source 's' to destination 'd'. int min = cost[s][d]; // Try every intermediate vertex to find minimum for (int i = s+1; i<d; i++) { int c = minCostRec(cost, s, i) + minCostRec(cost, i, d); if (c < min) min = c; } return min;} // This function returns the smallest possible cost to// reach station N-1 from station 0. This function mainly// uses minCostRec().int minCost(int cost[][N]){ return minCostRec(cost, 0, N-1);} // Driver program to test above functionint main(){ int cost[N][N] = { {0, 15, 80, 90}, {INF, 0, 40, 50}, {INF, INF, 0, 70}, {INF, INF, INF, 0} }; cout << "The Minimum cost to reach station " << N << " is " << minCost(cost); return 0;} // A Java naive recursive solution to find min cost path from station 0// to station N-1class shortest_path{ static int INF = Integer.MAX_VALUE,N = 4; // A recursive function to find the shortest path from // source 's' to destination 'd'. static int minCostRec(int cost[][], int s, int d) { // If source is same as destination // or destination is next to source if (s == d || s+1 == d) return cost[s][d]; // Initialize min cost as direct ticket from // source 's' to destination 'd'. int min = cost[s][d]; // Try every intermediate vertex to find minimum for (int i = s+1; i<d; i++) { int c = minCostRec(cost, s, i) + minCostRec(cost, i, d); if (c < min) min = c; } return min; } // This function returns the smallest possible cost to // reach station N-1 from station 0. This function mainly // uses minCostRec(). static int minCost(int cost[][]) { return minCostRec(cost, 0, N-1); } public static void main(String args[]) { int cost[][] = { {0, 15, 80, 90}, {INF, 0, 40, 50}, {INF, INF, 0, 70}, {INF, INF, INF, 0} }; System.out.println("The Minimum cost to reach station "+ N+ " is "+minCost(cost)); } }/* This code is contributed by Rajat Mishra */ # Python program to find min cost path# from station 0 to station N-1 global NN = 4def minCostRec(cost, s, d): if s == d or s+1 == d: return cost[s][d] min = cost[s][d] for i in range(s+1, d): c = minCostRec(cost,s, i) + minCostRec(cost, i, d) if c < min: min = c return min def minCost(cost): return minCostRec(cost, 0, N-1)cost = [ [0, 15, 80, 90], [float("inf"), 0, 40, 50], [float("inf"), float("inf"), 0, 70], [float("inf"), float("inf"), float("inf"), 0] ]print ("The Minimum cost to reach station %d is %d" % \ (N, minCost(cost))) # This code is contributed by Divyanshu Mehta // A C# naive recursive solution to find min// cost path from station 0 to station N-1using System; class GFG { static int INF = int.MaxValue, N = 4; // A recursive function to find the // shortest path from source 's' to // destination 'd'. static int minCostRec(int [,]cost, int s, int d) { // If source is same as destination // or destination is next to source if (s == d || s + 1 == d) return cost[s,d]; // Initialize min cost as direct // ticket from source 's' to // destination 'd'. int min = cost[s,d]; // Try every intermediate vertex to // find minimum for (int i = s + 1; i < d; i++) { int c = minCostRec(cost, s, i) + minCostRec(cost, i, d); if (c < min) min = c; } return min; } // This function returns the smallest // possible cost to reach station N-1 // from station 0. This function mainly // uses minCostRec(). static int minCost(int [,]cost) { return minCostRec(cost, 0, N-1); } // Driver code public static void Main() { int [,]cost = { {0, 15, 80, 90}, {INF, 0, 40, 50}, {INF, INF, 0, 70}, {INF, INF, INF, 0} }; Console.WriteLine("The Minimum cost to" + " reach station "+ N + " is "+minCost(cost)); }} // This code is contributed by Sam007. <?php// A PHP naive recursive solution to find min cost path from station 0// to station N-1// infinite value $INF= PHP_INT_MAX ; // Number of stations $N = 4; // A recursive function to find the shortest path from// source 's' to destination 'd'.function minCostRec($cost, $s, $d){ // If source is same as destination // or destination is next to source if ($s == $d || $s+1 == $d) return $cost[$s][$d]; // Initialize min cost as direct ticket from // source 's' to destination 'd'.$min = $cost[$s][$d]; // Try every intermediate vertex to find minimum for ($i = $s+1; $i<$d; $i++) { $c = minCostRec($cost, $s, $i) + minCostRec($cost, $i, $d); if ($c < $min) $min = $c; } return $min;} // This function returns the smallest possible cost to// reach station N-1 from station 0. This function mainly// uses minCostRec().function minCost($cost){ global $N; return minCostRec($cost, 0, $N-1);} // Driver program to test above function $cost = array(array(0, 15, 80, 90), array(INF, 0, 40, 50), array(INF, INF, 0, 70), array(INF, INF, INF, 0) ); echo "The Minimum cost to reach station ", $N , " is " , minCost($cost); ?> <script> // A Javascript naive recursive solution to find min cost path from station 0 to station N-1 let INF = Number.MAX_VALUE,N = 4; // A recursive function to find the shortest path from // source 's' to destination 'd'. function minCostRec(cost, s, d) { // If source is same as destination // or destination is next to source if (s == d || s+1 == d) return cost[s][d]; // Initialize min cost as direct ticket from // source 's' to destination 'd'. let min = cost[s][d]; // Try every intermediate vertex to find minimum for (let i = s+1; i<d; i++) { let c = minCostRec(cost, s, i) + minCostRec(cost, i, d); if (c < min) min = c; } return min; } // This function returns the smallest possible cost to // reach station N-1 from station 0. This function mainly // uses minCostRec(). function minCost(cost) { return minCostRec(cost, 0, N-1); } let cost = [ [0, 15, 80, 90], [INF, 0, 40, 50], [INF, INF, 0, 70], [INF, INF, INF, 0] ]; document.write("The Minimum cost to reach station "+ N+ " is "+minCost(cost)); // This code is contributed by decode2207.</script> Output: The Minimum cost to reach station 4 is 65 Time complexity of the above implementation is exponential as it tries every possible path from 0 to N-1. The above solution solves same subproblems multiple times (it can be seen by drawing recursion tree for minCostPathRec(0, 5). Since this problem has both properties of dynamic programming problems ((see this and this). Like other typical Dynamic Programming(DP) problems, re-computations of same subproblems can be avoided by storing the solutions to subproblems and solving problems in bottom up manner. One dynamic programming solution is to create a 2D table and fill the table using above given recursive formula. The extra space required in this solution would be O(N2) and time complexity would be O(N3)We can solve this problem using O(N) extra space and O(N2) time. The idea is based on the fact that given input matrix is a Directed Acyclic Graph (DAG). The shortest path in DAG can be calculated using the approach discussed in below post. Shortest Path in Directed Acyclic GraphWe need to do less work here compared to above mentioned post as we know topological sorting of the graph. The topological sorting of vertices here is 0, 1, ..., N-1. Following is the idea once topological sorting is known.The idea in below code is to first calculate min cost for station 1, then for station 2, and so on. These costs are stored in an array dist[0...N-1].1) The min cost for station 0 is 0, i.e., dist[0] = 02) The min cost for station 1 is cost[0][1], i.e., dist[1] = cost[0][1]3) The min cost for station 2 is minimum of following two. a) dist[0] + cost[0][2] b) dist[1] + cost[1][2]3) The min cost for station 3 is minimum of following three. a) dist[0] + cost[0][3] b) dist[1] + cost[1][3] c) dist[2] + cost[2][3]Similarly, dist[4], dist[5], ... dist[N-1] are calculated.Below is the implementation of above idea. C++ Java Python3 C# PHP Javascript // A Dynamic Programming based solution to find min cost// to reach station N-1 from station 0.#include<iostream>#include<climits>using namespace std; #define INF INT_MAX#define N 4 // This function returns the smallest possible cost to// reach station N-1 from station 0.int minCost(int cost[][N]){ // dist[i] stores minimum cost to reach station i // from station 0. int dist[N]; for (int i=0; i<N; i++) dist[i] = INF; dist[0] = 0; // Go through every station and check if using it // as an intermediate station gives better path for (int i=0; i<N; i++) for (int j=i+1; j<N; j++) if (dist[j] > dist[i] + cost[i][j]) dist[j] = dist[i] + cost[i][j]; return dist[N-1];} // Driver program to test above functionint main(){ int cost[N][N] = { {0, 15, 80, 90}, {INF, 0, 40, 50}, {INF, INF, 0, 70}, {INF, INF, INF, 0} }; cout << "The Minimum cost to reach station " << N << " is " << minCost(cost); return 0;} // A Dynamic Programming based solution to find min cost// to reach station N-1 from station 0.class shortest_path{ static int INF = Integer.MAX_VALUE,N = 4; // A recursive function to find the shortest path from // source 's' to destination 'd'. // This function returns the smallest possible cost to // reach station N-1 from station 0. static int minCost(int cost[][]) { // dist[i] stores minimum cost to reach station i // from station 0. int dist[] = new int[N]; for (int i=0; i<N; i++) dist[i] = INF; dist[0] = 0; // Go through every station and check if using it // as an intermediate station gives better path for (int i=0; i<N; i++) for (int j=i+1; j<N; j++) if (dist[j] > dist[i] + cost[i][j]) dist[j] = dist[i] + cost[i][j]; return dist[N-1]; } public static void main(String args[]) { int cost[][] = { {0, 15, 80, 90}, {INF, 0, 40, 50}, {INF, INF, 0, 70}, {INF, INF, INF, 0} }; System.out.println("The Minimum cost to reach station "+ N+ " is "+minCost(cost)); } }/* This code is contributed by Rajat Mishra */ # A Dynamic Programming based# solution to find min cost# to reach station N-1# from station 0. INF = 2147483647N = 4 # This function returns the# smallest possible cost to# reach station N-1 from station 0.def minCost(cost): # dist[i] stores minimum # cost to reach station i # from station 0. dist=[0 for i in range(N)] for i in range(N): dist[i] = INF dist[0] = 0 # Go through every station # and check if using it # as an intermediate station # gives better path for i in range(N): for j in range(i+1,N): if (dist[j] > dist[i] + cost[i][j]): dist[j] = dist[i] + cost[i][j] return dist[N-1] # Driver program to# test above function cost= [ [0, 15, 80, 90], [INF, 0, 40, 50], [INF, INF, 0, 70], [INF, INF, INF, 0]] print("The Minimum cost to reach station ", N," is ",minCost(cost)) # This code is contributed# by Anant Agarwal. // A Dynamic Programming based solution// to find min cost to reach station N-1// from station 0.using System; class GFG { static int INF = int.MaxValue, N = 4; // A recursive function to find the // shortest path from source 's' to // destination 'd'. // This function returns the smallest // possible cost to reach station N-1 // from station 0. static int minCost(int [,]cost) { // dist[i] stores minimum cost // to reach station i from // station 0. int []dist = new int[N]; for (int i = 0; i < N; i++) dist[i] = INF; dist[0] = 0; // Go through every station and check // if using it as an intermediate // station gives better path for (int i = 0; i < N; i++) for (int j = i + 1; j < N; j++) if (dist[j] > dist[i] + cost[i,j]) dist[j] = dist[i] + cost[i,j]; return dist[N-1]; } public static void Main() { int [,]cost = { {0, 15, 80, 90}, {INF, 0, 40, 50}, {INF, INF, 0, 70}, {INF, INF, INF, 0} }; Console.WriteLine("The Minimum cost to" + " reach station "+ N + " is "+minCost(cost)); }} // This code is contributed by Sam007. <?php// A Dynamic Programming based solution to find min cost// to reach station N-1 from station 0. $INF =PHP_INT_MAX;$N = 4; // This function returns the smallest possible cost to// reach station N-1 from station 0.function minCost($cost){global $INF;global $N; // dist[i] stores minimum cost to reach station i // from station 0. $dist[$N]=array(); for ($i=0; $i<$N; $i++) $dist[$i] = $INF; $dist[0] = 0; // Go through every station and check if using it // as an intermediate station gives better path for ($i=0; $i<$N; $i++) for ( $j=$i+1; $j<$N; $j++) if ($dist[$j] > $dist[$i] + $cost[$i][$j]) $dist[$j] = $dist[$i] + $cost[$i][$j]; return $dist[$N-1];} // Driver program to test above function $cost =array(array(0, 15, 80, 90), array(INF, 0, 40, 50), array(INF, INF, 0, 70), array(INF, INF, INF, 0)); echo "The Minimum cost to reach station ", $N , " is ",minCost($cost); ?> <script> // A Dynamic Programming based solution // to find min cost to reach station N-1 // from station 0. let INF = Number.MAX_VALUE, N = 4; // A recursive function to find the // shortest path from source 's' to // destination 'd'. // This function returns the smallest // possible cost to reach station N-1 // from station 0. function minCost(cost) { // dist[i] stores minimum cost // to reach station i from // station 0. let dist = new Array(N); dist.fill(0); for (let i = 0; i < N; i++) dist[i] = INF; dist[0] = 0; // Go through every station and check // if using it as an intermediate // station gives better path for (let i = 0; i < N; i++) for (let j = i + 1; j < N; j++) if (dist[j] > dist[i] + cost[i][j]) dist[j] = dist[i] + cost[i][j]; return dist[N-1]; } let cost = [ [0, 15, 80, 90], [INF, 0, 40, 50], [INF, INF, 0, 70], [INF, INF, INF, 0] ]; document.write("The Minimum cost to" + " reach station "+ N + " is "+minCost(cost)); </script> Output: The Minimum cost to reach station 4 is 65 This article is contributed by Udit Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Sam007 Sach_Code decode2207 divyeshrabadiya07 amartyaghoshgfg simmytarika5 Shortest Path Topological Sorting Dynamic Programming Graph Dynamic Programming Graph Shortest Path Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16 Subset Sum Problem | DP-25 Matrix Chain Multiplication | DP-8 Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Breadth First Search or BFS for a Graph Depth First Search or DFS for a Graph Dijkstra's shortest path algorithm | Greedy Algo-7 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
[ { "code": null, "e": 26129, "s": 26101, "text": "\n24 Feb, 2022" }, { "code": null, "e": 26374, "s": 26129, "text": "There are N stations on route of a train. The train goes from station 0 to N-1. The ticket cost for all pair of stations (i, j) is given where j is greater than i....
Add Leading Zeros to the Elements of a Vector in R Programming - Using paste0() and sprintf() Function - GeeksforGeeks
01 Jun, 2021 paste0() and sprintf() functions in R Language can also be used to add leading zeros to each element of a vector passed to it as argument. Syntax: paste0(“0”, vec) or sprintf(“%0d”, vec)Parameters: paste0: It will add zeros to vector sprintf: To format a vector(adding zeros) vec: Original vector dataReturns: Vectors by addition of leading zeros Example 1: r # R Program to add leading zeros # Create example vectorvec <- c(375, 21, 1, 7, 0)vec # Add leading zerosvec_0 <- paste0("0", vec)vec_0 Output : [1] 375 21 1 7 0 [1] "0375" "021" "01" "07" "00" Example 2: r # R Program to add leading zeros # Create example vectorvec <- seq(5) # Add leading zerossprintf("sequence_%03d", vec) Output : [1] "sequence_001" "sequence_002" "sequence_003" "sequence_004" "sequence_005" arorakashish0911 R Vector-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Group by function in R using Dplyr Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? How to Change Axis Scales in R Plots? Replace Specific Characters in String in R How to filter R DataFrame by values in a column? How to filter R dataframe by multiple conditions? Time Series Analysis in R R - if statement How to import an Excel File into R ?
[ { "code": null, "e": 25340, "s": 25312, "text": "\n01 Jun, 2021" }, { "code": null, "e": 25480, "s": 25340, "text": "paste0() and sprintf() functions in R Language can also be used to add leading zeros to each element of a vector passed to it as argument. " }, { "code": n...
Bottom-up traversal of a Trie - GeeksforGeeks
28 Dec, 2021 Trie is an efficient information retrieval data structure. Using Trie, search complexities can be brought to an optimal limit (key length). Given a trie. The task is to print the characters in a bottom-up mannerBottom-up traversal: First print string of left most subtree(from bottom to top) then print string of second left subtree(from bottom to top) then print for third left subtree and so on. It is similar to post-order traversal of a treeExample: Input : root / \ a t | | n h | \ | s y e | | \ w i r | | | e r e | r Output : r, e, w, s, y, n, a, r, i, e, r, e, h, t Input : root / \ c t | | a h | \ | l t e | | \ l i r | \ | | e i r e | | r n | g Output : r, e, g, n, i, l, l, t, a, c, r, i, e, r, e, h, t Explanation : In the first example, the root has two parts. First part contains strings: “answer” and “any”. the second part with strings “their” and “there”. Now first we got to left subtree containing strings “answer” and “any” which separates by character ‘n’. Now ‘n’ separates two-part of characters ‘s’, ‘w’, ‘e’, ‘r’ and ‘y’. so print ‘s’, ‘w’, ‘e’, ‘r’ in reverse order then print ‘y’ and go up and print ‘n'(which separates string) then go up and print ‘a’. Now first left subtree has printed in bottom up manner ‘r’, ‘e’, ‘w’, ‘s’, ‘y’, ‘n’, ‘a’. Do the same thing for another subtree of the root which contains strings “their” and “there” which is separated by character ‘e’. Approach : The idea to do this is to start traversing from the root node of the trie, whenever we find a NON-NULL child node, we recursively move ahead when we get “NULL” we return simply and print the value of current node and same goes un till we find the node which is a leaf node, which actually marks the end of the string.Below is the implementation of the above approach : C++ Java Python3 C# Javascript // CPP program to traverse in bottom up manner#include <bits/stdc++.h>using namespace std;#define CHILDREN 26#define MAX 100 // Trie nodestruct trie { trie* child[CHILDREN]; // endOfWord is true if the node represents // end of a word 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++) { // Initialise all child to the null, initially temp->child[i] = NULL; } // Return newly created node 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) { // Assigning a newly created node itr->child[index] = createNode(); } // Recursive call for insertion // of a string in a trie 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 print traverse// the tree in bottom to top mannervoid printPattern(trie* itr){ // Base condition if (itr == NULL) return; // Loop for printing t a value of character for (int i = 0; i < CHILDREN; i++) { // Recursive call for print pattern printPattern(itr->child[i]); if (itr->child[i] != NULL) { char ch = (i + 97); cout << ch << ", "; // Print character } }} // Driver codeint main(){ trie* root = createNode(); // Function to insert a string insert(root, "their"); insert(root, "there"); insert(root, "answer"); insert(root, "any"); // Function call for printing a pattern printPattern(root); return 0;} // Java program to traverse in bottom up mannerpublic class Main{ static int CHILDREN = 26; // Trie node static class trie { public boolean endOfWord; public trie[] child; public trie() { endOfWord = false; // endOfWord is true if the node represents // end of a word child = new trie[CHILDREN]; } } // 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++) { // Initialise all child to the null, initially temp.child[i] = null; } // Return newly created node return temp; } // Function will insert the string in a trie recursively static void insertRecursively(trie itr, String str, int i) { if (i < str.length()) { int index = str.charAt(i) - 'a'; if (itr.child[index] == null) { // Assigning a newly created node itr.child[index] = createNode(); } // Recursive call for insertion // of a string in a trie 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 static void insert(trie itr, String str) { // Function call with necessary arguments insertRecursively(itr, str, 0); } // Function to print traverse // the tree in bottom to top manner static void printPattern(trie itr) { // Base condition if (itr == null) return; // Loop for printing t a value of character for (int i = 0; i < CHILDREN; i++) { // Recursive call for print pattern printPattern(itr.child[i]); if (itr.child[i] != null) { char ch = (char)(i + 97); System.out.print(ch + ", "); // Print character } } } public static void main(String[] args) { trie root = createNode(); // Function to insert a string insert(root, "their"); insert(root, "there"); insert(root, "answer"); insert(root, "any"); // Function call for printing a pattern printPattern(root); }} // This code is contributed by divyesh072019. # 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 insert 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): # Assigning a newly created node itr.child[index] = createNode() # Recursive call for insertion # of a string in a trie 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 print traverse# the tree in bottom to top mannerdef printPattern(itr): # Base condition if(itr == None): return # Loop for printing t a value of character for i in range(CHILDREN): # Recursive call for print pattern printPattern(itr.child[i]) if (itr.child[i] != None): ch = chr(i + 97) # Print character print(ch,end=', ') # Driver codeif __name__=='__main__': root = createNode() # Function to insert a string insert(root, "their") insert(root, "there") insert(root, "answer") insert(root, "any") # Function call for printing a pattern printPattern(root) # This code is countributed by rutvik_56 // C# program to traverse in bottom up mannerusing System;class GFG { static int CHILDREN = 26; // Trie node class trie { public bool endOfWord; public trie[] child; public trie() { endOfWord = false; // endOfWord is true if the node represents // end of a word child = new trie[CHILDREN]; } } // 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++) { // Initialise all child to the null, initially temp.child[i] = null; } // Return newly created node return temp; } // Function will insert the string in a trie recursively static void insertRecursively(trie itr, string str, int i) { if (i < str.Length) { int index = str[i] - 'a'; if (itr.child[index] == null) { // Assigning a newly created node itr.child[index] = createNode(); } // Recursive call for insertion // of a string in a trie 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 static void insert(trie itr, string str) { // Function call with necessary arguments insertRecursively(itr, str, 0); } // Function to print traverse // the tree in bottom to top manner static void printPattern(trie itr) { // Base condition if (itr == null) return; // Loop for printing t a value of character for (int i = 0; i < CHILDREN; i++) { // Recursive call for print pattern printPattern(itr.child[i]); if (itr.child[i] != null) { char ch = (char)(i + 97); Console.Write(ch + ", "); // Print character } } } static void Main() { trie root = createNode(); // Function to insert a string insert(root, "their"); insert(root, "there"); insert(root, "answer"); insert(root, "any"); // Function call for printing a pattern printPattern(root); }} // This code is contributed by mukesh07. <script> // Javascript program to traverse in bottom up manner let CHILDREN = 26; // Trie node class trie { constructor() { // endOfWord is true if the node represents // end of a word this.child = new Array(CHILDREN); this.endOfWord = false; } } // Function will return the new node(initialized to NULLs) function createNode() { let temp = new trie(); temp.endOfWord = false; for (let i = 0; i < CHILDREN; i++) { // Initialise all child to the null, initially temp.child[i] = null; } // Return newly created node 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) { // Assigning a newly created node itr.child[index] = createNode(); } // Recursive call for insertion // of a string in a trie 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 print traverse // the tree in bottom to top manner function printPattern(itr) { // Base condition if (itr == null) return; // Loop for printing t a value of character for (let i = 0; i < CHILDREN; i++) { // Recursive call for print pattern printPattern(itr.child[i]); if (itr.child[i] != null) { let ch = String.fromCharCode(i + 97); document.write(ch + ", "); // Print character } } } let root = createNode(); // Function to insert a string insert(root, "their"); insert(root, "there"); insert(root, "answer"); insert(root, "any"); // Function call for printing a pattern printPattern(root); // This code is contributed by suresh07.</script> Output: r, e, w, s, y, n, a, e, r, e, r, e, i, h, t, Akanksha_Rai shubham_singh rutvik_56 sumitgumber28 mukesh07 kapoorsagar226 rkbhola5 divyesh072019 suresh07 Trie Advanced Data Structure Recursion Recursion 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) Difference between Backtracking and Branch-N-Bound technique 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": 25731, "s": 25703, "text": "\n28 Dec, 2021" }, { "code": null, "e": 25965, "s": 25731, "text": "Trie is an efficient information retrieval data structure. Using Trie, search complexities can be brought to an optimal limit (key length). Given a trie. The task ...
Hashtable remove() Method in Java - GeeksforGeeks
24 Jun, 2021 The java.util.Hashtable.remove() is an inbuilt method of Hashtable class and is used to remove the mapping of any particular key from the table. It basically removes the values for any particular key in the Table.Syntax: Hash_Table.remove(Object key) Parameters: The method takes one parameter key whose mapping is to be removed from the Table.Return Value: The method returns the value that was previously mapped to the specified key if the key exists else the method returns NULL.Below programs illustrates the working of java.util.Hashtable.remove() method: Program 1: When passing an existing key. Java // Java code to illustrate the remove() methodimport java.util.*; public class Hash_Table_Demo { public static void main(String[] args) { // Creating an empty Hashtable Hashtable<Integer, String> hash_table = new Hashtable<Integer, String>(); // Inserting elements into the table hash_table.put(10, "Geeks"); hash_table.put(15, "4"); hash_table.put(20, "Geeks"); hash_table.put(25, "Welcomes"); hash_table.put(30, "You"); // Displaying the Hashtable System.out.println("Initial Table is: " + hash_table); // Removing the existing key mapping String returned_value = (String)hash_table.remove(20); // Verifying the returned value System.out.println("Returned value is: " + returned_value); // Displaying the new table System.out.println("New table is: " + hash_table); }} Initial Table is: {10=Geeks, 20=Geeks, 30=You, 15=4, 25=Welcomes} Returned value is: Geeks New table is: {10=Geeks, 30=You, 15=4, 25=Welcomes} Program 2: When passing a new key. Java // Java code to illustrate the remove() methodimport java.util.*; public class Hash_Table_Demo { public static void main(String[] args) { // Creating an empty Hashtable Hashtable<Integer, String> hash_table = new Hashtable<Integer, String>(); // Inserting mappings into the table hash_table.put(10, "Geeks"); hash_table.put(15, "4"); hash_table.put(20, "Geeks"); hash_table.put(25, "Welcomes"); hash_table.put(30, "You"); // Displaying the Hashtable System.out.println("Initial table is: " + hash_table); // Removing the new key mapping String returned_value = (String)hash_table.remove(50); // Verifying the returned value System.out.println("Returned value is: " + returned_value); // Displaying the new table System.out.println("New table is: " + hash_table); }} Initial table is: {10=Geeks, 20=Geeks, 30=You, 15=4, 25=Welcomes} Returned value is: null New table is: {10=Geeks, 20=Geeks, 30=You, 15=4, 25=Welcomes} Note: The same operation can be performed with any type of variation and combination of different data types. simranarora5sos Java-HashTable Misc Misc Misc Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 10 algorithms in Interview Questions vector::push_back() and vector::pop_back() in C++ STL Overview of Data Structures | Set 1 (Linear Data Structures) How to write Regular Expressions? Association Rule Minimax Algorithm in Game Theory | Set 3 (Tic-Tac-Toe AI - Finding optimal move) fgets() and gets() in C language Recursive Functions Characteristics of Internet of Things Java Math min() method with Examples
[ { "code": null, "e": 24899, "s": 24871, "text": "\n24 Jun, 2021" }, { "code": null, "e": 25122, "s": 24899, "text": "The java.util.Hashtable.remove() is an inbuilt method of Hashtable class and is used to remove the mapping of any particular key from the table. It basically remov...
Angular Material - Chips
The md-chips, an Angular Directive, is used as a special component called Chip and can be used to represent a small set of information for example, a contact, tags etc. A custom template can be used to render the content of a chip. This can be achieved by specifying an md-chip-template element having the custom content as a child of md-chips. The following table lists out the parameters and description of the different attributes of md-chips. * ng-model Assignable angular expression to data-bind to. * ng-model A model to bind the list of items to. An expression of form myFunction($chip) that when called expects one of the following return values − an object representing the $chip input string. an object representing the $chip input string. undefined to simply add the $chip input string, or. undefined to simply add the $chip input string, or. null to prevent the chip from being appended. null to prevent the chip from being appended. * md-require-match If true, and the chips template contains an autocomplete, only allows selection of pre-defined chips (i.e. you cannot add new ones). placeholder Placeholder text that will be forwarded to the input. secondary-placeholder Placeholder text that will be forwarded to the input, displayed when there is at least one item in the list. readonly Disables list manipulation (deleting or adding list items), hiding the input and the delete buttons. md-on-add An expression which will be called when a chip has been added. md-on-remove An expression which will be called when a chip has been removed. md-on-select An expression which will be called when a chip is selected. delete-hint A string read by screen readers instructing users that pressing the delete key will remove the chip. delete-button-label A label for the Delete button. Also hidden and read by screen readers. md-separator-keys An array of key codes used to separate chips. The following example shows the use of the md-chips directive and also the use of angular chips. am_chips.htm <html lang = "en"> <head> <link rel = "stylesheet" href = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css"> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js"></script> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js"></script> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js"></script> <script src = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.js"></script> <link rel = "stylesheet" href = "https://fonts.googleapis.com/icon?family=Material+Icons"> <style> .closeButton { position: relative; height: 24px; width: 24px; line-height: 30px; text-align: center; background: rgba(0, 0, 0, 0.3); border-radius: 50%; border: none; box-shadow: none; padding: 0; margin: 3px; transition: background 0.15s linear; display: block; } </style> <script language = "javascript"> angular .module('firstApplication', ['ngMaterial']) .controller('chipController', chipController); function chipController ($scope) { var self = this; self.readonly = false; // Lists of fruit names and Vegetable objects self.fruitNames = ['Apple', 'Banana', 'Orange']; self.roFruitNames = angular.copy(self.fruitNames); self.tags = []; self.vegObjs = [ { 'name' : 'Broccoli', 'type' : 'Brassica' }, { 'name' : 'Cabbage', 'type' : 'Brassica' }, { 'name' : 'Carrot', 'type' : 'Umbelliferous' } ]; self.newVeg = function(chip) { return { name: chip, type: 'unknown' }; }; } </script> </head> <body ng-app = "firstApplication"> <div ng-controller = "chipController as ctrl" layout = "column" ng-cloak> <md-chips ng-model = "ctrl.fruitNames" readonly = "ctrl.readonly"> </md-chips> <md-chips class = "custom-chips" ng-model = "ctrl.vegObjs" readonly = "ctrl.readonly" md-transform-chip = "ctrl.newVeg($chip)"> <md-chip-template> <span> <strong>[{{$index}}] {{$chip.name}}</strong> <em>({{$chip.type}})</em> </span> </md-chip-template> <button md-chip-remove class = "md-primary closeButton"> <md-icon md-svg-icon = "md-close"></md-icon> </button> </md-chips> <br/> <md-checkbox ng-model = "ctrl.readonly">Readonly</md-checkbox> </div> </body> </html> Verify the result. 16 Lectures 1.5 hours Anadi Sharma 28 Lectures 2.5 hours Anadi Sharma 11 Lectures 7.5 hours SHIVPRASAD KOIRALA 16 Lectures 2.5 hours Frahaan Hussain 69 Lectures 5 hours Senol Atac 53 Lectures 3.5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2535, "s": 2190, "text": "The md-chips, an Angular Directive, is used as a special component called Chip and can be used to represent a small set of information for example, a contact, tags etc. A custom template can be used to render the content of a chip. This can be achieved ...
SequenceEqual method in C#
The SequenceEqual method is used to test collections for equality. Let us set three string arrays − string[] arr1 = { "This", "is", "it" }; string[] arr2 = { "My", "work", "report" }; string[] arr3 = { "This", "is", "it" }; Now, compare the first array with the second using the SequenceEqual() method − arr1.SequenceEqual(arr2); The following is an example − Live Demo using System; using System.Linq; class Program { static void Main() { string[] arr1 = { "This", "is", "it" }; string[] arr2 = { "My", "work", "report" }; string[] arr3 = { "This", "is", "it" }; bool res1 = arr1.SequenceEqual(arr2); Console.WriteLine(res1); bool res2 = arr1.SequenceEqual(arr3); Console.WriteLine(res2); } } False True
[ { "code": null, "e": 1129, "s": 1062, "text": "The SequenceEqual method is used to test collections for equality." }, { "code": null, "e": 1162, "s": 1129, "text": "Let us set three string arrays −" }, { "code": null, "e": 1286, "s": 1162, "text": "string[] ar...
How to implement custom serializer using @JsonSerialize annotation in Java?
The @JsonSerialize annotation is used to declare custom serializer during the serialization of a field. We can implement a custom serializer by extending the StdSeralizer class. and need to override the serialize() method of StdSerializer class. @Target(value={ANNOTATION_TYPE,METHOD,FIELD,TYPE,PARAMETER}) @Retention(value=RUNTIME) public @interface JsonSerialize In the below program, we can implement a custom serializer using @JsonSerialize annotation import java.io.*; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.annotation.*; import com.fasterxml.jackson.databind.ser.std.*; public class JsonSerializeAnnotationTest { public static void main (String[] args) throws JsonProcessingException, IOException { Employee emp = new Employee(115, "Adithya", new String[] {"Java", "Python", "Scala"}); ObjectMapper mapper = new ObjectMapper(); String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(emp); System.out.println(jsonString); } } // CustomSerializer class class CustomSerializer extends StdSerializer { public CustomSerializer(Class t) { super(t); } public CustomSerializer() { this(Employee.class); } @Override public void serialize(Employee emp, JsonGenerator jgen, SerializerProvider sp) throws IOException, JsonGenerationException { StringBuilder sb = new StringBuilder(); jgen.writeStartObject(); jgen.writeNumberField("id", emp.getId()); jgen.writeStringField("name", emp.getName()); for(String s: emp.getLanguages()) { sb.append(s).append(";"); } jgen.writeStringField("languages", sb.toString()); jgen.writeEndObject(); } } // Employee class @JsonSerialize(using=CustomSerializer.class) class Employee { private int id; private String name; private String[] languages; public Employee(int id, String name, String[] languages) { this.id = id; this.name = name; this.languages = languages; } public int getId() { return this.id; } public String getName() { return this.name; } public String[] getLanguages() { return this.languages; } @Override public String toString() { StringBuilder sb = new StringBuilder("ID: ").append(this.id).append("\nName: ").append(this.name).append("\nLanguages:"); for(String s: this.languages) { sb.append(" ").append(s); } return sb.toString(); } } { "id" : 115, "name" : "Adithya", "languages" : "Java;Python;Scala;" }
[ { "code": null, "e": 1308, "s": 1062, "text": "The @JsonSerialize annotation is used to declare custom serializer during the serialization of a field. We can implement a custom serializer by extending the StdSeralizer class. and need to override the serialize() method of StdSerializer class." }, ...
Parse a string to a Boolean object in Java
The valueOf() method returns the relevant Number Object holding the value of the argument passed. The argument can be a primitive data type, String, Boolean, etc. Therefore, to parse a string to a Boolean object, use the Java valueOf() method. The following is an example showing how to parse a string to a Boolean object in Java. Live Demo public class Demo { public static void main(String[] args) { System.out.println("Parsing a string to a Boolean object..."); Boolean val = Boolean.valueOf("true"); System.out.println("Value: "+val); } } Parsing a string to a Boolean object... Value: true Boolean object is used to parse a string in the above program. Boolean val = Boolean.valueOf("true"); We have passed a string “true” to valueOf() method above. This string is parsed.
[ { "code": null, "e": 1306, "s": 1062, "text": "The valueOf() method returns the relevant Number Object holding the value of the argument passed. The argument can be a primitive data type, String, Boolean, etc. Therefore, to parse a string to a Boolean object, use the Java valueOf() method." }, {...
Difference between single quote (‘) and double quote (“) in PowerShell?
There is no such difference between the single quote (‘) and double quote(“) in PowerShell. It is similar to a programming language like Python. We generally use both quotes to print the statements. PS C:\> Write-Output 'This will be printed using Single quote' This will be printed using Single quote PS C:\> Write-Output "This will be printed using double quote" This will be printed using double quote But when we evaluate any expression or print variable it makes a clear difference. $date = Get-Date Write-Output 'Today date is : $date' Today date is : $date Write-Output "Today date is : $date" Today date is : 11/02/2020 08:13:06 You can see in the above example that a single quote can’t print the variable output and instead it is printing the name of the variable, while the double quotes can print the output of the variable. Even if we try to evaluate a variable name it can’t be done using a single quote. PS C:\> Write-Output 'Today date is : $($date)' Today date is : $($date) Another example of multiplication operation, PS C:\> Write-Output "Square of 4 : $(4*4)" Square of 4 : 16 PS C:\> Write-Output 'square of 4 : $(4*4)' square of 4 : $(4*4) Take an example of printing multiple statements using an array. $name = 'Charlie' $age = 40 $str = @" New Joinee name is $name Her age is $age "@ $str New Joinee name is Charlie Her age is 40 He will receive 1200 dollar bonus after 2 years The above output is printed properly but when we use the single quote, it won’t print the variable name. $str = @' New Joinee name is $name Her age is $age He will receive $($age*30) dollar bonus after 2 years '@ New Joinee name is $name Her age is $age He will receive $($age*30) dollar bonus after 2 years It is concluded that, use a single quote only to print the plain text but to print variables and evaluating other expressions in the string, use the double quote in PowerShell.
[ { "code": null, "e": 1261, "s": 1062, "text": "There is no such difference between the single quote (‘) and double quote(“) in PowerShell. It is similar to a programming language like Python. We generally use both quotes to print the statements." }, { "code": null, "e": 1467, "s": 12...
Find frequency of each element in a limited range array in less than O(n) time in C++
Suppose we have an array of integers. The array is A, and the size is n. Our task is to find the frequency of all elements in the array less than O(n) time. The size of the elements must be less than one value say M. Here we will use the binary search approach. Here we will recursively divide the array into two parts if the end elements are different, if both its end elements are the same, it means all elements in the array are the same as the array is already sorted. Live Demo #include<iostream> #include<vector> using namespace std; void calculateFreq(int arr[], int left, int right, vector<int>& frequency) { if (arr[left] == arr[right]) frequency[arr[left]] += right - left + 1; else { int mid = (left + right) / 2; calculateFreq(arr, left, mid, frequency); calculateFreq(arr, mid + 1, right, frequency); } } void getAllFrequency(int arr[], int n) { vector<int> frequency(arr[n - 1] + 1, 0); calculateFreq(arr, 0, n - 1, frequency); for (int i = 0; i <= arr[n - 1]; i++) if (frequency[i] != 0) cout << "Frequency of element " << i << " is " << frequency[i] << endl; } int main() { int arr[] = { 10, 10, 10, 20, 30, 30, 50, 50, 80, 80, 80, 90, 90, 99 }; int n = sizeof(arr) / sizeof(arr[0]); getAllFrequency(arr, n); } Frequency of element 10 is 3 Frequency of element 20 is 1 Frequency of element 30 is 2 Frequency of element 50 is 2 Frequency of element 80 is 3 Frequency of element 90 is 2 Frequency of element 99 is 1
[ { "code": null, "e": 1535, "s": 1062, "text": "Suppose we have an array of integers. The array is A, and the size is n. Our task is to find the frequency of all elements in the array less than O(n) time. The size of the elements must be less than one value say M. Here we will use the binary search a...
How to create a New Line in PHP ? - GeeksforGeeks
21 Sep, 2021 New Line helps the page to look better and presentable. We will learn to insert a new line in PHP using 2 ways. Using Line Breaks as in HTML Using New Line tags Using Line Breaks as in HTML: The <br> tag in HTML is used to give the single line break. It is an empty tag, so it does not contain an end tag. Syntax: </br> Example: PHP <?phpecho "Akshit ". "<br>". "Loves GeeksForGeeks";?> Akshit Loves GeeksForGeeks Using new line tags: Newline characters \n or \r\n can be used to create a new line inside the source code. Syntax: "\n" Example 1: PHP <?phpecho "Akshit " ."\n"."Loves GeeksForGeeks";?> Akshit Loves GeeksForGeeks Syntax: "\r\n" Example 2: PHP <?phpecho "Akshit " ."\r\n"."Loves GeeksForGeeks";?> Akshit Loves GeeksForGeeks simmytarika5 HTML-Tags PHP-Questions Picked PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to fetch data from localserver database and display on HTML table using PHP ? How to pass form variables from one page to other page in PHP ? Create a drop-down list that options fetched from a MySQL database in PHP How to create admin login page using PHP? Different ways for passing data to view in Laravel Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24581, "s": 24553, "text": "\n21 Sep, 2021" }, { "code": null, "e": 24693, "s": 24581, "text": "New Line helps the page to look better and presentable. We will learn to insert a new line in PHP using 2 ways." }, { "code": null, "e": 24722, "s"...
Find the Next perfect square greater than a given number
13 Apr, 2021 Given a number N, the task is to find the next perfect square greater than N.Examples: Input: N = 6 Output: 9 9 is a greater number than 6 and is also a perfect square Input: N = 9 Output: 16 Approach: Find the square root of given N.Calculate its floor value using floor function in C++.Then add 1 to it.Print square of that number. Find the square root of given N. Calculate its floor value using floor function in C++. Then add 1 to it. Print square of that number. Below is the implementation of above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of above approach#include <iostream>#include<cmath>using namespace std; // Function to find the next perfect squareint nextPerfectSquare(int N){ int nextN = floor(sqrt(N)) + 1; return nextN * nextN;} // Driver Codeint main(){ int n = 35; cout << nextPerfectSquare(n); return 0;} // Java implementation of above approachimport java.util.*;import java.lang.*;import java.io.*; class GFG{ // Function to find the// next perfect squarestatic int nextPerfectSquare(int N){ int nextN = (int)Math.floor(Math.sqrt(N)) + 1; return nextN * nextN;} // Driver Codepublic static void main(String args[]){ int n = 35; System.out.println (nextPerfectSquare(n));}} // This code is contributed by Subhadeep # Python3 implementation of above approach import math#Function to find the next perfect square def nextPerfectSquare(N): nextN = math.floor(math.sqrt(N)) + 1 return nextN * nextN if __name__=='__main__': N = 35 print(nextPerfectSquare(N)) # this code is contributed by Surendra_Gangwar // C# implementation of above approachusing System; class GFG{ // Function to find the// next perfect squarestatic int nextPerfectSquare(int N){ int nextN = (int)Math.Floor(Math.Sqrt(N)) + 1; return nextN * nextN;} // Driver Codepublic static void Main(){ int n = 35; Console.WriteLine(nextPerfectSquare(n));}} // This code is contributed// by Shashank <?php// PHP implementation// of above approach // Function to find the// next perfect squarefunction nextPerfectSquare($N){ $nextN = floor(sqrt($N)) + 1; return $nextN * $nextN;} // Driver Code$n = 35; echo nextPerfectSquare($n); // This code is contributed by mits?> <script>// Javascript implementation of above approach // Function to find the next perfect squarefunction nextPerfectSquare(N){ let nextN = Math.floor(Math.sqrt(N)) + 1; return nextN * nextN;} // Driver Codelet n = 35; document.write(nextPerfectSquare(n)); // This code is contributed by souravmahato348.</script> 36 Time Complexity: O(1) Auxiliary Space: O(1) tufan_gupta2000 Mithun Kumar SURENDRA_GANGWAR Shashank12 subhammahato348 souravmahato348 maths-perfect-square Mathematical School Programming Mathematical 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": 53, "s": 25, "text": "\n13 Apr, 2021" }, { "code": null, "e": 141, "s": 53, "text": "Given a number N, the task is to find the next perfect square greater than N.Examples: " }, { "code": null, "e": 247, "s": 141, "text": "Input: N = 6\nOut...
Python | Scipy integrate.romb() method
23 Jan, 2020 With the help of scipy.integrate.romb() method, we can get the romberg integration using samples of a function from limit a to b by using scipy.integrate.romb() method. Syntax : scipy.integrate.romb(y, dx, axis, show)Return : Return the romberg integration of a sample. Example #1 :In this example we can see that by using scipy.integrate.romb() method, we are able to get the romberg integration using samples of a function from limit a to b by using this method. # import numpy and scipy.integrateimport numpy as npfrom scipy import integratex = np.arange(3, 12) # using scipy.integrate.romb() methodgfg = integrate.romb(x) print(gfg) Output : 56.0 Example #2 : # import numpy and scipy.integrateimport numpy as npfrom scipy import integratex = np.arange(3, 12)y = np.cos(np.power(x, 3.5)) # using scipy.integrate.romb() methodgfg = integrate.romb(y) print(gfg) Output : -3.5943771512643674 Python-scipy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Jan, 2020" }, { "code": null, "e": 197, "s": 28, "text": "With the help of scipy.integrate.romb() method, we can get the romberg integration using samples of a function from limit a to b by using scipy.integrate.romb() method." }, ...
How to Install Pyglet in python on Windows?
22 Sep, 2021 The pyglet library is a cross-platform windowing and multimedia library for Python, intended for developing games and other visually rich applications. In this article, we will look into the process of installing Pyglet in Python on Windows. The only thing that you need for installing Numpy on Windows are: Python PIP or Conda (depending upon user preference) If you want the installation to be done through conda, open up the Anaconda Powershell Prompt and use the below command: conda install -c conda-forge pyglet Type y for yes when prompted. You will get a similar message once the installation is complete: Make sure you follow the best practices for installation using conda as: Use an environment for installation rather than in the base environment using the below command: conda create -n my-env conda activate my-env Note: If your preferred method of installation is conda-forge, use the below command: conda config --env --add channels conda-forge To verify if pyglet library has been successfully installed in your system run the below command in Anaconda Powershell Prompt: conda list pyglet You’ll get the below message if the installation is complete: If you want the installation to be done through PIP, open up the Command Prompt and use the below command: pip install pyglet You will get a similar message once the installation is complete: To verify if the Pyglet Library has been successfully installed in your system run the below command in Command Prompt: python -m pip show pyglet You’ll get the below message if the installation is complete: Blogathon-2021 how-to-install Picked Blogathon How To Installation Guide Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SQL Query to Insert Multiple Rows How to Connect Python with SQL Database? How to Import JSON Data into SQL Server? Difference Between Local Storage, Session Storage And Cookies Explain the purpose of render() in ReactJS How to Find the Wi-Fi Password Using CMD in Windows? Java Tutorial How to filter object array based on attributes? How to Align Text in HTML? How to Install FFmpeg on Windows?
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Sep, 2021" }, { "code": null, "e": 270, "s": 28, "text": "The pyglet library is a cross-platform windowing and multimedia library for Python, intended for developing games and other visually rich applications. In this article, we wil...
How to create responsive website zoomed out to full width on mobile using Bootstrap?
03 Jun, 2020 Container Classes: This is one of the predefined classes of bootstrap, that contains the entire content of the web-page in it. There are two container classes, namely, container and container-fluid classes. These classes have different properties and one can use the class that fits one’s requirement. CONTAINER-FLUID: When the content of a web-page is enclosed in a div element having the container-fluid class, all the elements enclosed in the div are filled out to the complete width of the device. CONTAINER: When the content of a web-page is enclosed in a div element having the container class, all the elements enclosed in the div are not filled out to the complete width of the device. Instead, for every standard screen-size breakpoint, there are media queries predefined.For Example: @media (min-width: 1200px) .container { max-width: 1140px;} @media (min-width: 1200px) .container { max-width: 1140px;} @media (min-width: 992px) .container { max-width: 960px; } @media (min-width: 992px) .container { max-width: 960px; } It is clear that using the container class will provide a certain amount of left and right margin, which is default and different for various screen sizes. But, there is one exception, when the screen size changes from a tablet size to a mobile size, the media query behind the container class is automatically changed, to occupy 100% width of the screen. .container {width: 100%;padding-right: 15px;padding-left: 15px;margin-right: auto;margin-left: auto;} Examples: The following example is of a responsive web-page adapting to the width of the device screen. <!DOCTYPE html><html> <head> <title>Responsive Div</title> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" /> </head> <body> <div class="container"> <center> <h1 style="color: green;"> Geeks for Geeks </h1> </center> <br /> <hr /> <br /> <h3><u>About:</u></h3> GeeksforGeeks.org was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction. <br /> <hr /> <br /> <h3><u>List of all things available:</u></h3> <ul> <li>Courses</li> <li>Internships</li> <li>Coding Practice Platforms</li> <li>Company Specific Practice Platforms</li> <li>Interview Corner</li> <li>Subject Wise Practice Questions</li> </ul> <center>and all things TECH!</center> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script> </body></html> Output: In Mobile (425 px) ananya_reddy Bootstrap-Misc Picked Bootstrap Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Show Images on Click using HTML ? How to Use Bootstrap with React? Tailwind CSS vs Bootstrap How to set vertical alignment in Bootstrap ? How to toggle password visibility in forms using Bootstrap-icons ? Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 54, "s": 26, "text": "\n03 Jun, 2020" }, { "code": null, "e": 356, "s": 54, "text": "Container Classes: This is one of the predefined classes of bootstrap, that contains the entire content of the web-page in it. There are two container classes, namely, contai...
Higher Order Functions and Currying
27 Apr, 2018 Introduction:Generally while programming, we use first class functions which means that the programming language treats functions as values – that you can assign a function into a variable, pass it around. These functions do not take other functions as parameters and never has any function as their return type.To overcome all these shortcomings of first-class functions, the concept of Higher Order function was introduced. Why we need them?In Imperative programming languages like (C/C++), we use functions very often or actually we can say that functions play a major role when programming in these languages. A typical function can be defined by function name, it’s return type and parameters it takes. We usually give int, char, pointer etc as parameter but is it possible to give one function as parameter to other function or can a function return another function as it’s result? The answer is yes! The functions which take at least one function as parameter or returns a function as it results or performs both is called Higher Order Function. Many languages including- Javascript, Go, Haskell, Python, C++, C# etc, supports Higher Order Function.It is a great tool when it comes to functional programming. Currying:Functions can be classified on the basis of the number of inputs they accept like binary function will take two inputs while a unary function will take only a single input. In Haskell, every function takes only one input that is every function in Haskell can be said unary. Then it is not possible to implement a function which take multiple parameters? Of course, it is possible, by a methodology called currying (named after Haskell Curry, scientist who made this methodology popular and invented Haskell). In currying every function takes only one argument and returns a function. While the last function in this series will return the desired output. Currying is the methodology of translating the evaluation of a function that takes multiple arguments into evaluating a sequence of functions, each with a single argument. A Simple Example of Currying:Let’s take an example, PLUS is a function which adds two number We wish to add two numbers X and Y. X will be the input to PLUS function which returns a function named PLUS X.PLUS X function takes one number and add X to it. Now input to this function will be Y. Final output will be X + Y. We wish to add two numbers X and Y. X will be the input to PLUS function which returns a function named PLUS X. PLUS X function takes one number and add X to it. Now input to this function will be Y. Final output will be X + Y. Advantages of Higher Order Functions: By use of higher order function, we can solve many problems easily. For example we need to build a function which takes a list and another function as it’s input, applies that function to each element of that list and returns the new list. In Haskell, this could be done really easily using the inbuilt higher order function called map.Definition of map is: map :: (a -> b) -> [a] -> [b] map _ [ ] = [ ] map f (x : xs) = f x : map f xs Here, The first line is function initialisation. The :: symbol stands for “is of the type”. [a] represents a list of similar element, entity written after last -> is always the return type of the function.A function in Haskell always return only one entity. (a->b) defines a function from ‘a’ to ‘b’. We used recurrence to define map,[] denotes empty list and _ denotes “anything”. Second line depicts that if empty list and any function is input then the output will be empty list. x : xs is used to take out elements one by one from list, x is the first element (head) and xs is remaining list (tail). : sign stands for concatenation. So in a nutshell, the third line is taking each element from the list and applying function ‘f’ on them and concatenating it with remaining list. Example: map (+7) [1, 2, 3, 4, 5] will return the list [8, 9, 10, 11, 12]. Here +7 is the function. GBlog Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You! Geek Streak - 24 Days POTD Challenge What is Hashing | A Complete Tutorial GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge? GeeksforGeeks Job-A-Thon Exclusive - Hiring Challenge For Amazon Alexa Types of Software Testing Roadmap to Learn JavaScript For Beginners How to Learn Data Science in 10 weeks? What is Data Structure: Types, Classifications and Applications
[ { "code": null, "e": 53, "s": 25, "text": "\n27 Apr, 2018" }, { "code": null, "e": 479, "s": 53, "text": "Introduction:Generally while programming, we use first class functions which means that the programming language treats functions as values – that you can assign a function i...
White Collar Crimes – Cyber Security
31 Jan, 2022 Every time we read about White Collar Crimes, there is always a newer and bigger one getting exposed. One is forced to ask a question- Why do they do it? Why do individuals get engaged in such self-destructive misbehaviors? White-collar crimes encompass a whole slew of offenses that might seem different but certain characteristics of them unite them under the same umbrella. White-collar crimes have evolved their dimension with the passage of time. The major transformation was seen when the internet came into existence. In this article, we will discuss the following topics: What are White-collar cybercrimes?Fusion of White-collar crimes and CybercrimesMotivation behind White-collar cybercrimesExamples of White-collar cybercrimesProblems of White-collar crimes What are White-collar cybercrimes? Fusion of White-collar crimes and Cybercrimes Motivation behind White-collar cybercrimes Examples of White-collar cybercrimes Problems of White-collar crimes White-collar crimes refer to the non-violent, illegal activities that are committed by individuals or businesses for financial gain or personal gain. Some of the examples are- bribery, insider trading, cybercrime, credit card fraud, copyright infringement, and many more. White-collar criminals are physically distant from the victims and sometimes such victims are shapeless and amorphous. They are driven by greed, invincibility, and a desire to win at all costs. The damage white-collar criminals cause to society can be massive. Most numbers of crimes that we see on the internet are white-collar crimes as they don’t involve any sort of violence and the majority of them are financially motivated. Before the internet age, these crimes were committed outside the computer but now they are occurring at a wide pace by the source of the internet and the internet world. Any crime committed on the Internet is referred to as Cybercrime, and when such crime is non-violent and especially motivated towards financial gain then it becomes a White-collar cybercrime. Academic research shows that environmental cues and signals can nudge individuals to behave differently when faced with ethical choices. Work environments in an organization can elicit good or bad behavior out of individuals. Certain individuals fail to resit to the temptations and compromise their ethical values. Below are some environment cues and signal that can trigger a white-collar behavior: Poorly designed job incentives: Financial professionals are compensated and rewarded for a short-term degree of profits. To maximize their performance-based compensations, some adopt the way of circumventing the existing laws. Management unconcern towards ethics: Investment firms use expert networks to legitimize the use of insider information for stock trading. Such cues lead analysts at such firms to violate the security laws. Unethical behavior perceived as harmless: Many stock traders view insider trading as a victimless crime. For example- many individuals committing accounting fraud start with a justification that “it is a one-time event”. Aggressive goals without goalposts: Management directives “do whatever it takes” to achieve aggressive goals open up the possibility of following unethical tactics. It is very important that the goals are delineated with clear boundaries that state clearly what is not allowed. Moral Hazard: When others are there to bear the downside, risk-takers have incentives to undertake riskier decisions. For example- Personal property insurance policies can create incentives to generate and file false policy claims. Motivated Blindness: The failure to acknowledge the unethical behavior in order to avoid consequential self-harm can sometimes lead to white-collar crime. For example- Rating agencies, who rate financial instruments as paid services, can have an incentive to bias their ratings favorably. Stealing public or private entities: Stealing from a large company or an organization can be alluring. Sometimes Doctors, pharmacists, and patients conspire to fraud the system. For example- generating bills for the services that are not rendered, overutilization of the services, and many more. In this section, we will be discussing a few examples of white-collar cybercrimes. Economic espionage and trade secret theft: These are also white-collar crimes. It is illegal to steal important plans, ideas, designs from the other person for financial benefits.Credit-card fraud: This refers to stealing another person’s credit-cards details to make purchases.Telemarketing and Mail Fraud: Telemarketing fraud involves using a phone to conduct fraudulent stealing to obtain personal information for identity theft. They frequently target senior citizens. For example- requesting to deposit advance fees to claim a phony lottery prize or government loan. Mail fraud is similar to the telemarketing fraud except that it uses mail as a medium to construct the recipients into sending money or sharing personal information.Identity Theft: This involves assuming another person’s identity information such as name, address, date of birth, or Aadhaar number to commit financial fraud. Fake passports and Fake IDs are commonly used to commit crimes and evade captures.Phishing: Phishing takes place by impersonating someone else electronically. It can be done by using someone’s login information like user id, a password for gaining access to personal information or by application of digital signature of someone else in the electronic contracts without authorization or by cloning the sim cards of mobile forms so that account can be formed using other’s information.Computer Intrusion: It is one of the most common white-collar cybercrime that occurs instantly on the Internet. It involves accessing of computer or internet without having proper authorization. Hackers attack and try to obtain personal information for monetary benefits. Economic espionage and trade secret theft: These are also white-collar crimes. It is illegal to steal important plans, ideas, designs from the other person for financial benefits. Credit-card fraud: This refers to stealing another person’s credit-cards details to make purchases. Telemarketing and Mail Fraud: Telemarketing fraud involves using a phone to conduct fraudulent stealing to obtain personal information for identity theft. They frequently target senior citizens. For example- requesting to deposit advance fees to claim a phony lottery prize or government loan. Mail fraud is similar to the telemarketing fraud except that it uses mail as a medium to construct the recipients into sending money or sharing personal information. Identity Theft: This involves assuming another person’s identity information such as name, address, date of birth, or Aadhaar number to commit financial fraud. Fake passports and Fake IDs are commonly used to commit crimes and evade captures. Phishing: Phishing takes place by impersonating someone else electronically. It can be done by using someone’s login information like user id, a password for gaining access to personal information or by application of digital signature of someone else in the electronic contracts without authorization or by cloning the sim cards of mobile forms so that account can be formed using other’s information. Computer Intrusion: It is one of the most common white-collar cybercrime that occurs instantly on the Internet. It involves accessing of computer or internet without having proper authorization. Hackers attack and try to obtain personal information for monetary benefits. In this section we will discuss a few problems associated with white-collar cybercrimes: The laws regarding white-collar cybercrimes are far-reaching, constantly changing, and often difficult to understand. Law enforcement often lags behind the technological world, and prosecutors may seek harsher charges and punishments for crimes they don’t quite understand. Investigation for these crimes takes a very long time, maybe a month or a year. The innovation of technology has made our life much sorted and easier but on the other hand, it has also given rise to white-collar crimes in the internet world. These crimes are typically unidentifiable as they do little alterations but their overall impact is much more than we think. One day we will definitely have regulations that will restrict this fusion of white-collar and computer world. References: – https://en.wikipedia.org/wiki/White-collar_crime sweetyty Cyber-security Information-Security Computer Subject Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Type Checking in Compiler Design Aptitude for Placements Difference Between Edge Computing and Fog Computing Software Engineering | Testing Guidelines What is Transmission Control Protocol (TCP)? Optimization of Basic Blocks Cloud Based Services OSI Security Architecture ASCII Table Functional Programming Paradigm
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Jan, 2022" }, { "code": null, "e": 554, "s": 28, "text": "Every time we read about White Collar Crimes, there is always a newer and bigger one getting exposed. One is forced to ask a question- Why do they do it? Why do individuals ge...
Converting a String to its Equivalent Byte Array in C#
28 May, 2020 Given a string, the task is to convert this string into a Byte array in C#. Examples: Input: aA Output: [97, 65 ] Input: Hello Output: [ 72, 101, 108, 108, 111 ] Using ToByte() Method: This method is a Convert class method. It is used to converts other base data types to a byte data type. Syntax: byte byt = Convert.ToByte(char); Step 1: Get the string. Step 2: Create a byte array of the same length as of string. Step 3: Traverse over the string to convert each character into byte using the ToByte() Method and store all the bytes to the byte array. Step 4: Return or perform the operation on the byte array. Below is the implementation of the above approach: C# // C# program to convert a given// string to its equivalent byte[] using System; public class GFG{ static public void Main () { string str = "GeeksForGeeks"; // Creating byte array of string length byte[] byt = new byte[str.Length]; // converting each character into byte // and store it for (int i = 0; i < str.Length; i++) { byt[i] = Convert.ToByte(str[i]); } // printing characters with byte values for(int i =0; i<byt.Length; i++) { Console.WriteLine("Byte of char \'" + str[i] + "\' : " + byt[i]); } } } Output: Byte of char 'G' : 71 Byte of char 'e' : 101 Byte of char 'e' : 101 Byte of char 'k' : 107 Byte of char 's' : 115 Byte of char 'F' : 70 Byte of char 'o' : 111 Byte of char 'r' : 114 Byte of char 'G' : 71 Byte of char 'e' : 101 Byte of char 'e' : 101 Byte of char 'k' : 107 Byte of char 's' : 115 Using GetBytes() Method: The Encoding.ASCII.GetBytes() method is used to accepts a string as a parameter and get the byte array. Syntax: byte[] byte_array = Encoding.ASCII.GetBytes(string str); Step 1: Get the string. Step 2: Create an empty byte array. Step 3: Convert the string into byte[] using the GetBytes() Method and store all the convert string to the byte array. Step 4: Return or perform the operation on the byte array. C# // C# program to convert a given// string to its equivalent byte[] using System;using System.Text; public class GFG{ static public void Main () { string str = "GeeksForGeeks"; // Creating byte array of string length byte[] byt; // converting each character into byte // and store it byt = Encoding.ASCII.GetBytes(str); // printing characters with byte values for(int i =0; i<byt.Length; i++) { Console.WriteLine("Byte of char \'" + str[i] + "\' : " + byt[i]); } } } Output: Byte of char 'G' : 71 Byte of char 'e' : 101 Byte of char 'e' : 101 Byte of char 'k' : 107 Byte of char 's' : 115 Byte of char 'F' : 70 Byte of char 'o' : 111 Byte of char 'r' : 114 Byte of char 'G' : 71 Byte of char 'e' : 101 Byte of char 'e' : 101 Byte of char 'k' : 107 Byte of char 's' : 115 CSharp-Byte-Struct CSharp-string C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Multiple inheritance using interfaces Introduction to .NET Framework C# | Delegates Differences Between .NET Core and .NET Framework C# | Data Types C# | String.IndexOf( ) Method | Set - 1 C# | Replace() Method C# | Arrays Extension Method in C# C# | List Class
[ { "code": null, "e": 28, "s": 0, "text": "\n28 May, 2020" }, { "code": null, "e": 104, "s": 28, "text": "Given a string, the task is to convert this string into a Byte array in C#." }, { "code": null, "e": 114, "s": 104, "text": "Examples:" }, { "code"...
Python | Numpy matrix.compress()
10 Apr, 2019 With the help of Numpy matrix.compress() method, we can select the elements from a matrix by passing a parameter as an array which contain the value 0 to not include the element or 1 to include the element in a matrix. Simply we pass the boolean array in matrix.compress() method. Syntax : matrix.compress() Return : Return a compressed array Example #1 :In this example we can see that with the help of matrix.compress() method we are able to compress a matrix. # import the important module in pythonimport numpy as np # make a matrix with numpygfg = np.matrix('[1, 2, 3, 4; 3, 1, 5, 6]') # applying matrix.compress() methodgeeks = np.compress([1, 0, 1, 0, 1, 1], gfg) print(geeks) [[1 3 3 1]] Example #2 : # import the important module in pythonimport numpy as np # make a matrix with numpygfg = np.matrix('[1, 2, 3; 4, 5, 6; 7, 8, 9]') # applying matrix.compress() methodgeeks = np.compress([1, 0, 1, 1, 1, 0, 0, 1, 1], gfg) print(geeks) [[1 3 4 5 8 9]] Python numpy-Matrix Function Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Apr, 2019" }, { "code": null, "e": 309, "s": 28, "text": "With the help of Numpy matrix.compress() method, we can select the elements from a matrix by passing a parameter as an array which contain the value 0 to not include the eleme...
Program for Binomial Coefficients table
10 May, 2022 Given an integer max, print Binomial Coefficients table that prints all binomial coefficients B(m, x) where m and x vary from 0 to maxExample : Input : max = 3 Output : 0 1 1 1 1 2 1 2 1 3 1 3 3 1 The easiest way to explain what binomial coefficients are is to say that they count certain ways of grouping items. Specifically, the binomial coefficient B(m, x) counts the number of ways to form an unordered collection of k items chosen from a collection of n distinct items. Binomial coefficients are used in the study of binomial distributions and multicomponent redundant systems. It is given by Example : Compute B(7, 3) where m = 7 and x = 1 (7!/3!(7-3)!)7 = 7!/3!*4! = (7*6*5*4*3*2*1)/(3*2*1)*(4*3*2*1) = 35 A table of binomial coefficients is required to determine the binomial coefficient for any value m and x.Problem Analysis : The binomial coefficient can be recursively calculated as follows – further, That is the binomial coefficient is one when either x is zero or m is zero. The program prints the table of binomial coefficients for . C++ Java Python3 C# PHP Javascript // C++ program for binomial coefficients#include <stdio.h> // Function to print binomial tableint printbinomial(int max){ for (int m = 0; m <= max; m++) { printf("%2d", m); int binom = 1; for (int x = 0; x <= m; x++) { // B(m, x) is 1 if either m or x // is 0. if (m != 0 && x != 0) // Otherwise using recursive formula // B(m, x) = B(m, x - 1) * (m - x + 1) / x binom = binom * (m - x + 1) / x; printf("%4d", binom); } printf("\n"); }} // Driver Functionint main(){ int max = 10; printbinomial(max); return 0;} // Java program for// binomial coefficientsimport java.io.*; class GFG{ // Function to print// binomial tablestatic void printbinomial(int max){ for (int m = 0; m <= max; m++) { System.out.print(m + " "); int binom = 1; for (int x = 0; x <= m; x++) { // B(m, x) is 1 if either // m or x is 0. if (m != 0 && x != 0) // Otherwise using // recursive formula // B(m, x) = B(m, x - 1) * // (m - x + 1) / x binom = binom * (m - x + 1) / x; System.out.print(binom + " "); } System.out.println(); }} // Driver Codepublic static void main (String[] args){ int max = 10; printbinomial(max);}} // This code is contributed// by akt_mit # Python3 program for binomial# coefficients # Function to print binomial tabledef printbinomial (max): for m in range(max + 1): print( '% 2d'% m, end = ' ') binom = 1 for x in range(m + 1): # B(m, x) is 1 if either m # or x is 0. if m != 0 and x != 0: # Otherwise using recursive # formula # B(m, x) = B(m, x - 1) * # (m - x + 1) / x binom = binom * (m - x + 1) / x print( '% 4d'% binom, end = ' ') print("\n", end = '') # Driver Functionmax = 10printbinomial(max) # This code is contributed by "Sharad_bhardwaj". // C# program for binomial coefficientsusing System; public class GFG { // Function to print binomial table static void printbinomial(int max) { for (int m = 0; m <= max; m++) { Console.Write(m + " "); int binom = 1; for (int x = 0; x <= m; x++) { // B(m, x) is 1 if either m // or x is 0. if (m != 0 && x != 0) // Otherwise using recursive formula // B(m, x) = B(m, x - 1) * (m - x + 1) / x binom = binom * (m - x + 1) / x; Console.Write(binom + " "); } Console.WriteLine(); } } // Driver Function static public void Main() { int max = 10; printbinomial(max); }} // This code is contributed by vt_m. <?php// PHP program for// binomial coefficients // Function to print// binomial tablefunction printbinomial($max){ for ($m = 0; $m <= $max; $m++) { echo $m; $binom = 1; for ($x = 0; $x <= $m; $x++) { // B(m, x) is 1 if either // m or x is 0. if ($m != 0 && $x != 0) // Otherwise using // recursive formula // B(m, x) = B(m, x - 1) * // (m - x + 1) / x $binom = $binom * ($m - $x + 1) / $x; echo " ", $binom, " "; } echo "\n"; }} // Driver Code$max = 10;printbinomial($max); // This code is contributed by aj_36?> <script>// Javascript program for// binomial coefficients // Function to print// binomial tablefunction printbinomial(max){ for (let m = 0; m <= max; m++) { document.write(m); let binom = 1; for (let x = 0; x <= m; x++) { // B(m, x) is 1 if either // m or x is 0. if (m != 0 && x != 0) // Otherwise using // recursive formula // B(m, x) = B(m, x - 1) * // (m - x + 1) / x binom = binom * (m - x + 1) / x; document.write(" " + binom + " "); } document.write("<br>"); }} // Driver Codelet max = 10;printbinomial(max); // This code is contributed by _saurabh_jaiswal</script> Output : 0 1 1 1 1 2 1 2 1 3 1 3 3 1 4 1 4 6 4 1 5 1 5 10 10 5 1 6 1 6 15 20 15 6 1 7 1 7 21 35 35 21 7 1 8 1 8 28 56 70 56 28 8 1 9 1 9 36 84 126 126 84 36 9 1 10 1 10 45 120 210 252 210 120 45 10 1 jit_t _saurabh_jaiswal simmytarika5 binomial coefficient Combinatorial Mathematical Mathematical Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Find the Number of Permutations that satisfy the given condition in an array Ways to sum to N using Natural Numbers up to K with repetitions allowed Probability of getting K heads in N coin tosses Number of handshakes such that a person shakes hands only once Count ways to partition a Binary String such that each substring contains exactly two 0s Program for Fibonacci numbers Set in C++ Standard Template Library (STL) C++ Data Types Merge two sorted arrays Coin Change | DP-7
[ { "code": null, "e": 52, "s": 24, "text": "\n10 May, 2022" }, { "code": null, "e": 198, "s": 52, "text": "Given an integer max, print Binomial Coefficients table that prints all binomial coefficients B(m, x) where m and x vary from 0 to maxExample : " }, { "code": null, ...
C library function - localeconv()
The C library function struct lconv *localeconv(void) sets or reads location dependent information. These are returned in an object of the lconv structure type. Following is the declaration for localeconv() function. struct lconv *localeconv(void) NA NA This function returns a pointer to a struct lconv for the current locale, which has the following structure − typedef struct { char *decimal_point; char *thousands_sep; char *grouping; char *int_curr_symbol; char *currency_symbol; char *mon_decimal_point; char *mon_thousands_sep; char *mon_grouping; char *positive_sign; char *negative_sign; char int_frac_digits; char frac_digits; char p_cs_precedes; char p_sep_by_space; char n_cs_precedes; char n_sep_by_space; char p_sign_posn; char n_sign_posn; } lconv The following example shows the usage of localeconv() function. #include <locale.h> #include <stdio.h> int main () { struct lconv * lc; setlocale(LC_MONETARY, "it_IT"); lc = localeconv(); printf("Local Currency Symbol: %s\n",lc->currency_symbol); printf("International Currency Symbol: %s\n",lc->int_curr_symbol); setlocale(LC_MONETARY, "en_US"); lc = localeconv(); printf("Local Currency Symbol: %s\n",lc->currency_symbol); printf("International Currency Symbol: %s\n",lc->int_curr_symbol); setlocale(LC_MONETARY, "en_GB"); lc = localeconv(); printf ("Local Currency Symbol: %s\n",lc->currency_symbol); printf ("International Currency Symbol: %s\n",lc->int_curr_symbol); printf("Decimal Point = %s\n", lc->decimal_point); return 0; } Let us compile and run the above program that will produce the following result − Local Currency Symbol: EUR International Currency Symbol: EUR Local Currency Symbol: $ International Currency Symbol: USD Local Currency Symbol: £ International Currency Symbol: GBP Decimal Point = . 12 Lectures 2 hours Nishant Malik 12 Lectures 2.5 hours Nishant Malik 48 Lectures 6.5 hours Asif Hussain 12 Lectures 2 hours Richa Maheshwari 20 Lectures 3.5 hours Vandana Annavaram 44 Lectures 1 hours Amit Diwan Print Add Notes Bookmark this page
[ { "code": null, "e": 2168, "s": 2007, "text": "The C library function struct lconv *localeconv(void) sets or reads location dependent information. These are returned in an object of the lconv structure type." }, { "code": null, "e": 2224, "s": 2168, "text": "Following is the decl...
Creating 3D Globe using React-three-fiber
In this article, you will learn how to create a globe using react-threefiber. We will first make a sphere and then map a whole Earth map on it. This is an interesting texture loader feature using which we canmake any image to wrap over a sphere as texture. So, let's get started! First, download important libraries − npm i --save @react-three/fiber three This library react-three/fiber will be used to add webGL renderer to the website and to connect threejs and React. Download an image of Earth map and place it in the “src” folder. We have named the image file as "world-map.gif". Add the following lines of code in App.js − import React, { useRef } from "react"; import { Canvas,useFrame,useLoader } from "@reactthree/fiber"; import * as THREE from "three"; import earthImg from './world-map.gif' import "./App.css"; const Sphere=()=>{ const base=new THREE.TextureLoader().load(earthImg) const ref=useRef() useFrame(() => (ref.current.rotation.x=ref.current.rotation.y += 0.01)) <return( <mesh visible castShadow ref={ref}> <directionalLight intensity={0.5} /> <sphereGeometry attach="geometry" args={[2, 32, 32]} /> <meshBasicMaterial map={base} color="white" /> </mesh> ) } export default function App(){ return ( <Canvas> <ambientLight /> <Sphere/> </Canvas> ); }; Here we first created a Sphere and loaded a texture. Then we wrapped the texture over the sphere. <mesh> is used to make threeJS object, and inside it we made a box using SphereGeometry which is used to define size, shape and other structural things. meshBasicMaterial which is use to design our geometrical structure. <mesh> is used to combine the structure and the design together. We created a functional component inside which we made a reference. Next, we created a Frame which is used to change the position of our mesh object or sphere. Then we added frame to reference and gave reference to mesh. The Position argument simply positions the object. <AmbientLight> is used to make the colors visible. In its absence, <Sphere> will look whole black. It will produce the following output − Your browser does not support HTML5 video.
[ { "code": null, "e": 1342, "s": 1062, "text": "In this article, you will learn how to create a globe using react-threefiber. We will first make a sphere and then map a whole Earth map on it. This is an interesting texture loader feature using which we canmake any image to wrap over a sphere as textu...
Music Generation Through Deep Neural Networks | by Ramya Vidiyala | Towards Data Science
Deep Learning has improved many aspects of our lives, in ways both obvious and subtle. Deep learning plays a key role in processes such as movie recommendation systems, spam detection, and computer vision. Though there is ongoing discussion around deep learning as a black box and the difficulty of training, there is huge potential for it in a wide variety of fields including medicine, virtual assistants, and eCommerce. One fascinating area in which deep learning can play a role is at the intersection of art and technology. To explore this idea further, in this article we will look at machine learning music generation via deep learning processes, a field many assume is beyond the scope of machines (and another interesting area of fierce debate!). Music Representation for Machine Learning Models Music Dataset Data Processing Model Selection Many-Many RNN Time Distributed Dense Layer Stateful Dropout layers Softmax layer Optimizer Generation of music Summary We will be working with ABC music notation. ABC notation is a shorthand form of musical notation that uses the letters A through G to represent musical notes, and other elements to place added values. These added values include sharps, flats, the length of a note, the key, and ornamentation. This form of notation began as an ASCII character set code to facilitate music sharing online, adding a new and simple language for software developers designed for ease of use. Figure 1 is a snapshot of the ABC notation of music. Lines in part 1 of the music notation show a letter followed by a colon. These indicate various aspects of the tune such as the index, when there is more than one tune in a file (X:), the title (T:), the time signature (M:), the default note length (L:), the type of tune (R:) and the key (K:). The lines following the key designation represent the tune itself. In this article, we’ll use the open-sourced data available on the ABC version of the Nottingham Music Database. It contains more than 1000 folk tunes, the vast majority of which have been converted to ABC notation. The data is currently in a character-based categorical format. In the data processing stage, we need to transform the data into an integer-based numerical format, to prepare it for working with neural networks. Here each character is mapped to a unique integer. This can be achieved using a single line of code. The ‘text’ variable is the input data. char_to_idx = { ch: i for (i, ch) in enumerate(sorted(list(set(text)))) } To train the model, we convert the entirety of text data into a numerical format using the vocab. T = np.asarray([char_to_idx[c] for c in text], dtype=np.int32) In traditional machine learning models, we cannot store a model’s previous stages. However, we can store previous stages with Recurrent Neural Networks (commonly called RNN). An RNN has a repeating module that takes input from the previous stage and gives its output as input to the next stage. However, RNNs can only retain information from the most recent stage, so our network needs more memory to learn long-term dependencies. This is where Long Short Term Memory Networks (LSTMs) come to the rescue. LSTMs are a special case of RNNs, with the same chain-like structure as RNNs, but a different repeating module structure. RNN is used here because: The length of the data doesn’t need to be fixed. For every input, the data length can vary.Sequence memory is stored.Various combinations of input and output sequence lengths can be used. The length of the data doesn’t need to be fixed. For every input, the data length can vary. Sequence memory is stored. Various combinations of input and output sequence lengths can be used. In addition to the general RNN, we’ll customize it to our use case by adding a few tweaks. We’ll use a ‘character RNN’. In character RNNs, the input, output, and transition output are in the form of characters. As we need our output generated at each timestamp, we’ll use a many-many RNN. To implement a many-many RNN, we need to set the parameter ‘return_sequences’ to true so that each character is generated at each timestamp. You can get a better understanding of it by looking at figure 5, below. In the figure above, the blue units are the input, the yellow is the hidden units, and the green is the output units. This is a simple overview of a many-many RNN. For a more detailed look at RNN sequences, here’s a helpful resource. To process the output at each timestamp, we create a time distributed dense layer. To achieve this we create a time distributed dense layer on top of the outputs generated at each timestamp. The output from the batch is passed to the following batch as input by setting the parameter stateful to true. After combining all the features, our model will look like the overview depicted in figure 6, below. The code snippet for the model architecture is as follows: model = Sequential()model.add(Embedding(vocab_size, 512, batch_input_shape=(BATCH_SIZE, SEQ_LENGTH)))for i in range(3): model.add(LSTM(256, return_sequences=True, stateful=True)) model.add(Dropout(0.2))model.add(TimeDistributed(Dense(vocab_size)))model.add(Activation('softmax'))model.summary()model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) I highly recommend playing around with the layers to improve the performance. Dropout layers are a regularization technique that consists of a fraction of input units to zero at each update during the training to prevent overfitting. The fraction is determined by the parameter used with the layer. The generation of music is a multi-class classification problem, where each class is a unique character from the input data. Hence we are using a softmax layer on top of our model and categorical cross-entropy as a loss function. This layer gives the probability of each class. From the list of probability, we select the one with the largest probability. To optimize our model, we use Adaptive Moment Estimation, also called Adam, as it is a very good choice for RNN. Till now we created an RNN model and trained it on our input data. This model learned patterns of input data during the training phase. Let’s call this model the ‘trained model’. The input size used in the trained model is the batch size. And for the generation of music via machine learning, the input size is a single character. So we create a new model which is similar to the trained model, but with the input size of a single character which is (1,1). To this new model, we load the weights from the trained model to replicate the characteristics of the trained model. model2 = Sequential()model2.add(Embedding(vocab_size, 512, batch_input_shape=(1,1)))for i in range(3): model2.add(LSTM(256, return_sequences=True, stateful=True)) model2.add(Dropout(0.2))model2.add(TimeDistributed(Dense(vocab_size)))model2.add(Activation(‘softmax’)) We load the weights of the trained model to the new model. This can be achieved using a single line of code. model2.load_weights(os.path.join(MODEL_DIR,‘weights.100.h5’.format(epoch)))model2.summary() In the process of music generation, the first character is chosen randomly from the unique set of characters, the next character is generated using the previously generated character and so on. With this structure, we generate music. Here is the code snippet that helps us achieve this. sampled = []for i in range(1024): batch = np.zeros((1, 1)) if sampled: batch[0, 0] = sampled[-1] else: batch[0, 0] = np.random.randint(vocab_size) result = model2.predict_on_batch(batch).ravel() sample = np.random.choice(range(vocab_size), p=result) sampled.append(sample)print("sampled")print(sampled)print(''.join(idx_to_char[c] for c in sampled)) Here are a few generated pieces of music: We generated these pleasant samples of music using machine learning neural networks known as LSTMs. For every generation, the patterns will be different but similar to the training data. These melodies can be used for a wide variety of purposes: To enhance artists’ creativity through inspiration As a productivity tool to develop new ideas As additional tunes to artists’ compositions To complete an unfinished piece of work As a standalone piece of music However, this model can still be improved. Our training data consisted of a single instrument, the piano. One way we could enhance our training data is by adding music from multiple instruments. Another would be to increase the genres of music, their rhythms, and their timing signatures. At present, our model generates a few false notes and the music is not exceptional. We could reduce these errors and increase the quality of our music by increasing our training dataset as detailed above. In this article, we looked at how to process music for use with neural networks, the in-depth workings of deep learning models like RNN & LSTMs, and we also explored how tweaking a model can result in music generation. We can apply these concepts to any other system where we generate other formats of art, including generating landscape paintings or human portraits. Thanks for reading! This article was originally posted here. If you would like to experiment with this custom dataset yourself, you can download the annotated data here and see my code at Github. I am going to write more beginner-friendly posts in the future too. Follow me up on Medium to be informed about them. I welcome feedback and can be reached out on Twitter ramya_vidiyala and LinkedIn RamyaVidiyala. Happy learning!
[ { "code": null, "e": 470, "s": 47, "text": "Deep Learning has improved many aspects of our lives, in ways both obvious and subtle. Deep learning plays a key role in processes such as movie recommendation systems, spam detection, and computer vision. Though there is ongoing discussion around deep lea...
How to compare timestamps in MySQL?
To compare timestamps in MySQL, you can use DATE(). Let us first create a table− mysql> create table comparingTimestampDemo -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> AdmissionDate timestamp -> ); Query OK, 0 rows affected (0.54 sec) Following is the query to insert records in the table using insert command − mysql> insert into comparingTimestampDemo(AdmissionDate) values('2019-03-31'); Query OK, 1 row affected (0.13 sec) mysql> insert into comparingTimestampDemo(AdmissionDate) values('2019-04-10'); Query OK, 1 row affected (0.12 sec) mysql> insert into comparingTimestampDemo(AdmissionDate) values('2019-04-15'); Query OK, 1 row affected (0.17 sec) mysql> insert into comparingTimestampDemo(AdmissionDate) values('2019-03-29'); Query OK, 1 row affected (0.15 sec) mysql> insert into comparingTimestampDemo(AdmissionDate) values('2019-04-07'); Query OK, 1 row affected (0.18 sec) Following is the query to display all records from the table using select statement − mysql> select * from comparingTimestampDemo; This will produce the following output − +----+---------------------+ | Id | AdmissionDate | +----+---------------------+ | 1 | 2019-03-31 00:00:00 | | 2 | 2019-04-10 00:00:00 | | 3 | 2019-04-15 00:00:00 | | 4 | 2019-03-29 00:00:00 | | 5 | 2019-04-07 00:00:00 | +----+---------------------+ 5 rows in set (0.00 sec) Let us now compare timestamps in MySQL − mysql> SELECT DATE(`AdmissionDate`) FROM comparingTimestampDemo WHERE DATE(`AdmissionDate`) < CURDATE() - INTERVAL 3 DAY; This will produce the following output − +-----------------------+ | DATE(`AdmissionDate`) | +-----------------------+ | 2019-03-31 | | 2019-03-29 | +-----------------------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1143, "s": 1062, "text": "To compare timestamps in MySQL, you can use DATE(). Let us first create a table−" }, { "code": null, "e": 1320, "s": 1143, "text": "mysql> create table comparingTimestampDemo\n -> (\n -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY...
Construct lexicographically smallest palindrome - GeeksforGeeks
29 Apr, 2021 Given a string of lowercase alphabets. Some of characters of given string got corrupted and are now represented by *. We can replace * with any of lowercase alphabets. You have to construct lexicographically smallest palindrome string. If it is not possible to construct a palindrome print “Not Possible”. Examples: Input : str[] = "bc*b" Output : bccb Input : str[] = "bc*a*cb" Output : bcaaacb Input : str[] = "bac*cb" Output : Not Possible Start traversing the string from both end. Say with i=0, j=strlen-1, keep increasing i and decreasing j after every single iteration till i exceeds j. Now at any intermediate position we have five possible case : str[i] and str[j] both are same and also not equal to ‘*’. In this case simply continue.str[i] and str[j] both are same and are equal to ‘*’. Here you must fill str[i] = str[j] = ‘a’ for smallest possible palindrome.str[i] equals to ‘*’ and str[j] is some alphabet. Here fill str[i] = str[j] to make our string a palindrome.str[j] equals to ‘*’ and str[i] is some alphabet. Here fill str[j] = str[i] to make our string a palindrome.str[i] is not equals to str[j] and also both are some alphabet. In this case palindrome construction is not possible. So, print “Not Possible” and break from loop. str[i] and str[j] both are same and also not equal to ‘*’. In this case simply continue. str[i] and str[j] both are same and are equal to ‘*’. Here you must fill str[i] = str[j] = ‘a’ for smallest possible palindrome. str[i] equals to ‘*’ and str[j] is some alphabet. Here fill str[i] = str[j] to make our string a palindrome. str[j] equals to ‘*’ and str[i] is some alphabet. Here fill str[j] = str[i] to make our string a palindrome. str[i] is not equals to str[j] and also both are some alphabet. In this case palindrome construction is not possible. So, print “Not Possible” and break from loop. After i exceeds j means we have got our required palindrome. Else we got “Not possible” as result. C++ Java Python3 C# PHP Javascript // CPP for constructing smallest palindrome#include <bits/stdc++.h>using namespace std; // function for printing palindromestring constructPalin(string str, int len){ int i = 0, j = len - 1; // iterate till i<j for (; i < j; i++, j--) { // continue if str[i]==str[j] if (str[i] == str[j] && str[i] != '*') continue; // update str[i]=str[j]='a' if both are '*' else if (str[i] == str[j] && str[i] == '*') { str[i] = 'a'; str[j] = 'a'; continue; } // update str[i]=str[j] if only str[i]='*' else if (str[i] == '*') { str[i] = str[j]; continue; } // update str[j]=str[i] if only str[j]='*' else if (str[j] == '*') { str[j] = str[i]; continue; } // else print not possible and return cout << "Not Possible"; return ""; } return str;} // driver programint main(){ string str = "bca*xc**b"; int len = str.size(); cout << constructPalin(str, len); return 0;} // Java for constructing smallest palindromeclass GFG{ // function for printing palindromestatic String constructPalin(char []str, int len){ int i = 0, j = len - 1; // iterate till i<j for (; i < j; i++, j--) { // continue if str[i]==str[j] if (str[i] == str[j] && str[i] != '*') continue; // update str[i]=str[j]='a' if both are '*' else if (str[i] == str[j] && str[i] == '*') { str[i] = 'a'; str[j] = 'a'; continue; } // update str[i]=str[j] if only str[i]='*' else if (str[i] == '*') { str[i] = str[j]; continue; } // update str[j]=str[i] if only str[j]='*' else if (str[j] == '*') { str[j] = str[i]; continue; } // else print not possible and return System.out.println("Not Possible"); return ""; } return String.valueOf(str);} // Driver codepublic static void main(String[] args){ String str = "bca*xc**b"; int len = str.length(); System.out.println(constructPalin(str.toCharArray(), len));}} // This code is contributed by 29AjayKumar # Python3 for constructing smallest palindrome # function for printing palindromedef constructPalin(string, l): string = list(string) i = -1 j = l # iterate till i<j while i < j: i += 1 j -= 1 # continue if str[i]==str[j] if (string[i] == string[j] and string[i] != '*'): continue # update str[i]=str[j]='a' if both are '*' elif (string[i] == string[j] and string[i] == '*'): string[i] = 'a' string[j] = 'a' continue # update str[i]=str[j] if only str[i]='*' elif string[i] == '*': string[i] = string[j] continue # update str[j]=str[i] if only str[j]='*' elif string[j] == '*': string[j] = string[i] continue # else print not possible and return print("Not Possible") return "" return ''.join(string) # Driver Codeif __name__ == "__main__": string = "bca*xc**b" l = len(string) print(constructPalin(string, l)) # This code is contributed by# sanjeev2552 // C# for constructing smallest palindromeusing System; class GFG{ // function for printing palindromestatic String constructPalin(char []str, int len){ int i = 0, j = len - 1; // iterate till i<j for (; i < j; i++, j--) { // continue if str[i]==str[j] if (str[i] == str[j] && str[i] != '*') continue; // update str[i]=str[j]='a' if both are '*' else if (str[i] == str[j] && str[i] == '*') { str[i] = 'a'; str[j] = 'a'; continue; } // update str[i]=str[j] if only str[i]='*' else if (str[i] == '*') { str[i] = str[j]; continue; } // update str[j]=str[i] if only str[j]='*' else if (str[j] == '*') { str[j] = str[i]; continue; } // else print not possible and return Console.WriteLine("Not Possible"); return ""; } return String.Join("",str);} // Driver codepublic static void Main(String[] args){ String str = "bca*xc**b"; int len = str.Length; Console.WriteLine(constructPalin(str.ToCharArray(), len));}} // This code contributed by Rajput-Ji <?php// PHP for constructing smallest palindrome // function for printing palindromefunction constructPalin($str, $len){ $i = 0; $j = $len - 1; // iterate till i<j for (; $i < $j; $i++, $j--) { // continue if str[i]==str[j] if ($str[$i] == $str[$j] && $str[$i] != '*') continue; // update str[i]=str[j]='a' if both are '*' else if ($str[$i] == $str[$j] && $str[$i] == '*') { $str[$i] = 'a'; $str[$j] = 'a'; continue; } // update str[i]=str[j] if only str[i]='*' else if ($str[$i] == '*') { $str[$i] = $str[$j]; continue; } // update str[j]=str[i] if only str[j]='*' else if ($str[$j] == '*') { $str[$j] = $str[$i]; continue; } // else print not possible and return echo "Not Possible"; return ""; } return $str;} // Driver Code$str = "bca*xc**b";$len = strlen($str);echo constructPalin($str, $len); // This code is contributed by ita_c?> <script> // javascript for constructing smallest palindrome // function for printing palindromefunction constructPalin(str, len){ var i = 0, j = len - 1; // iterate till i<j for (; i < j; i++, j--) { // continue if str[i]==str[j] if (str[i] == str[j] && str[i] != '*') continue; // update str[i]=str[j]='a' if both are '*' else if (str[i] == str[j] && str[i] == '*') { str[i] = 'a'; str[j] = 'a'; continue; } // update str[i]=str[j] if only str[i]='*' else if (str[i] == '*') { str[i] = str[j]; continue; } // update str[j]=str[i] if only str[j]='*' else if (str[j] == '*') { str[j] = str[i]; continue; } // else print not possible and return document.write( "Not Possible"); return ""; } return str.join("");} // driver programvar str = "bca*xc**b".split("");var len = str.length;document.write( constructPalin(str, len)); </script> Output: bcacxcacb ukasp 29AjayKumar Rajput-Ji sanjeev2552 noob2000 lexicographic-ordering palindrome Strings Strings palindrome Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python program to check if a string is palindrome or not KMP Algorithm for Pattern Searching Different methods to reverse a string in C/C++ Convert string to char array in C++ Longest Palindromic Substring | Set 1 Array of Strings in C++ (5 Different Ways to Create) Caesar Cipher in Cryptography Reverse words in a given string Check whether two strings are anagram of each other Top 50 String Coding Problems for Interviews
[ { "code": null, "e": 24991, "s": 24963, "text": "\n29 Apr, 2021" }, { "code": null, "e": 25309, "s": 24991, "text": "Given a string of lowercase alphabets. Some of characters of given string got corrupted and are now represented by *. We can replace * with any of lowercase alphab...
Count of strings where adjacent characters are of difference one - GeeksforGeeks
28 Apr, 2021 Given a number n, count the number of strings of length n such that every string has adjacent characters with a difference between ASCII values as 1. Examples: Input : N = 1 Output : Total strings are 26 Explanation : For N=1, strings are a, b, c,, ...., x, y, z Input : N = 2 Output : Total strings are 50 Explanation : For N = 2, strings are ab, ba, bc, cb, .., yx, yz, zy For strings starting with character ‘A’ and length ‘i’, we consider all strings of length ‘i-1’ and starting with character ‘B’For strings starting with character ‘G’ and length ‘i’, we consider all strings of length ‘i-1’ and starting with character ‘H’ and all strings of length ‘i-1’ and starting with ‘F’.We take the base case for n = 1, and set result for all 26 characters as 1. This simply means when 1 character string is consider all alphabets from a-z are taken only once.For N = 2, For N = 3, Conclusion : For N = n countAdjacent(n) dp[i][j] finally stores count of strings of length i and starting with character j. Initialize dp[n+1][27] as 0 Initialize dp[1][j] = 1 where j = 0 to 25 for i = 2 to n for j = 0 to 25 if (j = 0) dp[i][j] = dp[i-1][j+1]; else dp[i][j] = dp[i-1][j-1] + dp[i-1][j+1]; Sum of n-th row from 0 to 25 is the result. C++ Java Python 3 C# Javascript // CPP Program to count strings with adjacent// characters.#include <bits/stdc++.h>using namespace std; int countStrs(int n){ long int dp[n + 1][27]; // Initializing arr[n+1][27] to 0 memset(dp, 0, sizeof(dp)); // Initialing 1st row all 1 from 0 to 25 for (int i = 0; i <= 25; i++) dp[1][i] = 1; // Begin evaluating from i=2 since 1st row is set for (int i = 2; i <= n; i++) { for (int j = 0; j <= 25; j++) // j=0 is 'A' which can make strings // of length i using strings of length // i-1 and starting with 'B' if (j == 0) dp[i][j] = dp[i - 1][j + 1]; else dp[i][j] = (dp[i - 1][j - 1] + dp[i - 1][j + 1]); } // Our result is sum of last row. long int sum = 0; for (int i = 0; i <= 25; i++) sum = (sum + dp[n][i]); return sum;} // Driver's Codeint main(){ int n = 3; cout << "Total strings are : " << countStrs(n); return 0;} // Java Program to count strings// with adjacent characters.class GFG{ static long countStrs(int n) { long[][] dp = new long[n + 1][27]; // Initializing arr[n+1][27] to 0 for (int i = 0; i < n + 1; i++) { for (int j = 0; j < 27; j++) { dp[i][j] = 0; } } // Initialing 1st row all 1 from 0 to 25 for (int i = 0; i <= 25; i++) { dp[1][i] = 1; } // Begin evaluating from i=2 // since 1st row is set for (int i = 2; i <= n; i++) { // j=0 is 'A' which can make strings for (int j = 0; j <= 25; j++) // of length i using strings of length // i-1 and starting with 'B' { if (j == 0) { dp[i][j] = dp[i - 1][j + 1]; } else { dp[i][j] = (dp[i - 1][j - 1] + dp[i - 1][j + 1]); } } } // Our result is sum of last row. long sum = 0; for (int i = 0; i <= 25; i++) { sum = (sum + dp[n][i]); } return sum; } // Driver Code public static void main(String[] args) { int n = 3; System.out.println("Total strings are : " + countStrs(n)); }} // This code is contributed by 29AjayKumar # Python3 Program to count strings with# adjacent characters.def countStrs(n): # Initializing arr[n+1][27] to 0 dp = [[0 for j in range(27)] for i in range(n + 1)] # Initialing 1st row all 1 from 0 to 25 for i in range(0, 26): dp[1][i] = 1 # Begin evaluating from i=2 since # 1st row is set for i in range(2, n + 1): for j in range(0, 26): # j=0 is 'A' which can make strings # of length i using strings of length # i-1 and starting with 'B' if(j == 0): dp[i][j] = dp[i - 1][j + 1]; else: dp[i][j] = (dp[i - 1][j - 1] + dp[i - 1][j + 1]) # Our result is sum of last row. sum = 0 for i in range(0, 26): sum = sum + dp[n][i] return sum # Driver's Codeif __name__ == "__main__": n = 3 print("Total strings are : ", countStrs(n)) # This code is contributed by Sairahul Jella // C# Program to count strings with // adjacent characters.using System; class GFG{ static long countStrs(int n) { long[,] dp = new long[n + 1, 27]; // Initializing arr[n+1][27] to 0 for(int i = 0; i < n + 1; i++) for(int j = 0; j < 27; j++) dp[i, j] = 0; // Initialing 1st row all 1 from 0 to 25 for (int i = 0; i <= 25; i++) dp[1, i] = 1; // Begin evaluating from i=2 since 1st row is set for (int i = 2; i <= n; i++) { for (int j = 0; j <= 25; j++) // j=0 is 'A' which can make strings // of length i using strings of length // i-1 and starting with 'B' if (j == 0) dp[i, j] = dp[i - 1, j + 1]; else dp[i, j] = (dp[i - 1, j - 1] + dp[i - 1, j + 1]); } // Our result is sum of last row. long sum = 0; for (int i = 0; i <= 25; i++) sum = (sum + dp[n, i]); return sum; } // Driver Code static void Main() { int n = 3; Console.Write("Total strings are : " + countStrs(n)); }} // This code is contributed by DrRoot_ <script>// JavaScript Program to count strings// with adjacent characters. function countStrs(n) { let dp = new Array(n + 1); // Loop to create 2D array using 1D array for (var i = 0; i < dp.length; i++) { dp[i] = new Array(2); } // Initializing arr[n+1][27] to 0 for (let i = 0; i < n + 1; i++) { for (let j = 0; j < 27; j++) { dp[i][j] = 0; } } // Initialing 1st row all 1 from 0 to 25 for (let i = 0; i <= 25; i++) { dp[1][i] = 1; } // Begin evaluating from i=2 // since 1st row is set for (let i = 2; i <= n; i++) { // j=0 is 'A' which can make strings for (let j = 0; j <= 25; j++) // of length i using strings of length // i-1 and starting with 'B' { if (j == 0) { dp[i][j] = dp[i - 1][j + 1]; } else { dp[i][j] = (dp[i - 1][j - 1] + dp[i - 1][j + 1]); } } } // Our result is sum of last row. let sum = 0; for (let i = 0; i <= 25; i++) { sum = (sum + dp[n][i]); } return sum; } // Driver Code let n = 3; document.write("Total strings are : " + countStrs(n)); </script> Output: Total strings are : 98 This article is contributed by Shubham Rana. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Sairahul Jella DrRoot_ 29AjayKumar code_hunt Dynamic Programming Strings Strings Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Overlapping Subproblems Property in Dynamic Programming | DP-1 Edit Distance | DP-5 Efficient program to print all prime factors of a given number Find minimum number of coins that make a given value Reverse a string in Java Write a program to reverse an array or string Write a program to print all permutations of a given string C++ Data Types Python program to check if a string is palindrome or not
[ { "code": null, "e": 24914, "s": 24886, "text": "\n28 Apr, 2021" }, { "code": null, "e": 25065, "s": 24914, "text": "Given a number n, count the number of strings of length n such that every string has adjacent characters with a difference between ASCII values as 1. " }, { ...
Talend - Quick Guide
Talend is a software integration platform which provides solutions for Data integration, Data quality, Data management, Data Preparation and Big Data. The demand for ETL professionals with knowledge on Talend is high. Also, it is the only ETL tool with all the plugins to integrate with Big Data ecosystem easily. According to Gartner, Talend falls in Leaders magic quadrant for Data Integration tools. Talend offers various commercial products as listed below − Talend Data Quality Talend Data Integration Talend Data Preparation Talend Cloud Talend Big Data Talend MDM (Master Data Management) Platform Talend Data Services Platform Talend Metadata Manager Talend Data Fabric Talend also offers Open Studio, which is an open source free tool used widely for Data Integration and Big Data. The following are the system requirements to download and work on Talend Open Studio − Microsoft Windows 10 Ubuntu 16.04 LTS Apple macOS 10.13/High Sierra Memory - Minimum 4 GB, Recommended 8 GB Storage Space - 30 GB Besides, you also need an up and running Hadoop cluster (preferably Cloudera. Note − Java 8 must be available with environment variables already set. To download Talend Open Studio for Big Data and Data Integration, please follow the steps given below − Step 1 − Go to the page: https://www.talend.com/products/big-data/big-data-open-studio/ and click the download button. You can see that TOS_BD_xxxxxxx.zip file starts downloading. Step 2 − After the download finishes, extract the contents of the zip file, it will create a folder with all the Talend files in it. Step 3 − Open the Talend folder and double click the executable file: TOS_BD-win-x86_64.exe. Accept the User License Agreement. Step 4 − Create a new project and click Finish. Step 5 − Click Allow Access in case you get Windows Security Alert. Step 6 − Now, Talend Open Studio welcome page will open. Step 7 − Click Finish to install the Required third-party libraries. Step 8 − Accept the terms and click on Finish. Step 9 − Click Yes. Now your Talend Open Studio is ready with necessary libraries. Talend Open Studio is a free open source ETL tool for Data Integration and Big Data. It is an Eclipse based developer tool and job designer. You just need to Drag and Drop components and connect them to create and run ETL or ETL Jobs. The tool will create the Java code for the job automatically and you need not write a single line of code. There are multiple options to connect with Data Sources such as RDBMS, Excel, SaaS Big Data ecosystem, as well as apps and technologies like SAP, CRM, Dropbox and many more. Some important benefits which Talend Open Studio offers are as below − Provides all features needed for data integration and synchronization with 900 components, built-in connectors, converting jobs to Java code automatically and much more. Provides all features needed for data integration and synchronization with 900 components, built-in connectors, converting jobs to Java code automatically and much more. The tool is completely free, hence there are big cost savings. The tool is completely free, hence there are big cost savings. In last 12 years, multiple giant organizations have adopted TOS for Data integration, which shows very high trust factor in this tool. In last 12 years, multiple giant organizations have adopted TOS for Data integration, which shows very high trust factor in this tool. The Talend community for Data Integration is very active. The Talend community for Data Integration is very active. Talend keeps on adding features to these tools and the documentations are well structured and very easy to follow. Talend keeps on adding features to these tools and the documentations are well structured and very easy to follow. Most organizations get data from multiple places and are store it separately. Now if the organization has to do decision making, it has to take data from different sources, put it in a unified view and then analyze it to get a result. This process is called as Data Integration. Data Integration offers many benefits as described below − Improves collaboration between different teams in the organization trying to access organization data. Improves collaboration between different teams in the organization trying to access organization data. Saves time and eases data analysis, as the data is integrated effectively. Saves time and eases data analysis, as the data is integrated effectively. Automated data integration process synchronizes the data and eases real time and periodic reporting, which otherwise is time consuming if done manually. Automated data integration process synchronizes the data and eases real time and periodic reporting, which otherwise is time consuming if done manually. Data which is integrated from several sources matures and improves over time, which eventually helps in better data quality. Data which is integrated from several sources matures and improves over time, which eventually helps in better data quality. In this section, let us understand how to work on Talend projects − Double click on TOS Big Data executable file, the window shown below will open. Select Create a new project option, mention the name of the project and click on Create. Select the project your created and click Finish. Double click on TOS Big Data executable file, you can see the window as shown below. Select Import a demo project option and click Select. You can choose from the options shown below. Here we are choosing Data Integration Demos. Now, click Finish. Now, give the Project name and description. Click Finish. You can see your imported project under existing projects list. Now, let us understand how to import an existing Talend project. Select Import an existing project option and click on Select. Give Project Name and select the “Select root directory” option. Browse your existing Talend project home directory and click Finish. Your existing Talend project will get imported. Select a project from existing project and click Finish. This will open that Talend project. To delete a project, click Manage Connections. Click Delete Existing Project(s) Select the project you want to delete and click Ok. Click OK again. Click Export project option. Select the project you want to export and give a path to where it should be exported. Click on Finish. Business Model is a graphical representation of a data integration project. It is a non-technical representation of the workflow of the business. A business model is built to show the higher management what you are doing, and it also makes your team understand what you are trying to accomplish. Designing a Business Model is considered as one the best practices which organizations adopt at the beginning of their data integration project. Besides, helping in reducing costs, it finds and resolves the bottlenecks in your project. The model can be modified during and after the implementation of the project, if required. Talend open studio provides multiple shapes and connectors to create and design a business model. Each module in a business model can have a documentation attached to itself. Talend Open Studio offers the following shapes and connector options for creating a business model − Decision − This shape is used for putting if condition in the model. Decision − This shape is used for putting if condition in the model. Action − This shape is used to show any transformation, translation or formatting. Action − This shape is used to show any transformation, translation or formatting. Terminal − This shape shows the output terminal type. Terminal − This shape shows the output terminal type. Data − This shape is used show data type. Data − This shape is used show data type. Document − This shape is used for inserting a document object which can be used for input/output of the data processed. Document − This shape is used for inserting a document object which can be used for input/output of the data processed. Input − This shape is used for inserting input object using which user can pass the data manually. Input − This shape is used for inserting input object using which user can pass the data manually. List − This shape contains the extracted data and it can be defined to hold only certain kind of data in the list. List − This shape contains the extracted data and it can be defined to hold only certain kind of data in the list. Database − This shape is used for holding the input / output data. Database − This shape is used for holding the input / output data. Actor − This shape symbolizes the individuals involved in decision making and technical processes Actor − This shape symbolizes the individuals involved in decision making and technical processes Ellipse − Inserts an Ellipse shape. Gear − This shape shows the manual programs that has to be replaced by Talend jobs. Ellipse − Inserts an Ellipse shape. Gear − This shape shows the manual programs that has to be replaced by Talend jobs. All the operations in Talend are performed by connectors and components. Talend offers 800+ connectors and components to perform several operations. These components are present in palette, and there are 21 main categories to which components belong. You can choose the connectors and just drag and drop it in the designer pane, it will create java code automatically which will get compiled when you save the Talend code. Main categories which contains components are shown below − The following is the list of widely used connectors and components for data integration in Talend Open Studio − tMysqlConnection − Connects to MySQL database defined in the component. tMysqlConnection − Connects to MySQL database defined in the component. tMysqlInput − Runs database query to read a database and extract fields (tables, views etc.) depending on the query. tMysqlInput − Runs database query to read a database and extract fields (tables, views etc.) depending on the query. tMysqlOutput − Used to write, update, modify data in a MySQL database. tMysqlOutput − Used to write, update, modify data in a MySQL database. tFileInputDelimited − Reads a delimited file row by row and divides them into separate fields and passes it to the next component. tFileInputDelimited − Reads a delimited file row by row and divides them into separate fields and passes it to the next component. tFileInputExcel − Reads an excel file row by row and divides them into separate fields and passes it to the next component. tFileInputExcel − Reads an excel file row by row and divides them into separate fields and passes it to the next component. tFileList − Gets all the files and directories from a given file mask pattern. tFileList − Gets all the files and directories from a given file mask pattern. tFileArchive − Compresses a set of files or folders in to zip, gzip or tar.gz archive file. tFileArchive − Compresses a set of files or folders in to zip, gzip or tar.gz archive file. tRowGenerator − Provides an editor where you can write functions or choose expressions to generate your sample data. tRowGenerator − Provides an editor where you can write functions or choose expressions to generate your sample data. tMsgBox − Returns a dialog box with the message specified and an OK button. tMsgBox − Returns a dialog box with the message specified and an OK button. tLogRow − Monitors the data getting processed. It displays data/output in the run console. tLogRow − Monitors the data getting processed. It displays data/output in the run console. tPreJob − Defines the sub jobs that will run before your actual job starts. tPreJob − Defines the sub jobs that will run before your actual job starts. tMap − Acts as a plugin in Talend studio. It takes data from one or more sources, transforms it, and then sends the transformed data to one or more destinations. tMap − Acts as a plugin in Talend studio. It takes data from one or more sources, transforms it, and then sends the transformed data to one or more destinations. tJoin − Joins 2 tables by performing inner and outer joins between the main flow and the lookup flow. tJoin − Joins 2 tables by performing inner and outer joins between the main flow and the lookup flow. tJava − Enables you to use personalized java code in the Talend program. tJava − Enables you to use personalized java code in the Talend program. tRunJob − Manages complex job systems by running one Talend job after another. tRunJob − Manages complex job systems by running one Talend job after another. This is the technical implementation/graphical representation of the business model. In this design, one or more components are connected with each other to run a data integration process. Thus, when you drag and drop components in the design pane and connect then with connectors, a job design converts everything to code and creates a complete runnable program which forms the data flow. In the repository window, right click the Job Design and click Create Job. Provide the name, purpose and description of the job and click Finish. You can see your job has been created under Job Design. Now, let us use this job to add components, connect and configure them. Here, we will take an excel file as an input and produce an excel file as an output with same data. There are several components in the palette to choose. There is a search option also, in which you can enter the name of the component to select it. Since, here we are taking an excel file as an input, we will drag and drop tFileInputExcel component from the palette to the Designer window. Now if you click anywhere on the designer window, a search box will appear. Find tLogRow and select it to bring it in the designer window. Finally, select tFileOutputExcel component from the palette and drag drop it in designer window. Now, the adding of the components is done. After adding components, you must connect them. Right click the first component tFileInputExcel and draw a Main line to tLogRow as shown below. Similarly, right click tLogRow and draw a Main line on tFileOutputExcel. Now, your components are connected. After adding and connecting the components in the job, you need to configure them. For this, double click the first component tFileInputExcel to configure it. Give the path of your input file in File name/stream as shown below. If your 1st row in the excel is having the column names, put 1 in the Header option. Click Edit schema and add the columns and its type according to your input excel file. Click Ok after adding the schema. Click Yes. In tLogRow component, click on sync columns and select the mode in which you want to generate the rows from your input. Here we have selected Basic mode with “,” as field separator. Finally, in tFileOutputExcel component, give the path of file name where you want to store your output excel file with the sheet name. Click on sync columns. Once you are done with adding, connecting and configuring your components, you are ready to execute your Talend job. Click Run button to begin the execution. You will see the output in the basic mode with “,” separator. You can also see that your output is saved as an excel at the output path you mentioned. Metadata basically means data about data. It tells about what, when, why, who, where, which, and how of data. In Talend, metadata has the entire information about the data which is present in Talend studio. The metadata option is present inside the Repository pane of Talend Open Studio. Various sources like DB Connections, different kind of files, LDAP, Azure, Salesforce, Web Services FTP, Hadoop Cluster and many more options are present under Talend Metadata. The main use of metadata in Talend Open Studio is that you can use these data sources in several jobs just by a simple drag and drop from the Metadata in repository panel. Context variables are the variables which can have different values in different environments. You can create a context group which can hold multiple context variables. You need not add each context variable one by one to a job, you can simply add the context group to the job. These variables are used to make the code production ready. Its means by using context variables, you can move the code in development, test or production environments, it will run in all the environments. In any job, you can go to Contexts tab as shown below and add context variables. In this chapter, let us look into managing jobs and the corresponding functionalities included in Talend. Activating/Deactivating a Component is very simple. You just need to select the component, right click on it, and choose the deactivate or activate that component option. To export item from the job, right click on the job in the Job Designs and click Export items. Enter the path where you want to export the item and click Finish. To import item from the job, right click on the job in the Job Designs and click on Import items. Browse the root directory from where you want to import the items. Select all the checkboxes and click Finish. In this chapter, let us understand handling a job execution in Talend. To build a job, right click the job and select Build Job option. Mention the path where you want to archive the job, select job version and build type, then click Finish. To run a job in a normal node, you need to select “Basic Run” and click the Run button for the execution to begin. To run job in a debug mode, add breakpoint to the components you want to debug. Then, select and right click on the component, click Add Breakpoint option. Observe that here we have added breakpoints to tFileInputExcel and tLogRow components. Then, go to Debug Run, and click Java Debug button. You can observe from the following screenshot that the job will now execute in debug mode and according to the breakpoints that we have mentioned. In Advanced setting, you can select from Statistics, Exec Time, Save Job before Execution, Clear before Run and JVM settings. Each of this option has the functionality as explained here − Statistics − It displays the performance rate of the processing; Statistics − It displays the performance rate of the processing; Exec Time − The time taken to execute the job. Exec Time − The time taken to execute the job. Save Job before Execution − Automatically saves the job before the execution begins. Save Job before Execution − Automatically saves the job before the execution begins. Clear before Run − Removes everything from the output console. Clear before Run − Removes everything from the output console. JVM Settings − Helps us to configure own Java arguments. JVM Settings − Helps us to configure own Java arguments. The tag line for Open Studio with Big data is “Simplify ETL and ELT with the leading free open source ETL tool for big data.” In this chapter, let us look into the usage of Talend as a tool for processing data on big data environment. Talend Open Studio – Big Data is a free and open source tool for processing your data very easily on a big data environment. You have plenty of big data components available in Talend Open Studio , that lets you create and run Hadoop jobs just by simple drag and drop of few Hadoop components. Besides, we do not need to write big lines of MapReduce codes; Talend Open Studio Big data helps you do this with the components present in it. It automatically generates MapReduce code for you, you just need to drag and drop the components and configure few parameters. It also gives you the option to connect with several Big Data distributions like Cloudera, HortonWorks, MapR, Amazon EMR and even Apache. The list of categories with components to run a job on Big Data environment included under Big Data, is shown below − The list of Big Data connectors and components in Talend Open Studio is shown below − tHDFSConnection − Used for connecting to HDFS (Hadoop Distributed File System). tHDFSConnection − Used for connecting to HDFS (Hadoop Distributed File System). tHDFSInput − Reads the data from given hdfs path, puts it into talend schema and then passes it to the next component in the job. tHDFSInput − Reads the data from given hdfs path, puts it into talend schema and then passes it to the next component in the job. tHDFSList − Retrieves all the files and folders in the given hdfs path. tHDFSList − Retrieves all the files and folders in the given hdfs path. tHDFSPut − Copies file/folder from local file system (user-defined) to hdfs at the given path. tHDFSPut − Copies file/folder from local file system (user-defined) to hdfs at the given path. tHDFSGet − Copies file/folder from hdfs to local file system (user-defined) at the given path. tHDFSGet − Copies file/folder from hdfs to local file system (user-defined) at the given path. tHDFSDelete − Deletes the file from HDFS tHDFSDelete − Deletes the file from HDFS tHDFSExist − Checks whether a file is present on HDFS or not. tHDFSExist − Checks whether a file is present on HDFS or not. tHDFSOutput − Writes data flows on HDFS. tHDFSOutput − Writes data flows on HDFS. tCassandraConnection − Opens the connection to Cassandra server. tCassandraConnection − Opens the connection to Cassandra server. tCassandraRow − Runs CQL (Cassandra query language) queries on the specified database. tCassandraRow − Runs CQL (Cassandra query language) queries on the specified database. tHBaseConnection − Opens the connection to HBase Database. tHBaseConnection − Opens the connection to HBase Database. tHBaseInput − reads data from HBase database. tHBaseInput − reads data from HBase database. tHiveConnection − Opens the connection to Hive database. tHiveConnection − Opens the connection to Hive database. tHiveCreateTable − Creates a table inside a hive database. tHiveCreateTable − Creates a table inside a hive database. tHiveInput − Reads data from hive database. tHiveInput − Reads data from hive database. tHiveLoad − Writes data to hive table or a specified directory. tHiveLoad − Writes data to hive table or a specified directory. tHiveRow − runs HiveQL queries on the specified database. tHiveRow − runs HiveQL queries on the specified database. tPigLoad − Loads input data to output stream. tPigLoad − Loads input data to output stream. tPigMap − Used for transforming and routing the data in a pig process. tPigMap − Used for transforming and routing the data in a pig process. tPigJoin − Performs join operation of 2 files based on join keys. tPigJoin − Performs join operation of 2 files based on join keys. tPigCoGroup − Groups and aggregates the data coming from multiple inputs. tPigCoGroup − Groups and aggregates the data coming from multiple inputs. tPigSort − Sorts the given data based on one or more defined sort keys. tPigSort − Sorts the given data based on one or more defined sort keys. tPigStoreResult − Stores the result from pig operation at a defined storage space. tPigStoreResult − Stores the result from pig operation at a defined storage space. tPigFilterRow − Filters the specified columns in order to split the data based on the given condition. tPigFilterRow − Filters the specified columns in order to split the data based on the given condition. tPigDistinct − Removes the duplicate tuples from the relation. tPigDistinct − Removes the duplicate tuples from the relation. tSqoopImport − Transfers data from relational database like MySQL, Oracle DB to HDFS. tSqoopImport − Transfers data from relational database like MySQL, Oracle DB to HDFS. tSqoopExport − Transfers data from HDFS to relational database like MySQL, Oracle DB tSqoopExport − Transfers data from HDFS to relational database like MySQL, Oracle DB In this chapter, let us learn in detail about how Talend works with Hadoop distributed file system. Before we proceed into Talend with HDFS, we should learn about settings and pre-requisites that should be met for this purpose. Here we are running Cloudera quickstart 5.10 VM on virtual box. A Host-Only Network must be used in this VM. Host-Only Network IP: 192.168.56.101 You must have the same host running on cloudera manager also. Now on your windows system, go to c:\Windows\System32\Drivers\etc\hosts and edit this file using Notepad as shown below. Similarly, on your cloudera quickstart VM, edit your /etc/hosts file as shown below. sudo gedit /etc/hosts In the repository panel, go to Metadata. Right click Hadoop Cluster and create a new cluster. Give the name, purpose and description for this Hadoop cluster connection. Click Next. Select the distribution as cloudera and choose the version which you are using. Select the retrieve configuration option and click Next. Enter the manager credentials (URI with port, username, password) as shown below and click Connect. If the details are correct, you will get Cloudera QuickStart under discovered clusters. Click Fetch. This will fetch all the connections and configurations for HDFS, YARN, HBASE, HIVE. Select All and click Finish. Note that all the connection parameters will be auto-filled. Mention cloudera in the username and click Finish. With this, you have successfully connected to a Hadoop Cluster. In this job, we will list all the directories and files which are present on HDFS. Firstly, we will create a job and then add HDFS components to it. Right click on the Job Design and create a new job – hadoopjob. Now add 2 components from the palette – tHDFSConnection and tHDFSList. Right click tHDFSConnection and connect these 2 components using ‘OnSubJobOk’ trigger. Now, configure both the talend hdfs components. In tHDFSConnection, choose Repository as the Property Type and select the Hadoop cloudera cluster which you created earlier. It will auto-fill all the necessary details required for this component. In tHDFSList, select “Use an existing connection” and in the component list choose the tHDFSConnection which you configured. Give the home path of HDFS in HDFS Directory option and click the browse button on the right. If you have established the connection properly with the above-mentioned configurations, you will see a window as shown below. It will list all the directories and files present on HDFS home. You can verify this by checking your HDFS on cloudera. In this section, let us understand how to read a file from HDFS in Talend. You can create a new job for this purpose, however here we are using the existing one. Drag and Drop 3 components – tHDFSConnection, tHDFSInput and tLogRow from the palette to designer window. Right click tHDFSConnection and connect tHDFSInput component using ‘OnSubJobOk’ trigger. Right click tHDFSInput and drag a main link to tLogRow. Note that tHDFSConnection will have the similar configuration as earlier. In tHDFSInput, select “Use an existing connection” and from the component list, choose tHDFSConnection. In the File Name, give the HDFS path of the file you want to read. Here we are reading a simple text file, so our File Type is Text File. Similarly, depending on your input, fill the row separator, field separator and header details as mentioned below. Finally, click the Edit schema button. Since our file is just having plain text, we are adding just one column of type String. Now, click Ok. Note − When your input is having multiple columns of different types, you need to mention the schema here accordingly. In tLogRow component, click Sync columns in edit schema. Select the mode in which you want your output to be printed. Finally, click Run to execute the job. Once you were successful in reading a HDFS file, you can see the following output. Let’s see how to write a file from HDFS in Talend. Drag and Drop 3 components – tHDFSConnection, tFileInputDelimited and tHDFSOutput from the palette to designer window. Right click on tHDFSConnection and connect tFileInputDelimited component using ‘OnSubJobOk’ trigger. Right click on tFileInputDelimited and drag a main link to tHDFSOutput. Note that tHDFSConnection will have the similar configuration as earlier. Now, in tFileInputDelimited, give the path of input file in File name/Stream option. Here we are using a csv file as an input, hence the field separator is “,”. Select the header, footer, limit according to your input file. Note that here our header is 1 because the 1 row contains the column names and limit is 3 because we are writing only first 3 rows to HDFS. Now, click edit schema. Now, as per our input file, define the schema. Our input file has 3 columns as mentioned below. In tHDFSOutput component, click sync columns. Then, select tHDFSConnection in Use an existing connection. Also, in File name, give a HDFS path where you want to write your file. Note that file type will be text file, Action will be “create”, Row separator will be “\n” and field separator is “;” Finally, click Run to execute your job. Once the job has executed successfully, check if your file is there on HDFS. Run the following hdfs command with the output path you had mentioned in your job. hdfs dfs -cat /input/talendwrite You will see the following output if you are successful in writing on HDFS. In the previous chapter, we have seen how to Talend works with Big Data. In this chapter, let us understand how to use map Reduce with Talend. Let us learn how to run a MapReduce job on Talend. Here we will run a MapReduce word count example. For this purpose, right click Job Design and create a new job – MapreduceJob. Mention the details of the job and click Finish. To add components to a MapReduce job, drag and drop five components of Talend – tHDFSInput, tNormalize, tAggregateRow, tMap, tOutput from the pallet to designer window. Right click on tHDFSInput and create main link to tNormalize. Right click tNormalize and create main link to tAggregateRow. Then, right click on tAggregateRow and create main link to tMap. Now, right click on tMap and create main link to tHDFSOutput. In tHDFSInput, select the distribution cloudera and its version. Note that Namenode URI should be “hdfs://quickstart.cloudera:8020” and username should be “cloudera”. In the file name option, give the path of your input file to the MapReduce job. Ensure that this input file is present on HDFS. Now, select file type, row separator, files separator and header according to your input file. Click edit schema and add the field “line” as string type. In tNomalize, the column to normalize will be line and Item separator will be whitespace -> “ “. Now, click edit schema. tNormalize will have line column and tAggregateRow will have 2 columns word and wordcount as shown below. In tAggregateRow, put word as output column in Group by option. In operations, put wordcount as output column, function as count and Input column position as line. Now double click tMap component to enter the map editor and map the input with required output. In this example, word is mapped with word and wordcount is mapped with wordcount. In the expression column, click on [...] to enter the expression builder. Now, select StringHandling from category list and UPCASE function. Edit the expression to “StringHandling.UPCASE(row3.word)” and click Ok. Keep row3.wordcount in expression column corresponding to wordcount as shown below. In tHDFSOutput, connect to the Hadoop cluster we created from property type as repository. Observe that fields will get auto-populated. In File name, give the output path where you want to store the output. Keep the Action, row separator and field separator as shown below. Once your configuration is successfully completed, click Run and execute your MapReduce job. Go to your HDFS path and check the output. Note that all the words will be in uppercase with their wordcount. In this chapter, let us learn how to work with a Pig job in Talend. In this section, let us learn how to run a Pig job on Talend. Here, we will process NYSE data to find out average stock volume of IBM. For this, right click Job Design and create a new job – pigjob. Mention the details of the job and click Finish. To add components to Pig job, drag and drop four Talend components: tPigLoad, tPigFilterRow, tPigAggregate, tPigStoreResult, from the pallet to designer window. Then, right click tPigLoad and create Pig Combine line to tPigFilterRow. Next, right click tPigFilterRow and create Pig Combine line to tPigAggregate. Right click tPigAggregate and create Pig combine line to tPigStoreResult. In tPigLoad, mention the distribution as cloudera and the version of cloudera. Note that Namenode URI should be “hdfs://quickstart.cloudera:8020” and Resource Manager should be “quickstart.cloudera:8020”. Also, the username should be “cloudera”. In the Input file URI, give the path of your NYSE input file to the pig job. Note that this input file should be present on HDFS. Click edit schema, add the columns and its type as shown below. In tPigFilterRow, select the “Use advanced filter” option and put “stock_symbol = = ‘IBM’” in the Filter option. In tAggregateRow, click edit schema and add avg_stock_volume column in output as shown below. Now, put stock_exchange column in Group by option. Add avg_stock_volume column in Operations field with count Function and stock_exchange as Input Column. In tPigStoreResult, give the output path in Result Folder URI where you want to store the result of Pig job. Select store function as PigStorage and field separator (not mandatory) as “\t”. Now click on Run to execute your Pig job. (Ignore the warnings) Once the job finishes, go and the check your output at the HDFS path you mentioned for storing the pig job result. The average stock volume of IBM is 500. In this chapter, let us understand how to work with Hive job on Talend. As an example, we will load NYSE data to a hive table and run a basic hive query. Right click on Job Design and create a new job – hivejob. Mention the details of the job and click on Finish. To ass components to a Hive job, drag and drop five talend components − tHiveConnection, tHiveCreateTable, tHiveLoad, tHiveInput and tLogRow from the pallet to designer window. Then, right click tHiveConnection and create OnSubjobOk trigger to tHiveCreateTable. Now, right click tHiveCreateTable and create OnSubjobOk trigger to tHiveLoad. Right click tHiveLoad and create iterate trigger on tHiveInput. Finally, right click tHiveInput and create a main line to tLogRow. In tHiveConnection, select distribution as cloudera and its version you are using. Note that connection mode will be standalone and Hive Service will be Hive 2. Also check if the following parameters are set accordingly − Host: “quickstart.cloudera” Port: “10000” Database: “default” Username: “hive” Note that password will be auto-filled, you need not edit it. Also other Hadoop properties will be preset and set by default. In tHiveCreateTable, select Use an existing connection and put tHiveConnection in Component list. Give the Table Name which you want to create in default database. Keep the other parameters as shown below. In tHiveLoad, select “Use an existing connection” and put tHiveConnection in component list. Select LOAD in Load action. In File Path, give the HDFS path of your NYSE input file. Mention the table in Table Name, in which you want to load the input. Keep the other parameters as shown below. In tHiveInput, select Use an existing connection and put tHiveConnection in Component list. Click edit schema, add the columns and its type as shown in schema snapshot below. Now give the table name which you created in tHiveCreateTable. Put your query in query option which you want to run on the Hive table. Here we are printing all the columns of first 10 rows in the test hive table. In tLogRow, click sync columns and select Table mode for showing the output. Click on Run to begin the execution. If all the connection and the parameters were set correctly, you will see the output of your query as shown below. 61 Lectures 4 hours Jim Macaulay Print Add Notes Bookmark this page
[ { "code": null, "e": 2290, "s": 1976, "text": "Talend is a software integration platform which provides solutions for Data integration, Data quality, Data management, Data Preparation and Big Data. The demand for ETL professionals with knowledge on Talend is high. Also, it is the only ETL tool with ...
How to remove an item from a C++ STL vector with a certain value?
Erase function is used to remove an item from a C++ STL vector with a certain value. Begin Declare vector v and iterator it to the vector. Initialize the vector. Erase() function is used to remove item from end. Print the remaining elements. End. #include <iostream> #include <vector> using namespace std; int main() { vector<int> v{ 6,7,8,9,10}; vector<int>::iterator it; it = v.end(); it--; v.erase(it); for (auto it = v.begin(); it != v.end(); ++it) cout << ' ' << *it; return 0; } The current content of the vector is : 6 7 8 9 10 Please enter the element to be deleted -> 7 The current content of the vector is : 6 8 9 10
[ { "code": null, "e": 1147, "s": 1062, "text": "Erase function is used to remove an item from a C++ STL vector with a certain value." }, { "code": null, "e": 1309, "s": 1147, "text": "Begin\nDeclare vector v and iterator it to the vector.\nInitialize the vector.\nErase() function ...
How to execute zombie and orphan process in a single program? - GeeksforGeeks
04 Sep, 2018 Prerequisite: Zombie and Orphan Processes in C Zombie Process:A zombie process is a process that has completed execution but still has an entry in the process table. This entry is still needed to allow the parent process to read its child’s exit status.A process that terminates cannot leave the system until its parent accepts its return code. If its parent process is already dead, it’ll already have been adopted by the “init” process, which always accepts its children’s return codes. However, if a process’s parent is alive but never executes a wait ( ), the process’s return code will never be accepted and the process will remain a zombie. Orphan Process:An orphan process is a process that is still executing, but whose parent has died. They do not become zombie processes; instead, they are adopted by init (process ID 1), which waits on its children.When a parent dies before its child, the child is automatically adopted by the original “init” process whose PID is 1. Approach:In the following code, we have made a scenario that there is a parent and it has a child and that child also has a child, firstly if our process gets into child process, we put our system into sleep for 5 sec so that we could finish up the parent process so that its child become orphan, then we have made a child’s child as zombie process, the child’s child finishes its execution while the parent(i.e child) sleeps for 1 seconds, hence the child’s child doesn’t call terminate, and it’s entry still exists in the process table. Below is the implementation of above approach: // C program to execute zombie and// orphan process in a single program#include <stdio.h>int main(){ int x; x = fork(); if (x > 0) printf("IN PARENT PROCESS\nMY PROCESS ID : %d\n", getpid()); else if (x == 0) { sleep(5); x = fork(); if (x > 0) { printf("IN CHILD PROCESS\nMY PROCESS ID :%d\n PARENT PROCESS ID : %d\n", getpid(), getppid()); while(1) sleep(1); printf("IN CHILD PROCESS\nMY PARENT PROCESS ID : %d\n", getppid()); } else if (x == 0) printf("IN CHILD'S CHILD PROCESS\n MY PARENT ID : %d\n", getppid()); } return 0;} Output:Note: Above code may not work with the online compiler as fork() is disabled. CPP-Library Operating Systems-Process Management system-programming C Language C++ Operating Systems Questions CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C Multithreading in C Exception Handling in C++ 'this' pointer in C++ Arrow operator -> in C/C++ with Examples Vector in C++ STL Initialize a vector in C++ (6 different ways) Inheritance in C++ Map in C++ Standard Template Library (STL) C++ Classes and Objects
[ { "code": null, "e": 24232, "s": 24204, "text": "\n04 Sep, 2018" }, { "code": null, "e": 24279, "s": 24232, "text": "Prerequisite: Zombie and Orphan Processes in C" }, { "code": null, "e": 24879, "s": 24279, "text": "Zombie Process:A zombie process is a proces...
Difference between RUN vs CMD vs ENTRYPOINT Docker Commands - GeeksforGeeks
23 Oct, 2020 Commands such as CMD, RUN and ENTRYPOINT are interchangeably used when you are writing a dockerfile to create the Docker Image. However, if you have just started using Docker or you don’t have enough hands-on experience working with these commands, then these commands might cause a lot of confusion for you. In this article, we are going to discuss all three commands in-depth with practical examples. But before we dive into the explanation, we need to first understand the different execution forms. We can use two different forms for executing commands in Docker. Normal shell processing takes place if we opt for shell form execution of commands. Behind the scenes, the bash calls the /bin/sh -c. The general form of shell commands is as shown below: <Instruction> <Command> To get a clearer picture, look at the commands below. RUN apt-get -y install firefox CMD echo "GeeksforGeeks" ENTRYPOINT echo "GeeksforGeeks" Both the above commands outputs “GeeksforGeeks”. The shell form of execution commands is generally used for RUN commands. Executable form of commands is generally used for CMD and ENTRYPOINT commands. The general form of executable commands is as shown below: <Instruction> ["executable", "parameter no. 1", "parameter no. 2", ...] Using the executable form of commands executes the commands directly and shell processing does not take place. Check out the commands below.: ENTRYPOINT ["/bin/echo", "geeksforgeeks"] CMD ["/bin/echo", "geeksforgeeks"] Let’s now try to understand the RUN, CMD, and ENTRYPOINT commands in-depth. When you use a RUN command in your dockerfile, it always creates a new intermediate image layer on top of the previous ones. That’s why it is always recommended chaining all the RUN commands together. RUN command in executable form is: RUN ["apt-get", "install", "firefox"] RUN command in shell form is : RUN apt-get -y install firefox A CMD command is used to set a default command that gets executed once you run the Docker Container. In case you provide a command with the Docker run command, the CMD arguments get ignored from the dockerfile. In the case of multiple CMD commands, only the last one gets executed. CMD ["python3", "app.py"] If you are using an ENTRYPOINT in your dockerfile, you can add some additional parameters using the CMD command’s following form. CMD ["parameter 1", "parameter 2"] Note that the CMD commands get ignored if you provide arguments in your Docker run command. sudo docker run -it ubuntu bash If you use the above command and at the same time, you have used a CMD command in your dockerfile, it gets ignored and simply opens the bash. For example, if the dockerfile contains : Input file If we use additional arguments along with the docker run command such as “bash”, it will simple open the bash and not echo anything. Output An ENTRYPOINT command, unlike CMD, does not ignore additional parameters that you specify in your Docker run command. Consider the example below: ENTRYPOINT ["echo", "Geeksforgeeks "] CMD ["Docker Tutorials"] For example, if the dockerfile is Input The output of the above commands on running the Docker Container without any additional arguments would be – Geeksforgeeks Docker Tutorials Output In case you specify additional parameters, the CMD arguments get ignored. To conclude, in this article, we discussed the shell and executable form for executing dockerfile instructions. We then discussed the differences between RUN, CMD and ENTRYPOINT commands each with an example. Docker Container linux Linux-Unix TechTips Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. nohup Command in Linux with Examples scp command in Linux with Examples Thread functions in C/C++ mv command in Linux with examples chown command in Linux with Examples How to Find the Wi-Fi Password Using CMD in Windows? How to Run a Python Script using Docker? Docker - COPY Instruction Running Python script on GPU. Setting up the environment in Java
[ { "code": null, "e": 24406, "s": 24378, "text": "\n23 Oct, 2020" }, { "code": null, "e": 24809, "s": 24406, "text": "Commands such as CMD, RUN and ENTRYPOINT are interchangeably used when you are writing a dockerfile to create the Docker Image. However, if you have just started u...
A better way to visualize Decision Trees with the dtreeviz library | by Parul Pandey | Towards Data Science
It is rightly said that a picture is worth a thousand words. This axiom is equally applicable for machine learning models. If one can visualize and interpret the result, it instills more confidence in the model's predictions. Visualizing how a machine learning model works also makes it possible to explain the results to people with less or no machine learning skills. Scikit-learn library inherently comes with the plotting capability for decision trees. However, there are some inconsistencies with the default option. This article will look at an alternative called dtreeviz that renders better-looking and intuitive visualizations while offering greater interpretability options. The dtreeviz is a python library for decision tree visualization and model interpretation. According to the information available on its Github repo, the library currently supports scikit-learn, XGBoost, Spark MLlib, and LightGBM trees. Here is a visual comparison of the visualization generated from default scikit-learn and that from dtreeviz on the famous wine quality dataset. The dataset includes 178 instances and 13 numeric predictive attributes. Each data point can belong to one of the three classes named class_0, class_1, and class_2. As is evident from the pictures above, the figure on the right delivers far more information than its counterpart on the left. There are some apparent issues with the default scikit learn visualization, for instance: It is not immediately clear as to what the different colors represent. There are no legends for the target class. The visualization returns the count of the samples, and it isn't easy to visualize the distributions. The size of every decision node is the same regardless of the number of samples. The dtreeviz library plugs in these loopholes to offer a clear and more comprehensible picture. Here is what the authors have to say: The visualizations are inspired by an educational animation by R2D3; A visual introduction to machine learning. With dtreeviz, you can visualize how the feature space is split up at decision nodes, how the training samples get distributed in leaf nodes, how the tree makes predictions for a specific observation and more. These operations are critical to for understanding how classification or regression decision trees work. We’ll see how the dtreeviz scores over the other visualization libraries through some common examples in the following sections. For the installation instructions, please refer to the official Github page. It can be installed with pip install dtreeviz butrequires graphviz to be pre-installed. Before visualizing a decision tree, it is also essential to understand how it works. A Decision Tree is a supervised learning predictive model that uses a set of binary rules to calculate a target value. It can be used both for regression as well as classification tasks. Decision trees have three main parts: Root Node: The node that performs the first split. Terminal Nodes/Leaf node: Nodes that predict the outcome. Branches: arrows connecting nodes, showing the flow from question to answer. The algorithm of the decision tree models works by repeatedly partitioning the data into multiple sub-spaces so that the outcomes in each final sub-space are as homogeneous as possible. This approach is technically called recursive partitioning. The algorithm tries to split the data into subsets so that each subgroup is as pure or homogeneous as possible. The above excerpt has been taken from an article I wrote on understanding decision trees. This article goes deeper into explaining how the algorithm typically makes a decision. Now let’s get back to the dtreeviz library and plot a few of them using the wine data mentioned above. We’ll be using the famous red wine dataset from the Wine Quality Data Set. The dataset consists of few physicochemical tests related to the red variant of the Portuguese “Vinho Verde” wine. The goal is to model wine quality based on these tests. Since this dataset can be viewed both as a classification and regression task, it is apt for our use case. We will not have to use separate datasets for demonstrating the classification and regression examples. Here is the nbviewer link to the notebook incase you want to follow along. Let’s look at the first few rows of the dataset: The quality parameter refers to the wine quality and is a score between 0 and 10 Creating the features and target variables for ease. features = wine.drop('quality',axis=1)target = wine['quality'] For the regression example, we’ll be predicting the quality of the wine. # Regression tree on Wine datafig = plt.figure(figsize=(25,20))regr= tree.DecisionTreeRegressor(max_depth=3) regr.fit(features, target)viz = dtreeviz(regr, features, target, target_name='wine quality', feature_names=features.columns, title="Wine data set regression", fontname="Arial", colors = {"title":"purple"}, scale=1.5)viz The horizontal dashed lines indicate the target mean for the left and right buckets in decision nodes; A vertical dashed line indicates the split point in feature space. The black wedge highlights the split point and identifies the exact split value. Leaf nodes indicate the target prediction (mean) with a dashed line. Classification decision tree For the classification example, we’ll predict the class of wine from the given six classes. Again the target here is the quality variable. # Classification tree on Wine datafig = plt.figure(figsize=(25,20))clf = tree.DecisionTreeClassifier(max_depth=3)clf.fit(features, target)# pick random X observation for demo#X = wine.data[np.random.randint(0, len(wine.data)),:]viz = dtreeviz(clf, features, target, target_name='wine quality', feature_names=features.columns, title="Wine data set classification", class_names=['5', '6', '7', '4', '8', '3'], histtype='barstacked', # default scale=1.2)viz Unlike regressors, the target is a category for the classifiers. Therefore histograms are used to illustrate feature-target space. The stacked histograms might be challenging to read when the number of classes increases. In such cases, the histogram type parameter can be changed to barfrom barstacked, which is the default. The dtreeviz library also offers a bunch of customizations. I’ll showcase a few of them here: The scale parameter can be used to scale the overall image. The orientation parameter can be set to LR to display the trees from left to right rather than top-down fig = plt.figure(figsize=(25,20))clf = tree.DecisionTreeClassifier(max_depth=2)clf.fit(features, target)# pick random X observation for demoviz = dtreeviz(clf, features, target, target_name='wine quality', feature_names=features.columns, title="Wine data set classification", class_names=['5', '6', '7', '4', '8', '3'], orientation='LR', scale=1.2)viz The library also helps to isolate and understand which decision path is followed by a specific test observation. This is very useful in explaining the prediction or the results to others. For instance, let’s pick out a random sample from the dataset and traverse its decision path. fig = plt.figure(figsize=(25,20))clf = tree.DecisionTreeClassifier(max_depth=3)clf.fit(features, target)# pick random X observation for demoX = features.iloc[np.random.randint(0, len(features)),:].valuesviz = dtreeviz(clf, features, target, target_name='wine quality', feature_names=features.columns, title="Wine data set classification", class_names=['5', '6', '7', '4', '8', '3'], scale=1.3, X=X)viz The output graph can be saved in an SVG format as follows: viz.save_svg() The dtreeviz library scores above others when it comes to plotting decision trees. The additional capability of making results interpretable is an excellent add-on; You can isolate a single data point and understand the prediction at a micro-level. This helps in better understanding a model’s predictions, and it also makes it easy to communicate the findings to others. What I have touched here is just the tip of the iceberg. The Github repository and the accompanying article by the author go into more detail, and I’ll highly recommend going through them. The links are in the reference section below. The official Github repository of dtreeviz. How to visualize decision trees — A great read on decision tree visualization by creators of dtreeviz. Understanding Decision Trees 👉 Interested in reading other articles authored by me. This repo contains all the articles written by me category-wise.
[ { "code": null, "e": 732, "s": 47, "text": "It is rightly said that a picture is worth a thousand words. This axiom is equally applicable for machine learning models. If one can visualize and interpret the result, it instills more confidence in the model's predictions. Visualizing how a machine lear...
Swift - Subscripts
Accessing the element members of a collection, sequence and a list in Classes, Structures and Enumerations are carried out with the help of subscripts. These subscripts are used to store and retrieve the values with the help of index. Array elements are accessed with the help of someArray[index] and its subsequent member elements in a Dictionary instance can be accessed as someDicitonary[key]. For a single type, subscripts can range from single to multiple declarations. We can use the appropriate subscript to overload the type of index value passed to the subscript. Subscripts also ranges from single dimension to multiple dimension according to the users requirements for their input data type declarations. Let's have a recap to the computed properties. Subscripts too follow the same syntax as that of computed properties. For querying type instances, subscripts are written inside a square bracket followed with the instance name. Subscript syntax follows the same syntax structure as that of 'instance method' and 'computed property' syntax. 'subscript' keyword is used for defining subscripts and the user can specify single or multiple parameters with their return types. Subscripts can have read-write or read-only properties and the instances are stored and retrieved with the help of 'getter' and 'setter' properties as that of computed properties. subscript(index: Int) −> Int { get { // used for subscript value declarations } set(newValue) { // definitions are written here } } struct subexample { let decrementer: Int subscript(index: Int) -> Int { return decrementer / index } } let division = subexample(decrementer: 100) print("The number is divisible by \(division[9]) times") print("The number is divisible by \(division[2]) times") print("The number is divisible by \(division[3]) times") print("The number is divisible by \(division[5]) times") print("The number is divisible by \(division[7]) times") When we run the above program using playground, we get the following result − The number is divisible by 11 times The number is divisible by 50 times The number is divisible by 33 times The number is divisible by 20 times The number is divisible by 14 times class daysofaweek { private var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "saturday"] subscript(index: Int) -> String { get { return days[index] } set(newValue) { self.days[index] = newValue } } } var p = daysofaweek() print(p[0]) print(p[1]) print(p[2]) print(p[3]) When we run the above program using playground, we get the following result − Sunday Monday Tuesday Wednesday Subscripts takes single to multiple input parameters and these input parameters also belong to any datatype. They can also use variable and variadic parameters. Subscripts cannot provide default parameter values or use any in-out parameters. Defining multiple subscripts are termed as 'subscript overloading' where a class or structure can provide multiple subscript definitions as required. These multiple subscripts are inferred based on the types of values that are declared within the subscript braces. struct Matrix { let rows: Int, columns: Int var print: [Double] init(rows: Int, columns: Int) { self.rows = rows self.columns = columns print = Array(count: rows * columns, repeatedValue: 0.0) } subscript(row: Int, column: Int) -> Double { get { return print[(row * columns) + column] } set { print[(row * columns) + column] = newValue } } } var mat = Matrix(rows: 3, columns: 3) mat[0,0] = 1.0 mat[0,1] = 2.0 mat[1,0] = 3.0 mat[1,1] = 5.0 print("\(mat[0,0])") When we run the above program using playground, we get the following result − 1.0 Swift 4 subscript supports single parameter to multiple parameter declarations for appropriate data types. The program declares 'Matrix' structure as a 2 * 2 dimensional array matrix to store 'Double' data types. The Matrix parameter is inputted with Integer data types for declaring rows and columns. New instance for the Matrix is created by passing row and column count to the initialize as shown below. var mat = Matrix(rows: 3, columns: 3) Matrix values can be defined by passing row and column values into the subscript, separated by a comma as shown below. mat[0,0] = 1.0 mat[0,1] = 2.0 mat[1,0] = 3.0 mat[1,1] = 5.0 38 Lectures 1 hours Ashish Sharma 13 Lectures 2 hours Three Millennials 7 Lectures 1 hours Three Millennials 22 Lectures 1 hours Frahaan Hussain 12 Lectures 39 mins Devasena Rajendran 40 Lectures 2.5 hours Grant Klimaytys Print Add Notes Bookmark this page
[ { "code": null, "e": 2650, "s": 2253, "text": "Accessing the element members of a collection, sequence and a list in Classes, Structures and Enumerations are carried out with the help of subscripts. These subscripts are used to store and retrieve the values with the help of index. Array elements are...
MongoDB - Atomic Operations
The recommended approach to maintain atomicity would be to keep all the related information, which is frequently updated together in a single document using embedded documents. This would make sure that all the updates for a single document are atomic. Assume we have created a collection with name productDetails and inserted a documents in it as shown below − >db.createCollection("products") { "ok" : 1 } > db.productDetails.insert( { "_id":1, "product_name": "Samsung S3", "category": "mobiles", "product_total": 5, "product_available": 3, "product_bought_by": [ { "customer": "john", "date": "7-Jan-2014" }, { "customer": "mark", "date": "8-Jan-2014" } ] } ) WriteResult({ "nInserted" : 1 }) > In this document, we have embedded the information of the customer who buys the product in the product_bought_by field. Now, whenever a new customer buys the product, we will first check if the product is still available using product_available field. If available, we will reduce the value of product_available field as well as insert the new customer's embedded document in the product_bought_by field. We will use findAndModify command for this functionality because it searches and updates the document in the same go. >db.products.findAndModify({ query:{_id:2,product_available:{$gt:0}}, update:{ $inc:{product_available:-1}, $push:{product_bought_by:{customer:"rob",date:"9-Jan-2014"}} } }) Our approach of embedded document and using findAndModify query makes sure that the product purchase information is updated only if it the product is available. And the whole of this transaction being in the same query, is atomic. In contrast to this, consider the scenario where we may have kept the product availability and the information on who has bought the product, separately. In this case, we will first check if the product is available using the first query. Then in the second query we will update the purchase information. However, it is possible that between the executions of these two queries, some other user has purchased the product and it is no more available. Without knowing this, our second query will update the purchase information based on the result of our first query. This will make the database inconsistent because we have sold a product which is not available. 44 Lectures 3 hours Arnab Chakraborty 54 Lectures 5.5 hours Eduonix Learning Solutions 44 Lectures 4.5 hours Kaushik Roy Chowdhury 40 Lectures 2.5 hours University Code 26 Lectures 8 hours Bassir Jafarzadeh 70 Lectures 2.5 hours Skillbakerystudios Print Add Notes Bookmark this page
[ { "code": null, "e": 2806, "s": 2553, "text": "The recommended approach to maintain atomicity would be to keep all the related information, which is frequently updated together in a single document using embedded documents. This would make sure that all the updates for a single document are atomic."...
callable() in Python
The callable() function in python is part of its standard library which returns true if the object is callable and returns false if it is not.The object itself should have a call method to be callable. For example if we just declare a variable with value, it is not callable, but if we declare a function then it becomes callable. Below we declare a function which is callable. That can be verified by actually making a call to the function, as well as checking through the callable function. def func_callable(): x = 3 y = 5 z = x^y return z # an object is created of Geek() res = func_callable print(callable(res)) print(res) # Call and use the function final_res=func_callable() print(final_res) Running the above code gives us the following result − True 6 Here we see the same program as above but without using any functions. We just use some variables for calculations. When the results are nor printed we see that the variable values are not callable. x = 3 y = 5 z = x^y print(callable(z)) print(z) Running the above code gives us the following result − False 6
[ { "code": null, "e": 1393, "s": 1062, "text": "The callable() function in python is part of its standard library which returns true if the object is callable and returns false if it is not.The object itself should have a call method to be callable. For example if we just declare a variable with valu...
How can I get the current Android SDK version programmatically using Kotlin?
This example demonstrates how to Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="4dp" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="50dp" android:text="Tutorials Point" android:textAlignment="center" android:textColor="@android:color/holo_green_dark" android:textSize="32sp" android:textStyle="bold" /> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:textColor="@android:color/black" android:textSize="24sp" android:textStyle="bold" /> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.kt import android.os.Build import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.TextView class MainActivity : AppCompatActivity() { private lateinit var textView: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" textView = findViewById(R.id.textView) val versionAPI = Build.VERSION.SDK_INT val versionRelease = Build.VERSION.RELEASE textView.text = "API Version : $versionAPI\nVersion Release : $versionRelease" } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.q11"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
[ { "code": null, "e": 1095, "s": 1062, "text": "This example demonstrates how to" }, { "code": null, "e": 1224, "s": 1095, "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"...
C/C++ do while loop with Examples - GeeksforGeeks
22 Jun, 2021 Loops in C/C++ come into use when we need to repeatedly execute a block of statements. Like while the do-while loop execution is also terminated on the basis of a test condition. The main difference between a do-while loop and while loop is in the do-while loop the condition is tested at the end of the loop body, i.e do-while loop is exit controlled whereas the other two loops are entry controlled loops.Note: In do-while loop the loop body will execute at least once irrespective of test condition. Syntax: do { // loop body update_expression; } while (test_expression); Note: Notice the semi – colon(“;”) in the end of loop.The various parts of the do-while loop are: Test Expression: In this expression we have to test the condition. If the condition evaluates to true then we will execute the body of the loop and go to update expression. Otherwise, we will exit from the while loop. Example: Test Expression: In this expression we have to test the condition. If the condition evaluates to true then we will execute the body of the loop and go to update expression. Otherwise, we will exit from the while loop. Example: i <= 10 Update Expression: After executing the loop body, this expression increments/decrements the loop variable by some value. Example: Update Expression: After executing the loop body, this expression increments/decrements the loop variable by some value. Example: i++; How does a do-While loop executes? Control falls into the do-while loop.The statements inside the body of the loop get executed.Updation takes place.The flow jumps to ConditionCondition is tested. If Condition yields true, goto Step 6.If Condition yields false, the flow goes outside the loopFlow goes back to Step 2. Control falls into the do-while loop. The statements inside the body of the loop get executed. Updation takes place. The flow jumps to Condition Condition is tested. If Condition yields true, goto Step 6.If Condition yields false, the flow goes outside the loop If Condition yields true, goto Step 6.If Condition yields false, the flow goes outside the loop If Condition yields true, goto Step 6. If Condition yields false, the flow goes outside the loop Flow goes back to Step 2. Flow Diagram do-while loop: Example 1: This program will try to print “Hello World” depending on few conditions. C C++ // C program to illustrate do-while loop #include <stdio.h> int main(){ // Initialization expression int i = 2; do { // loop body printf("Hello World\n"); // Update expression i++; } // Test expression while (i < 1); return 0;} // C++ program to illustrate do-while loop #include <iostream>using namespace std; int main(){ // Initialization expression int i = 2; do { // Loop body cout << "Hello World\n"; // Update expression i++; } // Test expression while (i < 1); return 0;} Hello World Dry-Running Example 1: 1. Program starts. 2. i is initialised to 2. 3. Execution enters the loop 3.a) "Hello World" gets printed 1st time. 3.b) Updation is done. Now i = 2. 4. Condition is checked. 2 < 2 yields false. 5. The flow goes outside the loop. Example 2: C C++ // C program to illustrate do-while loop #include <stdio.h> int main(){ // Initialization expression int i = 1; do { // Loop body printf("%d\n", i); // Update expression i++; } // Test expression while (i <= 5); return 0;} // C++ program to illustrate do-while loop #include <iostream>using namespace std; int main(){ // Initialization expression int i = 1; do { // Loop body cout << i << endl; // Update expression i++; } // Test expression while (i <= 5); return 0;} 1 2 3 4 5 Related Articles: Loops in C and C++C/C++ while loop with ExamplesC/C++ For loop with ExamplesDifference between while and do-while loop in C, C++, JavaDifference between for and while loop in C, C++, Java Loops in C and C++ C/C++ while loop with Examples C/C++ For loop with Examples Difference between while and do-while loop in C, C++, Java Difference between for and while loop in C, C++, Java anikaseth98 C Language C++ School Programming CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Multidimensional Arrays in C / C++ rand() and srand() in C/C++ Left Shift and Right Shift Operators in C/C++ fork() in C Core Dump (Segmentation fault) in C/C++ Vector in C++ STL Initialize a vector in C++ (6 different ways) Map in C++ Standard Template Library (STL) Inheritance in C++ C++ Classes and Objects
[ { "code": null, "e": 23907, "s": 23879, "text": "\n22 Jun, 2021" }, { "code": null, "e": 24412, "s": 23907, "text": "Loops in C/C++ come into use when we need to repeatedly execute a block of statements. Like while the do-while loop execution is also terminated on the basis of a ...
Deserialize JSON to Object in Python - GeeksforGeeks
07 Jul, 2021 Let us see how to deserialize a JSON document into a Python object. Deserialization is the process of decoding the data that is in JSON format into native data type. In Python, deserialization decodes JSON data into a dictionary(data type in python).We will be using these methods of the json module to perform this task : loads() : to deserialize a JSON document to a Python object. load() : to deserialize a JSON formatted stream ( which supports reading from a file) to a Python object. Example 1 : Using the loads() function. Python3 # importing the moduleimport json # creating the JSON data as a stringdata = '{"Name" : "Romy", "Gender" : "Female"}' print("Datatype before deserialization : " + str(type(data))) # deserializing the datadata = json.loads(data) print("Datatype after deserialization : " + str(type(data))) Output : Datatype before deserialization : Datatype after deserialization : Example 2 : Using the load() function. We have to deserialize a file named file.json. Python3 # importing the moduleimport json # opening the JSON filedata = open('file.json',) print("Datatype before deserialization : " + str(type(data))) # deserializing the datadata = json.load(data) print("Datatype after deserialization : " + str(type(data))) Output : Datatype before deserialization : Datatype after deserialization : gabaa406 Python-json Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python program to convert a list to string
[ { "code": null, "e": 41137, "s": 41109, "text": "\n07 Jul, 2021" }, { "code": null, "e": 41462, "s": 41137, "text": "Let us see how to deserialize a JSON document into a Python object. Deserialization is the process of decoding the data that is in JSON format into native data typ...