title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
C++ Program To Print All Permutations Of A Given String
11 Dec, 2021 A permutation also called an “arrangement number” or “order,” is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation. Source: Mathword(http://mathworld.wolfram.com/Permutation.html) Below are the permutations of string ABC. ABC ACB BAC BCA CBA CAB Here is a solution that is used as a basis in backtracking. C++ // C++ program to print all permutations // with duplicates allowed #include <bits/stdc++.h> using namespace std; // Function to print permutations // of string // This function takes three parameters: // 1. String // 2. Starting index of the string // 3. Ending index of the string. void permute(string a, int l, int r) { // Base case if (l == r) cout<<a<<endl; else { // Permutations made for (int i = l; i <= r; i++) { // Swapping done swap(a[l], a[i]); // Recursion called permute(a, l+1, r); //backtrack swap(a[l], a[i]); } } } // Driver Code int main() { string str = "ABC"; int n = str.size(); permute(str, 0, n-1); return 0; } // This is code is contributed by rathbhupendra Output: ABC ACB BAC BCA CBA CAB Algorithm Paradigm: Backtracking Time Complexity: O(n*n!) Note that there are n! permutations and it requires O(n) time to print a permutation. Auxiliary Space: O(r – l) Note: The above solution prints duplicate permutations if there are repeating characters in the input string. Please see the below link for a solution that prints only distinct permutations even if there are duplicates in input.Print all distinct permutations of a given string with duplicates. Permutations of a given string using STL Another approach: C++ // C++ program to implement// the above approach#include <bits/stdc++.h>#include <string>using namespace std; void permute(string s, string answer){ if(s.length() == 0) { cout << answer << " "; return; } for(int i = 0; i < s.length(); i++) { char ch = s[i]; string left_substr = s.substr(0, i); string right_substr = s.substr(i + 1); string rest = left_substr + right_substr; permute(rest , answer+ch); }} // Driver codeint main(){ string s; string answer = ""; cout << "Enter the string : "; cin >> s; cout << "All possible strings are : "; permute(s, answer); return 0;} Output: Enter the string : abc All possible strings are : abc acb bac bca cab cba Time Complexity: O(n*n!) The time complexity is the same as the above approach, i.e. there are n! permutations and it requires O(n) time to print a permutation. Auxiliary Space: O(|s|) Please refer complete article on Write a program to print all permutations of a given string for more details! Accolite Amazon Apple Cisco Citrix MAQ Software OYO Rooms permutation Samsung Snapdeal Walmart Backtracking C++ Programs Combinatorial Greedy Mathematical Recursion Strings Accolite Amazon OYO Rooms Samsung Snapdeal Citrix Walmart MAQ Software Cisco Apple Strings Greedy Mathematical Recursion permutation Combinatorial Backtracking Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Find shortest safe route in a path with landmines Find if there is a path of more than k length from a source Top 20 Backtracking Algorithm Interview Questions Longest Possible Route in a Matrix with Hurdles Sum of subsets of all the subsets of an array | O(N) Header files in C/C++ and its uses How to return multiple values from a function in C or C++? Sorting a Map by value in C++ STL C++ program for hashing with chaining Passing a function as a parameter in C++
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Dec, 2021" }, { "code": null, "e": 236, "s": 28, "text": "A permutation also called an “arrangement number” or “order,” is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string ...
How to test a URL for 404 error in PHP?
20 May, 2019 Checking if a Webpage URL exists or not is relatively easy in PHP. If the required URL does not exist, then it will return 404 error. The checking can be done with and without using cURL library. cURL: The cURL stands for ‘Client for URLs’, originally with URL spelled in uppercase to make it obvious that it deals with URLs. It is pronounced as ‘see URL’. The cURL project has two products libcurl and curl. libcurl: A free and easy-to-use client-side URL transfer library, supporting FTP, TPS, HTTP, HTTPS, GOPHER, TELNET, DICT, FILE, and LDAP. libcurl supports TTPS certificates, HTTP POST, HTTP PUT, FTP uploading, kerberos, HTTP based upload, proxies, cookies, user & password authentication, file transfer resume, HTTP proxy tunneling and many more. libcurl is free, thread-safe, IPv6 compatible, feature rich, well supported and fast. curl: A command line tool for getting or sending files using URL syntax. Since curl uses libcurl, it supports a range of common internal protocols, currently including HTTP, HTTPS, FTP, FTPS, GOPHER, TELNET, DICT, and FILE. Example 1: This example test a URL for 404 error without using cURL approach. <?php // Creating a variable with an URL// to be checked$url = 'https://www.geeksforgeeks.org'; // Getting page header data$array = @get_headers($url); // Storing value at 1st position because// that is only what we need to check$string = $array[0]; // 404 for error, 200 for no errorif(strpos($string, "200")) { echo 'Specified URL Exists';} else { echo 'Specified URL does not exist';} ?> Output: Specified URL exists Example 2: This example test a URL for 404 error using cURL approach. <?php // Initializing new session$ch = curl_init("https://www.geeksforgeeks.org"); // Request method is setcurl_setopt($ch, CURLOPT_NOBODY, true); // Executing cURL sessioncurl_exec($ch); // Getting information about HTTP Code$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); // Testing for 404 Errorif($retcode != 200) { echo "Specified URL does not exist";}else { echo "Specified URL exists";} curl_close($ch); ?> Output: Specified URL exists Picked PHP PHP Programs Web Technologies Web technologies Questions PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to fetch data from localserver database and display on HTML table using PHP ? Difference between HTTP GET and POST Methods Different ways for passing data to view in Laravel PHP | file_exists( ) Function PHP | Ternary Operator How to call PHP function on the click of a Button ? How to fetch data from localserver database and display on HTML table using PHP ? PHP | Ternary Operator How to create admin login page using PHP? How to send an email using PHPMailer ?
[ { "code": null, "e": 28, "s": 0, "text": "\n20 May, 2019" }, { "code": null, "e": 224, "s": 28, "text": "Checking if a Webpage URL exists or not is relatively easy in PHP. If the required URL does not exist, then it will return 404 error. The checking can be done with and without...
Python | os.symlink() method
26 Aug, 2019 OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.symlink() method in Python is used to create symbolic link. This method creates symbolic link pointing to source named destination.To read about symbolic links/soft links, please refer to this article. Syntax: os.symlink(src, dst, target_is_directory = False, *, dir_fd = None) Parameters:src: A path-like object representing the file system path. This is the source file path for which the symbolic link will be created.dst: A path-like object representing the file system path. This is the target file path where symbolic link will be created.target_is_directory (optional): The default value of this parameter is False. If the specified target path is directory then its value should be True.dir_fd (optional): A file descriptor referring to a directory. Return type: This method does not return any value. Code: Use of os.symlink() method # Python program to explain os.symlink() method # importing os module import os # Source file pathsrc = '/home/ihritik/file.txt' # Destination file pathdst = '/home/ihritik/Desktop/file(symlink).txt' # Create a symbolic link# pointing to src named dst# using os.symlink() methodos.symlink(src, dst) print("Symbolic link created successfully") Symbolic link created successfully Reference: https://docs.python.org/3/library/os.html#os.link python-os-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Introduction To PYTHON
[ { "code": null, "e": 53, "s": 25, "text": "\n26 Aug, 2019" }, { "code": null, "e": 272, "s": 53, "text": "OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of usi...
Spring @Service Annotation with Example
18 Feb, 2022 Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. It made the development of Web applications much easier than compared to classic Java frameworks and application programming interfaces (APIs), such as Java database connectivity (JDBC), JavaServer Pages(JSP), and Java Servlet. This framework uses various new techniques such as Aspect-Oriented Programming (AOP), Plain Old Java Object (POJO), and dependency injection (DI), to develop enterprise applications. Now talking about Spring Annotation Spring Annotations are a form of metadata that provides data about a program. Annotations are used to provide supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program. There are many annotations are available in Spring Framework. Some of the Spring Framework Annotations are listed below as follows where here we are going to discuss one of the most important annotations that is @ServiceAnnotation @Required @Autowired @Configuration @ComponentScan @Bean @Component @Controller @Service @Repository, etc. @Service Annotation In an application, the business logic resides within the service layer so we use the @Service Annotation to indicate that a class belongs to that layer. It is also a specialization of @Component Annotation like the @Repository Annotation. One most important thing about the @Service Annotation is it can be applied only to classes. It is used to mark the class as a service provider. So overall @Service annotation is used with classes that provide some business functionalities. Spring context will autodetect these classes when annotation-based configuration and classpath scanning is used. Procedure Create a Simple Spring Boot ProjectAdd the spring-context dependency in your pom.xml file.Create one package and name the package as “service”.Test the spring repository Create a Simple Spring Boot Project Add the spring-context dependency in your pom.xml file. Create one package and name the package as “service”. Test the spring repository Step 1: Create a Simple Spring Boot Project Refer to this article Create and Setup Spring Boot Project in Eclipse IDE and create a simple spring boot project. Step 2: Add the spring-context dependency in your pom.xml file. Go to the pom.xml file inside your project and add the following spring-context dependency. XML <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.3.13</version></dependency> Step 3: In your project create one package and name the package as “service”. In the service, package creates a class and name it as MyServiceClass. This is going to be our final project structure. Example Java // Java Program to Illustrate MyServiceClass // Importing package module to code modulepackage com.example.demo.service;// Importing required classesimport org.springframework.stereotype.Service; // Annotation@Service // Classpublic class MyServiceClass { // Method // To compute factorial public int factorial(int n) { // Base case if (n == 0) return 1; return n * factorial(n - 1); }} In this code notice that it’s a simple java class that provides functionalities to calculate the factorial of a number. So we can call it a service provider. We have annotated it with @Service annotation so that spring-context can autodetect it and we can get its instance from the context. Step 4: Spring Repository Test So now our Spring Repository is ready, let’s test it out. Go to the DemoApplication.java file and refer to the below code. Example Java // Java Program to Illustrate DemoApplication // Importing package module to code fragmentpackage com.example.demo;// Importing required classesimport com.example.demo.service.MyServiceClass;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.annotation.AnnotationConfigApplicationContext; // Annotation@SpringBootApplication // Main classpublic class DemoApplication { // MAin driver method public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.scan("com.example.demo"); context.refresh(); MyServiceClass myServiceClass = context.getBean(MyServiceClass.class); // Testing the factorial method int factorialOf5 = myServiceClass.factorial(5); System.out.println("Factorial of 5 is: " + factorialOf5); // Closing the spring context // using close() method context.close(); }} Output: Note: If you are not using the @Service annotation then you are going to encounter the following exception Exception in thread “main” org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type ‘com.example.demo.service.MyServiceClass’ available at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:351) at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:342) at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1172) at com.example.demo.DemoApplication.main(DemoApplication.java:17) surindertarika1234 simranarora5sos kk773572498 Java-Spring Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Feb, 2022" }, { "code": null, "e": 768, "s": 28, "text": "Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enter...
Tryit Editor v3.7
Tryit: Using object-fit: cover
[]
Visualizing representations of Outputs/Activations of each CNN layer - GeeksforGeeks
30 Jun, 2020 Convolutional neural networks are very powerful in image classification and recognition tasks. CNN models learn features of the training images with various filters applied at each layer. The features learned at each convolutional layer significantly vary. It is an observed fact that initial layers predominantly capture edges, the orientation of image and colours in the image which are low-level features. With an increase in the number of layers, CNN captures high-level features which help differentiate between various classes of images.To understand how convolutional neural networks learn spatial and temporal dependencies of an image, different features captured at each layer can be visualized in the following manner. To visualize the features at each layer, Keras Model class is used. It allows the model to have multiple outputs. It maps given a list of input tensors to list of output tensors. tf.keras.Model() Arguments: inputs: It can be a single input or a list of inputs which are objects of keras.Input class outputs: Output/ List of outputs. Considering a dataset with images of cats and dogs, we build a convolutional neural network and add a classifier on top of it, to recognize the image given as either a cat or a dog. Training images and Validation images are loaded into a data generator using Keras ImageDataGenerator.The class mode is considered as ‘Binary’ and Batch size is considered as 20. The target size of the image is fixed as (150, 150). from keras.preprocessing.image import ImageDataGeneratortrain_datagen = ImageDataGenerator(rescale = 1./255)test_datagen = ImageDataGenerator(rescale = 1./255) train_generator = train_datagen.flow_from_directory(train_img_path, target_size =(150, 150), batch_size = 20, class_mode = "binary") validation_generator = test_datagen.flow_from_directory(val_img_path, target_size =(150, 150), batch_size = 20, class_mode = "binary") Step 2: Architecture of the modelA combination of two-dimensional convolutional layers and max-pooling layers are added, a dense classification layer is also added on top of it. For the final Dense layer, Sigmoid activation function is used as it is a two-class classification problem. from keras import modelsfrom keras import layers model = models.Sequential() model.add(layers.Conv2D(32, (3, 3), activation ='relu', input_shape =(150, 150, 3)))model.add(layers.MaxPooling2D((2, 2))) model.add(layers.Conv2D(64, (3, 3), activation ='relu'))model.add(layers.MaxPooling2D((2, 2))) model.add(layers.Conv2D(128, (3, 3), activation ='relu'))model.add(layers.MaxPooling2D((2, 2))) model.add(layers.Conv2D(128, (3, 3), activation ='relu'))model.add(layers.MaxPooling2D((2, 2))) model.add(layers.Flatten()) model.add(layers.Dense(512, activation ='relu'))model.add(layers.Dense(1, activation ="sigmoid")) model.summary() Output: Model Summary Model: "sequential_1" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv2d_1 (Conv2D) (None, 148, 148, 32) 896 _________________________________________________________________ max_pooling2d_1 (MaxPooling2 (None, 74, 74, 32) 0 _________________________________________________________________ conv2d_2 (Conv2D) (None, 72, 72, 64) 18496 _________________________________________________________________ max_pooling2d_2 (MaxPooling2 (None, 36, 36, 64) 0 _________________________________________________________________ conv2d_3 (Conv2D) (None, 34, 34, 128) 73856 _________________________________________________________________ max_pooling2d_3 (MaxPooling2 (None, 17, 17, 128) 0 _________________________________________________________________ conv2d_4 (Conv2D) (None, 15, 15, 128) 147584 _________________________________________________________________ max_pooling2d_4 (MaxPooling2 (None, 7, 7, 128) 0 _________________________________________________________________ flatten_1 (Flatten) (None, 6272) 0 _________________________________________________________________ dense_1 (Dense) (None, 512) 3211776 _________________________________________________________________ dense_2 (Dense) (None, 1) 513 ================================================================= Total params: 3, 453, 121 Trainable params: 3, 453, 121 Non-trainable params: 0 Step 3: Compiling and training the model on cats and dogs datasetLoss function: Binary cross EntropyOptimizer: RMSpropMetrics: Accuracy from keras import optimizers model.compile(loss ="binary_crossentropy", optimizer = optimizers.RMSprop(lr = 1e-4),metrics =['accuracy']) history = model.fit_generator(train_generator, steps_per_epoch = 100, epochs = 30,validation_data = validation_generator, validation_steps = 50) Step 4: Visualizing intermediate activations (Output of each layer) Consider an image which is not used for training, i.e., from test data, store the path of image in a variable ‘image_path’. from keras.preprocessing import imageimport numpy as np # Pre-processing the imageimg = image.load_img(image_path, target_size = (150, 150))img_tensor = image.img_to_array(img)img_tensor = np.expand_dims(img_tensor, axis = 0)img_tensor = img_tensor / 255. # Print image tensor shapeprint(img_tensor.shape) # Print imageimport matplotlib.pyplot as pltplt.imshow(img_tensor[0])plt.show() Output: Tensor shape: (1, 150, 150, 3) Input image: Code: Using Keras Model class to get outputs of each layer # Outputs of the 8 layers, which include conv2D and max pooling layerslayer_outputs = [layer.output for layer in model.layers[:8]]activation_model = models.Model(inputs = model.input, outputs = layer_outputs)activations = activation_model.predict(img_tensor) # Getting Activations of first layerfirst_layer_activation = activations[0] # shape of first layer activationprint(first_layer_activation.shape) # 6th channel of the image after first layer of convolution is appliedplt.matshow(first_layer_activation[0, :, :, 6], cmap ='viridis') # 15th channel of the image after first layer of convolution is appliedplt.matshow(first_layer_activation[0, :, :, 15], cmap ='viridis') Output: First layer activation shape: (1, 148, 148, 32) Sixth channel of first layer activation: Fifteenth channel of first layer activation: As already discussed, initial layers identify low-level features. The 6th channel identifies edges in the image, whereas, the fifteenth channel identifies the colour of the eyes. Code: The names of the eight layers in our model layer_names = [] for layer in model.layers[:8]: layer_names.append(layer.name)print(layer_names) Output: Layer names: ['conv2d_1', 'max_pooling2d_1', 'conv2d_2', 'max_pooling2d_2', 'conv2d_3', 'max_pooling2d_3', 'conv2d_4', 'max_pooling2d_4'] Feature maps of each layer:Layer 1: conv2d_1 Layer 2: max_pooling2d_1 Layer 3: conv2d_2 Layer 4: max_pooling2d_2 Layer 5: conv2d_3 Layer 6: max_pooling2d_3 Layer 7: conv2d_4 Layer 8: max_pooling2d_4 Inference:Initial layers are more interpretable and retain the majority of the features in the input image. As the level of the layer increases, features become less interpretable, they become more abstract and they identify features specific to the class leaving behind the general features of the image. References: https://keras.io/api/models/model/ https://www.kaggle.com/c/dogs-vs-cats https://www.geeksforgeeks.org/introduction-convolution-neural-network/ Deep-Learning Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between Informed and Uninformed Search in AI Deploy Machine Learning Model using Flask Support Vector Machine Algorithm Types of Environments in AI k-nearest neighbor algorithm in Python 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": 23953, "s": 23925, "text": "\n30 Jun, 2020" }, { "code": null, "e": 24682, "s": 23953, "text": "Convolutional neural networks are very powerful in image classification and recognition tasks. CNN models learn features of the training images with various filter...
How to use Python features in your data analytics project | by René Bremer | Towards Data Science
A lot of companies are moving to cloud and consider what tooling shall be used for data analytics. On-premises, companies mostly use propriety software for advanced analytics, BI and reporting. However, this tooling may not be the most logical choice in a cloud environment. Reasons can be 1) lack of integration with cloud provider, 2) lack of big data support or 3) lack of support for new use cases such as machine learning and deep learning. Python is a general-purpose programming language and is widely used for data analytics. Almost all cloud data platforms offer Python support and often new features become available in Python first. In this, Python can be seen as the Swiss Army knife of data analytics. In this tutorial, two projects are created that take into account important features of Python. Projects are described as follows: In the first project, a Jupyter notebook is executed on a Data Science Virtual Machine (DSVM) in Azure. Object-oriented (OO) classes are created using inheritance, overloading and encapsulation of data. Subsequently, NumPy and pandas are used for data analytics. Finally, the data is stored in a database on the DSVM. In the second project, a Databricks notebook is executed on a Spark cluster with multiple VMs. PySpark is used to create a machine learning model. Therefore, the following steps are executed: 3. Prerequisites 4. OO, NumPy, pandas and SQL with Jupyter on DSVM 5. PySpark with Azure Databricks on Spark cluster 6. Conclusion It is a standalone tutorial in which the focus is to learn the different aspects of Python. The focus is less to “deep dive” in the separate aspects. In case you more interested in deep learning, see here or in devops for AI, refer to my previous blogs, here and with focus on security, see here. The following resources need to be created: Data Science Virtual Machine (part 4) Azure Databricks Workspace (part 5) In this part, a sample Python project with three classes. Using these classes, football player’s data is registered. The following steps are executed: 4a. Get started 4b. Object-oriented (OO) programming 4c. Matrix analytics using NumPy 4d. Statistical analytics using pandas 4e. Read/write to database Log in to your Windows Data Science Virtual Machine (DSVM). On the desktop, an overview of icons of preinstalled components can be found. Click on Jupyter short cut to start a Jupyter session. Subsequently, open the Jupyter command line session that can be found in the taskbar. Copy the URL and open this in a Firefox session. Then download the following notebook to the desktop of your DSVM: https://raw.githubusercontent.com/rebremer/python_swiss_army_knife/master/SwissArmyKnifePython.ipynb Finally, select to upload the notebook in your jupyter session. Then click on the run button in the menu to run code in a cell. The most important parts of the notebook are also discussed in the remaining of the chapter. This part of the tutorial is inspired by the following tutorial by Theophano Mitsa. In this part, three classes are created to keep track of football players’ data. A snippet of the first class Player can be found below: # Class 1: Playerclass Player(object): _posList = {'goalkeeper', 'defender', 'midfielder', 'striker'} def __init__(self,name): self._playerName=name self._trainingList=[] self._rawData = np.empty((0,3), int) def setPosition(self, pos): if pos in self._posList: self._position=pos print(self._playerName + " is " + pos) else: raise ValueError("Value {} not in list.".format(pos)) def setTraining(self, t, rawData): self._trainingList.append(t) self._rawData = np.append(self._rawData, rawData, axis=0) def getTrainingRawData(self): return self._rawData #def getTrainingFilter(self, stage, tt, date): # see github project for rest of code The following can be seen in this class: A _rawData attribute is created when a new player is instantiated. This attribute is used to encapsulate training data with the setTraining method _rawData is created as protected variable. This tells a programmer that _rawData should be approached using get and set methods Subsequently, class FirstTeamPlayer can be found below: # Class 2: FirstTeamPlayerclass FirstTeamPlayer(Player): def __init__(self,ftp): Player.__init__(self, ftp) def setPosition(self,pos1, pos2): if pos1 in self._posList and pos2 in self._posList: self._posComp=pos1 self._posCL=pos2 print(self._playerName + " is " + pos1) print(self._playerName + " is " + pos2 + " in the CL") else: raise ValueError("Pos {},{} unknown".format(pos1, pos2)) def setNumber(self,number): self._number=number print(self._playerName + " has number " + str(number)) The following can be seen in this class: FirstTeamPlayer inherits from Player class which means that all the attributes/methods of the Player class can also be used in FirstTeamPlayer Method setPosition is overloaded in FirstPlayerClass and has a new definition. Method setNumber is only available in FirstPlayerClass Finally, a snippet of the training class can be found below: # Class 3: Trainingclass Training(object): _stageList = {'ArenA', 'Toekomst', 'Pool', 'Gym'} _trainingTypeList = {'strength', 'technique', 'friendly game'} def __init__(self, stage, tt, date): if stage in self._stageList: self._stage = stage else: raise ValueError("Value {} not in list.".format(stage)) if tt in self._trainingTypeList: self._trainingType = tt else: raise ValueError("Value {} not in list.".format(tt)) #todo: Valid date test (no static type checking in Python) self._date = date def getStage(self): return self._stage def getTrainingType(self): return self._trainingType def getDate(self): return self._date The following can be seen in this class: No static type checking is present in Python. For instance, a date attribute cannot be declared as date and an additional check has to be create An example how the three classes are instantiated and are used can be found in the final snippet below: # Construct two players, FirstTeamPlayer class inherits from Playerplayer1 = Player("Janssen")player2 = FirstTeamPlayer("Tadic")# SetPosition of player, method is overloaded in FirsTeamPlayerplayer1.setPosition("goalkeeper")player2.setPosition("midfielder", "striker")# Create new traning object and add traningsdata to player object. training1=Training('Toekomst', 'strength', date(2019,4,19))player1.setTraining(training1, rawData=np.random.rand(1,3))player2.setTraining(training1, rawData=np.random.rand(1,3))# Add another objecttraining2=Training('ArenA', 'friendly game', date(2019,4,20))player1.setTraining(training2, rawData=np.random.rand(1,3))player2.setTraining(training2, rawData=np.random.rand(1,3)) NumPy is the fundamental package for scientific computing with Python. In this tutorial it will be used to do matrix analytics. Notice that attribute _rawData is already encapsulated in the Player class as a NumPy array. NumPy is often used with Matplotlib to visualize data. In the snippet below, the data is taken from player class and then some matrix operations are done, from basic to more advanced. Full example can be found in the github project. # Take the matrix data from player objecs that were created earlierm1=player1.getTrainingRawData()m2=player2.getTrainingRawData()# print some valuesprint(m1[0][1])print(m1[:,0])print(m1[1:3,1:3])# arithmetictmp3=m1*m2 # [m2_11*m1_11, .., m1_33*m2_33]print(tmp3)# matrix multiplicationtmp1 = m1.dot(m2) # [m1_11 * m2_11 + m1_23 * m2_32 + m1_13 * m2_31, # ..., # m1_31 * m2_13 + m1_23 * m2_32 + m1_33 * m2_33]print(tmp1)# inverse matrixm1_inv = np.linalg.inv(m1)print("inverse matrix")print(m1_inv)print(m1.dot(m1_inv))# singular value decompositionu, s, vh = np.linalg.svd(m1, full_matrices=True)print("singular value decomposition")print(u)print(s)print(vh) Pandas is the package for high-performance, easy-to-use data structures and data analysis tools in Python. Under the hood, pandas uses NumPy for its array structure. In this tutorial it will be used to calculate some basic statistics. In the snippet below, the data is taken from player class and then some statistics operations are done. Full example can be found in the github project. # Create the same matrices as earlierm1=player1.getTrainingRawData()m2=player2.getTrainingRawData()# create column names to be added to pandas dataframecolumns = np.array(['col1', 'col2', 'col3'])# Create pandas dataframedf_1=pd.DataFrame(data=m1, columns=columns)df_2=pd.DataFrame(data=m2, columns=columns)# calculate basic statistics col1print(df_1['col1'].sum())print(df_1['col1'].mean())print(df_1['col1'].median())print(df_1['col1'].std())print(df_1['col1'].describe())# calculate correlation and covariance of dataframetmp1=df_1.cov()tmp2=df_1.corr()print("correlation:\n " + str(tmp1))print("\n")print("covariance:\n " + str(tmp2)) Finally, the data will be written to a SQL database. In this tutorial, the MSSQL database is used that is part of the DSVM. Look for the Microsoft SQL Server Management Studio (SSMS) icon that can be found in taskbar and start a new session. Log in using Windows Authentication, see also below. Look for “New Query” in the menu and start a new query session. Then execute the following script: USE [Master]GOCREATE DATABASE pythontestGOUSE [pythontest]CREATE TABLE [dbo].[trainingsdata]( [col1] [float] NOT NULL, [col2] [float] NOT NULL, [col3] [float] NOT NULL)GO Finally, the data can be written to and read from the database. Pandas dataframes will be used for this, see also the snippet below. # import libraryimport pyodbc# set connection variablesserver = '<<your vm name, which name of SQL server instance >>'database = 'pythontest'driver= '{ODBC Driver 17 for SQL Server}'# Make connection to databasecnxn = pyodbc.connect('DRIVER='+driver+';SERVER='+server+';PORT=1433;DATABASE='+database + ';Trusted_Connection=yes;')cursor = cnxn.cursor()#Write results, use pandas dataframefor index,row in df_1.iterrows(): cursor.execute("INSERT INTO dbo.trainingsdata([col1],[col2],[col3]) VALUES (?,?,?)", row['col1'], row['col2'], row['col3']) cnxn.commit()#Read results, use pandas dataframesql = "SELECT [col1], [col2], [col3] FROM dbo.trainingsdata"df_1read = pd.read_sql(sql,cnxn)print(df_1read)cursor.close() In the previous chapter, all code was run on a single machine. In case more data is generated or more advanced calculations need to be done (e.g. deep learning), the only possibility is to take a heavier machine an thus to scale up to execute the code. That is, compute cannot be distributed to other VMs. Spark is an analytics framework that can distribute compute to other VMs and thus can scale out by adding more VMs to do work. This is most of times more efficient than having a “supercomputer” doing all the work. Python can be used in Spark and is often referred to as PySpark. In this tutorial, Azure Databricks will be used that is an Apache Spark-based analytics platform optimized for the Azure. In this, the following steps are executed. 5a. Get started 5b. Project setup Start your Azure Databricks workspace and go to Cluster. Create a new cluster with the following settings: Subsequenly, select Workspace, right-click and then select import. In the radio button, select to import the following notebook using URL: https://raw.githubusercontent.com/rebremer/devopsai_databricks/master/project/modelling/1_IncomeNotebookExploration.py See also picture below: Select the notebook you imported in 4b and attach the notebook to the cluster you created in 4a. Make sure that the cluster is running and otherwise start it. Walk through the notebook cell by cell by using shortcut SHIFT+ENTER. Finally, if you want to keep track of the model, create an HTTP endpoint of the model and/or create a DevOps pipeline of the project, see my advanced DevOps for AI tutorial here, and with focus on security, see here. In this project, a machine learning model is created that predicts the income class of a person using features as age, hours of week working, education. In this, the following steps are executed: Ingest, explore and prepare data as Spark Dataframe Logistic Regression — 1 feature using hours of week worked Logistic Regression — all features (hours of work, age, state, etc) Logistic regression — prevent overfitting (regularization) Decision tree — different algorithm, find the falgorithm performs best Notice that pyspark.ml libraries are used to build the model. It is also possible to run scikit-learn libraries in Azure Databricks, however, then work would only be done be the driver (master) node and the compute is not distributed. See below a snippet of what pyspark packages are used. from pyspark.ml import Pipeline, PipelineModelfrom pyspark.ml.classification import LogisticRegressionfrom pyspark.ml.classification import DecisionTreeClassifier#... In this tutorial, two Python projects were created as follows: Jupyter notebook on a Data Science Virtual Machine using Object-oriented programming, NumPy, pandas for data analytics and SQL to store data Databricks notebook on a distributed Spark cluster with multiple VMs using PySpark to build a machine learning model A lot of companies consider what tooling to use in the cloud for data analytics. In this, almost all cloud data analytics platforms have Python support and therefore, Python can be seen as the Swiss Army knife of data analytics. This tutorial may have helped you to explore the possibilites of Python.
[ { "code": null, "e": 618, "s": 172, "text": "A lot of companies are moving to cloud and consider what tooling shall be used for data analytics. On-premises, companies mostly use propriety software for advanced analytics, BI and reporting. However, this tooling may not be the most logical choice in a...
Adding caption below X-axis for a scatter plot using Matplotlib
To add caption below X-axis for a scatter plot, we can use text() method for the current figure. Create x and y data points using numpy. Create x and y data points using numpy. Create a new figure or activate an existing figure using figure() method. Create a new figure or activate an existing figure using figure() method. Plot the scatter points with x and y data points. Plot the scatter points with x and y data points. To add caption to the figure, use text() method. To add caption to the figure, use text() method. Adjust the padding between and around the subplots. Adjust the padding between and around the subplots. To display the figure, use show() method. To display the figure, use show() method. import numpy as np from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True x = np.random.rand(10) y = np.random.rand(10) fig = plt.figure() plt.scatter(x, y, c=y) fig.text(.5, .0001, "Scatter Plot", ha='center') plt.tight_layout() plt.show()
[ { "code": null, "e": 1159, "s": 1062, "text": "To add caption below X-axis for a scatter plot, we can use text() method for the current figure." }, { "code": null, "e": 1199, "s": 1159, "text": "Create x and y data points using numpy." }, { "code": null, "e": 1239, ...
Flutter - Stateful vs Stateless Widgets - GeeksforGeeks
19 Mar, 2021 The state of an app can very simply be defined as anything that exists in the memory of the app while the app is running. This includes all the widgets that maintain the UI of the app including the buttons, text fonts, icons, animations, etc. So now as we know what are these states let’s dive directly into our main topic i.e what are these stateful and stateless widgets and how do they differ from one another. State The State is the information that can be read synchronously when the widget is built and might change during the lifetime of the widget. In other words, the state of the widget is the data of the objects that its properties (parameters) are sustaining at the time of its creation (when the widget is painted on the screen). The state can also change when it is used for example when a CheckBox widget is clicked a check appears on the box. Stateless Widget: The widgets whose state can not be altered once they are built are called stateless widgets. These widgets are immutable once they are built i.e any amount of change in the variables, icons, buttons, or retrieving data can not change the state of the app. Below is the basic structure of a stateless widget. Stateless widget overrides the build() method and returns a widget. For example, we use Text or the Icon is our flutter application where the state of the widget does not change in the runtime. It is used when the UI depends on the information within the object itself. Other examples can be Text, RaisedButton, IconButtons. Dart import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return Container(); }} So let us see what this small code snippet tells us. The name of the stateless widget is MyApp which is being called from the runApp() and extends a stateless widget. Inside this MyApp a build function is overridden and takes BuildContext as a parameter. This BuildContext is unique to each and every widget as it is used to locate the widget inside the widget tree. Note: The widgets of a Flutter application are displayed in the form of a Widget Tree where we connect the parent and child widgets to show a relationship between them which then combines to form the state of your app. The build function contains a container which is again a widget of Flutter inside which we will design the UI of the app. In the stateless widget, the build function is called only once which makes the UI of the screen. Stateful Widgets: The widgets whose state can be altered once they are built are called stateful Widgets. These states are mutable and can be changed multiple times in their lifetime. This simply means the state of an app can change multiple times with different sets of variables, inputs, data. Below is the basic structure of a stateful widget. Stateful widget overrides the createState() and returns a State. It is used when the UI can change dynamically. Some examples can be CheckBox, RadioButton, Form, TextField. Classes that inherit “Stateful Widget” are immutable. But the State is mutable which changes in the runtime when the user interacts with it. Dart import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState();} class _MyAppState extends State<MyApp> { @override Widget build(BuildContext context) { return Container(); }} So let us see what we have in this code snippet. The name of the Stateful Widget is MyApp which is called from the runApp() and extends a stateful widget. In the MyApp class, we override the create state function. This createState() function is used to create a mutable state for this widget at a given location in the tree. This method returns an instance for the respected state subclass. The other class which is _MyAppState extends the state, which manages all the changes in the widget. Inside this class, the build function is overridden which takes the BuildContext as the parameter. This build function returns a widget where we design the UI of the app. Since it is a stateful widget the build function is called many times which creates the entire UI once again with all the changes. Stateless widget is useful when the part of the user interface you are describing does not depend on anything other than the configuration information and the BuildContext whereas a Stateful widget is useful when the part of the user interface you are describing can change dynamically. tanmayhi54320 ankit_kumar_ Flutter Dart Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Flutter - DropDownButton Widget Flutter - Custom Bottom Navigation Bar Flutter - Checkbox Widget Flutter - Row and Column Widgets How to Append or Concatenate Strings in Dart? Flutter - Flexible Widget Dart Tutorial ListView Class in Flutter Operators in Dart Flutter - BoxShadow Widget
[ { "code": null, "e": 23857, "s": 23829, "text": "\n19 Mar, 2021" }, { "code": null, "e": 24271, "s": 23857, "text": "The state of an app can very simply be defined as anything that exists in the memory of the app while the app is running. This includes all the widgets that mainta...
Dart Programming - If Statement
The if...else construct evaluates a condition before a block of code is executed. Following is the syntax. if(boolean_expression){ // statement(s) will execute if the boolean expression is true. } If the Boolean expression evaluates to be true, then the block of code inside the if statement will be executed. If Boolean expression evaluates to be false, then the first set of code after the end of the if statement (after the closing curly brace) will be executed. The following illustration shows the flowchart of the if statement. The following example shows how you can use the if statement in Dart. void main() { var num=5; if (num>0) { print("number is positive"); } } The above example will print “number is positive” as the condition specified by the if block is true. number is positive 44 Lectures 4.5 hours Sriyank Siddhartha 34 Lectures 4 hours Sriyank Siddhartha 69 Lectures 4 hours Frahaan Hussain 117 Lectures 10 hours Frahaan Hussain 22 Lectures 1.5 hours Pranjal Srivastava 34 Lectures 3 hours Pranjal Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2607, "s": 2525, "text": "The if...else construct evaluates a condition before a block of code is executed." }, { "code": null, "e": 2632, "s": 2607, "text": "Following is the syntax." }, { "code": null, "e": 2729, "s": 2632, "text": "if(b...
Get only a single value from a specific MySQL row?
For this, use SELECT INTO variable with where clause. Let us first create a table − mysql> create table DemoTable1896 ( StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, StudentName varchar(20), StudentMarks int ); Query OK, 0 rows affected (0.00 sec) Insert some records in the table using insert command − mysql> insert into DemoTable1896(StudentName,StudentMarks) values('Chris',56); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1896(StudentName,StudentMarks) values('David',98); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1896(StudentName,StudentMarks) values('Mike',89); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1896(StudentName,StudentMarks) values('Sam',78); Query OK, 1 row affected (0.00 sec) Display all records from the table using select statement − mysql> select * from DemoTable1896; This will produce the following output − +-----------+-------------+--------------+ | StudentId | StudentName | StudentMarks | +-----------+-------------+--------------+ | 1 | Chris | 56 | | 2 | David | 98 | | 3 | Mike | 89 | | 4 | Sam | 78 | +-----------+-------------+--------------+ 4 rows in set (0.00 sec) Here is the query to get value from a specific MySQL row − mysql> set @Name:=NULL; Query OK, 0 rows affected (0.00 sec) mysql> select StudentName into @Name from DemoTable1896 where StudentMarks=98; Query OK, 1 row affected (0.00 sec) Now you can display the value of the above variable − mysql> select @Name; This will produce the following output − +-------+ | @Name | +-------+ | David | +-------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1146, "s": 1062, "text": "For this, use SELECT INTO variable with where clause. Let us first create a table −" }, { "code": null, "e": 1330, "s": 1146, "text": "mysql> create table DemoTable1896\n (\n StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n ...
Run Length Encoding - GeeksforGeeks
15 Feb, 2022 Given an input string, write a function that returns the Run Length Encoded string for the input string.For example, if the input string is “wwwwaaadexxxxxx”, then the function should return “w4a3d1e1x6” a) Pick the first character from the source string. b) Append the picked character to the destination string. c) Count the number of subsequent occurrences of the picked character and append the count to the destination string. d) Pick the next character and repeat steps b) c) and d) if the end of the string is NOT reached. C++ Python3 C# Javascript // CPP program to implement run length encoding#include <bits/stdc++.h>using namespace std; void printRLE(string str){ int n = str.length(); for (int i = 0; i < n; i++) { // Count occurrences of current character int count = 1; while (i < n - 1 && str[i] == str[i + 1]) { count++; i++; } // Print character and its count cout << str[i] << count; }} int main(){ string str = "wwwwaaadexxxxxxywww"; printRLE(str); return 0;} # Python3 program to implement# run length encodingdef printRLE(st): n = len(st) i = 0 while i < n- 1: # Count occurrences of # current character count = 1 while (i < n - 1 and st[i] == st[i + 1]): count += 1 i += 1 i += 1 # Print character and its count print(st[i - 1] + str(count), end = "") # Driver codeif __name__ == "__main__": st = "wwwwaaadexxxxxxywww" printRLE(st) # This code is contributed by Chitranayal // C# program to implement run length encodingusing System;class GFG{public class RunLength_Encoding{ public static void printRLE(String str) { int n = str.Length; for (int i = 0; i < n; i++) { // Count occurrences of current character int count = 1; while (i < n - 1 && str[i] == str[i + 1]) { count++; i++; } // Print character and its count Console.Write(str[i]); Console.Write(count); } } public static void Main(String[] args) { String str = "wwwwaaadexxxxxxywww"; printRLE(str); }}} // This code is contributed by shivanisinghss2110 <script>// Javascript program to implement run length encoding function printRLE(str) { let n = str.length; for (let i = 0; i < n; i++) { // Count occurrences of current character let count = 1; while (i < n - 1 && str[i] == str[i+1]) { count++; i++; } // Print character and its count document.write(str[i]); document.write(count); } } let str = "wwwwaaadexxxxxxywww"; printRLE(str); // This code is contributed by rag2127</script> w4a3d1e1x6y1w3 C Implementation C #include <stdio.h>#include <stdlib.h>#include <string.h>#define MAX_RLEN 50 /* Returns the Run Length Encoded string for the source string src */char* encode(char* src){ int rLen; char count[MAX_RLEN]; int len = strlen(src); /* If all characters in the source string are different, then size of destination string would be twice of input string. For example if the src is "abcd", then dest would be "a1b1c1d1" For other inputs, size would be less than twice. */ char* dest = (char*)malloc(sizeof(char) * (len * 2 + 1)); int i, j = 0, k; /* traverse the input string one by one */ for (i = 0; i < len; i++) { /* Copy the first occurrence of the new character */ dest[j++] = src[i]; /* Count the number of occurrences of the new character */ rLen = 1; while (i + 1 < len && src[i] == src[i + 1]) { rLen++; i++; } /* Store rLen in a character array count[] */ sprintf(count, "%d", rLen); /* Copy the count[] to destination */ for (k = 0; *(count + k); k++, j++) { dest[j] = count[k]; } } /*terminate the destination string */ dest[j] = '\0'; return dest;} /*driver program to test above function */int main(){ char str[] = "geeksforgeeks"; char* res = encode(str); printf("%s", res); getchar();} g1e2k1s1f1o1r1g1e2k1s1 Time Complexity: O(n)References: http://en.wikipedia.org/wiki/Run-length_encodingPlease write comments if you find the above code/algorithm incorrect, or find better ways to solve the same problem. shivanisinghss2110 ukasp rag2127 devsoni kushsharma1001 techieshabbir Amazon CouponDunia FactSet Microsoft String-Run Length Encoding VMWare Strings VMWare Amazon Microsoft FactSet CouponDunia Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Different methods to reverse a string in C/C++ Python program to check if a string is palindrome or not Check for Balanced Brackets in an expression (well-formedness) using Stack KMP Algorithm for Pattern Searching Convert string to char array in C++ Longest Palindromic Substring | Set 1 Caesar Cipher in Cryptography Array of Strings in C++ (5 Different Ways to Create) Reverse words in a given string Top 50 String Coding Problems for Interviews
[ { "code": null, "e": 24838, "s": 24810, "text": "\n15 Feb, 2022" }, { "code": null, "e": 25042, "s": 24838, "text": "Given an input string, write a function that returns the Run Length Encoded string for the input string.For example, if the input string is “wwwwaaadexxxxxx”, then...
Value of continuous floor function : F(x) = F(floor(x/2)) + x - GeeksforGeeks
29 Apr, 2021 Given an array of positive integers. For every element x of array, we need to find the value of continuous floor function defined as F(x) = F(floor(x/2)) + x, where F(0) = 0. Examples :- Input : arr[] = {6, 8} Output : 10 15 Explanation : F(6) = 6 + F(3) = 6 + 3 + F(1) = 6 + 3 + 1 + F(0) = 10 Similarly F(8) = 15 Basic Approach : For given value of x, we can calculate F(x) by using simple recursive function as: int func(int x) { if (x == 0) return 0; return (x + func(floor(x/2))); } In this approach if we have n queries then it will take O(x) for every query elementAn Efficient Approach is to use memoization We construct an array which holds the value of F(x) for each possible value of x. We compute the value if not already computed. Else we return the value. C++ Java Python3 C# PHP Javascript // C++ program for finding value// of continuous floor function#include <bits/stdc++.h> #define max 10000using namespace std; int dp[max]; void initDP() { for (int i = 0; i < max; i++) dp[i] = -1; } // function to return value of F(n)int func(int x) { if (x == 0) return 0; if (dp[x] == -1) dp[x] = x + func(x / 2); return dp[x]; } void printFloor(int arr[], int n) { for (int i = 0; i < n; i++) cout << func(arr[i]) << " "; } // Driver codeint main() { // call the initDP() to fill DP array initDP(); int arr[] = { 8, 6 }; int n = sizeof(arr) / sizeof(arr[0]); printFloor(arr, n); return 0; } // Java program for finding value// of continuous floor functionclass GFG{ static final int max = 10000; static int dp[] = new int[max]; static void initDP() { for (int i = 0; i < max; i++) dp[i] = -1; } // function to return value of F(n) static int func(int x) { if (x == 0) return 0; if (dp[x] == -1) dp[x] = x + func(x / 2); return dp[x]; } static void printFloor(int arr[], int n) { for (int i = 0; i < n; i++) System.out.print(func(arr[i]) + " "); } // Driver code public static void main(String[] args) { // call the initDP() to fill DP array initDP(); int arr[] = {8, 6}; int n = arr.length; printFloor(arr, n); }} // This code is contributed by Anant Agarwal. # Python3 program for finding value# of continuous floor function max = 10000 dp = [0] * max # function to initialize the DP arraydef initDP() : for i in range(max) : dp[i] = -1 # function to return value of F(n)def func(x) : if (x == 0) : return 0 if (dp[x] == -1) : dp[x] = x + func(x // 2) return dp[x] def printFloor(arr, n) : for i in range(n) : print(func(arr[i]), end = " ") # Driver Codeif __name__ == "__main__" : # call the initDP() to # fill DP array initDP() arr = [8, 6] n = len(arr) printFloor(arr, n) # This code is contributed by Ryuga // C# program for finding value// of continuous floor functionusing System; class GFG{ static int max = 10000; static int []dp = new int[max]; static void initDP() { for (int i = 0; i < max; i++) dp[i] = -1; } // function to return value of F(n) static int func(int x) { if (x == 0) return 0; if (dp[x] == -1) dp[x] = x + func(x / 2); return dp[x]; } static void printFloor(int []arr, int n) { for (int i = 0; i < n; i++) Console.Write(func(arr[i]) + " "); } // Driver code public static void Main() { // call the initDP() to fill DP array initDP(); int []arr = {8, 6}; int n = arr.Length; printFloor(arr, n); }} // This code is contributed by nitin mittal <?php// PHP program for finding value// of continuous floor function$max = 10000; $dp = array_fill(0, $max, NULL); function initDP(){ global $max,$dp; for ($i = 0; $i < $max; $i++) $dp[$i] = -1;} // function to return value of F(n)function func($x){ global $dp; if ($x == 0) return 0; if ($dp[$x] == -1) $dp[$x] = $x + func(intval($x / 2)); return $dp[$x];} function printFloor(&$arr, $n){ for ($i = 0; $i < $n; $i++) echo func($arr[$i]) . " ";} // Driver code // call the initDP() to fill DP arrayinitDP(); $arr = array(8, 6);$n = sizeof($arr); printFloor($arr, $n); // This code is contributed by ita_c?> <script>// Javascript program for finding value// of continuous floor function let max = 10000; let dp = Array.from({length: max}, (_, i) => 0); function initDP() { for (let i = 0; i < max; i++) dp[i] = -1; } // function to return value of F(n) function func(x) { if (x == 0) return 0; if (dp[x] == -1) dp[x] = x + func(Math.floor(x / 2)); return dp[x]; } function prletFloor(arr, n) { for (let i = 0; i < n; i++) document.write(func(arr[i]) + " "); } // driver function // call the initDP() to fill DP array initDP(); let arr = [8, 6]; let n = arr.length; prletFloor(arr, n); // This code is contributed by code_hunt.</script> Output: 15 10 This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.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. nitin mittal ankthon ukasp code_hunt Dynamic Programming Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16 Matrix Chain Multiplication | DP-8 Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Overlapping Subproblems Property in Dynamic Programming | DP-1 Edit Distance | DP-5 Minimum number of jumps to reach end Find minimum number of coins that make a given value Cutting a Rod | DP-13 Longest Common Substring | DP-29
[ { "code": null, "e": 24787, "s": 24759, "text": "\n29 Apr, 2021" }, { "code": null, "e": 24976, "s": 24787, "text": "Given an array of positive integers. For every element x of array, we need to find the value of continuous floor function defined as F(x) = F(floor(x/2)) + x, wher...
Function hoisting in JavaScript
Hoisting is a JavaScript technique which moves variables and function declarations to the top of their scope before code execution begins. Within a scope no matter where functions or variables are declared, they're moved to the top of their scope. Note that hoisting only moves the declaration while assignments are left in place. console.log(functionBelow("Hello")); function functionBelow(greet) { return `${greet} world`; } console.log(functionBelow("Hi")); Hello world Hi world Note that the function declaration was after it was called but was still called. This was possible due to function hoisting. Also note that it doesn't work when you assign functions like variables. console.log(functionBelow("Hello")); var functionBelow = function(greet) { return `${greet} world`; } console.log(functionBelow("Hi")); This will fail with an error: functionBelow is not a function If you remove var, it'll fail with the error: functionBelow is not defined Note that when it was declared with var, it was hoisted as a variable in the context. But it still remained undefined. This is known as variable hoisting. Due to this property, anonymous and arrow functions are never hoisted in JavaScript.
[ { "code": null, "e": 1310, "s": 1062, "text": "Hoisting is a JavaScript technique which moves variables and function declarations to the top of their scope before code execution begins. Within a scope no matter where functions or variables are declared, they're moved to the top of their scope." },...
numpy.less() in Python
28 Mar, 2022 The numpy.less() : checks whether x1 is lesser than x2 or not. Syntax : numpy.less(x1, x2[, out]) Parameters : x1, x2 : [array_like]Input arrays. If x1.shape != x2.shape, they must be broadcastable to a common shape out : [ndarray, boolean]Array of bools, or a single bool if x1 and x2 are scalars. Return : Boolean array indicating results, whether x1 is lesser than x2 or not. Code 1 : Python # Python Program illustrating# numpy.less() method import numpy as geek a = geek.less([8., 2.], [5., 3.])print("Not equal : \n", a, "\n") b = geek.less([2, 2], [[1, 3],[1, 4]])print("Not equal : \n", b, "\n") a = geek.array([4,2])b = geek.array([6,2]) print("Is a lesser than b : ", a < b) Output : Not equal : [False True] Not equal : [[False True] [False True]] Is a lesser than b : [ True False]] Code 2 : Python # Python Program illustrating# numpy.less() method import numpy as geek # Here we will compare Complex values with inta = geek.array([1j,2])b = geek.array([1,2]) # indicating 1j is lesser than 1print("Comparing complex with int : ", a < b) # indicating 1j is lesser than 1d = geek.less(a, b)print("\n Comparing complex with int .less() : ", d) Output : Comparing complex with int : [ True False] Comparing complex with int .less() : [ True False] Code 3 : Python # Python Program illustrating# numpy.less() method import numpy as geek # Here we will compare Float with int valuesa = geek.array([1.1, 1])b = geek.array([1, 2]) # indicating 1.1 is greater than 1print("Comparing float with int : ", a < b) # indicating 1.1 is greater than 1d = geek.less(a, b)print("\n Comparing float with int using .less() : ", d) Output : Comparing float with int : [False True] Comparing float with int using .less() : [False True] References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.less.html#numpy.less Note : These codes won’t run on online IDE’s. So please, run them on your systems to explore the working. This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vinayedula Python numpy-Logic Functions Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Mar, 2022" }, { "code": null, "e": 101, "s": 28, "text": "The numpy.less() : checks whether x1 is lesser than x2 or not. Syntax : " }, { "code": null, "e": 127, "s": 101, "text": "numpy.less(x1, x2[, out])" }, ...
How to Design a Web Page in HTML?
09 Mar, 2022 HTML is known as HyperText Markup Language. It is a combination of both Hypertext and Markup language. Here hypertext means the link between the web pages and markup is used to define the text document within tag which defines the structure of web pages. It acts as a skeleton of a web page and without HTML it would be very difficult or impossible to build a webpage. It is used by all the browsers and used to manipulate text, images, and other content, in order to display it in the required format. In this article, we will learn how to create an HTML webpage. The first step of creating a web page is to create an HTML document. An HTML document can be created in any text editor even on a notepad. So any text editor can be used to make an Html file. We just need to add extension .html /.htm . Let us create the first basic HTML program. To create an HTML document follow the following steps: Step 1: Open your text editor such as Notepad Sublimetext, etc. Step 2: Write the code given below in the text editor. HTML <!DOCTYPE html><html><head><title>First HTML file</title></head><body> Hello Everyone!!</body></html> Step 3: Save this file with the .html/.htm extension. Step 4: Open that file with any browser. The output will be displayed. So this is how we create a simple HTML document. To design a webpage in HTML we need to learn about tags and attributes available in HTML. In HTML, tags are some instructions that are enclosed in angle braces. With the help of these tages, we can design a more attractive HTML page. Some of the important tags to be used are as follows: 1. <h1> ... </h1> to <h5> ... </h5>: These tags are called header tags and they are used to give heading to your webpage of different sizes.<h1>...</h1> being the Largest Heading to <h5> ...</h5> being the Smallest Heading. 2. Bold Tag (<strong>...</strong> or<b>...</b>): These tags are used to make text look bold. 3. Italic Tag (<i> ...</i> or <em>... </em>): These tags are used to make text look italics. The only difference between <i> and <em > is that <em>semantically emphasis on important text or word whereas <i> tag is used to make is just used to make text italics. 4. Ordered List ( <ol> ... </ol>): The HTML <ol> tag defines an ordered list. An ordered list can be numerical or alphabetical ., An ordered list starts and ends with a <ol> tag. Each list item starts with <li> tag. We can use the type attribute to define type of ordered list we need to make: 5. Unordered List (<ul>...</ul>): It displays elements in bulletin form . An unordered list starts with <ul > tag and each item starts with <li> tag. We can use the type attribute to define the type of unordered list we need to make: 6. Image Tag: If we need to add an image to our website we need to use the following syntax. Syntax: <img src=”filename” alt=”name / bit about image”> Here, img: Tells browser that we want to add an image. src: Tells source of image for eg image from desktop or a website. alt: This attribute is used to describe an image. If the image is not able to download in a web browser due to some reason then alt is shown. 7. Anchor Tag: This tag is mainly used to connect one web page to another. Syntax: <a href=”https://www.geeksforgeeks.org/c-plus-plus/?ref=shm”> Click Here to Learn C++</a> Note: Nesting is possible in HTML, which means that we can write one tag between another tag. Example: HTML <!DOCTYPE html><html><head> <title> Steps To Form Spread Cookies </title></head><body> <h1> Spread Cookies</h1><br><h2> Steps:- </h2><ol type="I"> <li>Preheat kitchen appliance to 350oF (180oC).</li> <li> In a massive bowl, combine along the spread, sugar, and egg. </li> <li>Scoop out a spoon of dough and roll it into a ball. Place the cookie balls onto a slippy baking sheet. </li> <li>For further decoration and to form them cook additional equally, flatten the cookie balls by pressing a fork down on prime of them, then press it down once more at a 90o angle to form a criss-cross pattern.</li> <li>Bake for 8-10 minutes or till rock bottom of the cookies square measure golden brown.</li> <li>Remove from baking sheet and freeze it.</li> <li><b>ENJOY!!</b></li></ol> </body></html> Output Here, we create a simple webpage of GeeksforGeeks. HTML <!DOCTYPE html><html lang="en" dir="ltr"><head> <meta charset="utf-8"> <title>GeeksForGeeks</title></head> <body style="background-color:#D5F5E3 "> <img src="https://upload.wikimedia.org/wikipedia/commons/4/43/GeeksforGeeks.svg" style="display: block; margin-left: auto;margin-right: auto; width: 10%;" > <h1 style="color:green;text-align:center"><strong>GeeksForGeeks</strong></h1> <h1><strong>Table of Content</strong></h1> <h2><strong>C++</strong></h2> <div>C++ is an object-oriented programming language that is widely used for competitive programming, Data structure, and Algorithms, developing operating Systems, etc.</div> <h3><em>Some of its topic are given below:- </em></h3> <ul> <li><a href="https://www.geeksforgeeks.org/c-plus-plus/?ref=shm#Basics">Basics</a></li> <li><a href="https://www.geeksforgeeks.org/difference-c-structures-c-structures/">Difference Between C Structures and C++ Structures</a></li> <li><a href="https://www.geeksforgeeks.org/comparison-of-inheritance-in-c-and-java/">Comparison of Inheritance in C++ and Java</a></li> <li><a href="https://www.geeksforgeeks.org/static-keyword-in-java/">Comparison of static keyword in C++ and Java</a></li> <li><a href="https://www.geeksforgeeks.org/comparison-of-exception-handling-in-c-and-java/">Comparison of Exception Handling in C++ and Java</a></li> <li><a href="https://www.geeksforgeeks.org/basic-input-output-c/">Basic Input / Output in C++</a></li> <li><a href="https://www.geeksforgeeks.org/write-a-c-program-that-wont-compile-in-cpp/">Write a C program that won’t compile in C++</a></li> <li><a href="https://www.geeksforgeeks.org/references-in-c/">References in C++</a></li> </ul> <h2 style="color:red;"><em>Java</em></h2> <div>Java has been one amongst the foremost standard programming languages for several years. When compared with C++, Java codes are typically additional reparable as a result of Java doesn't enable several things which can cause bad/inefficient programming if used incorrectly.For instance, non-primitives are references in Java. </div> <h3><em>Some of its Topics are given below:- </em></h3> <ul> <li><a href="https://www.geeksforgeeks.org/introduction-to-java/">Introduction to Java</a></li> <li><a href="https://www.geeksforgeeks.org/c-vs-java-vs-python/">C++ vs Java vs Python</a></li> <li><a href="https://www.geeksforgeeks.org/jvm-works-jvm-architecture/">How JVM Works – JVM Architecture?</a></li> <li><a href="https://www.geeksforgeeks.org/java-basic-syntax/">Java Basic Syntax</a></li> <li><a href="https://www.geeksforgeeks.org/java-identifiers/">Java Identifiers</a></li> <li><a href="https://www.geeksforgeeks.org/variable-scope-in-java/">Scope of Variables In Java</a></li> <li><a href="https://www.geeksforgeeks.org/decision-making-javaif-else-switch-break-continue-jump/">Decision Making in Java (if, if-else, switch, break, continue, jump)</a></li> <li><a href="https://www.geeksforgeeks.org/java-arithmetic-operators-with-examples/">Java Arithmetic Operators with Examples</a></li> </ul> <h2 style="color: blue;">Python</h3> <div> Python language is being employed in website development, Machine Learning applications, at the side of all innovative technology in Software World. Python language is extremely compatible for Beginners, additionally for knowledgeable programmers with alternative programming languages like C++ and Java. </div> <h3><em>Some of its topics given below are:- </em></h3> <ul> <li><a href="https://www.geeksforgeeks.org/python-language-introduction/">Python Language Intro</a></li> <li><a href="https://www.geeksforgeeks.org/structuring-python-programs/">Structures</a></li> <li><a href="https://www.geeksforgeeks.org/python-keywords/">Keywords</a></li> <li><a href="https://www.geeksforgeeks.org/python-if-else/">Decision Making</a></li> <li><a href="https://www.geeksforgeeks.org/python-3-basics/">Python 3 basics</a></li> </ul> <h1 style="text-align: center">Thank You</h1> </body></html> Output: kk9826225 Picked Class 10 School Learning School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Internet Mobile Technologies - Definition, Types, Uses, Advantages Metals and Non-Metals - Definition, Properties, Uses and Applications Dependent and Independent Events - Probability Chemical Indicators - Definition, Types, Examples How to Align Text in HTML? Libraries in Python Geometric Series Generations of Computers - Computer Fundamentals What are Different Output Devices?
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Mar, 2022" }, { "code": null, "e": 593, "s": 28, "text": "HTML is known as HyperText Markup Language. It is a combination of both Hypertext and Markup language. Here hypertext means the link between the web pages and markup is used t...
Create a Responsive Navbar using ReactJS
30 Jul, 2021 In this Article, We will create a functioning navigation bar using Reactjs. Problem statement: Create a navigation bar using reactJS & styled-component Modules required: npmcreate-react-appstyled-componentsreact-router-dom npm create-react-app styled-components react-router-dom Basic Setup: For creating a react app you have a node installed on your computer, you can check it by typing in your terminal: node -v If you don’t please install the latest version. All set now! You will start a new project using create-react-app so open your terminal and type: npx create-react-app navigation-bar Now go to your navigation-bar folder by typing the given command in the terminal: cd navigation-bar Install the dependencies required in this project by typing the given command in the terminal: npm install react-router-dom npm install --save styled-components Now create the components folder in src then go to the components folder and create a new folder name Navbar.In Navbar folder create two files index,js and NavbarElements.js. Create one more folder in src name pages and in pages create files name about.js, annual.js, blogs.js, events.js, index.js, signup.js, team.js Project Structure: The file structure in the project will look like this: File pathe: Create index.js file in src/components/Navbar. Javascript import React from 'react';import { Nav, NavLink, Bars, NavMenu, NavBtn, NavBtnLink,} from './NavbarElements'; const Navbar = () => { return ( <> <Nav> <Bars /> <NavMenu> <NavLink to='/about' activeStyle> About </NavLink> <NavLink to='/events' activeStyle> Events </NavLink> <NavLink to='/annual' activeStyle> Annual Report </NavLink> <NavLink to='/team' activeStyle> Teams </NavLink> <NavLink to='/blogs' activeStyle> Blogs </NavLink> <NavLink to='/sign-up' activeStyle> Sign Up </NavLink> {/* Second Nav */} {/* <NavBtnLink to='/sign-in'>Sign In</NavBtnLink> */} </NavMenu> <NavBtn> <NavBtnLink to='/signin'>Sign In</NavBtnLink> </NavBtn> </Nav> </> );}; export default Navbar; File path: Create NavbarElements.js file in src/components/Navbar. Javascript import { FaBars } from 'react-icons/fa';import { NavLink as Link } from 'react-router-dom';import styled from 'styled-components'; export const Nav = styled.nav` background: #63D471; height: 85px; display: flex; justify-content: space-between; padding: 0.2rem calc((100vw - 1000px) / 2); z-index: 12; /* Third Nav */ /* justify-content: flex-start; */`; export const NavLink = styled(Link)` color: #808080; display: flex; align-items: center; text-decoration: none; padding: 0 1rem; height: 100%; cursor: pointer; &.active { color: #000000; }`; export const Bars = styled(FaBars)` display: none; color: #808080; @media screen and (max-width: 768px) { display: block; position: absolute; top: 0; right: 0; transform: translate(-100%, 75%); font-size: 1.8rem; cursor: pointer; }`; export const NavMenu = styled.div` display: flex; align-items: center; margin-right: -24px; /* Second Nav */ /* margin-right: 24px; */ /* Third Nav */ /* width: 100vw; white-space: nowrap; */ @media screen and (max-width: 768px) { display: none; }`; export const NavBtn = styled.nav` display: flex; align-items: center; margin-right: 24px; /* Third Nav */ /* justify-content: flex-end; width: 100vw; */ @media screen and (max-width: 768px) { display: none; }`; export const NavBtnLink = styled(Link)` border-radius: 4px; background: #808080; padding: 10px 22px; color: #000000; outline: none; border: none; cursor: pointer; transition: all 0.2s ease-in-out; text-decoration: none; /* Second Nav */ margin-left: 24px; &:hover { transition: all 0.2s ease-in-out; background: #fff; color: #808080; }`; Edit various pages for the navigation bar in the project in src/pages: Filename about.js:JavascriptJavascriptimport React from 'react'; const About = () => { return ( <div style={{ display: 'flex', justifyContent: 'Right', alignItems: 'Right', height: '100vh' }} > <h1>GeeksforGeeks is a Computer Science portal for geeks.</h1> </div> );}; export default About; Filename about.js: Javascript import React from 'react'; const About = () => { return ( <div style={{ display: 'flex', justifyContent: 'Right', alignItems: 'Right', height: '100vh' }} > <h1>GeeksforGeeks is a Computer Science portal for geeks.</h1> </div> );}; export default About; Filename annual.js:JavascriptJavascriptimport React from 'react'; const AnnualReport = () => { return ( <div style={{ display: 'flex', justifyContent: 'Right', alignItems: 'Right', height: '100vh' }} > <h1>Annual Report</h1> </div> );}; export default AnnualReport; Filename annual.js: Javascript import React from 'react'; const AnnualReport = () => { return ( <div style={{ display: 'flex', justifyContent: 'Right', alignItems: 'Right', height: '100vh' }} > <h1>Annual Report</h1> </div> );}; export default AnnualReport; Filename blogs.js:JavascriptJavascriptimport React from 'react'; const Blogs = () => { return ( <div style={{ display: 'flex', justifyContent: 'Right', alignItems: 'Right', height: '100vh' }} > <h1>Welcome to GeeksforGeeks Blogs</h1> </div> );}; export default Blogs; Filename blogs.js: Javascript import React from 'react'; const Blogs = () => { return ( <div style={{ display: 'flex', justifyContent: 'Right', alignItems: 'Right', height: '100vh' }} > <h1>Welcome to GeeksforGeeks Blogs</h1> </div> );}; export default Blogs; Filename events.js:JavascriptJavascriptimport React from 'react'; const Events = () => { return ( <div style={{ display: 'flex', justifyContent: 'Right', alignItems: 'Right', height: '100vh' }} > <h1>Welcome to GeeksforGeeks Events</h1> </div> );}; export default Events; Filename events.js: Javascript import React from 'react'; const Events = () => { return ( <div style={{ display: 'flex', justifyContent: 'Right', alignItems: 'Right', height: '100vh' }} > <h1>Welcome to GeeksforGeeks Events</h1> </div> );}; export default Events; Filename index.js:JavascriptJavascriptimport React from 'react'; const Home = () => { return ( <div style={{ display: 'flex', justifyContent: 'Right', alignItems: 'Right', height: '100vh' }} > <h1>Welcome to GeeksforGeeks</h1> </div> );}; export default Home; Filename index.js: Javascript import React from 'react'; const Home = () => { return ( <div style={{ display: 'flex', justifyContent: 'Right', alignItems: 'Right', height: '100vh' }} > <h1>Welcome to GeeksforGeeks</h1> </div> );}; export default Home; Filename signup.js:JavascriptJavascriptimport React from 'react'; const SignUp = () => { return ( <div style={{ display: 'flex', justifyContent: 'Right', alignItems: 'Right', height: '100vh' }} > <h1>Sign Up</h1> </div> );}; export default SignUp; Filename signup.js: Javascript import React from 'react'; const SignUp = () => { return ( <div style={{ display: 'flex', justifyContent: 'Right', alignItems: 'Right', height: '100vh' }} > <h1>Sign Up</h1> </div> );}; export default SignUp; Filename team.js:JavascriptJavascriptimport React from 'react'; const Teams = () => { return ( <div style={{ display: 'flex', justifyContent: 'Right', alignItems: 'Right', height: '100vh' }} > <h1>Welcome to GeeksforGeeks Team</h1> </div> );}; export default Teams; Filename team.js: Javascript import React from 'react'; const Teams = () => { return ( <div style={{ display: 'flex', justifyContent: 'Right', alignItems: 'Right', height: '100vh' }} > <h1>Welcome to GeeksforGeeks Team</h1> </div> );}; export default Teams; Filename src/index.js: file in src. Javascript import React from 'react';import ReactDOM from 'react-dom';import App from './App'; ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById('root')); Filename App.js: file in src folder. Javascript import React from 'react';import './App.css';import Navbar from './components/Navbar';import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';import Home from './pages';import About from './pages/about';import Events from './pages/events';import AnnualReport from './pages/annual';import Teams from './pages/team';import Blogs from './pages/blogs';import SignUp from './pages/signup'; function App() { return ( <Router> <Navbar /> <Switch> <Route path='/' exact component={Home} /> <Route path='/about' component={About} /> <Route path='/events' component={Events} /> <Route path='/annual' component={AnnualReport} /> <Route path='/team' component={Teams} /> <Route path='/blogs' component={Blogs} /> <Route path='/sign-up' component={SignUp} /> </Switch> </Router> );} export default App; Save all files and start the server by using the command. npm start Output: CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples. Technical Scripter 2020 CSS JavaScript ReactJS Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n30 Jul, 2021" }, { "code": null, "e": 130, "s": 54, "text": "In this Article, We will create a functioning navigation bar using Reactjs." }, { "code": null, "e": 206, "s": 130, "text": "Problem statement: Create a n...
Multimap in C++ Standard Template Library (STL)
17 Jan, 2022 Multimap is similar to a map with the addition that multiple elements can have the same keys. Also, it is NOT required that the key-value and mapped value pair have to be unique in this case. One important thing to note about multimap is that multimap keeps all the keys in sorted order always. These properties of multimap make it very much useful in competitive programming. Some Basic Functions associated with multimap: begin() – Returns an iterator to the first element in the multimap end() – Returns an iterator to the theoretical element that follows last element in the multimap size() – Returns the number of elements in the multimap max_size() – Returns the maximum number of elements that the multimap can hold empty() – Returns whether the multimap is empty pair<int,int> insert(keyvalue,multimapvalue) – Adds a new element to the multimap C++ implementation to illustrate above functions: CPP // CPP Program to demonstrate the implementation of multimap#include <iostream>#include <iterator>#include <map>using namespace std; // Driver Codeint main(){ multimap<int, int> gquiz1; // empty multimap container // insert elements in random order gquiz1.insert(pair<int, int>(1, 40)); gquiz1.insert(pair<int, int>(2, 30)); gquiz1.insert(pair<int, int>(3, 60)); gquiz1.insert(pair<int, int>(6, 50)); gquiz1.insert(pair<int, int>(6, 10)); // printing multimap gquiz1 multimap<int, int>::iterator itr; cout << "\nThe multimap gquiz1 is : \n"; cout << "\tKEY\tELEMENT\n"; for (itr = gquiz1.begin(); itr != gquiz1.end(); ++itr) { cout << '\t' << itr->first << '\t' << itr->second << '\n'; } cout << endl; // adding elements randomly, // to check the sorted keys property gquiz1.insert(pair<int, int>(4, 50)); gquiz1.insert(pair<int, int>(5, 10)); // printing multimap gquiz1 again cout << "\nThe multimap gquiz1 after adding extra " "elements is : \n"; cout << "\tKEY\tELEMENT\n"; for (itr = gquiz1.begin(); itr != gquiz1.end(); ++itr) { cout << '\t' << itr->first << '\t' << itr->second << '\n'; } cout << endl; // assigning the elements from gquiz1 to gquiz2 multimap<int, int> gquiz2(gquiz1.begin(), gquiz1.end()); // print all elements of the multimap gquiz2 cout << "\nThe multimap gquiz2 after assign from " "gquiz1 is : \n"; cout << "\tKEY\tELEMENT\n"; for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) { cout << '\t' << itr->first << '\t' << itr->second << '\n'; } cout << endl; // remove all elements up to // key with value 3 in gquiz2 cout << "\ngquiz2 after removal of elements less than " "key=3 : \n"; cout << "\tKEY\tELEMENT\n"; gquiz2.erase(gquiz2.begin(), gquiz2.find(3)); for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) { cout << '\t' << itr->first << '\t' << itr->second << '\n'; } // remove all elements with key = 4 int num; num = gquiz2.erase(4); cout << "\ngquiz2.erase(4) : "; cout << num << " removed \n"; cout << "\tKEY\tELEMENT\n"; for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) { cout << '\t' << itr->first << '\t' << itr->second << '\n'; } cout << endl; // lower bound and upper bound for multimap gquiz1 key = // 5 cout << "gquiz1.lower_bound(5) : " << "\tKEY = "; cout << gquiz1.lower_bound(5)->first << '\t'; cout << "\tELEMENT = " << gquiz1.lower_bound(5)->second << endl; cout << "gquiz1.upper_bound(5) : " << "\tKEY = "; cout << gquiz1.upper_bound(5)->first << '\t'; cout << "\tELEMENT = " << gquiz1.upper_bound(5)->second << endl; return 0;} The multimap gquiz1 is : KEY ELEMENT 1 40 2 30 3 60 6 50 6 10 The multimap gquiz1 after adding extra elements is : KEY ELEMENT 1 40 2 30 3 60 4 50 5 10 6 50 6 10 The multimap gquiz2 after assign from gquiz1 is : KEY ELEMENT 1 40 2 30 3 60 4 50 5 10 6 50 6 10 gquiz2 after removal of elements less than key=3 : KEY ELEMENT 3 60 4 50 5 10 6 50 6 10 gquiz2.erase(4) : 1 removed KEY ELEMENT 3 60 5 10 6 50 6 10 gquiz1.lower_bound(5) : KEY = 5 ELEMENT = 10 gquiz1.upper_bound(5) : KEY = 6 ELEMENT = 50 Function Definition Recent Articles on Multimap Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. smodi2007 atharvakango dlbm1302 c0d3rpr0 anshikajain26 cpp-containers-library cpp-multimap cpp-multimap-functions STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n17 Jan, 2022" }, { "code": null, "e": 429, "s": 52, "text": "Multimap is similar to a map with the addition that multiple elements can have the same keys. Also, it is NOT required that the key-value and mapped value pair have to be uni...
HTML5 <audio> Tag
15 Jul, 2022 Since the release of HTML5, audios can be added to webpages using the “audio” tag. Previously, audios could be only played on web pages using web plugins like Flash. The “audio” tag is an inline element that is used to embed sound files into a web page. It is a useful tag if you want to add audio such as songs, interviews, etc. on your webpage. Syntax: <audio> <source src="sample.mp3" type="audio/mpeg"> </audio> Attributes: The various attributes that can be used with the “audio” tag are listed below: Controls: Designates what controls to display with the audio player. Autoplay: Designates that the audio file will play immediately after it loads controls. Loop: Designates that the audio file should continuously repeat. src: Designates the URL of the audio file. muted: Designates that the audio file should be muted. Supported Formats: Three formats mp3, ogg, wav are supported by HTML5. The support for each format by different browsers is given below : The below Examples explain the audio Tag: Example 1 (Adding audio to Webpage): The controls attribute is used to add audio controls such as play, pause, and volume. The “source” element is used to specify the audio files which the browser may use. The first recognized format is used by the browser. HTML <!DOCTYPE html><html> <body> <p>Audio Sample</p> <!-- audio tag starts here --> <audio controls> <source src="test.mp3" type="audio/mp3"> <source src="test.ogg" type="audio/ogg"> </audio> <!-- audio tag ends here --> </body> </html> Output : Example 2 (Autoplaying audio on a Webpage): The autoplay attribute is used to automatically begin playback of the audio file whenever the URL of the webpage is loaded. HTML <!DOCTYPE html><html> <body> <p>Audio Sample</p> <!-- audio tag starts here --> <audio controls autoplay> <source src="test.mp3" type="audio/mp3"> <source src="test.ogg" type="audio/ogg"> </audio> <!-- audio tag ends here --></body> </html> Output : Example 3 (Adding muted audio file on a Webpage): The muted attribute specifies that the audio should be muted on the webpage. HTML <!DOCTYPE html><html> <body> <p>Audio Sample</p> <!-- audio tag starts here --> <audio controls muted> <source src="test.mp3" type="audio/mp3"> <source src="test.ogg" type="audio/ogg"> </audio> <!-- audio tag ends here --></body> </html> Output : Example 4 (Adding audio using the source element): The source element can be used to add audio files to a webpage. The src attribute is used to specify the source of the file specified. HTML <!DOCTYPE html><html> <body> <p>Audio Sample</p> <!-- audio tag starts here --> <audio controls autoplay> <source src="test.mp3" type="audio/mp3"> </audio> <!-- audio tag ends here --> </body> </html> Output : Example 5 (Adding audio with multiple sources): Multiple sources of audios are specified so that if the browser is unable to play the first source, then it will automatically jump to the second source and try to play it. HTML <!DOCTYPE html><html> <body> <p>Audio Sample</p> <!-- audio tag starts here --> <audio controls autoplay> <source src="test.mp3" type="audio/mp3"> <source src="test.ogg" type="audio/ogg"> <source src="test.opus" type="audio/ogg"> </audio> <!-- audio tag ends here --> </body> </html> Output : Example 6 (Adding audio using the “Embed” tag): Adding audios to a webpage using the “embed” tag is an old technique. This method does work, but is comparatively less efficient than the other methods. The user must have a plugin like MIDI or QuickTime because the embed tag requires a plugin for support. HTML <!DOCTYPE html><html> <body> <p>Audio Sample</p> <!-- embed code starts here --> <embed src="test.mp3" width="200" height="50" autoplay="true" loop="true"> <!-- embed code ends here --></body> </html> Output: Supported browsers: Google Chrome 3.0 and above Edge 12.0 and above Internet Explorer 9.0 and above Firefox 3.5 and above Opera 10.5 and above Safari 3.1 and above nidhi_biet shubhamyadav4 sanayush1357 kumargaurav97520 HTML-Tags HTML5 HTML Technical Scripter HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n15 Jul, 2022" }, { "code": null, "e": 400, "s": 53, "text": "Since the release of HTML5, audios can be added to webpages using the “audio” tag. Previously, audios could be only played on web pages using web plugins like Flash. The “aud...
Output of C programs | Set 31 (Pointers)
19 Apr, 2018 Prerequisite: Pointers in C/C++ Question 1What will be the output?#include<stdio.h> int main(){ int a[] = { 1, 2, 3, 4, 5} ; int *ptr; ptr = a; printf(" %d ", *( ptr + 1) ); return 0;}output 2 Description:It is possible to assign an array to a pointer. so, when ptr = a; is executed the address of element a[0] is assigned to ptr and *ptr gives the value of element a[0]. When *(ptr + n) is executed the value at the nth location in the array is accessed.Question 2What will be the output?#include<stdio.h> int main(){ int a = 5; int *ptr ; ptr = &a; *ptr = *ptr * 3; printf("%d", a); return 0;}Output: 15 Description:ptr = &a; copies the address of a in ptr making *ptr = a and the statement *ptr = *ptr * 3; can be written as a = a * 3; making a as 15.Question 2What will be the output? #include<stdio.h> int main(){ int i = 6, *j, k; j = &i; printf("%d\n", i * *j * i + *j); return 0;}Output:222 Description:According to BODMAS rule multiplication is given higher priority. In the expression i * *j * i + *j;, i * *j *i will be evaluated first and gives result 216 and then adding *j i.e., i = 6 the output becomes 222.Question 4What will be the output?#include<stdio.h> int main(){ int x = 20, *y, *z; // Assume address of x is 500 and // integer is 4 byte size y = &x; z = y; *y++; *z++; x++; printf("x = %d, y = %d, z = %d \n", x, y, z); return 0;}Output:x=21 y=504 z=504Description:In the beginning, the address of x is assigned to y and then y to z, it makes y and z similar. when the pointer variables are incremented there value is added with the size of the variable, in this case, y and z are incremented by 4.Question 5What will be the output?#include<stdio.h> int main(){ int x = 10; int *y, **z; y = &x; z = &y; printf("x = %d, y = %d, z = %d\n", x, *y, **z); return 0;}Output:x=10 y=10 z=10Description:*y is a pointer variable whereas **z is a pointer to a pointer variable. *y gives the value at the address it holds and **z searches twice i.e., it first takes the value at the address it holds and then gives the value at that address. Question 1What will be the output?#include<stdio.h> int main(){ int a[] = { 1, 2, 3, 4, 5} ; int *ptr; ptr = a; printf(" %d ", *( ptr + 1) ); return 0;}output 2 Description:It is possible to assign an array to a pointer. so, when ptr = a; is executed the address of element a[0] is assigned to ptr and *ptr gives the value of element a[0]. When *(ptr + n) is executed the value at the nth location in the array is accessed. #include<stdio.h> int main(){ int a[] = { 1, 2, 3, 4, 5} ; int *ptr; ptr = a; printf(" %d ", *( ptr + 1) ); return 0;} output 2 Description:It is possible to assign an array to a pointer. so, when ptr = a; is executed the address of element a[0] is assigned to ptr and *ptr gives the value of element a[0]. When *(ptr + n) is executed the value at the nth location in the array is accessed. Question 2What will be the output?#include<stdio.h> int main(){ int a = 5; int *ptr ; ptr = &a; *ptr = *ptr * 3; printf("%d", a); return 0;}Output: 15 Description:ptr = &a; copies the address of a in ptr making *ptr = a and the statement *ptr = *ptr * 3; can be written as a = a * 3; making a as 15. #include<stdio.h> int main(){ int a = 5; int *ptr ; ptr = &a; *ptr = *ptr * 3; printf("%d", a); return 0;} Output: 15 Description:ptr = &a; copies the address of a in ptr making *ptr = a and the statement *ptr = *ptr * 3; can be written as a = a * 3; making a as 15. Question 2What will be the output? #include<stdio.h> int main(){ int i = 6, *j, k; j = &i; printf("%d\n", i * *j * i + *j); return 0;}Output:222 Description:According to BODMAS rule multiplication is given higher priority. In the expression i * *j * i + *j;, i * *j *i will be evaluated first and gives result 216 and then adding *j i.e., i = 6 the output becomes 222. #include<stdio.h> int main(){ int i = 6, *j, k; j = &i; printf("%d\n", i * *j * i + *j); return 0;} Output: 222 Description:According to BODMAS rule multiplication is given higher priority. In the expression i * *j * i + *j;, i * *j *i will be evaluated first and gives result 216 and then adding *j i.e., i = 6 the output becomes 222. Question 4What will be the output?#include<stdio.h> int main(){ int x = 20, *y, *z; // Assume address of x is 500 and // integer is 4 byte size y = &x; z = y; *y++; *z++; x++; printf("x = %d, y = %d, z = %d \n", x, y, z); return 0;}Output:x=21 y=504 z=504Description:In the beginning, the address of x is assigned to y and then y to z, it makes y and z similar. when the pointer variables are incremented there value is added with the size of the variable, in this case, y and z are incremented by 4. #include<stdio.h> int main(){ int x = 20, *y, *z; // Assume address of x is 500 and // integer is 4 byte size y = &x; z = y; *y++; *z++; x++; printf("x = %d, y = %d, z = %d \n", x, y, z); return 0;} Output: x=21 y=504 z=504 Description:In the beginning, the address of x is assigned to y and then y to z, it makes y and z similar. when the pointer variables are incremented there value is added with the size of the variable, in this case, y and z are incremented by 4. Question 5What will be the output?#include<stdio.h> int main(){ int x = 10; int *y, **z; y = &x; z = &y; printf("x = %d, y = %d, z = %d\n", x, *y, **z); return 0;}Output:x=10 y=10 z=10Description:*y is a pointer variable whereas **z is a pointer to a pointer variable. *y gives the value at the address it holds and **z searches twice i.e., it first takes the value at the address it holds and then gives the value at that address. #include<stdio.h> int main(){ int x = 10; int *y, **z; y = &x; z = &y; printf("x = %d, y = %d, z = %d\n", x, *y, **z); return 0;} Output: x=10 y=10 z=10 Description:*y is a pointer variable whereas **z is a pointer to a pointer variable. *y gives the value at the address it holds and **z searches twice i.e., it first takes the value at the address it holds and then gives the value at that address. This article is contributed by I.HARISH KUMARs 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. mohit rao 1 C-Output Program Output Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Runtime Errors Different ways to copy a string in C/C++ Output of C++ Program | Set 1 Output of Java Program | Set 3 Output of Java Programs | Set 12 Output of C++ programs | Set 47 (Pointers) Output of C programs | Set 59 (Loops and Control Statements) Output of Java Program | Set 7 Output of C Programs | Set 3 Output of Java program | Set 15 (Inner Classes)
[ { "code": null, "e": 52, "s": 24, "text": "\n19 Apr, 2018" }, { "code": null, "e": 84, "s": 52, "text": "Prerequisite: Pointers in C/C++" }, { "code": null, "e": 2230, "s": 84, "text": "Question 1What will be the output?#include<stdio.h> int main(){ int a...
outtextxy() function in C
05 Dec, 2019 The header file graphics.h contains outtextxy() function which displays the text or string at a specified point (x, y) on the screen. Syntax : void outtextxy(int x, int y, char *string); where, x, y are coordinates of the point and, third argument contains the address of string to be displayed. Examples : Input : x = 200, y = 150, string = "Hello Geek, Have a good day !" Output : Input : x = 150, y = 250, string = "GeeksforGeeks is the best !" Output : Below is the implementation for outtextxy() function: // C Implementation for outtextxy()#include <graphics.h> // driver codeint main(){ // gm is Graphics mode which is // a computer display mode that // generates image using pixels. // DETECT is a macro defined in // "graphics.h" header file int gd = DETECT, gm; // initgraph initializes the // graphics system by loading a // graphics driver from disk initgraph(&gd, &gm, ""); // outtextxy function outtextxy(200, 150, "Hello Geek, Have a good day !"); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system . closegraph(); return 0;} Output : Akanksha_Rai c-graphics computer-graphics C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n05 Dec, 2019" }, { "code": null, "e": 188, "s": 54, "text": "The header file graphics.h contains outtextxy() function which displays the text or string at a specified point (x, y) on the screen." }, { "code": null, "e": 197...
How to setup Competitive Programming in Visual Studio Code for C++
11 May, 2022 We need to install GCC compilers for Windows. Linux has already GCC installed. 1.Download and Install the MinGW for GCC compiler using this link. 2.Open Control Panel in your system and then select: System (Control Panel) 3.Click on the Advanced system settings 4.Click on Environment Variables. In the section System Variables, find the PATH environment variable and select it. Click Edit. 5.In the Edit System Variable window, specify the value of the PATH environment variable. 6.Type "C:\MinGW\bin" 7.Click OK. 8.Close all remaining windows by clicking OK. 1.Code Runner (By JunHan)---> To run the c++ code 2.C/C++ (By Microsoft)---> For intellisense and debugging 3.competitive-programming helper (By Divyanshu Agrawal) ---> Automatically Reads I/O for codechef/codeforces Below is the example for the template for competitive programming which programmers use. You can change this template according to your choice and preference: C++ #pragma GCC optimize("Ofast")#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,fma")#pragma GCC optimize("unroll-loops")#include <bits/stdc++.h> #include <complex>#include <queue>#include <set>#include <unordered_set>#include <list>#include <chrono>#include <random>#include <iostream>#include <algorithm>#include <cmath>#include <string>#include <vector>#include <map>#include <unordered_map>#include <stack>#include <iomanip>#include <fstream> using namespace std; typedef long long ll;typedef long double ld;typedef pair<int,int> p32;typedef pair<ll,ll> p64;typedef pair<double,double> pdd;typedef vector<ll> v64;typedef vector<int> v32;typedef vector<vector<int> > vv32;typedef vector<vector<ll> > vv64;typedef vector<vector<p64> > vvp64;typedef vector<p64> vp64;typedef vector<p32> vp32;ll MOD = 998244353;double eps = 1e-12;#define forn(i,e) for(ll i = 0; i < e; i++)#define forsn(i,s,e) for(ll i = s; i < e; i++)#define rforn(i,s) for(ll i = s; i >= 0; i--)#define rforsn(i,s,e) for(ll i = s; i >= e; i--)#define ln "\n"#define dbg(x) cout<<#x<<" = "<<x<<ln#define mp make_pair#define pb push_back#define fi first#define se second#define INF 2e18#define fast_cin() ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL)#define all(x) (x).begin(), (x).end()#define sz(x) ((ll)(x).size()) void solve(){}int main(){ fast_cin(); ll t; cin >> t; for(int it=1;it<=t;it++) { cout << "Case #" << it+1 << ": "; solve(); } return 0;} 1.Open VS Code and go to: File > Preferences > User Snippets 2.Click on New Snippets 3.Type cpp.json((can be anything).json)(the name of snippet) 4.Delete all the default code 5.Paste the json code given below (dont copy above C++ code!!, json files are needed for user snippets in VS Code) 1.Create a .cpp file(note: below snippet will only work once used in C++ file) 2.type the Snippet Trigger(look at "prefix" attribute in 3rd line of json file given below) 3.press tab or enter (the default prefix is set as gfg, you can alter it as per your need) Javascript { "C++ Snippet": { "prefix": "gfg", "body": [ "#pragma GCC optimize(\"Ofast\")", "#pragma GCC target(\"sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,fma\")", "#pragma GCC optimize(\"unroll-loops\")", "#include <bits/stdc++.h> ", "#include <complex>", "#include <queue>", "#include <set>", "#include <unordered_set>", "#include <list>", "#include <chrono>", "#include <random>", "#include <iostream>", "#include <algorithm>", "#include <cmath>", "#include <string>", "#include <vector>", "#include <map>", "#include <unordered_map>", "#include <stack>", "#include <iomanip>", "#include <fstream>", " ", "using namespace std;", " ", "typedef long long ll;", "typedef long double ld;", "typedef pair<int,int> p32;", "typedef pair<ll,ll> p64;", "typedef pair<double,double> pdd;", "typedef vector<ll> v64;", "typedef vector<int> v32;", "typedef vector<vector<int> > vv32;", "typedef vector<vector<ll> > vv64;", "typedef vector<vector<p64> > vvp64;", "typedef vector<p64> vp64;", "typedef vector<p32> vp32;", "ll MOD = 998244353;", "double eps = 1e-12;", "#define forn(i,e) for(ll i = 0; i < e; i++)", "#define forsn(i,s,e) for(ll i = s; i < e; i++)", "#define rforn(i,s) for(ll i = s; i >= 0; i--)", "#define rforsn(i,s,e) for(ll i = s; i >= e; i--)", "#define ln \"\\n\"", "#define dbg(x) cout<<#x<<\" = \"<<x<<ln", "#define mp make_pair", "#define pb push_back", "#define fi first", "#define se second", "#define INF 2e18", "#define fast_cin() ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL)", "#define all(x) (x).begin(), (x).end()", "#define sz(x) ((ll)(x).size())", " ", "", "void solve(){", "}", "int main()", "{", " fast_cin();", " ll t;", " cin >> t;", " for(int it=1;it<=t;it++) {", " cout << \"Case #\" << it+1 << \": \";", " solve();", " }", " return 0;", "}" ], "description": "C++ Snippet" }} Basic Navigation Select highlighted option to create a new snippet “type cpp.json” the name of snippet, it should be a json file Erase all this default code and paste the given json code Note: In Prefix you have to use your personal choice word, here for example i am using gfg. This is very important because it is the key to call the template in your code. Save this snippet by pressing CTRL+S. Open a new cpp file and write your prefix that you wrote in the prefix box.(Here i had used gfg). All coding sites use a file comparison method to check answers. It means they store the output through your program in a text file and compare it with the actual answer file. Therefore, you should also do so. What you need to do is create a folder and inside it create 2 files input.txt, output.txt. First of all create the three required files. A cpp file containing your program.A text file input.txt and output.txt. Ensure that all three files are in the same directory. We need to divide the editor into three spaces Main code space Input SpaceOutput Space Main code space Input Space Output Space 1.Once your cpp program is open, go to View>Editor Layout>Two Columns 2.In the empty(right) column right click and choose Split down 3.In the top window, right click and click on open file, open input.txt from the dropdown. 4.Repeat the same process in the bottom window. 5.Paste the c++ code at the end of post just inside the main method Note: When you make any changes in input don’t forgot to save it by pressing ctrl+S in input.txt box. Note: Don’t forgot to add this code after your main () C++ #ifndef ONLINE_JUDGEfreopen("input.txt", "r", stdin);freopen("output.txt", "w", stdout);#endif sarvjot surindertarika1234 rs1686740 CPP-Competitive-Programming C++ Programs Competitive Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n11 May, 2022" }, { "code": null, "e": 131, "s": 52, "text": "We need to install GCC compilers for Windows. Linux has already GCC installed." }, { "code": null, "e": 618, "s": 131, "text": "1.Download and Install the...
Python | Grouping similar substrings in list
17 Jun, 2021 Sometimes we have an application in which we require to group common prefix strings into one such that further processing can be done according to the grouping. This type of grouping is useful in the cases of Machine Learning and Web Development. Let’s discuss certain ways in which this can be done.Method #1 : Using lambda + itertools.groupby() + split() The combination of above three functions help us achieve the task. The split method is key as it defines the separator by which grouping has to be performed. The groupby function does the grouping of elements. Python3 # Python3 code to demonstrate# group similar substrings# using lambda + itertools.groupby() + split()from itertools import groupby # initializing listtest_list = ['geek_1', 'coder_2', 'geek_4', 'coder_3', 'pro_3'] # sort list# essential for groupingtest_list.sort() # printing the original listprint ("The original list is : " + str(test_list)) # using lambda + itertools.groupby() + split()# group similar substringsres = [list(i) for j, i in groupby(test_list, lambda a: a.split('_')[0])] # printing resultprint ("The grouped list is : " + str(res)) The original list is : [‘coder_2’, ‘coder_3’, ‘geek_1’, ‘geek_4’, ‘pro_3’] The grouped list is : [[‘coder_2’, ‘coder_3’], [‘geek_1’, ‘geek_4’], [‘pro_3’]] Method #2 : Using lambda + itertools.groupby() + partition() The similar task can also be performed replacing the split function with the partition function. This is more efficient way to perform this task as it uses the iterators and hence internally quicker. Python3 # Python3 code to demonstrate# group similar substrings# using lambda + itertools.groupby() + partition()from itertools import groupby # initializing listtest_list = ['geek_1', 'coder_2', 'geek_4', 'coder_3', 'pro_3'] # sort list# essential for groupingtest_list.sort() # printing the original listprint ("The original list is : " + str(test_list)) # using lambda + itertools.groupby() + partition()# group similar substringsres = [list(i) for j, i in groupby(test_list, lambda a: a.partition('_')[0])] # printing resultprint ("The grouped list is : " + str(res)) The original list is : [‘coder_2’, ‘coder_3’, ‘geek_1’, ‘geek_4’, ‘pro_3’] The grouped list is : [[‘coder_2’, ‘coder_3’], [‘geek_1’, ‘geek_4’], [‘pro_3’]] sweetyty Python list-programs Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Jun, 2021" }, { "code": null, "e": 596, "s": 28, "text": "Sometimes we have an application in which we require to group common prefix strings into one such that further processing can be done according to the grouping. This type of g...
Inheritance in C++
13 Jul, 2022 The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object-Oriented Programming. Inheritance is a feature or a process in which, new classes are created from the existing classes. The new class created is called “derived class” or “child class” and the existing class is known as the “base class” or “parent class”. The derived class now is said to be inherited from the base class. When we say derived class inherits the base class, it means, the derived class inherits all the properties of the base class, without changing the properties of base class and may add new features to its own. These new features in the derived class will not affect the base class. The derived class is the specialized class for the base class. Sub Class: The class that inherits properties from another class is called Subclass or Derived Class. Super Class: The class whose properties are inherited by a subclass is called Base Class or Superclass. The article is divided into the following subtopics: Why and when to use inheritance? Modes of Inheritance Types of Inheritance Consider a group of vehicles. You need to create classes for Bus, Car, and Truck. The methods fuelAmount(), capacity(), applyBrakes() will be the same for all three classes. If we create these classes avoiding inheritance then we have to write all of these functions in each of the three classes as shown below figure: Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. You can clearly see that the above process results in duplication of the same code 3 times. This increases the chances of error and data redundancy. To avoid this type of situation, inheritance is used. If we create a class Vehicle and write these three functions in it and inherit the rest of the classes from the vehicle class, then we can simply avoid the duplication of data and increase re-usability. Look at the below diagram in which the three classes are inherited from vehicle class: Using inheritance, we have to write the functions only one time instead of three times as we have inherited the rest of the three classes from the base class (Vehicle).Implementing inheritance in C++: For creating a sub-class that is inherited from the base class we have to follow the below syntax. Derived Classes: A Derived class is defined as the class derived from the base class.Syntax: class <derived_class_name> : <access-specifier> <base_class_name> { //body } Whereclass — keyword to create a new classderived_class_name — name of the new class, which will inherit the base classaccess-specifier — either of private, public or protected. If neither is specified, PRIVATE is taken as defaultbase-class-name — name of the base classNote: A derived class doesn’t inherit access to private data members. However, it does inherit a full parent object, which contains any private members which that class declares. Example:1. class ABC : private XYZ //private derivation { }2. class ABC : public XYZ //public derivation { }3. class ABC : protected XYZ //protected derivation { }4. class ABC: XYZ //private derivation by default{ } o When a base class is privately inherited by the derived class, public members of the base class becomes the private members of the derived class and therefore, the public members of the base class can only be accessed by the member functions of the derived class. They are inaccessible to the objects of the derived class.o On the other hand, when the base class is publicly inherited by the derived class, public members of the base class also become the public members of the derived class. Therefore, the public members of the base class are accessible by the objects of the derived class as well as by the member functions of the derived class. C++ // Example: define member function without argument within the class #include<iostream>using namespace std; class Person{ int id; char name[100]; public: void set_p() { cout<<"Enter the Id:"; cin>>id; fflush(stdin); cout<<"Enter the Name:"; cin.get(name,100); } void display_p() { cout<<endl<<id<<"\t"<<name; }}; class Student: private Person{ char course[50]; int fee; public: void set_s() { set_p(); cout<<"Enter the Course Name:"; fflush(stdin); cin.getline(course,50); cout<<"Enter the Course Fee:"; cin>>fee; } void display_s() { display_p(); cout<<"t"<<course<<"\t"<<fee; }}; main(){ Student s; s.set_s(); s.display_s(); return 0;} Enter the Id:Enter the Name:Enter the Course Name:Enter the Course Fee: 0 t 0 C++ // Example: define member function without argument outside the class #include<iostream>using namespace std; class Person{ int id; char name[100]; public: void set_p(); void display_p();}; void Person::set_p(){ cout<<"Enter the Id:"; cin>>id; fflush(stdin); cout<<"Enter the Name:"; cin.get(name,100);} void Person::display_p(){ cout<<endl<<id<<"\t"<<name;} class Student: private Person{ char course[50]; int fee; public: void set_s(); void display_s();}; void Student::set_s(){ set_p(); cout<<"Enter the Course Name:"; fflush(stdin); cin.getline(course,50); cout<<"Enter the Course Fee:"; cin>>fee;} void Student::display_s(){ display_p(); cout<<"t"<<course<<"\t"<<fee;} main(){ Student s; s.set_s(); s.display_s(); return 0;} Enter the Id:Enter the Name:Enter the Course Name:Enter the Course Fee: 0 t 0 C++ // Example: define member function with argument outside the class #include<iostream>#include<string.h>using namespace std; class Person{ int id; char name[100]; public: void set_p(int,char[]); void display_p();}; void Person::set_p(int id,char n[]){ this->id=id; strcpy(this->name,n); } void Person::display_p(){ cout<<endl<<id<<"\t"<<name;} class Student: private Person{ char course[50]; int fee; public: void set_s(int,char[],char[],int); void display_s();}; void Student::set_s(int id,char n[],char c[],int f){ set_p(id,n); strcpy(course,c); fee=f;} void Student::display_s(){ display_p(); cout<<"t"<<course<<"\t"<<fee;} main(){ Student s; s.set_s(1001,"Ram","B.Tech",2000); s.display_s(); return 0;} CPP // C++ program to demonstrate implementation// of Inheritance #include <bits/stdc++.h>using namespace std; // Base classclass Parent {public: int id_p;}; // Sub class inheriting from Base Class(Parent)class Child : public Parent {public: int id_c;}; // main functionint main(){ Child obj1; // An object of class child has all data members // and member functions of class parent obj1.id_c = 7; obj1.id_p = 91; cout << "Child id is: " << obj1.id_c << '\n'; cout << "Parent id is: " << obj1.id_p << '\n'; return 0;} Child id is: 7 Parent id is: 91 Output: Child id is: 7 Parent id is: 91 In the above program, the ‘Child’ class is publicly inherited from the ‘Parent’ class so the public data members of the class ‘Parent’ will also be inherited by the class ‘Child’.Modes of Inheritance: There are 3 modes of inheritance. Public Mode: If we derive a subclass from a public base class. Then the public member of the base class will become public in the derived class and protected members of the base class will become protected in the derived class.Protected Mode: If we derive a subclass from a Protected base class. Then both public members and protected members of the base class will become protected in the derived class.Private Mode: If we derive a subclass from a Private base class. Then both public members and protected members of the base class will become Private in the derived class. Public Mode: If we derive a subclass from a public base class. Then the public member of the base class will become public in the derived class and protected members of the base class will become protected in the derived class. Protected Mode: If we derive a subclass from a Protected base class. Then both public members and protected members of the base class will become protected in the derived class. Private Mode: If we derive a subclass from a Private base class. Then both public members and protected members of the base class will become Private in the derived class. Note: The private members in the base class cannot be directly accessed in the derived class, while protected members can be directly accessed. For example, Classes B, C, and D all contain the variables x, y, and z in the below example. It is just a question of access. CPP // C++ Implementation to show that a derived class// doesn’t inherit access to private data members.// However, it does inherit a full parent object.class A {public: int x; protected: int y; private: int z;}; class B : public A { // x is public // y is protected // z is not accessible from B}; class C : protected A { // x is protected // y is protected // z is not accessible from C}; class D : private A // 'private' is default for classes{ // x is private // y is private // z is not accessible from D}; The below table summarizes the above three modes and shows the access specifier of the members of the base class in the subclass when derived in public, protected and private modes: Single inheritanceMultilevel inheritanceMultiple inheritanceHierarchical inheritanceHybrid inheritance Single inheritance Multilevel inheritance Multiple inheritance Hierarchical inheritance Hybrid inheritance 1. Single Inheritance: In single inheritance, a class is allowed to inherit from only one class. i.e. one subclass is inherited by one base class only. Syntax: class subclass_name : access_mode base_class { // body of subclass }; OR class A { ... .. ... }; class B: public A { ... .. ... }; CPP // C++ program to explain// Single inheritance#include<iostream>using namespace std; // base classclass Vehicle { public: Vehicle() { cout << "This is a Vehicle\n"; }}; // sub class derived from a single base classesclass Car : public Vehicle { }; // main functionint main(){ // Creating object of sub class will // invoke the constructor of base classes Car obj; return 0;} This is a Vehicle C++ // Example: #include<iostream>using namespace std; class A{ protected: int a; public: void set_A() { cout<<"Enter the Value of A="; cin>>a; } void disp_A() { cout<<endl<<"Value of A="<<a; }}; class B: public A{ int b,p; public: void set_B() { set_A(); cout<<"Enter the Value of B="; cin>>b; } void disp_B() { disp_A(); cout<<endl<<"Value of B="<<b; } void cal_product() { p=a*b; cout<<endl<<"Product of "<<a<<" * "<<b<<" = "<<p; } }; main(){ B _b; _b.set_B(); _b.cal_product(); return 0; } Output:- Enter the Value of A= 3 3 Enter the Value of B= 5 5 Product of 3 * 5 = 15 C++ // Example: #include<iostream>using namespace std; class A{ protected: int a; public: void set_A(int x) { a=x; } void disp_A() { cout<<endl<<"Value of A="<<a; }}; class B: public A{ int b,p; public: void set_B(int x,int y) { set_A(x); b=y; } void disp_B() { disp_A(); cout<<endl<<"Value of B="<<b; } void cal_product() { p=a*b; cout<<endl<<"Product of "<<a<<" * "<<b<<" = "<<p; } }; main(){ B _b; _b.set_B(4,5); _b.cal_product(); return 0;} Product of 4 * 5 = 20 2. Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class can inherit from more than one class. i.e one subclass is inherited from more than one base class. Syntax: class subclass_name : access_mode base_class1, access_mode base_class2, .... { // body of subclass }; class B { ... .. ... }; class C { ... .. ... }; class A: public B, public C { ... ... ... }; Here, the number of base classes will be separated by a comma (‘, ‘) and the access mode for every base class must be specified. CPP // C++ program to explain// multiple inheritance#include <iostream>using namespace std; // first base classclass Vehicle {public: Vehicle() { cout << "This is a Vehicle\n"; }}; // second base classclass FourWheeler {public: FourWheeler() { cout << "This is a 4 wheeler Vehicle\n"; }}; // sub class derived from two base classesclass Car : public Vehicle, public FourWheeler {}; // main functionint main(){ // Creating object of sub class will // invoke the constructor of base classes. Car obj; return 0;} This is a Vehicle This is a 4 wheeler Vehicle C++ // Example: #include<iostream>using namespace std; class A{ protected: int a; public: void set_A() { cout<<"Enter the Value of A="; cin>>a; } void disp_A() { cout<<endl<<"Value of A="<<a; }}; class B: public A{ protected: int b; public: void set_B() { cout<<"Enter the Value of B="; cin>>b; } void disp_B() { cout<<endl<<"Value of B="<<b; }}; class C: public B{ int c,p; public: void set_C() { cout<<"Enter the Value of C="; cin>>c; } void disp_C() { cout<<endl<<"Value of C="<<c; } void cal_product() { p=a*b*c; cout<<endl<<"Product of "<<a<<" * "<<b<<" * "<<c<<" = "<<p; }}; main(){ C _c; _c.set_A(); _c.set_B(); _c.set_C(); _c.disp_A(); _c.disp_B(); _c.disp_C(); _c.cal_product(); return 0; } To know more about it, please refer to the article Multiple Inheritances. 3. Multilevel Inheritance: In this type of inheritance, a derived class is created from another derived class. Syntax:- class C { ... .. ... }; class B:public C { ... .. ... }; class A: public B { ... ... ... }; CPP // C++ program to implement// Multilevel Inheritance#include <iostream>using namespace std; // base classclass Vehicle {public: Vehicle() { cout << "This is a Vehicle\n"; }}; // first sub_class derived from class vehicleclass fourWheeler : public Vehicle {public: fourWheeler() { cout << "Objects with 4 wheels are vehicles\n"; }};// sub class derived from the derived base class fourWheelerclass Car : public fourWheeler {public: Car() { cout << "Car has 4 Wheels\n"; }}; // main functionint main(){ // Creating object of sub class will // invoke the constructor of base classes. Car obj; return 0;} This is a Vehicle Objects with 4 wheels are vehicles Car has 4 Wheels 4. Hierarchical Inheritance: In this type of inheritance, more than one subclass is inherited from a single base class. i.e. more than one derived class is created from a single base class. Syntax:- class A { // body of the class A. } class B : public A { // body of class B. } class C : public A { // body of class C. } class D : public A { // body of class D. } CPP // C++ program to implement// Hierarchical Inheritance#include <iostream>using namespace std; // base classclass Vehicle {public: Vehicle() { cout << "This is a Vehicle\n"; }}; // first sub classclass Car : public Vehicle {}; // second sub classclass Bus : public Vehicle {}; // main functionint main(){ // Creating object of sub class will // invoke the constructor of base class. Car obj1; Bus obj2; return 0;} This is a Vehicle This is a Vehicle 5. Hybrid (Virtual) Inheritance: Hybrid Inheritance is implemented by combining more than one type of inheritance. For example: Combining Hierarchical inheritance and Multiple Inheritance. Below image shows the combination of hierarchical and multiple inheritances: CPP // C++ program for Hybrid Inheritance #include <iostream>using namespace std; // base classclass Vehicle {public: Vehicle() { cout << "This is a Vehicle\n"; }}; // base classclass Fare {public: Fare() { cout << "Fare of Vehicle\n"; }}; // first sub classclass Car : public Vehicle {}; // second sub classclass Bus : public Vehicle, public Fare {}; // main functionint main(){ // Creating object of sub class will // invoke the constructor of base class. Bus obj2; return 0;} This is a Vehicle Fare of Vehicle C++ // Example: #include <iostream> using namespace std; class A { protected: int a; public: void get_a() { cout << "Enter the value of 'a' : "; cin>>a; } }; class B : public A { protected: int b; public: void get_b() { cout << "Enter the value of 'b' : "; cin>>b; } }; class C { protected: int c; public: void get_c() { cout << "Enter the value of c is : "; cin>>c; } }; class D : public B, public C { protected: int d; public: void mul() { get_a(); get_b(); get_c(); cout << "Multiplication of a,b,c is : " <<a*b*c; } }; int main() { D d; d.mul(); return 0; } 6. A special case of hybrid inheritance: Multipath inheritance: A derived class with two base classes and these two base classes have one common base class is called multipath inheritance. Ambiguity can arise in this type of inheritance. Example: CPP // C++ program demonstrating ambiguity in Multipath// Inheritance #include <iostream>using namespace std; class ClassA {public: int a;}; class ClassB : public ClassA {public: int b;}; class ClassC : public ClassA {public: int c;}; class ClassD : public ClassB, public ClassC {public: int d;}; int main(){ ClassD obj; // obj.a = 10; // Statement 1, Error // obj.a = 100; // Statement 2, Error obj.ClassB::a = 10; // Statement 3 obj.ClassC::a = 100; // Statement 4 obj.b = 20; obj.c = 30; obj.d = 40; cout << " a from ClassB : " << obj.ClassB::a; cout << "\n a from ClassC : " << obj.ClassC::a; cout << "\n b : " << obj.b; cout << "\n c : " << obj.c; cout << "\n d : " << obj.d << '\n';} a from ClassB : 10 a from ClassC : 100 b : 20 c : 30 d : 40 Output: a from ClassB : 10 a from ClassC : 100 b : 20 c : 30 d : 40 In the above example, both ClassB and ClassC inherit ClassA, they both have a single copy of ClassA. However Class-D inherits both ClassB and ClassC, therefore Class-D has two copies of ClassA, one from ClassB and another from ClassC. If we need to access the data member of ClassA through the object of Class-D, we must specify the path from which a will be accessed, whether it is from ClassB or ClassC, bcoz compiler can’t differentiate between two copies of ClassA in Class-D. 1) Avoiding ambiguity using the scope resolution operator: Using the scope resolution operator we can manually specify the path from which data member a will be accessed, as shown in statements 3 and 4, in the above example. CPP obj.ClassB::a = 10; // Statement 3obj.ClassC::a = 100; // Statement 4 Note: Still, there are two copies of ClassA in Class-D.2) Avoiding ambiguity using the virtual base class: CPP #include<iostream> class ClassA{ public: int a;}; class ClassB : virtual public ClassA{ public: int b;}; class ClassC : virtual public ClassA{ public: int c;}; class ClassD : public ClassB, public ClassC{ public: int d;}; int main(){ ClassD obj; obj.a = 10; // Statement 3 obj.a = 100; // Statement 4 obj.b = 20; obj.c = 30; obj.d = 40; cout << "\n a : " << obj.a; cout << "\n b : " << obj.b; cout << "\n c : " << obj.c; cout << "\n d : " << obj.d << '\n';} Output: a : 100 b : 20 c : 30 d : 40 According to the above example, Class-D has only one copy of ClassA, therefore, statement 4 will overwrite the value of a, given in statement 3. This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. vasu_arora _nimesh_ surendrapandey kziemianfvt sackshamsharmaintern aditiyadav20102001 sasasakukuku123123 deetav001 C++ School Programming CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n13 Jul, 2022" }, { "code": null, "e": 244, "s": 52, "text": "The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object-Orien...
Simplifying Context Free Grammars
11 Apr, 2022 The definition of context free grammars (CFGs) allows us to develop a wide variety of grammars. Most of the time, some of the productions of CFGs are not useful and are redundant. This happens because the definition of CFGs does not restrict us from making these redundant productions. By simplifying CFGs we remove all these redundant productions from a grammar , while keeping the transformed grammar equivalent to the original grammar. Two grammars are called equivalent if they produce the same language. Simplifying CFGs is necessary to later convert them into Normal forms. Types of redundant productions and the procedure of removing them are mentioned below. 1. Useless productions – The productions that can never take part in derivation of any string , are called useless productions. Similarly , a variable that can never take part in derivation of any string is called a useless variable. For eg. S -> abS | abA | abB A -> cd B -> aB C -> dc In the example above , production ‘C -> dc’ is useless because the variable ‘C’ will never occur in derivation of any string. The other productions are written in such a way that variable ‘C’ can never reached from the starting variable ‘S’. Production ‘B ->aB’ is also useless because there is no way it will ever terminate . If it never terminates , then it can never produce a string. Hence the production can never take part in any derivation. To remove useless productions , we first find all the variables which will never lead to a terminal string such as variable ‘B’. We then remove all the productions in which variable ‘B’ occurs. So the modified grammar becomes – S -> abS | abA A -> cd C -> dc We then try to identify all the variables that can never be reached from the starting variable such as variable ‘C’. We then remove all the productions in which variable ‘C’ occurs. The grammar below is now free of useless productions – S -> abS | abA A -> cd 2. λ productions – The productions of type ‘A -> λ’ are called λ productions ( also called lambda productions and null productions) . These productions can only be removed from those grammars that do not generate λ (an empty string). It is possible for a grammar to contain null productions and yet not produce an empty string. To remove null productions , we first have to find all the nullable variables. A variable ‘A’ is called nullable if λ can be derived from ‘A’. For all the productions of type ‘A -> λ’ , ‘A’ is a nullable variable. For all the productions of type ‘B -> A1A2...An ‘ , where all ’Ai’s are nullable variables , ‘B’ is also a nullable variable. After finding all the nullable variables, we can now start to construct the null production free grammar. For all the productions in the original grammar , we add the original production as well as all the combinations of the production that can be formed by replacing the nullable variables in the production by λ. If all the variables on the RHS of the production are nullable , then we do not add ‘A -> λ’ to the new grammar. An example will make the point clear. Consider the grammar – S -> ABCd (1) A -> BC (2) B -> bB | λ (3) C -> cC | λ (4) Lets first find all the nullable variables. Variables ‘B’ and ‘C’ are clearly nullable because they contain ‘λ’ on the RHS of their production. Variable ‘A’ is also nullable because in (2) , both variables on the RHS are also nullable. Similarly , variable ‘S’ is also nullable. So variables ‘S’ , ‘A’ , ‘B’ and ‘C’ are nullable variables. Lets create the new grammar. We start with the first production. Add the first production as it is. Then we create all the possible combinations that can be formed by replacing the nullable variables with λ. Therefore line (1) now becomes ‘S -> ABCd | ABd | ACd | BCd | Ad | Bd |Cd | d ’.We apply the same rule to line (2) but we do not add ‘A -> λ’ even though it is a possible combination. We remove all the productions of type ‘V -> λ’. The new grammar now becomes – S -> ABCd | ABd | ACd | BCd | Ad | Bd |Cd | d A -> BC | B | C B -> bB | b C -> cC | c 3. Unit productions – The productions of type ‘A -> B’ are called unit productions. To create a unit production free grammar ‘Guf’ from the original grammar ‘G’ , we follow the procedure mentioned below. First add all the non-unit productions of ‘G’ in ‘Guf’. Then for each variable ‘A’ in grammar ‘G’ , find all the variables ‘B’ such that ‘A *=> B’. Now , for all variables like ‘A ’ and ‘B’, add ‘A -> x1 | x2 | ...xn’ to ‘Guf’ where ‘B -> x1 | x2 | ...xn ‘ is in ‘Guf’ . None of the x1 , x2 ... xn are single variables because we only added non-unit productions in ‘Guf’. Hence the resultant grammar is unit production free. For eg. S -> Aa | B A -> b | B B -> A | a Lets add all the non-unit productions of ‘G’ in ‘Guf’. ‘Guf’ now becomes – S -> Aa A -> b B -> a Now we find all the variables that satisfy ‘X *=> Z’. These are ‘S*=>B’, ‘A *=> B’ and ‘B *=> A’. For ‘A *=> B’ , we add ‘A -> a’ because ‘B ->a’ exists in ‘Guf’. ‘Guf’ now becomes S -> Aa A -> b | a B -> a For ‘B *=> A’ , we add ‘B -> b’ because ‘A -> b’ exists in ‘Guf’. The new grammar now becomes S -> Aa A -> b | a B -> a | b We follow the same step for ‘S*=>B’ and finally get the following grammar – S -> Aa | b | a A -> b | a B -> a | b Now remove B -> a|b , since it doesnt occur in the production ‘S’, then the following grammar becomes, S->Aa|b|a A->b|a Note: To remove all kinds of productions mentioned above, first remove the null productions, then the unit productions and finally , remove the useless productions. Following this order is very important to get the correct result. This article is contributed by Nitish Joshi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. jagandevaki1 abhigyanmishra5000 mithisomp simmytarika5 Theory of Computation & Automata Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n11 Apr, 2022" }, { "code": null, "e": 339, "s": 52, "text": "The definition of context free grammars (CFGs) allows us to develop a wide variety of grammars. Most of the time, some of the productions of CFGs are not useful and are redun...
Joining Threads in Java
java.lang.Thread class provides a method join() which serves the following purposes usign its overloaded version. join() − The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates. join() − The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates. join(long millisec) − The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates or the specified number of milliseconds passes. join(long millisec) − The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates or the specified number of milliseconds passes. join(long millisec, int nanos) − The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates or the specified number of milliseconds + nanoseconds passes. join(long millisec, int nanos) − The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates or the specified number of milliseconds + nanoseconds passes. See the below example demonstrating the concept. Live Demo class CustomThread implements Runnable { public void run() { System.out.println(Thread.currentThread().getName() + " started."); try { Thread.sleep(500); } catch (InterruptedException e) { System.out.println(Thread.currentThread().getName() + " interrupted."); } System.out.println(Thread.currentThread().getName() + " exited."); } } public class Tester { public static void main(String args[]) throws InterruptedException { Thread t1 = new Thread( new CustomThread(), "Thread-1"); t1.start(); //main thread class the join on t1 //and once t1 is finish then only t2 can start t1.join(); Thread t2 = new Thread( new CustomThread(), "Thread-2"); t2.start(); //main thread class the join on t2 //and once t2 is finish then only t3 can start t2.join(); Thread t3 = new Thread( new CustomThread(), "Thread-3"); t3.start(); } } Thread-1 started. Thread-1 exited. Thread-2 started. Thread-2 exited. Thread-3 started. Thread-3 exited.
[ { "code": null, "e": 1176, "s": 1062, "text": "java.lang.Thread class provides a method join() which serves the following purposes usign its overloaded version." }, { "code": null, "e": 1316, "s": 1176, "text": "join() − The current thread invokes this method on a second thread, ...
Minimum Operations | Practice | GeeksforGeeks
Given a number N. Find the minimum number of operations required to reach N starting from 0. You have 2 operations available: Double the number Add one to the number Example 1: Input: N = 8 Output: 4 Explanation: 0 + 1 = 1, 1 + 1 = 2, 2 * 2 = 4, 4 * 2 = 8 ​Example 2: Input: N = 7 Output: 5 Explanation: 0 + 1 = 1, 1 + 1 = 2, 1 + 2 = 3, 3 * 2 = 6, 6 + 1 = 7 Your Task: You don't need to read input or print anything. Your task is to complete the function minOperation() which accepts an integer N and return number of minimum operations required to reach N from 0. Expected Time Complexity: O(LogN) Expected Auxiliary Space: O(1) Constraints: 1 <= N <= 106 0 shaank181851 minutes ago Java Code class Solution { public int minOperation(int n) { int count = 0; //code here. while(n!=0){ //if no is divisible by 2 then divide it by two else substract 1; if(n%2==0){ n = n/2; count++; } else{ n = n-1; count++; } } return count; } } 0 mohitaggar20083 weeks ago int minOperation(int n) { //code here. int A[n+1],j,k,min=INT_MAX; A[0]=0; A[1]=1; A[2]=2; for(int i=3;i<n+1;++i) { min=INT_MAX; A[i]=i; j=i; k=0; while(k<j) { if(A[k]+A[j]<min) min=A[k]+A[j]; j--; k++; } A[i]=min; if(j==k) { if(A[j]+1<A[i]) A[i]=A[j]+1; } } return A[n]; } solution using dp but time limit exeeds 0 moaslam8263 weeks ago C++ EASY SOLN int fun(int n){ if(n==0){ return 0; } if(n/2!=0 && !(n&1)){ return 1+fun(n/2); } else{ return 1+fun(n-1); } } int minOperation(int n) { //code here return fun(n); } +1 kashyapjhon3 weeks ago C++ Solution DP Code Time=(0.0/1.3): int help(vector<int> &dp,int n){ if(n==0){ return 0; } if(dp[n]!=-1){ return dp[n]; } if(n%2==0){ int l= help(dp,n-1)+1; int r= help(dp,n/2)+1; return dp[n]=min(l,r); } else{ return dp[n]=help(dp,n-1)+1; } } int minOperation(int n) { //code here. vector<int> dp(n+1,-1); help(dp,n); return dp[n]; } +1 19501a05h21 month ago simple C++ dp answer int minOperation(int n) { int dp[n]; dp[0] = 0; for(int i=1;i<=n;i++) { if(i%2==0) dp[i]=dp[i/2]+1; else dp[i] = dp[i-1]+1; } return dp[n]; } 0 mayank20211 month ago C++ : 0.0/1.3int minOperation(int n) { int count=0; while(n) { if(n&1) n=n-1; else n=n/2; count++; } return count; } 0 cs19b01911 month ago int dp[n+1]; for(int i = n ; i >= 1 ; i--) { if(i == n) dp[i] = 0; else { int temp1 = i+1; int temp2 = i*2; if(temp1 > n && temp2 > n) dp[i] = 1+i; else if(temp1 > n) dp[i] = min(1+i,1+dp[temp2]); else if(temp2 > n) dp[i] = min(1+dp[temp1] , 1+i); else dp[i] = min(1+dp[temp1] , 1+dp[temp2]); } } return dp[1]+1; 0 tyagipratap1111 month ago // Just for reference type variable class Count { private int a; public Count(int x) { a = x; } public void update(int x) { a = x; } public int get() { return a; } } // Recursive function int find(int n, Count c) { if (n == 0) return 0; if (n == 1) { c.update(c.get() + 1); return 1; } if (n % 2 == 0) n = n / 2; else n = n - 1; c.update(c.get() + 1); return find(n, c); } int minOperation(int n) { Count c = new Count(0); find(n, c); return c.get(); } 0 anshul gupta 62 months ago WITH DP int[] dp = new int[n + 1]; Arrays.fill(dp, Integer.MAX_VALUE); dp[0] = 0; for (int i = 0; i < dp.length; i++) { int temp = i + 1; if (temp < dp.length) dp[temp] = Math.min(dp[i] + 1, dp[temp]); temp = i * 2; if (temp < dp.length) dp[temp] = Math.min(dp[i] + 1, dp[temp]); } return dp[n]; 0 akkick1432 months ago class Solution: def minOperation(self, n): if n<2: return n else: if n%2==1: res=1+self.minOperation(n-1) else: res=self.minOperation(n//2)+1 return res We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 352, "s": 226, "text": "Given a number N. Find the minimum number of operations required to reach N starting from 0. You have 2 operations available:" }, { "code": null, "e": 371, "s": 352, "text": "Double the number " }, { "code": null, "e": 393,...
How to open multiple filenames in Tkinter and add the file names to a list?
To open a file dialog in a tkinter application, tkinter provides the tkfiledialog package which creates a dialog box to interact with the external files located on the system. In order to work with filedialog, we have to first import the package using the following command, import tkinter.filedialog as fd To open the explorer in the window, use asopenfilename(parent, title, **options) function. It will just pull the window and allow the user to select the file from the explorer. Once the file has been opened, we can define a function to print the list of all the selected files. # Import the required libraries from tkinter import * from tkinter import ttk import tkinter.filedialog as fd # Create an instance of tkinter frame or window win = Tk() # Set the geometry of tkinter frame win.geometry("700x350") def open_file(): file = fd.askopenfilenames(parent=win, title='Choose a File') print(win.splitlist(file)) # Add a Label widget label = Label(win, text="Select the Button to Open the File", font=('Aerial 11')) label.pack(pady=30) # Add a Button Widget ttk.Button(win, text="Select a File", command=open_file).pack() win.mainloop() Running the above code will display a window that contains a button and a Label Text widget. Click the Button "Select a File" to open the Dialog for selecting the Files from the Explorer.
[ { "code": null, "e": 1337, "s": 1062, "text": "To open a file dialog in a tkinter application, tkinter provides the tkfiledialog package which creates a dialog box to interact with the external files located on the system. In order to work with filedialog, we have to first import the package using t...
New Algorithm to Generate Prime Numbers from 1 to Nth Number - GeeksforGeeks
24 Apr, 2019 Apart from Sieve of Eratosthenes method to generate Prime numbers, we can implement a new Algorithm for generating prime numbers from 1 to N. It might be amazing to know that all the prime numbers ≥ 5 can be traced from a pattern:Let’s try to understand the series: Series 1:5 + 6 = 1111 + 6 = 1717 + 6 = 2323 + 6 = 29...... Series 2:7 + 6 = 1313 + 6 = 19...... We see that adding 6 to 5 and again adding 6 to the obtained result, we are able to get another prime number. Similarly, adding 6 to 7 and again adding 6 to the obtained result. we can get another prime number. Hence, we can inference that we can obtain all the primes numbers doing same procedure.However, when we keep adding 6 to the previous result to obtain next prime number, we can notice some numbers that are not prime numbers.For example: 13 + 6 = 19 (Prime Number)19 + 6 = 25 (Composite Number; Say Pseudo Prime Number)29 + 6 = 35 (Composite Number; Say Pseudo Prime Number) We may say these types of Composite Numbers as Pseudo Prime Numbers (appear as prime number, but are not in reality).Now, if we are able to separate these Pseudo Prime Numbers from Real Prime Numbers, we can get the Real Prime Numbers. Using 4 important equations, we can exactly track all these Pseudo Prime Numbers and separate them from Real Prime Numbers. The Equation that will generate series is: y = 6 * x ± 1where x = 1, 2, 3, 4, 5, 6, 7, ...For example:6 * (1) – 1 = 5 (Prime Number)6 * (1) + 1 = 7 (Prime Number)6 * (2) – 1 = 11 (Prime Number)6 * (2) + 1 = 13 (Prime Number)6 * (3) – 1 = 17 (Prime Number)6 * (3) + 1 = 19 (Prime Number)6 * (4) – 1 = 23 (Prime Number)6 * (4) + 1 = 25 (Pseudo Prime Number) We can track all the Pseudo Prime Numbers using 4 equations: For the series produced from y = 6 * x – 1: y = (6 * d * x) + d where, x = {1, 2, 3, 4, 5, 6, ...}y = (6 * d * x) + (d * d) where, x = {0, 1, 2, 3, 4, 5, ...} and d = {5, (5+6), (5+6+6), (5+6+6+6), ..., (5+(n-1)*6)} y = (6 * d * x) + d where, x = {1, 2, 3, 4, 5, 6, ...} y = (6 * d * x) + (d * d) where, x = {0, 1, 2, 3, 4, 5, ...} and d = {5, (5+6), (5+6+6), (5+6+6+6), ..., (5+(n-1)*6)} For the series produced from y = 6 * x + 1: y = (6 * d * x) + (d * d) where, x = {0, 1, 2, 3, ...}y = (6 * d * x) + (d * d) – 2 * d where, x = {1, 2, 3, 4, ...}, d = {7, (7+6), (7+6+6), ..., (7 + (n – 1) * 6)} and n = {1, 2, 3, 4, 5, ...} y = (6 * d * x) + (d * d) where, x = {0, 1, 2, 3, ...} y = (6 * d * x) + (d * d) – 2 * d where, x = {1, 2, 3, 4, ...}, d = {7, (7+6), (7+6+6), ..., (7 + (n – 1) * 6)} and n = {1, 2, 3, 4, 5, ...} ExamplesTake d = 5 and x = 0 in equation 2,y = 25 (Pseudo Prime Number)Take d = 5 and x = 1 in equation 1,y = 35 (Pseudo Prime Number)Similarly, putting values in equation 3 and 4 we can track all Pseudo Prime Numbers. How to implement in programming? We assume two bool type arrays of same size.Say first one is array1, every element of which is initialized to 0.And, second one is array2, every element of which is initialized to 1.Now,In array1, we initialize the specified indexes with 1, the index values are calculated using the equation y = (6 * x) ± 1.And, in array2, we initialize the specified indexes with 0, the index values are calculated using 4 equations described above. Now, run a loop from 0 to N and print the index value of array,If array1[i] = 1 and array2[i] = 1 (i is a prime number). Below is the implementation of the approach: // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count of prime numbers <= nint countPrimesUpto(int n){ // To store the count of prime numbers int count = 0; // To mark all the prime numbers according // to the equation (y = 6*x -/+ 1) // where x = 1, 2, 3, 4, 5, 6, 7, ... bool arr1[n + 1]; // To mark all the Pseudo Prime Numbers // using the four equations // described in the approach bool arr2[n + 1]; // Starting with >= 5 int d = 5; // 2 and 3 are primes arr1[2] = arr2[2] = 1; arr1[3] = arr2[3] = 1; // Initialize every element of arr1 with 0 memset(arr1, 0, sizeof(arr1)); // Initialize every element of arr2 with 1 memset(arr2, 1, sizeof(arr2)); // Update arr1[] to mark all the primes while (d <= n) { // For 5, (5 + 6), (5 + 6 + 6), ... memset(arr1 + d, 1, (sizeof(arr1)) / (n + 1)); // For 7, (7 + 6), (7 + 6 + 6), ... memset(arr1 + (d + 2), 1, (sizeof(arr1)) / (n + 1)); // Increase d by 6 d = d + 6; } // Update arr2[] to mark all pseudo primes for (int i = 5; i * i <= n; i = i + 6) { int j = 0; // We will run while loop until we find all // pseudo prime numbers <= n while (1) { int flag = 0; // Equation 1 int temp1 = 6 * i * (j + 1) + i; // Equation 2 int temp2 = ((6 * i * j) + i * i); // Equation 3 int temp3 = ((6 * (i + 2) * j) + ((i + 2) * (i + 2))); // Equation 4 int temp4 = ((6 * (i + 2) * (j + 1)) + ((i + 2) * (i + 2)) - 2 * (i + 2)); // If obtained pseudo prime number <=n then its // corresponding index in arr2 is set to 0 // Result of equation 1 if (temp1 <= n) { arr2[temp1] = 0; } else { flag++; } // Result of equation 2 if (temp2 <= n) { arr2[temp2] = 0; } else { flag++; } // Result of equation 3 if (temp3 <= n) { arr2[temp3] = 0; } else { flag++; } // Result of equation 4 if (temp4 <= n) { arr2[temp4] = 0; } else { flag++; } if (flag == 4) { break; } j++; } } // Include 2 if (n >= 2) count++; // Include 3 if (n >= 3) count++; // If arr1[i] = 1 && arr2[i] = 1 then i is prime number // i.e. it is a prime which is not a pseudo prime for (int p = 5; p <= n; p = p + 6) { if (arr2[p] == 1 && arr1[p] == 1) count++; if (arr2[p + 2] == 1 && arr1[p + 2] == 1) count++; } return count;} // Driver codeint main(){ int n = 100; cout << countPrimesUpto(n);} 25 number-theory Prime Number Articles Mathematical number-theory Mathematical Prime Number Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Time Complexity and Space Complexity Time complexities of different data structures Difference between Min Heap and Max Heap SQL | Date functions Difference between Class and Object Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Program to find sum of elements in a given array
[ { "code": null, "e": 24107, "s": 24079, "text": "\n24 Apr, 2019" }, { "code": null, "e": 24249, "s": 24107, "text": "Apart from Sieve of Eratosthenes method to generate Prime numbers, we can implement a new Algorithm for generating prime numbers from 1 to N." }, { "code":...
How to Convert Binary to Hexadecimal?
Binary is the simplest kind of number system that uses only two digits of 0 and 1 (i.e. value of base 2). Since digital electronics have only these two states (either 0 or 1), so binary number is most preferred in modern computer engineer, networking and communication specialists, and other professionals. Whereas Hexadecimal number is one of the number systems which has value is 16 and it has only 16 symbols − 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and A, B, C, D, E, F. Where A, B, C, D, E and F are single bit representations of decimal value 10, 11, 12, 13, 14 and 15 respectively. Hexadecimal number system provides convenient way of converting large binary numbers into more compact and smaller groups. There are various ways to convert a binary number into hexadecimal number. You can convert using direct methods or indirect methods. First, you need to convert a binary into other base system (e.g., into decimal, or into octal). Then you need to convert it hexadecimal number. Since number numbers are type of positional number system. That means weight of the positions from right to left are as 160, 161, 162, 163and so on. for the integer part and weight of the positions from left to right are as 16-1, 16-2, 16-3and so on. for the fractional part. Example − Convert binary number 1101010 into hexadecimal number. First convert this into decimal number: = (1101010)2 = 1x26+1x25+0x24+1x23+0x22+1x21+0x20 = 64+32+0+8+0+2+0 = (106)10 Then, convert it into hexadecimal number = (106)10 = 6x161+10x160 = (6A)16 which is answer. However, there is also a direct method to convert a binary number into hexadecimal number − grouping which is explained as following below. Since, there are only 16 digits (from 0 to 7 and A to F) in hexadecimal number system, so we can represent any digit of hexadecimal number system using only 4 bit as following below. So, if you make each group of 4 bit of binary input number, then replace each group of binary number from its equivalent hexadecimal digits. That will be hexadecimal number of given number. Note that you can add any number of 0’s in leftmost bit (or in most significant bit) for integer part and add any number of 0’s in rightmost bit (or in least significant bit) for fraction part for completing the group of 4 bit, this does not change value of input binary number. So, these are following steps to convert a binary number into hexadecimal number. Take binary number Take binary number Divide the binary digits into groups of four (starting from right) for integer part and start from left for fraction part. Divide the binary digits into groups of four (starting from right) for integer part and start from left for fraction part. Convert each group of four binary digits to one hexadecimal digit. Convert each group of four binary digits to one hexadecimal digit. This is simple algorithm where you have to grouped binary number and replace their equivalent hexadecimal digit. Example-1 − Convert binary number 1010101101001 into hexadecimal number. Since there is no binary point here and no fractional part. So, Therefore, Binary to hexadecimal is, = (1010101101001)2 = (1 0101 0110 1001)2 = (0001 0101 0110 1001)2 = (1 5 6 9)16 = (1569)16 Example-2 − Convert binary number 001100101.110111 into hexadecimal number. Since there is binary point here and fractional part. So, Therefore, Binary to hexadecimal is, = (001100101.110111)2 = (0 0110 0101 . 1101 1100)2 = (0110 0101 . 1101 1100)2 = (6 5 . D C)16 = (65.DC)16 These are above simple conversions binary number to hexadecimal number.
[ { "code": null, "e": 1369, "s": 1062, "text": "Binary is the simplest kind of number system that uses only two digits of 0 and 1 (i.e. value of base 2). Since digital electronics have only these two states (either 0 or 1), so binary number is most preferred in modern computer engineer, networking an...
Create a dynamic table name from current year in MySQL like 2019
To create a table name like year (2019), use PREPARE statement. Let us first create a table − mysql> create table DemoTable1959 ( UserName varchar(20) ); Query OK, 0 rows affected (0.00 sec) Insert some records in the table using insert command − mysql> insert into DemoTable1959 values('Chris'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1959 values('David'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1959 values('Bob'); Query OK, 1 row affected (0.00 sec) Display all records from the table using select statement − mysql> select * from DemoTable1959; This will produce the following output − +----------+ | UserName | +----------+ | Chris | | David | | Bob | +----------+ 3 rows in set (0.00 sec) Here is the query to create a dynamic table name from current year mysql> set @dynamicQuery = CONCAT('create table `', date_format(curdate(),'%Y'), '` as select UserName from DemoTable1959'); Query OK, 0 rows affected (0.00 sec) mysql> prepare st from @dynamicQuery; Query OK, 0 rows affected (0.00 sec) Statement prepared mysql> execute st; Query OK, 3 rows affected (0.00 sec) Records: 3 Duplicates: 0 Warnings: 0 Display all records from the table using select statement. Here the current year is 2019 − mysql> select * from `2019`; This will produce the following output − +----------+ | UserName | +----------+ | Chris | | David | | Bob | +----------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1156, "s": 1062, "text": "To create a table name like year (2019), use PREPARE statement. Let us first create a table −" }, { "code": null, "e": 1262, "s": 1156, "text": "mysql> create table DemoTable1959\n (\n UserName varchar(20)\n );\nQuery OK, 0 row...
Why I Think Python is Perfect for Machine Learning and Artificial Intelligence | by Andrew Luashchuk | Towards Data Science
This article about why Python is good for ML and AI is originally posted on Django Stars blog. Artificial Intelligence (AI) and Machine Learning (ML) are the new black of the IT industry. While discussions over the safety of its development keep escalating, developers expand abilities and capacity of artificial intellect. Today Artificial Intelligence went far beyond science fiction idea. It became a necessity. Being widely used for processing and analyzing huge volumes of data, AI helps to handle the work that cannot be done manually anymore because of its significantly increased volumes and intensity. For instance, AI is applied in analytics to build predictions that can help people create strong strategies and look for more effective solutions. FinTech applies AI in investment platforms to do market research and predict where to invest funds for bigger profits. The traveling industry uses AI to deliver personalized suggestions or launch chatbots, plus enhance the overall user experience. These examples show that AI and ML are used process loads of data to offer better user experience, more personal and accurate one. Today, with the expansion of volumes and complexity of data, AI and ML are used for its processing and analysis. To be fair, the human brain can analyze large amounts of data, but this ability is limited by the volume of data it can absorb at any moment. Artificial intelligence is free from this limitation. More accurate predictions and insights delivered by AI improve business efficiency, lower production cost and increase productivity. No wonder that many industries apply AI and ML to improve performance and propel the product development. According to Deloitte research, AI-fueled companies are the latest trend in the technological transformation aimed at improvement of productivity. That is also proved by their prediction that within the next 24 months the number of companies that will use AI in their products and processes to achieve greater efficiency and strategic goals will likely increase. To put it short, AI helps doing better work with fewer efforts. Given the listed advantages of AI usage, more and more companies are eager to use it. However, AI is a two-way street — being used for optimization of the analytic process it is not the easiest technology to develop. Due to huge volumes of data to be analyzed, the AI product has to be able to handle the high-loaded process effectively and does not take too much time for that. To make it work properly, the appropriate language has to be chosen for its development. The one that will not be too complex in terms of syntax, will be able to handle sophisticated processes and is easy to support. As AI and ML are being applied across various channels and industries, big corporations invest in these fields, and the demand for experts in ML and AI grows accordingly. Jean Francois Puget, from IBM’s machine learning department, expressed his opinion that Python is the most popular language for AI and ML and based it on a trend search results on indeed.com. According to the graph from Francois Puget, Python is the major code language for AI and ML. We have conducted some research on Python’s strong sides and found out why you should opt in for Python when bringing your AI and ML projects to life. djangostars.com djangostars.com A great choice of libraries is one of the main reasons Python is the most popular programming language used for AI. A library is a module or a group of modules published by different sources like PyPi which include a pre-written piece of code that allows users to reach some functionality or perform different actions. Python libraries provide base level items so developers don’t have to code them from the very beginning every time. ML requires continuous data processing, and Python’s libraries let you access, handle and transform data. These are some of the most widespread libraries you can use for ML and AI: Scikit-learn for handling basic ML algorithms like clustering, linear and logistic regressions, regression, classification, and others. Pandas for high-level data structures and analysis. It allows merging and filtering of data, as well as gathering it from other external sources like Excel, for instance. Keras for deep learning. It allows fast calculations and prototyping, as it uses the GPU in addition to the CPU of the computer. TensorFlow for working with deep learning by setting up, training, and utilizing artificial neural networks with massive datasets. Matplotlib for creating 2D plots, histograms, charts, and other forms of visualization. NLTK for working with computational linguistics, natural language recognition, and processing. Scikit-image for image processing. PyBrain for neural networks, unsupervised and reinforcement learning. Caffe for deep learning that allows switching between the CPU and the GPU and processing 60+ mln images a day using a single NVIDIA K40 GPU. StatsModels for statistical algorithms and data exploration. In the PyPI repository, you can discover and compare more Python libraries. Working in the ML and AI industry means dealing with a bunch of data that you need to process in the most convenient and effective way. The low entry barrier allows more data scientists to quickly pick up Python and start using it for AI development without wasting too much effort into learning the language. Python programming language resembles the everyday English language, and that makes the process of learning easier. Its simple syntax allows you to comfortably work with complex systems, ensuring сlear relations between the system elements. For instance, this code is written in an attempt to find out if an input number is prime. Here’s the view of the code: test_number = 407 # our example is not a prime number# prime numbers are greater than 1if test_number > 1:# check for factorsnumber_list = range(2, test_number)for number in number_list:number_of_parts = test_number // numberprint(f"{test_number} is not a prime number")print(f"{number} times {number_of_parts} is {test_number}")breakelse:print(f"{test_number} is a prime number")else:print(f"{test_number} is not a prime number") And as you may see in the last row, the result of this code is that the test number is not a prime one. To put it bluntly, an English-speaking person could easily understand the meaning of the code, as it uses simple English words. In addition to this, there’s a lot of documentation available, and Python’s community is always there to help out and give advice. Python for machine learning is a great choice, as this language is very flexible: It offers an option to choose either to use OOPs or scripting. There’s also no need to recompile the source code, developers can implement any changes and quickly see the results. Programmers can combine Python and other languages to reach their goals. Moreover, flexibility allows developers to choose the programming styles which they are fully comfortable with or even combine these styles to solve different types of problems in the most efficient way. The imperative style consists of commands that describe how a computer should perform these commands. With this style, you define the sequence of computations which happen as a change of the program state. The functional style is also called declarative because it declares what operations should be performed. It doesn’t consider the program state, compared to the imperative style, it declares statements in the form of mathematical equations. The object-oriented style is based on two concepts: class and object, where similar objects form classes. This style is not fully supported by Python, as it can’t fully perform encapsulation, but developers can still use this style to a finite degree. The procedural style is the most common among beginners, as it proceeds tasks in a step-by-step format. It’s often used for sequencing, iteration, modularization, and selection. The flexibility factor decreases the possibility of errors, as programmers have a chance to take the situation under control and work in a comfortable environment. Python is not only comfortable to use and easy to learn but also very versatile. What we mean is that Python for machine learning development can run on any platform including Windows, MacOS, Linux, Unix, and twenty-one others. To transfer the process from one platform to another, developers need to implement several small-scale changes and modify some lines of code to create an executable form of code for the chosen platform. Developers can use packages like PyInstaller to prepare their code for running on different platforms. Again, this saves time and money for tests on various platforms and makes the overall process more simple and convenient. Python is very easy to read so every Python developer can understand the code of their peers and change, copy or share it. There’s no confusion, errors or conflicting paradigms, and this leads to more a efficient exchange of algorithms, ideas, and tools between AI and ML professionals. There are also tools like IPython available, which is an interactive shell that provides extra features like testing, debugging, tab-completion, and others, and facilitates the work process. We’ve already mentioned that Python offers a variety of libraries, and some of them are great visualization tools. However, for AI developers, it’s important to highlight that in artificial intelligence, deep learning, and machine learning, it’s vital to be able to represent data in a human-readable format. Libraries like Matplotlib allow data scientists to build charts, histograms, and plots for better data comprehension, effective presentation, and visualization. Different application programming interfaces also simplify the visualization process and make it easier to create clear reports. It’s always very helpful when there’s strong community support built around the programming language. Python is an open-source language which means that there’s a bunch of resources open for programmers starting from beginners and ending with pros. A lot of Python documentation is available online as well as in Python communities and forums, where programmers and machine learning developers discuss errors, solve problems, and help each other out. Python programming language is absolutely free as is the variety of useful libraries and tools. As a result of the advantages discussed above, Python is becoming more and more popular among data scientists. According to StackOverflow, the popularity of Python is predicted to grow until 2020, at least. This means it’s easier to search for developers and replace team players if required. Also, the cost of their work maybe not as high as when using a less popular programming language. Python offers many features that are helpful for AI and ML in particular, and that makes it the best language for these purposes. No wonder that various industries use Python for predictions and other machine learning tasks. Let’s take a closer look at some examples in: Travel; Fintech; Transportation; Healthcare. For example, the travel industry giant Skyscanner used a Python unsupervised ML algorithm to predict the behavior of new airplane routes. They compared thousands of origins and destinations, evaluating each one of them with 30 different criteria to define the demand of passengers. Their results are displayed on a dashboard, where you can choose any origin city to see the groups of destinations numbered from 0 to 9 and their characteristics. Such an example of AI implementation in the traveling industry is extremely helpful for suggesting destinations to the users, assisting the creation of marketing budgets, as well as setting an initial price for new routes. AI used in financial services helps to solve problems connected with risk management, fraud prevention, personalized banking, automation, and other tools which help to provide a high-quality financial service to the users. It’s predicted that AI in fintech could reduce operating costs by 22% by 2030, resulting in an impressive $1 trillion. Some successful examples of online banking software built on Python are Venmo, Affirm or Robinhood. These services not only allow users to make and control their payments and purchases but they also create a social network inside the software, so people can stay connected. When it comes to cryptocurrency, Python is used to build solutions like Anaconda to effectively analyze the market, make predictions and visualize data. Uber developed an ML platform Michelangelo PyML using Python. They use it for online and offline predictions solving day-to-day tasks. The Michelangelo PyML is the extension of the initial Michelangelo product which was scalable but not flexible enough. Now, users can validate models with PyML and then replicate them in Michelangelo for full efficiency and scalability. AI is reshaping the healthcare industry by helping to predict and scan diseases, detect injuries, and help people maintain good health even on a day-to-day basis with easy-to-use mobile applications. There are many great AI based projects in the industry. For example, Fathom is a natural language processing system which is made to analyze electronic health records, and their mission is “to automate medical coding.” Their leaders have come from companies like Google, Amazon, Facebook or the universities of Stanford and Harvard. AiCure is another startup focused on making sure that patients take the right medications at the right time. For that purpose, they use technologies like face recognition, pill recognition, and action recognition. The application is also able to analyze the patient’s state and understand if the treatment is working. They use IMA which is an interactive medical assistant that can gather clinically significant data which then can be analyzed by the software. Growing popularity leads to the growing demand for Python programmers inside the data science community, and it’s a wise choice to choose a language that’s in high demand, as, in the future, it will allow even more functionality. The open-source nature of Python allows any AI development company to share their achievements with the community. If you’ve made up your mind and decided to learn Python, or want to use this language for your AI projects, here’s a list of useful opensource projects for you to begin with: OpenCog FoundationOpenCog is “building better minds together” by putting effort into creating the Artificial General Intelligence (AGI) with human capacities. It was founded in 2011, and, now, it’s used at the SingularityNET project, as well as at the Hanson Robotics delivering intelligence to the Sofia and other robots. Institute for Artificial IntelligenceThe Institute of Artificial Intelligence is a part of the Faculty of Computer Science at the University of Bremen. It conducts research on AI and holds different workshops and events which help move the AI technologies forward, involving more young people into the sphere and educating them, while also supporting existing AI-powered projects and companies. ZulipIt’s the “world’s most productive team chat” that allows the processing of thousands of real-time messages a day. Fortune 500 companies and other large and open source projects use Zulip, which offers clear organization, asynchronous communication, and other great advantages that are useful for teams. MagentaMagenta is a Python library and a research project, the biggest goal of which is to make music and art using AI. It works on image, songs, drawings generation and lets artists explore new ways of creating. MailPileMailPile is an innovative email client that focuses on safe and private communication. It’s a project that tries to answer a question: “How can I protect my privacy online?” It’s fast, has no ads and comes with a powerful search function as well as privacy and encryption. AI and ML are fast-growing and universal technologies that let scientists resolve real-life dilemmas and come up with clever solutions. The reason why many of them consider Python the perfect programming language for AI is due to the following advantages:
[ { "code": null, "e": 267, "s": 172, "text": "This article about why Python is good for ML and AI is originally posted on Django Stars blog." }, { "code": null, "e": 783, "s": 267, "text": "Artificial Intelligence (AI) and Machine Learning (ML) are the new black of the IT industry...
NLP Text Preprocessing: Steps, tools, and examples | by Viet Hoang Tran Duong | Towards Data Science
Text data is everywhere, from your daily Facebook or Twitter newsfeed to textbooks and customer feedback. Data is the new oil, and text is an oil well that we need to drill deeper. Before we can actually use the oil, we must preprocess it so it fits our machines. Same for data, we must clean and preprocess the data to fit our purposes. This post will include a few simple approaches to cleaning and preprocessing text data for text analytics tasks. We will model the approach on the Covid-19 Twitter dataset. There are 3 major components to this approach: First, we clean and filter all non-English tweets/texts as we want consistency in the data.Second, we create a simplified version for our complex text data.Finally, we vectorize the text and save their embedding for future analysis. If you want to check out the code: feel free to check out the code for part 1, part 2, and part 3 embedded here. You can also check the whole project blogpost and codes here. First, to simplify the text, we want to standardize our text into only English characters. This function will remove all non-English characters. def clean_non_english(txt): txt = re.sub(r'\W+', ' ', txt) txt = txt.lower() txt = txt.replace("[^a-zA-Z]", " ") word_tokens = word_tokenize(txt) filtered_word = [w for w in word_tokens if all(ord(c) < 128 for c in w)] filtered_word = [w + " " for w in filtered_word] return "".join(filtered_word) We can even do better by removing the stopwords. Stopwords are common words that appear in English sentences without contributing much to the meaning. We will use the nltk package to filter the stopwords. As our main task is visualizing the common theme of tweets using word cloud, this step is necessary to avoid common words like “the,” “a,” etc. However, if your tasks require full sentence structure, like next word prediction or grammar check, you can skip this step. import nltknltk.download('punkt') # one time executionnltk.download('stopwords')from nltk.corpus import stopwordsstop_words = set(stopwords.words('english'))def clean_text(english_txt): try: word_tokens = word_tokenize(english_txt) filtered_word = [w for w in word_tokens if not w in stop_words] filtered_word = [w + " " for w in filtered_word] return "".join(filtered_word) except: return np.nan For tweets, there is a special feature we need to consider before cleaning: mentions. Your data might have special features like this (or not), and this is case-by-case and not a universal requirement. Hence, know your data well before blindly clean and preprocess! def get_mention(txt): mention = [] for i in txt.split(" "): if len(i) > 0 and i[0] == "@": mention.append(i) return "".join([mention[i] + ", " if i != len(mention) - 1 else mention[i] for i in range(len(mention))] Before, we clean the non-English characters. Now, we remove the non-English texts (semantically). Langdetect is a python package that allows for checking the language of the text. It is a direct port of Google’s language detection library from Java to Python. from langdetect import detectdef detect_lang(txt): try: return detect(txt) except: return np.nan We then filter out all columns then is not “en” language. All of the codes for part 1 can be found here. For numerical data, good processing methods are scaling, standardizing, and normalizing. This resource is beneficial in understanding and applies these methods to your data. Within this post's scope, I will not discuss further as other resources have done a great job doing so. For categorical data, there are numerous approaches. The two nominal approaches are Label Encoder (assigning a distinct number for each label) and One hot encoding (represent with a vector of 0s and 1). More details on the approach to these categorical values can be found here. This resource is very substantial with more types of encoding than these two I mentioned. This post will introduce some ways to reduce the complexity of data, especially location data. In my dataset, there is a column for location, with the address of the author. However, I cannot perform much analysis with these raw data as they are too messy and complex (having city, county, state, country). Hence, we can standardize the text and reduce it to the “country” level (or state if you are interested). A package to deal with location data is geopy. It can identify the correct address and reformat these locations to standard form. Then, you can choose to keep whichever information you need. For me, the state, country is decent enough. from geopy.geocoders import Nominatimgeolocator = Nominatim(user_agent="twitter")def get_nation(txt): try: location = geolocator.geocode(txt) x = location.address.split(",")[-1] return x except: return np.nan Python is awesome with so many packages. I believe you can always find something for your specific need, as I do with my messy location data. Good luck with simplifying these messy data. The code for part 2 can be found here. Text vectorization is converting text into vectors of values to represent their meanings. Earlier days, we have one hot encoding method with a vector with a size of our vocabulary, and value 1 wherever the text appear and 0s elsewhere. Nowadays, we have more advanced methods like spacy, GloVe, or even bert embedding. For the scope of this project, I will introduce you to GloVe in python and Jupiter notebooks. First, we download the embeddings. You can download it manually here or do it directly in your notebooks. !wget http://nlp.stanford.edu/data/glove.6B.zip!unzip glove*.zip Then, we create a function to vectorize each data point. The sentence is the mean representation of each word. For empty sentences, we default it to a zeros vector. def vectorize(value, word_embeddings, dim = 100): sentences = value.to_list() sentence_vectors = [] for i in sentences: if len(i) != 0: v = sum([word_embeddings.get(w, np.zeros((dim,))) for w in i.split()])/(len(i.split())+0.001) else: v = np.zeros((dim,)) sentence_vectors.append(v) sentence_vectors = np.array(sentence_vectors) return sentence_vectors Finally, we vectorize the whole dataset and save the vectorized numpy array as a file, so we don’t have to go through this process again every time running the code. The vectorized version will be saved as a numpy array in the form of .npy files. Numpy package is convenient in storing and dealing with massive array data. As my personal standard practice, I try to save all data as separate files after each part to evaluate the data and alter my code more flexibly. def vectorize_data(data = data, value = 'english_text', dim = 100): # Extract word vectors word_embeddings = {} f = open('glove.6B.{}d.txt'.format(str(dim)), encoding='utf-8') for line in f: values = line.split() word = values[0] coefs = np.asarray(values[1:], dtype='float32') word_embeddings[word] = coefs f.close() text_vec = vectorize(data[value], word_embeddings, dim) np.save("vectorized_{}.npy".format(str(dim)), text_vec) print("Done. Data:", text_vec.shape) return True The code for part 3 is here. Data preprocessing, specifically with text, can be a very troublesome process. A big part of your machine learning engineer workflow will be for these cleaning and formatting data (lucky you if your data is already perfectly clean & kudos to all data engineers for making that happen). All the code in this post is very abstract and can be applied to many data projects (you only need to change to the name of columns, and all should work properly). In the notebook, I also added exception functions to handle failure cases, ensuring that your code will not crash midway. I hope it helps you with your projects, as much as it helps me in mine. You can check out the project blog post here. Good luck with your projects, and let me know if anything needs to change and improve! Thank you, and see you in the next posts! References:Hale, J. (2020, February 21). Scale, Standardize, or Normalize with Scikit-Learn. Retrieved from https://towardsdatascience.com/scale-standardize-or-normalize-with-scikit-learn-6ccc7d176a02KazAnova. (2017, September 13). Sentiment140 dataset with 1.6 million tweets. Retrieved from https://www.kaggle.com/kazanova/sentiment140Preda, G. (2020, August 30). COVID19 Tweets. Retrieved from https://www.kaggle.com/gpreda/covid19-tweetsRoy, B. (2020, April 25). All about Categorical Variable Encoding. Retrieved from https://towardsdatascience.com/all-about-categorical-variable-encoding-305f3361fd02
[ { "code": null, "e": 623, "s": 172, "text": "Text data is everywhere, from your daily Facebook or Twitter newsfeed to textbooks and customer feedback. Data is the new oil, and text is an oil well that we need to drill deeper. Before we can actually use the oil, we must preprocess it so it fits our m...
Python code to move spaces to front of string in single traversal - GeeksforGeeks
23 Nov, 2020 Given a string that has set of words and spaces, write a program to move all spaces to front of string, by traversing the string only once. Examples: Input : str = "geeks for geeks" Output : ste = " geeksforgeeks" Input : str = "move these spaces to beginning" Output : str = " movethesespacestobeginning" There were four space characters in input, all of them should be shifted in front. This problem has existing solution, please refer Move spaces to front of string in single traversal link.We will solve this problem quickly in Python using List Comprehension.Approach: Traverse input string and create a string without any space character using list comprehension.Now to know how many space characters were there in original string just take a difference of length of original string and new string.Now create another string and append space characters at the beginning. Traverse input string and create a string without any space character using list comprehension. Now to know how many space characters were there in original string just take a difference of length of original string and new string. Now create another string and append space characters at the beginning. # Function to move spaces to front of string # in single traversal in Python def moveSpaces(input): # Traverse string to create string without spaces noSpaces = [ch for ch in input if ch!=' '] # calculate number of spaces space= len(input) - len(noSpaces) # create result string with spaces result = ' '*space # concatenate spaces with string having no spaces result = '"'+result + ''.join(noSpaces)+'"' print (result) # Driver program if __name__ == "__main__": input = 'geeks for geeks' moveSpaces(input) Output: " geeksforgeeks" Python string-programs python-string Python Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Reverse a string in Java Write a program to reverse an array or string Longest Common Subsequence | DP-4 Write a program to print all permutations of a given string C++ Data Types
[ { "code": null, "e": 23926, "s": 23898, "text": "\n23 Nov, 2020" }, { "code": null, "e": 24066, "s": 23926, "text": "Given a string that has set of words and spaces, write a program to move all spaces to front of string, by traversing the string only once." }, { "code": n...
Python Type Object
Everything in Python is an object including classes. All classes are instances of a class called "type".The type object is also an instance of type class. You can inspect the inheritance hierarchy of class by examining the __bases__ attribute of a class object. type() method returns class type of the argument(object) passed as parameter.If single argument type(obj) is passed to type method, it returns the type of given object. If three arguments type(name, bases, dict) is passed, it returns a new type object. Let’s look at the classes for the most used data types. In the below program we initialize some variables and then use the type() to ascertain their class. Live Demo # Some variables a = 5 b = 5.2 c = 'hello' A = [1,4,7] B = {'k1':'Sun','K2':"Mon",'K3':'Tue'} C = ('Sky','Blue','Vast') print(type(a)) print(type(b)) print(type(c)) print(type(A)) print(type(B)) print(type(C)) Running the above code gives us the following result − <class 'int'> <class 'float'> <class 'str'> <class 'list'> <class 'dict'> <class 'tuple'> If we go deeper to look at the type of classes above, we will see that they are all belong to class named ‘type’. Live Demo print(type(int)) print(type(dict)) print(type(list)) print(type(type)) Running the above code gives us the following result − <class 'type'> <class 'type'> <class 'type'> <class 'type'> We can also use a similar approach as above to create new objects. Here we pass three parameters to create the new type object. Live Demo Object1 = type('A', (object,), dict(a='Hello', b=5)) print(type(Object1)) print(vars(Object1)) class NewCalss: a = 'Good day!' b = 7 Object2 = type('B', (NewCalss,), dict(a='Hello', b=5)) print(type(Object2)) print(vars(Object2)) Running the above code gives us the following result − <class 'type'> {'a': 'Hello', 'b': 5, '__module__': '__main__', '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None} <class 'type'> {'a': 'Hello', 'b': 5, '__module__': '__main__', '__doc__': None}
[ { "code": null, "e": 1577, "s": 1062, "text": "Everything in Python is an object including classes. All classes are instances of a class called \"type\".The type object is also an instance of type class. You can inspect the inheritance hierarchy of class by examining the __bases__ attribute of a cla...
Difference between EnumMap and HashMap in Java
EnumMap is introduced in JDK5. It is designed to use Enum as key in the Map. It is also the implementation of the Map interface. All of the key in the EnumMap should be of the same enum type. In EnumMap , key can’t be null and any it will throw NullPointerException. As per java docs − EnumMap internally using as arrays, this representation is extremely compact and efficient. HashMap is also the implementation of the Map interface. It is used to store the data in Key and Value form. It can contain one null key and multiple null values . In HashMap, keys can’t be a primitive type. Java HashMap implementation provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets. 1 Basic A specialized Map implementation for use with enum type keys HashMap is also the implementation of the Map interface. 2 Null Key It can’t have null key. It can have one null key and multiple null values 3 Performance All operations execute in constant time therefore it is faster than HashMap It is slower than HashMap 4. Internal Implementation It uses Array internally It uses Hashtable internally 5. Ordering EnumMap stores keys in the natural order of their keys HashMap is not ordered import java.util.ArrayList; import java.util.EnumMap; import java.util.List; import java.util.Map; public class EnumMapExample { public enum LaptopEnum { HCL, DELL, IBM }; public static void main(String[] args) { // create enum map EnumMap map = new EnumMap(LaptopEnum.class); map.put(LaptopEnum.HCL, "100"); map.put(LaptopEnum.DELL, "200"); map.put(LaptopEnum.IBM, "300"); // print the map for (Map.Entry m : map.entrySet()) { System.out.println(m.getKey() + " " + m.getValue()); } } } import java.util.ArrayList; import java.util.EnumMap; import java.util.HashMap; import java.util.List; import java.util.Map; public class HashMapExample { public static void main(String[] args) { // create Hash map Map map = new HashMap(); map.put("HCL", "100"); map.put("DELL", "200"); map.put("IBM", "300"); // print the map for (Map.Entry m : map.entrySet()) { System.out.println(m.getKey() + " " + m.getValue()); } } }
[ { "code": null, "e": 1329, "s": 1062, "text": "EnumMap is introduced in JDK5. It is designed to use Enum as key in the Map. It is also the implementation of the Map interface. All of the key in the EnumMap should be of the same enum type. In EnumMap , key can’t be null and any it will throw NullPoin...
Java - max() Method
This method gives the maximum of the two arguments. The argument can be int, float, long, double. This method has the following variants − double max(double arg1, double arg2) float max(float arg1, float arg2) int max(int arg1, int arg2) long max(long arg1, long arg2) Here is the detail of parameters − This method accepts any primitive data type as a parameter. This method returns the maximum of the two arguments. public class Test { public static void main(String args[]) { System.out.println(Math.max(12.123, 12.456)); System.out.println(Math.max(23.12, 23.0)); } } This will produce the following result − 12.456 23.12 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2475, "s": 2377, "text": "This method gives the maximum of the two arguments. The argument can be int, float, long, double." }, { "code": null, "e": 2516, "s": 2475, "text": "This method has the following variants −" }, { "code": null, "e": 2647, ...
Python program to check credit card number is valid or not
Suppose we have a credit card number. We have to check whether the card number is valid or not. The card numbers have certain properties − It will start with 4, 5 and 6 It will start with 4, 5 and 6 It will be 16 digits’ long It will be 16 digits’ long Numbers must contain only digits Numbers must contain only digits It may have digits in four groups separated by '-' It may have digits in four groups separated by '-' It must not use any other separator like space or underscore It must not use any other separator like space or underscore It must not have 4 or more consecutive same digits It must not have 4 or more consecutive same digits So, if the input is like s = "5423-2578-8632-6589", then the output will be True To solve this, we will follow these steps − if number of '-' in s is greater than 0, thena := a list of parts separated by "-"p:= 1if size of a is not same as 4, thenp:= nulla:= blank listfor each b in a, doif size of b is not same as 4, thenp:= nullcome out from loop a := a list of parts separated by "-" p:= 1 if size of a is not same as 4, thenp:= nulla:= blank list p:= null a:= blank list for each b in a, doif size of b is not same as 4, thenp:= nullcome out from loop if size of b is not same as 4, thenp:= nullcome out from loop p:= null come out from loop otherwise,p := search a substring which is starting with 4 or 5 or 6 and remaining are numbers of 15 digits longs := remove "-" from sq := search substring where 4 or more consecutive characters are sameif p is not null and q is null, thenreturn Trueotherwise,return False p := search a substring which is starting with 4 or 5 or 6 and remaining are numbers of 15 digits long s := remove "-" from s q := search substring where 4 or more consecutive characters are same if p is not null and q is null, thenreturn True return True otherwise,return False return False Let us see the following implementation to get better understanding import re def solve(s): if s.count("-")>0: a = s.split("-") p=1 if len(a)!=4: p=None a=[] for b in a: if len(b)!=4: p=None break else: p = re.search("[456][0-9]{15}",s) s = s.replace("-","") q = re.search(".*([0-9])\\1{3}.*",s) if p!=None and q==None: return True else: return False s = "5423-2578-8632-6589" print(solve(s)) "5423-2578-8632-6589" False
[ { "code": null, "e": 1201, "s": 1062, "text": "Suppose we have a credit card number. We have to check whether the card number is valid or not. The card numbers have certain properties −" }, { "code": null, "e": 1231, "s": 1201, "text": "It will start with 4, 5 and 6" }, { ...
How to use HTML5 GeoLocation API with Google Maps?
HTML5 Geolocation API lets you share your location with your favorite websites. A Javascript can capture your latitude and longitude and can be sent to backend web server and do fancy location-aware things like finding local businesses or showing your location on a map. The geolocation coordinates specify the geographic location of the device. We will be using getCurrentPostion() method to get the current location. To get current location using HTML5 Geolocation with Google Maps, you need to set an API key for Google Static Maps API. Go to https://console.developers.google.com and get a free API key for Google Map. Add this key to the code to work Geolocation with it. You can try to run the following code to show current location using HTML5 Geolocation with Google Maps − <!DOCTYPE HTML> <html> <head> <script type = "text/javascript"> function showLocation(position) { var latitude = position.coords.latitude; var longitude = position.coords.longitude; var latlongvalue = position.coords.latitude + "," + position.coords.longitude; var img_url = "https://maps.googleapis.com/maps/api/staticmap?center=" +latlongvalue+"&zoom=14&size = 400x300&key = AIzaSyAa8HeLH2lQMbPeOiMlM9D1VxZ7pbGQq8o"; document.getElementById("mapholder").innerHTML = "<img src ='"+img_url+"'>"; } function errorHandler(err) { if(err.code == 1) { alert("Error: Access is denied!"); }else if( err.code == 2) { alert("Error: Position is unavailable!"); } } function getLocation(){ if(navigator.geolocation){ // timeout at 60000 milliseconds (60 seconds) var options = {timeout:60000}; navigator.geolocation.getCurrentPosition (showLocation, errorHandler, options); }else{ alert("Sorry, browser does not support geolocation!"); } } </script> </head> <body> <div id="mapholder"></div> <form> <input type="button" onclick="getLocation();" value="Your Location"/> </form> </body> </html>
[ { "code": null, "e": 1408, "s": 1062, "text": "HTML5 Geolocation API lets you share your location with your favorite websites. A Javascript can capture your latitude and longitude and can be sent to backend web server and do fancy location-aware things like finding local businesses or showing your l...
Bajaj Finserv Interview Experience for Data Engineer - GeeksforGeeks
26 Aug, 2021 Round 1 (API Round): The first round was the challenge round where we were asked to upload our name, email, college, and other details by using the open API given by the company. A maximum of 10 chances was given to get a success message. Round 2 (Coding round): After two hours we got the shortlisted students who had successfully submitted their details. This was a coding test conducted on the HackerEarth platform. I had applied for a data engineering role. The test had 10 multiple choice questions and 1 coding question. Given a number x raise it to the power of 2, if the resultant number consists of two or more digits find the sum of digits until the sum becomes a single digit.My approach is given below. Python3 def fun(x): y = pow(2, x) if (y == 0): return 0 if (y % 9 == 0): return 9 else: return y % 9 Round 3 (Technical interview): The third round was a technical round with the panel. The process was very smooth and the interviewer asked me about my projects mentioned in the resume and questions on SQL and python. Tell me about yourself.Explain the project you mentioned in your resume.https://www.geeksforgeeks.org/egg-dropping-puzzle-dp-11/Pseudocode of https://www.geeksforgeeks.org/c-program-for-tower-of-hanoi/How to reverse a string in python?How many joins do you know in SQL? Explain them. (I explained all the joins through the Venn diagram)https://www.geeksforgeeks.org/convert-number-to-words/Do you have any questions for me? Tell me about yourself. Explain the project you mentioned in your resume. https://www.geeksforgeeks.org/egg-dropping-puzzle-dp-11/ Pseudocode of https://www.geeksforgeeks.org/c-program-for-tower-of-hanoi/ How to reverse a string in python? How many joins do you know in SQL? Explain them. (I explained all the joins through the Venn diagram) https://www.geeksforgeeks.org/convert-number-to-words/ Do you have any questions for me? The total interview lasted for around 50 mins and the questions were of medium difficulty. Tips: Be confident while answering and choose the apt projects for the role you are applying for. Try to practice unique coding problems with difficulty level medium or higher. If you need time to think for an answer ask the interviewer for permission for few seconds and start thinking. Round 4 (HR Round): It was a telephonic interview. The interviewer asked me how was the previous round and asked if I had any questions. He explained the work environment and asked if I am willing to relocate, to which I agreed. I was selected as an intern for the role of Data engineer. Bajaj Finserv Marketing Internship Interview Experiences Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Microsoft Interview Experience for Internship (Via Engage) Persistent Systems Interview Experience (Martian Program) Zoho Interview Experience (Off-Campus ) 2022 Zoho Corporation (Internship cum Offer Experience ) Difference Between ON Page and OFF Page SEO Commonly Asked Java Programming Interview Questions | Set 2 Amazon Interview Questions Amazon Interview Experience for SDE-1 (On-Campus) Microsoft Interview Experience for Internship (Via Engage) Amazon Interview Experience for SDE-1
[ { "code": null, "e": 25078, "s": 25050, "text": "\n26 Aug, 2021" }, { "code": null, "e": 25099, "s": 25078, "text": "Round 1 (API Round):" }, { "code": null, "e": 25318, "s": 25099, "text": "The first round was the challenge round where we were asked to upload...
Program to find GCD or HCF of two numbers in C++
In this tutorial, we will be discussing a program to find GCD and HCF of two numbers. For this we will be provided with two numbers. Our task is to find the GCD or HCF (highest common factor) for those given two numbers. Live Demo #include <iostream> using namespace std; int gcd(int a, int b){ if (a == 0) return b; if (b == 0) return a; if (a == b) return a; if (a > b) return gcd(a-b, b); return gcd(a, b-a); } int main(){ int a = 98, b = 56; cout<<"GCD of "<<a<<" and "<<b<<" is "<<gcd(a, b); return 0; } GCD of 98 and 56 is 14
[ { "code": null, "e": 1148, "s": 1062, "text": "In this tutorial, we will be discussing a program to find GCD and HCF of two numbers." }, { "code": null, "e": 1283, "s": 1148, "text": "For this we will be provided with two numbers. Our task is to find the GCD or HCF (highest commo...
Fibonacci Coding
18 Oct, 2021 Fibonacci coding encodes an integer into binary number using Fibonacci Representation of the number. The idea is based on Zeckendorf’s Theorem which states that every positive integer can be written uniquely as a sum of distinct non-neighboring Fibonacci numbers (0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ........). The Fibonacci code word for a particular integer is exactly the integer’s Zeckendorf representation with the order of its digits reversed and an additional “1” appended to the end. The extra 1 is appended to indicate the end of code (Note that the code never contains two consecutive 1s as per Zeckendorf’s Theorem. The representation uses Fibonacci numbers starting from 1 (2’nd Fibonacci Number). So the Fibonacci Numbers used are 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 141, ....... Given a number n, print its Fibonacci code. Examples: Input: n = 1 Output: 11 1 is first Fibonacci number in this representation and an extra 1 is appended at the end. Input: n = 11 Output: 001011 11 is sum of 8 and 3. The last 1 represents extra 1 that is always added. A 1 before it represents 8. The third 1 (from beginning) represents 3. We strongly recommend you to minimize your browser and try this yourself first.The following algorithm takes an integer as input and generates a string that stores Fibonacci Encoding.Find the largest Fibonacci number f less than or equal to n. Say it is the i’th number in the Fibonacci series. The length of codeword for n will be i+3 characters (One for extra 1 appended at the end, One because i is an index, and one for ‘\0’). Assuming that the Fibonacci series is stored: Let f be the largest Fibonacci less than or equal to n, prepend ‘1’ in the binary string. This indicates usage of f in representation for n. Subtract f from n: n = n – f Else if f is greater than n, prepend ‘0’ to the binary string. Move to the Fibonacci number just smaller than f . Repeat until zero remainder (n = 0) Append an additional ‘1’ to the binary string. We obtain an encoding such that two consecutive 1s indicate the end of a number (and the start of the next). Below is the implementation of above algorithm. C++ C Java Python3 C# Javascript /* C++ program for Fibonacci Encoding of a positive integer n */#include <bits/stdc++.h>using namespace std; // To limit on the largest Fibonacci number to be used#define N 30 /* Array to store fibonacci numbers. fib[i] is going to store (i+2)'th Fibonacci number*/int fib[N]; // Stores values in fib and returns index of the largest// fibonacci number smaller than n.int largestFiboLessOrEqual(int n){ fib[0] = 1; // Fib[0] stores 2nd Fibonacci No. fib[1] = 2; // Fib[1] stores 3rd Fibonacci No. // Keep Generating remaining numbers while previously // generated number is smaller int i; for (i=2; fib[i-1]<=n; i++) fib[i] = fib[i-1] + fib[i-2]; // Return index of the largest fibonacci number // smaller than or equal to n. Note that the above // loop stopped when fib[i-1] became larger. return (i-2);} /* Returns pointer to the char string which corresponds to code for n */char* fibonacciEncoding(int n){ int index = largestFiboLessOrEqual(n); //allocate memory for codeword char *codeword = (char*)malloc(sizeof(char)*(index+3)); // index of the largest Fibonacci f <= n int i = index; while (n) { // Mark usage of Fibonacci f (1 bit) codeword[i] = '1'; // Subtract f from n n = n - fib[i]; // Move to Fibonacci just smaller than f i = i - 1; // Mark all Fibonacci > n as not used (0 bit), // progress backwards while (i>=0 && fib[i]>n) { codeword[i] = '0'; i = i - 1; } } //additional '1' bit codeword[index+1] = '1'; codeword[index+2] = '\0'; //return pointer to codeword return codeword;} /* driver function */int main(){ int n = 143; cout <<"Fibonacci code word for " <<n <<" is " << fibonacciEncoding(n); return 0;}// This code is contributed by shivanisinghss2110 /* C program for Fibonacci Encoding of a positive integer n */ #include<stdio.h>#include<stdlib.h> // To limit on the largest Fibonacci number to be used#define N 30 /* Array to store fibonacci numbers. fib[i] is going to store (i+2)'th Fibonacci number*/int fib[N]; // Stores values in fib and returns index of the largest// fibonacci number smaller than n.int largestFiboLessOrEqual(int n){ fib[0] = 1; // Fib[0] stores 2nd Fibonacci No. fib[1] = 2; // Fib[1] stores 3rd Fibonacci No. // Keep Generating remaining numbers while previously // generated number is smaller int i; for (i=2; fib[i-1]<=n; i++) fib[i] = fib[i-1] + fib[i-2]; // Return index of the largest fibonacci number // smaller than or equal to n. Note that the above // loop stopped when fib[i-1] became larger. return (i-2);} /* Returns pointer to the char string which corresponds to code for n */char* fibonacciEncoding(int n){ int index = largestFiboLessOrEqual(n); //allocate memory for codeword char *codeword = (char*)malloc(sizeof(char)*(index+3)); // index of the largest Fibonacci f <= n int i = index; while (n) { // Mark usage of Fibonacci f (1 bit) codeword[i] = '1'; // Subtract f from n n = n - fib[i]; // Move to Fibonacci just smaller than f i = i - 1; // Mark all Fibonacci > n as not used (0 bit), // progress backwards while (i>=0 && fib[i]>n) { codeword[i] = '0'; i = i - 1; } } //additional '1' bit codeword[index+1] = '1'; codeword[index+2] = '\0'; //return pointer to codeword return codeword;} /* driver function */int main(){ int n = 143; printf("Fibonacci code word for %d is %s\n", n, fibonacciEncoding(n)); return 0;} // Java program for Fibonacci Encoding// of a positive integer nimport java.io.*; class GFG{ // To limit on the largest Fibonacci// number to be usedpublic static int N = 30; // Array to store fibonacci numbers.// fib[i] is going to store (i+2)'th// Fibonacci numberpublic static int[] fib = new int[N]; // Stores values in fib and returns index of// the largest fibonacci number smaller than n. public static int largestFiboLessOrEqual(int n){ // Fib[0] stores 2nd Fibonacci No. fib[0] = 1; // Fib[1] stores 3rd Fibonacci No. fib[1] = 2; // Keep Generating remaining numbers while // previously generated number is smaller int i; for(i = 2; fib[i - 1] <= n; i++) { fib[i] = fib[i - 1] + fib[i - 2]; } // Return index of the largest fibonacci // number smaller than or equal to n. // Note that the above loop stopped when // fib[i-1] became larger. return(i - 2);} // Returns pointer to the char string which// corresponds to code for npublic static String fibonacciEncoding(int n){ int index = largestFiboLessOrEqual(n); // Allocate memory for codeword char[] codeword = new char[index + 3]; // Index of the largest Fibonacci f <= n int i = index; while (n > 0) { // Mark usage of Fibonacci f(1 bit) codeword[i] = '1'; // Subtract f from n n = n - fib[i]; // Move to Fibonacci just smaller than f i = i - 1; // Mark all Fibonacci > n as not used // (0 bit), progress backwards while (i >= 0 && fib[i] > n) { codeword[i] = '0'; i = i - 1; } } // Additional '1' bit codeword[index + 1] = '1'; codeword[index + 2] = '\0'; String string = new String(codeword); // Return pointer to codeword return string;} // Driver codepublic static void main(String[] args){ int n = 143; System.out.println("Fibonacci code word for " + n + " is " + fibonacciEncoding(n));}} // This code is contributed by avanitrachhadiya2155 # Python3 program for Fibonacci Encoding# of a positive integer n # To limit on the largest# Fibonacci number to be usedN = 30 # Array to store fibonacci numbers.# fib[i] is going to store# (i+2)'th Fibonacci numberfib = [0 for i in range(N)] # Stores values in fib and returns index of# the largest fibonacci number smaller than n.def largestFiboLessOrEqual(n): fib[0] = 1 # Fib[0] stores 2nd Fibonacci No. fib[1] = 2 # Fib[1] stores 3rd Fibonacci No. # Keep Generating remaining numbers while # previously generated number is smaller i = 2 while fib[i - 1] <= n: fib[i] = fib[i - 1] + fib[i - 2] i += 1 # Return index of the largest fibonacci number # smaller than or equal to n. Note that the above # loop stopped when fib[i-1] became larger. return (i - 2) # Returns pointer to the char string which# corresponds to code for ndef fibonacciEncoding(n): index = largestFiboLessOrEqual(n) # allocate memory for codeword codeword = ['a' for i in range(index + 2)] # index of the largest Fibonacci f <= n i = index while (n): # Mark usage of Fibonacci f (1 bit) codeword[i] = '1' # Subtract f from n n = n - fib[i] # Move to Fibonacci just smaller than f i = i - 1 # Mark all Fibonacci > n as not used (0 bit), # progress backwards while (i >= 0 and fib[i] > n): codeword[i] = '0' i = i - 1 # additional '1' bit codeword[index + 1] = '1' # return pointer to codeword return "".join(codeword) # Driver Coden = 143print("Fibonacci code word for", n, "is", fibonacciEncoding(n)) # This code is contributed by Mohit Kumar // C# program for Fibonacci Encoding// of a positive integer nusing System; class GFG{ // To limit on the largest Fibonacci// number to be usedpublic static int N = 30; // Array to store fibonacci numbers.// fib[i] is going to store (i+2)'th// Fibonacci numberpublic static int[] fib = new int[N]; // Stores values in fib and returns index of// the largest fibonacci number smaller than n. public static int largestFiboLessOrEqual(int n){ // Fib[0] stores 2nd Fibonacci No. fib[0] = 1; // Fib[1] stores 3rd Fibonacci No. fib[1] = 2; // Keep Generating remaining numbers while // previously generated number is smaller int i; for(i = 2; fib[i - 1] <= n; i++) { fib[i] = fib[i - 1] + fib[i - 2]; } // Return index of the largest fibonacci // number smaller than or equal to n. // Note that the above loop stopped when // fib[i-1] became larger. return(i - 2);} // Returns pointer to the char string which// corresponds to code for npublic static String fibonacciEncoding(int n){ int index = largestFiboLessOrEqual(n); // Allocate memory for codeword char[] codeword = new char[index + 3]; // Index of the largest Fibonacci f <= n int i = index; while (n > 0) { // Mark usage of Fibonacci f(1 bit) codeword[i] = '1'; // Subtract f from n n = n - fib[i]; // Move to Fibonacci just smaller than f i = i - 1; // Mark all Fibonacci > n as not used // (0 bit), progress backwards while (i >= 0 && fib[i] > n) { codeword[i] = '0'; i = i - 1; } } // Additional '1' bit codeword[index + 1] = '1'; codeword[index + 2] = '\0'; string str = new string(codeword); // Return pointer to codeword return str;} // Driver codestatic public void Main(){ int n = 143; Console.WriteLine("Fibonacci code word for " + n + " is " + fibonacciEncoding(n));}} // This code is contributed by rag2127 <script>// Javascript program for Fibonacci Encoding// of a positive integer n // To limit on the largest Fibonacci// number to be used let N = 30; // Array to store fibonacci numbers.// fib[i] is going to store (i+2)'th// Fibonacci number let fib = new Array(N); // Stores values in fib and returns index of// the largest fibonacci number smaller than n. function largestFiboLessOrEqual(n) { // Fib[0] stores 2nd Fibonacci No. fib[0] = 1; // Fib[1] stores 3rd Fibonacci No. fib[1] = 2; // Keep Generating remaining numbers while // previously generated number is smaller let i; for(i = 2; fib[i - 1] <= n; i++) { fib[i] = fib[i - 1] + fib[i - 2]; } // Return index of the largest fibonacci // number smaller than or equal to n. // Note that the above loop stopped when // fib[i-1] became larger. return(i - 2); } // Returns pointer to the char string which// corresponds to code for n function fibonacciEncoding(n) { let index = largestFiboLessOrEqual(n); // Allocate memory for codeword let codeword = new Array(index + 3); // Index of the largest Fibonacci f <= n let i = index; while (n > 0) { // Mark usage of Fibonacci f(1 bit) codeword[i] = '1'; // Subtract f from n n = n - fib[i]; // Move to Fibonacci just smaller than f i = i - 1; // Mark all Fibonacci > n as not used // (0 bit), progress backwards while (i >= 0 && fib[i] > n) { codeword[i] = '0'; i = i - 1; } } // Additional '1' bit codeword[index + 1] = '1'; codeword[index + 2] = '\0'; let string =(codeword).join(""); // Return pointer to codeword return string; } // Driver code let n = 143; document.write("Fibonacci code word for " + n + " is " + fibonacciEncoding(n)); // This code is contributed by unknown2108</script> Output: Fibonacci code word for 143 is 01010101011 Illustration Field of application:Data Processing & Compression – representing the data (which can be text, image, video...) in such a way that the space needed to store or transmit data is less than the size of input data. Statistical methods use variable-length codes, with the shorter codes assigned to symbols or group of symbols that have a higher probability of occurrence. If the codes are to be used over a noisy communication channel, their resilience to bit insertions, deletions and to bit-flips is of high importance.Read more about the application here. This article is contributed by Yash Varyani. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above mohit kumar 29 avanitrachhadiya2155 rag2127 unknown2108 shivanisinghss2110 rochelledeulley Fibonacci Mathematical Mathematical Fibonacci Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n18 Oct, 2021" }, { "code": null, "e": 376, "s": 54, "text": "Fibonacci coding encodes an integer into binary number using Fibonacci Representation of the number. The idea is based on Zeckendorf’s Theorem which states that every positiv...
p5.js camera() Method
04 Mar, 2021 The camera() function in p5.js is used to set the virtual camera’s position on a 3D sketch. This can be used to simulate the position of the camera as it would move around the scene making it possible to view objects from various angles. The parameters of this function include setting the position for the camera, the center of the camera, and the vector which is pointing upside. Syntax: camera([x], [y], [z], [centerX], [centerY], [centerZ], [upX], [upY], [upZ]) Parameters: This function accept nine parameters as mentioned above and described below: x: This is a number that denotes the camera position on x-axis. y: This is a number that denotes the camera position on y-axis. z: This is a number that denotes the camera position on z-axis. centerX: This is a number that denotes the x coordinate of the center of the sketch. centerY: This is a number that denotes the y coordinate of the center of the sketch. centerZ: This is a number that denotes the z coordinate of the center of the sketch. upX: This is a number that denotes the x component of direction ‘up’ from camera. upY: This is a number that denotes the y component of direction ‘up’ from camera. upZ: This is a number that denotes the z component of direction ‘up’ from camera. Below examples illustrates the camera() function in p5.js: Example 1: Set the view of the camera on the x-axis. Javascript function setup() { createCanvas(600, 400, WEBGL);} function draw() { background(175); // Map the coordinates of the mouse // to the variable let cX = map(mouseX, 0, width, -200, 200); // Set the camera to the given coordinates camera(cX, 0, (height/2) / tan(PI/6), cX, 0, 0, 0, 1, 0); ambientLight(255); rotateZ(frameCount * 0.01); rotateX(frameCount * 0.03); rotateY(frameCount * 0.06); noStroke(); normalMaterial(); box(100, 100, 100);} Output: Example 2: Set the view of the camera in a random direction every frame. Javascript function setup() { frameRate(5); createCanvas(600, 400, WEBGL);} function draw() { background(175); let cX = random(-10,10); let cY = random(-10,10); let cZ = random(-10,10); camera(cX, cY, cZ+(height/2) / tan(PI/6), cX, 0, 0, 0, 1, 0); ambientLight(255); rotateX(frameCount * 0.1); rotateY(frameCount * 0.1); noStroke(); normalMaterial(); box(100, 100, 100);} Output: Reference:https://p5js.org/reference/#/p5.Camera JavaScript-p5.js Picked 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 Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request JavaScript | Promises 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": "\n04 Mar, 2021" }, { "code": null, "e": 292, "s": 54, "text": "The camera() function in p5.js is used to set the virtual camera’s position on a 3D sketch. This can be used to simulate the position of the camera as it would move around th...
Perform DDoS attack using Torshammer
11 Jul, 2022 There are very few methods available which claim to be successful for DDoS or any type of network loss. Let’s see one of such method to perform DDoS attack. This attack is really powerful and requires the only skill that you should know how to operate commands on Kali Linux Operating System. First of all, If you want to check that any website has its TCP port 80 opened or not, you can go for nmap, and all the tutorial given for nmap . This tool we are using is Torshammer. It is written in Python and can give damage to unprotected web servers in an instance that’s why it is a slow post tool. Main feature of this tool is it works on the 7th layer of HTTP(Hyper Text Transfer Protocol). Install Torshammer tool: Go to GitHub dotfighter/torshammer by this link or, just open a terminal and write this command- git clone https://github.com/dotfighter/torshammer.git Now, Come to the directory wherever that script is cloned. You will find something like this: You can see there are five Python scripts, two for the terminal, two for sockets and remaining one is main torshammer script. Now Right click on the blank space and select “Open In Terminal”, it will directly open a terminal with that right path. Otherwise, you can type “cd torshammer” in the newly opened terminal. Write this command- python torshammer.py It will finally open the main interface for the tool. Let’s understand these first: Any Python tool in Kali Linux should start with “python” suffix and follow by toolname(.)py also. Like that any PHP tool should start with “php” and follow by toolname(.)php. -t is for the target, some domain or ip-address.-p is for port Defaults to 80.-r is for the threads, how many threads we want to run for this attack.-T stands for tor customized attacks. Let’s do the main thing: python torshammer.py <i>any hostname/IP</i> -t -p 80 -r 5000 For example- python torshammer.py -t xyz.com -p 80 -r 5000 As you hit enter after writing those commands, something will appear like this: So, you have successfully run an attack. Please note that, if that website is opening normally then they have settled up their website on some Content Delivery Network(CDN) e.g. Akamai, Cloudflare which is designed to work against any kind of DoS or DDoS attacks. For checking that attack is successful or not, you can go to isitdownrightnow to verify. Disclaimer: This article is just for knowledge purpose. Please don’t use this article to perform any malicious activity. Remember, before targeting or attacking anyone’s IP/hostname/Servers one must have the necessary permissions. user_zmkb Technical Scripter 2018 Linux-Unix Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n11 Jul, 2022" }, { "code": null, "e": 345, "s": 52, "text": "There are very few methods available which claim to be successful for DDoS or any type of network loss. Let’s see one of such method to perform DDoS attack. This attack is re...
Built-in Objects in Python-builtins
26 Mar, 2020 This Python module provides direct access to all ‘built-in’ identifiers of Python. For example, builtins.open is the full name for the built-in function open(). This module is not normally accessed explicitly by most applications, but can be useful in modules that provide objects with the same name as a built-in value, but in which the built-in of that name is also needed. For example, in a module that wants to implement an open() function that wraps the built-in open(), this module can be used directly: open(path, 'r') But in cases where there is a function with the same name as the builtin functions these needs to be called explicitly: def open(path): f = builtins.open(path, 'r') Here the first open function is defined by the programmer and the second one is being imported from the builtins module. Example: # without explicitly calling # the builtins moduleprint(round(3.14)) # explicitly calling the # builtins moduleimport builtins a = builtins.round(3.14)print(a) Output: 3 3 One more interesting thing to keep in mind is that the compiler gives higher priority to user-defined versions of the predefined functions contained by the builtins module. So, if a program consists of a call to both types of programs, the user-defined program will be called. To call the predefined version builtins keyword should be used. Example: import builtins def pow(): print("inside user-defined function pow() \ to calculate 2**3 ") val = 2 for i in range(1, 3, 1): val=val*2 return val def main(): print("calling for pre-defined version of pow() \ from builtins module to calculate 2**3 ") print(builtins.pow(2, 3)) a = pow() print(a) # Driver Codemain() Output: calling for pre-defined version of pow() from builtins module to calculate 2**38inside user-defined function pow() to calculate 2**38 This module is automatically loaded every time the interpreter starts, this is the reason why it is generally never called explicitly. The following are defined within builtins: The Object Class– base class for all python objects All Built-in Data-Type Class– all data types like numbers, string, list etc. Built-in Exception Classes– like BaseException class, etc. Built-in Functions– functions like open(), abs(), all(), etc. Built-in Constants– constants like False, True, etc. TRUTH VALUE TESTING- statements and conditions for checking the validity of the code. BOOLEAN OPERATIONS- and, or, not. COMPARISONS- =, ==, !=, is and is not. NUMERIC TYPES- int, float, complex and bitwise operations like and, or, exclusive or, shifts and inverse. ITERATOR TYPES- operations related to iteration of a container. SEQUENCE TYPES- list, tuple, range and operations on these. TEXT SEQUENCE TYPE- str and methods related with string mutation and display. BINARY SEQUENCE TYPE- bytes, bytearray and memoryview. SET TYPES- set and frozenset. MAPPING TYPES- dict. CONTEXT MANAGER TYPES- runtime context related matter. OTHERS – module, instances, null object, Example: simple program to depict the application of builtin types a =[1, 2, 3, 4] for i in a: if i == 3: print("found") else: print("not found") Output: not found not found found not found BUILT-IN FUNCTIONS python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n26 Mar, 2020" }, { "code": null, "e": 429, "s": 53, "text": "This Python module provides direct access to all ‘built-in’ identifiers of Python. For example, builtins.open is the full name for the built-in function open(). This module i...
Python | Smile detection using OpenCV
26 May, 2021 Emotion detectors are used in many industries, one being the media industry where it is important for the companies to determine the public reaction to their products. In this article, we are going to build a smile detector using OpenCV which takes in live feed from webcam. The smile/happiness detector that we are going to implement would be a raw one, there exist many better ways to implement it.Step # 1: First of all, we need to import the OpenCV library. import cv2 Step #2: Include the desired haar-cascades.Haar-cascades are classifiers that are used to detect features (of face in this case) by superimposing predefined patterns over face segments and are used as XML files. In our model, we shall use face, eye and smile haar-cascades, which after downloading need to be placed in the working directory.All the required Haar-cascades can be found here. Python3 face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades +'haarcascade_frontalface_default.xml')eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades +'haarcascade_eye.xml')smile_cascade = cv2.CascadeClassifier(cv2.data.haarcascades +'haarcascade_smile.xml') Step #3: In this step, we are going to build main function which would be performing the smile detection. The live feed coming from the webcam/video device is processed frame by frame. We process the gray scale image, as haar-cascades work better on them.To detect the face, we use: The live feed coming from the webcam/video device is processed frame by frame. We process the gray scale image, as haar-cascades work better on them. To detect the face, we use: Python3 faces = face_cascade.detectMultiScale(gray, 1.3, 5) where 1.3 is the scaling factor, and 5 is the number of nearest neighbors. We can adjust these factors as per our convenience/results to improve our detector.Now for each subsequent face detected, we need to check for smiles. where 1.3 is the scaling factor, and 5 is the number of nearest neighbors. We can adjust these factors as per our convenience/results to improve our detector. Now for each subsequent face detected, we need to check for smiles. Python3 def detect(gray, frame): faces = face_cascade.detectMultiScale(gray, 1.3, 5) for (x, y, w, h) in faces: cv2.rectangle(frame, (x, y), ((x + w), (y + h)), (255, 0, 0), 2) roi_gray = gray[y:y + h, x:x + w] roi_color = frame[y:y + h, x:x + w] smiles = smile_cascade.detectMultiScale(roi_gray, 1.8, 20) for (sx, sy, sw, sh) in smiles: cv2.rectangle(roi_color, (sx, sy), ((sx + sw), (sy + sh)), (0, 0, 255), 2) return frame Explanations – The face data is stored as tuples of coordinates. Here, x and y define the coordinate of the upper-left corner of the face frame, w and h define the width and height of the frame. The cv2.rectangle function takes in the arguments frame, upper-left coordinates of the face, lower right coordinates, the RGB code for the rectangle (that would contain within it the detected face) and the thickness of the rectangle. The roi_gray defines the region of interest of the face and roi_color does the same for the original frame. In line 7, we apply smile detection using the cascade. Step #4: We define main function in this step. After execution, the function can be terminated by pressing the “q” key. Python3 video_capture = cv2.VideoCapture(0)while video_capture.isOpened(): # Captures video_capture frame by frame _, frame = video_capture.read() # To capture image in monochrome gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # calls the detect() function canvas = detect(gray, frame) # Displays the result on camera feed cv2.imshow('Video', canvas) # The control breaks once q key is pressed if cv2.waitKey(1) & 0xff == ord('q'): break # Release the capture once all the processing is done.video_capture.release() cv2.destroyAllWindows() Output: samagarwal082 Image-Processing OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n26 May, 2021" }, { "code": null, "e": 518, "s": 54, "text": "Emotion detectors are used in many industries, one being the media industry where it is important for the companies to determine the public reaction to their products. In thi...
Python | Make pair from two list such that elements are not same in pairs
28 Feb, 2019 Given two lists, the task is to create pairs of elements (pairs can be repeated) from two list such that elements are not same in pairs. Examples: Input : list1 = [100, 20, 30, 400] list2 = [400, 2, 30] Output: [[100, 400], [100, 2], [100, 30], [20, 400], [20, 2], [20, 30], [30, 400], [30, 2], [400, 2], [400, 30]] Input: list1 = [10,20,30,40] list2 = [60, 10, 20] Output: [[10, 60], [10, 20], [20, 60], [20, 10], [30, 60], [30, 10], [30, 20], [40, 60], [40, 10], [40, 20]] Method #1: Using list comprehension # Python code to create pair of element # from two list such that element # in pairs are not equal. # List initializationlist1 =[10, 20, 30, 40]list2 =[40, 50, 60] # using list comprehensionoutput = [[a, b] for a in list1 for b in list2 if a != b] # printing outputprint(output) [[10, 40], [10, 50], [10, 60], [20, 40], [20, 50], [20, 60], [30, 40], [30, 50], [30, 60], [40, 50], [40, 60]] Method #2: Using itertools and iteration # Python code to create pair of element # from two list such that element # in pairs are not equal. # Importingimport itertools # List initializationlist1 =[11, 22, 33, 44]list2 =[22, 44, 66] # using itertoolstemp = list(itertools.product(list1, list1)) # output list initializationout = [] # iterationfor elem in temp: if elem[0]!= elem[1]: out.append(elem) # printing outputprint(out) [(11, 22), (11, 33), (11, 44), (22, 11), (22, 33), (22, 44), (33, 11), (33, 22), (33, 44), (44, 11), (44, 22), (44, 33)] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Feb, 2019" }, { "code": null, "e": 191, "s": 54, "text": "Given two lists, the task is to create pairs of elements (pairs can be repeated) from two list such that elements are not same in pairs." }, { "code": null, "e": ...
How to create Price Range Selector in ReactJS?
22 Jan, 2021 Price Range Selector means the user is able to select the range between the given values. Material UI for React has this component available for us and it is very easy to integrate. Price Ranges Selectors is a very popular feature for filter the results on the basis of the range selected by the user. Creating React Application And Installing Module: Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the material-ui modules using the following command: npm install @material-ui/core Project Structure: It will look like the following. Project Structure App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. Javascript import React from 'react';import Typography from '@material-ui/core/Typography';import Slider from '@material-ui/core/Slider'; const App = () => { // Our States const [value, setValue] = React.useState([2,10]); // Changing State when volume increases/decreases const rangeSelector = (event, newValue) => { setValue(newValue); console.log(newValue) }; return ( <div style={{ margin: 'auto', display: 'block', width: 'fit-content' }}> <h3>How to create Price Range Selector in ReactJS?</h3> <Typography id="range-slider" gutterBottom> Select Price Range: </Typography> <Slider value={value} onChange={rangeSelector} valueLabelDisplay="auto" /> Your range of Price is between {value[0]} /- and {value[1]} /- </div> );} export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Supported Browser: Chrome Explorer Microsoft Edge JavaScript ReactJS 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 Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request JavaScript | Promises How to fetch data from an API in ReactJS ? Axios in React: A Guide for Beginners How to redirect to another page in ReactJS ? ReactJS Functional Components
[ { "code": null, "e": 53, "s": 25, "text": "\n22 Jan, 2021" }, { "code": null, "e": 355, "s": 53, "text": "Price Range Selector means the user is able to select the range between the given values. Material UI for React has this component available for us and it is very easy to int...
numpy.log() in Python
04 Dec, 2020 The numpy.log() is a mathematical function that helps user to calculate Natural logarithm of x where x belongs to all the input array elements.Natural logarithm log is the inverse of the exp(), so that log(exp(x)) = x. The natural logarithm is log in base e. Syntax :numpy.log(x[, out] = ufunc ‘log1p’)Parameters : array : [array_like] Input array or object.out : [ndarray, optional] Output array with same dimensions as Input array, placed with result. Return :An array with Natural logarithmic value of x; where x belongs to all elements of input array. Code #1 : Working # Python program explaining# log() functionimport numpy as np in_array = [1, 3, 5, 2**8]print ("Input array : ", in_array) out_array = np.log(in_array)print ("Output array : ", out_array) print("\nnp.log(4**4) : ", np.log(4**4))print("np.log(2**8) : ", np.log(2**8)) Output : Input array : [1, 3, 5, 256] Output array : [ 0. 1.09861229 1.60943791 5.54517744] np.log(4**4) : 5.54517744448 np.log(2**8) : 5.54517744448 Code #2 : Graphical representation # Python program showing# Graphical representation # of log() functionimport numpy as npimport matplotlib.pyplot as plt in_array = [1, 1.2, 1.4, 1.6, 1.8, 2]out_array = np.log(in_array) print ("out_array : ", out_array) plt.plot(in_array, in_array, color = 'blue', marker = "*") # red for numpy.log()plt.plot(out_array, in_array, color = 'red', marker = "o") plt.title("numpy.log()")plt.xlabel("out_array")plt.ylabel("in_array")plt.show() Output : out_array : [ 0. 0.18232156 0.33647224 0.47000363 0.58778666 0.69314718] References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.log.html#numpy.log. Python numpy-Mathematical Function Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n04 Dec, 2020" }, { "code": null, "e": 311, "s": 52, "text": "The numpy.log() is a mathematical function that helps user to calculate Natural logarithm of x where x belongs to all the input array elements.Natural logarithm log is the in...
Hyperlink Vs Hypertext
19 Oct, 2021 Both the term are twins to each other and perform with each other basically complete each other. But few times we get confused about which one is the which one really. To clear that confusion, we will discuss the specificness of both in detail with the proper example and explain the differences as well. Both the terms are used in the WWW(World Wide Web) Hyperlink: The hyperlink contains the URL of the webpages. In a general way, a hyperlink is referenced when a hypertext navigated. These hyperlinks are hidden under the text, image, graphics, audio, video, and gets highlighted once we hover the mouse over it. To activate the hyperlink, we click the hypermedia, which ends up within the opening of the new document. It establishes the connection between the knowledge units, usually known as the target document and therefore the alternate name for the hyperlink is anchor or node.Hypertext: Ted Nelson introduced the term Hypertext in 1956. Hypertext is a text which contains the visible text to redirect the targeted page(page URL contained by Hyperlink). It was invented to establish cross-reference in the computer world, similar to that is made in books like an index. However, the usual pattern of reading a book is sequential. But, this hypertext introduces the idea of cross-referencing the data. This cross-referencing is sort of complicated within the world, but it makes the work easier. If we are surfing on the web, at the time of reading a piece of writing we suddenly encounter a term, which we wanted to understand at that moment. If that term may be a hypertext, we will directly attend that page where we will find the information about that term. So, this eliminates the additional time of searching that term.Example: This example combines both the term. html <!DOCTYPE html><html> <head> <title> Hyperlink vs Hypertext </title> <style> h1 { color: green; } .container { width: 800px; height: 150px; border: 2px solid black; } .img { width: 200px; height: 100px; border: 2px solid black; margin: 20px 40px; float: left; } img { width:200px; height: 100px; } .text { width: 200px; height: 100px; border: 2px solid black; margin: 20px; } .graphics { width: 200px; height: 100px; border: 2px solid black; margin: 20px 40px; float: right; } svg { width: 200; height: 100; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <b> A Computer Science Portal for Geeks </b> <br><br> <div class="container"> <div class="img"> <a href="https://ide.geeksforgeeks.org/"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200121141240/ide.png"> </a> </div> <div class="graphics"> <a href="https://ide.geeksforgeeks.org/"> <svg> <circle cx="100" cy="50" r="50" stroke="black" stroke-width="2" fill="green" /> </svg> </a> </div> <div class="text"> <a href="https://ide.geeksforgeeks.org/"> <h3>GeeksforGeeks IDE</h3> </a> </div> </div> </center></body> </html> Output: Difference between Hyperlink and Hypertext: sumitgumber28 HTML-Misc Technical Scripter 2019 HTML Technical Scripter Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) Design a Tribute Page using HTML & CSS Build a Survey Form using HTML and CSS Angular File Upload Form validation using jQuery Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array
[ { "code": null, "e": 54, "s": 26, "text": "\n19 Oct, 2021" }, { "code": null, "e": 411, "s": 54, "text": "Both the term are twins to each other and perform with each other basically complete each other. But few times we get confused about which one is the which one really. To cle...
Kotlin Standard Input/Output
04 Aug, 2021 In this article, we will discuss here how to take input and how to display the output on the screen in Kotlin. Kotlin standard I/O operations are performed to flow sequence of bytes or byte streams from input device such as Keyboard to the main memory of the system and from main memory to output device such as Monitor. In Java, we use System.out.println(message) to print output on the screen but, in Kotlin println(message) is used to print. Kotlin standard output is the basic operation performed to flow byte streams from main memory to the output device. You can output any of the data types integer, float and any patterns or strings on the screen of the system. You can use any one of the following function to display output on the screen. print() function println() function Here is the Kotlin program for standard output. Kotlin fun main(args: Array<String>){ print("Hello, Geeks! ") println("This is Kotlin tutorial.")} Output: Hello, Geeks! This is Kotlin tutorial. Difference between println() and print() – print() function prints the message inside the double quotes. println() function prints the message inside the double quotes and moves to the beginning of the next line. kotlin program to print string: Kotlin fun main(args : Array<String>){ println("GeeksforGeeks") println("A Computer Science portal for Geeks") print("GeeksforGeeks - ") print("A Computer Science portal for Geeks")} Output: GeeksforGeeks A Computer Science portal for Geeks GeeksforGeeks - A Computer Science portal for Geeks Actually print() internally calls System.out.print() and println() internally calls System.out.println(). If your are using Intellij IDEA, then click next to println and Go To > Declaration by clicking the right button. (Shortcut: in Window Press Ctrl + B and in Mac press Cmd + B). It will open Console.kt file and you can see that internally it calls System.out.println(). Print literals and Variables – Kotlin fun sum(a: Int,b: Int) : Int{ return a + b}fun main(args: Array<String>){ var a = 10 var b = 20 var c = 30L var marks = 40.4 println("Sum of {$a} and {$b} is : ${sum(a,b)}") println("Long value is: $c") println("marks") println("$marks")} Output: Sum of {10} and {20} is : 30 Long value is: 30 marks 40.4 Kotlin standard input is the basic operation performed to flow byte streams from input device such as Keyboard to the main memory of the system. You can take input from user with the help of the following function: readline() method Scanner class Take input from user using readline() method – Kotlin fun main(args : Array<String>) { print("Enter text: ") var input = readLine() print("You entered: $input")} Output: Enter text: Hello, Geeks! You are learning how to take input using readline() You entered: Hello, Geeks! You are learning how to take input using readline() Take input from user using Scanner class – If you are taking input from user other than String data type, you need to use Scanner class. To use Scanner first of all you have to import the Scanner on the top of the program. import java.util.Scanner; Create an object for the scanner class and use it to take input from the user. In the below program we will show you how to take input of integer, float and boolean data type. Kotlin import java.util.Scanner fun main(args: Array<String>) { // create an object for scanner class val number1 = Scanner(System.`in`) print("Enter an integer: ") // nextInt() method is used to take // next integer value and store in enteredNumber1 variable var enteredNumber1:Int = number1.nextInt() println("You entered: $enteredNumber1") val number2 = Scanner(System.`in`) print("Enter a float value: ") // nextFloat() method is used to take next // Float value and store in enteredNumber2 variable var enteredNumber2:Float = number2.nextFloat() println("You entered: $enteredNumber2") val booleanValue = Scanner(System.`in`) print("Enter a boolean: ") // nextBoolean() method is used to take // next boolean value and store in enteredBoolean variable var enteredBoolean:Boolean = booleanValue.nextBoolean() println("You entered: $enteredBoolean")} Output: Enter an integer: 123 You entered: 123 Enter a float value: 40.45 You entered: 40.45 Enter a boolean: true You entered: true Take input from user without using the Scanner class – Here, we will use readline() to take input from the user and no need to import Scanner class. readline()!! take the input as a string and followed by (!!) to ensure that the input value is not null. Kotlin fun main(args: Array<String>) { print("Enter an Integer value: ") val string1 = readLine()!! // .toInt() function converts the string into Integer var integerValue: Int = string1.toInt() println("You entered: $integerValue") print("Enter a double value: ") val string2= readLine()!! // .toDouble() function converts the string into Double var doubleValue: Double = string2.toDouble() println("You entered: $doubleValue")} Output: Enter an Integer value: 123 You entered: 123 Enter a double value: 22.22222 You entered: 22.22222 surindertarika1234 Kotlin Basics Kotlin Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Kotlin constructor Retrofit with Kotlin Coroutine in Android Android Menus Kotlin Higher-Order Functions Suspend Function In Kotlin Coroutines Spinner in Kotlin MVP (Model View Presenter) Architecture Pattern in Android with Example Kotlin extension function How to Get Current Location in Android? Launch vs Async in Kotlin Coroutines
[ { "code": null, "e": 52, "s": 24, "text": "\n04 Aug, 2021" }, { "code": null, "e": 374, "s": 52, "text": "In this article, we will discuss here how to take input and how to display the output on the screen in Kotlin. Kotlin standard I/O operations are performed to flow sequence o...
Python | Delete elements with frequency atmost K
15 Apr, 2019 There are many methods that can be employed to perform the deletion in the list. Be it remove function, pop function and many other functions. But most of the times, we usually don’t deal with the simple deletion, but with certain constraints. This article discusses certain ways in which we can delete only those elements which occurs less than K times. Method #1 : Using list comprehension + count()The idea applied here is to construct a new list using list comprehension and insert only those elements which occur more than K times. The count operation is done with the help of count function. # Python3 code to demonstrate# remove elements less than and equal K # using list comprehension + count() # initializing listtest_list = [1, 4, 3, 2, 3, 3, 2, 2, 2, 1] # printing original listprint("The original list : " + str(test_list)) # initializing KK = 2 # using list comprehension + count()# remove elements less than K res = [ i for i in test_list if test_list.count(i) > K] # print resultprint("The list removing elements less than and equal K : " + str(res)) The original list : [1, 4, 3, 2, 3, 3, 2, 2, 2, 1] The list removing elements less than and equal K : [3, 2, 3, 3, 2, 2, 2] Method #2 : Using Counter() + list comprehensionThis problem can be efficiently solved using the Counter function that precomputes the count of each elements in list so that the decision to keep or reject a particular element takes lesser time. # Python3 code to demonstrate# remove elements less than and equal K # using Counter() + list comprehensionfrom collections import Counter # initializing listtest_list = [1, 4, 3, 2, 3, 3, 2, 2, 2, 1] # printing original listprint("The original list : " + str(test_list)) # initializing KK = 2 # using Counter() + list comprehension# remove elements less than K freq = Counter(test_list)res = [ele for ele in test_list if freq[ele] > K] # print resultprint("The list removing elements less than and equal K : " + str(res)) The original list : [1, 4, 3, 2, 3, 3, 2, 2, 2, 1] The list removing elements less than and equal K : [3, 2, 3, 3, 2, 2, 2] Marketing Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Apr, 2019" }, { "code": null, "e": 383, "s": 28, "text": "There are many methods that can be employed to perform the deletion in the list. Be it remove function, pop function and many other functions. But most of the times, we usuall...
Snake Water Gun game using Python and C
12 Jan, 2022 Snake Water Gun is one of the famous two-player game played by many people. It is a hand game in which the player randomly chooses any of the three forms i.e. snake, water, and gun. Here, we are going to implement this game using python. This python project is to build a game for a single player that plays with the computer Following are the rules of the game: Snake vs. Water: Snake drinks the water hence wins.Water vs. Gun: The gun will drown in water, hence a point for waterGun vs. Snake: Gun will kill the snake and win. In situations where both players choose the same object, the result will be a draw. We will use random.choice() method and nested if-else statements to select a random item from a list. Below is the implementation: Python3 C # Import random moduleimport randomprint('Snake - Water - Gun') # Input no. of roundsn = int(input('Enter number of rounds: ')) # List containing Snake(s), Water(w), Gun(g)options = ['s', 'w', 'g'] # Round numbersrounds = 1 # Count of computer winscomp_win = 0 # Count of player winsuser_win = 0 # There will be n rounds of gamewhile rounds <= n: # Display round print(f"Round :{rounds}\nSnake - 's'\nWater - 'w'\nGun - 'g'") # Exception handling try: player = input("Choose your option: ") except EOFError as e: print(e) # Control of bad inputs if player != 's' and player != 'w' and player != 'g': print("Invalid input, try again\n") continue # random.choice() will randomly choose # item from list- options computer = random.choice(options) # Conditions based on the game rule if computer == 's': if player == 'w': comp_win += 1 elif player == 'g': user_win += 1 elif computer == 'w': if player == 'g': comp_win += 1 elif player == 's': user_win += 1 elif computer == 'g': if player == 's': comp_win += 1 elif player == 'w': user_win += 1 # Announce winner of every round if user_win > comp_win: print(f"You Won round {rounds}\n") elif comp_win > user_win: print(f"Computer Won round {rounds}\n") else: print("Draw!!\n") rounds += 1 # Final winner based on the number of wonsif user_win > comp_win: print("Congratulations!! You Won")elif comp_win > user_win: print("You lose!!")else: print("Match Draw!!") #include <stdio.h>#include <stdlib.h>#include <time.h> int snakeWaterGun(char you, char comp){ // returns 1 if you win, -1 if you lose and 0 if draw // Condition for draw // Cases // covered: | snake snake | // gun gun | water water if (you == comp) { return 0; } // Non-draw conditions // Cases covered:// snake gun // | gun snake | snake water // | water sanke | gun water | water gun if (you == 's' && comp == 'g') { return -1; } else if (you == 'g' && comp == 's') { return 1; } if (you == 's' && comp == 'w') { return 1; } else if (you == 'w' && comp == 's') { return -1; } if (you == 'g' && comp == 'w') { return -1; } else if (you == 'w' && comp == 'g') { return 1; }} // Driver Codeint main(){ char you, comp; srand(time(0)); int number = rand() % 100 + 1; if (number < 33) { comp = 's'; } else if (number > 33 && number < 66) { comp = 'w'; } else { comp = 'g'; } printf("Enter 's' for snake, 'w' for " "water and 'g' for gun\n"); scanf("%c", &you); int result = snakeWaterGun(you, comp); if (result == 0) { printf("Game draw!\n"); } else if (result == 1) { printf("You win!\n"); } else { printf("You Lose!\n"); } printf("You choose %c and computer choose %c. ", you, comp); return 0;}// this code is provided by harsh sinha username-// harshsinha03 Output: harshsinha03 adnanirshad158 Python-projects Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n12 Jan, 2022" }, { "code": null, "e": 291, "s": 52, "text": "Snake Water Gun is one of the famous two-player game played by many people. It is a hand game in which the player randomly chooses any of the three forms i.e. snake, water, a...
Print shortest path to print a string on screen - GeeksforGeeks
16 Jun, 2021 Given a screen containing alphabets from A-Z, we can go from one character to another characters using a remote. The remote contains left, right, top and bottom keys.Find shortest possible path to type all characters of given string using the remote. Initial position is top left and all characters of input string should be printed in order.Screen: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z Example: Input: “GEEK” Output: Move Down Move Right Press OK Move Up Move Right Move Right Move Right Press OK Press OK Move Left Move Left Move Left Move Left Move Down Move Down Press OK The idea is to consider screen as 2D-matrix of characters. Then we consider all characters of given string one by one and print out the shortest path between current character and next character in the matrix. In order to find shortest path, we consider the coordinates of current character and next character in the matrix. Based on the difference between x and y values of current and next character’s coordinates, we move left, right, top or bottom. i.e. If row difference is negative, we move up If row difference is positive, we move down If column difference is negative, we go left If column difference is positive, we go right Below is implementation of above idea C++ Java Python3 C# PHP Javascript // C++ program to print shortest possible path to// type all characters of given string using a remote#include <iostream>using namespace std; // Function to print shortest possible path to// type all characters of given string using a remotevoid printPath(string str){ int i = 0; // start from character 'A' present at position (0, 0) int curX = 0, curY = 0; while (i < str.length()) { // find coordinates of next character int nextX = (str[i] - 'A') / 5; int nextY = (str[i] - 'B' + 1) % 5; // Move Up if destination is above while (curX > nextX) { cout << "Move Up" << endl; curX--; } // Move Left if destination is to the left while (curY > nextY) { cout << "Move Left" << endl; curY--; } // Move down if destination is below while (curX < nextX) { cout << "Move Down" << endl; curX++; } // Move Right if destination is to the right while (curY < nextY) { cout << "Move Right" << endl; curY++; } // At this point, destination is reached cout << "Press OK" << endl; i++; }} // Driver codeint main(){ string str = "COZY"; printPath(str); return 0;} // Java program to print shortest possible path to// type all characters of given string using a remote class GFG{ // Function to print shortest possible path to // type all characters of given string using a remote static void printPath(String str) { int i = 0; // start from character 'A' present at position (0, 0) int curX = 0, curY = 0; while (i < str.length()) { // find coordinates of next character int nextX = (str.charAt(i) - 'A') / 5; int nextY = (str.charAt(i) - 'B' + 1) % 5; // Move Up if destination is above while (curX > nextX) { System.out.println("Move Up"); curX--; } // Move Left if destination is to the left while (curY > nextY) { System.out.println("Move Left"); curY--; } // Move down if destination is below while (curX < nextX) { System.out.println("Move Down"); curX++; } // Move Right if destination is to the right while (curY < nextY) { System.out.println("Move Right"); curY++; } // At this point, destination is reached System.out.println("Press OK"); i++; } } // driver program public static void main (String[] args) { String str = "COZY"; printPath(str); }} // Contributed by Pramod Kumar # Python 3 program to print shortest possible# path to type all characters of given string# using a remote # Function to print shortest possible path# to type all characters of given string# using a remotedef printPath(str): i = 0 # start from character 'A' present # at position (0, 0) curX = 0 curY = 0 while (i < len(str)): # find coordinates of next character nextX = int((ord(str[i]) - ord('A')) / 5) nextY = (ord(str[i]) - ord('B') + 1) % 5 # Move Up if destination is above while (curX > nextX): print("Move Up") curX -= 1 # Move Left if destination is to the left while (curY > nextY): print("Move Left") curY -= 1 # Move down if destination is below while (curX < nextX): print("Move Down") curX += 1 # Move Right if destination is to the right while (curY < nextY): print("Move Right") curY += 1 # At this point, destination is reached print("Press OK") i += 1 # Driver codeif __name__ == '__main__': str = "COZY" printPath(str) # This code is contributed by# Sanjit_Prasad // C# program to print shortest// possible path to type all// characters of given string// using a remoteusing System; class GFG { // Function to print shortest // possible path to type all // characters of given string // using a remote static void printPath(String str) { int i = 0; // start from character 'A' // present at position (0, 0) int curX = 0, curY = 0; while (i < str.Length) { // find coordinates of // next character int nextX = (str[i] - 'A') / 5; int nextY = (str[i] - 'B' + 1) % 5; // Move Up if destination // is above while (curX > nextX) { Console.WriteLine("Move Up"); curX--; } // Move Left if destination // is to the left while (curY > nextY) { Console.WriteLine("Move Left"); curY--; } // Move down if destination // is below while (curX < nextX) { Console.WriteLine("Move Down"); curX++; } // Move Right if destination // is to the right while (curY < nextY) { Console.WriteLine("Move Right"); curY++; } // At this point, destination // is reached Console.WriteLine("Press OK"); i++; } } // Driver Code public static void Main () { String str = "COZY"; printPath(str); }} // This Code is contributed by nitin mittal. <?php// PHP program to print shortest possible path to// type all characters of given string using a remote // Function to print shortest possible path to// type all characters of given string using a remotefunction printPath($str){ $i = 0; // start from character 'A' present at position (0, 0) $curX = $curY = 0; while ($i < strlen($str)) { // find coordinates of next character $nextX = (int)((ord($str[$i]) - ord('A')) / 5); $nextY = (ord($str[$i]) - ord('B') + 1) % 5; // Move Up if destination is above while ($curX > $nextX) { echo "Move Up\n"; $curX--; } // Move Left if destination is to the left while ($curY > $nextY) { echo "Move Left\n"; $curY--; } // Move down if destination is below while ($curX < $nextX) { echo "Move Down\n"; $curX++; } // Move Right if destination is to the right while ($curY < $nextY) { echo "Move Right\n"; $curY++; } // At this point, destination is reached echo "Press OK\n"; $i++; }} // Driver code $str = "COZY"; printPath($str); // This code is contributed by chandan_jnu?> <script> // JavaScript program to print shortest // possible path to type all // characters of given string // using a remote // Function to print shortest // possible path to type all // characters of given string // using a remote function printPath(str) { let i = 0; // start from character 'A' // present at position (0, 0) let curX = 0, curY = 0; while (i < str.length) { // find coordinates of // next character let nextX = parseInt((str[i].charCodeAt() - 'A'.charCodeAt()) / 5, 10); let nextY = (str[i].charCodeAt() - 'B'.charCodeAt() + 1) % 5; // Move Up if destination // is above while (curX > nextX) { document.write("Move Up" + "</br>"); curX--; } // Move Left if destination // is to the left while (curY > nextY) { document.write("Move Left" + "</br>"); curY--; } // Move down if destination // is below while (curX < nextX) { document.write("Move Down" + "</br>"); curX++; } // Move Right if destination // is to the right while (curY < nextY) { document.write("Move Right" + "</br>"); curY++; } // At this point, destination // is reached document.write("Press OK" + "</br>"); i++; } } let str = "COZY"; printPath(str); </script> Output: Move Right Move Right Press OK Move Down Move Down Move Right Move Right Press OK Move Left Move Left Move Left Move Left Move Down Move Down Move Down Press OK Move Up Move Right Move Right Move Right Move Right Press OK This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above nitin mittal Sanjit_Prasad Chandan_Kumar nidhi_biet sumitgumber28 divyeshrabadiya07 Accolite Shortest Path Matrix Strings Accolite Strings Matrix Shortest Path Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Efficiently compute sums of diagonals of a matrix Flood fill Algorithm - how to implement fill() in paint? Check for possible path in 2D matrix Zigzag (or diagonal) traversal of Matrix Mathematics | L U Decomposition of a System of Linear Equations Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Longest Common Subsequence | DP-4
[ { "code": null, "e": 26167, "s": 26139, "text": "\n16 Jun, 2021" }, { "code": null, "e": 26519, "s": 26167, "text": "Given a screen containing alphabets from A-Z, we can go from one character to another characters using a remote. The remote contains left, right, top and bottom ke...
Implementation of Binomial Heap | Set - 2 (delete() and decreseKey()) - GeeksforGeeks
17 Feb, 2018 In previous post i.e. Set 1 we have discussed that implements these below functions: insert(H, k): Inserts a key ‘k’ to Binomial Heap ‘H’. This operation first creates a Binomial Heap with single key ‘k’, then calls union on H and the new Binomial heap.getMin(H): A simple way to getMin() is to traverse the list of root of Binomial Trees and return the minimum key. This implementation requires O(Logn) time. It can be optimized to O(1) by maintaining a pointer to minimum key root.extractMin(H): This operation also uses union(). We first call getMin() to find the minimum key Binomial Tree, then we remove the node and create a new Binomial Heap by connecting all subtrees of the removed minimum node. Finally we call union() on H and the newly created Binomial Heap. This operation requires O(Logn) time. insert(H, k): Inserts a key ‘k’ to Binomial Heap ‘H’. This operation first creates a Binomial Heap with single key ‘k’, then calls union on H and the new Binomial heap. getMin(H): A simple way to getMin() is to traverse the list of root of Binomial Trees and return the minimum key. This implementation requires O(Logn) time. It can be optimized to O(1) by maintaining a pointer to minimum key root. extractMin(H): This operation also uses union(). We first call getMin() to find the minimum key Binomial Tree, then we remove the node and create a new Binomial Heap by connecting all subtrees of the removed minimum node. Finally we call union() on H and the newly created Binomial Heap. This operation requires O(Logn) time. Examples: 12------------10--------------------20 / \ / | \ 15 50 70 50 40 | / | | 30 80 85 65 | 100 A Binomial Heap with 13 nodes. It is a collection of 3 Binomial Trees of orders 0, 2 and 3 from left to right. 10--------------------20 / \ / | \ 15 50 70 50 40 | / | | 30 80 85 65 | 100 In this post, below functions are implemented. delete(H): Like Binary Heap, delete operation first reduces the key to minus infinite, then calls extractMin().decreaseKey(H): decreaseKey() is also similar to Binary Heap. We compare the decreases key with it parent and if parent’s key is more, we swap keys and recur for parent. We stop when we either reach a node whose parent has smaller key or we hit the root node. Time complexity of decreaseKey() is O(Logn) delete(H): Like Binary Heap, delete operation first reduces the key to minus infinite, then calls extractMin(). decreaseKey(H): decreaseKey() is also similar to Binary Heap. We compare the decreases key with it parent and if parent’s key is more, we swap keys and recur for parent. We stop when we either reach a node whose parent has smaller key or we hit the root node. Time complexity of decreaseKey() is O(Logn) // C++ program for implementation of// Binomial Heap and Operations on it#include <bits/stdc++.h>using namespace std; // Structure of Nodestruct Node{ int val, degree; Node *parent, *child, *sibling;}; // Making root global to avoid one extra// parameter in all functions.Node *root = NULL; // link two heaps by making h1 a child// of h2.int binomialLink(Node *h1, Node *h2){ h1->parent = h2; h1->sibling = h2->child; h2->child = h1; h2->degree = h2->degree + 1;} // create a NodeNode *createNode(int n){ Node *new_node = new Node; new_node->val = n; new_node->parent = NULL; new_node->sibling = NULL; new_node->child = NULL; new_node->degree = 0; return new_node;} // This function merge two Binomial TreesNode *mergeBHeaps(Node *h1, Node *h2){ if (h1 == NULL) return h2; if (h2 == NULL) return h1; // define a Node Node *res = NULL; // check degree of both Node i.e. // which is greater or smaller if (h1->degree <= h2->degree) res = h1; else if (h1->degree > h2->degree) res = h2; // traverse till if any of heap gets empty while (h1 != NULL && h2 != NULL) { // if degree of h1 is smaller, increment h1 if (h1->degree < h2->degree) h1 = h1->sibling; // Link h1 with h2 in case of equal degree else if (h1->degree == h2->degree) { Node *sib = h1->sibling; h1->sibling = h2; h1 = sib; } // if h2 is greater else { Node *sib = h2->sibling; h2->sibling = h1; h2 = sib; } } return res;} // This function perform union operation on two// binomial heap i.e. h1 & h2Node *unionBHeaps(Node *h1, Node *h2){ if (h1 == NULL && h2 == NULL) return NULL; Node *res = mergeBHeaps(h1, h2); // Traverse the merged list and set // values according to the degree of // Nodes Node *prev = NULL, *curr = res, *next = curr->sibling; while (next != NULL) { if ((curr->degree != next->degree) || ((next->sibling != NULL) && (next->sibling)->degree == curr->degree)) { prev = curr; curr = next; } else { if (curr->val <= next->val) { curr->sibling = next->sibling; binomialLink(next, curr); } else { if (prev == NULL) res = next; else prev->sibling = next; binomialLink(curr, next); curr = next; } } next = curr->sibling; } return res;} // Function to insert a Nodevoid binomialHeapInsert(int x){ // Create a new node and do union of // this node with root root = unionBHeaps(root, createNode(x));} // Function to display the Nodesvoid display(Node *h){ while (h) { cout << h->val << " "; display(h->child); h = h->sibling; }} // Function to reverse a list// using recursion.int revertList(Node *h){ if (h->sibling != NULL) { revertList(h->sibling); (h->sibling)->sibling = h; } else root = h;} // Function to extract minimum valueNode *extractMinBHeap(Node *h){ if (h == NULL) return NULL; Node *min_node_prev = NULL; Node *min_node = h; // Find minimum value int min = h->val; Node *curr = h; while (curr->sibling != NULL) { if ((curr->sibling)->val < min) { min = (curr->sibling)->val; min_node_prev = curr; min_node = curr->sibling; } curr = curr->sibling; } // If there is a single Node if (min_node_prev == NULL && min_node->sibling == NULL) h = NULL; else if (min_node_prev == NULL) h = min_node->sibling; // Remove min node from list else min_node_prev->sibling = min_node->sibling; // Set root (which is global) as children // list of min node if (min_node->child != NULL) { revertList(min_node->child); (min_node->child)->sibling = NULL; } // Do union of root h and children return unionBHeaps(h, root);} // Function to search for an elementNode *findNode(Node *h, int val){ if (h == NULL) return NULL; // check if key is equal to the root's data if (h->val == val) return h; // Recur for child Node *res = findNode(h->child, val); if (res != NULL) return res; return findNode(h->sibling, val);} // Function to decrease the value of old_val// to new_valvoid decreaseKeyBHeap(Node *H, int old_val, int new_val){ // First check element present or not Node *node = findNode(H, old_val); // return if Node is not present if (node == NULL) return; // Reduce the value to the minimum node->val = new_val; Node *parent = node->parent; // Update the heap according to reduced value while (parent != NULL && node->val < parent->val) { swap(node->val, parent->val); node = parent; parent = parent->parent; }} // Function to delete an elementNode *binomialHeapDelete(Node *h, int val){ // Check if heap is empty or not if (h == NULL) return NULL; // Reduce the value of element to minimum decreaseKeyBHeap(h, val, INT_MIN); // Delete the minimum element from heap return extractMinBHeap(h);} // Driver codeint main(){ // Note that root is global binomialHeapInsert(10); binomialHeapInsert(20); binomialHeapInsert(30); binomialHeapInsert(40); binomialHeapInsert(50); cout << "The heap is:\n"; display(root); // Delete a particular element from heap root = binomialHeapDelete(root, 10); cout << "\nAfter deleing 10, the heap is:\n"; display(root); return 0;} Output: The heap is: 50 10 30 40 20 After deleing 10, the heap is: 20 30 40 50 Data Structures-Heap Advanced Data Structure Heap Heap 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) Quad Tree HeapSort Binary Heap Huffman Coding | Greedy Algo-3 K'th Smallest/Largest Element in Unsorted Array | Set 1 k largest(or smallest) elements in an array
[ { "code": null, "e": 25733, "s": 25705, "text": "\n17 Feb, 2018" }, { "code": null, "e": 25818, "s": 25733, "text": "In previous post i.e. Set 1 we have discussed that implements these below functions:" }, { "code": null, "e": 26542, "s": 25818, "text": "inser...
Resize Multiple Images using OpenCV-Python - GeeksforGeeks
26 Sep, 2021 In this article, we are going to write a python script using the OpenCV library to Resize Multiple Images and save them as an image file. Resizing the image refers to the growth of the images. Measurement works best in the use of multiple images and in machine learning applications. It helps to reduce the number of pixels from an image and that has several benefits e.g. It can reduce neural network training time as the number of pixels in the image greatly increases the number of input nodes which also improves the model difficulty. Approach: Firstly, load the required libraries into a Python file (argparse, OpenCV, etc.). We are using argparse() function to get the path of the directory of images on which we need to perform the resizing. Use for loop to iterate every image in the directory. Load image in a variable using cv2.imread() function. Define a resizing scale and set the calculated height and width. Resize the image using cv2.resize() function. Place the output file inside the output folder using cv2.imwrite() function. All the images inside the Images folder will be resized and will be saved in an output folder. Below is the implementation: Python3 # Required Librariesimport cv2import numpy as npfrom os import listdirfrom os.path import isfile, joinfrom pathlib import Pathimport argparseimport numpy # Argument parsing variable declaredap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required=True, help="Path to folder") args = vars(ap.parse_args()) # Find all the images in the provided images foldermypath = args["image"]onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]images = numpy.empty(len(onlyfiles), dtype=object) # Iterate through every image# and resize all the images.for n in range(0, len(onlyfiles)): path = join(mypath, onlyfiles[n]) images[n] = cv2.imread(join(mypath, onlyfiles[n]), cv2.IMREAD_UNCHANGED) # Load the image in img variable img = cv2.imread(path, 1) # Define a resizing Scale # To declare how much to resize resize_scaling = 50 resize_width = int(img.shape[1] * resize_scaling/100) resize_hieght = int(img.shape[0] * resize_scaling/100) resized_dimensions = (resize_width, resize_hieght) # Create resized image using the calculated dimensions resized_image = cv2.resize(img, resized_dimensions, interpolation=cv2.INTER_AREA) # Save the image in Output Folder cv2.imwrite( 'output/' + str(resize_width) + str(resize_hieght) + str(n) + '_resized.jpg', resized_image) print("Images resized Successfully") Open the terminal in the folder where this Python Script is saved and type the below command. python resize.py --image path/to/images/folder/ Output: anikaseth98 Picked Python-OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25563, "s": 25535, "text": "\n26 Sep, 2021" }, { "code": null, "e": 26102, "s": 25563, "text": "In this article, we are going to write a python script using the OpenCV library to Resize Multiple Images and save them as an image file. Resizing the image refers...
Argument Coercion in C/C++ - GeeksforGeeks
26 Dec, 2018 Argument coercion is a feature of function prototypes by which the compiler implicitly converts the datatype of the arguments passed during the function call to match the datatype in the definition of the function. It follows Argument promotion rules. Therefore a lower datatype maybe converted into a higher datatype but vice-versa is not true. This is because when a higher datatype is converted to a lower datatype it can result into loss or truncation of data. The Promotion hierarchy for fundamental datatypes in C++ is: Example: Take for Example the code given below consists of an add function that expects double arguments. But even when integer arguments are passed it works correctly. In case long double arguments are passed the code will give an error. #include <iostream>using namespace std; double add(double a, double b){ return a + b;} int main(){ // Passing double arguments, as expected cout << "Sum = " << add(2.4, 8.5) << endl; // Passing int arguments, when double is expected // This will lead to Argument Coercion cout << "Sum = " << add(16, 18) << endl; return 0;} C-Data Types cpp-data-types CPP-Functions C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C Exception Handling in C++ Multithreading 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": 25478, "s": 25450, "text": "\n26 Dec, 2018" }, { "code": null, "e": 25693, "s": 25478, "text": "Argument coercion is a feature of function prototypes by which the compiler implicitly converts the datatype of the arguments passed during the function call to ma...
Encode given string by replacing substrings with prefix same as itself with * - GeeksforGeeks
29 Dec, 2021 Given string str of size N containing only lowercase English letters. The task is to encrypt the string such that the substrings having same prefix as itself are replaced by a *. Generate the encrypted string. Note: If the string can be encrypted in multiple ways, find the smallest encrypted string. Examples: Input: str = “ababcababcd”Output: ab*c*dExplanation: The substring “ababc” starting from 5th index (0 based indexing) can be replaced by a ‘*’. So the string becomes “ababcababcd” -> “ababc*d”. Now the substring “ab” starting from 2nd index can again be replaced with a ‘*’. So the string becomes “ab*c*d” Input: str = “zzzzzzz”Output: z*z*zExplanation: The string can be encrypted in 2 ways: “z*z*z” and “z**zzz”. Out of the two “z*z*z” is smaller in length. Approach: A simple solution to generate smallest encrypted string is to find the longest non-overlapping repeated substring and encrypt that substring first. To implement this use the following steps: Create a stack to store the encrypted string. Declare two pointers (i & j) to point to the 1st index and middle index respectively. Now start traversing the string and repeat the loop until the entire string is scanned. Follow steps mentioned below for each iteration:Compare both the substring from index i and j.If both substrings are equal, then repeat the same process on this substring and store the remaining string into stack.Else decrement the value of 2nd pointer ( j ) by 1. Compare both the substring from index i and j. If both substrings are equal, then repeat the same process on this substring and store the remaining string into stack. Else decrement the value of 2nd pointer ( j ) by 1. Now pop all the elements from the stack and append a symbol “*” then store it in a output string. Return the encrypted string. Below is the implementation of the above approach. C++ Java Python3 C# Javascript // C++ code to implement the above approach#include <bits/stdc++.h>using namespace std; // Function to generate the encrypted stringstring compress(string str){ // Stack to store encrypted string stack<string> st; // Variable to store length of string int N = str.length(); // Variable to point 1st and middle index int i = 0, j = N / 2; // Repeat the loop until // the entire string is checked while (j > 0) { int mid = j; // Compare the substring // from index 0 to mid-1 // with the rest of the substring // after mid. for (i = 0; i < mid && str[i] == str[j]; i++, j++) ; // If both substrings are equal // then repeat the same process // on this substring and store // the remaining string into stack if (i == mid) { st.push(str.substr(j, N - 1)); // Update the value of // string 'str' with the // longest repeating substring str = str.substr(0, i); // Set the new string length to n N = mid; // Initialize the 2nd pointer // from the mid of new string j = N / 2; } // If both substrings are not equal // then decrement the 2nd pointer by 1 else { j = mid - 1; } } // Pop all the elements from the stack // append a symbol '*' and store // in a output string while (!st.empty()) { str = str + "*" + st.top(); st.pop(); } return str;} // Driver codeint main(){ // Declare and initialize the string string str = "zzzzzzz"; cout << compress(str) << "\n"; return 0;} // Java code to implement the above approach import java.util.*; class GFG{ // Function to generate the encrypted Stringstatic String compress(String str){ // Stack to store encrypted String Stack<String> st = new Stack<String>(); // Variable to store length of String int N = str.length(); // Variable to point 1st and middle index int i = 0, j = N / 2; // Repeat the loop until // the entire String is checked while (j > 0) { int mid = j; // Compare the subString // from index 0 to mid-1 // with the rest of the subString // after mid. for (i = 0; i < mid && str.charAt(i) == str.charAt(j); i++, j++) ; // If both subStrings are equal // then repeat the same process // on this subString and store // the remaining String into stack if (i == mid) { st.add(str.substring(j, N)); // Update the value of // String 'str' with the // longest repeating subString str = str.substring(0, i); // Set the new String length to n N = mid; // Initialize the 2nd pointer // from the mid of new String j = N / 2; } // If both subStrings are not equal // then decrement the 2nd pointer by 1 else { j = mid - 1; } } // Pop all the elements from the stack // append a symbol '*' and store // in a output String while (!st.isEmpty()) { str = str + "*" + st.peek(); st.pop(); } return str;} // Driver codepublic static void main(String[] args){ // Declare and initialize the String String str = "zzzzzzz"; System.out.print(compress(str)+ "\n");}} // This code is contributed by 29AjayKumar # Python code for the above approach # Function to generate the encrypted stringdef compress(str): # Stack to store encrypted string st = [] # Variable to store length of string N = len(str) # Variable to point 1st and middle index i = 0 j = (int)(N / 2) # Repeat the loop until # the entire string is checked while (j > 0): mid = j # Compare the substring # from index 0 to mid-1 # with the rest of the substring # after mid. i=0 while(str[i] == str[j] and i < mid): i += 1 j += 1 # If both substrings are equal # then repeat the same process # on this substring and store # the remaining string into stack if (i == mid): st.append(str[j:N]) # Update the value of # string 'str' with the # longest repeating substring str = str[0:i] # Set the new string length to n N = mid # Initialize the 2nd pointer # from the mid of new string j = N // 2 # If both substrings are not equal # then decrement the 2nd pointer by 1 else: j = mid - 1 # Pop all the elements from the stack # append a symbol '*' and store # in a output string while (len(st) != 0): str = str + '*' + st[len(st) - 1] st.pop() return str # Driver code # Declare and initialize the stringstr = "zzzzzzz"print(compress(str)) # This code is contributed by Saurabh jaiswal // C# code to implement the above approachusing System;using System.Collections.Generic; public class GFG{ // Function to generate the encrypted Stringstatic String compress(String str){ // Stack to store encrypted String Stack<String> st = new Stack<String>(); // Variable to store length of String int N = str.Length; // Variable to point 1st and middle index int i = 0, j = N / 2; // Repeat the loop until // the entire String is checked while (j > 0) { int mid = j; // Compare the subString // from index 0 to mid-1 // with the rest of the subString // after mid. for (i = 0; i < mid && str[i] == str[j]; i++, j++) ; // If both subStrings are equal // then repeat the same process // on this subString and store // the remaining String into stack if (i == mid) { st.Push(str.Substring(j, N-j)); // Update the value of // String 'str' with the // longest repeating subString str = str.Substring(0, i); // Set the new String length to n N = mid; // Initialize the 2nd pointer // from the mid of new String j = N / 2; } // If both subStrings are not equal // then decrement the 2nd pointer by 1 else { j = mid - 1; } } // Pop all the elements from the stack // append a symbol '*' and store // in a output String while (st.Count!=0) { str = str + "*" + st.Peek(); st.Pop(); } return str;} // Driver codepublic static void Main(String[] args){ // Declare and initialize the String String str = "zzzzzzz"; Console.Write(compress(str)+ "\n");}} // This code is contributed by shikhasingrajput <script> // JavaScript code for the above approach // Function to generate the encrypted string function compress(str) { // Stack to store encrypted string let st = []; // Variable to store length of string let N = str.length; // Variable to point 1st and middle index let i = 0, j = Math.floor(N / 2); // Repeat the loop until // the entire string is checked while (j > 0) { let mid = j; // Compare the substring // from index 0 to mid-1 // with the rest of the substring // after mid. for (i = 0; i < mid && str[i] == str[j]; i++, j++) ; // If both substrings are equal // then repeat the same process // on this substring and store // the remaining string into stack if (i == mid) { st.push(str.slice(j, N)); // Update the value of // string 'str' with the // longest repeating substring str = str.slice(0, i); // Set the new string length to n N = mid; // Initialize the 2nd pointer // from the mid of new string j = Math.floor(N / 2); } // If both substrings are not equal // then decrement the 2nd pointer by 1 else { j = mid - 1; } } // Pop all the elements from the stack // append a symbol '*' and store // in a output string while (st.length != 0) { str = str + '*' + st[st.length - 1]; st.pop(); } return str; } // Driver code // Declare and initialize the string let str = "zzzzzzz"; document.write(compress(str) + '<br>'); // This code is contributed by Potta Lokesh</script> z*z*z Time Complexity: O(N. Log(N))Auxiliary Space: O(N) lokeshpotta20 _saurabh_jaiswal 29AjayKumar shikhasingrajput Algo-Geek 2021 encoding-decoding prefix substring Algo Geek Stack Strings Strings Stack Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Check if the given string is valid English word or not Sort strings on the basis of their numeric part Divide given number into two even parts Smallest set of vertices to visit all nodes of the given Graph Count of Palindrome Strings in given Array of strings Stack Data Structure (Introduction and Program) Stack Class in Java Stack in Python Check for Balanced Brackets in an expression (well-formedness) using Stack Stack | Set 2 (Infix to Postfix)
[ { "code": null, "e": 27535, "s": 27507, "text": "\n29 Dec, 2021" }, { "code": null, "e": 27745, "s": 27535, "text": "Given string str of size N containing only lowercase English letters. The task is to encrypt the string such that the substrings having same prefix as itself are r...
Executable Comments in Java - GeeksforGeeks
18 Apr, 2019 A comment is a statement that is not executed by the compiler or the interpreter, but before the lexical transformation of the program in the compiler, the contents of the program are encoded into ASCII to make the processing easier. Consider this program: class Main{ public static void main(String[] args) { // The comment below is magic.. // \u000d System.out.println("Geek Comment Executed!"); }} This code will be executed and compiled successfully to produce the output.Output Geek Comment Executed! This successfully produces this output because java compiler before lexical transformation parses the Unicode character \u000d as a new line and the program gets transformed into: class Main{ public static void main(String[] args) { // The comment below is magic // System.out.println("Geek Comment Executed!"); }} The Unicode character Shifts the print statement to the next line which is then executed like a normal java program. So, the question arises why the translation of Unicode escapes happens before any other source code processing? 1. Java source code can be written in any encoding which allows a wide range of characters in string, literal and comments.1. It makes processing by ASCII-based tools easier.2. This guarantees java Platform dependence which is the independence from supported character sets.3. This helps in documenting code in non-Latin languages. Being able to write any Unicode character anywhere in the file is a neat feature, The fact that it can interfere with the semantics in such subtle ways is just a side-effect. Let’s consider this java program: \u0070\u0075\u0062\u006c\u0069\u0063\u0020\u0020\u0020\u0020\u0063\u006c\u0061\u0073\u0073\u0020\u0055\u0067\u006c\u0079\u007b\u0070\u0075\u0062\u006c\u0069\u0063\u0020\u0020\u0020\u0020\u0020\u0020\u0020\u0073\u0074\u0061\u0074\u0069\u0063\u0076\u006f\u0069\u0064\u0020\u006d\u0061\u0069\u006e\u0028\u0053\u0074\u0072\u0069\u006e\u0067\u005b\u005d\u0020\u0020\u0020\u0020\u0020\u0020\u0061\u0072\u0067\u0073\u0029\u007b\u0053\u0079\u0073\u0074\u0065\u006d\u002e\u006f\u0075\u0074\u002e\u0070\u0072\u0069\u006e\u0074\u006c\u006e\u0028\u0020\u0022\u0048\u0065\u006c\u006c\u006f\u0020\u0077\u0022\u002b\u0022\u006f\u0072\u006c\u0064\u0022\u0029\u003b\u007d\u007d Output: Hello World This unicode program is converted into its representative values to produce “Hello World”Reference–https://stackoverflow.com/questions/30727515/why-is-executing-java-code-in-comments-with-certain-unicode-characters-allowed?newsletter=1&nlcode=222379%7C1266 Akanksha_Rai java-puzzle Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Comparator Interface in Java with Examples Internal Working of HashMap in Java Strings in Java
[ { "code": null, "e": 25249, "s": 25221, "text": "\n18 Apr, 2019" }, { "code": null, "e": 25506, "s": 25249, "text": "A comment is a statement that is not executed by the compiler or the interpreter, but before the lexical transformation of the program in the compiler, the content...
Common Memory/Pointer Related bug in C Programs - GeeksforGeeks
01 Oct, 2018 Dereferencing an unknown memory location : C programmers mostly use scanf() function to take input, but sometimes a small mistake can bring a bug or even crash whole program.The syntax for scanf() is scanf(“%d”, &a);. It might be possible to miss a & and write &a as a so now scanf(“%d”, a); is dereferencing to an unknown location.Now either the program may terminate with an exception or it may correspond to a valid location(not related to current program but to some other program) and may get overwritten which may cause unknown effect later. // A C program to demonstrate that missing// an & in scanf() may cause memory problems.#include <stdio.h> int main(){ int a; scanf("%d", a); printf("%d", a); return 0;} Reading an uninitialized Memory. In C, beginners generally use malloc() to provide run time memory but with malloc() the memory block do not get initialized and one may access . // A C program to demonstrate that missing// an & may cause memory problems.#include <stdio.h> int main(){ int* p = (int*)malloc(sizeof(int) * 4); int i; // p[] contains some garbage value so // below loop does not make any sense. for (i = 0; i < 4; i++) p[i] += 100;} A solution is to use calloc() instead which initialize block to 0. Buffer overflow : This is a very common mistake that occur in C and this become even more common due to presence of a faulty function in C itself i.e. gets() function which is used to take string as input. It does not check the memory provided to store string in the program due to which if a user enter string of greater size then gets() with overwrite memory location after the string and cause overflow. void read(){ char str[20]; gets(str); printf("%s", str); return;} The code suffers from Buffer Overflow as gets() doesn’t do any array bound testing. gets() keeps on reading until it sees a newline character. To avoid Buffer Overflow, fgets() should be used instead of gets() as fgets() makes sure that not more than MAX_LIMIT characters are read. #define MAX_LIMIT 20void read(){ char str[MAX_LIMIT]; fgets(str, MAX_LIMIT, stdin); printf("%s", str); return;} Memory leaks This situation arises when the used heap memory is not de-allocated due to which the main memory get eventually filled up and free memory become less. /* Function with memory leak */#include <stdlib.h> void f(){ int* ptr = (int*)malloc(sizeof(int)); /* Do some work */ return; /* Return without freeing ptr*/} We should use free() after malloc() if memory is not used anymore. /* Function without memory leak */#include <stdlib.h> void f(){ int* ptr = (int*)malloc(sizeof(int)); /* Do some work */ free(ptr); // Deallocate memory return;} Bug due to precedence Less understanding of operator and their precedence can produce a bug especially with pointers like // C program to demonstrate bug introduced due// to precedence.#include <stdlib.h> int demo(){ int a = 10; int* p = &a; // intention was to increase the value of a *p++;} Precedence of * (dereference/indirection operator not multiplication) and postfix ++ are not same but prefix ++ and * has same, and hence, first the value of p will increase and will point to a bad memory area and then dereference and will overwrite that location or program may get terminated. Please see Difference between ++*p, *p++ and *++p for details. Sending address of non-existing variable Returning address of a local variable causes problems, #include <stdlib.h> int fun(){ int x = 10; return &x;}int main(){ int* p = fun(); *p = 20;} When function fun() is called variable a is created but as soon function returns, it get destroyed. Since function is returned its address p will point to a memory area in stack area and if another function is called then a change by pointer p may result in error. Pointer arithmetic Pointer arithmetic can be confusing let’s take an example suppose integer is of 4 Bytes. int main(){ int x[10] = { 0 }, i = 0, *p; // p point to starting address of array x p = &x[0]; while (i < 10) { *p = 10; // intention was to point to integer at x[1] p = p + 4; i++; }} Although it seems correct as integer is of 4 byte and p is at starting location so adding 4 to it will cause p to point at next integer in array n but pointer arithmetic work according to size of its data type so adding 1 to a pointer of integer then sizeof(int) will get added to it same applies for pointer to any other data type. int main(){ int x[10] = { 0 }, i = 0, *p; p = &x[0]; // p point to starting address of array x while (i < 10) { *p = 10; p++; // means p = p + sizeof(int) i++; }} Passing array as parameter When we pass an array to a function, it is always treated as a pointer in the function. That’s why we should never use sizeof on array parameter. We should rather always pass size as a second parameter. #include <stdio.h> // arr is a pointer even if we have// use square brackets.void printArray(int arr[]){ int i; /* sizeof should not be used here to get number of elements in array*/ int arr_size = sizeof(arr) / sizeof(arr[0]); for (i = 0; i < arr_size; i++) { printf("%d ", arr[i]); }} int main(){ int arr[4] = { 1, 2, 3, 4 }; printArray(arr); return 0;} Below is the corrected code #include <stdio.h> // arr is a pointer even if we have// use square brackets.void printArray(int arr[], int arr_size){ int i; for (i = 0; i < arr_size; i++) { printf("%d ", arr[i]); }} int main(){ int arr[] = { 1, 2, 3, 4 }; int arr_size = sizeof(arr) / sizeof(arr[0]); printArray(arr, arr_size); return 0;} Reference :Computer Systems :A programmer’s Perspective xdsarkar C-Dynamic Memory Allocation cpp-pointer C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C Exception Handling in C++ Multithreading 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": 25477, "s": 25449, "text": "\n01 Oct, 2018" }, { "code": null, "e": 26025, "s": 25477, "text": "Dereferencing an unknown memory location : C programmers mostly use scanf() function to take input, but sometimes a small mistake can bring a bug or even crash who...
Data Structures | Heap | Question 1 - GeeksforGeeks
07 Nov, 2019 What is the time complexity of Build Heap operation. Build Heap is used to build a max(or min) binary heap from a given array. Build Heap is used in Heap Sort as a first step for sorting.(A) O(nLogn)(B) O(n^2)(C) O(Logn)(D) O(n)Answer: (D)Explanation: Following is algorithm for building a Heap of an input array A. BUILD-HEAP(A) heapsize := size(A); for i := floor(heapsize/2) downto 1 do HEAPIFY(A, i); end for END Although the worst case complexity looks like O(nLogn), upper bound of time complexity is O(n). See following links for the proof of time complexity. Time Complexity of building a heapQuiz of this Question Data Structures Data Structures-Heap Heap Quizzes Data Structures Data Structures Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Data Structures | Tree Traversals | Question 4 Data Structures | Graph | Question 9 Data Structures | Stack | Question 1 Binary Search Tree | Set 3 (Iterative Delete) Program to create Custom Vector Class in C++ Encryption and Decryption of String according to given technique Data Structures | Hash | Question 5 Count of triplets in an Array (i, j, k) such that i < j < k and a[k] < a[i] < a[j] Data Structures | Tree Traversals | Question 5 Data Structures | Tree Traversals | Question 8
[ { "code": null, "e": 26097, "s": 26069, "text": "\n07 Nov, 2019" }, { "code": null, "e": 26413, "s": 26097, "text": "What is the time complexity of Build Heap operation. Build Heap is used to build a max(or min) binary heap from a given array. Build Heap is used in Heap Sort as a...
Find the equation of plane which passes through two points and parallel to a given axis - GeeksforGeeks
27 Mar, 2022 Given two points A(x1, y1, z1) and B(x2, y2, z2) and a set of points (a, b, c) which represent the axis (ai + bj + ck), the task is to find the equation of plane which passes through the given points A and B and parallel to the given axis. Examples: Input: x1 = 1, y1 = 2, z1 = 3, x2 = 3, y2 = 4, z2 = 5, a= 6, b = 7, c = 8 Output: 2x + 4y + 2z + 0 = 0 Input: x1 = 2, y1 = 3, z1 = 5, x2 = 6, y2 = 7, z2 = 8, a= 11, b = 23, c = 10. Output: -29x + 7y + 48z + 0= 0 Approach: From the given two points on plane A and B, The directions ratios a vector equation of line AB is given by: direction ratio = (x2 – x1, y2 – y1, z2 – z1) Since the line is parallel to the given axis . Therefore, the cross-product of and is 0 which is given by: where, d, e, and f are the coefficient of vector equation of line AB i.e., d = (x2 – x1), e = (y2 – y1), and f = (z2 – z1) and a, b, and c are the coefficient of given axis. The equation formed by the above determinant is given by: (Equation 1) Equation 1 is perpendicular to the line AB which means it is perpendicular to the required plane. Let the Equation of the plane is given by (Equation 2) where A, B, and C are the direction ratio of the plane perpendicular to the plane.Since Equation 1 is Equation 2 are perpendicular to each other, therefore the value of the direction ratio of Equation 1 & 2 are parallel. Then the coefficient of the plane is given by: A = (b*f – c*e), B = (a*f – c*d), and C = (a*e – b*d) Now dot product of plane and vector line AB gives the value of D as D = -(A * d – B * e + C * f) Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation to find the// equation of plane which passes// through two points and parallel// to a given axis #include <bits/stdc++.h>using namespace std; void findEquation(int x1, int y1, int z1, int x2, int y2, int z2, int d, int e, int f){ // Find direction vector // of points (x1, y1, z1) // and (x2, y2, z2) double a = x2 - x1; double b = y2 - y1; double c = z2 - z1; // Values that are calculated // and simplified from the // cross product int A = (b * f - c * e); int B = (a * f - c * d); int C = (a * e - b * d); int D = -(A * d - B * e + C * f); // Print the equation of plane cout << A << "x + " << B << "y + " << C << "z + " << D << "= 0";} // Driver Codeint main(){ // Point A int x1 = 2, y1 = 3, z1 = 5; // Point B int x2 = 6, y2 = 7, z2 = 8; // Given axis int a = 11, b = 23, c = 10; // Function Call findEquation(x1, y1, z1, x2, y2, z2, a, b, c); return 0;} // Java implementation to find the// equation of plane which passes// through two points and parallel// to a given axisimport java.util.*; class GFG{ static void findEquation(int x1, int y1, int z1, int x2, int y2, int z2, int d, int e, int f){ // Find direction vector // of points (x1, y1, z1) // and (x2, y2, z2) double a = x2 - x1; double b = y2 - y1; double c = z2 - z1; // Values that are calculated // and simplified from the // cross product int A = (int)(b * f - c * e); int B = (int)(a * f - c * d); int C = (int)(a * e - b * d); int D = -(int)(A * d - B * e + C * f); // Print the equation of plane System.out.println(A + "x + " + B + "y + " + C + "z + " + D + "= 0 ");} // Driver codepublic static void main(String[] args){ // Point A int x1 = 2, y1 = 3, z1 = 5; // Point B int x2 = 6, y2 = 7, z2 = 8; // Given axis int a = 11, b = 23, c = 10; // Function Call findEquation(x1, y1, z1, x2, y2, z2, a, b, c);}} // This code is contributed by Pratima Pandey # Python3 implementation# to find the equation# of plane which passes# through two points and# parallel to a given axisdef findEquation(x1, y1, z1, x2, y2, z2, d, e, f): # Find direction vector # of points (x1, y1, z1) # and (x2, y2, z2) a = x2 - x1 b = y2 - y1 c = z2 - z1 # Values that are calculated # and simplified from the # cross product A = (b * f - c * e) B = (a * f - c * d) C = (a * e - b * d) D = -(A * d - B * e + C * f) # Print the equation of plane print (A, "x + ", B, "y + ", C, "z + ", D, "= 0") # Driver Codeif __name__ == "__main__": # Point A x1 = 2 y1 = 3 z1 = 5; # Point B x2 = 6 y2 = 7 z2 = 8 # Given axis a = 11 b = 23 c = 10 # Function Call findEquation(x1, y1, z1, x2, y2, z2, a, b, c) # This code is contributed by Chitranayal // C# implementation to find the// equation of plane which passes// through two points and parallel// to a given axisusing System;class GFG{ static void findEquation(int x1, int y1, int z1, int x2, int y2, int z2, int d, int e, int f){ // Find direction vector // of points (x1, y1, z1) // and (x2, y2, z2) double a = x2 - x1; double b = y2 - y1; double c = z2 - z1; // Values that are calculated // and simplified from the // cross product int A = (int)(b * f - c * e); int B = (int)(a * f - c * d); int C = (int)(a * e - b * d); int D = -(int)(A * d - B * e + C * f); // Print the equation of plane Console.Write(A + "x + " + B + "y + " + C + "z + " + D + "= 0 ");} // Driver codepublic static void Main(){ // Point A int x1 = 2, y1 = 3, z1 = 5; // Point B int x2 = 6, y2 = 7, z2 = 8; // Given axis int a = 11, b = 23, c = 10; // Function Call findEquation(x1, y1, z1, x2, y2, z2, a, b, c);}} // This code is contributed by Code_Mech <script>// javascript implementation to find the// equation of plane which passes// through two points and parallel// to a given axis function findEquation(x1 , y1 , z1 , x2 , y2 , z2 , d , e , f) { // Find direction vector // of points (x1, y1, z1) // and (x2, y2, z2) var a = x2 - x1; var b = y2 - y1; var c = z2 - z1; // Values that are calculated // and simplified from the // cross product var A = parseInt( (b * f - c * e)); var B = parseInt( (a * f - c * d)); var C = parseInt( (a * e - b * d)); var D = -parseInt( (A * d - B * e + C * f)); // Print the equation of plane document.write(A + "x + " + B + "y + " + C + "z + " + D + "= 0 "); } // Driver code // Point A var x1 = 2, y1 = 3, z1 = 5; // Point B var x2 = 6, y2 = 7, z2 = 8; // Given axis var a = 11, b = 23, c = 10; // Function Call findEquation(x1, y1, z1, x2, y2, z2, a, b, c); // This code is contributed by Rajput-Ji</script> -29x + 7y + 48z + 0= 0 Time Complexity: O(1) Auxiliary Space: O(1) dewantipandeydp Code_Mech ukasp Rajput-Ji arorakashish0911 rohitkumarsinghcna Geometric Mathematical Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Haversine formula to find distance between two points on a sphere Program to find slope of a line Equation of circle when three points on the circle are given Program to find line passing through 2 Points Maximum Manhattan distance between a distinct pair from N coordinates Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 26561, "s": 26533, "text": "\n27 Mar, 2022" }, { "code": null, "e": 26801, "s": 26561, "text": "Given two points A(x1, y1, z1) and B(x2, y2, z2) and a set of points (a, b, c) which represent the axis (ai + bj + ck), the task is to find the equation of plane w...
Python - Find all duplicate characters in string - GeeksforGeeks
19 Feb, 2021 Given a string, find all the duplicate characters which are similar to each others. Let’s look at the example.Examples: Input : hello Output : l Input : geeksforgeeeks Output : e g k s We have discussed a solution in below post.Print all the duplicates in the input string We can solve this problem quickly using python Counter() method. Approach is very simple. 1) First create a dictionary using Counter method having strings as keys and their frequencies as values.2) Declare a temp variable.3) Print all the indexes from the keys which have value greater than 1. from collections import Counter def find_dup_char(input): # now create dictionary using counter method # which will have strings as key and their # frequencies as value WC = Counter(input) j = -1 # Finding no. of occurrence of a character # and get the index of it. for i in WC.values(): j = j + 1 if( i > 1 ): print WC.keys()[j], # Driver programif __name__ == "__main__": input = 'geeksforgeeks' find_dup_char(input) Output: e g k s YouTubeGeeksforGeeks507K subscribersPython Programming Tutorial | Find duplicates in a string using Counter method | 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 / 2:24•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=Z8Zc84SoXiY" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Python string-programs python-string Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() *args and **kwargs in Python Create a Pandas DataFrame from Lists Check if element exists in list in Python Convert integer to string in Python How To Convert Python Dictionary To JSON? sum() function in Python
[ { "code": null, "e": 25493, "s": 25465, "text": "\n19 Feb, 2021" }, { "code": null, "e": 25577, "s": 25493, "text": "Given a string, find all the duplicate characters which are similar to each others." }, { "code": null, "e": 25613, "s": 25577, "text": "Let’s ...
Place plots side by side in Matplotlib - GeeksforGeeks
19 Aug, 2021 Matplotlib is the most popular Python library for plotting graphs and visualizing our data. In Matplotlib we can create multiple plots by calling them once. To create multiple plots we use the subplot function of pyplot module in Matplotlib. Syntax: plt.subplot(nrows, .ncolumns, index) Parameters: nrows is for number of rows means if the row is 1 then the plots lie horizontally. ncolumns stands for column means if the column is 1 then the plot lie vertically. and index is the count/index of plots. It starts with 1. Approach: Import libraries and modules. Create data for plot. Now, create a subplot using above function. Give the parameters to the function according to the requirement. Example 1: Python3 # importing librariesimport numpy as npimport matplotlib.pyplot as plt # creating an array of data for x-axisx = np.array([2, 4, 6, 8, 10, 12, 14, 16, 18, 20]) # data for y-axisy_1 = 2*x # dat for y-axis for another ploty_2 = 3*x # using subplot function and creating plot oneplt.subplot(1, 2, 1) # row 1, column 2, count 1plt.plot(x, y_1, 'r', linewidth=5, linestyle=':')plt.title('FIRST PLOT')plt.xlabel('x-axis')plt.ylabel('y-axis') # using subplot function and creating plot two# row 1, column 2, count 2plt.subplot(1, 2, 2) # g is gor green colorplt.plot(x, y_2, 'g', linewidth=5)plt.title('SECOND PLOT')plt.xlabel('x-axis')plt.ylabel('y-axis') # space between the plotsplt.tight_layout(4) # show plotplt.show() Output: Example 2: In vertical form. Python3 # importing librariesimport numpy as npimport matplotlib.pyplot as plt # creating an array of data for x-axisx = np.array([2, 4, 6, 8, 10, 12, 14, 16, 18, 20]) # data for y-axisy_1 = 2*x # dat for y-axis for another ploty_2 = 3*x # using subplot function and creating plot one# row 2, column 1, count 1plt.subplot(2, 1, 1)plt.plot(x, y_1, 'r', linewidth=5, linestyle=':')plt.title('FIRST PLOT')plt.xlabel('x-axis')plt.ylabel('y-axis') # using subplot function and creating plot two# row 2, column 1, count 2plt.subplot(2, 1, 2)plt.plot(x, y_2, 'g', linewidth=5)plt.title('SECOND PLOT')plt.xlabel('x-axis')plt.ylabel('y-axis') # space between the plotsplt.tight_layout() # show plotplt.show() Output: To increase the size of the plots we can write like this plt.subplots(figsize(l, b)) Example 3: Python3 # importing librariesimport numpy as npimport matplotlib.pyplot as plt # creating an array of data for x-axisx = np.array([2, 4, 6, 8, 10, 12, 14, 16, 18, 20]) # data for y-axisy_1 = 2*x # dat for y-axis for another ploty_2 = 3*x # figsize() function to adjust the size# og functionplt.subplots(figsize=(15, 5)) # using subplot function and creating# plot oneplt.subplot(1, 2, 1)plt.plot(x, y_1, 'r', linewidth=5, linestyle=':')plt.title('FIRST PLOT')plt.xlabel('x-axis')plt.ylabel('y-axis') # using subplot function and creating plot twoplt.subplot(1, 2, 2)plt.plot(x, y_2, 'g', linewidth=5)plt.title('SECOND PLOT')plt.xlabel('x-axis')plt.ylabel('y-axis') # space between the plotsplt.tight_layout(4) # show plotplt.show() Output: anikakapoor kalrap615 Picked Python-matplotlib Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n19 Aug, 2021" }, { "code": null, "e": 25779, "s": 25537, "text": "Matplotlib is the most popular Python library for plotting graphs and visualizing our data. In Matplotlib we can create multiple plots by calling them once. To cre...
LinkedList set() Method in Java - GeeksforGeeks
10 Dec, 2018 The Java.util.LinkedList.set() method is used to replace any particular element in the linked list created using the LinkedList class with another element. This can be done by specifying the position of the element to be replaced and the new element in the parameter of the set() method. Syntax: LinkedList.set(int index, Object element) Parameters: This function accepts two parameters as shown in the above syntax and described below. index: This is of integer type and refers to the position of the element that is to be replaced from the linked list. element: It is the new element by which the existing element will be replaced and is of the same object type as the linked list. Return Value: The method returns the previous value from the linked list that is replaced with the new value. Below program illustrate the Java.util.LinkedList.set() method: // Java code to illustrate set()import java.io.*;import java.util.LinkedList; public class LinkedListDemo { public static void main(String args[]) { // Creating an empty LinkedList LinkedList<String> list = new LinkedList<String>(); // Use add() method to add elements in the list list.add("Geeks"); list.add("for"); list.add("Geeks"); list.add("10"); list.add("20"); // Displaying the linkedlist System.out.println("LinkedList:" + list); // Using set() method to replace Geeks with GFG System.out.println("The Object that is replaced is: " + list.set(2, "GFG")); // Using set() method to replace 20 with 50 System.out.println("The Object that is replaced is: " + list.set(4, "50")); // Displaying the modified linkedlist System.out.println("The new LinkedList is:" + list); }} LinkedList:[Geeks, for, Geeks, 10, 20] The Object that is replaced is: Geeks The Object that is replaced is: 20 The new LinkedList is:[Geeks, for, GFG, 10, 50] Java - util package Java-Collections Java-Functions java-LinkedList Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Stream In Java Interfaces in Java How to iterate any Map in Java Initialize an ArrayList in Java Stack Class in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java
[ { "code": null, "e": 25719, "s": 25691, "text": "\n10 Dec, 2018" }, { "code": null, "e": 26007, "s": 25719, "text": "The Java.util.LinkedList.set() method is used to replace any particular element in the linked list created using the LinkedList class with another element. This ca...
Iterator Pattern - GeeksforGeeks
08 Apr, 2022 Iterator Pattern is a relatively simple and frequently used design pattern. There are a lot of data structures/collections available in every language. Each collection must provide an iterator that lets it iterate through its objects. However while doing so it should make sure that it does not expose its implementation. Suppose we are building an application that requires us to maintain a list of notifications. Eventually, some part of your code will require to iterate over all notifications. If we implemented your collection of notifications as array you would iterate over them as: // If a simple array is used to store notifications for (int i = 0; i < notificationList.length; i++) Notification notification = notificationList[i]); // If ArrayList is Java is used, then we would iterate // over them as: for (int i = 0; i < notificationList.size(); i++) Notification notification = (Notification)notificationList.get(i); And if it were some other collection like set, tree etc. way of iterating would change slightly. Now, what if we build an iterator that provides a generic way of iterating over a collection independent of its type. // Create an iterator Iterator iterator = notificationList.createIterator(); // It wouldn’t matter if list is Array or ArrayList or // anything else. while (iterator.hasNext()) { Notification notification = iterator.next()); } Iterator pattern lets us do just that. Formally it is defined as below: The iterator pattern provides a way to access the elements of an aggregate object without exposing its underlying representation. Class Diagram: Here we have a common interface Aggregate for client as it decouples it from the implementation of your collection of objects. The ConcreteAggregate implements createIterator() that returns iterator for its collection. Each ConcreteAggregate’s responsibility is to instantiate a ConcreteIterator that can iterate over its collection of objects. The iterator interface provides a set of methods for traversing or modifying the collection that is in addition to next()/hasNext() it can also provide functions for search, remove etc. Let’s understand this through an example. Suppose we are creating a notification bar in our application that displays all the notifications which are held in a notification collection. NotificationCollection provides an iterator to iterate over its elements without exposing how it has implemented the collection (array in this case) to the Client (NotificationBar). The class diagram would be: Below is the Java implementation of the same: Java // A Java program to demonstrate implementation// of iterator pattern with the example of// notifications // A simple Notification classclass Notification{ // To store notification message String notification; public Notification(String notification) { this.notification = notification; } public String getNotification() { return notification; }} // Collection interfaceinterface Collection{ public Iterator createIterator();} // Collection of notificationsclass NotificationCollection implements Collection{ static final int MAX_ITEMS = 6; int numberOfItems = 0; Notification[] notificationList; public NotificationCollection() { notificationList = new Notification[MAX_ITEMS]; // Let us add some dummy notifications addItem("Notification 1"); addItem("Notification 2"); addItem("Notification 3"); } public void addItem(String str) { Notification notification = new Notification(str); if (numberOfItems >= MAX_ITEMS) System.err.println("Full"); else { notificationList[numberOfItems] = notification; numberOfItems = numberOfItems + 1; } } public Iterator createIterator() { return new NotificationIterator(notificationList); }} // We could also use Java.Util.Iteratorinterface Iterator{ // indicates whether there are more elements to // iterate over boolean hasNext(); // returns the next element Object next();} // Notification iteratorclass NotificationIterator implements Iterator{ Notification[] notificationList; // maintains curr pos of iterator over the array int pos = 0; // Constructor takes the array of notificationList are // going to iterate over. public NotificationIterator (Notification[] notificationList) { this.notificationList = notificationList; } public Object next() { // return next element in the array and increment pos Notification notification = notificationList[pos]; pos += 1; return notification; } public boolean hasNext() { if (pos >= notificationList.length || notificationList[pos] == null) return false; else return true; }} // Contains collection of notifications as an object of// NotificationCollectionclass NotificationBar{ NotificationCollection notifications; public NotificationBar(NotificationCollection notifications) { this.notifications = notifications; } public void printNotifications() { Iterator iterator = notifications.createIterator(); System.out.println("-------NOTIFICATION BAR------------"); while (iterator.hasNext()) { Notification n = (Notification)iterator.next(); System.out.println(n.getNotification()); } }} // Driver classclass Main{ public static void main(String args[]) { NotificationCollection nc = new NotificationCollection(); NotificationBar nb = new NotificationBar(nc); nb.printNotifications(); }} Output: -------NOTIFICATION BAR------------ Notification 1 Notification 2 Notification 3 Notice that if we would have used ArrayList instead of Array there will not be any change in the client (notification bar) code due to the decoupling achieved by the use of iterator interface. Further Read – Iterator Method in Python References: Head First Design Patterns This article is contributed by Sulabh Kumar.If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Shraddhesh Bhandari creatsiv simmytarika5 Design Pattern Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Unified Modeling Language (UML) | An Introduction Unified Modeling Language (UML) | State Diagrams Abstract Factory Pattern Composite Design Pattern Observer Pattern | Set 1 (Introduction) Monolithic vs Microservices architecture Unified Modeling Language (UML) | Class Diagrams Singleton Design Pattern | Introduction How to design a parking lot using object-oriented principles? Chain of Responsibility Design Pattern
[ { "code": null, "e": 25803, "s": 25775, "text": "\n08 Apr, 2022" }, { "code": null, "e": 26393, "s": 25803, "text": "Iterator Pattern is a relatively simple and frequently used design pattern. There are a lot of data structures/collections available in every language. Each collec...
Subarrays with sum K | Practice | GeeksforGeeks
Given an unsorted array of integers, find the number of continuous subarrays having sum exactly equal to a given number k. Example 1: Input: N = 5 Arr = {10 , 2, -2, -20, 10} k = -10 Output: 3 Explaination: Subarrays: arr[0...3], arr[1...4], arr[3..4] have sum exactly equal to -10. Example 2: Input: N = 6 Arr = {9, 4, 20, 3, 10, 5} k = 33 Output: 2 Explaination: Subarrays : arr[0...2], arr[2...4] have sum exactly equal to 33. Your Task: You don't need to read input or print anything. Your task is to complete the function findSubArraySum() which takes the array Arr[] and its size N and k as input parameters and returns the count of subarrays. Expected Time Complexity: O(NlogN) Expected Auxiliary Space: O(N) Constraints: 1 ≤ N ≤ 2*104 -103 ≤ Arr[i] ≤ 103 -107 ≤ k ≤ 107 0 dipeshmakwane2 weeks ago //Using hashing //O(N) solution and O(N) space int findSubArraySum(int Arr[], int N, int k) { // code here int pre_sum=0; int count=0; unordered_map<int,int>um; for(int i=0;i<N;i++){ pre_sum+=Arr[i]; um[pre_sum]++; if(pre_sum==k){ count++; } if(um.count(pre_sum-k)==1){ count+=um[pre_sum-k]; } } return count; } 0 siddhant073 weeks ago //Using hashing //O(N) solution and O(N) space int findSubArraySum(int Arr[], int N, int k) { unordered_map< int, int> mp; mp[0] = 1; int cnt = 0; int curr = 0; for(int i = 0; i < N; i++){ curr += Arr[i]; cnt += mp[curr - k]; mp[curr]++; } return cnt; } 0 itachinamikaze2211 month ago JAVA static int findSubArraySum(int Arr[], int N, int k) { HashMap<Integer, Integer> map =new HashMap<>(); int c=0; int sum=0; map.put(sum, 1); for(int i=0;i<Arr.length;i++) { sum=sum+Arr[i]; if(map.containsKey(sum-k)) { c=c+map.get(sum-k); } map.put(sum, map.getOrDefault(sum,0)+1); } return c; } 0 sy9924551 month ago class Solution { static int findSubArraySum(int arr[], int n, int k) { HashMap<Integer,Integer> map = new HashMap<>(); map.put(0,1); int currSum = 0; int cnt = 0; for(int i=0;i<n;i++){ currSum+=arr[i]; if(map.containsKey(currSum-k)){ cnt+=map.get(currSum-k); } map.put(currSum , map.getOrDefault(currSum,0)+1); } return cnt; } } 0 amanasati11 month ago Here, we will be using a dictionary which if a key not present in it. Instead of raising the error, it will automatically creates the key and raises its value to 0. Defaultdict is a module in collections library with same features mentioned above. Python code: from collections import defaultdict class Solution: def findSubArraySum(self, Arr, N, k): # code here dic=defaultdict(lambda:0) l,i,s=0,0,0 #l= count, s=sum while i<N: s+=Arr[i] if s==k: l+=1 if s-k in dic: l+=dic[s-k] dic[s]+=1 i+=1 return l 0 samad11 month ago My Approach (1.2/4.4 ):Why Do we Have to use HashTable:Let us Consider a subarray within the array whose sum is let say ‘x’ and a subarray starting just after this subarray sums up to k , a[i,j]=x & a[j+1,l]=k (l be any positive number ≥ j+1 and less than the size of array) so a[i,l]=x+k.Main observation to take from here is if take the sum form the starting index and store in a hashmap for every index i and also check for every index if ‘sum-k’ is already present in the subarray or not (x+k-k→x) ,sum-k would have been present in the map if and only if my current value is x+k hence we'll be able to consider all the subarrays , the last point which we have to to take care is that there can be more than 1 ‘x’ in the array while taking the sum as our array contains negative values so we have to count all those x's in our answer , that's why we use a map instead of a set to also keep the count of x's we have previously encountered and then add it to the answer. class Solution { static int findSubArraySum(int Arr[], int N, int k) { // code here HashMap<Integer,Integer> hm=new HashMap<>(); hm.put(0,1); int sum=0,cnt=0; for(int i=0;i<Arr.length;i++){ sum+=Arr[i]; if( hm.containsKey(sum-k))cnt+=hm.get(sum-k); if(hm.containsKey(sum))hm.put(sum,hm.get(sum)+1); else hm.put(sum,1); } return cnt; } } 0 gargnipungarg2 months ago class Solution{ static int findSubArraySum(int nums[], int N, int k) { // code here Map<Integer , Integer> freq = new HashMap<>(); int count=0, sum=0; for(int i=0; i<nums.length ; i++){ sum+=nums[i]; if(sum==k) count++; //if sum equals target if(freq.get(sum-k)!=null) count+= freq.get(sum-k); //to find middle subarrays freq.put(sum, freq.getOrDefault(sum, 0)+1); } return count; }} +1 kashyapjhon2 months ago C++ Solution Time=(1.3/3.7): int findSubArraySum(int Arr[], int N, int k) { // code here unordered_map<int,int> u; int c=0; u.insert({0,1}); int pre[N]; pre[0]=Arr[0]; for(int i=1;i<N;i++){ pre[i]=pre[i-1]+Arr[i]; } for(int i=0;i<N;i++){ auto it=u.find(pre[i]-k); if(it!=u.end()){ c=c+it->second; } u[pre[i]]++; } return c; } 0 anandkumarsatapathy2 months ago Very Easy int c= 0; unordered_map<int,int> m; int sum=0; for(int i = 0;i<n;i++){ sum+=nums[i]; if(sum==k) c++; if(m.find(sum-k)!=m.end()) c+=m[sum-k]; m[sum]++; } return c; +1 gulshan992 months ago int findSubArraySum(int Arr[], int N, int k) { // code here int sum=0; int count=0; unordered_map<int,int>mp; for(int i=0;i<N;i++) { sum+=Arr[i]; if(sum==k)count++; if(mp[sum-k]) count+=mp[sum-k]; mp[sum]++; } return count; } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 361, "s": 238, "text": "Given an unsorted array of integers, find the number of continuous subarrays having sum exactly equal to a given number k." }, { "code": null, "e": 373, "s": 361, "text": "\nExample 1:" }, { "code": null, "e": 523, "s":...
Network Analysis of the Romance of Three Kingdoms | by Dimitris Manolidis | Towards Data Science
Recently, I posted an article about the social networks of the 14th-century novel Romance of Three Kingdoms. In the article, I discuss the social networks which emerge when analyzing the interactions of the characters of the novel. Furthermore, with the use of centrality measures, I determine who the most influential characters are. The article is non-technical and some of the details of my analysis are left out. Here, I present the code behind the analysis and discuss further the technical details of the social networks of the novel. Moreover, this code can be used (with minor modifications) to apply a similar analysis to other novels or pieces of text. My analysis was inspired by the network analysis of Game of Thrones, by Andrew Beveridge and Jie Shan. Both works of literature have an intricate plot and a large number of characters. This makes Romance of Three Kingdoms a good candidate for such analysis. Before starting my analysis of Romance of Three Kingdoms, there were some initial decisions I had to make. Characters: The first decision was which characters to include in my analysis. There are over a thousand characters appearing in the novel. For the reader to be able to follow the characters more closely, only 70 characters were selected. To select the characters, I used the following procedure. First, I selected 100 characters whose names appear the most throughout the novel. Then, I made a list of characters that appear the most in websites and articles about the novel, the characters that appeared in the series and even some characters I personally considered important. I compared the lists and manually selected which characters I was going to keep for my final list. Sections: Another decision I made, was to analyze the novel in sections. The volume of the novel is great. It includes 120 chapters and the English translated version contains more than 500,000 words. I decided that, to better follow the interactions of the characters, I should divide the novel into groups of chapters and analyze each group separately, before analyzing the full text. Since chapters are similar in length, I decided to create groups of 30 chapters, making a total of 4 groups. In the end, I also processed the whole novel, to get the grand network of all characters. With the use of bash scripts, I concatenated the chapters in groups of 30 in separate files, plus one file with the full text. Next, I created the python script which would take a text file as input and produce a graph object as output. Then, I could further process the graph with a tool like Gephi to create beautiful network visualizations. We start by importing our file and removing any special characters, as the initial text had a lot of them import rewith open(infile, 'r') as file: data = file.read().replace('\n', ' ')text = re.sub('[^A-Za-z0–9]+', ' ', data) Next, we need to create a list of tokens from our text. Python’s nltk library can do that for us easily. Also, we remove stop words from our tokens import nltkstopWords = nltk.corpus.stopwords.words('english')def wordTokens(text, stop_words): wtokens = nltk.word_tokenize(text.lower()) wtokens = [w for w in wtokens if w not in stop_words]return wtokens Since the names we are looking for in the text all consist of two words, we want to create bigrams. This is again really easy with the help of nltk bigrm = nltk.bigrams(tokens)bigrms = list(bigrm) If there were one-word names or names with more than two words, we could generalize the code by including the initial tokens, as well as trigrams or any other n-grams. Finally, we create tuples from our characters list, to be directly comparable to the bigrams def char_tuple_f(chars_list): char_tuples_list = [] for char in chars: tup = tuple(char.split(" ")) char_tuples_list.append(tup)return char_tuples_list Our ultimate goal is to analyze the interactions the characters have with each other. But what counts as an interaction? Here, I followed Beveridge and Shan and counted an interaction between two characters when their names appear in the novel within 15 words of each other. Actually, the number of words, the “word distance” of the characters, can be a variable itself. After experimenting with various values, 15 seemed as a value which gave good results. We create a dictionary with the names of the characters as keys. The values of each key are a numpy array of all the indexes where the character’s name appears in the bigrams list. def indices_dic(char_tuples, bigr): dic = {} for tup in char_tuples: char_name = " ".join(tup) indices = [i for i, x in enumerate(bigr) if x == tup] dic[char_name] = np.array(indices) return dic Then, for each character in the above dictionary, we take the difference of the character’s indexes with every other character indexes. If that difference is lower than some threshold (usually 15), we count that as one interaction between the characters. Here, the vectorization of numpy significantly speeds up the code. Finally, we add all the interactions of each character to a dictionary. We only consider characters that have more than 3 interactions. This is done for the following reason. Sometimes, the name of a character at the end of a paragraph/line and the name of the character at the beginning of the next paragraph/line may appear within our threshold, even though the characters don’t really interact with each other. Such occurrences usually happen randomly and the probability of them happening for the same characters more than three times is low. On the other hand, if two characters truly interact with each other, they will have more than 3 interactions def links_dic_f(indices_dic, threshold): link_dic = {} for first_char, ind_arr1 in indices_dic.items(): dic = {} for second_char, ind_arr2 in indices_dic.items(): if first_char == second_char: continuematr = np.abs(ind_arr1[np.newaxis].T - ind_arr2) <= threshold s = np.sum(matr) if s > 3: dic[second_char] = s link_dic[first_char] = dic return link_dic This part of the code could probably be optimized further. Nevertheless, for the size of the text I was analyzing, the code ran almost instantly and I didn’t feel the need for further optimization. Since we are using the same list of characters for all sections of the novel, it is possible that some characters don’t appear, or don’t interact with anyone in certain sections. This is already taken care of in the interactions dictionary, but we would like to remove them from the characters list as well. This way, we will not have isolated nodes with no edges in our graph. def remove_zero_link_chars(inter_dic, chars_list): rem_set = set() for key in inter_dic: if inter_dic[key] == {}: rem_set.add(key) fin_list = [char for char in chars_list if char not in rem_set] return fin_list Now that we have a dictionary with the number of interactions of all characters, we are ready to create a graph representing our characters’ network. We are going to use the networkx library to create the graph. networkx expects the nodes of the graph as a list. We already have that, it is the list of our characters. Also, it expects the edges of the graph to be given as a tuple of two nodes plus a value for the weight of the edge. We create those tuples as follows def edge_tuples_f(link_dic): edges_tuples = [] for key in link_dic: for item, value in link_dic[key].items(): tup = (key.title(), item.title(), value) edges_tuples.append(tup)return edges_tuples When we have both lists, creating the graph is extremely simple with networkx import networkx as nxG = nx.Graph()G.add_nodes_from(node_chars)G.add_weighted_edges_from(edges_tuples) Finally, we want to detect communities that exist within our graph. Communities are subsets of our graph, the members of which interact more with each other than with members of other communities. The algorithm behind community detection is beyond the scope of this article. Nevertheless, we want to show that the python module community can accomplish this, with just one line of code. We add this partition as an attribute to the nodes of the graph. This can be used later by Gephi, to group the nodes. import communitypartition = community.best_partition(G)nx.set_node_attributes(G, partition, ‘group’) We export the graph as a .gexf file nx.write_gexf(G, outfile) Using Gephi, we can produce beautiful visualizations of our graphs. The main point when creating the network in Gephi is that I use the Force Atlas layout. Also, I use the community groups for the color of the nodes and the number of edges to determine the size of the nodes. In order to find the most influential character of the novel, we look at the centrality measures. We calculate three different centralities. Degree centrality is defined as the number of edges of each node. A node, or a character in our case, with more edges, is considered more influential Betweenness centrality shows how many times a node is found within the shortest path of two other nodes. Practically, it identifies the character Eigenvector centrality measures the importance of nodes based on their connections, but connections to other important nodes contribute more than connections to unimportant nodes. It identifies the characters that interact with powerful characters. We use all three centralities to calculate the importance of a character. Since we cannot directly compare different centralities, at the end, our assertion will be qualitative. Nevertheless, for characters of a novel, we consider someone who is connected with more important characters to be more influential than someone who has connections with minor characters. Thus, we consider the eigenvector centrality more decisive of a character’s importance than the other two centralities. Moreover, in our calculations, the eigenvector centrality takes into account the weight of the edges. The networkx library includes algorithms to calculate all three centralities. We create a pandas data frame with the centralities of each node. def calc_centralities(graph): dgc = nx.degree_centrality(graph) dgc = pd.DataFrame.from_dict(dgc, orient='index', columns=["DGC"]) btc = nx.betweenness_centrality(graph) btc = pd.DataFrame.from_dict(btc, orient='index', columns=["BTC"]) evc = nx.eigenvector_centrality(graph, weight='weight') evc = pd.DataFrame.from_dict(evc, orient='index', columns=["EVC"])df = pd.concat([dgc, btc, evc], axis=1) return dfdf = calc_centralities(G) Finally, we create a plot with the top 10 characters for all three centralities import matplotlib.pyplot as pltdef plot_centrality(centr, df, title, n, col_list): ax = plt.subplot(1, 3, n) s = df.sort_values(centr, ascending=False)[:10] x = list(s[centr].index)[::-1] y = list(s[centr])[::-1] for i, v in enumerate(y): bars = plt.barh(x[i], v, color=col_list[n-1]) plt.title(title, size=22) ax.get_xaxis().set_visible(False) ax.spines['top'].set_visible(False) ax.spines['bottom'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['left'].set_visible(False) ax.tick_params(axis='y', length = 0, labelsize=14)col_list = ["peachpuff", "plum", "orange"]fig, ax = plt.subplots(1,3, figsize=(15, 10))plot_centrality("DGC", df, 'Degree Centrality', 1, col_list)plot_centrality("BTC", df, 'Betweeness Centrality', 2, col_list)plot_centrality("EVC", df, 'Eigenvector Centrality', 3, col_list)plt.savefig(figfile_centr, dpi=300) Of course, for one of the colors of the graph, we use “peachpuff”, which reminds me of the oath at the peach garden. The full jupyter notebook can be found here. The results of the analysis can be found in this article.
[ { "code": null, "e": 588, "s": 171, "text": "Recently, I posted an article about the social networks of the 14th-century novel Romance of Three Kingdoms. In the article, I discuss the social networks which emerge when analyzing the interactions of the characters of the novel. Furthermore, with the u...
C library function - isgraph()
The C library function int isgraph(int c) checks if the character has graphical representation. The characters with graphical representations are all those characters that can be printed except for whitespace characters (like ' '), which is not considered as isgraph characters. Following is the declaration for isgraph() function. int isgraph(int c); c − This is the character to be checked. c − This is the character to be checked. This function returns non-zero value if c has a graphical representation as character, else it returns 0. The following example shows the usage of isgraph() function. #include <stdio.h> #include <ctype.h> int main () { int var1 = '3'; int var2 = 'm'; int var3 = ' '; if( isgraph(var1) ) { printf("var1 = |%c| can be printed\n", var1 ); } else { printf("var1 = |%c| can't be printed\n", var1 ); } if( isgraph(var2) ) { printf("var2 = |%c| can be printed\n", var2 ); } else { printf("var2 = |%c| can't be printed\n", var2 ); } if( isgraph(var3) ) { printf("var3 = |%c| can be printed\n", var3 ); } else { printf("var3 = |%c| can't be printed\n", var3 ); } return(0); } Let us compile and run the above program to produce the following result − var1 = |3| can be printed var2 = |m| can be printed var3 = | | can't be printed 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": 2103, "s": 2007, "text": "The C library function int isgraph(int c) checks if the character has graphical representation." }, { "code": null, "e": 2286, "s": 2103, "text": "The characters with graphical representations are all those characters that can be pri...
\nrightarrow - Tex Command
\nrightarrow - Used to create nrightarrow symbol. { \nrightarrow} \nrightarrow command draws nrightarrow symbol. \nrightarrow ↛ \nrightarrow ↛ \nrightarrow 14 Lectures 52 mins Ashraf Said 11 Lectures 1 hours Ashraf Said 9 Lectures 1 hours Emenwa Global, Ejike IfeanyiChukwu 29 Lectures 2.5 hours Mohammad Nauman 14 Lectures 1 hours Daniel Stern 15 Lectures 47 mins Nishant Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 8036, "s": 7986, "text": "\\nrightarrow - Used to create nrightarrow symbol." }, { "code": null, "e": 8052, "s": 8036, "text": "{ \\nrightarrow}" }, { "code": null, "e": 8099, "s": 8052, "text": "\\nrightarrow command draws nrightarrow sym...
PHP | preg_replace() Function - GeeksforGeeks
26 Jul, 2019 The preg_replace() function is an inbuilt function in PHP which is used to perform a regular expression for search and replace the content. Syntax: preg_replace( $pattern, $replacement, $subject, $limit, $count ) Parameters: This function accepts five parameters as mention above and describe below. $pattern: This parameter contains the string element which is used to search the content and it can be a string or array of string. $replacement: It is mandatory parameter which specifies the string or an array with strings to replace. $subject: The string or an array with strings to search and replace. $limit: This parameter specifies the maximum possible replacements for each pattern. $count: It is optional parameter. This variable will be filled with the number of replacements done. Return Value: This function returns an array if the subject parameter is an array, or a string otherwise. Below programs illustrate the preg_replace() function in PHP: Program 1: <?php // PHP program to illustrate // preg_replace function $string = 'November 01, 2018';$pattern = '/(\w+) (\d+), (\d+)/i';$replacement = '${1} 02, $3'; // print output of functionecho preg_replace($pattern, $replacement, $string);?> November 02, 2018 Program 2 : <?php // PHP program to illustrate // preg_replace function$subject = array('1', 'GFG', '2','Geeks', '3', 'GCET', 'Contribute', '4'); $pattern = array('/\d/', '/[a-z]/', '/[1a]/'); $replace = array('X:$0', 'Y:$0', 'Z:$0'); // Print Result return by functionecho "preg_replace returns\n";print_r(preg_replace($pattern, $replace, $subject)); ?> preg_replace returns Array ( [0] => X:Z:1 [1] => GFG [2] => X:2 [3] => GY:eY:eY:kY:s [4] => X:3 [5] => GCET [6] => CY:oY:nY:tY:rY:iY:bY:uY:tY:e [7] => X:4 ) Program 3: <?php // PHP program to illustrate // preg_replace function$count = 0; // Display result after replace and count echo preg_replace(array('/\d/', '/\s/'), '*', 'Geeks 4 Geeks', -1, $count);echo "\n" . $count;?> Geeks***Geeks 3 Reference: http://php.net/manual/en/function.preg-replace.php Akanksha_Rai PHP-function PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? PHP | Converting string to Date and DateTime Comparing two dates in PHP How to receive JSON POST with PHP ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26293, "s": 26265, "text": "\n26 Jul, 2019" }, { "code": null, "e": 26433, "s": 26293, "text": "The preg_replace() function is an inbuilt function in PHP which is used to perform a regular expression for search and replace the content." }, { "code": n...
re.MatchObject.group() function in Python Regex - GeeksforGeeks
27 May, 2021 re.MatchObject.group() method returns the complete matched subgroup by default or a tuple of matched subgroups depending on the number of arguments Syntax: re.MatchObject.group([group]) Parameter: group: (optional) group defaults to zero (meaning that it it will return the complete matched string). Return -1 if group exists but did not contribute to the match. Return: Complete match by default else one or more matched subgroups depending on the arguments. IndexError: If the group number passed as argument is negative or greater than the number of groups defined in the match pattern then an IndexError exception will be raised AttributeError: If a matching pattern is not found then it raise AttributeError. Consider the below example: Example 1: A program to print the username, company_name and domain from a emailID Python3 import re """We create a re.MatchObject and store it in match_object variable the '()' parenthesis are used to define a specific group""" match_object = re.match(r'(\w+)@(\w+)\.(\w+)', 'username@geekforgeeks.org') """ w in above pattern stands for alphabetical character + is used to match a consecutive set of characters satisfying a given condition so w+ will match a consecutive set of alphabetical characters""" # for entire matchprint(match_object.group())# also print(match_object.group(0)) can be used # for the first parenthesized subgroupprint(match_object.group(1)) # for the second parenthesized subgroupprint(match_object.group(2)) # for the third parenthesized subgroupprint(match_object.group(3)) # for a tuple of all matched subgroupsprint(match_object.group(1, 2, 3)) Output: username@geekforgeeks.org username geekforgeeks org ('username', 'geekforgeeks', 'org') It’s time to understand the above program. We use a re.match() method to find a match in the given string(‘username@geekforgeeks.org‘) the ‘w‘ indicates that we are searching for an alphabetical character and the ‘+‘ indicates that we are searching for continuous alphabetical characters in the given string. Note the use of ‘()‘ the parenthesis is used to define different subgroups, in the above example, we have three subgroups in the match pattern. The result we get is a re.MatchObject which is stored in match_object. Note: To know more about regex patterns refer Python regex Depending on the arguments passed the group method returns us different strings and also it returns a tuple of matched strings. Example 2: If we pass an invalid group number in the method argument then we will get an IndexError exception. Python3 import re """We create a re.MatchObject and store it in match_object variable the '()' parenthesis are used to define a specific group""" match_object = re.match(r'(\w+)@(\w+)\.(\w+)', 'username@geekforgeeks.org') """ w in above pattern stands for alphabetical character + is used to match a consecutive set of characters satisfying a given condition so w+ will match a consecutive set of alphabetical characters""" # Following line will raise IndexError exceptionprint(match_object.group(7)) Output: Traceback (most recent call last): File "/home/8da42759204c98da7baa88422a4a74e0.py", line 17, in print(match_object.group(7)) IndexError: no such group simranarora5sos python-regex Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25718, "s": 25690, "text": "\n27 May, 2021" }, { "code": null, "e": 25866, "s": 25718, "text": "re.MatchObject.group() method returns the complete matched subgroup by default or a tuple of matched subgroups depending on the number of arguments" }, { "...
How to get cookies from curl into a variable in PHP ? - GeeksforGeeks
31 Dec, 2019 The cURL standing for Client URL refers to a library for transferring data using various protocols supporting cookies, HTTP, FTP, IMAP, POP3, HTTPS (with SSL Certification), etc. This example will illustrate how to get cookies from a PHP cURL into a variable. The functions provide an option to set a callback that will be called for each response header line. The function will receive the curl object and a string with the header line. Along with their purpose, required for this example are described below: curl_init(): Used to initialize a curl object. curl_setopt(object, parameter, value): Used to set the value of parameter for a certain curl object. curl_exec(object): Used to execute the current curl session. Called after setting the values for desired curl parameters. preg_match_all(regExp, inputVariable, OutputVariable): Used to perform a global regular expression check. Example 1: This example illustrates how to fetch cookies from www.amazon.com <?php // URL to fetch cookies$url = "https://www.amazon.com/"; // Initialize cURL object$curlObj = curl_init(); /* setting values to required cURL parameters.CURLOPT_URL is used to set the URL to fetch CURLOPT_RETURNTRANSFER is enabled curlresponse to be saved in a variable CURLOPT_HEADER enables curl to includeprotocol header CURLOPT_SSL_VERIFYPEERenables to fetch SSL encrypted HTTPS request.*/curl_setopt($curlObj, CURLOPT_URL, $url);curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1);curl_setopt($curlObj, CURLOPT_HEADER, 1);curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, false);$result = curl_exec($curlObj); // Matching the response to extract cookie valuepreg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $result, $match_found); $cookies = array();foreach($match_found[1] as $item) { parse_str($item, $cookie); $cookies = array_merge($cookies, $cookie);} // Printing cookie dataprint_r( $cookies); // Closing curl object instancecurl_close($curlObj);?> Note: Each website has its own format of storing cookies according to its requirements. Therefore, any specific format is not available for cookies.Output: Example 2: This example illustrates how to fetch cookies from www.google.com <?php $url = "https://www.google.com/";$curlObj = curl_init(); curl_setopt($curlObj, CURLOPT_URL, $url);curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1);curl_setopt($curlObj, CURLOPT_HEADER, 1);curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, false);$result = curl_exec($curlObj); preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $result, $match_found);$cookies = array(); foreach($match_found[1] as $item) { parse_str($item, $cookie); $cookies = array_merge($cookies, $cookie);} print_r( $cookies);curl_close($curlObj);?> Output: Note: Personal data is blurred out. PHP-cURL PHP-Misc Picked PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to Upload Image into Database and Display it using PHP ? How to check whether an array is empty using PHP? PHP | Converting string to Date and DateTime Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25743, "s": 25715, "text": "\n31 Dec, 2019" }, { "code": null, "e": 26254, "s": 25743, "text": "The cURL standing for Client URL refers to a library for transferring data using various protocols supporting cookies, HTTP, FTP, IMAP, POP3, HTTPS (with SSL Certi...
How to Remove Column from HTML Table using JavaScript ? - GeeksforGeeks
20 May, 2020 Given an HTML table and the task is to remove the certain column from the HTML table. There are two approaches that are discussed below: Approach 1: First, select the table and also get the rows of table using table.rows. Get the number of columns of a row and go through each one of the columns. Use str.search(“someColumnName”) (Because, we want to remove the column with some columnName) to match the current column name and the column name that we want to remove. If the column name matches then delete its every cell by .deleteCell(i) method (where, i is the column index) by traversing the each row of the table. Example: This example implements the above approach. <!DOCTYPE HTML><html> <head> <title> How to Remove Column from HTML Table using JavaScript ? </title> <style> #myCol { background: green; } table { color: white; margin: 0 auto; } td { padding: 10px; } </style></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <table id="table"> <colgroup> <col id="myCol" span="2"> <col style="background-color:green"> </colgroup> <tr> <th>S.No</th> <th>Title</th> <th>Geek_id</th> </tr> <tr> <td>Geek_1</td> <td>GeekForGeeks</td> <th>Geek_id_1</th> </tr> <tr> <td>Geek_2</td> <td>GeeksForGeeks</td> <th>Geek_id_2</th> </tr> </table> <br> <button onclick="Geeks()"> Click here </button> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> function Geeks() { var el_down = document.getElementById("GFG_DOWN"); var tble = document.getElementById('table'); var row = tble.rows; // Getting the rows for (var i = 0; i < row[0].cells.length; i++) { // Getting the text of columnName var str = row[0].cells[i].innerHTML; // If 'Geek_id' matches with the columnName if (str.search("Geek_id") != -1) { for (var j = 0; j < row.length; j++) { // Deleting the ith cell of each row row[j].deleteCell(i); } } } el_down.innerHTML = "Column is removed from the table."; } </script></body> </html> Output: Approach 2: Select the table and get the rows of table using table.rows to traverse through the whole table. Get the column index in a variable (Column that we want to remove). Delete each cell by .deleteCell(i) method(where, i is the column index) by traversing the each row of the table. Example: This example implements the above approach. <!DOCTYPE HTML><html> <head> <title> How to Remove Column from HTML Table using JavaScript ? </title> <style> #myCol { background: green; } table { color: white; margin: 0 auto; } td { padding: 10px; } </style></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <table id="table"> <colgroup> <col id="myCol" span="2"> <col style="background-color:green"> </colgroup> <tr> <th>S.No</th> <th>Title</th> <th>Geek_id</th> </tr> <tr> <td>Geek_1</td> <td>GeekForGeeks</td> <th>Geek_id_1</th> </tr> <tr> <td>Geek_2</td> <td>GeeksForGeeks</td> <th>Geek_id_2</th> </tr> </table> <br> <button onclick="Geeks()"> Click here </button> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> function Geeks() { var el_down = document.getElementById("GFG_DOWN"); // Getting the table var tble = document.getElementById('table'); // Getting the rows in table. var row = tble.rows; // Removing the column at index(1). var i = 1; for (var j = 0; j < row.length; j++) { // Deleting the ith cell of each row. row[j].deleteCell(i); } el_down.innerHTML = "Column is removed from the table."; } </script></body> </html> Output: CSS-Misc HTML-Misc JavaScript-Misc CSS HTML JavaScript Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to apply style to parent if it has child with CSS? Types of CSS (Cascading Style Sheet) How to position a div at the bottom of its container using CSS? Design a web page using HTML and CSS How to set space between the flexbox ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction) How to Insert Form Data into Database using PHP ?
[ { "code": null, "e": 26033, "s": 26005, "text": "\n20 May, 2020" }, { "code": null, "e": 26170, "s": 26033, "text": "Given an HTML table and the task is to remove the certain column from the HTML table. There are two approaches that are discussed below:" }, { "code": null...
Google Search Automation with Python Selenium
We can perform Google search automation with Selenium webdriver in Python. First of all, we shall locate the Google search box with the help of any of the locators like id, css, xpath, class, or name. Then simulate the action of pressing the ENTER key with the help of Keys.ENTER/Keys.RETURN. To perform this operation, we have to use the method send_keys and then pass the parameter – Keys.RETURN /Keys.ENTER. Also, we have to add the statement - from selenium.webdriver.common.keys import Keys to use the Keys class. from selenium import webdriver from selenium.webdriver.common.keys import Keys import time #set chromodriver.exe path driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe") driver.implicitly_wait(0.5) #launch URL driver.get("https://www.google.com/") #identify search box m = driver.find_element_by_name("q") #enter search text m.send_keys("Tutorialspoint") time.sleep(0.2) #perform Google search with Keys.ENTER m.send_keys(Keys.ENTER)
[ { "code": null, "e": 1263, "s": 1062, "text": "We can perform Google search automation with Selenium webdriver in Python. First of all, we shall locate the Google search box with the help of any of the locators like id, css, xpath, class, or name." }, { "code": null, "e": 1581, "s": ...
Generate Sports Rankings with Data Science | by Percy Jaiswal | Towards Data Science
In this tutorial, we will go through one very popular algorithm used in generating rankings for sports teams. The method which we will be studying is called Colley Ratings. Before going into depth, lets first understand why are these ranking systems required. Will a simple win-loss ratio not be enough? To answer this, let’s go through an example. Consider there is a tournament with 4 teams playing in it and following are the results, and final table of the tournament standings so far. As you can see, Manchester United has won all of their 6 games and sit comfortably on top, Liverpool have lost all their games and lie on bottom of table. Arsenal and Chelsea share the spoil having been defeated by Man Utd in both rounds, defeating Liverpool in both rounds and then splitting the tie between themselves with Arsenal winning in 1st round and Chelsea returning the favour in reverse fixture. Now imagine we begin 3rd round of fixtures and first couple of game’s results were as below.Game 1: Arsenal defeat Manchester UnitedGame 2: Chelsea defeat LiverpoolWith that, updated table will look like below. Now wait a minute, does Chelsea and Arsenal really deserve to get same rankings? Isn’t it pretty obvious that Arsenal has defeated Manchester United who were dominant team in the tournament so far, whereas Chelsea defeated Liverpool who had anyways lost all their games. Definitely Arsenal should get more credit and should be ranked higher than Chelsea. But how do we do that? If we are using just a simple win-loss ratio, there is no way to differentiate them. Further on if you are considering goal difference and such, consider that all games have been won by the score line of 2 goals to 1, again we have a deadlock. Then how should we take into account the fact Arsenal defeated a much stronger team than Chelsea did, and hence deserves a higher ranking. This is where ranking systems come into picture. As we will see, Colley rankings are able to understand the event of a strong team being defeated and adjust their rankings accordingly. So without further delay, let’s get started. Mr. Wesley N. Colley suggested that instead of calculating rankings based on win-loss ratio like; ratings = [total wins] / [total games], ratings should be calculated based on following formula Rating = [1 + total wins] / [2 + total games]. If you look at this formula, before start of any tournament, all teams will begin with a rating of 0.5, as both ‘total wins’ and ‘total games’ will be zero. Keep note of this point (the fact that all teams start with a rating of 0.5), it will come in handy later on. In fact, during all times, the average of all team’s ratings in Colley’s algorithm will always stay at 0.5.We can write total-wins as shown below. Looking closely into 1⁄2 * [total-games] term for a single team, we can say that 1⁄2 * [total-games] = 1⁄2 * [1+1+1...1] where ‘1’ stands for a game played against each opponent. This in turn can be written as 1⁄2 * [total-games] = [1/2 + 1⁄2 + 1⁄2+..]. Now if you remember, as said before at the start, rating of all teams would be around 0.5 and hence average rating for all teams combined will also be 0.5. Considering this, we can say that [1/2 + 1⁄2 + 1⁄2 + ..] ~= [sum of opponent’s ratings]. With this, rewriting equation for total-wins. Rewriting formula for ratings, Expanding total-wins and writing down rating for individual team, we can write as. Where ri, wi, li, and ti represent rating, wins, loss and total game for the team of interest and ∑rj is sum of opponent’s ratings. This can be further rearranged as Now, as with most of my other tutorials, let’s use a toy example to understand mathematical equations better. Consider a case of two teams. As stated above, before beginning, they both will have a rating of 0.5 each. Now let’s suppose they played one game against each other. Let rW and rL represent new ratings for winning and loosing team respectively. If you put ti (which will be equal to 1) for both teams, and consider their wi and li values, we will get following results from equation (A) This represents a simple two variable linear system, which when solved gives us our new ratings as rw = 5/8 and rL = 3/8. For 2 teams, equation (A) resulted in two variable linear system, for N teams, it will result in N variable linear system. In programming world, whenever we want to solve N variable linear equations, we always write them in form of a matrix. So rewriting equation (A) in matrix form as Where vector r represents column-vector of all the ratings ri and vector b is a column-vector of the right-hand-side of equation (A). The matrix C, defined as the Colley Matrix, is just slightly more complicated. Imagine having our four favorite English premier league teams as rows and columns of a 4x4 matrix, as shown in below picture The diagonal elements in Colley matrix should be filled by number = (2 + total-games) for corresponding team. So 1st blue cell should have a value of 2 + number of games played by Manchester United. Similarly rest of cells to be filled for Chelsea, Arsenal and Liverpool games. The off diagonal elements, represented by green cell should have negative value of the number of games played between team represented by row and column for that cell. So for e.g. cell intersecting Man Utd row and Chelsea column should have a number equal to negative value of number of Man Utd vs Chelsea games. And like that we will fill rest of the cells in Colley matrix. Once we solve this N variable linear equation Cr = b, we will get vector value for ‘r’, which represents ratings for each individual team. With this clear understanding of theoretical background, let’s go ahead and write a Python code to calculate Colley’s rankings for toy example introduced at the beginning of this article. Python code file, along with couple of supporting files can be found at my github repo here. Before beginning to code, let me explain structure of couple of supporting files, namely ‘scores’ and ‘teams’, both of which are in ‘comma separated value’ format. ‘teams’ file contains list of teams, alongside a ‘number’. This ‘number’ will be used to represent the team in ‘scores’ file. Following screenshot shows contents of ‘teams’ file. So from now on, whenever we want to represent Manchester United, we will represent them with number 1. Similarly for Chelsea, Arsenal and Liverpool, we will use numbers 2, 3, and 4 respectively while representing them in ‘scores’ file. Now let’s have a look at ‘score’s file with help of following screenshot. Each row in ‘scores’ file corresponds to a game. I will explain it little later as to why is this file in such a particular order. Columns in ‘scores’ file represent => Column 1 = Number of days since 1/1/0000 when this particular game was played. Column 2 = today’s date. Column 3 = team 1 number. Column 4 = team 1 ‘home’ value (1 = home game, -1 = away game, 0 = neutral). Column 5 = team 1 score. Column 6 = team 2 number. Column 7 = team 2 ‘home’ value (1 = home game, -1 = away game, 0 = neutral). Column 8 = team 2 score. As we will not be using Column 1, 2, 4 and 7 values in this exercise, I have put dummy numbers for them. Also, just for my convenience I have kept score (Column 5 for team 1 score and Column 8 for team 2 score) as mostly 2 and 1 each, as we will not be looking into scores either in this example. We will just use it to determine winner of each game. Let’s take example of first row. Column 1 and 2 representing date of the game has dummy values of ‘1’ each. Column 3 has a value of ‘1’. Cross checking this with our ‘teams’ file, we can see that value of ‘1’ is used to represent Manchester United. Column 4 has ‘-1’, signifying that this game was away game for Manchester United. Col 5 has a value of ‘2’ meaning that 2 goals were scored by Manchester United. Col 6 value represent team 2 number, where number 2 means team 2 was Chelsea and this was a Manchester United vs Chelsea game. Col 7 has a value of ‘1’ meaning to say this was a home game for Chelsea and final column has a value of ‘1’ representing number of goals scored by Chelsea. Finally, let’s start to code this algorithm. Coding Colley algorithm is relatively simple and fairly self explanatory. As with any Python file, we will import required packages, namely numpy and pandas in this case. # Importing packagesimport numpy as npimport pandas as pd Then we go and read ‘teams’ and ‘scores’ files. # Reading 'teams' and 'scores' datateams = pd.read_csv('teams.txt', header = None)num_of_teams = len(teams.index)data = pd.read_csv('scores.txt', header = None) We initialize Colley matrix and vector b with all 0 in required dimensions. # Initializing Colley Matrix 'c'and vector 'b'c = np.zeros([num_of_teams, num_of_teams])b = np.zeros(num_of_teams) Then, iterating through ‘scores’ file line by line, we populate Colley matrix and vector ‘b’ depending on which teams are playing and winner of each game. # Iterating through rows and populating Colley matrix valuesfor index, row in data.iterrows(): t1 = row[2] t2 = row[5] c[(t1-1)][(t1-1)] = c[(t1-1)][(t1-1)] + 1 # Updating diagonal element c[(t2-1)][(t2-1)] = c[(t2-1)][(t2-1)] + 1 # Updating diagonal element c[(t1-1)][(t2-1)] = c[(t1-1)][(t2-1)] - 1 # Updating off - diagonal element c[(t2-1)][(t1-1)] = c[(t2-1)][(t1-1)] - 1 # Updating off - diagonal element # Updating vecotr b based on result of each game if row[4] > row[7]: b[(t1-1)] += 1 b[(t2-1)] -= 1 elif row[4] < row[7]: b[(t1-1)] -= 1 b[(t2-1)] += 1 Once that is done, we make the adjustment of adding 2 to diagonal elements of Colley matrix and dividing and adding 1 to each element of vector b, as per equation (A). # Adding 2 to diagonal elements (total number of games) of Colley matrixdiag = c.diagonal() + 2np.fill_diagonal(c, diag)# Dividing by 2 and adding one to vector bfor i, value in enumerate(b): b[i] = b[i] / 2 b[i] += 1 Afterwards we solve this N variable linear equation using numpy’s linalg.solve(). # Solving N variable linear equationr = np.linalg.solve(c, b) Once we get result in ‘r’, we display top 4 teams by using argsort() method. # Displaying ranking for top 4 teamstop_teams = r.argsort()[-4:][::-1]for i in top_teams: print (str(r[i]) + " " + str(teams.iloc[i][1])) And with that, if you successfully downloaded the repo and ran this code, you should see following output. Now, to check real strength of this algorithm, we will be adding two more games in our ‘scores’ files by inserting following lines.Game 1: Arsenal defeat Manchester United => 1, 1, 1, -1, 1, 3, 1, 2Game 2: Chelsea defeat Liverpool => 1, 1, 2, -1, 2, 4, 1, 1Running Python file again after making above modifications in ‘scores’, you will get following result. As you can see, even though Arsenal and Chelsea have played, won and loss equal number of games, Colley algorithm was able to recognize the fact that Arsenal had defeated a stronger team in Manchester United compared to Liverpool who was defeated by Chelsea. Coming back to the format of ‘scores’ files, let’s see how it is useful with one more use case. Consider there are 3 rounds in tournament with results shown in below image. Manchester United win all their games in round 1, Chelsea win all their games in round 2, and Arsenal in round 3. Although all 3 teams are tied on number of wins, any knowledgeable sports person will tell you that after winning all games in first round, Man Utd have fizzled out. Arsenal on the other hand are on a hot streak winning all their games in latest round of fixtures, and Chelsea lie in between. With this in mind, even though total points for Man Utd, Arsenal and Chelsea are same, a good ranking system should provide a provision to distinguish old performances against recent one. To take this ‘momentum’ or ‘in-form’ factor into account, a new variable called ‘weight’ is introduced. With the help of a simple ‘if else’ conditional statements, we are giving different weightage to different games. # Iterating through rows and populating Colley matrix valuesfor index, row in data.iterrows(): t1 = row[2] t2 = row[5] if row[0] <= 6: #For first round matches weight = 0.9 elif row[0] > 6 and row[0] <=12: #For second round matches weight = 1.0 else: weight = 1.1 #For third round matches c[(t1-1)][(t1-1)] = c[(t1-1)][(t1-1)] + 1 * weight # Updating diagonal element c[(t2-1)][(t2-1)] = c[(t2-1)][(t2-1)] + 1 * weight # Updating diagonal element c[(t1-1)][(t2-1)] = c[(t1-1)][(t2-1)] - 1 * weight # Updating off - diagonal element c[(t2-1)][(t1-1)] = c[(t2-1)][(t1-1)] - 1 * weight # Updating off - diagonal element # Updating vecotr b based on result of each game if row[4] > row[7]: b[(t1-1)] += 1 * weight b[(t2-1)] -= 1 * weight elif row[4] < row[7]: b[(t1-1)] -= 1 * weight b[(t2-1)] += 1 * weight As the tournament progress, less weightage is given to old games. Whereas latest round of fixtures are given higher weightage compared to previous two rounds. With above modification, if we again run our Colley algorithm, we will get following results. As expected, Arsenal having won all its games in latest fixtures are ranked first, whereas Man Utd are ranked third even though they share same points with Arsenal and Chelsea. And with that, I will draw curtains on this article. Hope the sports fanatic and Data scientist in you was able to appreciate the beauty and simplicity of Colley’s method. As usual, if you liked this post, Follow, Like, Retweet it on Twitter or Claps, Likes here on Medium will act as encouragement for writing new posts as I continue my journey into Blogging world. Till next time....cheers!!
[ { "code": null, "e": 344, "s": 171, "text": "In this tutorial, we will go through one very popular algorithm used in generating rankings for sports teams. The method which we will be studying is called Colley Ratings." }, { "code": null, "e": 661, "s": 344, "text": "Before going ...
What are the differences between current_window_handle and window_handles methods in Selenium with python?
There are differences between current_window_handle and window_handles methods in Selenium. Both are methods to handle multiple windows. They differences are listed below − current_window_handleThis method fetches the handle of the present window. Thus it deals with the window in focus at the moment. It returns the window handle id as a string value. current_window_handle This method fetches the handle of the present window. Thus it deals with the window in focus at the moment. It returns the window handle id as a string value. Syntax − driver.current_window_handle window_handlesThis method fetches all the handle ids of the windows that are currently open. The collection of window handle ids is returned as a set data structure. window_handles This method fetches all the handle ids of the windows that are currently open. The collection of window handle ids is returned as a set data structure. Syntax − driver.window_handles w = driver.window_handles[2] The above code gives the handle id of the second window open in the present session. Code Implementation with current_window_handle from selenium import webdriver driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe") # to maximize the browser window driver.maximize_window() #get method to launch the URL driver.get("https://the-internet.herokuapp.com/windows") #to refresh the browser driver.refresh() driver.find_element_by_link_text("Click Here").click() #prints the window handle in focus print(driver.current_window_handle) #to close the browser driver.quit() Code Implementation with window_handles. from selenium import webdriver driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe") # to maximize the browser window driver.maximize_window() #get method to launch the URL driver.get("https://the-internet.herokuapp.com/windows") #to refresh the browser driver.refresh() driver.find_element_by_link_text("Click Here").click() #prints the window handle in focus print(driver.current_window_handle) #to fetch the all handle ids of opened windows chwnd = driver.window_handles; # count the number of open windows in console print("Total Windows : "+chwnd.size()); #to close the browser driver.quit()
[ { "code": null, "e": 1235, "s": 1062, "text": "There are differences between current_window_handle and window_handles methods in Selenium. Both are methods to handle multiple windows. They differences are listed below −" }, { "code": null, "e": 1415, "s": 1235, "text": "current_w...
How to create bubble maps in Python with Geospatial data | by Abdishakur | Towards Data Science
Ever thought how you can create bubble maps in Python with Geospatial data? I will show you how you can easily make a bubble maps both in a static format as well as an interactive one. A bubble map uses size as an encoding variable. The size of the circle represents a numeric value on a Geographic area. We often use Choropleth maps to display areas, and in that case, we use a colour encoding. Choropleth maps have an inherent bias problem with large areas. In contrast, bubble maps use circles to represent a numeric value of an area or region. It often seems to be complicated and a bit advanced feature to create your bubble map in Python, but it is not. It is like creating bubble charts with latitude and longitude columns. Let us first import the libraries we need. import pandas as pdimport numpy as npimport geopandas as gpdimport matplotlib.pyplot as pltimport plotly_express as px And we can read the data with Geopandas. With Geopandas, you can read most of the geographic data formats like Shapefile, Geojson, Geo package, etc.. In this example, we are using population data from the city of Mälmo, Sweden. gdf = gpd.read_file(“data/malmo-pop.shp”)gdf.head() Here is a glimpse of the first rows of the dataset. We have numerous columns of the population subdivision (Age 5 to age 80 and above) for each administrative unit (Deso). We usually use choropleth maps and use a colour encoding. As we are going to see, we can create a choropleth map very easily with Geopandas. Notice that we first normalize the data (Age80_w) by subdividing the total population. gdf["Age_80_norm"] = (gdf["Age80_w"] / gdf["Total"]) * 100fig, ax = plt.subplots(figsize=(16,16))gdf.plot(ax=ax, column="Age_80_norm", cmap="Blues",edgecolor="grey", linewidth=0.4, legend=True)ax.axis("off")plt.axis('equal')plt.show() Alternatively, we can use bubble maps and avoid some of the pitfalls of choropleth maps. For example, we do not need to normalize the data, and we can use the total subdivision of populations. However, we need to do some conversion to the data to be able to create a bubble map. As you can see, the data we are using are Polygons, and we need points if we want to create bubble maps. That is, however, a simple process with Geopandas. We only need to change the geometry column, in this case, Polygons to Point geometry. gdf_points = gdf.copy()gdf_points[‘geometry’] = gdf_points[‘geometry’].centroid We first copy the Geodataframe with Polygon geometry to a new Geodataframe. As we want to the bubble to be at the centre of the area, we can use centroid function in Geopandas to achieve this. Now, we have the same Geodataframe with different Geometry column, a Point Geometry. Let us plot a bubble map as we have points dataset now. fig, ax = plt.subplots(figsize=(16,16))gdf.plot(ax=ax, color=”lightgray”, edgecolor=”grey”, linewidth=0.4)gdf_points.plot(ax=ax,color=”#07424A”, markersize=”Age80_w”,alpha=0.7, categorical=False, legend=True )ax.axis(“off”)plt.axis(‘equal’)plt.show() The map below shows a bubble map for Age 80 and above population in a smaller administrative area in Mälmo, Sweden. Each circle represents a different size based on the subtotal population at the age of 80 and above. To construct a bubble map, you need to provide markersize to the column you want to be mapped, and in this case, the Age80_w. As you can see, this is a static map, and often a problem with bubble maps is the overlapping of point circles. One way we can avoid this is to create interactive maps that allow the user to interact with and zoom into an area of interest. In the next section, we are going to see how you can create an interactive bubble map. There are different Python libraries for plotting interactive bubble maps. To construct an interactive bubble map, we use Plotly Express. We just need to convert to another projection to display the map with Plotly Express. Plotly Express has scatter_mapbox() function which can take a Geodataframe and the column you want to use for the bubble map. gdf_points_4326 = gdf_points.to_crs(“EPSG:4326”)fig = px.scatter_mapbox( gdf_points_4326, lat=gdf_points_4326.geometry.y, lon=gdf_points_4326.geometry.x, size=”Age80_w”, color=”Total”, hover_name = “Age80_w”, color_continuous_scale=px.colors.colorbrewer.Reds, size_max=15, zoom=10 )fig.show() With Plotly Express, we can avoid the overlapping problem of bubble maps by creating an interactive bubble map. See the below GIF. Bubble maps can be an alternative map to display a numeric variable with different bubble size, instead of the most used choropleth maps. If you have a list of regions (i.e. administration areas) with values (i.e., age subdivisions), bubble maps can replace Choropleth maps. Bubble maps do not have the inherent big area bias in choropleth maps. In this tutorial, we have seen how to create both static and interactive bubble maps, using Python. The static bubble maps have an overlapping problem. To avoid it, you can either create interactive maps that allow zoom in/out or increase the transparency of the static map circles. The code for this tutorial is available in this Github Repository.
[ { "code": null, "e": 357, "s": 172, "text": "Ever thought how you can create bubble maps in Python with Geospatial data? I will show you how you can easily make a bubble maps both in a static format as well as an interactive one." }, { "code": null, "e": 477, "s": 357, "text": "A...
Logstash - Output Stage
Output is the last stage in Logstash pipeline, which send the filter data from input logs to a specified destination. Logstash offers multiple output plugins to stash the filtered log events to various different storage and searching engines. Logstash can store the filtered logs in a File, Elasticsearch Engine, stdout, AWS CloudWatch, etc. Network protocols like TCP, UDP, Websocket can also be used in Logstash for transferring the log events to remote storage systems. In ELK stack, users use the Elasticsearch engine to store the log events. Here, in the following example, we will generate log events for a local Elasticsearch engine. We can install the Elasticsearch output plugin with the following command. >logstash-plugin install Logstash-output-elasticsearch This config file contains an Elasticsearch plugin, which stores the output event in Elasticsearch installed locally. input { file { path => "C:/tpwork/logstash/bin/log/input.log" } } filter { grok { match => [ "message", "%{LOGLEVEL:loglevel} - %{NOTSPACE:taskid} - %{NOTSPACE:logger} - %{WORD:label}( - %{INT:duration:int})?" ] } if [logger] == "TRANSACTION_START" { aggregate { task_id => "%{taskid}" code => "map['sql_duration'] = 0" map_action => "create" } } if [logger] == "SQL" { aggregate { task_id => "%{taskid}" code => "map['sql_duration'] ||= 0 ; map['sql_duration'] += event.get('duration')" } } if [logger] == "TRANSACTION_END" { aggregate { task_id => "%{taskid}" code => "event.set('sql_duration', map['sql_duration'])" end_of_task => true timeout => 120 } } mutate { add_field => {"user" => "tutorialspoint.com"} } } output { elasticsearch { hosts => ["127.0.0.1:9200"] } } The following code block shows the input log data. INFO - 48566 - TRANSACTION_START - start INFO - 48566 - SQL - transaction1 - 320 INFO - 48566 - SQL - transaction1 - 200 INFO - 48566 - TRANSACTION_END - end To start Elasticsearch at the localhost, you should use the following command. C:\elasticsearch\bin> elasticsearch Once Elasticsearch is ready, you can check it by typing the following URL in your browser. http://localhost:9200/ The following code block shows the response of Elasticsearch at localhost. { "name" : "Doctor Dorcas", "cluster_name" : "elasticsearch", "version" : { "number" : "2.1.1", "build_hash" : "40e2c53a6b6c2972b3d13846e450e66f4375bd71", "build_timestamp" : "2015-12-15T13:05:55Z", "build_snapshot" : false, "lucene_version" : "5.3.1" }, "tagline" : "You Know, for Search" } Note − For more information about Elasticsearch, you can click on the following link. https://www.tutorialspoint.com/elasticsearch/index.html Now, run Logstash with the above-mentioned Logstash.conf >Logstash –f Logstash.conf After pasting the above-mentioned text in the output log, that text will be stored in Elasticsearch by Logstash. You can check the stored data by typing the following URL in the browser. http://localhost:9200/logstash-2017.01.01/_search?pretty It is the data in JSON format stored in index Logstash-2017.01.01. { "took" : 20, "timed_out" : false, "_shards" : { "total" : 5, "successful" : 5, "failed" : 0 }, "hits" : { "total" : 10, "max_score" : 1.0, "hits" : [ { "_index" : "logstash-2017.01.01", "_type" : "logs", "_id" : "AVlZ9vF8hshdrGm02KOs", "_score" : 1.0, "_source":{ "duration":200,"path":"C:/tpwork/logstash/bin/log/input.log", "@timestamp":"2017-01-01T12:17:49.140Z","loglevel":"INFO", "logger":"SQL","@version":"1","host":"wcnlab-PC", "label":"transaction1", "message":" INFO - 48566 - SQL - transaction1 - 200\r", "user":"tutorialspoint.com","taskid":"48566","tags":[] } }, { "_index" : "logstash-2017.01.01", "_type" : "logs", "_id" : "AVlZ9vF8hshdrGm02KOt", "_score" : 1.0, "_source":{ "sql_duration":520,"path":"C:/tpwork/logstash/bin/log/input.log", "@timestamp":"2017-01-01T12:17:49.145Z","loglevel":"INFO", "logger":"TRANSACTION_END","@version":"1","host":"wcnlab-PC", "label":"end", "message":" INFO - 48566 - TRANSACTION_END - end\r", "user":"tutorialspoint.com","taskid":"48566","tags":[] } } } } Print Add Notes Bookmark this page
[ { "code": null, "e": 2298, "s": 2055, "text": "Output is the last stage in Logstash pipeline, which send the filter data from input logs to a specified destination. Logstash offers multiple output plugins to stash the filtered log events to various different storage and searching engines." }, { ...
First-Fit Allocation in Operating Systems - GeeksforGeeks
28 Aug, 2020 For both fixed and dynamic memory allocation schemes, the operating system must keep list of each memory location noting which are free and which are busy. Then as new jobs come into the system, the free partitions must be allocated. These partitions may be allocated by 4 ways: 1. First-Fit Memory Allocation 2. Best-Fit Memory Allocation 3. Worst-Fit Memory Allocation 4. Next-Fit Memory Allocation These are Contiguous memory allocation techniques. First-Fit Memory Allocation:This method keeps the free/busy list of jobs organized by memory location, low-ordered to high-ordered memory. In this method, first job claims the first available memory with space more than or equal to it’s size. The operating system doesn’t search for appropriate partition but just allocate the job to the nearest memory partition available with sufficient size. As illustrated above, the system assigns J1 the nearest partition in the memory. As a result, there is no partition with sufficient space is available for J3 and it is placed in the waiting list. Advantages of First-Fit Memory Allocation:It is fast in processing. As the processor allocates the nearest available memory partition to the job, it is very fast in execution. Disadvantages of First-Fit Memory Allocation :It wastes a lot of memory. The processor ignores if the size of partition allocated to the job is very large as compared to the size of job or not. It just allocates the memory. As a result, a lot of memory is wasted and many jobs may not get space in the memory, and would have to wait for another job to complete. sarthakdandriyal3199 kakashi01 memory-management Operating Systems-Memory Management GATE CS Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Normal Forms in DBMS Differences between TCP and UDP Data encryption standard (DES) | Set 1 Semaphores in Process Synchronization LRU Cache Implementation Banker's Algorithm in Operating System Program for FCFS CPU Scheduling | Set 1 Program for Round Robin scheduling | Set 1 Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive) Introduction of Deadlock in Operating System
[ { "code": null, "e": 24196, "s": 24168, "text": "\n28 Aug, 2020" }, { "code": null, "e": 24430, "s": 24196, "text": "For both fixed and dynamic memory allocation schemes, the operating system must keep list of each memory location noting which are free and which are busy. Then as...
How to Create a vector of specific type and length in R ?
05 Apr, 2021 In this article, we will see how to create a vector of specified type and length in R programming language. To create a vector of specified data type and length in R we make use of function vector(). vector() function is also used to create empty vector. Syntax: vector(class of the data object, length of the vector) There is a very straightforward approach for this. Steps – Create vector of required type Also pass the size to it Here we can also check the type and size of the vector so created Implementation combined with this approach paints a better picture. Example 1: R # Create a vector of type integer, numeric class and length 5a <- vector( "integer" , 5 )b <- vector( "numeric" , 5 ) # Printing vector aprint(a) # Printing the data type of the vector print(typeof(a)) # Printing the length of vector aprint(length(a)) # Printing vector bprint(b) # Printing the data type of the vector bprint(typeof(b)) # Printing the length of vector bprint(length(b)) Output: [1] 0 0 0 0 0 [1] “integer” [1] 5 [1] 0 0 0 0 0 [1] “double” [1] 5 Example 2: R # Create a vector of type logical and length 5a <- vector( "logical" , 5 ) # Printing vector aprint(a) # Printing the data type of the vector print(typeof(a)) # Printing the length of vector aprint(length(a)) Output: [1] FALSE FALSE FALSE FALSE FALSE [1] “logical” [1] 5 Example 3: R # Create a vector of type character and length 5a <- vector( "character" , 5 ) # Printing vector aprint(a) # Printing the data type of the vector print(typeof(a)) # Printing the length of vector aprint(length(a)) Output: [1] “” “” “” “” “” [1] “character” [1] 5 Picked R Vector-Programs R-Vectors R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Apr, 2021" }, { "code": null, "e": 283, "s": 28, "text": "In this article, we will see how to create a vector of specified type and length in R programming language. To create a vector of specified data type and length in R we make u...
Publish Websites on GitHub Pages with a Custom Domain
11 Feb, 2021 Publishing websites can sometimes be very tricky and could cost you some bucks as well but with GitHub Pages, the entire process is so seamless and easy that it just takes a few minutes to get your website live onto the internet. Although the process in itself is quite easy yet having a step-by-step guide is always better, isn’t it? Follow the below steps to publish your own website onto GitHub Pages with a custom domain for absolutely no charges. Set up an empty GitHub repository just the way you normally do. Give any name to the repository. You could keep the repository either public or private, your choice. Here’s a sample repository for this blog here. Push the entire code onto the repository. Ensure that you have the index.html in the root directory or in a folder named docs (you’ll understand why in the next step). Here’s the directory structure: - index.html - public |_ css Head to the Settings tab of the repository and scroll down to where it says GitHub Pages. By default, the options look like this: For the Source, click the dropdown where it says None and choose the branch where your code is present, in my case it’s main. As soon as you select the branch, a new dropdown will appear. Choose the respective folder (root/docs) where your code is present. Click Save. Scroll back down to the GitHub Pages section and you should see something like this: Head to the URL and you should see your website live on the internet. In the next step, we’ll explain how to get a free custom domain. Now to set up a custom domain, enter the domain name in the Custom domain section, in my case, it’s github-pages.tk Click Save. This adds a new CNAME file to your repository. Sometimes the Enforce HTTPS option is auto-enabled, if it’s not, enable it manually to get a free SSL certificate for your website. Sometimes, it could also take time to give you the option to enable it. To get free custom domains, I use Freenom. If you already have the domain from another provider, the below steps should be similar. Login onto the website and goto Services > Register a New Domain and search for the desired domain name. Select the available domain and complete the checkout process. Now go to Services > My Domains. Select the Manage Domain option against the domain you just got and head to Manage Freenom DNS. Now, all we need to do is set A & CNAME records for the selected domain. For A record, add four entries: 185.199.108.153 185.199.109.153 185.199.110.153 185.199.111.153 To redirect www subdomain to the original domain, add a CNAME record with your GitHub pages profile URL with a .(dot) in the end, in my case, it would be ‘ishaanohri.github.io.’. Just to be sure, check for the latest IPs in GitHub’s Official Documentation. Save the records and wait for some time. Your website would be live on www.custom-domain.com and custom-domain.com. Sometimes it may take up to 24 hours to reflect the changes. Your website is now live on your custom domain. Now, any changes you push onto the selected branch of the repository will be published live on your domain. GitHub GBlog Git Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You! Geek Streak - 24 Days POTD Challenge How to Learn Data Science in 10 weeks? What is Hashing | A Complete Tutorial GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge? Working on Git for GUI How to Set Git Username and Password in GitBash? How to integrate Git Bash with Visual Studio Code? Git - Difference Between Git Fetch and Git Pull How to Set Upstream Branch on Git?
[ { "code": null, "e": 54, "s": 26, "text": "\n11 Feb, 2021" }, { "code": null, "e": 389, "s": 54, "text": "Publishing websites can sometimes be very tricky and could cost you some bucks as well but with GitHub Pages, the entire process is so seamless and easy that it just takes a ...
Slim Framework | Installation and Configuration
10 May, 2022 Slim is a lightweight, easy to use and fast PHP framework used to develop the powerful website quickly with ease. Like other PHP frameworks, slim also supports routers, middlewares, bodyparser, page templates, encrypted cookies and much more. Prerequisites: PHP installation on windowsEnvironment Setup To Run the ProjectComposer Software to install slim PHP installation on windows Environment Setup To Run the Project Composer Software to install slim Installation: Go to your directory where XAMPP is installed and open htdocs folder. (In my case it is C:\xampp\htdocs).Open command prompt and navigate to current working directory as your current directory. Enter the command Go to your directory where XAMPP is installed and open htdocs folder. (In my case it is C:\xampp\htdocs). Open command prompt and navigate to current working directory as your current directory. Enter the command mkdir project_name && cd project_name This command will create a project folder with project_name and set the present working directory to it. Now enter the command This command will create a project folder with project_name and set the present working directory to it. Now enter the command composer require slim/slim:3.* (Here 3.* refers to version number) This will install the slim framework in the current directory. Now enter the command (Here 3.* refers to version number) This will install the slim framework in the current directory. Now enter the command notepad index.php and click on yes. It will create a new file index.php and will open it for editing. Now type the following code in the file and click on yes. It will create a new file index.php and will open it for editing. Now type the following code in the file CPP <?php require 'vendor/autoload.php'; $app = new \Slim\App;$app->get('/', function () { echo 'Welcome to my slim app';});$app->run();?> It is the code for our first slim application. Save the file and close it.Open xampp control panel and run the apache server.Now open a web browser and go to url -> http://localhost:81/project_name/ As you can see our first app is running on the server successfully. You have successfully installed slim and have created your first app with that. It is the code for our first slim application. Save the file and close it. Open xampp control panel and run the apache server. Now open a web browser and go to url -> http://localhost:81/project_name/ As you can see our first app is running on the server successfully. You have successfully installed slim and have created your first app with that. varshagumber28 how-to-install PHP-Misc Installation Guide PHP PHP Programs Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n10 May, 2022" }, { "code": null, "e": 286, "s": 28, "text": "Slim is a lightweight, easy to use and fast PHP framework used to develop the powerful website quickly with ease. Like other PHP frameworks, slim also supports routers, middle...
PHP - Validation Example
Required field will check whether the field is filled or not in the proper way. Most of cases we will use the * symbol for required field. Validation means check the input submitted by the user. There are two types of validation are available in PHP. They are as follows − Client-Side Validation − Validation is performed on the client machine web browsers. Client-Side Validation − Validation is performed on the client machine web browsers. Server Side Validation − After submitted by data, The data has sent to a server and perform validation checks in server machine. Server Side Validation − After submitted by data, The data has sent to a server and perform validation checks in server machine. Below code shows validation of URL $website = input($_POST["site"]); if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) { $websiteErr = "Invalid URL"; } Above syntax will verify whether a given URL is valid or not. It should allow some keywords as https, ftp, www, a-z, 0-9,..etc.. Below code shows validation of Email address $email = input($_POST["email"]); if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $emailErr = "Invalid format and please re-enter valid email"; } Above syntax will verify whether given Email address is well-formed or not.if it is not, it will show an error message. Example below shows the form with required field validation <html> <head> <style> .error {color: #FF0000;} </style> </head> <body> <?php // define variables and set to empty values $nameErr = $emailErr = $genderErr = $websiteErr = ""; $name = $email = $gender = $comment = $website = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["name"])) { $nameErr = "Name is required"; }else { $name = test_input($_POST["name"]); } if (empty($_POST["email"])) { $emailErr = "Email is required"; }else { $email = test_input($_POST["email"]); // check if e-mail address is well-formed if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $emailErr = "Invalid email format"; } } if (empty($_POST["website"])) { $website = ""; }else { $website = test_input($_POST["website"]); } if (empty($_POST["comment"])) { $comment = ""; }else { $comment = test_input($_POST["comment"]); } if (empty($_POST["gender"])) { $genderErr = "Gender is required"; }else { $gender = test_input($_POST["gender"]); } } function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?> <h2>Absolute classes registration</h2> <p><span class = "error">* required field.</span></p> <form method = "post" action = "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> <table> <tr> <td>Name:</td> <td><input type = "text" name = "name"> <span class = "error">* <?php echo $nameErr;?></span> </td> </tr> <tr> <td>E-mail: </td> <td><input type = "text" name = "email"> <span class = "error">* <?php echo $emailErr;?></span> </td> </tr> <tr> <td>Time:</td> <td> <input type = "text" name = "website"> <span class = "error"><?php echo $websiteErr;?></span> </td> </tr> <tr> <td>Classes:</td> <td> <textarea name = "comment" rows = "5" cols = "40"></textarea></td> </tr> <tr> <td>Gender:</td> <td> <input type = "radio" name = "gender" value = "female">Female <input type = "radio" name = "gender" value = "male">Male <span class = "error">* <?php echo $genderErr;?></span> </td> </tr> <td> <input type = "submit" name = "submit" value = "Submit"> </td> </table> </form> <?php echo "<h2>Your given values are as:</h2>"; echo $name; echo "<br>"; echo $email; echo "<br>"; echo $website; echo "<br>"; echo $comment; echo "<br>"; echo $gender; ?> </body> </html> It will produce the following result −
[ { "code": null, "e": 3030, "s": 2891, "text": "Required field will check whether the field is filled or not in the proper way. Most of cases we will use the * symbol for required field." }, { "code": null, "e": 3164, "s": 3030, "text": "Validation means check the input submitted ...
Transpose graph
03 Jun, 2022 Transpose of a directed graph G is another directed graph on the same set of vertices with all of the edges reversed compared to the orientation of the corresponding edges in G. That is, if G contains an edge (u, v) then the converse/transpose/reverse of G contains an edge (v, u) and vice versa. Given a graph (represented as adjacency list), we need to find another graph which is the transpose of the given graph. Example: Transpose Graph Input : figure (i) is the input graph. Output : figure (ii) is the transpose graph of the given graph. We traverse the adjacency list and as we find a vertex v in the adjacency list of vertex u which indicates an edge from u to v in main graph, we just add an edge from v to u in the transpose graph i.e. add u in the adjacency list of vertex v of the new graph. Thus traversing lists of all vertices of main graph we can get the transpose graph. Thus the total time complexity of the algorithm is O(V+E) where V is number of vertices of graph and E is the number of edges of the graph. Note : It is simple to get the transpose of a graph which is stored in adjacency matrix format, you just need to get the transpose of that matrix. C++ Java Python3 C# Javascript // CPP program to find transpose of a graph.#include <bits/stdc++.h>using namespace std; // function to add an edge from vertex source to vertex destvoid addEdge(vector<int> adj[], int src, int dest){ adj[src].push_back(dest);} // function to print adjacency list of a graphvoid displayGraph(vector<int> adj[], int v){ for (int i = 0; i < v; i++) { cout << i << "--> "; for (int j = 0; j < adj[i].size(); j++) cout << adj[i][j] << " "; cout << "\n"; }} // function to get Transpose of a graph taking adjacency// list of given graph and that of Transpose graphvoid transposeGraph(vector<int> adj[], vector<int> transpose[], int v){ // traverse the adjacency list of given graph and // for each edge (u, v) add an edge (v, u) in the // transpose graph's adjacency list for (int i = 0; i < v; i++) for (int j = 0; j < adj[i].size(); j++) addEdge(transpose, adj[i][j], i);} int main(){ int v = 5; vector<int> adj[v]; addEdge(adj, 0, 1); addEdge(adj, 0, 4); addEdge(adj, 0, 3); addEdge(adj, 2, 0); addEdge(adj, 3, 2); addEdge(adj, 4, 1); addEdge(adj, 4, 3); // Finding transpose of graph represented // by adjacency list adj[] vector<int> transpose[v]; transposeGraph(adj, transpose, v); // displaying adjacency list of transpose // graph i.e. b displayGraph(transpose, v); return 0;} // Java program to find the transpose of a graphimport java.util.*;import java.lang.*;import java.io.*; class Graph{ // Total number of vertices private static int vertices = 5; // Find transpose of graph represented by adj private static ArrayList<Integer>[] adj = new ArrayList[vertices]; // Store the transpose of graph represented by tr private static ArrayList<Integer>[] tr = new ArrayList[vertices]; // Function to add an edge from source vertex u to // destination vertex v, if choice is false the edge is added // to adj otherwise the edge is added to tr public static void addedge(int u, int v, boolean choice) { if(!choice) adj[u].add(v); else tr[u].add(v); } // Function to print the graph representation public static void printGraph() { for(int i = 0; i < vertices; i++) { System.out.print(i + "--> "); for(int j = 0; j < tr[i].size(); j++) System.out.print(tr[i].get(j) + " "); System.out.println(); } } // Function to print the transpose of // the graph represented as adj and store it in tr public static void getTranspose() { // Traverse the graph and for each edge u, v // in graph add the edge v, u in transpose for(int i = 0; i < vertices; i++) for(int j = 0; j < adj[i].size(); j++) addedge(adj[i].get(j), i, true); } public static void main (String[] args) throws java.lang.Exception { for(int i = 0; i < vertices; i++) { adj[i] = new ArrayList<Integer>(); tr[i] = new ArrayList<Integer>(); } addedge(0, 1, false); addedge(0, 4, false); addedge(0, 3, false); addedge(2, 0, false); addedge(3, 2, false); addedge(4, 1, false); addedge(4, 3, false); // Finding transpose of the graph getTranspose(); // Printing the graph representation printGraph(); }} // This code is contributed by code_freak # Python3 program to find transpose of a graph. # function to add an edge from vertex# source to vertex destdef addEdge(adj, src, dest): adj[src].append(dest) # function to print adjacency list# of a graphdef displayGraph(adj, v): for i in range(v): print(i, "--> ", end = "") for j in range(len(adj[i])): print(adj[i][j], end = " ") print() # function to get Transpose of a graph# taking adjacency list of given graph# and that of Transpose graphdef transposeGraph(adj, transpose, v): # traverse the adjacency list of given # graph and for each edge (u, v) add # an edge (v, u) in the transpose graph's # adjacency list for i in range(v): for j in range(len(adj[i])): addEdge(transpose, adj[i][j], i) # Driver Codeif __name__ == '__main__': v = 5 adj = [[] for i in range(v)] addEdge(adj, 0, 1) addEdge(adj, 0, 4) addEdge(adj, 0, 3) addEdge(adj, 2, 0) addEdge(adj, 3, 2) addEdge(adj, 4, 1) addEdge(adj, 4, 3) # Finding transpose of graph represented # by adjacency list adj[] transpose = [[]for i in range(v)] transposeGraph(adj, transpose, v) # displaying adjacency list of # transpose graph i.e. b displayGraph(transpose, v) # This code is contributed by PranchalK // C# program to find the transpose of a graphusing System;using System.Collections.Generic; class Graph{ // Total number of vertices private static int vertices = 5; // Find transpose of graph represented by adj private static List<int>[] adj = new List<int>[vertices]; // Store the transpose of graph represented by tr private static List<int>[] tr = new List<int>[vertices]; // Function to add an edge from source vertex u to // destination vertex v, if choice is false the edge is added // to adj otherwise the edge is added to tr public static void addedge(int u, int v, bool choice) { if(!choice) adj[u].Add(v); else tr[u].Add(v); } // Function to print the graph representation public static void printGraph() { for(int i = 0; i < vertices; i++) { Console.Write(i + "--> "); for(int j = 0; j < tr[i].Count; j++) Console.Write(tr[i][j] + " "); Console.WriteLine(); } } // Function to print the transpose of // the graph represented as adj and store it in tr public static void getTranspose() { // Traverse the graph and for each edge u, v // in graph add the edge v, u in transpose for(int i = 0; i < vertices; i++) for(int j = 0; j < adj[i].Count; j++) addedge(adj[i][j], i, true); } // Driver code public static void Main(String[] args) { for(int i = 0; i < vertices; i++) { adj[i] = new List<int>(); tr[i] = new List<int>(); } addedge(0, 1, false); addedge(0, 4, false); addedge(0, 3, false); addedge(2, 0, false); addedge(3, 2, false); addedge(4, 1, false); addedge(4, 3, false); // Finding transpose of the graph getTranspose(); // Printing the graph representation printGraph(); }} // This code is contributed by Rajput-Ji <script>// Javascript program to find transpose of a graph. // function to add an edge from vertex// source to vertex destfunction addEdge(adj, src, dest) { adj[src].push(dest)} // function to print adjacency list// of a graphfunction displayGraph(adj, v) { for (let i = 0; i < v; i++) { document.write(i + "--> ") for (let j = 0; j < adj[i].length; j++) { document.write(adj[i][j] + " ") } document.write("<br>") }} // function to get Transpose of a graph// taking adjacency list of given graph// and that of Transpose graphfunction transposeGraph(adj, transpose, v) { // traverse the adjacency list of given // graph and for each edge (u, v) add // an edge (v, u) in the transpose graph's // adjacency list for (let i = 0; i < v; i++) for (let j = 0; j < adj[i].length; j++) addEdge(transpose, adj[i][j], i)} // Driver Codelet v = 5let adj = new Array(v).fill(0).map(() => new Array())addEdge(adj, 0, 1)addEdge(adj, 0, 4)addEdge(adj, 0, 3)addEdge(adj, 2, 0)addEdge(adj, 3, 2)addEdge(adj, 4, 1)addEdge(adj, 4, 3) // Finding transpose of graph represented// by adjacency list adj[]let transpose = new Array(v).fill(0).map(() => new Array())transposeGraph(adj, transpose, v) // displaying adjacency list of// transpose graph i.e. bdisplayGraph(transpose, v) // This code is contributed by Saurabh Jaiswal </script> 0--> 2 1--> 0 4 2--> 3 3--> 0 4 4--> 0 PranchalKatiyar code_freak Rajput-Ji simmytarika5 _saurabh_jaiswal graph-basics Graph Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Dijkstra's shortest path algorithm | Greedy Algo-7 Find if there is a path between two vertices in a directed graph Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Detect Cycle in a Directed Graph Introduction to Data Structures Find if there is a path between two vertices in an undirected graph Bellman–Ford Algorithm | DP-23 What is Data Structure: Types, Classifications and Applications Minimum number of swaps required to sort an array m Coloring Problem | Backtracking-5
[ { "code": null, "e": 52, "s": 24, "text": "\n03 Jun, 2022" }, { "code": null, "e": 470, "s": 52, "text": "Transpose of a directed graph G is another directed graph on the same set of vertices with all of the edges reversed compared to the orientation of the corresponding edges in...
Python program to convert seconds into hours, minutes and seconds
28 Jan, 2019 Given an integer n (in seconds), convert it into hours, minutes and seconds. Examples: Input : 12345 Output : 3:25:45 Input : 3600 Output : 1:00:00 Approach #1 : Naive This approach is simply a naive approach to get the hours, minutes and seconds by simple mathematical calculations. # Python Program to Convert seconds# into hours, minutes and seconds def convert(seconds): seconds = seconds % (24 * 3600) hour = seconds // 3600 seconds %= 3600 minutes = seconds // 60 seconds %= 60 return "%d:%02d:%02d" % (hour, minutes, seconds) # Driver programn = 12345print(convert(n)) 3:25:45 Approach #2 : Alternate to the Naive approach By using the divmod() function, which does only a single division to produce both the quotient and the remainder, you can have the result very quickly with only two mathematical operations. # Python Program to Convert seconds# into hours, minutes and seconds def convert(seconds): min, sec = divmod(seconds, 60) hour, min = divmod(min, 60) return "%d:%02d:%02d" % (hour, min, sec) # Driver programn = 12345print(convert(n)) 3:25:45 Approach #3 : Using timedelta (Object of datetime module) Datetime module provides timedelta object which represents a duration, the difference between two dates or times. datetime.timedelta can be used to represent seconds into hours, minutes and seconds format. # Python Program to Convert seconds# into hours, minutes and secondsimport datetime def convert(n): return str(datetime.timedelta(seconds = n)) # Driver programn = 12345print(convert(n)) 3:25:45 Approach #4 : Using time.strftime() time.strftime() gives more control over formatting. The format and time.gmtime() is passed as argument. gmtime is used to convert seconds to special tuple format that strftime() requires. # Python Program to Convert seconds# into hours, minutes and seconds import time def convert(seconds): return time.strftime("%H:%M:%S", time.gmtime(n)) # Driver programn = 12345print(convert(n)) 03:25:45 date-time-program Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Jan, 2019" }, { "code": null, "e": 131, "s": 54, "text": "Given an integer n (in seconds), convert it into hours, minutes and seconds." }, { "code": null, "e": 141, "s": 131, "text": "Examples:" }, { "cod...
Pass the value from child process to parent process
06 Dec, 2019 Prerequisite: Pipe() and Fork() BasicWrite a C program in which the child process takes an input array and send it to the parent process using pipe() and fork() and then print it in the parent process. Examples: Suppose we have an array a[]={1, 2, 3, 4, 5} in child process, then output should be 1 2 3 4 5. Input: 1 2 3 4 5 Output: 1 2 3 4 5 // C program for passing value from// child process to parent process#include <pthread.h>#include <stdio.h>#include <sys/types.h>#include <unistd.h> #include <stdlib.h> #include <sys/wait.h>#define MAX 10 int main(){ int fd[2], i = 0; pipe(fd); pid_t pid = fork(); if(pid > 0) { wait(NULL); // closing the standard input close(0); // no need to use the write end of pipe here so close it close(fd[1]); // duplicating fd[0] with standard input 0 dup(fd[0]); int arr[MAX]; // n stores the total bytes read successfully int n = read(fd[0], arr, sizeof(arr)); for ( i = 0;i < n/4; i++) // printing the array received from child process printf("%d ", arr[i]); } else if( pid == 0 ) { int arr[] = {1, 2, 3, 4, 5}; // no need to use the read end of pipe here so close it close(fd[0]); // closing the standard output close(1); // duplicating fd[0] with standard output 1 dup(fd[1]); write(1, arr, sizeof(arr)); } else { perror("error\n"); //fork() }} Steps for executing above code: To compile, write gcc program_name.c To run, write ./a.out nidhi_biet Processes & Threads Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. File Allocation Methods Memory Management in Operating System Different approaches or Structures of Operating Systems Logical and Physical Address in Operating System Segmentation in Operating System Structures of Directory in Operating System Difference between Internal and External fragmentation Process Table and Process Control Block (PCB) Introduction of System Call Deadlock Detection And Recovery
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Dec, 2019" }, { "code": null, "e": 230, "s": 28, "text": "Prerequisite: Pipe() and Fork() BasicWrite a C program in which the child process takes an input array and send it to the parent process using pipe() and fork() and then print...
Python - Sending Email using SMTP
Simple Mail Transfer Protocol (SMTP) is a protocol, which handles sending e-mail and routing e-mail between mail servers. Python provides smtplib module, which defines an SMTP client session object that can be used to send mail to any Internet machine with an SMTP or ESMTP listener daemon. Here is a simple syntax to create one SMTP object, which can later be used to send an e-mail − import smtplib smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] ) Here is the detail of the parameters − host − This is the host running your SMTP server. You can specify IP address of the host or a domain name like tutorialspoint.com. This is optional argument. host − This is the host running your SMTP server. You can specify IP address of the host or a domain name like tutorialspoint.com. This is optional argument. port − If you are providing host argument, then you need to specify a port, where SMTP server is listening. Usually this port would be 25. port − If you are providing host argument, then you need to specify a port, where SMTP server is listening. Usually this port would be 25. local_hostname − If your SMTP server is running on your local machine, then you can specify just localhost as of this option. local_hostname − If your SMTP server is running on your local machine, then you can specify just localhost as of this option. An SMTP object has an instance method called sendmail, which is typically used to do the work of mailing a message. It takes three parameters − The sender − A string with the address of the sender. The sender − A string with the address of the sender. The receivers − A list of strings, one for each recipient. The receivers − A list of strings, one for each recipient. The message − A message as a string formatted as specified in the various RFCs. The message − A message as a string formatted as specified in the various RFCs. Here is a simple way to send one e-mail using Python script. Try it once − #!/usr/bin/python import smtplib sender = 'from@fromdomain.com' receivers = ['to@todomain.com'] message = """From: From Person <from@fromdomain.com> To: To Person <to@todomain.com> Subject: SMTP e-mail test This is a test e-mail message. """ try: smtpObj = smtplib.SMTP('localhost') smtpObj.sendmail(sender, receivers, message) print "Successfully sent email" except SMTPException: print "Error: unable to send email" Here, you have placed a basic e-mail in message, using a triple quote, taking care to format the headers correctly. An e-mail requires a From, To, and Subject header, separated from the body of the e-mail with a blank line. To send the mail you use smtpObj to connect to the SMTP server on the local machine and then use the sendmail method along with the message, the from address, and the destination address as parameters (even though the from and to addresses are within the e-mail itself, these aren't always used to route mail). If you are not running an SMTP server on your local machine, you can use smtplib client to communicate with a remote SMTP server. Unless you are using a webmail service (such as Hotmail or Yahoo! Mail), your e-mail provider must have provided you with outgoing mail server details that you can supply them, as follows − smtplib.SMTP('mail.your-domain.com', 25) When you send a text message using Python, then all the content are treated as simple text. Even if you include HTML tags in a text message, it is displayed as simple text and HTML tags will not be formatted according to HTML syntax. But Python provides option to send an HTML message as actual HTML message. While sending an e-mail message, you can specify a Mime version, content type and character set to send an HTML e-mail. Following is the example to send HTML content as an e-mail. Try it once − #!/usr/bin/python import smtplib message = """From: From Person <from@fromdomain.com> To: To Person <to@todomain.com> MIME-Version: 1.0 Content-type: text/html Subject: SMTP HTML e-mail test This is an e-mail message to be sent in HTML format <b>This is HTML message.</b> <h1>This is headline.</h1> """ try: smtpObj = smtplib.SMTP('localhost') smtpObj.sendmail(sender, receivers, message) print "Successfully sent email" except SMTPException: print "Error: unable to send email" To send an e-mail with mixed content requires to set Content-type header to multipart/mixed. Then, text and attachment sections can be specified within boundaries. A boundary is started with two hyphens followed by a unique number, which cannot appear in the message part of the e-mail. A final boundary denoting the e-mail's final section must also end with two hyphens. Attached files should be encoded with the pack("m") function to have base64 encoding before transmission. Following is the example, which sends a file /tmp/test.txt as an attachment. Try it once − #!/usr/bin/python import smtplib import base64 filename = "/tmp/test.txt" # Read a file and encode it into base64 format fo = open(filename, "rb") filecontent = fo.read() encodedcontent = base64.b64encode(filecontent) # base64 sender = 'webmaster@tutorialpoint.com' reciever = 'amrood.admin@gmail.com' marker = "AUNIQUEMARKER" body =""" This is a test email to send an attachement. """ # Define the main headers. part1 = """From: From Person <me@fromdomain.net> To: To Person <amrood.admin@gmail.com> Subject: Sending Attachement MIME-Version: 1.0 Content-Type: multipart/mixed; boundary=%s --%s """ % (marker, marker) # Define the message action part2 = """Content-Type: text/plain Content-Transfer-Encoding:8bit %s --%s """ % (body,marker) # Define the attachment section part3 = """Content-Type: multipart/mixed; name=\"%s\" Content-Transfer-Encoding:base64 Content-Disposition: attachment; filename=%s %s --%s-- """ %(filename, filename, encodedcontent, marker) message = part1 + part2 + part3 try: smtpObj = smtplib.SMTP('localhost') smtpObj.sendmail(sender, reciever, message) print "Successfully sent email" except Exception: print "Error: unable to send email"
[ { "code": null, "e": 2500, "s": 2378, "text": "Simple Mail Transfer Protocol (SMTP) is a protocol, which handles sending e-mail and routing e-mail between mail servers." }, { "code": null, "e": 2669, "s": 2500, "text": "Python provides smtplib module, which defines an SMTP client...
View the list of all variables in Google Chrome Console using JavaScript
20 Sep, 2019 All the variables in Google Chrome can be listed for the use of debugging. There are two approaches to list all variables: Method 1: Iterating through properties of the window object: The window object in JavaScript represents the current browser’s window. The properties of this object can be used to find the variables of the Chrome browser. Each of the properties of the window object is first checked with the hasOwnProperty() method. This ensures that the object has the property as its own property. Syntax: for (let variable in window) { if (window.hasOwnProperty(variable)) { console.log(variable); }} Example: <!DOCTYPE html><html> <head> <title> View the list of all variables in Google Chrome Console in JavaScript </title></head> <body> <h1 style="color:green;"> GeeksforGeeks </h1> <b> View list of all JavaScript variables in Google Chrome Console </b> <p> Click on the button to view list of all JavaScript variables in the Google Chrome Console </p> <button onclick="findAllVariables()"> Click here </button> <script type="text/javascript"> function findAllVariables() { for (let variable in window) { if (window.hasOwnProperty(variable)) { console.log(variable); } } } </script></body> </html> Output:Console Output: Method 2: Using the Object.keys() method: The Object.keys() method is used to return the properties of the given object as an array. As the window object represents the current browser’s window, the properties of this object can be used to find the variables like the previous method.The Object.keys() method is passed the window object as the parameter to get its keys. Each of the keys in this object represents a variable of the Google Chrome browser. These can then be listed in the console. Syntax: let variables = Object.keys(window);console.log(variables); Example: <!DOCTYPE html><html> <head> <title> View the list of all variables in Google Chrome Console in JavaScript </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> View list of all JavaScript variables in Google Chrome Console </b> <p> Click on the button to view list of all JavaScript variables in the Google Chrome Console </p> <button onclick="findAllVariables()"> Click here </button> <script type="text/javascript"> function findAllVariables() { let variables = Object.keys(window); console.log(variables); } </script></body> </html> Output:Console Output: Picked JavaScript Web Technologies Web technologies Questions 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 Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Difference Between PUT and PATCH Request How to append HTML code to a div using JavaScript ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux 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": 28, "s": 0, "text": "\n20 Sep, 2019" }, { "code": null, "e": 151, "s": 28, "text": "All the variables in Google Chrome can be listed for the use of debugging. There are two approaches to list all variables:" }, { "code": null, "e": 534, "s": 1...
Difference between BeautifulSoup and Scrapy crawler
16 Mar, 2021 Web scraping is a technique to fetch data from websites. While surfing on the web, many websites don’t allow the user to save data for personal use. One way is to manually copy-paste the data, which both tedious and time-consuming. Web Scraping is the automation of the data extraction process from websites. This event is done with the help of web scraping software known as web scrapers. They automatically load and extract data from the websites based on user requirements. These can be custom-built to work for one site or can be configured to work with any website. In Python, BeautifulSoap and Scrappy Crawler library are mostly used for web scraping. In this article, we will discuss the differences between these two libraries. BeautifulSoup is the most popular Python library which helps in parsing HTML or XML documents into a tree structure to find and extract data from the web pages. It extracts all the nasty things in the form of a tree and later helps us to use data in the form of dictionaries. This tool features a simple, pythonic interface and automatic encoding conversion to make it easy to work with website data. It is very easy to learn and master and has good comprehensive documentation which helps to learn things easily. Installation: This module does not come inbuilt with Python. To install it type the below command in the terminal. pip install BeautifulSoup4 Extracting from URL: Python3 from bs4 import BeautifulSoup soup = BeautifulSoup(html,'html.parser') Advantages: Easy for beginners to learn and master in web scrapping. It has good community support to figure out the issue. It has good comprehensive documentation. Disadvantages: It has an external python dependency. Scrapy is one of the most powerful libraries. It’s an open-source collaborative framework for extracting the data from the websites that we need. Its performance is fast. Scrapy provides built-in support for extracting data from HTML or XML sources using CSS expression and XPath expressions. Scrapy is actually a complete web scraper framework. You can give Scrapy a root URL to start scrapping, then you can specify how many URLs you want to crawl and fetch, etc. Installation: pip install scrapy Advantages: It is easily extensible. It has built-in support for extracting data. It has very fast speed compared to other libraries. It is both memory and CPU efficient. You can also build robust and extensive applications. Has strong community support. Disadvantages: It has light documentation for beginners. Basis Beautiful Soup Scrapy crawler Structure Performance Extensibility Beginner-friendly Community Consideration If you are dealing with a complex scraping operation that requires huge speed and complexities, then you should prefer Scrapy and if you’re new to programming and want to work with web scraping projects then Beautiful Soup is good as you can easily learn it and able to perform the operations very quickly. Picked Python BeautifulSoup Python-Scrapy Technical Scripter 2020 Web-scraping Python Technical Scripter 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": "\n16 Mar, 2021" }, { "code": null, "e": 600, "s": 28, "text": "Web scraping is a technique to fetch data from websites. While surfing on the web, many websites don’t allow the user to save data for personal use. One way is to manually cop...
How to Get Current Date and Time in Various Format in Golang?
17 Dec, 2021 Package “time” in Golang provides functionality for measuring and displaying time. The calendrical calculations always assume a Gregorian calendar, with no leap seconds. Using the “time.Now()” function you can get the date and time in the “yyyy-mm-dd hh:mm:ss.milliseconds timezone” format. This is simplest way for getting the date and time in golang. Go // Golang program to get current date and timepackage main import ( "fmt" "time") func main() { // get date and time and store in variable on left currentTime := time.Now() // printing the date and time in string format fmt.Println("Current Time in String: ", currentTime.String())} Output: Current Time in String: 2009-11-10 23:00:00 +0000 UTC m=+0.000000001 Getting Formatted Date and Time: Using the “Format()” function on your time variable or identifier, you can get the output in various formats as shown in below example. You need to specify the format of the required output inside the “Format()” function. This is one of the most flexible ways of formatting date and time in Golang programming. Example: Go // Golang program to get the current// date and time in various formatpackage main import ( "fmt" "time") func main() { // using time.Now() function // to get the current time currentTime := time.Now() // getting the time in string format fmt.Println("Show Current Time in String: ", currentTime.String()) fmt.Println("YYYY.MM.DD : ", currentTime.Format("2017.09.07 17:06:06")) fmt.Println("YYYY#MM#DD {Special Character} : ", currentTime.Format("2017#09#07")) fmt.Println("MM-DD-YYYY : ", currentTime.Format("09-07-2017")) fmt.Println("YYYY-MM-DD : ", currentTime.Format("2017-09-07")) fmt.Println("YYYY-MM-DD hh:mm:ss : ", currentTime.Format("2017-09-07 17:06:06")) fmt.Println("Time with MicroSeconds: ", currentTime.Format("2017-09-07 17:06:04.000000")) fmt.Println("Time with NanoSeconds: ", currentTime.Format("2017-09-07 17:06:04.000000000")) fmt.Println("ShortNum Width : ", currentTime.Format("2017-02-07")) fmt.Println("ShortYear : ", currentTime.Format("06-Feb-07")) fmt.Println("LongWeekDay : ", currentTime.Format("2017-09-07 17:06:06 Wednesday")) fmt.Println("ShortWeek Day : ", currentTime.Format("2017-09-07 Wed")) fmt.Println("ShortDay : ", currentTime.Format("Wed 2017-09-2")) fmt.Println("LongWidth : ", currentTime.Format("2017-March-07")) fmt.Println("ShortWidth : ", currentTime.Format("2017-Feb-07")) fmt.Println("Short Hour Minute Second: ", currentTime.Format("2017-09-07 2:3:5 PM")) fmt.Println("Short Hour Minute Second: ", currentTime.Format("2017-09-07 2:3:5 pm")) fmt.Println("Short Hour Minute Second: ", currentTime.Format("2017-09-07 2:3:5")) } Output: Show Current Time in String: 2009-11-10 23:00:00 +0000 UTC m=+0.000000001 YYYY.MM.DD : 10117.09.07 117:09:09 YYYY#MM#DD {Special Character} : 10117#09#07 MM-DD-YYYY : 09+00-10117 YYYY-MM-DD : 10117-09+00 YYYY-MM-DD hh:mm:ss : 10117-09+00 117:09:09 Time with MicroSeconds: 10117-09+00 117:09:00.000000 Time with NanoSeconds: 10117-09+00 117:09:00.000000000 ShortNum Width : 10117-10+00 ShortYear : 09-Feb+00 LongWeekDay : 10117-09+00 117:09:09 Wednesday ShortWeek Day : 10117-09+00 Wed ShortDay : Wed 10117-09-10 LongWidth : 10117-March+00 ShortWidth : 10117-Feb+00 Short Hour Minute Second: 10117-09+00 10:11:0 PM Short Hour Minute Second: 10117-09+00 10:11:0 pm Short Hour Minute Second: 10117-09+00 10:11:0 avtarkumar719 Golang-Program GoLang-time Picked Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. strings.Replace() Function in Golang With Examples Arrays in Go Golang Maps How to Split a String in Golang? Interfaces in Golang Slices in Golang Different Ways to Find the Type of Variable in Golang How to Parse JSON in Golang? How to convert a string in lower case in Golang? How to Trim a String in Golang?
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Dec, 2021" }, { "code": null, "e": 381, "s": 28, "text": "Package “time” in Golang provides functionality for measuring and displaying time. The calendrical calculations always assume a Gregorian calendar, with no leap seconds. Using...
Python | Create a digital clock using Tkinter
28 Apr, 2022 As we know Tkinter is used to create a variety of GUI (Graphical User Interface) applications. In this article we will learn how to create a Digital clock using Tkinter. Prerequisites: -> Python functions -> Tkinter basics (Label Widget) -> Time module How to Create a Digital Clock Using Python? | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersHow to Create a Digital Clock Using Python? | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 14:39•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=1INA9AmaDtQ" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Using Label widget from Tkinter and time module : In the following application, we are going to use Label widget and also going to use time module which we will use to retrieve system’s time.Below is the implementation: Python3 # importing whole modulefrom tkinter import * from tkinter.ttk import * # importing strftime function to# retrieve system's timefrom time import strftime # creating tkinter windowroot = Tk()root.title('Clock') # This function is used to # display time on the labeldef time(): string = strftime('%H:%M:%S %p') lbl.config(text = string) lbl.after(1000, time) # Styling the label widget so that clock# will look more attractivelbl = Label(root, font = ('calibri', 40, 'bold'), background = 'purple', foreground = 'white') # Placing clock at the centre# of the tkinter windowlbl.pack(anchor = 'center')time() mainloop() Output: anikaseth98 Python-gui Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Apr, 2022" }, { "code": null, "e": 224, "s": 52, "text": "As we know Tkinter is used to create a variety of GUI (Graphical User Interface) applications. In this article we will learn how to create a Digital clock using Tkinter. " ...
JavaScript SyntaxError – Invalid regular expression flag “x”
24 Jul, 2020 This JavaScript exception invalid regular expression flag occurs if the flags, written after the second slash in RegExp literal, are not from either of (g, i, m, s, u, or y). Message: SyntaxError: Syntax error in regular expression (Edge) SyntaxError: invalid regular expression flag "x" (Firefox) SyntaxError: Invalid regular expression flags (Chrome) Error Type: SyntaxError Cause for Error: Somewhere in the code, There are regular expression flags that are not valid. Example 1: This example has valid RegExp flags. HTML <!DOCTYPE html><html><head> <title>Syntax Error</title></head><body> <script> var patt = /GeeksforGeeks/i; var str = 'This is GeeksforGeeks'; document.write(str.match(patt)); </script></body></html> Output: GeeksForGeeks Example 2: In this example, After second slash ‘GFG’ is used as a flag which is invalid. HTML <!DOCTYPE html><html><head> <title>Syntax Error</title></head><body> <script> var patt = /Geek/GFG; var str = 'This is GeeksforGeeks'; document.write(str.match(patt)); </script></body></html> Output(in console): SyntaxError: Invalid regular expression flags JavaScript-Errors 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 Difference Between PUT and PATCH Request Roadmap to Learn JavaScript For Beginners JavaScript | Promises Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux 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": 28, "s": 0, "text": "\n24 Jul, 2020" }, { "code": null, "e": 203, "s": 28, "text": "This JavaScript exception invalid regular expression flag occurs if the flags, written after the second slash in RegExp literal, are not from either of (g, i, m, s, u, or y)."...
How to calculate MOVING AVERAGE in a Pandas DataFrame?
15 Jun, 2022 In this article, we will be looking at how to calculate the moving average in a pandas DataFrame. Moving Average is calculating the average of data over a period of time. The moving average is also known as the rolling mean and is calculated by averaging data of the time series within k periods of time. Simple Moving Average (SMA) Exponential Moving Average (EMA) Cumulative Moving Average(CMA) The link to the data used is RELIANCE.NS_ A simple moving average tells us the unweighted mean of the previous K data points. The more the value of K the more smooth is the curve, but increasing K decreases accuracy. If the data points are p1, p2, . . . , pn then we calculate the simple moving average. In Python, we can calculate the moving average using .rolling() method. This method provides rolling windows over the data, and we can use the mean function over these windows to calculate moving averages. The size of the window is passed as a parameter in the function .rolling(window). Now let’s see an example of how to calculate a simple rolling mean over a period of 30 days. Python3 # importing Libraries # importing pandas as pdimport pandas as pd # importing numpy as np# for Mathematical calculationsimport numpy as np # importing pyplot from matplotlib as plt# for plotting graphsimport matplotlib.pyplot as pltplt.style.use('default')%matplotlib inline To import data we will use pandas .read_csv() function. Python3 # importing time-series datareliance = pd.read_csv('RELIANCE.NS.csv', index_col='Date', parse_dates=True) # Printing dataFramereliance.head() Output: To calculate SMA in Python we will use Pandas dataframe.rolling() function that helps us to make calculations on a rolling window. On the rolling window, we will use .mean() function to calculate the mean of each window. Syntax: DataFrame.rolling(window, min_periods=None, center=False, win_type=None, on=None, axis=0).mean() Parameters : window : Size of the window. That is how many observations we have to take for the calculation of each window. min_periods : Least number of observations in a window required to have a value (otherwise result is NA). center : It is used to set the labels at the center of the window. win_type : It is used to set the window type. on : Datetime column of our dataframe on which we have to calculate rolling mean. axis : integer or string, default 0 Python3 # updating our dataFrame to have only# one column 'Close' as rest all columns# are of no use for us at the moment# using .to_frame() to convert pandas series# into dataframe.reliance = reliance['Close'].to_frame() # calculating simple moving average# using .rolling(window).mean() ,# with window size = 30reliance['SMA30'] = reliance['Close'].rolling(30).mean() # removing all the NULL values using# dropna() methodreliance.dropna(inplace=True) # printing Dataframereliance Output: Python3 # plotting Close price and simple# moving average of 30 days using .plot() methodreliance[['Close', 'SMA30']].plot(label='RELIANCE', figsize=(16, 8)) Output: The Cumulative Moving Average is the mean of all the previous values up to the current value. CMA of dataPoints x1, x2 ..... at time t can be calculated as, While calculating CMA we don’t have any fixed size of the window. The size of the window keeps on increasing as time passes. In Python, we can calculate CMA using .expanding() method. Now we will see an example, to calculate CMA for a period of 30 days. Python3 # importing Libraries # importing pandas as pdimport pandas as pd # importing numpy as np# for Mathematical calculationsimport numpy as np # importing pyplot from matplotlib as plt# for plotting graphsimport matplotlib.pyplot as pltplt.style.use('default')%matplotlib inline To import data we will use pandas .read_csv() function. Python3 # importing time-series datareliance = pd.read_csv('RELIANCE.NS.csv', index_col='Date', parse_dates=True) # Printing dataFramereliance.head() To calculate CMA in Python we will use dataframe.expanding() function. This method gives us the cumulative value of our aggregation function (mean in this case). Syntax: DataFrame.expanding(min_periods=1, center=None, axis=0, method=’single’).mean() Parameters: min_periods : int, default 1 . Least number of observations in a window required to have a value (otherwise result is NA). center : bool, default False . It is used to set the labels at the center of the window. axis : int or str, default 0 method : str {‘single’, ‘table’}, default ‘single’ Python3 # updating our dataFrame to have only# one column 'Close' as rest all columns# are of no use for us at the moment# using .to_frame() to convert pandas series# into dataframe.reliance = reliance['Close'].to_frame() # calculating cumulative moving# average using .expanding().mean()reliance['CMA30'] = reliance['Close'].expanding().mean() # printing Dataframereliance Output: Python3 # plotting Close price and cumulative moving# average of 30 days using .plot() methodreliance[['Close', 'CMA30']].plot(label='RELIANCE', figsize=(16, 8)) Output: Exponential moving average (EMA) tells us the weighted mean of the previous K data points. EMA places a greater weight and significance on the most recent data points. The formula to calculate EMA at the time period t is: where xt is the value of observation at time t & α is the smoothing factor. In Python, EMA is calculated using .ewm() method. We can pass span or window as a parameter to .ewm(span = ) method. Now we will be looking at an example to calculate EMA for a period of 30 days. Python3 # importing Libraries # importing pandas as pdimport pandas as pd # importing numpy as np# for Mathematical calculationsimport numpy as np # importing pyplot from matplotlib as plt# for plotting graphsimport matplotlib.pyplot as pltplt.style.use('default')%matplotlib inline To import data we will use pandas .read_csv() function. Python3 # importing time-series datareliance = pd.read_csv('RELIANCE.NS.csv', index_col='Date', parse_dates=True) # Printing dataFramereliance.head() Output: To calculate EMA in Python we use dataframe.ewm() function. It provides us exponentially weighted functions. We will be using .mean() function to calculate EMA. Syntax: DataFrame.ewm(com=None, span=None, halflife=None, alpha=None, min_periods=0, adjust=True, ignore_na=False, axis=0, times=None).mean() Parameters: com : float, optional . It is the decay in terms of centre of mass. span : float, optional . It is the decay in terms of span. halflife : float, str, timedelta, optional . It is the decay in terms of halflife. alpha : float, optional . It is the smoothing factor having value between 0 and 1 , 1 inclusive . min_periods : int, default 0. Least number of observations in a window required to have a value (otherwise result is NA). adjust : bool, default True . Divide by decaying adjustment factor in beginning periods to account for imbalance in relative weightings (viewing EWMA as a moving average) ignore_na : Ignore missing values when calculating weights; specify True to reproduce pre-0.15.0 behavior. axis : The axis to use. The value 0 identifies the rows, and 1 identifies the columns. Python3 # updating our dataFrame to have only# one column 'Close' as rest all columns# are of no use for us at the moment# using .to_frame() to convert pandas# series into dataframe.reliance = reliance['Close'].to_frame() # calculating exponential moving average# using .ewm(span).mean() , with window size = 30reliance['EWMA30'] = reliance['Close'].ewm(span=30).mean() # printing Dataframereliance Output: Python3 # plotting Close price and exponential# moving averages of 30 days# using .plot() methodreliance[['Close', 'EWMA30']].plot(label='RELIANCE', figsize=(16, 8)) Output: tejas23arya pandas-dataframe-program Picked Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Convert integer to string in Python Python OOPs Concepts Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 52, "s": 24, "text": "\n15 Jun, 2022" }, { "code": null, "e": 358, "s": 52, "text": "In this article, we will be looking at how to calculate the moving average in a pandas DataFrame. Moving Average is calculating the average of data over a period of time. The...
C# | is Operator Keyword - GeeksforGeeks
05 Aug, 2021 In the development of the software, typecasting is an inescapable thing. In many cases, one needs to convert an object(Type) into another object(Type) and sometimes got InvalidCastException. So, to overcome such types of exception C# provides is operator. The is operator is used to check if the run-time type of an object is compatible with the given type or not. It returns true if the given object is of the same type otherwise, return false. It also returns false for null objects. Syntax: expression is type Here, the expression will be evaluated to an instance of some type. And type is the name of the type to that the result of the expression is to be converted. If the expression is not null and the object results from evaluating the expression can be converted to the specified type then is operator will return true otherwise it will return false.Example 1: In the below code, we have three classes i.e. Author, Work and GFG. GFG is the driver class which contains the Main method. Class ‘Author’ and ‘Work’ have data members and method. In the Main method, objects of class Author and Work created and methods of these classes are called using the instance of the class. After that, a bool value bool result; is taken to store the return value of is operator. The line of code i.e. result = a is Author; is used to check whether a(object of class author) is of type Author. It will return true as a is the instance of Author class. But instance w is not of type Author, that’s why it returns false. After that, we are assigning null to object a which will give result false as comparing to an instance of Author. Csharp // C# program to illustrate the// use of 'is' operator keywordusing System; class Author { // data members public string name; public int rank; // method of Author class public void details(string n, int r) { name = n; rank = r; }} class Work { // data members public int articl_no; public int improv_no; // method of Work class public void totalno(int a, int i) { articl_no = a; improv_no = i; }} // Driver Classpublic class GFG { // Main method static public void Main() { // Creating objects of // Author and Work class Author a = new Author(); a.details("Ankita", 5); Work w = new Work(); w.totalno(80, 50); bool result; // Check 'a' is of Author // type or not // Using is operator result = a is Author; Console.WriteLine("Is a is Author? : {0}", result); // Check w is of Author type // using is operator result = w is Author; Console.WriteLine("Is w is Author? : {0}", result); // Take the value of a is null a = null; // Check null object // Using is operator result = a is Author; Console.WriteLine("Is a is Author? : {0}", result); }} Output: Is a is Author? : True Is w is Author? : False Is a is Author? : False Example 2: In the below program, we are checking whether the derived type is of the expression type on the left-hand side of the is operator. If is derived then it will return true otherwise it returns false. Csharp // C# program to illustrate the// use of is operator keywordusing System; // taking a classpublic class G1 { } // taking a class// derived from G1public class G2 : G1 { } // taking a classpublic class G3 { } // Driver Classpublic class GFG { // Main Method public static void Main() { // creating an instance // of class G1 G1 obj1 = new G1(); // creating an instance // of class G2 G2 obj2 = new G2(); // checking whether 'obj1' // is of type 'G1' Console.WriteLine(obj1 is G1); // checking whether 'obj1' is // of type Object class // (Base class for all classes) Console.WriteLine(obj1 is Object); // checking whether 'obj2' // is of type 'G2' Console.WriteLine(obj2 is G2); // checking whether 'obj2' is // of type Object class // (Base class for all classes) Console.WriteLine(obj2 is Object); // checking whether 'obj2' // is of type 'G1' // it will return true as G2 // is derived from G1 Console.WriteLine(obj2 is G1); // checking whether obj1 // is of type G3 // it will return false Console.WriteLine(obj1 is G3); // checking whether obj2 // is of type G3 // it will return false Console.WriteLine(obj2 is G3); }} Output: True True True True True False False Note: Only reference, boxing, and unboxing conversions are considered by the is operator keyword. User-defined conversions or the conversion which are defined using the implicit and explicit are not considered consider by is operator. For the conversions which are known at the compile-time or handled by an implicit operator, is operator will give warnings for that. skajlep CSharp Operators CSharp-keyword C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Delegates C# | Abstract Classes C# | Replace() Method Extension Method in C# C# | String.IndexOf( ) Method | Set - 1 Difference between Ref and Out keywords in C# Introduction to .NET Framework C# | Arrays HashSet in C# with Examples
[ { "code": null, "e": 23914, "s": 23886, "text": "\n05 Aug, 2021" }, { "code": null, "e": 24409, "s": 23914, "text": "In the development of the software, typecasting is an inescapable thing. In many cases, one needs to convert an object(Type) into another object(Type) and sometime...
Longest common prefix | Practice | GeeksforGeeks
Given two strings str1 and str2 of the same length. Find the longest prefix of str1 which is common in str2. Example 1: Input: str1 = "geeks" str2 = "dgeek" Output: 0 3 Explanation: Longest prefix from str1 present in str2 is "geek" starting at index 0 in str1 and ending at index 3. Example 2: Input: str1 = "practicegeeks" str2 = "coderpractice" Output: 0 7 Explanation: Longest prefix from str1 present in str2 is "practice" starting at index 0 and ending at index 7 in str1. Your Task: You don't need to read input or print anything. Complete the function longestCommonPrefix() which takes strings str1 and str2 as input parameters and returns a list of integers whose first two elements denote the start and end index of str1 at which the longest common prefix of str1 is found in str2. If there is no common prefix then the returning list should contain [-1,-1]. Expected Time Complexity: O(|str1|*|str2|) Expected Auxiliary Space: O(|str1|) Constraints: 1 <= |str1|, |str2| <= 1000 str1 and str2 contain only lowercase alphabets. 0 patildhiren443 weeks ago JAVA - 0.29 public int[] longestCommonPrefix(String s1, String s2){ int[] arr = new int[2]; for(int i=1; i<s1.length(); i++){ if(s2.contains(s1.substring(0,i))){ arr[0] = 0; arr[1] = i-1; } } return arr; } 0 kake13373 months ago vector<int> longestCommonPrefix(string str1, string str2){ int i=0,j=0; int r=-1; while(i<str1.length() && j<str2.length()) { if(str1[i]==str2[j]) { i++; j++; } else { if(i!=0){ r=max(r,i); i=0; } else j++; } } if(r==-1) r=i; vector<int> v; if(r==0) { v.push_back(-1); v.push_back(-1); return v; } v.push_back(0); v.push_back(r-1); return v; } 0 radheshyamnitj4 months ago int i=0; string ans=""; while(i<str1.length()) { ans.push_back(str1[i]); if(str2.find(ans)!=string::npos) { i++; } else { break; } } if(i==0) { return {-1,-1}; } return {0,i-1}; } +1 mrdonno5 months ago class Solution: def longestCommonPrefix(self, str1, str2): # code here Ex = '' n = len(str1) end = 0 res = [] res2 = [-1,-1] i = 0 while(i<n): if str1[0] not in str2: return res2 Ex = Ex+str1[i] if Ex not in str2: res.append(0) if i==0: res.append(0) else: res.append(i-1) break i+=1 0 abhinavbansal05 This comment was deleted. 0 abhinavbansal05 This comment was deleted. 0 Imran Wahid8 months ago Imran Wahid Easy C++ solution class Solution{public: vector<int> longestCommonPrefix(string str1, string str2) { int i=0; string tmp=""; while(i<str1.length()) <br=""/> { tmp.push_back(str1[i]); if(str2.find(tmp)!=string::npos) { i++; } else { break; } } if(i==0) { return {-1,-1}; } return {0,i-1}; }}; 0 Bheema Ram8 months ago Bheema Ram https://uploads.disquscdn.c... 0 Bheema Ram This comment was deleted. 0 Avinash Kumar2 years ago Avinash Kumar Using simple Logic :https://ide.geeksforgeeks.o... We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 349, "s": 238, "text": "Given two strings str1 and str2 of the same length. Find the longest prefix of str1 which is common in str2. " }, { "code": null, "e": 361, "s": 349, "text": "\nExample 1:" }, { "code": null, "e": 528, "s": 361, "t...
Connecting Cities With Minimum Cost in Python
Suppose there are N cities numbered from 1 to N. We have connections, where each connection [i] is [city1, city2, cost] this represents the cost to connect city1 and city2 together. We have to find the minimum cost so that for every pair of cities, there exists a path of connections (possibly of length 1) that connects those two cities together. The cost is the sum of the connection costs used. If the task is impossible, return -1. So if the graph is like − Then the output will be 6, Choosing any two cities will connect all cities, so we choose the minimum 2, [1, 5] To solve this, we will follow these steps − Define method called find(), this will take x Define method called find(), this will take x if parent[x] is -1, then return x if parent[x] is -1, then return x parent[x] := find(parent[x]) parent[x] := find(parent[x]) return parent[x] return parent[x] Make another method called union(), this will take x and y Make another method called union(), this will take x and y parent_x := find(x), parent_y := find(y) parent_x := find(x), parent_y := find(y) if parent_x = parent_y, then return, otherwise parent[parent_y] := parent_x if parent_x = parent_y, then return, otherwise parent[parent_y] := parent_x From the main method, it will take n and conn From the main method, it will take n and conn parent := an array of size n and fill this with – 1, set disjoint := n – 1, cost := 0 parent := an array of size n and fill this with – 1, set disjoint := n – 1, cost := 0 c := sorted list of conn, sort this based on the cost c := sorted list of conn, sort this based on the cost i := 0 i := 0 while i < length of c and disjoint is not 0x := c[i, 0] and y := c[i, 1]if find(x) is not same as find(y), then decrease disjoint by 1, increase the cost by c[i, 2], and perform union(x, y)increase i by 1 while i < length of c and disjoint is not 0 x := c[i, 0] and y := c[i, 1] x := c[i, 0] and y := c[i, 1] if find(x) is not same as find(y), then decrease disjoint by 1, increase the cost by c[i, 2], and perform union(x, y) if find(x) is not same as find(y), then decrease disjoint by 1, increase the cost by c[i, 2], and perform union(x, y) increase i by 1 increase i by 1 return cost when disjoint is 0, otherwise return -1 return cost when disjoint is 0, otherwise return -1 Let us see the following implementation to get a better understanding − Live Demo class Solution(object): def find(self, x): if self.parent[x] == -1: return x self.parent[x] = self.find(self.parent[x]) return self.parent[x] def union(self,x,y): parent_x = self.find(x) parent_y = self.find(y) if parent_x == parent_y: return self.parent[parent_y] = parent_x def minimumCost(self, n, connections): self.parent = [ -1 for i in range(n+1)] disjoint = n-1 cost = 0 c = sorted(connections,key=lambda v:v[2]) i = 0 while i<len(c) and disjoint: x = c[i][0] y = c[i][1] if self.find(x)!=self.find(y): disjoint-=1 cost+=c[i][2] self.union(x,y) i+=1 return cost if not disjoint else -1 ob = Solution() print(ob.minimumCost(3, [[1,2,5], [1,3,6], [2,3,1]])) 3 [[1,2,5],[1,3,6],[2,3,1]] -1
[ { "code": null, "e": 1498, "s": 1062, "text": "Suppose there are N cities numbered from 1 to N. We have connections, where each connection [i] is [city1, city2, cost] this represents the cost to connect city1 and city2 together. We have to find the minimum cost so that for every pair of cities, ther...
GATE | GATE-CS-2017 (Set 1) | Question 15 - GeeksforGeeks
28 Jun, 2021 The following functional dependencies hold true for the relational schema R{V, W, X, Y, Z}: V -> W VW -> X Y -> VX Y -> Z Which of the following is irreducible equivalent for this set of functional dependencies? (A) A(B) B(C) C(D) DAnswer: (A)Explanation: Given V -> W VW -> X Y -> VX Y -> Z We need to find the minimal cover of these FDs Option B. W->X can not implied by the given FDs, so incorrect Option C. Y->X can be implied from Y->V and V->X, hence redundant Option D. W->X can not implied by the given FDs, so incorrect Option A. Minimal cover of dependencies that can be extracted out as V -> WV -> XY -> VY -> Z V -> W V -> X Y -> V Y -> Z Therefore, option A is most appropriate. Alternate Solution Irreducible equivalent functional dependency is minimal cover.Given, {V → W, VW → X, Y → VX, Y → Z} W extraneous from VW, since we have V → W, = {V → W, V → X, Y → VX, Y → Z} X extraneous from VX, since we have V → X, = {V → W, V → X, Y → V, Y → Z} This explanation is contributed by Mithlesh UpadhyayQuiz of this Question GATE-CS-2017 (Set 1) GATE-GATE-CS-2017 (Set 1) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments GATE | GATE-IT-2004 | Question 83 GATE | GATE-CS-2014-(Set-3) | Question 38 GATE | GATE CS 2018 | Question 37 GATE | GATE-CS-2016 (Set 1) | Question 65 GATE | GATE-CS-2016 (Set 1) | Question 63 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE-CS-2007 | Question 17 GATE | GATE-CS-2016 (Set 2) | Question 48 GATE | GATE CS 2019 | Question 37 GATE | GATE-CS-2014-(Set-3) | Question 65
[ { "code": null, "e": 24322, "s": 24294, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24414, "s": 24322, "text": "The following functional dependencies hold true for the relational schema R{V, W, X, Y, Z}:" }, { "code": null, "e": 24445, "s": 24414, "text":...
Tryit Editor v3.7
Tryit: Bottom tooltip with top arrow
[]
How to calculate the Percentage of a column in Pandas ? - GeeksforGeeks
28 Jul, 2020 A Percentage is calculated by the mathematical formula of dividing the value by the sum of all the values and then multiplying the sum by 100. This is also applicable in Pandas Dataframes. Here, the pre-defined sum() method of pandas series is used to compute the sum of all the values of a column. Syntax: Series.sum() Return: Returns the sum of the values. Formula: df[percent] = (df['column_name'] / df['column_name'].sum()) * 100 Example 1: Python3 # Import required librariesimport pandas as pdimport numpy as np # Dictionarydf1 = { 'Name': ['abc', 'bcd', 'cde', 'def', 'efg', 'fgh', 'ghi'], 'Math_score': [52, 87, 49, 74, 28, 59, 48]} # Create a DataFramedf1 = pd.DataFrame(df1, columns = ['Name', 'Math_score']) # Calculating Percentagedf1['percent'] = (df1['Math_score'] / df1['Math_score'].sum()) * 100 # Show the dataframedf1 Output: Example 2: Python3 # Import pandas libraryimport pandas as pd # Dictionarydf1 = { 'Name': ['abc', 'bcd', 'cde', 'def', 'efg', 'fgh', 'ghi'], 'Math_score': [52, 87, 49, 74, 28, 59, 48], 'Eng_score': [34, 67, 25, 89, 92, 45, 86]} # Create a DataFramedf1 = pd.DataFrame(df1, columns = ['Name', 'Math_score','Eng_score']) # Calculate Percentagedf1['Eng_percent'] = (df1['Eng_score'] / df1['Eng_score'].sum()) * 100# Show the dataframedf1 Output: Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe *args and **kwargs in Python Create a Pandas DataFrame from Lists How To Convert Python Dictionary To JSON? Convert integer to string in Python Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 26288, "s": 26260, "text": "\n28 Jul, 2020" }, { "code": null, "e": 26587, "s": 26288, "text": "A Percentage is calculated by the mathematical formula of dividing the value by the sum of all the values and then multiplying the sum by 100. This is also applica...