title stringlengths 3 221 | text stringlengths 17 477k | parsed listlengths 0 3.17k |
|---|---|---|
How to convert Number to Boolean in JavaScript ? - GeeksforGeeks | 08 Jan, 2021
We convert a Number to Boolean by using the JavaScript Boolean() method. A JavaScript boolean results in one of the two values i.e true or false. However, if one wants to convert a variable that stores integer “0” or “1” into Boolean Value i.e “true” or “false”.
Syntax:
Boolean(variable/expression)
Example:
HTML
<!DOCTYPE html><html> <body> <center> <h1 style="color:green"> GeeksforGeeks </h1> <h4> Click the button to change the number value into boolean. </h4> <button onclick="myFunction()">Change</button> <p>The number value of the variable is :</p> <p id="result"></p> <script> // Initializing boolvalue as true var numvalue = 1; // JavaScript program to illustrate boolean // conversion using ternary operator function myFunction() { document.getElementById("result") .innerHTML = Boolean(numvalue); } </script> </center></body> </html>
Note: If the above Boolean() method is called as Boolean(!numvalue), it shows the result as “false“. Similarly if it is called as Boolean(!!numvalue), it gives the result as “true“.
Output:
Before clicking on button:
After clicking on button:
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.
Comments
Old Comments
Types of CSS (Cascading Style Sheet)
How to create footer to stay at the bottom of a Web page?
Making a div vertically scrollable using CSS
How to Upload Image into Database and Display it using PHP ?
Build a Survey Form using HTML and CSS
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Types of CSS (Cascading Style Sheet)
Hide or show elements in HTML using display property
How to Insert Form Data into Database using PHP ? | [
{
"code": null,
"e": 24421,
"s": 24393,
"text": "\n08 Jan, 2021"
},
{
"code": null,
"e": 24685,
"s": 24421,
"text": "We convert a Number to Boolean by using the JavaScript Boolean() method. A JavaScript boolean results in one of the two values i.e true or false. However, if one w... |
Display the Operating System name in Java | Use the System.getProperty() method in Java to get the Operating System name.
It’s syntax is −
String getProperty(String key)
Above, the key is the name of the system property. Since, we want the OS name, therefore we will add the key as −
os.name
Live Demo
public class Demo {
public static void main(String[] args) {
System.out.print("Operating System: ");
System.out.println(System.getProperty("os.name"));
}
}
Operating System: Linux | [
{
"code": null,
"e": 1140,
"s": 1062,
"text": "Use the System.getProperty() method in Java to get the Operating System name."
},
{
"code": null,
"e": 1157,
"s": 1140,
"text": "It’s syntax is −"
},
{
"code": null,
"e": 1188,
"s": 1157,
"text": "String getProper... |
Find the Second Largest Element in a Linked List in C++ | Here we will see the second largest element in the linked list. Suppose there are n different nodes with numerical values. So if the list is like [12, 35, 1, 10, 34, 1], then second largest element will be 34.
This process is similar to the finding of second largest element in an array, we will traverse through the list and find second largest element by comparing.
#include<iostream>
using namespace std;
class Node {
public:
int data;
Node *next;
};
void prepend(Node** start, int new_data) {
Node* new_node = new Node;
new_node->data = new_data;
new_node->next = NULL;
if ((*start) != NULL){
new_node->next = (*start);
*start = new_node;
}
(*start) = new_node;
}
int secondLargestElement(Node *start) {
int first_max = INT_MIN, second_max = INT_MIN;
Node *p = start;
while(p != NULL){
if (p->data > first_max) {
second_max = first_max;
first_max = p->data;
}else if (p->data > second_max)
second_max = p->data;
p = p->next;
}
return second_max;
}
int main() {
Node* start = NULL;
prepend(&start, 15);
prepend(&start, 16);
prepend(&start, 10);
prepend(&start, 9);
prepend(&start, 7);
prepend(&start, 17);
cout << "Second largest element is: " << secondLargestElement(start);
}
Second largest element is: 16 | [
{
"code": null,
"e": 1272,
"s": 1062,
"text": "Here we will see the second largest element in the linked list. Suppose there are n different nodes with numerical values. So if the list is like [12, 35, 1, 10, 34, 1], then second largest element will be 34."
},
{
"code": null,
"e": 1430,
... |
Enum Methods in Java | Let us learn about some of the methods in Java.
Get the ordinal of an enumeration constant in Java using ordinal() method in Java.
The following is an example −
Live Demo
public class Demo {
enum Devices {
LAPTOP, MOBILE, TABLET, DESKTOP;
}
public static void main(String[] args) {
Devices d1, d2, d3, d4;
d1 = Devices.LAPTOP;
d2 = Devices.LAPTOP;
d3 = Devices.TABLET;
d4 = Devices.DESKTOP;
System.out.println("Ordinal Values...");
for(Devices d : Devices.values()) {
System.out.print(d+" = ");
System.out.println(d.ordinal());
}
}
}
Ordinal Values...
LAPTOP = 0
MOBILE = 1
TABLET = 2
DESKTOP = 3
It returns true if the specified object is equal to this enum constant.
Let us see an example −
Live Demo
public class Demo {
enum Devices {
LAPTOP, MOBILE, TABLET;
}
public static void main(String[] args) {
Devices d1, d2, d3;
d1 = Devices.LAPTOP;
d2 = Devices.LAPTOP;
d3 = Devices.TABLET;
if(d1.equals(d2))
System.out.println("Devices are same.");
else
System.out.println("Devices are different.");
}
}
Devices are same. | [
{
"code": null,
"e": 1110,
"s": 1062,
"text": "Let us learn about some of the methods in Java."
},
{
"code": null,
"e": 1193,
"s": 1110,
"text": "Get the ordinal of an enumeration constant in Java using ordinal() method in Java."
},
{
"code": null,
"e": 1223,
"s":... |
Predicting Stock Price Direction using Support Vector Machines - GeeksforGeeks | 23 Sep, 2021
We are going to implement an End-to-End project using Support Vector Machines to live Trade For us. You Probably must have Heard of the term stock market which is known to have made the lives of thousands and to have destroyed the lives of millions. If you are not familiar with the stock market you can surf some basic Stuff about markets.
Python
Sklearn- Support Vector Classifier
Yahoo Finance
Jupyter-Notebook
BlueShift
Python3
# Machine learningfrom sklearn.svm import SVCfrom sklearn.metrics import accuracy_score # For data manipulationimport pandas as pdimport numpy as np # To plotimport matplotlib.pyplot as pltplt.style.use('seaborn-darkgrid') # To ignore warningsimport warningswarnings.filterwarnings("ignore")
We will Read the Stock Data Downloaded From Yahoo Finance Website. The Data Is stored in OHLC(Open, High, Low, Close) format in a CSV file. To read a CSV file, you can use the read_csv() method of pandas.
Syntax :
pd.read_csv(filename, index_col)
Note: We have downloaded the past 1 year data of Reliance Industries Trading In NSE from Yahoo Finance Website.
File Used:
Python3
# Read the csv file using read_csv # method of pandasdf = pd.read_csv('RELIANCE.csv')df
Output:
The data needed to be processed before use such that the date column should act as an index to do that
Python3
# Changes The Date column as index columnsdf.index = pd.to_datetime(df['Date'])df # drop The original date columndf = df.drop(['Date'], axis='columns')df
Output:
Explanatory or independent variables are used to predict the value response variable. The X is a dataset that holds the variables which are used for prediction. The X consists of variables such as ‘Open – Close’ and ‘High – Low’. These can be understood as indicators based on which the algorithm will predict tomorrow’s trend. Feel free to add more indicators and see the performance
Python3
# Create predictor variablesdf['Open-Close'] = df.Open - df.Closedf['High-Low'] = df.High - df.Low # Store all predictor variables in a variable XX = df[['Open-Close', 'High-Low']]X.head()
Output:
The target variable is the outcome which the machine learning model will predict based on the explanatory variables. y is a target dataset storing the correct trading signal which the machine learning algorithm will try to predict. If tomorrow’s price is greater than today’s price then we will buy the particular Stock else we will have no position in the. We will store +1 for a buy signal and 0 for a no position in y. We will use where() function from NumPy to do this.
Syntax:
np.where(condition,value_if_true,value_if_false)
Python3
# Target variablesy = np.where(df['Close'].shift(-1) > df['Close'], 1, 0)y
Output:
We will split data into training and test data sets. This is done so that we can evaluate the effectiveness of the model in the test dataset
Python3
split_percentage = 0.8split = int(split_percentage*len(df)) # Train data setX_train = X[:split]y_train = y[:split] # Test data setX_test = X[split:]y_test = y[split:]
We will use SVC() function from sklearn.svm.SVC library to create our classifier model using the fit() method on the training data set.
Python3
# Support vector classifiercls = SVC().fit(X_train, y_train)
We will compute the accuracy of the algorithm on the train and test the data set by comparing the actual values of the signal with the predicted values of the signal. The function accuracy_score() will be used to calculate the accuracy.
An accuracy of 50%+ in test data suggests that the classifier model is effective.
We will predict the signal (buy or sell) using the cls.predict() function.
Python3
df['Predicted_Signal'] = cls.predict(X)
Calculate Daily returns
Python3
# Calculate daily returnsdf['Return'] = df.Close.pct_change()
Calculate Strategy Returns
Python3
# Calculate strategy returnsdf['Strategy_Return'] = df.Return *df.Predicted_Signal.shift(1)
Calculate Cumulative Returns
Python3
# Calculate Cumulutive returnsdf['Cum_Ret'] = df['Return'].cumsum()df
Calculate Strategy Cumulative Returns
Python3
# Plot Strategy Cumulative returns df['Cum_Strategy'] = df['Strategy_Return'].cumsum()df
Python3
import matplotlib.pyplot as plt%matplotlib inline plt.plot(Df['Cum_Ret'],color='red')plt.plot(Df['Cum_Strategy'],color='blue')
Output:
As You Can See Our Strategy Seem to be Totally Outperforming the Performance of The Reliance Stock. Our Strategy(Blue Line) Provided the return of 18.87 % in the last 1 year whereas the stock of Reliance Industries (Red Line) Provides the Return of just 5.97% in the last 1 year.
1. TCS
Stock Return Over Last 1 year - 48%
Strategy result - 48.9 %
2. ICICI BANK
Stock Return Over Last 1 year - 48%
Strategy result - 48.9 %
The Strategy Coded Can be easily deployed in the live market and can also be back-tested on any number of data throughout exchanges. The deployment can be easily done Using the BlueShift Platform. It is an Interactive Platform with Live Data Feed and connections through various Brokers. You can Do Back-testing On the BlueShift platform for any Number Of Time with data from various Exchanges.
The Strategy Provider Promising Returns During Live market. Currently, I have just trained the model based on previous day levels however to increase the accuracy of the model we also add various Technical Indicators for training the model such as RSI, ADX, ATR, MACD, Stochastic, and Many more.
To Get More Accuracy in Live Market Deep Learning Proved to be Very Effective In Trading in a live market. We can Automate our Trades using Reinforcement Learning and also using Stacked LSTM which gives exponential Rise for our Strategy returns.
Note: Real Money Should not be deployed until complete Backtesting of Strategy and without promising returns by Strategy during Paper-Trading
Blogathon-2021
Python-projects
Blogathon
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install Numpy on MacOS?
Dart - Null Aware Operators
Format Dates in Flutter
How to Install Tkinter in Windows?
Designing algorithm to solve Ball Sort Puzzle
Naive Bayes Classifiers
Linear Regression (Python Implementation)
Decision Tree
Reinforcement learning
ML | Linear Regression | [
{
"code": null,
"e": 24447,
"s": 24419,
"text": "\n23 Sep, 2021"
},
{
"code": null,
"e": 24788,
"s": 24447,
"text": "We are going to implement an End-to-End project using Support Vector Machines to live Trade For us. You Probably must have Heard of the term stock market which is ... |
CSS - Pseudo-class :link | The :link pseudo-class is used to add special effect to an unvisited link.
While defining pseudo-classes in a <style>...</style> block, following points should be taken care −
a:hover MUST come after a:link and a:visited in the CSS definition in order to be effective.
a:hover MUST come after a:link and a:visited in the CSS definition in order to be effective.
a:active MUST come after a:hover in the CSS definition in order to be effective.
a:active MUST come after a:hover in the CSS definition in order to be effective.
Pseudo-class names are not case-sensitive.
Pseudo-class names are not case-sensitive.
Pseudo-class are different from CSS classes but they can be combined.
Pseudo-class are different from CSS classes but they can be combined.
color − Any valid color value.
color − Any valid color value.
Anchor / Link element.
Following is the example which demonstrates how to use :link class to set the link color.
<html>
<head>
<style type = "text/css">
a:link {color:#000000}
</style>
</head>
<body>
<a href = "/html/index.htm">Black Link</a>
</body>
</html>
This will produce following black link −
33 Lectures
2.5 hours
Anadi Sharma
26 Lectures
2.5 hours
Frahaan Hussain
44 Lectures
4.5 hours
DigiFisk (Programming Is Fun)
21 Lectures
2.5 hours
DigiFisk (Programming Is Fun)
51 Lectures
7.5 hours
DigiFisk (Programming Is Fun)
52 Lectures
4 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2701,
"s": 2626,
"text": "The :link pseudo-class is used to add special effect to an unvisited link."
},
{
"code": null,
"e": 2802,
"s": 2701,
"text": "While defining pseudo-classes in a <style>...</style> block, following points should be taken care −"
},
... |
Water Detection in High Resolution Satellite Images using the waterdetect python package | by Maurício Cordeiro | Towards Data Science | This story is divided in two parts: Methodology and the waterdetect package. In the methodology, the main concepts of the algorithm are given, in order to provide the reader a better understanding of the package and how to tune it. The second part is a tutorial on the waterdetect package with sample codes to run it.
For information about the course Introduction to Python for Scientists (available on YouTube) and other articles like this, please visit my website cordmaur.carrd.co.
The use of deep learning techniques for remote sensing applications has been increasing in recent years. The recently published review paper “Object Detection and Image Segmentation with Deep Learning on Earth Observation Data: A Review-Part I: Evolution and Recent Trends” (Hoeser and Kuenzer 2020)[1] presents the evolution of Convolutional Neural Networks (CNN) in satellite applications, notably Object Detection and Image Segmentation, where it achieves state-of-the-art results.
One drawback of this approach is the need to train the neural network for every possible condition (water type, atmospheric condition, etc.) and there are few pretrained models ready to be used anywhere on the globe (DeepWaterMap 2.0 being one of them)(Isikdogan et al., 2017; Isikdogan et al., 2019)[2, 3]. Besides that, there are moments where we just want a quick unsupervised tool to do the task, without the complexities of model training. In such cases, I believe there is still room for a more traditional approach and that’s what is proposed in waterdetect package.
To fill this gap we have recently proposed the methodology that is implmented in the waterdetect package through the following paper: “Automatic Water Detection from Multidimensional Hierarchical Clustering for Sentinel-2 Images and a Comparison with Level 2A Processors”(Cordeiro et. al., 2020)[4].
The method combines a multidimensional agglomerative clustering with a machine learning classifier to make the detection effective and fast at the same time. It’s not the objective of this post to enter in the details of the algorithm, as it is already described in the paper. However, some knowledge on the rational behind it is needed to make proper use of the package.
Detecting water
The main idea of the algorithm is to combine water indexes (NDWI, MNDWI, etc.) with reflectance bands (NIR, SWIR, etc.) into an automated clustering process. Water indexes tend to have high values in water surfaces, however, as shown in the literature, just a single index associated with a threshold suffer from false positives or false negatives and the optimal threshold value is hard to find, depending on the scene. In the multidimensional clustering we can take advantage of water reflectance properties like the high absorption on SWIR and combine it with indexes for a better pixel discrimination. Figure 2 shows an example of water pixels (blue dots) separated through a multidimensional clustering and what would be the single threshold (red line).
This is important because the algorithm let’s the user choose the best combination for the water detection in the desired area in the WaterDetect.ini configuration file. Currently, the supported indexes are:
NDWI — Normalized Water Index
MNDWI — Modified Normalized Water Index
AWEI — Automated Water Extraction Index
MBWI — Multiband Water Index
The combinations that provides better balance between robustness and accuracy are [MNDWI, NDWI, Mir2] and [NDWI, Mir2], where Mir2 is the second SWIR band present on Sentinel 2 and Landsat 8 images.
The algorithm will look for the best number of clusters (K) by testing different possibilities and deciding for the best according to the Calinsk Harabasz index. The maximum and minimum values for K are also configurable in the WaterDetect.ini.
To identify among all the clusters, the one that contains the water pixels, the algorithm implements the following methods:
minmir: selects as water the pixels in the cluster with minimum mir value
maxmndwi: selects as water the pixels in the clusterthe cluster with maximum mndwi value
maxndwi: selects as water the pixels in the clusterthe cluster with maximum ndwi value
maxmbwi: selects as water the pixels in the cluster the cluster with maximum mbwi value
Performance
The clustering algorithm used is agglomerative because the usual K-means don’t provide good results when the clusters have different sizes. The problem is that a single Sentinel 2 scene has 120 million pixels in full resolution (10m) and the agglomerative clustering has time complexity (O2) and space complexity of (O3) making it unfeasible for processing this kind of image.
To overcome this limitation we subsample the pixels randomly and apply the clustering in this subsample. Afterwards, a machine learning classifier (we chose näive bayes) is applied to generalize from the subsampled pixels to reconstruct the whole scene. With this solution, the full resolution Sentinel 2 image can be processed in less than 3 minutes. I have already written a full story about the k-means problem and the this upsampling procedure in “Leveraging the Performance of Agglomerative Clustering for High-Resolution Satellite Images”. Figure 3 has an overview of how the algorithm works.
The algorithm proposed in [4] is available as a python package called waterdetect. The source code can be found in the git repository https://github.com/cordmaur/WaterDetect.
The easiest way to install waterdetect package is through thecommand pip install waterdetect .
Alternatively, you can clone the repository and install from its root throught the following commands:
Alternatively, you can clone the repository and install from its root throught the following commands:
git clone https://github.com/cordmaur/WaterDetect.gitcd WaterDetectpip install .
Once installed, a waterdetect entry point is created in the path of the environment. The waterdetect can be run from this entry point (refer to the git repository for more information). Typing waterdetect -h displays the help.
usage: waterdetect [-h] [-GC] [-i INPUT] [-o OUT] [-s SHP] [-p PRODUCT] [-c CONFIG]The waterdetect is a high speed water detection algorithm for satelliteimages. It will loop through all images available in the input folder andwrite results for every combination specified in the .ini file to the outputfolder. It can also run for single images from Python console or Jupyternotebook. Refer to the onlinedocumentationoptional arguments: -h, --help show this help message and exit -GC, --GetConfig Copy the WaterDetect.ini from the package into the specifieddirectory and skips the processing. Once copied you can edit the .ini file and launch the waterdetect without -c option. -i INPUT, --input INPUT The products input folder. Required. -o OUT, --out OUT Output directory. Required. -s SHP, --shp SHP SHP file. Optional. -p PRODUCT, --product PRODUCT The product to be processed (S2_THEIA, L8_USGS, S2_L1C or S2_S2COR) -c CONFIG, --config CONFIG Configuration .ini file. If not specified WaterDetect.ini from current dir and used as defaultTo copy the package's default .ini file into the current directory, type:`waterdetect -GC .` without other arguments and it will copy WaterDetect.iniinto the current directory.
A configuration file specifying the clustering bands, water cluster detection method and other parameters is necessary for the algorithm to run. The command waterdetect -GC will copy the default configuration file to current directory. You can create other variants of this file and pass them as an argument using the -c option. If it is not explicitly specified, a WaterDetect.ini in the current directory is searched for. The input_folder argument should point to a directory that contains uncompressed images of the same product type (an example of the structure is shown in Figure 4), so the algorithm can loop through all the images and process them at once.
During running, one folder for each image will be created in the output directory. The final water mask, as well as the clustering results, will be available inside the folder with the name corresponding to the bands used for clustering. If more than one combination of bands is specified in the config file, they all will be processed and saved. In the config it is also possible to specify pdf_reports=True and plot_graphs=True. With these options the algorithm will save a .PDF file with the results in low resolution and include any graphs that you have specified in the configuration. For the above directory configuration, the commands to run are:
(waterdetect_env) PS D:\> waterdetect -GCCopying d:\programs\anaconda\envs\waterdetect_env\lib\site-packages\waterdetect\WaterDetect.ini into current dir.WaterDetect.ini copied into D:\.(waterdetect_env) PS D:\> waterdetect -i d:\Images\Download\France-MAJA -o d:\Images\out -p S2_THEIALoading configuration file WaterDetect.iniFile WaterDetect.ini verified.Folder d:\Images\Download\France-MAJA verified.Folder d:\Images\out verified.Opening image in loaderRetrieving bands for image: d:/Images/Download/France-MAJA/SENTINEL2B_20190224-103835-289_L2A_T31TGK_C_V1-0The following bands were found:SENTINEL2B_20190224-103835-289_L2A_T31TGK_C_V1-0_SRE_B11.tifSENTINEL2B_20190224-103835-289_L2A_T31TGK_C_V1-0_SRE_B12.tifSENTINEL2B_20190224-103835-289_L2A_T31TGK_C_V1-0_SRE_B2.tif...T31TGK_C_V1-0_MTD_ALL.xml verified.---------------------------VALUES ANGLE GLINT[58.89489588415046, 59.00516357439775, 59.125230327623676, 59.1975351244004, 59.27428320701952, 59.35296101146046, 58.94729756082948, 59.43995100981233, 59.260483478237774, 59.45799750367317]PAS DE GLINT SUR IMAGE d:/Images/Download/France-MAJA/SENTINEL2B_20190224-103835-289_L2A_T31TGK_C_V1-0/SENTINEL2B_20190224-103835-289_L2A_T31TGK_C_V1-0_MTD_ALL.xml---------------------------
A full Sentinel 2 tile has approximately 120million pixels and it takes about 3–5 min depending on the processor and operating system. At the end of each image’s processing, a message indicating a probability of sun glint is displayed. An example of the PDF report is shown in Figure 5.
Instead of calling the waterdetect from script, it is also possible to import the package into a console or jupyter notebook to launch it. This way, two options are available. There is the run_batch, that is pretty similar to the script call and also the run_single, that runs the algorithm for one image only and returns the result in memory.
When you execute import waterdetect it initializes and declares the most important classes.
DWWaterDetect
DWImageClustering
The DWWaterDetect class is responsible for orchestrating the full chain, since the opening of the satellite images, to the contstruction of reports. For that, it will use the other modules. The DWWaterDetect allows two main modes:
Batch mode: the algorithm will loop through all the images available in the input folder and save the results to the output folder. Additionally, it can provide more than one result for each image, with different clustering parameters, depending on the configuration.
Single mode: in the single mode, just one image is processed and just one combination of bands (the first) is used to create the products. Additionally, a DWClusteringImage instance is returned with the resultings mask and clustering.
The following code shows an example on how to launch both modes from a jupyter notebook.
If GDAL is not installed on the environment, the waterdetect will display a message and none of the above methods will work as GDAL is needed to open the satellite images. However, if you want to feed the algorithm with your own arrays in the case you use other library (such as rasterio) or the satellite you are using is not supported it is still possible to use the waterdetect package.
In such case, the bands should be passed to the DWImageClustering object as a dicionary. To work with multiple satellites (Sentinel 2 and Landsat at the moment) the waterdetect uses the following convention for the bands names
Blue: 492nmGreen: 559nmRed: 665nmRedEdg1: 703nmRedEdg2: 739nmRedEdg3: 780nmNir: 833nmNir2: 864nmMir: 1610nmMir2: 2185nm
The minimum required bands will depend on the bands combination that has been chosen and the method for detecting the water cluster. The following code shows an example on using the waterdetect with bands loaded manually using the rasterio.
As you can see, the attributes water_mask and clustering_matrix store numpy arrays with the resulting mask and the intermediate clustering result. The resulting values are:
water_mask: 0= non water; 1= water; 255= no data
clustering_matrix: 1= water; 2...n= other clusters; 255= no data
As seen throughout this story, the waterdetect package is a good solution for extracting water masks from high resolution satellite images without any prior knowledge about the scene or arbitrary thresholds. Important to notice that for tasks other than water detection, it can still be used as a high performance clustering algorithm that delivers much better results than the most common K-means that would not be feasible due to memory and time to process.
The package is still under development, so if you find any trouble or have suggestions on how to improve this tutorial feel free to leave a message or open an issue in the github repository (https://github.com/cordmaur/WaterDetect).
See you next story.
[1] Hoeser, T.; Kuenzer, C. Object Detection and Image Segmentation with Deep Learning on Earth Observation Data: A Review-Part I: Evolution and Recent Trends. Remote Sensing 2020, 12 (10), 1667. https://doi.org/10.3390/rs12101667.
[2] Isikdogan, F., Bovik, A. C., & Passalacqua, P. (2017). Surface Water Mapping by Deep Learning. IEEE Journal of Selected Topics in Applied Earth Observations and Remote Sensing, 10(11), 4909–4918. https://doi.org/10.1109/JSTARS.2017.2735443
[3] Isikdogan, L. F., Bovik, A., & Passalacqua, P. (2019). Seeing Through the Clouds With DeepWaterMap. IEEE Geoscience and Remote Sensing Letters, 1–5. https://doi.org/10.1109/LGRS.2019.2953261
[4] Cordeiro, M. C. R.; Martinez, J.-M.; Peña-Luque, S. Automatic Water Detection from Multidimensional Hierarchical Clustering for Sentinel-2 Images and a Comparison with Level 2A Processors. Remote Sensing of Environment 2021, 253, 112209. https://doi.org/10.1016/j.rse.2020.112209. | [
{
"code": null,
"e": 490,
"s": 172,
"text": "This story is divided in two parts: Methodology and the waterdetect package. In the methodology, the main concepts of the algorithm are given, in order to provide the reader a better understanding of the package and how to tune it. The second part is a tu... |
SciPy - Environment Setup | Standard Python distribution does not come bundled with any SciPy module. A lightweight alternative is to install SciPy using the popular Python package installer,
pip install pandas
If we install the Anaconda Python package, Pandas will be installed by default. Following are the packages and links to install them in different operating systems.
Anaconda (from https://www.continuum.io) is a free Python distribution for the SciPy stack. It is also available for Linux and Mac.
Canopy (https://www.enthought.com/products/canopy/) is available free, as well as for commercial distribution with a full SciPy stack for Windows, Linux and Mac.
Python (x,y) − It is a free Python distribution with SciPy stack and Spyder IDE for Windows OS. (Downloadable from https://python-xy.github.io/)
Package managers of respective Linux distributions are used to install one or more packages in the SciPy stack.
We can use the following path to install Python in Ubuntu.
sudo apt-get install python-numpy python-scipy
python-matplotlibipythonipython-notebook python-pandas python-sympy python-nose
We can use the following path to install Python in Fedora.
sudo yum install numpyscipy python-matplotlibipython python-pandas
sympy python-nose atlas-devel
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2051,
"s": 1887,
"text": "Standard Python distribution does not come bundled with any SciPy module. A lightweight alternative is to install SciPy using the popular Python package installer,"
},
{
"code": null,
"e": 2071,
"s": 2051,
"text": "pip install pandas... |
Introduction on TensorFlow 2.0. A soft introduction to some features of... | by Jean-Michel D | Towards Data Science | In this article, I am going to present some of my findings on my exploration of TensorFlow, the idea will be with TensorFlow to build and monitor ML models around image classification and what a better dataset than the car dataset that I build a few weeks ago.
TensorFlow is a project started in 2011 by Google Brain as a research project and that become very popular in the Alphabet group all over the years. The framework is popular in the machine learning community by its highly flexible architecture that can leverage different kinds of processing units like CPU, GPU or TPU to execute computation without big modifications of the running code.
The framework is open-sourced since 2015 and seems very popular all around the world with more than 76 000 000 downloads. There is multiple API offer by Google to interact with the framework like Python, Javascript, C++, Java and Go.
TensorFlow possessed multiples tools to produce machine learning systems:
TensorFlow (dah)
TensorFlow.js
TensorFlow lite to deploy machine learning model in an embedded system
TensorFlow Extended to productizing machine learning pipeline
TensorFlow Quantum a “library for rapid prototyping of hybrid quantum-classical ML models”
The set of tools is very wide and really I advise you to have a look at the different documentations above that will give you a great overview of the tools.
I am just going to talk about TensorFlow, but I am planning to have a look in a few weeks on the Lite and .js tools (I ordered a device to make some tests on it 😉)
To interact with TensorFlow, one of the most popular API is the Python one (and to be honest that’s the one that I am the more comfortable with), but there are two paths available to interact with this API:
The beginner one that is using a user-friendly sequential API called Keras
The expert one that is using a subclassing API more pythonic
I am attaching you a snapshot of an example of the two API format
For me, I will really advise to use the Keras one that is maybe more easier to read for a non-python expert. This API originally in the TensorFlow 1.x version was not a native API (since the 2.0 it’s native) and have to be installed separately to access it.
Keras is an API that can run on top of various ML frameworks as TensorFlow, CNTK and Theano to help people to easily reused functions to build layer, solver etc without going too deep on the ml framework (an abstraction layer in some ways).
Let’s build some models to test the framework.
In this part, I am not going to enter in an explanation of the architectures of the models that I am going to used (maybe in a specific article). To start the model building I need first to connect the framework to the data.
The data is divided between folder related to the training, validation and testing set, in each folder, there is a subfolder for each class to predict that containing all the pictures that will be used for the process. There is a graph to represent the distribution of the pictures per class in the training set.
The repartition of the classes in the validation and testing set is the same that in the training set with just less data (training 80%, validation 10% and testing 10% of the full dataset).
To use the data in the model a data generator can be used like in this tutorial of TensorFlow, there is a quick snapshot of the code.
The idea of this code is to :
Normalize the picture (RGB converted from a value between 0–255 to 0–1)
Resize the pictures
Build the different batches for the training
It needs to apply to all the folders, but after that everything is ready to start to the training of the model.
In term of models, I reused the model design of the tutorial of TensorFlow and applied to some other resources. The models can be found in these gists:
The CNN tutorial of TensorFlow
The MLP of Aurelien Geron in chapter 10 of his book Hands-on machine learning with Scikit-Learn, Keras and TensorFlow
The CNN of Sebastian Raschka and Vahid Mirjalil in chapter 15 in their book Python machine learning
The inputs and the output of the model have been adapted to fit my needs but most of the code comes from the various resources listed. Once again these models are only there to test the framework they are not optimal for my problem (and will need a lot of refinement).
By executing the data generation and the model building the model is ready after a few minutes.
Let’s have a look now on the monitoring component of TensorFlow.
To monitor your model there are two paths (for me) with TensorFlow :
Use the history of the model fit operation to access the various metrics that have been computed (in this case the loss and the accuracy)
acc = history.history['accuracy']val_acc = history.history['val_accuracy']loss=history.history['loss']val_loss=history.history['val_loss']
The output of history can be used to plot graphs very easily with matplotlib for example.
The other path is to use a component called Tensorboard, it’s a package associated to TensorFlow that is offering the ability to collect in live various metrics during your run to build a model (cf gif), visualize the architecture the data etc.
Recently Google announced the ability to share the dashboard with everybody with the tensorboard.dev initiative, you can find for example at this link a tensorboard associated with some of my runs for this project.
Tensorboad is an interesting initiative and they announced a lot of new features at the last TensorFlow dev summit but I am honestly not a very experienced deep learning practitioner so I am not very a good advocate of this component that looks complex for me but I am thinking that it could be a very nice tool for a data science toolbox in association with mlflow.
To finish on this analysis I wanted to present another component called TensorFlow hub.
TensorFlow hub is born at Google from a simple situation if I am reading a really good article on some neural network architecture that looks very promising but a lot of questions can pop out during the investigation like:
how can I reproduce this article?
(in the case of a repo in the article) Is it the last version of the model?
where is the data?
(in the case of a repo in the article) Is it safe to use this piece of code?
TensorFlow hub wants to be there for people to limit all these questions and give more transparency on the ML development.
A very interesting feature of TensorFlow hub is to help people to build a machine learning model with components of famous and robust models, this approach is to reused model weights of another model and it is called transfer learning.
With TensorFlow hub, you can reuse in few lines of code components of another model very easily, in the following gist there is an illustration of a code that I built to reused a feature extractor of a model called Mobilenetv2 very popular for object classification (mostly inspired by TensorFlow tutorial).
Let’s now do a wrap-up of this analysis
This first hands-on TensorFlow was very good, I found the tutorial pretty well done and understandable and you can really easily build neural networks with the Keras API of the framework. There is a lot of components that I didn’t test yet as it can be seen on this screenshot
I add the occasion to have a look at TensorFlow Extended (TFX) which is the approach of Google to build a machine learning pipeline, I add a try on an AWS EC2 instance but the tutorial crashed at some point but I am inviting you to watch this great talk of Robert Crowe that is presenting the tool more in details.
The approach looks very promising and I am really curious to see the interactions that will exist between TFX and Kubeflow (another ML pipeline of Google based on Kubernetes).
My only concerns/interrogations on TensorFlow is the usage of the processing unit, during my test I alternated between CPU and GPU but my monitoring of the processing didn’t show that the processing unit used at full potential (but I am maybe just a newbie).
Another path to increase the efficiency of TensorFlow is to use tfRecords, but it seems that data management is still a hot topic (from what I heard around me), I found a really interesting Pydata talk around parquet files management with TensorFlow.
My next tasks around deep learning are to:
Do a soft introduction of Pytorch, made by Facebook it seems to be the nemesis of TensorFlow and this framework is winning a lot of traction in the research world
Ramp-up on deep learning algorithms to build a decent car classifiers
Understand the deployment of these deep learning models in production (data management, serving, etc) | [
{
"code": null,
"e": 433,
"s": 172,
"text": "In this article, I am going to present some of my findings on my exploration of TensorFlow, the idea will be with TensorFlow to build and monitor ML models around image classification and what a better dataset than the car dataset that I build a few weeks... |
Java Swing | Creating a Toast Message - GeeksforGeeks | 05 Jun, 2018
What are toast messages? And how to create them by using Java Swing?Toast Messages are a quick way of informing the user by short Pop-up messages that last for a short period of time and then disappear.
Java Swing does not have an inbuilt class for toast message but toast message is a popular and an effective way to display auto-expiring message that is displayed only for a short length of time. So in order to implement a toast message we have to manually build a class that is capable of creating a toast message.
In this article we will discuss how to manually create a toast message in Java, using Java Swing Components. The Following programs will create a text toast message that lasts for a short length of time and then they will disappear.
Please go through the following article for more details on translucent Window and Frames, This will give you the idea how to implement translucent and shaped window.Java Swing | Translucent and Shaped Window in JavaJSwing | Translucent and Shaped window
The following program creates the toast message (which is a selectively translucent JWindow)
// Java program that creates the toast message//(which is a selectively translucent JWindow)import java.awt.*;import javax.swing.*;import java.awt.event.*;class toast extends JFrame { //String of toast String s; // JWindow JWindow w; toast(String s, int x, int y) { w = new JWindow(); // make the background transparent w.setBackground(new Color(0, 0, 0, 0)); // create a panel JPanel p = new JPanel() { public void paintComponent(Graphics g) { int wid = g.getFontMetrics().stringWidth(s); int hei = g.getFontMetrics().getHeight(); // draw the boundary of the toast and fill it g.setColor(Color.black); g.fillRect(10, 10, wid + 30, hei + 10); g.setColor(Color.black); g.drawRect(10, 10, wid + 30, hei + 10); // set the color of text g.setColor(new Color(255, 255, 255, 240)); g.drawString(s, 25, 27); int t = 250; // draw the shadow of the toast for (int i = 0; i < 4; i++) { t -= 60; g.setColor(new Color(0, 0, 0, t)); g.drawRect(10 - i, 10 - i, wid + 30 + i * 2, hei + 10 + i * 2); } } }; w.add(p); w.setLocation(x, y); w.setSize(300, 100); } // function to pop up the toast void showtoast() { try { w.setOpacity(1); w.setVisible(true); // wait for some time Thread.sleep(2000); // make the message disappear slowly for (double d = 1.0; d > 0.2; d -= 0.1) { Thread.sleep(100); w.setOpacity((float)d); } // set the visibility to false w.setVisible(false); } catch (Exception e) { System.out.println(e.getMessage()); } }}
Driver program that runs the above program .
// Java Program to create a driver class to run // the toast classimport javax.swing.*;import java.awt.*;import java.awt.event.*;class driver extends JFrame implements ActionListener { // create a frame static JFrame f; // textfield static JTextField tf; public static void main(String args[]) { // create the frame f = new JFrame("toast"); driver d = new driver(); // textfield tf = new JTextField(16); // button Button b = new Button("create"); // add action listener b.addActionListener(d); // create a panel JPanel p = new JPanel(); p.add(tf); p.add(b); // add panel f.add(p); // setSize f.setSize(500, 500); f.show(); } // if button is pressed public void actionPerformed(ActionEvent e) { // create a toast message toast t = new toast(tf.getText(), 150, 400); // call the method t.showtoast(); }}
Output :
Note: This Program will not run in an online IDE please use an offline IDE with latest version of java.
java-swing
Java
Programming Language
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Arrow operator -> in C/C++ with Examples
Modulo Operator (%) in C/C++ with Examples
Structures in C++
Differences between Procedural and Object Oriented Programming
Top 10 Programming Languages to Learn in 2022 | [
{
"code": null,
"e": 23557,
"s": 23529,
"text": "\n05 Jun, 2018"
},
{
"code": null,
"e": 23760,
"s": 23557,
"text": "What are toast messages? And how to create them by using Java Swing?Toast Messages are a quick way of informing the user by short Pop-up messages that last for a s... |
Check whether the point (x, y) lies on a given line - GeeksforGeeks | 22 Oct, 2021
Given the values of m and c for the equation of a line y = (m * x) + c, the task is to find whether the point (x, y) lies on the given line.
Examples:
Input: m = 3, c = 2, x = 1, y = 5 Output: Yes m * x + c = 3 * 1 + 2 = 3 + 2 = 5 which is equal to y Hence, the given point satisfies the line’s equation
Input: m = 5, c = 2, x = 2, y = 5 Output: No
Approach: In order for the given point to lie on the line, it must satisfy the equation of the line. Check whether y = (m * x) + c holds true.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that return true if// the given point lies on the given linebool pointIsOnLine(int m, int c, int x, int y){ // If (x, y) satisfies the equation of the line if (y == ((m * x) + c)) return true; return false;} // Driver codeint main(){ int m = 3, c = 2; int x = 1, y = 5; if (pointIsOnLine(m, c, x, y)) cout << "Yes"; else cout << "No";}
// Java implementation of the approach class GFG{ // Function that return true if// the given point lies on the given linestatic boolean pointIsOnLine(int m, int c, int x, int y){ // If (x, y) satisfies the equation // of the line if (y == ((m * x) + c)) return true; return false;} // Driver codepublic static void main(String[] args){ int m = 3, c = 2; int x = 1, y = 5; if (pointIsOnLine(m, c, x, y)) System.out.print("Yes"); else System.out.print("No");}} // This code has been contributed by 29AjayKumar
# Python3 implementation of the approach # Function that return true if the# given point lies on the given linedef pointIsOnLine(m, c, x, y): # If (x, y) satisfies the # equation of the line if (y == ((m * x) + c)): return True; return False; # Driver codem = 3; c = 2;x = 1; y = 5; if (pointIsOnLine(m, c, x, y)): print("Yes");else: print("No"); # This code is contributed by mits
// C# implementation of the approachusing System; class GFG{ // Function that return true if// the given point lies on the given linestatic bool pointIsOnLine(int m, int c, int x, int y){ // If (x, y) satisfies the equation // of the line if (y == ((m * x) + c)) return true; return false;} // Driver codepublic static void Main(){ int m = 3, c = 2; int x = 1, y = 5; if (pointIsOnLine(m, c, x, y)) Console.Write("Yes"); else Console.Write("No");}} // This code is contributed by Akanksha Rai
<?php// PHP implementation of the approach // Function that return true if the// given point lies on the given linefunction pointIsOnLine($m, $c, $x, $y){ // If (x, y) satisfies the equation // of the line if ($y == (($m * $x) + $c)) return true; return false;} // Driver code$m = 3; $c = 2;$x = 1; $y = 5; if (pointIsOnLine($m, $c, $x, $y)) echo "Yes";else echo "No"; // This code is contributed by Ryuga?>
<script> // Javascript implementation of the approach // Function that return true if// the given point lies on the given linefunction pointIsOnLine(m, c, x, y){ // If (x, y) satisfies the equation // of the line if (y == ((m * x) + c)) return true; return false;} // Driver codevar m = 3, c = 2;var x = 1, y = 5; if (pointIsOnLine(m, c, x, y)) document.write("Yes");else document.write("No"); // This code is contributed by Rajput-Ji </script>
Yes
ankthon
Akanksha_Rai
Mithun Kumar
29AjayKumar
Rajput-Ji
ankita_saini
Geometric
Mathematical
Mathematical
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Equation of circle when three points on the circle are given
Convex Hull using Divide and Conquer Algorithm
Circle and Lattice Points
Line Clipping | Set 2 (Cyrus Beck Algorithm)
Check if a right-angled triangle can be formed by the given coordinates
Program for Fibonacci numbers
C++ Data Types
Write a program to print all permutations of a given string
Set in C++ Standard Template Library (STL)
Coin Change | DP-7 | [
{
"code": null,
"e": 25298,
"s": 25270,
"text": "\n22 Oct, 2021"
},
{
"code": null,
"e": 25439,
"s": 25298,
"text": "Given the values of m and c for the equation of a line y = (m * x) + c, the task is to find whether the point (x, y) lies on the given line."
},
{
"code": ... |
Even Number With Prime Sum | All even numbers from 4, can be expressed as a sum of two prime numbers. Sometimes a number can have more than one sum of the prime number combination.
For an example the number 10 = (5 + 5) and (7 + 3)
This algorithm will find all of the combinations of prime sums for a given number. When one number x is prime, then only we will check whether (number - x) is prime or not, if yes, the sum of x and (number – x) represents the even number.
Input:
Even number: 70
Output:
Prime sums
70 = 3 + 67
70 = 11 + 59
70 = 17 + 53
70 = 23 + 47
70 = 29 + 41
dispPrimeSum(num)
Input − The even number.
Output: Display the number using the sum of some prime numbers.
Begin
if num is odd, then
exit
for i := 3 to num/2, do
if i is prime, then
if (num - i) is prime, then
display ‘’num = i + (num – i)”
done
End
#include<iostream>
using namespace std;
int isPrime(int number) { //check whether number is prime or not
int lim;
lim = number/2;
for(int i = 2; i<=lim; i++) {
if(number % i == 0)
return 0; //The number is not prime
}
return 1; //The number is prime
}
void displayPrimeSum(int num) {
string res;
if(num%2 != 0) { //when number is an odd number
cout << "Invalid Number";
exit(1);
}
for(int i = 3; i <= num/2; i++) {
if(isPrime(i)) { //if i is a prime number
if(isPrime(num-i)) { //num - i is also prime, then
cout << num <<"= "<<i << " + "<<(num-i)<<endl;
}
}
}
}
main() {
int num;
cout << "Enter an even number: "; cin >> num;
displayPrimeSum(num);
}
Enter an even number: 70
70 = 3 + 67
70 = 11 + 59
70 = 17 + 53
70 = 23 + 47
70 = 29 + 41 | [
{
"code": null,
"e": 1214,
"s": 1062,
"text": "All even numbers from 4, can be expressed as a sum of two prime numbers. Sometimes a number can have more than one sum of the prime number combination."
},
{
"code": null,
"e": 1265,
"s": 1214,
"text": "For an example the number 10 =... |
Apex - Invoking | Apex invoking refers to the process of executing the Apex class. Apex class can only be executed when it is invoked via one of the ways listed below −
Triggers and Anonymous block
Triggers and Anonymous block
A trigger invoked for specified events
A trigger invoked for specified events
Asynchronous Apex
Asynchronous Apex
Scheduling an Apex class to run at specified intervals, or running a batch job
Scheduling an Apex class to run at specified intervals, or running a batch job
Web Services class
Web Services class
Apex Email Service class
Apex Email Service class
Apex Web Services, which allow exposing your methods via SOAP and REST Web services
Apex Web Services, which allow exposing your methods via SOAP and REST Web services
Visualforce Controllers
Visualforce Controllers
Apex Email Service to process inbound email
Apex Email Service to process inbound email
Invoking Apex Using JavaScript
Invoking Apex Using JavaScript
The Ajax toolkit to invoke Web service methods implemented in Apex
The Ajax toolkit to invoke Web service methods implemented in Apex
We will now understand a few common ways to invoke Apex.
You can invoke the Apex class via execute anonymous in the Developer Console as shown below −
Step 1 − Open the Developer Console.
Step 2 − Click on Debug.
Step 3 − Execute anonymous window will open as shown below. Now, click on the Execute
button −
Step 4 − Open the Debug Log when it will appear in the Logs pane.
You can call an Apex class from Trigger as well. Triggers are called when a specified event occurs and triggers can call the Apex class when executing.
Following is the sample code that shows how a class gets executed when a Trigger is called.
// Class which will gets called from trigger
public without sharing class MyClassWithSharingTrigger {
public static Integer executeQuery (List<apex_customer__c> CustomerList) {
// perform some logic and operations here
Integer ListSize = CustomerList.size();
return ListSize;
}
}
// Trigger Code
trigger Customer_After_Insert_Example on APEX_Customer__c (after insert) {
System.debug('Trigger is Called and it will call Apex Class');
MyClassWithSharingTrigger.executeQuery(Trigger.new); // Calling Apex class and
// method of an Apex class
}
// This example is for reference, no need to execute and will have detail look on
// triggers later chapters.
Apex class can be called from the Visualforce page as well. We can specify the controller or the controller extension and the specified Apex class gets called.
VF Page Code
Apex Class Code (Controller Extension)
14 Lectures
2 hours
Vijay Thapa
7 Lectures
2 hours
Uplatz
29 Lectures
6 hours
Ramnarayan Ramakrishnan
49 Lectures
3 hours
Ali Saleh Ali
10 Lectures
4 hours
Soham Ghosh
48 Lectures
4.5 hours
GUHARAJANM
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2203,
"s": 2052,
"text": "Apex invoking refers to the process of executing the Apex class. Apex class can only be executed when it is invoked via one of the ways listed below −"
},
{
"code": null,
"e": 2232,
"s": 2203,
"text": "Triggers and Anonymous block"
... |
Train all Classification or Regression models in one line of Python Code | by Satyam Kumar | Towards Data Science | Automated Machine Learning (Auto-ML) refers to automating the components of a data science model development pipeline. AutoML reduces the workload of a data scientist and speeds up the workflow. AutoML can be used to automate various pipeline components, including data understanding, EDA, data processing, model training, hyperparameter tuning, etc.
For an end-to-end machine learning project, the complexity of each of the pipeline components depends on the project. There are various AutoML open source libraries that speed up each of the pipeline components. Read this article to know 8 such AutoML libraries to automate the machine learning pipeline.
In this article, we will discuss how to automate the model training process using an open-source Python library LazyPredict.
LazyPredict is an open-source Python library that automates the model training pipeline and speeds up the workflow. LazyPredict trains around 30 classification models for a classification dataset and trains around 40 regression models for a regression dataset.
LazyPredict returns with the trained models along with its performance metric without writing much code. One can compare the performance metrics of each model and tune the best model to further improve the performance.
LazyPredict can be installed from the PyPl library using:
pip install lazypredict
Post-installation, one can import the library to perform auto-training of classification and regression models.
from lazypredict.Supervised import LazyRegressor, LazyClassifier
LazyPredict support both classification and regression problems, so I will discuss a demonstration of both tasks
Boston Housing (Regression) and Titanic (Classification) dataset are used for the demonstration of the LazyPredict library.
Usage of LazyPredict is very intuitive and similar to scikit-learn. First, create an instance of the estimator LazyClassifier for the classification task. One can pass custom metrics for evaluation, by default each of the models will be evaluated on Accuracy, ROC AUC score, F1 score.
Before proceeding to lazypredict model training, one must read the dataset and process it to make it fit for training.
After feature engineering and splitting the data into train test data, we can proceed with model training using LazyPredict.
# LazyClassifier Instance and fiting datacls= LazyClassifier(ignore_warnings=False, custom_metric=None)models, predictions = cls.fit(X_train, X_test, y_train, y_test)
Similar to classification model training, LazyPredict comes with automated model training for regression datasets. The implementation is similar to the classification task, with a change in the instance LazyRegressor.
reg = LazyRegressor(ignore_warnings=False, custom_metric=None)models, predictions = reg.fit(X_train, X_test, y_train, y_test)
Observing the above performance metrics, the AdaBoost classifier is the best performing model for classification tasks and the GradientBoostingRegressor model is the best performing model for regression tasks.
In this article, we have discussed the implementation of the LazyPredict library that can train around 70 classification and regression models in few lines of Python code. It is a very handy tool, as it gives an overall picture of how is the model performing, and one can compare the performance of each of the models.
Each model is trained with its default parameters, as it does not perform hyperparameter tuning. After choosing the best performing model, the developer can tune the model to improve the performance further.
Read the below-mentioned article to know 8 such AutoML libraries similar to LazyPredict.
medium.com
[1] LazyPredict Documentation: https://pypi.org/project/lazypredict/
Thank You for Reading | [
{
"code": null,
"e": 522,
"s": 171,
"text": "Automated Machine Learning (Auto-ML) refers to automating the components of a data science model development pipeline. AutoML reduces the workload of a data scientist and speeds up the workflow. AutoML can be used to automate various pipeline components, ... |
Prototype - AJAX Request() Method | This AJAX method initiates and processes an AJAX request. This object is a general-purpose AJAX requester: it handles the life-cycle of the request, handles the boilerplate, and lets you plug in callback functions for your custom needs.
In the optional options hash, you can use any callback function like onComplete and/or onSuccess depending on your custom needs.
new Ajax.Request(url[, options]);
As soon as the object is created, it initiates the request, then goes on processing it throughout its life-cyle. The defined life-cycle is as follows −
Created
Initialized
Request sent
Response being received (can occur many times, as packets come in)
Response received, request complete
There is a set of callback functions, defined in Ajax Options,, which are triggered in the following order −
onCreate (this is actually a callback reserved to AJAX global responders))
onUninitialized (maps on Created)
onLoading (maps on Initialized)
onLoaded (maps on Request sent)
onInteractive (maps on Response being received)
onXYZ (numerical response status code), onSuccess or onFailure (see below)
onComplete
Depending on how your browser implements XMLHttpRequest, one or more callbacks may never be invoked. In particular, onLoaded and onInteractive are not a 100% safe bet so far. However, the global onCreate, onUninitialized and the two final steps are very much guaranteed.
new Ajax.Request
You can pull the brake on a running PeriodicalUpdater by simply calling its stop method. If you wish to re-enable it later, just call its start method. Both take no argument.
<html>
<head>
<title>Prototype examples</title>
<script type = "text/javascript" src = "/javascript/prototype.js"></script>
<script>
function SubmitRequest() {
new Ajax.Request('/cgi-bin/ajax.cgi', {
method: 'get',
onSuccess: successFunc,
onFailure: failureFunc
});
}
function successFunc(response) {
if (200 == response.status) {
alert("Call is success");
}
var container = $('notice');
var content = response.responseText;
container.update(content);
}
function failureFunc(response) {
alert("Call is failed" );
}
</script>
</head>
<body>
<p>Click submit button see how current notice changes.</p>
<br />
<div id = "notice">Current Notice</div>
<br />
<br />
<input type = "button" value = "Submit" onclick = "SubmitRequest();"/>
</body>
</html>
Here is the content of ajax.cgi.
#!/usr/bin/perl
print "Content-type: text/html\n\n";
print "This content is returned by AJAX cgi <br />";
print "Current Time " . localtime;
Click submit button see how current notice changes.
You can pass the parameters for the request as the parameters property in options −
new Ajax.Request('/some_url', {
method: 'get',
parameters: {company: 'example', limit: 12}
});
127 Lectures
11.5 hours
Aleksandar Cucukovic
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2298,
"s": 2061,
"text": "This AJAX method initiates and processes an AJAX request. This object is a general-purpose AJAX requester: it handles the life-cycle of the request, handles the boilerplate, and lets you plug in callback functions for your custom needs."
},
{
"c... |
How to Install Flutter on Windows? - GeeksforGeeks | 21 Sep, 2021
Flutter is basically Google’s portable user interface (UI) toolkit, used to build and develop eye-catching, natively-built applications for mobile, desktop, and web, from a single codebase. Flutter is free, open-sourced, and compatible with existing code. It is utilized by companies and developers around the world, due to its user-friendly interface and fairly simple, yet to-the-point commands.
In this article, we will look into the process of installing Flutter on Windows.
Follow the below steps to install Flutter on Windows:
Step 1: Navigate to flutter.dev on your webpage. On the top menu bar, select Docs > Get Started > Install > Windows.
Step 2: Check for the System Requirements. Henceforth, you can begin the installation.
You can get a detailed procedure for installing the latest versions of Windows PowerShell 5.0 and Git for Windows, if not already installed.
Step 3: Restart the system after installing Git on your windows. Once done, let’s get to the installation of Flutter Software development Kit (Flutter SDK). Click on the download link for the latest version (as of today).
Flutter SDK is the tool that not only allows us to create flutter projects but also build those projects and transform them into native mobile applications. In simpler words, Flutter SDK is the core tool for building a flutter UI.
Once the zip file is downloaded, extract the ‘flutter’ folder (drag and drop) to any path/directory of the system where you get the read and write access. Typically, it is better to create a new folder in a separate directory apart from the system drive due to permission issues (In my case, the target destination is D: > development > flutter).
Now double-click on the ‘flutter’ folder. Go to ‘flutter_console.bat’ file and double-click to open a command prompt window. It should look something like this:
This console is actually a Windows terminal available for the developer to run flutter commands. Type in ‘flutter’ to get a list of all the flutter commands that can be run.
Whilst it is pretty good to have a terminal to execute flutter commands and create projects, it’d still be better and more convenient to store all our flutter projects somewhere else on our system for easy access. Let us steer over to the next step of our journey!
Step 4: Check and edit environment variables for global system access. For this, scroll down to ‘Update your path’ on the official Docs page of the flutter installation page. For this, go to Control Panel > System and Security > System > Advanced System Settings > Environment Variables... . A dialog box displaying a list of the available environment variables appears on your screen.
Environment Variables are global system variables present at the root level, which aids in configuring various aspects of Windows. We will now add the flutter tool as an environment variable for direct access (instead of running the .bat executable), and unlock it on the entire PowerShell and Command Prompt of your system.
To do this, glance through the following steps:
Check for ‘Path’ variable under User Variables list. If not already present, create a new variable (‘New...’) and assign the ‘flutter\bin‘ directory as its value.
Now double-click on the ‘Path’ variable and add a new entry by double-clicking on a column below. It should look something like this:
In the path, copy the entire directory of flutter\bin folder and paste it. Click ‘Ok’ twice to complete the setup. Now, make sure that you have closed any existing Command Prompt/Windows PowerShell windows that are open.
Now, check whether your flutter framework can be accessed globally. To do this, open any terminal (say Command Prompt) and type in ‘flutter‘ and see whether you get the same list of commands as you did get earlier from the .bat terminal. If yes, you have successfully completed setting up flutter on the root level in your system. If not, you might as well consider re-running the setup again.
Step 5: Now, you have to analyze and check whether something is missing/has to be installed further. To do this, under the Command Prompt terminal, type in ‘Flutter Doctor‘ to check for other requirements.
(Since a version has already been installed on my computer, below is an image shown from a previous version, to help you get an understanding of the ‘errors’ that appear after flutter doctor analysis.)
According to the flutter doctor check, we see that flutter was installed successfully in our system, but the Android tools are missing, and so is Android Studio. We also see that there are no connected devices too. Eventually, the next step is about setting up Android tools on your device, to execute the flutter apps built by you.
Step 6: Setting up Android tools and emulator for android devices.
The first step is to download and install Android Studio. To do this, navigate to the official page of Android Studio and click on ‘Download Android Studio‘.
After accepting the license agreements, you are good to go! Click on the final Download button to start downloading.
After the download is complete, let’s move on to the next step, i.e. installation.
Under ‘Components‘, make sure that both Android Studio and Android Virtual Device are checked, and only then proceed. The Android Virtual Device is an essential tool for running various types and sizes of android emulators to test your flutter project. Henceforth, click on ‘Next‘.
Select the directory you would want your file to be installed in. It is recommended to select some other path apart from the system drive. Once done, click on ‘Next‘.
Finally, click on ‘Install‘. Wait for a couple of seconds for the installation to complete. Check the box beside ‘Launch Android Studio‘. Click on ‘Finish‘.
Wait for Android Studio to launch on your computer. On the home screen, click Next > Custom > Next.
For the Java Development kit location in the next step, it is recommended to keep the default path it requires, to avoid the hassle. In the next step, choose the UI appearance you’d like for Android Studio. Click ‘Next‘.
This next step is a bit important. Remember to check the required boxes exactly as shown below. If kits have already been installed, you can ignore those and move on. Click ‘Next‘. Set your desired folder for Android SDK.
With that done, click on ‘Finish‘. Android Studio will now install all the necessary android tools required for the execution of your flutter projects. This may take a significant time – it’s better to wait!
Now, we are ready to create and build flutter projects on Android Studio and run it on a real or a virtual Android device (emulator).
Step 6: Set SDK as an environment variable, for global access.
Now, open Command Prompt terminal and run ‘flutter doctor’ again. If you have installed Android SDK in the default directory suggested by Android Studio, there wouldn’t be any problem that would appear. Nevertheless, if you have installed it in a non-default directory, flutter would not be able to detect it in your system. To help it able to do that, you guessed it...we would be assigning it as an environment variable, giving global access.
As discussed earlier in Step 4, go to environment variables and click ‘New‘, and do the following (as recommended by flutter doctor). Click ‘OK‘.
Step 7: Accept required Android Licenses.
On the Command Prompt terminal, type in:
flutter doctor --android-licenses
as suggested by flutter doctor. Hit Enter. To review licenses, type ‘y‘ for Yes.
You’ll see a couple of repeated prompts that look like this:
Accept? (y/N):
Type ‘y‘ whenever asked for.
Finally, after all the license agreements have been accepted, you should see a message that looks something like this:
All SDK package licenses accepted
Step 7: Setup Android Emulator.
You have the option to choose between an Android Device or an Android Emulator to build your application on. It depends totally on you.
For setting up Android Device, go through the official docs page and follow the exact steps as mentioned. Download The Google USB Driver by following the link and install according to the instructions given. This can also be installed through Android Studio, which you can later connect to a real Android Device to build the application.
For setting up Android Emulator, you need to go through the following steps:
Open Android Studio.
On the topmost menu bar, click on Tools > SDK Manager.
Verify whether you have the latest SDK installed. Remember to install the latest stable version too by checking on the box to the left. In my case, it is ‘Android 9.0 (Pie)‘. You can even uncheck the latest version (if not stable), to not only save space but also run all your applications on the stable version itself.
Under the ‘SDK Tools‘ tab, don’t forget to check Google USB Driver to later connect a real Android Device. With that, click ‘Apply‘. Click ‘OK‘ to start SDK installation.This might take a couple of minutes to complete. After the setup is done, click on ‘Finish‘. Your setup is now complete!
To have a first look at your Android Emulator, open Android Studio. Go to Tools > AVD Manager. A dialog box appears.
Click on ‘Create Virtual Device...‘, select a device and its dimensions according to your preference, select a system image and lastly, under all default settings, click on ‘Finish’. Click on the ‘’ button to fire up your emulator.
There you go! You now have a fully functional flutter framework with devices/emulators to build your beautiful apps on. Go crazy!
Flutter
how-to-install
Picked
How To
Installation Guide
TechTips
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install FFmpeg on Windows?
How to Set Git Username and Password in GitBash?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
How to Create and Setup Spring Boot Project in Eclipse IDE?
Installation of Node.js on Linux
How to Install FFmpeg on Windows?
How to Install Pygame on Windows ?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS? | [
{
"code": null,
"e": 24561,
"s": 24533,
"text": "\n21 Sep, 2021"
},
{
"code": null,
"e": 24959,
"s": 24561,
"text": "Flutter is basically Google’s portable user interface (UI) toolkit, used to build and develop eye-catching, natively-built applications for mobile, desktop, and we... |
Why do we use import * and then ttk in TKinter? | In order to work with a tkinter application, we have to install and import the tkinter library in our environment. Generally, we import the tkinter library in the environment by using from tkinter import * command.
The significance of "import *" represents all the functions and built-in modules in the tkinter library. By importing all the functions and methods, we can use the inbuilt functions or methods in a particular application without importing them implicitly.
There are lots of widgets, functions, methods available in tkinter library which can be used to construct the component of a particular application. Tkinter provides the ttk package that is used to style the widget's property and its look and feel. In order to use the ttk package, we have to import it by typing the following code −;
from tkinter import ttk
In this particular example, we will create a functional application that will contain a button and a label widget.
#Import tkinter library
from tkinter import *
from tkinter import ttk
#Create an instance of tkinter frame or window
win= Tk()
#Set the geometry of tkinter frame
win.geometry("750x250")
#Define the function to close the window
def change_text():
label.configure(text="Welcome")
#Create a label
label=Label(win, text= "Click the below button to Change this Text", font=('Aerial 20 bold'))
label.pack(pady=30)
#Create a button widget
button= ttk.Button(win, text="Commit",command=lambda:change_text())
button.pack()
win.mainloop()
Executing the above code will display a window that contains a button and a text label showing some text. When we click the button, it will change the message on the screen.
Now, click the "Commit" button to change the Label text. | [
{
"code": null,
"e": 1277,
"s": 1062,
"text": "In order to work with a tkinter application, we have to install and import the tkinter library in our environment. Generally, we import the tkinter library in the environment by using from tkinter import * command."
},
{
"code": null,
"e": 1... |
Generate Random Integer Numbers in Java | In order to generate Random Integer Numbers in Java, we use the nextInt() method of the java.util.Random class. This returns the next random integer value from this random number generator sequence.
Declaration − The java.util.Random.nextInt() method is declared as follows −
public int nextInt()
Let us see a program to generate random integer numbers in Java −
Live Demo
import java.util.Random;
public class Example {
public static void main(String[] args) {
Random rd = new Random(); // creating Random object
System.out.println(rd.nextInt());
}
}
27100093
Note - The output might vary on Online Compilers. | [
{
"code": null,
"e": 1261,
"s": 1062,
"text": "In order to generate Random Integer Numbers in Java, we use the nextInt() method of the java.util.Random class. This returns the next random integer value from this random number generator sequence."
},
{
"code": null,
"e": 1338,
"s": 12... |
MedCAT | Dataset Analysis and Preparation | by Zeljko | Towards Data Science | One of the most important steps when doing any kind of machine learning is to understand the dataset and to be sure that what we want to achieve is in fact possible. So, before continuing with our main goal of analysing the connection between age and diseases, we will first show some basic statistical information on the MIMIC-III dataset and prepare the EHRs for the next steps.
Please Note: (1) To reproduce the results (images) in this tutorial you will need access to MIMIC-III, but as I know this can be bothersome, I’ve created two dummy CSV files available in the repository. These two CSV files emulate the two files we get from MIMIC-III using the SQL scripts below. This is not real data and can only be used to test MedCAT or to learn how to use it. (2) I will be showing plots and statistics from the MIMIC-III dataset.
It is not too difficult to get access to MIMIC-III, you can submit a request here and usually a couple of days later they will approve your request.
Once you get access to MIMIC-III, you can download the full dataset from their website. Initially, the files are in CSV format, I’ve decided to import them into a PostgreSQL database to make the exploration phase a bit easier (you can do everything from the CSV files directly). Physionet provides a tutorial on how to import MIMIC-III into a PostgreSQL database, link. In my case, I had to slightly modify the scripts to make this work and run them without using Makefiles, still a fairly smooth process.
The reason we have imported everything into PostgreSQL is so that we can easier view, filter and select what is needed from the dataset. MIMIC-III has a large number of tables and information, but we are interested in only two: noteevents and patients.
noteevents — contains the written portion of a patients EHR. More on the noteevents table can be found on the MIMIC-III website. From this table we are only interested in 4 columns: subject_id (the patient identifier), chartdate (date when the note was created), category (what is the type of the note, e.g. Nursing) and text (the text portion of the note). The SQL script used to extract the needed information is bellow (use the save to CSV option, or Python to create a CSV):
SELECT subject_id, chartdate, category, text FROM mimiciii.noteevents
patients — contains basic structured information on patients. Again, more on the MIMIC-III website. From here, we will take three columns: subject_id (the patient identifier), gender (male or female), dob (date of birth). The SQL script:
SELECT subject_id, gender, dob FROM mimiciii.patients
Please Note: (1) dates in MIMIC-III are randomly shifted into the future (the good thing is, for one patient, all dates are shifted using the same random number). (2) There is a huge number of noteevents in MIMIC-III, the CSV is ~3.9GB.
Google Colab
Later on, we will group patients based on gender to show some differences between female and male. Because of that, we want to check is our dataset balanced. In Figure 1, we can see that there are more male patients than female, but nothing significant (at least not for our use-case). In numbers, there are 46520 patients in total and from that 20399 are female, and 26121 are male. The number of patients in the noteeventstable is slightly different; not all patients have clinical notes.
Nothing else (useful) can be done given this table alone, let’s first check a couple of things in the noteevents table and then we’ll combine the two tables and plot statistics related to age.
From the noteevents table we want to check the length (number of characters) of clinical notes, not an absolute necessity, but it is nice to know what are we working with. The left side of Figure 2 shows that there are some very long documents and also some that have close to 0 characters. To clean-up a bit we will remove the top and the bottom outliers based on length (in other words the shortest and longest notes). Cleaning is not really necessary, but outliers can produce strange results, so better to remove them. The right side of Figure 2 shows the final distribution of the documents based on length.
Next, we want to analyse the number of documents per patient (Figure 3). As these are health records, more documents mean the situation is probably worse for the patient. And one document usually means false alarm, the patient was discharged immediately. Same as above, we will do a bit of cleaning and remove outliers, we don’t want the patients with thousands of documents, nor the ones with only a few.
Lastly, we will also show the distribution of documents per category (Figure 4), useful to know from where are the documents coming. For now, we will not do any filtering based on category.
Remember that all dates for one patient are shifted by the same random number, that means we can use the difference between the patient’s date of birth and the creation date for a document to calculate how old was the patient when that document was written. We will do another cleaning step here, remove patients older than 89 or younger than 16 (this step removes the largest number of patients, around 20%). MIMIC-III does not contain information on children, only neonates and adults, so removing anyone younger than 16 means removing only neonates. Age-related statistics for neonates do not make sense. And regarding people older than 89, this is a bit of an extreme and the data in MIMIC-III is messy for this age group. Details can be seen in the Jupyter notebook, Figure 5 shows the resulting plot.
Figure 5 agrees with the patient distribution presented in a recent study on the MIMIC-III dataset.
Finally, Table 1 shows the statistics of our dataset before and after preprocessing.
If you are interested in more posts about MedCAT and Electronic Health Records, have a look here. | [
{
"code": null,
"e": 552,
"s": 171,
"text": "One of the most important steps when doing any kind of machine learning is to understand the dataset and to be sure that what we want to achieve is in fact possible. So, before continuing with our main goal of analysing the connection between age and dise... |
How to select a subset of a DataFrame? - GeeksforGeeks | 02 Jun, 2021
In this article, we are going to discuss how to select a subset of columns and rows from a DataFrame. We are going to use the nba.csv dataset to perform all operations.
Python3
# import required moduleimport pandas as pd # assign dataframedata = pd.read_csv("nba.csv") # display dataframedata.head()
Output:
Below are various operations by using which we can select a subset for a given dataframe:
Select a specific column from a dataframe
To select a single column, we can use a square bracket [ ]:
Python3
# import required moduleimport pandas as pd # assign dataframedata = pd.read_csv("nba.csv") # get a single columnsages = data["Age"] # display the columnages.head()
Output:
Select multiple columns from a dataframe
We can pass a list of column names inside the square bracket [] to get multiple columns:
Python3
# import required moduleimport pandas as pd # assign dataframedata = pd.read_csv("nba.csv") # get a single columnsname_sex = data[["Name","Age"]] # display the columnname_sex.head()
Output:
Select a subset of rows from a dataframe
To select rows of people older than 25 years in the given dataset, we can put conditions within the brackets to select specific rows depending on the condition.
Python3
# importing pandas libraryimport pandas as pd # reading csv filedata = pd.read_csv("nba.csv") # subset of dataframeabove_25 = data[data["Age"] > 35] # display subsetprint(above_25.head())
Output:
Select a subset of rows and columns combined
In this case, a subset of all rows and columns is made in one go, and select [] is not sufficient now. The loc or iloc operators are needed. The section before the comma is the rows you choose, and the part after the comma is the columns you want to pick by using loc or iloc. Here we select only names of people older than 25.
Python3
# importing pandas libraryimport pandas as pd # reading csv filedata = pd.read_csv("nba.csv") # subset of dataframeadults = data.loc[data["Age"] > 25, "Name"] # display susbsetprint(adults.head())
Output:
saurabh1990aror
Picked
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Python Classes and Objects
Create a directory in Python | [
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n02 Jun, 2021"
},
{
"code": null,
"e": 24070,
"s": 23901,
"text": "In this article, we are going to discuss how to select a subset of columns and rows from a DataFrame. We are going to use the nba.csv dataset to perform all operat... |
How semaphore is used to implement mutual exclusion? | A semaphore is a shared variable which is used to implement mutual exclusion between
system processes. It is mainly helpful to solve critical section problems and is a
technique to achieve process synchronization.
Binary semaphore − Can take only two values, 0 or 1 which means at a time only one process can enter into the critical section. Semaphore is initialized to 1.
Binary semaphore − Can take only two values, 0 or 1 which means at a time only one process can enter into the critical section. Semaphore is initialized to 1.
Counting semaphore − Can take any non-negative value N which means at a time at most N processes can enter into CS. Semaphore is initialized to N.
Counting semaphore − Can take any non-negative value N which means at a time at most N processes can enter into CS. Semaphore is initialized to N.
P(s)
P(s)
CS
CS
V(s)
V(s)
Each of these operations is defined below −
Wait(P) − Whenever a process enters into CS, first it executes P operation where it decreases semaphore value and if after that s>=0 then enters into CS otherwise added to the waiting queue.
P(Semaphore s)
{
s = s - 1;
if (s < 0) {
block(p);
}
}
Signal(V) − When a process exists CS operation V is performed which increases the value of semaphore indicating another process can enter into CS which is currently blocked by P operation.
V(Semaphore s)
{
s = s + 1;
if (s >= 0) {
wakeup(p);
}
}
Let us see how the lock variable is used to introduce the mutual exclusion −
It uses a similar mechanism as semaphore but at a time only one process can enter into a critical section and uses lock variable to implement synchronization as below −
while(lock != 0);
Lock = 1;
//critical section
Lock = 0;
It checks if the lock is equal to 0 then sets the lock to 1 indicating that lock is occupied and then
enters into CS. If the lock is not 0, then wait until it is available. When exiting CS set
lock back to 0 indicating lock is available and another process can enter into CS.
The difference between locks and semaphores is that locks can be implemented in user mode
whereas semaphores are implemented in kernel mode. Also, locks allow only one
process to enter into CS but semaphore can allow multiple processes to enter into CS. In
short, semaphore is the generalization of locks. | [
{
"code": null,
"e": 1276,
"s": 1062,
"text": "A semaphore is a shared variable which is used to implement mutual exclusion between\nsystem processes. It is mainly helpful to solve critical section problems and is a\ntechnique to achieve process synchronization."
},
{
"code": null,
"e": ... |
Concrete class in Java - GeeksforGeeks | 16 Jan, 2019
A concrete class is a class that has an implementation for all of its methods. They cannot have any unimplemented methods. It can also extend an abstract class or implement an interface as long as it implements all their methods. It is a complete class and can be instantiated.
In other words, we can say that any class which is not abstract is a concrete class.
Necessary condition for a concrete class: There must be an implementation for each and every method.
Example: The image below shows three classes Shape, Rectangle and Circle. Shape is abstract whereas Rectangle and Circle are concrete and inherit Shape. This is because Rectangle and Circle implement area() method.
Example 1: The below code shows a simple concrete class:
// Java program to illustrate concrete class // Concrete Classclass Main { // this method calculates // product of two numbers static int product(int a, int b) { return a * b; } // this method calculates // sum of two numbers static int sum(int a, int b) { return a + b; } // main method public static void main(String args[]) { int p = product(5, 10); int s = sum(5, 10); // print product System.out.println("Product: " + p); // print sum System.out.println("Sum: " + s); }}
Product: 50
Sum: 15
Example 2: The code below illustrates a concrete class which extends an abstract class. The method product() in interface X is implemented by class Product but it does not implement method sum(), therefore it has to be abstract. Whereas class Main implements the unimplemented method sum(), therefore there are no unimplemented methods. Hence, it is a concrete class.
// Java program to illustrate concrete class // This is an interfaceinterface X { int product(int a, int b); int sum(int a, int b);} // This is an abstract classabstract class Product implements X { // this method calculates // product of two numbers public int product(int a, int b) { return a * b; }} // This is a concrete class that implementsclass Main extends Product { // this method calculates // sum of two numbers public int sum(int a, int b) { return a + b; } // main method public static void main(String args[]) { Main ob = new Main(); int p = ob.product(5, 10); int s = ob.sum(5, 10); // print product System.out.println("Product: " + p); // print sum System.out.println("Sum: " + s); }}
Product: 50
Sum: 15
java-basics
Java-Classes
Java-Object Oriented
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
How to iterate any Map in Java
ArrayList in Java
Multidimensional Arrays in Java
Stream In Java
Stack Class in Java
Singleton Class in Java
Set in Java | [
{
"code": null,
"e": 24234,
"s": 24206,
"text": "\n16 Jan, 2019"
},
{
"code": null,
"e": 24512,
"s": 24234,
"text": "A concrete class is a class that has an implementation for all of its methods. They cannot have any unimplemented methods. It can also extend an abstract class or ... |
"delete this" in C++? | Delete is an operator that is used to Deallocate storage space of Variable.
This pointer is a kind of pointer that can be accessed but only inside nonstatic member function and it points to the address of the object which has called the member function.
This pointer holds the address of the current object, in simple words, you can say that this pointer points to the current object of the class
Whenever we call a member function through its object, compiler secretly passes the address of calling that object as the first parameter in member function as this pointer.
Generally, delete operator should not be used for this pointer. Suppose, if used, then the following points must be considered.
Ideally, delete operator should not be used for this pointer. However, if used, then the following points must be considered.
delete operator works only for objects allocated using operator new (See this post). If the object is created using new, then we can do delete this, otherwise, the behavior is undefined.
delete operator works only for objects allocated using operator new (See this post). If the object is created using new, then we can do delete this, otherwise, the behavior is undefined.
filter_none
edit
play_arrow
brightness_4
class A {
public:
void fun() {
delete this;
}
};
int main() {
/* Following is Valid */
A *ptr = new A;
ptr->fun();
ptr = NULL; // make ptr NULL to make sure that things are not accessed using ptr.
/* And following is Invalid: Undefined Behavior */
A a;
a.fun();
getchar();
return 0;
}
Once delete this is done, any member of the deleted object should not be accessed after deletion.
Once delete this is done, any member of the deleted object should not be accessed after deletion.
filter_none
edit
play_arrow
brightness_4
#include<iostream>
using namespace std;
class A {
int x;
public:
A() { x = 0;}
void fun() {
delete this;
/* Invalid: Undefined Behavior */
cout<<x;
}
};
The best thing is to not do delete this at all.
Deleting this pointer inside member function is wrong, we should never do that. But if we do these following things can happen,
If that object from which this member function is called is created on the stack then deleting this pointer either crash your application or will result in undefined behavior.
If that object from which this member function is called is created on the stack then deleting this pointer either crash your application or will result in undefined behavior.
If that object from which this member function is called is created on the heap using new operator, then deleting this pointer will destroy the object. It will not crash the application at that particular time but after it, if some member function will try to access the member variable through this object then the application will crash.
If that object from which this member function is called is created on the heap using new operator, then deleting this pointer will destroy the object. It will not crash the application at that particular time but after it, if some member function will try to access the member variable through this object then the application will crash.
#include <iostream>
class Dummy {
int m_value;
public:
Dummy(int val) :
m_value(val)
{}
void destroy();
void displayValue();
void displayText();
};
void Dummy::destroy() {
delete this;
}
void Dummy::displayValue() {
std::cout << this->m_value << std::endl;
}
void Dummy::displayText() {
std::cout << "Not accessing any member function" << std::endl;
}
int main() {
Dummy * dummyPtr = new Dummy(5);
dummyPtr->destroy();
dummyPtr->displayText();
return 0;
}
Once we deleted this pointer in destroy() member function, after this calling displayText() is safe because it is not accessing any member function. But calling displayValue() will crash the application because it is accessing member variable through a dangling pointer i.e. deleted this pointer. | [
{
"code": null,
"e": 1138,
"s": 1062,
"text": "Delete is an operator that is used to Deallocate storage space of Variable."
},
{
"code": null,
"e": 1316,
"s": 1138,
"text": "This pointer is a kind of pointer that can be accessed but only inside nonstatic member function and it po... |
Getting details when a table is modified in SAP HANA DB | You can query SYS.M_TABLE_STATISTICS providing name of table and LAST MODIFY DATE. Here is the sample SQL query.
SELECT "ABC", "LAST_MODIFY_TIME"
FROMSYS.M_TABLE_STATISTICS
ORDER BY “LAST_MODIFY_TIME" DESC
In above command, you need to replace “ABC” by your table name. | [
{
"code": null,
"e": 1175,
"s": 1062,
"text": "You can query SYS.M_TABLE_STATISTICS providing name of table and LAST MODIFY DATE. Here is the sample SQL query."
},
{
"code": null,
"e": 1270,
"s": 1175,
"text": "SELECT \"ABC\", \"LAST_MODIFY_TIME\" \nFROMSYS.M_TABLE_STATISTICS\nO... |
How can I simulate a print statement in MySQL? | To simulate a print statement in MySQL, you can use select statement. The syntax is as follows −
SELECT ‘anyStringValue’ as ’ ‘;
You can check the above syntax at the MySQL command line client.
To print a string.
mysql> select 'HELLO MYSQL' as ' ';
+-------------+
| |
+-------------+
| HELLO MYSQL |
+-------------+
1 row in set (0.00 sec)
a) To print integer, use the following query −
mysql> select 23 as ' ';
+----+
| |
+----+
| 23 |
+----+
1 row in set (0.00 sec)
b) To print float or double type, use the following query −
mysql> select 23.45 as ' ';
+-------+
| |
+-------+
| 23.45 |
+-------+
1 row in set (0.00 sec) | [
{
"code": null,
"e": 1159,
"s": 1062,
"text": "To simulate a print statement in MySQL, you can use select statement. The syntax is as follows −"
},
{
"code": null,
"e": 1191,
"s": 1159,
"text": "SELECT ‘anyStringValue’ as ’ ‘;"
},
{
"code": null,
"e": 1256,
"s": 1... |
Set, Clear and Toggle a given bit of a number in C - GeeksforGeeks | 20 Nov, 2019
Given a number N, the task is to set, clear and toggle the K-th bit of this number N.
Setting a bit means that if K-th bit is 0, then set it to 1 and if it is 1 then leave it unchanged.
Clearing a bit means that if K-th bit is 1, then clear it to 0 and if it is 0 then leave it unchanged.
Toggling a bit means that if K-th bit is 1, then change it to 0 and if it is 0 then change it to 1.
Examples:
Input: N = 5, K = 1
Output:
Setting Kth bit: 5
Clearing Kth bit: 4
Toggling Kth bit: 4
Explanation:
5 is represented as 101 in binary
and has its first bit 1, so
setting it will result in 101 i.e. 5.
clearing it will result in 100 i.e. 4.
toggling it will result in 100 i.e. 4.
Input: N = 7, K = 2
Output:
Setting Kth bit: 7
Clearing Kth bit: 5
Toggling Kth bit: 5
Explanation:
7 is represented as 111 in binary
and has its second bit 1, so
setting it will result in 111 i.e. 7.
clearing it will result in 101 i.e. 5.
toggling it will result in 101 i.e. 5.
Approach:
Below are the steps to set, clear and toggle Kth bit of N:
Setting a bit
Since we all know that performing bitwise OR of any bit with a set bit results in a set bit, i.e.Any bit <bitwise OR> Set bit = Set bit
which means,
0 | 1 = 1
1 | 1 = 1
Any bit <bitwise OR> Set bit = Set bit
which means,
0 | 1 = 1
1 | 1 = 1
So for setting a bit, performing a bitwise OR of the number with a set bit is the best idea.N = N | 1 << K
OR
N |= 1 << K
where K is the bit that is to be set
N = N | 1 << K
OR
N |= 1 << K
where K is the bit that is to be set
Clearing a bit
Since bitwise AND of any bit with a reset bit results in a reset bit, i.e.Any bit <bitwise AND> Reset bit = Reset bit
which means,
0 & 0 = 0
1 & 0 = 0
So for clearing a bit, performing a bitwise AND of the number with a reset bit is the best idea.
n = n & ~(1 << k)
OR
n &= ~(1 << k)
where k is the bit that is to be cleared
Any bit <bitwise AND> Reset bit = Reset bit
which means,
0 & 0 = 0
1 & 0 = 0
So for clearing a bit, performing a bitwise AND of the number with a reset bit is the best idea.
n = n & ~(1 << k)
OR
n &= ~(1 << k)
where k is the bit that is to be cleared
So for clearing a bit, performing a bitwise AND of the number with a reset bit is the best idea.
n = n & ~(1 << k)
OR
n &= ~(1 << k)
where k is the bit that is to be cleared
So for clearing a bit, performing a bitwise AND of the number with a reset bit is the best idea.
n = n & ~(1 << k)
OR
n &= ~(1 << k)
where k is the bit that is to be cleared
n = n & ~(1 << k)
OR
n &= ~(1 << k)
where k is the bit that is to be cleared
Toggle a bit
Since XOR of unset and set bit results in a set bit and XOR of a set and set bit results in an unset bit. Hence performing bitwise XOR of any bit with a set bit results in toggle of that bit, i.e.Any bit <bitwise XOR> Set bit = Toggle
which means,
0 ^ 1 = 1
1 ^ 1 = 0
So in order to toggle a bit, performing a bitwise XOR of the number with a reset bit is the best idea.
n = n ^ 1 << k
OR
n ^= 1 << k
where k is the bit that is to be cleared
Any bit <bitwise XOR> Set bit = Toggle
which means,
0 ^ 1 = 1
1 ^ 1 = 0
So in order to toggle a bit, performing a bitwise XOR of the number with a reset bit is the best idea.
n = n ^ 1 << k
OR
n ^= 1 << k
where k is the bit that is to be cleared
So in order to toggle a bit, performing a bitwise XOR of the number with a reset bit is the best idea.
n = n ^ 1 << k
OR
n ^= 1 << k
where k is the bit that is to be cleared
So in order to toggle a bit, performing a bitwise XOR of the number with a reset bit is the best idea.
n = n ^ 1 << k
OR
n ^= 1 << k
where k is the bit that is to be cleared
n = n ^ 1 << k
OR
n ^= 1 << k
where k is the bit that is to be cleared
Below is the implementation of the above approach:
// C program to set, clear and toggle a bit #include <stdio.h> // Function to set the kth bit of nint setBit(int n, int k){ return (n | (1 << (k - 1)));} // Function to clear the kth bit of nint clearBit(int n, int k){ return (n & (~(1 << (k - 1))));} // Function to toggle the kth bit of nint toggleBit(int n, int k){ return (n ^ (1 << (k - 1)));} // Driver codeint main(){ int n = 5, k = 1; printf("%d with %d-th bit Set: %d\n", n, k, setBit(n, k)); printf("%d with %d-th bit Cleared: %d\n", n, k, clearBit(n, k)); printf("%d with %d-th bit Toggled: %d\n", n, k, toggleBit(n, k)); return 0;}
5 with 1-th bit Set: 5
5 with 1-th bit Cleared: 4
5 with 1-th bit Toggled: 4
Bit Magic
C Programs
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Cyclic Redundancy Check and Modulo-2 Division
Little and Big Endian Mystery
Add two numbers without using arithmetic operators
Binary representation of a given number
Program to find whether a given number is power of 2
Strings in C
Arrow operator -> in C/C++ with Examples
C Program to read contents of Whole File
UDP Server-Client implementation in C
Header files in C/C++ and its uses | [
{
"code": null,
"e": 24331,
"s": 24303,
"text": "\n20 Nov, 2019"
},
{
"code": null,
"e": 24417,
"s": 24331,
"text": "Given a number N, the task is to set, clear and toggle the K-th bit of this number N."
},
{
"code": null,
"e": 24517,
"s": 24417,
"text": "Sett... |
Program to print all the numbers divisible by 5 or 7 for a given number - GeeksforGeeks | 18 Nov, 2021
Given the integer N, the task is to print all the numbers less than N, which are divisible by 5 or 7.
Examples :
Input : 20
Output : 5 7 10 14 15 20
Input: 50
Output: 5 7 10 14 15 20 21 25 28 30 35 40 42 45 49 50
Approach: For example, let’s take N = 20 as a limit, then the program should print all numbers less than 20 which are divisible by both 5 or 7. For this divide each number from 0 to N by both 5 and 7 and check their remainder. If the remainder is 0 in both cases then simply print that number.
Below is the implementation :
C++
Java
Python3
C#
Javascript
// C++ program to print all the numbers
// divisible by 5 or 7 for a given number
# include<bits/stdc++.h>
using namespace std;
// Result generator with N
int NumGen(int n)
{
// Iterate from 0 to N
for(int j = 1; j < n + 1; j++)
{
// Short-circuit operator is used
if (j % 5 == 0 || j % 7 == 0)
cout << j << " ";
}
return n;
}
// Driver code
int main()
{
// Input goes here
int N = 50;
// Iterating over generator function
NumGen(N);
return 0;
}
// This code is contributed by Code_Mech
// Java program to print all the numbers
// divisible by 5 or 7 for a given number
import java.util.*;
class GFG{
// Result generator with N
static int NumGen(int n)
{
// Iterate from 0 to N
for(int j = 1; j < n + 1; j++)
{
// Short-circuit operator is used
if (j % 5 == 0 || j % 7 == 0)
System.out.print(j + " ");
}
return n;
}
// Driver code
public static void main(String args[])
{
// Input goes here
int N = 50;
// Iterating over generator function
NumGen(N);
}
}
// This code is contributed by AbhiThakur
# Python3 program to print all the numbers
# divisible by 5 or 7 for a given number
# Result generator with N
def NumGen(n):
# iterate from 0 to N
for j in range(1, n+1):
# Short-circuit operator is used
if j % 5 == 0 or j % 7 == 0:
yield j
# Driver code
if __name__ == "__main__":
# input goes here
N = 50
# Iterating over generator function
for j in NumGen(N):
print(j, end = " ")
// C# program to print all the numbers
// divisible by 5 or 7 for a given number
using System;
class GFG{
// Result generator with N
static int NumGen(int n)
{
// Iterate from 0 to N
for(int j = 1; j < n + 1; j++)
{
// Short-circuit operator is used
if (j % 5 == 0 || j % 7 == 0)
Console.Write(j + " ");
}
return n;
}
// Driver code
public static void Main()
{
// Input goes here
int N = 50;
// Iterating over generator
// function
NumGen(N);
}
}
// This code is contributed by Code_Mech
<script>
// JavaScript program to print all the numbers
// divisible by 5 or 7 for a given number
// Result generator with N
function NumGen(n)
{
// Iterate from 0 to N
for(let j = 1; j < n + 1; j++)
{
// Short-circuit operator is used
if (j % 5 == 0 || j % 7 == 0)
document.write(j + " ");
}
return n;
}
// Driver code
// Input goes here
let N = 50;
// Iterating over generator function
NumGen(N);
</script>
Output:
5 7 10 14 15 20 21 25 28 30 35 40 42 45 49 50
Time Complexity: O(N)
Auxiliary Space: O(1)
abhaysingh290895
Code_Mech
arorakashish0911
vaibhavrabadiya3
rohitkumarsinghcna
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python | [
{
"code": null,
"e": 24997,
"s": 24966,
"text": " \n18 Nov, 2021\n"
},
{
"code": null,
"e": 25099,
"s": 24997,
"text": "Given the integer N, the task is to print all the numbers less than N, which are divisible by 5 or 7."
},
{
"code": null,
"e": 25111,
"s": 25099... |
Transform Grayscale Images to RGB Using Python’s Matplotlib | by Matthew Arthur | Towards Data Science | Data pre-processing is critical for computer vision applications, and properly converting grayscale images to the RGB format expected by current deep learning frameworks is an essential technique. What does that mean?
Most color photos are composed of three interlocked arrays, each responsible for either Red, Green, or Blue values (hence RGB) and the integer values within each array representing a single pixel-value. Meanwhile, black-and-white or grayscale photos have only a single channel, read from one array.
Using the matplotlib library, let’s look at a color (RGB) image:
img = plt.imread('whales/547b59eec.jpg')plt.imshow(img)print(img.shape)(525, 1050, 3)
The output of the matplotlib.plot.shape call tells us that the image has height of 525 pixels, width of 1050 pixels, and there are three arrays (channels) of this size.
The img object is <class ‘numpy.ndarray’>, so let’s look at the shape and values of each layer:
#valuesprint(img[524][1049][2])198print(img[524][1049])[155 177 198]print(img[524])[[ 68 107 140] [ 76 115 148] [ 76 115 148] [ 75 114 147] ... [171 196 216] [171 193 214] [171 193 214] [155 177 198]]
All right, what are the print commands above telling us about this image which is composed of 1050 columns (width) each with 525 rows (height)?
First, we look at the value of the very last pixel, at the last row of the last column and the last channel: 198. This tell us that the file most likely uses values from 0 to 255.
Next, we look at the values of this pixel across all three channels: [155, 177, 198]. These are the Red, Green & Blue values at that pixel.3
And for fun we can look at the values of the last row across all layers and all rows.
Grayscale images only have one channel! That’s it!
Quoting the Pytorch documentation:1 All pre-trained models expect input images normalized in the same way, i.e. mini-batches of 3-channel RGB images of shape (3 x H x W)...
So trying to ingest your grayscale with many computer vision / deep learning pipelines relying on transfer learning from a standard commodity model such as Resnet18 or -34 will result in a variety of errors.
Add two additional channels to a grayscale! There are a variety of ways to do this, so my way is below: copy the first layer into new layers of a new 3D array, thus generating a color image (of a black-and-white, so it’ll still be B&W).
I’ll work with a square image from the Arabic Handwritten Digit Dataset as an example. The shape is (28, 28) which confirms it is a single-channel image.
Since I want to feed this into a model based on Resnet34, I need three channels.
The obvious (and less-than-correct) way is to add two arrays of zeros of the same size:
dim = np.zeros((28,28))R = np.stack((O,dim, dim), axis=2)
O is our Original array. We can add two zero arrays of the same shape easily enough but we will get a red-dominated image:
Whoops! We want to populate the same values across all channels. Before we do, though, let’s see what happens if we roll our original array through each of the non-fully-RGB possibilities:
All right, here’s RGB:
And that’s it.
Additional code is on my github: www.github.com/matthewarthur. My LinkedIn is https://www.linkedin.com/in/matt-a-8208aaa/. Say hi!
[1] https://pytorch.org/docs/stable/torchvision/models.html
[2] https://www.cs.virginia.edu/~vicente/recognition/notebooks/image_processing_lab.html
[3] Indexing in numpy is detailed here: https://docs.scipy.org/doc/numpy-1.10.0/user/basics.indexing.html | [
{
"code": null,
"e": 390,
"s": 172,
"text": "Data pre-processing is critical for computer vision applications, and properly converting grayscale images to the RGB format expected by current deep learning frameworks is an essential technique. What does that mean?"
},
{
"code": null,
"e": ... |
How do I create an automatically updating GUI using Tkinter in Python? | GUI window has many controls such as labels, buttons, text boxes, etc. We may sometimes want the content of our controls such as labels to update automatically while we are viewing the window.
We can use after() to run a function after a certain time. For example, 1000 milliseconds mean 1 second. The function which we call continuously after a certain amount of time will update the text or any updation you want to happen.
We have a label on our window. We want the text of the label to update automatically after 1 second. To keep the example easy, suppose we want the label to show some number between 0 and 1000. We want this number to change after each 1 second.
We can do this by defining a function that will change the text of the label to some random number between 0 and 1000. We can call this function continuously after an interval of 1 second using the after().
from Tkinter import *
from random import randint
root = Tk()
lab = Label(root)
lab.pack()
def update():
lab['text'] = randint(0,1000)
root.after(1000, update) # run itself again after 1000 ms
# run first time
update()
root.mainloop()
This will automatically change the text of the label to some new number after 1000 milliseconds. You can change the time interval according to need. The update function can be modified to perform the required updation.
This line of the code performs the main function of recalling the function update().
The first parameter in root.after() specifies the time interval in milliseconds after which you want the function to be recalled.
The second parameter specifies the name of the function to be recalled. | [
{
"code": null,
"e": 1255,
"s": 1062,
"text": "GUI window has many controls such as labels, buttons, text boxes, etc. We may sometimes want the content of our controls such as labels to update automatically while we are viewing the window."
},
{
"code": null,
"e": 1488,
"s": 1255,
... |
CSS3 - Multi Columns | CSS3 supported multi columns to arrange the text as news paper structure.
Some of most common used multi columns properties as shown below −
column-count
Used to count the number of columns that element should be divided.
column-fill
Used to decide, how to fill the columns.
column-gap
Used to decide the gap between the columns.
column-rule
Used to specifies the number of rules.
rule-color
Used to specifies the column rule color.
rule-style
Used to specifies the style rule for column.
rule-width
Used to specifies the width.
column-span
Used to specifies the span between columns.
Below example shows the arrangement of text as new paper structure.
<html>
<head>
<style>
.multi {
/* Column count property */
-webkit-column-count: 4;
-moz-column-count: 4;
column-count: 4;
/* Column gap property */
-webkit-column-gap: 40px;
-moz-column-gap: 40px;
column-gap: 40px;
/* Column style property */
-webkit-column-rule-style: solid;
-moz-column-rule-style: solid;
column-rule-style: solid;
}
</style>
</head>
<body>
<div class = "multi">
Tutorials Point originated from the idea that there exists a class
of readers who respond better to online content and prefer to learn
new skills at their own pace from the comforts of their drawing rooms.
The journey commenced with a single tutorial on HTML in 2006 and elated
by the response it generated, we worked our way to adding fresh tutorials
to our repository which now proudly flaunts a wealth of tutorials and
allied articles on topics ranging from programming languages to web
designing to academics and much more.
</div>
</body>
</html>
It will produce the following result −
For suppose, if user wants to make text as new paper without line, we can do this by removing style syntax as shown below −
.multi {
/* Column count property */
-webkit-column-count: 4;
-moz-column-count: 4;
column-count: 4;
/* Column gap property */
-webkit-column-gap: 40px;
-moz-column-gap: 40px;
column-gap: 40px;
}
It will produce the following result −
33 Lectures
2.5 hours
Anadi Sharma
26 Lectures
2.5 hours
Frahaan Hussain
44 Lectures
4.5 hours
DigiFisk (Programming Is Fun)
21 Lectures
2.5 hours
DigiFisk (Programming Is Fun)
51 Lectures
7.5 hours
DigiFisk (Programming Is Fun)
52 Lectures
4 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2700,
"s": 2626,
"text": "CSS3 supported multi columns to arrange the text as news paper structure."
},
{
"code": null,
"e": 2767,
"s": 2700,
"text": "Some of most common used multi columns properties as shown below −"
},
{
"code": null,
"e": 2780... |
GATE | GATE-CS-2005 | Question 57 - GeeksforGeeks | 28 Jun, 2021
Consider the languages:
L1 = {wwR |w ∈ {0, 1}*}
L2 = {w#wR | w ∈ {0, 1}*}, where # is a special symbol
L3 = {ww | w ∈ (0, 1}*)
Which one of the following is TRUE?(A) L1 is a deterministic CFL(B) L2 is a deterministic CFL(C) L3 is a CFL, but not a deterministic CFL(D) L3 is a deterministic CFLAnswer: (B)Explanation:
L1: {ww^R | w belongs {0,1}*}This is a CFL but not a DCFL. It can be derived from the following grammarS -> aSa | bSb | epsilonBut it can’t be derived from any deterministic pushdown automaton, because there is no way to figure out where a word w ends and its reverse starts.
L2: {w#w^R | w belongs {0,1}*}This is a CFL, due to the same reason as described above. This is a deterministic CFL because we have a marker to help us find out the end of the word w and start of its reverse. Thus a PDA where all the alphabets are pushed until we get # and afterwards pop only if the top of the stack matches the current alphabet and reject otherwise – will derive L2.
L3: {ww | w belongs {0,1}*}This is not even a CFL. Above claim could be proved using pumping lemma –Consider a string z of the form (0^n 1^n 0^n 1^n).Assuming L3 is a CFL, and z obviously satisfies L3 – thus z should also satisfy pumping lemma.We will take n such that n = p, where p is the pumping length of L3, hence forcing our string to be of length greater than pumping length.Now, according to pumping lemma, there must exist u,v,w,x,y such that z = uvwxy, |vwx| <= p, |vx| > 0 and u{v^i}x{y^i}z belongs L3 for all i>=0.There doesn’t exist any such configuration of u,v,w,x,y such that u{v^0}x{y^0}z belongs L3. Hence z doesn’t satisfy pumping lemma. Hence L3 is not a CFL.
Considering all the above conclusions, only correct option comes out to be (B) L2 is a deterministic CFL.
Reference ;
https://courses.engr.illinois.edu/cs373/sp2013/Lectures/lec17.pdf
This solution is contributed by Vineet Purswani.Quiz of this Question
GATE-CS-2005
GATE-GATE-CS-2005
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE-IT-2004 | Question 83
GATE | GATE CS 2018 | Question 37
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2016 (Set 1) | Question 63
GATE | GATE-CS-2007 | Question 17
GATE | GATE-IT-2004 | Question 12
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2007 | Question 64 | [
{
"code": null,
"e": 24330,
"s": 24302,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 24354,
"s": 24330,
"text": "Consider the languages:"
},
{
"code": null,
"e": 24459,
"s": 24354,
"text": "L1 = {wwR |w ∈ {0, 1}*}\nL2 = {w#wR | w ∈ {0, 1}*}, where # is a s... |
This Dress Doesn’t Exist. Fine tuning GPT-2 and StyleGAN for a... | by Michael Sugimura | Towards Data Science | This post was originally published on the Shoprunner Engineering blog here feel free to check it out and at some of the other work our teams are doing.
Our ShopRunner Data Science team allows all members to have a quarterly hack week. It is important for data science teams to keep innovating so once per quarter team members are allowed to spend a week working on more speculative projects of their choice. For my 2019 Q3 hack week I decided to build a series of generator models to attempt to create fake products. Generator models are models commonly trained to create realistic images or text based on real world examples. This project may seem fairly outlandish, which it is, but my general idea is that if we can create strong generator models that can capture the diversity of our product catalog then we could use these generators to augment low frequency classes within our catalog for other deep learning projects such as taxonomy classification or attribute tagging.
The two networks I decided to use were OpenAI’s GPT-2 117M parameter small model for text generation and Nvidia’s StyleGAN for image generation. I then fine tuned these to internal ShopRunner datasets. For both models I found using the original Tensorflow implementations to be the best path forward since ports to other frameworks either didn’t have features that I needed or were not as well built out.
Both models were trained on a Nvidia 2080 TI graphics card.
In February of 2019 OpenAI announced its newest language model GPT-2. GPT-2 is trained on 40GB of internet text but OpenAI restricted the release of the model down to much smaller versions due to concerns of malicious behavior. A large part of building that high quality dataset was taking higher quality reddit. In its raw state GPT-2 is excellent at generating realistic sounding text but the text tends to fall into either reddit style dialogue or wikipedia style description. So to get the most use out of GPT-2 as a generator for fake products we need to tune it to our specific use case, in this case fashion.
The repo provided by nshepperd for fine tuning provides a series of scripts and instructions for fine tuning. To perform fine tuning we really just need to format a text dataset for consumption by GPT-2. For this I ended up writing 100K product descriptions to their own line in a .txt file with a GPT-2 specific <endoftext> token appended to the end so that GPT-2 would learn how to end the product descriptions and hopefully learn how to structure them in a more realistic manner.
GPT-2 trained fairly quickly producing good results after 15K batches/steps which took a few hours.
We fine tuned GPT-2 on ShopRunner data for 15K steps, leading to what we call SR GPT-2. After fine tuning SR GPT-2 is able to generate fairly realistic looking product descriptions including line breaks and formatting. These are also fairly entertaining to read.
======================================== SAMPLE 1 ========================================WATERDOG | PINK HALSTON COLLECTION. HALSTON'S HOODED SILK FIT IS SO AWESOME HONG KONG\'s black wool-blend hooded cowl jacket is handmade from lightweight wool sourced from two countries located in the Arctic Circle and Wye Hydroelectric Power Supply.- HALSTON WOOL CLIMB JERRY WOOL FIT - Fabric: 90% wool, 10% wool crepe; 12% viscose, 8% polyester and 5% nylon - Washable, dry clean recommended - ImportedSKU: HU18-17FBCFABRIC & CAREMachine wash cold with similar colorsWarm down with whiteWash in cold water and hang dry ======================================== SAMPLE 2 ========================================Wool-Cotton Cropped T-Shirt Dress Dress with Boho Floral Print - Black This T-Shirt Dress features a Boho Floral printed front, a short sleeve hemline, and an asymmetrical ruffled hemline. A limited edition piece from our New York Fashion Show capsule.New York Fashion is celebrating the 20th anniversary of their popular T-Shirt Dress in 2011. The T-Shirt Dress is a loose-fitting bodice cut out cut in black silk crepe de chine with a fitted waistband. The dress has a V neckline, long sleeves, two front split pockets, and a draped waist.100% SilkDry Clean OnlyImportedSI38S-F18Size & FitModel is wearing a size 6Model Measurements: Height: 5ft 9in; Bust-Chest: 33in; Waist: 23.6in; Hips: 34.5inAbout SI38S-F18Sieviast designer and renowned expert James Simone launched his versatile collection of womens ready-to-wear and accessories in 2008. The label\'s garments have been named the year\'s top fashion showpieces, and the lines are sure to become a summer staple.
However using GPT-2 we can also generate context based examples.
Here is a sample generated with the context “sleeveless red asymmetric dress”
DetailsThis asymmetric fit-and-flare fit is cut in a slim fit. Cut for a flattering, relaxed fit.- Round neckline. - Sleeveless. - One center front, two center back. - 100% polyester. - Machine wash. - Imported. - Model is 5\'10""/178 cm and has a 32"" bust. She wears a US size 2.
This example seems fairly realistic and reasonable. One thing I was happy about is that besides just generating a realistic looking description was that words like “asymmetric” and “sleeveless” which were used in the input phrase also appear in the generated description.
On a less serious note, sometimes with less fashion sounding context we can still get some of the old GPT-2 training and structure bleeding through.
For context “meat dress” inspired by Lady Gaga
With the same context meat dress below are two generated examples. When SR GPT-2 generates a sample it takes into consideration words with the highest probability of following the given context. However there is some randomness involved in the process so outputs can come out quite differently. The first example generates a fairly reasonable looking product description. The second SR GPT-2 falls back a bit into the more definition type training of GPT-2
Meat dress: our Italian twist, crafted of a crepe fabric with a stretchy, crinkle finish. Features hand-woven details, an embroidered floral pattern throughout.- Adjustable, pull-on, belt - Side slit - Adjustable, belt with cut from a relaxed fit - Fabric has been softened by hand washing - 95% rayon, 5% spandex blend; lining: 100% polyester crepe de chine - Washable - Importeddress made of meat, bone, and vegetable gabardine. In honor of the American Heart Foundation.
Generative Adversarial Networks (GAN) are an interesting area of deep learning where the training process involves two networks a generator and a discriminator. The generator model starts to create images on its own, it starts from random noise while the discriminator gives feedback by looking at training examples and generator output and predicts if they are “real” or “fake”. Overtime this feedback helps the generator create more realistic images.
StyleGAN is a model that was released by Nvidia near the end of 2018. It is an improvement over a previous model from Nvidia called ProGAN. ProGAN was trained to generate high quality images 1024x1024 and did so by implementing a progressive training cycle where it starts training images at low-resolution (4x4)and increases that resolution over time by adding additional layers. Training the low resolution images helped make training faster and increased the quality of final images as the networks were able to learn important lower level characteristics. However ProGAN has limited ability to control the generated images.
StyleGAN improves on ProGAN by giving the ability to control the “style” of outputs by allowing users to manipulate the latent space vectors of a generated image. Every image that StyleGAN generates is represented by a vector that exists within StyleGAN’s latent space. So if you modify that vector you can adjust the characteristics of the image within StyleGAN’s latent space to create a new image with desired characteristics.
This is just a brief description of StyleGAN for more information check out the paper or other write-ups on online.
I ended up training SR StyleGAN for around 4 days and generated around 2 million 512x512 images in the process. As a starting point for weight initialization I actually used another anime trained StyleGAN. I used this anime StyleGAN as a starting point because the original Nvidia StyleGAN was trained to generate 1024x1024 images which are great, but also harder to work with because they require more computational firepower. The anime StyleGAN in comparison was trained to generate 512x512 images so it is more manageable.
The dataset for SR StyleGAN was around 9000 mostly dress product images which I pruned down based on a few criteria. Step 1 I did with a few lines of code, but the last three steps were manual.
Size: I threw out images with a width or height below 300. If you leave low quality images in the dataset you end up with pixelated looking final generated images.composition: for simplicity I tried to keep images where the model/product was located in the center of the imagebackground: removed overly complex backgrounds since it would mostly just mean lots of additional effort on the model’s part to begin to generate them wellremoved non product shots: certain images were either blank placeholder images or zoomed in shots of pattern/fabric. Leaving shots like this in the dataset I found gives StyleGAN an easy way to cheat and generate “realistic” looking images to fool the discriminator. However, this is not really the most desirable behavior so I did my best to remove them.
Size: I threw out images with a width or height below 300. If you leave low quality images in the dataset you end up with pixelated looking final generated images.
composition: for simplicity I tried to keep images where the model/product was located in the center of the image
background: removed overly complex backgrounds since it would mostly just mean lots of additional effort on the model’s part to begin to generate them well
removed non product shots: certain images were either blank placeholder images or zoomed in shots of pattern/fabric. Leaving shots like this in the dataset I found gives StyleGAN an easy way to cheat and generate “realistic” looking images to fool the discriminator. However, this is not really the most desirable behavior so I did my best to remove them.
Now that we have walked through some of the training details of SR StyleGAN we can start talking about how to generate those low frequency products. In the following video you see a few seconds where jumpsuits are generated even though this dataset was mostly dresses. So for this hack week I used jumpsuits as an example low frequency class.
One quick method to generate additional jumpsuit samples would be to generate a large number of SR StyleGAN images unconditionally and search through those to find examples of the low frequency class we care about.
Here are some examples that I manually pulled out of a few hundred generated StyleGAN images. This is fine? BUT if we can figure out where exactly jumpsuits exist in the SR StyleGAN latent space we could generate them as we see fit.
Each image is represented by a feature vector in SR StyleGAN’s latent space. So if we combine different vectors together we are able to start to get at “style mixing”. In the two sets of videos below what we are seeing the top right image get mapped onto the bottom left image. The resulting mixture is in the bottom right image which should be dominated by the characteristics of the top right image. In both videos you see the characteristics of the top right image shift in response to changes in the bottom left image.
This is cool, it sort of gives us a way to combine two images by combining their feature vectors in SR StyleGAN’s latent space.
Since the goal was to generate realistic looking fake products here are two examples of generated images with contextually generated text. As of now the text context is manually generated, but a future project could be to build a captioning model or simply use tags generated by internal attribute and taxonomy models which the team has been working on. These generated tags can be used as a sort of stand in for product title. For example potential attributes of the following dress could be “sleeveless red asymmetric dress” and could be fed into GPT-2 to get contextually generated product descriptions.
Context for SR GPT-2: sleeveless red asymmetric dress
DetailsThis asymmetric fit-and-flare fit is cut in a slim fit. Cut for a flattering, relaxed fit.- Round neckline. - Sleeveless. - One center front, two center back. - 100% polyester. - Machine wash. - Imported. - Model is 5\'10""/178 cm and has a 32"" bust. She wears a US size 2.
A second example using a jumpsuit generated by SR StyleGAN with potential tags being “black short sleeve jumpsuit” which feels like a reasonable description or boring title.
SR GPT-2 context: black short sleeve jumpsuit.
A loose, fluid silhouette lends a comfortable wear to any look. The buttonless back features a keyhole on the chest.Material and CareMaterial information: 100% Cotton, Lining: 100% Viscose, Lining: 100% Polyester
Then as a fun follow up I fed these two examples through our internal taxonomy classification service which uses images and text input and found that the taxonomy service successfully categorizes the two images as a “women’s dress” and a “jumpsuit”.
Over the course of this hack week I spent a lot of time training models and looking at generated image and text outputs. I still think that while hard to utilize these generator style models could potentially be very useful for adding interesting business value. I mentioned initially things like synthetic data augmentation for low frequency classes, but other ideas that came from the team could be letting users generate items and manipulate the items if we can figure out how to successfully locate and manipulate different features in the GAN’s latent space. If users can generate items they would like then we can do more standard visual searches of our catalog and so on.
As for notes on the models.
GPT-2 seems fine and learns quickly, potentially overfits quickly as well... by feeding it appropriate context it can generate reasonable text. What we use as context is really the question. Thoughts would be a captioning model based on a real image or a GAN image. A simpler way would just be to feed in all available attributes and taxonomy information as plain text and see how it does.
StyleGAN is decently trained and to get better results I would likely need to train it from scratch or at least from a much earlier point in its training. I intentionally had StyleGAN start at a point where it was generating fairly large images. all while using those anime weights.
Something that I experimented with but did not find much success with was mapping images in and out of StyleGAN’s latent space. The general idea is to use a pretrained network to learn find the the closest approximation of an image in StyleGAN’s latent space by generating StyleGAN vectors and comparing how close the image is to the original. If we can successfully map items into StyleGAN’s latent space then we can combine those vectors to have a bit more control of what we are modifying. For example we could map a bunch of jumpsuits into StyleGAN’s latent space and mix those jumpsuits together to make new samples. Another related step is finding where certain attributes or patterns exist in the latent space then we could potentially
For a full training run Nvidia does list a training time of 42 days with a single GPU. You could likely get good results in a full week or two of training since other folks who have tried training from scratch report the last few weeks are really just about getting clean minor details.
If I end up continuing on this hack week idea a lot of future work will likely be around manipulating SR StyleGAN outputs and locating where things like dress/sleeve length are located or colors and patterns in order to allow for more fine grained control over manipulating different aspects of the generated images. | [
{
"code": null,
"e": 323,
"s": 171,
"text": "This post was originally published on the Shoprunner Engineering blog here feel free to check it out and at some of the other work our teams are doing."
},
{
"code": null,
"e": 1149,
"s": 323,
"text": "Our ShopRunner Data Science team ... |
Count digits in a factorial | Practice | GeeksforGeeks | Given an integer N. You have to find the number of digits that appear in its factorial, where factorial is defined as, factorial(N) = 1*2*3*4........*N and factorial(0) = 1.
Example 1:
Input:
N = 5
Output:
3
Explanation:
5! is 120 so there are 3
digits in 120
Example 2:
Input:
N = 100
Output:
7
Explanation:
100! is 3628800​ so there are
7 digits in 3628800​
Your Task:
You don't need to read input or print anything. Your task is to complete the function facDigits() which takes an integer N as input parameter and returns the number of digits in factorial of N.
Expected Time Complexity: O(1)
Expected Space Complexity: O(1)
Constraints:
1 ≤ N ≤ 104
+1
yashchawla1163 months ago
Java Simple To Understand And Easy To Implement.
https://yashboss116.blogspot.com/2022/01/count-digits-in-factorial-geeks-for.html
+2
Shreyansh Kumar Singh1 year ago
Shreyansh Kumar Singh
Count of Digits in N!We know,log(a*b) = log(a) + log(b)∴ log( n! ) = log(1*2*3....... * n) = log(1) + log(2) + ........ +log(n)So, digits in N! = ceil (log(n!))Programming Approach:Run a loop from 2 to N,in each iteration add the value of log10(i) to countAt the end return the ceiling value of count.(Take extra care when i<2)
+1
Sumit Pardhiya1 year ago
Sumit Pardhiya
if(N<0) return 0; if(N<=1) return 1; double r=0; for(int i=2;i<=N;i++) { r=r+log10(i); } return floor(r)+1; }
0
Annanya Mathur1 year ago
Annanya Mathur
def facDigits(self,N): r=1; for i in range (1,N+1): r=r*i return math. floor(math. log (r,10)+1)
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": 414,
"s": 238,
"text": "Given an integer N. You have to find the number of digits that appear in its factorial, where factorial is defined as, factorial(N) = 1*2*3*4........*N and factorial(0) = 1.\n "
},
{
"code": null,
"e": 425,
"s": 414,
"text": "Example 1... |
How do I change button size in Python Tkinter? | Tkinter Button widgets are used to create buttons that are necessary for an application. We can also add an event Object in the Button constructor and trigger it to perform some operation.
In order to customize the Button size, we can use the width and height property of the button widget.
In this example, we will create some buttons with different sizes,
#Import the required libraries
from tkinter import *
#Create an instance of tkinter frame
win= Tk()
#Set the geometry of frame
win.geometry("600x250")
win.resizable(False, False)
Button(win, text="Button-1",height= 5, width=10).pack()
Button(win, text="Button-2",height=8, width=15).pack()
Button(win, text= "Button-3",height=10, width=30).pack()
win.mainloop()
Running the above code will display a window containing buttons of different sizes. | [
{
"code": null,
"e": 1251,
"s": 1062,
"text": "Tkinter Button widgets are used to create buttons that are necessary for an application. We can also add an event Object in the Button constructor and trigger it to perform some operation."
},
{
"code": null,
"e": 1353,
"s": 1251,
"t... |
Multiple Linear Regression — with math and code | by Niranjan Pramanik, Ph.D. | Towards Data Science | Linear regression is a form of predictive model which is widely used in many real world applications. Quite a good number of articles published on linear regression are based on single explanatory variable with detail explanation of minimizing mean square error (MSE) to optimize best fit parameters. In this article, multiple explanatory variables (independent variables) are used to derive MSE function and finally gradient descent technique is used to estimate best fit regression parameters. An example data set having three independent variables and single dependent variable is used to build a multivariate regression model and in the later section of the article, R-code is provided to model the example data set.
The equation for linear regression model is known to everyone which is expressed as:
y = mx + c
where y is the output of the model which is called the response variable and x is the independent variable which is also called explanatory variable. m is the slope of the regression line and c denotes the intercept. Usually we get measured values of x and y and try to build a model by estimating optimal values of m and c so that we can use the model for future prediction for y by giving x as input.
Practically, we deal with more than just one independent variable and in that case building a linear model using multiple input variables is important to accurately model the system for better prediction. Therefore, in this article multiple regression analysis is described in detail. Matrix representation of linear regression model is required to express multivariate regression model to make it more compact and at the same time it becomes easy to compute model parameters. I believe readers do have fundamental understanding about matrix operations and linear algebra. However, in the last section, matrix rules used in this regression analysis are provided to refresh the knowledge of readers.
Let’s say we have following data showing scores obtained by different students in a class. The scores are given for four exams in a year with last column being the scores obtained in the final exam. From data, it is understood that scores in the final exam bear some sort of relationship with the performances in previous three exams.
Here considering that scores from previous three exams are linearly related to the scores in the final exam, our linear regression model for first observation (first row in the table) should look like below.
152 = a×73 + b×80 + c×75 + d
Where a, b, c and d are model parameters.
The right hand side of the equation is the regression model which upon using appropriate parameters should produce the output equals to 152. But practically no model can be perfectly built to mimic 100% of the reality. Always, there exists an error between model output and true observation. Therefore, the correct regression equation can be defined as below:
152 = a×73 + b×80 + c×75 + d ×1+ e1
Where e1 is the error of prediction for first observation. Similarly for other rows in the data table, the equations can be written
185 = a×93 + b×88 + c×93 + d×1 + e2
180 = a×89+ b×91+ c×90 + d×1 + e3
196 = a×96+ b×98+ c×100 + d×1 + e4
........................................................
........................................................
192 = a×96+ b×93+ c×95+ d×1 + e25
Above equations can be written with help of four different matrices as mentioned below.
Using above four matrices, the equation for linear regression in algebraic form can be written as:
Y = Xβ + e
To obtain right hand side of the equation, matrix X is multiplied with β vector and the product is added with error vector e. As we know that two matrices can be multiplied if the number of columns of 1st matrix is equal to the number of rows of 2nd matrix. In this case, X has 4 columns and β has four rows.
Rearranging the terms, error vector is expressed as:
e = Y - Xβ
Now, it is obvious that error, e is a function of parameters, β. In the next section, MSE in matrix form is derived and used as objective function to optimize model parameters.
MSE is calculated by summing the squares of e from all observations and dividing the sum by number of observations in the data table. Mathematically:
Replacing e with Y — Xβ in the equation, MSE is re-written as:
Expanding above equation as follows:
Above equation is used as cost function (objective function in optimization problem) which needs to be minimized to estimate best fit parameters in our regression model. Gradient needs to be estimated by taking derivative of MSE function with respect to parameter vector β and to be used in gradient descent optimization.
As mentioned above, gradient is expressed as:
Where,∇ is the differential operator used for gradient. Using matrix. differentiation rules, we get following equations.
The above matrix is called Jacobian which is used in gradient descent optimization along with learning rate (lr) to update model parameters.
The formula for gradient descent method to update model parameter is shown below.
βold is the initialized parameter vector which gets updated in each iteration and at the end of each iteration βold is equated with βnew. lr is the learning rate which represents step size and helps preventing overshooting the lowest point in the error surface. The iteration process continues till MSE value gets reduced and becomes flat.
In this section, a multivariate regression model is developed using example data set. Gradient descent method is applied to estimate model parameters a, b, c and d. The values of the matrices X and Y are known from the data whereas β vector is unknown which needs to be estimated. Initially, MSE and gradient of MSE are computed followed by applying gradient descent method to minimize MSE.
Read data and initialize β:
dataLR <- read.csv("C:\\Users\\Niranjan\\Downloads\\mlr03.csv", header = T)beta <- c(0,0,0,0) ## beta initializedbeta_T <- t(beta)X = matrix(NA,nrow(dataLR),ncol = 4)X[,1] <- dataLR$EXAM1X[,2] <- dataLR$EXAM2X[,3] <- dataLR$EXAM3X[,4] <- 1XT <- t(X)y <- as.vector(dataLR$FINAL)yT <- t(y)
Compute MSE and update β
mse <- (1/nrow(dataLR))* (yT%*%y - 2 * beta_T%*%XT%*%y + beta_T%*%XT%*%X%*%beta)betanew <- beta - (lr *(2/nrow(dataLR)) * (XT%*%X%*%beta - XT%*%y))
Complete code for parameter estimation
##multivariate linear regressiondataLR <- read.csv("C:\\Users\\Niranjan\\Downloads\\mlr03.csv", header = T)beta <- c(0,0,0,0)beta_T <- t(beta)X = matrix(NA,nrow(dataLR),ncol = 4)X[,1] <- dataLR$EXAM1X[,2] <- dataLR$EXAM2X[,3] <- dataLR$EXAM3X[,4] <- 1XT <- t(X)y <- as.vector(dataLR$FINAL)yT <- t(y)iteration <- 1lr = 0.00001msef = NULLwhile (iteration < 10) { mse <- (1/nrow(dataLR))* (yT%*%y - 2 * beta_T%*%XT%*%y + beta_T%*%XT%*%X%*%beta) betanew <- beta - (lr *(2/nrow(dataLR)) * (XT%*%X%*%beta - XT%*%y)) msef <- rbind(msef,mse) beta <- betanew beta_T <- t(betanew) iteration <- iteration + 1}plot(1:length(msef), msef, type = "l", lwd = 2, col = 'red', xlab = 'Iterations', ylab = 'MSE')grid(nx = 10, ny = 10)print(list(a = beta[1],b = beta[2], c = beta[3], d = beta[4]))
Code for plotting output
library(plot3D)ymod <- X%*%betascatter3D(dataLR$EXAM1,dataLR$EXAM2,dataLR$EXAM3, colvar = ymod, pch = 17, cex = 2,bty = "g",ticktype = "detailed",phi = 0,lwd=2.5, xlab = "Exam1", ylab = 'Exam2',zlab = 'Exam3')scatter3D(dataLR$EXAM1,dataLR$EXAM2,dataLR$EXAM3, colvar = dataLR$FINAL, pch = 16, cex = 2,bty = "g",ticktype = "detailed",phi = 0,lwd=2.5, xlab = "Exam1", ylab = 'Exam2',zlab = 'Exam3',add = T)plot(dataLR$FINAL, ymod, pch = 16, cex = 2, xlab = 'Data', ylab = 'Model')lines(ymod,ymod, lwd = 4, col = "green", lty = 6)grid(nx = 10, ny = 10)legend("topleft",c('Model-Data Points','Best fit line'), lty = c(NA,6), lwd = c(NA,4), col = c("black","green"), pch = c(16,NA))
The value of MSE gets reduced drastically and after six iterations it becomes almost flat as shown in the plot below. The corresponding model parameters are the best fit values.
Minimizing MSE:
Optimized β:
The computed final scores are compared with the final scores from data. Model efficiency is visualized by comparing modeled output with the target output in the data. Coefficient of determination is estimated to be 0.978 to numerically assess the performance of the model. The plot below shows the comparison between model and data where three axes are used to express explanatory variables like Exam1, Exam2, Exam3 and the color scheme is used to show the output variable i.e. the final score.
Comparison between model output and target in the data: | [
{
"code": null,
"e": 893,
"s": 172,
"text": "Linear regression is a form of predictive model which is widely used in many real world applications. Quite a good number of articles published on linear regression are based on single explanatory variable with detail explanation of minimizing mean square... |
Python | Convert a list into a tuple - GeeksforGeeks | 22 Jul, 2019
Given a list, write a Python program to convert the given list into a tuple.
Examples:
Input : [1, 2, 3, 4]
Output : (1, 2, 3, 4)
Input : ['a', 'b', 'c']
Output : ('a', 'b', 'c')
Approach #1 : Using tuple(list_name).
Typecasting to tuple can be done by simply using tuple(list_name).
# Python3 program to convert a # list into a tupledef convert(list): return tuple(list) # Driver functionlist = [1, 2, 3, 4]print(convert(list))
(1, 2, 3, 4)
Approach #2 :A small variation to the above approach is to use a loop inside tuple() .
# Python3 program to convert a # list into a tupledef convert(list): return tuple(i for i in list) # Driver functionlist = [1, 2, 3, 4]print(convert(list))
(1, 2, 3, 4)
Approach #3 : Using (*list, )This essentially unpacks the list l inside a tuple literal which is created due to the presence of the single comma (, ). This approach is a bit faster but suffers from readability.
# Python3 program to convert a # list into a tupledef convert(list): return (*list, ) # Driver functionlist = [1, 2, 3, 4]print(convert(list))
(1, 2, 3, 4)
ManasChhabra2
Python list-programs
Python tuple-programs
python-list
python-tuple
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Defaultdict in Python
Python | Get dictionary keys as a list
Python program to check whether a number is Prime or not
Python | Convert a list to dictionary
How to print without newline in Python? | [
{
"code": null,
"e": 24092,
"s": 24064,
"text": "\n22 Jul, 2019"
},
{
"code": null,
"e": 24169,
"s": 24092,
"text": "Given a list, write a Python program to convert the given list into a tuple."
},
{
"code": null,
"e": 24179,
"s": 24169,
"text": "Examples:"
... |
Application connectivity with Cassandra - GeeksforGeeks | 25 Nov, 2019
In this article we will learn Basic access to Cassandra with code such that how to set up development environment and how to use code to perform CQL statements.
In case of high availability and scalability Cassandra is always the best choice to connect your application with Cassandra database.let’s have a look.
To connect with cassandra there are many Driver available. few are listed below.
Java
Python
Node.js
C#
In programming language to connect application with database there is a programming Pattern.Three Easy steps are following :
Create a connection (which is called a Session)Use the session to execute the query.Be sure to close the connection/session.
Create a connection (which is called a Session)
Use the session to execute the query.
Be sure to close the connection/session.
Let’s understand with example one by one.
In Java programming language to connect application with Cassandra Database using Cloud used the following steps:
Step-1:To create the session used the following Java code.try (DseSession session = DseSession.builder()
.withCloudSecureConnectBundle
("/path/to/secure-connect-database_name.zip")
// Database Credentials
.withAuthCredentials("DBUserName", "DBPassword")
.build()) {
try (DseSession session = DseSession.builder()
.withCloudSecureConnectBundle
("/path/to/secure-connect-database_name.zip")
// Database Credentials
.withAuthCredentials("DBUserName", "DBPassword")
.build()) {
Step-2:To execute the CQL used the following Java code.session.execute(
SimpleStatement.builder("SELECT password
FROM keyspace-name.Table-name
WHERE email = ?")
.addPossitionalValues("name@datastax.com")
.build());
session.execute(
SimpleStatement.builder("SELECT password
FROM keyspace-name.Table-name
WHERE email = ?")
.addPossitionalValues("name@datastax.com")
.build());
Step-3:To close the Session used the following Java code.// Close happens automatically here
// - otherwise use session.close()
session.close()
// Close happens automatically here
// - otherwise use session.close()
session.close()
In Python programming language to connect application with Cassandra Database using Cloud used the following steps:
Step-1:To create the session used the following Python code.cluster = Cluster(
cloud = {'secure_connection_bundle'
: '/path / to / secure-connect-database_name.zip'},
auth_provider = PlainTextAuthProvider('DBUsername', 'DBPassword'))
# Database Credentials
session = cluster.connect()
cluster = Cluster(
cloud = {'secure_connection_bundle'
: '/path / to / secure-connect-database_name.zip'},
auth_provider = PlainTextAuthProvider('DBUsername', 'DBPassword'))
# Database Credentials
session = cluster.connect()
Step-2:To execute the CQL used the following Pyhton code.session.execute(("SELECT password
FROM keyspace-name.Table-name
WHERE email = % s, ('name@datastax.com'))
session.execute(("SELECT password
FROM keyspace-name.Table-name
WHERE email = % s, ('name@datastax.com'))
Step-3:To close the Session used the following Python code.session.shutdown()
session.shutdown()
Apache
DBMS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Trigger | Student Database
CTE in SQL
Introduction of B-Tree
Difference between Clustered and Non-clustered index
SQL Interview Questions
Introduction of ER Model
Data Preprocessing in Data Mining
SQL | GROUP BY
Introduction of DBMS (Database Management System) | Set 1
SQL | Views | [
{
"code": null,
"e": 24294,
"s": 24266,
"text": "\n25 Nov, 2019"
},
{
"code": null,
"e": 24455,
"s": 24294,
"text": "In this article we will learn Basic access to Cassandra with code such that how to set up development environment and how to use code to perform CQL statements."
... |
Compact prediction tree. A Lossless Model for Accurate Sequence... | by Louis Fruleux | Towards Data Science | The sequence prediction problem consists of finding the next element of an ordered sequence by only looking at the sequence’s items.
This problem covers a lot of applications in a variety of domains. It includes applications such as product recommendation, forecasting, and web page prefetching.
A lot of different approaches have been studied for this problem, popular ones include PPM (Prediction by Partial Matching), Markov chains, and more recently LSTM (Long short-term memory).
The Compact Prediction Tree (CPT) is an approach published in 2015 which aims to match the accuracy and outmatches the performances (time to train and predict) of popular algorithms with a lossless compression of the entire training set.We will now enter into detail the methodologies to train, predict and what are the pros and cons of this method.
Before entering into details of how it is used for making a prediction, let’s describe the different elements that compose a Compact Prediction Tree (CPT):
A trie, for efficient storage of sequences.
An inverted index, for constant time retrieving of sequences containing a certain word.
A lookup table, for retrieving the sequence from the sequence Id.
A trie, commonly called Prefix tree, is an ordered tree-based data structure to store sequences (such as strings). The elements of the sequences are stored in the edges, hence every descendent of a given node has the same prefix.
In this well-known example, we would like to store ["tea", "ten", "inn"].We first put “tea” in the empty tree. Each branch of the tree corresponding to a letter. Then we add “ten”: as “tea” and “ten” share the same “te” prefix, we just create a new branch in our tree after the “te” prefix. Finally, we add “inn” in the tree that has no common prefix with the two previous sequences.
Trie is commonly used to fetch, with a tree search every word starting with a prefix. In our case, we use it to compress and efficiently store our training set.
An inverted index is an index used to store a mapping from elements to its location. Here we use it to store a mapping from elements of the sequences to the IDs of the sequences.
Considering again our previous example, we notice that “T” appears in sequence 0 and 1, “E” in sequence 0 and 1, “A” in sequence 0, “N” in sequence 1 and 2, and “I” in sequence 2 only.Hence we have the following inverted index:
{ "T": [0, 1], "E": [0, 1], "A": [0], "N": [1, 2], "I": [2]}
As a matter of efficiency, we will use bitsets to store the inverted index (this also helps in finding “similar sequences” efficiently).
The lookup table is a data structure (usually an array) used to store pointers of the last node (leaf) of each sequence.
This data structure is essential to iterate on the elements of a given sequence.For instance, if we want to retrieve the sequence of id 0, we can simply iterate over its parents. In our example the parent of the leaf of the sequence of id 0 is linked with an “A”, then an “E” and finally a “T”. Which gives us our first sequence backward: “TEA”.
The training time is linear with the number of sequences in the training set.For each training sequence, we need to do 3 steps:
Insert the sequence in the trie.
Add the elements in the inverted index.
Add the location of the last node in the lookup table.
A picture is worth a thousand words, here is a fully trained compact prediction tree step by step.
To predict a sequence S we need to do these 3 steps:
Find similar sequences (sequences containing every element of S).
Compute the consequent sequence of each similar sequences (the subsequence starting after the last item in common with S).
Count occurrences of each element in all the subsequent sequences.
For this part, let’s take a slightly more complex example where our model trains on ["ABC", "ABD", "BC", "BAC"]. We should have an algorithm trained as:
And let’s try to predict what should come after "AB".
First, let’s compute similar sequences.The sequences similar to S are the sequences containing every item of S in any order, any position.To compute similar sequences we could simply use our inverted index and compute the intersections. For our example, we need to intersect [0, 1, 3] (ids of sequences where A appears) and [0, 1, 2, 3] (where B appears). Which gives [0, 1, 3].
Then, we need to compute the consequent sequences.The consequent of a sequence Y with respect to a sequence S is the subsequence of Y starting after the last item in common with S until the end of Y.The consequent sequences for our example should be "C" , "D" and "C" . (For our sequences 0, 1, and 3 with respect to "AB").
Finally, we simply count the number of occurrences of each element that appear in all consequent sequences and predict the letter with the most occurrences.Which is "C" (2 occurrences) in our example.
In a few words, the authors predicted the next element on several public datasets with several algorithms (including CPT, Dependency graphs, Markov like algorithms...).To see the results (to take with caution), I suggest you have a look at the original paper, Compact Prediction Tree: A Lossless Model for Accurate Sequence Prediction.
Another paper, Predicting train journeys from smart card data: a real-world application of the sequence prediction problem, shows the steps to tackle a sequence prediction problem. From the alphabet construction to the choice of the model.In this paper, Dr. Hoekstra compares CPT with different approaches such as PPM and AKOM. And depending on your needs, it also shows CPT can be a relevant solution with relatively good accuracy.
The pros of Compact Prediction Trees are:
CPT is an algorithm to store losslessly all the data from the training set.
The algorithm is highly explainable (easy to trace back the similar sequences, the subsequent sequences...)
Fast prediction. Some benchmarks can be found in the original paper or here.
The cons of Compact Prediction Trees are:
CPT ignores the order within the sequences, hence CPT tends to predict the most frequent item. (If you are ready to have a slower prediction which takes into consideration order. I suggest you check out the subseq algorithm, developed by a common coauthor.)
CPT is quite sensitive to noise. If a new element is in a sequence to predict, CPT won’t be able to find any similar sequence. This has been addressed by CPT+, which you can find details in the “Go further” section.
For this small example, we will use this implementation. It is referenced on the official website of one of the co-authors as an implementation of CPT. It also includes some features of CPT+ such as noise reduction.
from cpt.cpt import Cptmodel = Cpt()# trainingmodel.fit([['hello', 'world'], ['hello', 'this', 'is', 'me'], ['hello', 'me'] ])# predictionsmodel.predict([['hello'], ['hello', 'this']])# Output: ['me', 'is']
For more information about the parameters of the predict method or the hyperparameters, you can check out the documentation.
If you are interested in the subject, I strongly suggest the following papers:
CPT+: Decreasing the time/space complexity of the Compact Prediction Tree This adds a noise reduction technique and two compressions of the training set strategies.
Improving webpage access predictions based on sequence prediction and Pagerank algorithm The idea of this paper is to add a Pagerank algorithm to train CPT only on relevant sequences. There is a good improvement overall.
Succinct BWT-Based Sequence Prediction (subseq) An algorithm developed by one of the co-authors of CPT. This algorithm takes more time to predict, takes more space to store the entire training set but gives more importance to the order of the sequences. You can have a look at this implementation.
Special thanks to Joseph Rocca for all the help.Thanks to my friends who also proofread this article. | [
{
"code": null,
"e": 305,
"s": 172,
"text": "The sequence prediction problem consists of finding the next element of an ordered sequence by only looking at the sequence’s items."
},
{
"code": null,
"e": 468,
"s": 305,
"text": "This problem covers a lot of applications in a variet... |
Portfolio Optimization With SciPy | by Tony Yiu | Towards Data Science | Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details.
Not intended to be investment advice. You can find my code on my GitHub here.
Time for another article on portfolio optimization since I’ve been doing a lot of work around it lately. In case you need a refresher, here are my previous writings on the topic:
towardsdatascience.com
towardsdatascience.com
As fun as it is to optimize a portfolio with just matrix algebra and NumPy, sometimes we need to add constraints. For example, many investors don’t want to or are not allowed to short investments. We can’t guarantee that the optimal portfolio produced using matrix algebra won’t include short positions (negative weights). So instead, we turn to optimization.
In case you didn’t read my previous articles on optimization, optimization refers to the process of solving for the combination of assets that maximizes return for a given amount of risk (or minimizes risk for a specified level of return). The desired output from an optimization is a set of portfolio weights (for each asset) that would produce the optimal portfolio.
The two key inputs to a portfolio optimization are:
Expected returns for each asset being considered.The covariance matrix of asset returns. Embedded in this are information on cross-asset correlations and each asset’s volatility (the diagonals).
Expected returns for each asset being considered.
The covariance matrix of asset returns. Embedded in this are information on cross-asset correlations and each asset’s volatility (the diagonals).
Expected returns are hard to estimate — some people like to use historical averages (dangerous as the past is often not representative of the future), others have their own methodology for estimating return forecasts. I am planning a whole post on this so I won’t go into the details this time. Today we will focus on the optimization process itself. Thus, we will pretend like we got expected return estimates from a consultant. By the way, these were very roughly estimated by me, so they should definitely not be taken as investment advice.
So as you can see from the plot above, we have a portfolio of eight investments ranging from stocks and bonds to commodities. For those unfamiliar with the abbreviation, TIPS are Treasury Inflation Protected Securities — in other words, Treasury bonds with no inflation risk.
Here are the correlations estimated using the past 10 years of returns. The lower the better, so the bluer shaded cells represent potential opportunities for diversification. Technically, the optimization needs the covariance matrix, but the correlation matrix is much more informative to look at.
Now that we have our inputs, let’s get to the code.
I used the same data set as I did in my previous optimization post, except that there are now eight assets instead of four. The labels of each asset are:
factors = ['S&P 500','Emerging Markets','Small Cap', 'Treasury Bonds', 'High Yield','TIPS','Gold','Oil']
I store the daily returns in a Pandas dataframe called factor_returns. Calculating the covariance matrix of our assets is as simple as:
cov = factor_returns.cov()
As I mentioned above, we will use a return forecast that I created (the returns are specified in the same order as they are listed in factors):
expected_returns = np.array([[ 0.080], [ 0.092], [ 0.092], [-0.017], [ 0.034], [ 0.001], [ 0.010], [ 0.079]])
Now let’s import the Python libraries that we need for optimization:
from scipy.optimize import minimize, Bounds, LinearConstraint
I’m going to explain things slightly out of order of how they are actually coded because it’s easier to understand this way. The next block of code shows a function called optimize that runs an optimization using SciPy’s minimize function.
Look at where minimize is called (I bolded it). The first argument func is the function that we want to minimize. The second argument W is the input that the optimizer is allowed to vary — W is what we are solving for and corresponds to the weights of the assets in our portfolio. We need to start it off with a guess — without any strong priors, I just equal weight each asset.
The exp_ret (expected return) and cov (covariance) variables in the args argument are provided inputs that the optimizer is not allowed to vary.
So what the optimizer does is it searches for the vector of portfolio weights (W) that minimize func given our supplied expected returns and covariance matrix.
At the end of the function, you will see that I return optimal_weights[‘x’]. That’s because in the optimizer object we get back from mimimize, ‘x’ pertains to the optimized weights, W.
W = np.ones((factor_moments.shape[0],1))*(1.0/factor_moments.shape[0])# Function that runs optimizerdef optimize(func, W, exp_ret, cov, target_return): opt_bounds = Bounds(0, 1) opt_constraints = ({'type': 'eq', 'fun': lambda W: 1.0 - np.sum(W)}, {'type': 'eq', 'fun': lambda W: target_return - W.T@exp_ret}) optimal_weights = minimize(func, W, args=(exp_ret, cov), method='SLSQP', bounds=opt_bounds, constraints=opt_constraints) return optimal_weights['x']
You might notice that minimize also can take two optional arguments — bounds and constraints. These are important so let’s go over them one by one. Bounds is pretty straightforward. We want each of our weights in W to be between 0 and 1, in other words no negative weights or leverage:
opt_bounds = Bounds(0, 1)
For constraints, we have two — we want our weights to sum to 1 (in order for it to be a proper portfolio) and we want to achieve a pre-specified target return (you can set this as a target risk as well or leave it out to altogether). The reason we have a return target is to avoid the case where we optimize and obtain a sweet and diversified portfolio, but the expected return of that portfolio is 3% or some other value that’s too low.
opt_constraints = ({'type': 'eq', 'fun': lambda W: 1.0 - np.sum(W)}, {'type': 'eq', 'fun': lambda W: target_return - W.T@exp_ret})
Now let’s take a look at the part of the code I skipped over earlier. First, what is func? Well, when we solve for the optimal portfolio, we are trying to find the portfolio that gives us the most return per unit of risk (where risk is the portfolio’s standard deviation).
So we want to maximize the ratio of return, which we can calculate as W.T@exp_ret (this multiplies each asset’s return by its weight and sums them), and risk, which we can calculate as W.T@cov@W. The @ character denotes matrix multiplication.
Since we are using an optimizer function that minimizes things, we need to slap a negative sign on our return to risk ratio — that way when we minimize it, we are actually maximizing it.
# Function to optimizedef ret_risk(W, exp_ret, cov): return -((W.T@exp_ret) / (W.T@cov@W)**0.5)
Now all that’s left to do is to optimize our portfolio:
x = optimize(ret_risk, W, expected_returns, cov, target_return=0.055)
Here’s what the optimal weights look like:
A few things that jump out in terms of weights:
Small cap and Emerging Markets have the highest expected returns but are not highly weighted. That’s because their volatility, a.k.a. risk, is significantly higher than that of the S&P 500 (see bar chart below). Also they are highly correlated to the S&P 500 and thus offer very little diversification.
Treasury bonds have a negative expected return and yet are the second highest weighted asset class. That’s because it’s also the least correlated asset class to stocks (negative correlation of approximately -0.40). So in effect, the portfolio relies on stocks and high yield bonds for return and Treasury bonds for insurance when stock markets crash.
Oil despite its relatively high return and low correlation to the other assets is just too volatile, hence its low weighting.
And that’s it for optimization with SciPy. The next step in the portfolio strategy process would be to do our best to measure the impact of model and estimation error. Namely, we want to know which inputs are likely to be mis-specified (measurement error) and how sensitive our model outputs are to such errors. Hint: expected returns are very noisy and the outputs of the optimization are highly sensitive to even small changes in expected returns. Next time, we will see how we can get around this issue. Cheers!
If you liked this article and my writing in general, please consider supporting my writing by signing up for Medium via my referral link here. Thanks! | [
{
"code": null,
"e": 472,
"s": 172,
"text": "Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking profession... |
Object-Oriented Programming in GoLang - GeeksforGeeks | 22 Jun, 2020
Object-oriented programming is a programming paradigm which uses the idea of “objects” to represent data and methods. Go does not strictly support object orientation but is a lightweight object Oriented language. Object Oriented Programming in Golang is different from that in other languages like C++ or Java due to factors mentioned below:
Go does not support custom types through classes but structs. Structs in Golang are user-defined types that hold just the state and not the behavior. Structs can be used to represent a complex object comprising more than one key-value pairs. We can add functions to the struct that can add behavior to it as shown below:
Example:
// Golang program to illustrate the// concept of custom typespackage main import ( "fmt") // declaring a structtype Book struct{ // defining struct variables name string author string pages int} // function to print book detailsfunc (book Book) print_details(){ fmt.Printf("Book %s was written by %s.", book.name, book.author) fmt.Printf("\nIt contains %d pages.\n", book.pages)} // main functionfunc main() { // declaring a struct instance book1 := Book{"Monster Blood", "R.L.Stine", 131} // printing details of book1 book1.print_details() // modifying book1 details book1.name = "Vampire Breath" book1.pages = 162 // printing modified book1 book1.print_details() }
Output:
Book Monster Blood was written by R.L.Stine.
It contains 131 pages.
Book Vampire Breath was written by R.L.Stine.
It contains 162 pages.
It means hiding sensitive data from users. In Go, encapsulation is implemented by capitalizing fields, methods, and functions which makes them public. When the structs, fields, or functions are made public, they are exported on a package level. Some examples of public and private members are:
package gfg
// this function is public as
// it begins with a capital letter
func Print_this(){
// implementation
}
// public struct
type Book struct{
// public field
Name string
// private field, only
// available in gfg package
author string
}
When a class acquires the properties of its superclass then we can say it is inheritance. Here, subclass/child class are the terms used for the class which acquire properties. For this one, one must use a struct to achieve inheritance in Golang. Here, users have to compose using structs to form the other objects.
Interfaces are types that have multiple methods. Objects that implement all the methods of the interface automatically implement the interface, i.e., interfaces are satisfied implicitly. By treating objects of different types in a consistent way, as long as they stick to one interface, Golang implements polymorphism.
Example:
// Golang program to illustrate the// concept of interfacespackage main import ( "fmt") // defining an interfacetype Sport interface{ // name of sport method sportName() string} // declaring a structtype Human struct{ // defining struct variables name string sport string} // function to print book detailsfunc (h Human) sportName() string{ // returning a string value return h.name + " plays " + h.sport + "."} // main functionfunc main() { // declaring a struct instance human1 := Human{"Rahul", "chess"} // printing details of human1 fmt.Println(human1.sportName()) // declaring another struct instance human2 := Human{"Riya", "carrom"} // printing details of human2 fmt.Println(human2.sportName())}
Output:
Rahul plays chess.
Riya plays carrom.
Golang-OOPs
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Parse JSON in Golang?
Defer Keyword in Golang
time.Parse() Function in Golang With Examples
Anonymous function in Go Language
Time Durations in Golang
Structures in Golang
Strings in Golang
Class and Object in Golang
How to convert a string in uppercase in Golang?
Rune in Golang | [
{
"code": null,
"e": 24460,
"s": 24432,
"text": "\n22 Jun, 2020"
},
{
"code": null,
"e": 24802,
"s": 24460,
"text": "Object-oriented programming is a programming paradigm which uses the idea of “objects” to represent data and methods. Go does not strictly support object orientati... |
p5.js | curve() function | 17 Jan, 2020
The curve() function is used to draws a curved line between two points given in the middle four parameters on the screen. The first two and last two parameters are used as a control point.
Syntax:
curve( x1, y1, x2, y2, x3, y3, x4, y4 )
or
curve( x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4 )
Parameters:
Below examples illustrate the curve() function in CSS:
function setup() { // Create canvas of given size createCanvas(500, 300); // Set the background of canvas background('green'); } function draw() { // Use noFill() function to not fill the color noFill(); // Set the stroke color stroke('white'); // Use curve() function to create curve curve(50, 50, 400, 50, 50, 250, 50, 50); // Set the stroke color stroke('blue'); // Use curve() function to create curve curve(400, 50, 50, 250, 50, 50, 50, 50); }
Output:
function setup() { // Create canvas of given size createCanvas(500, 300); // Set the background of canvas background('green'); } function draw() { // Use noFill() function to not fill the color noFill(); // Set the stroke color stroke('white'); // Use curve() function to create curve curve(50, 50, 50, 200, 50, 10, 50, 250, 150, 50, 50, 50); // Set the stroke color stroke('blue'); // Use curve() function to create curve curve(50, 200, 450, 50, 250, 100, 350, 250, 250, 450, 450, 400); }
Output:
Online editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Jan, 2020"
},
{
"code": null,
"e": 217,
"s": 28,
"text": "The curve() function is used to draws a curved line between two points given in the middle four parameters on the screen. The first two and last two parameters are used as a c... |
How to access nested object in ReactJS ? | 21 May, 2021
The structure of an object in ReactJS can be nested many times and can get complicated quickly. If we want to access all the values of nested objects then we have to use recursion to access each and every level of that object.
Example of a Nested object:
var person = {
"name":"Kapil",
"age":27,
"vehicles": {
"car":"city 100",
"bike":"ktm-duke",
"plane":"lufthansa"
}
}
And it can get more complicated according to the nesting of the object. That why we have to use recursion to get all the values and access the whole nested object.
Creating React Application:
Step 1: Create a React application using the following command:npx create-react-app foldername
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 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Project Structure: It will look like the following.
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from 'react'; class App extends React.Component { constructor(props) { super(props); this.state = { person: { name: { first: "Kapil", last: "Chhipa" }, age: 23, key1: { key2: { key3: { val: "Welcome to GeeksforGeeks" } } } } }; } helper = (obj) => { const values = Object.values(obj) values.forEach(val => val && typeof val === "object" ? this.helper(val) : this.addtoConsole(val)) } addtoConsole = (val) => { console.log(val) } render() { return ( <div> <button onClick={() => { this.helper(this.state.person) }}>click here</button> </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:
Picked
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 May, 2021"
},
{
"code": null,
"e": 255,
"s": 28,
"text": "The structure of an object in ReactJS can be nested many times and can get complicated quickly. If we want to access all the values of nested objects then we have to use recur... |
ISRO | ISRO CS 2008 | Question 7 | 11 Jun, 2018
Consider the grammar
S → ABCc ∣ bc
BA → AB
Bb → bb
Ab → ab
Aa → aa
Which of the following sentences can be derived by this grammar?(A) abc(B) aab(C) abcc(D) abbcAnswer: (A)Explanation:Quiz of this Question
ISRO
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ISRO | ISRO CS 2018 | Question 74
ISRO | ISRO CS 2013 | Question 21
ISRO | ISRO CS 2018 | Question 44
ISRO | ISRO CS 2011 | Question 56
ISRO | ISRO CS 2014 | Question 64
ISRO | ISRO CS 2007 | Question 16
ISRO | ISRO CS 2009 | Question 30
ISRO | ISRO CS 2017 - May | Question 14
ISRO | ISRO CS 2018 | Question 79
ISRO | ISRO CS 2013 | Question 54 | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Jun, 2018"
},
{
"code": null,
"e": 49,
"s": 28,
"text": "Consider the grammar"
},
{
"code": null,
"e": 95,
"s": 49,
"text": "S → ABCc ∣ bc\nBA → AB\nBb → bb\nAb → ab\nAa → aa"
},
{
"code": null,
"e": 2... |
Static Variables in C | 19 Jul, 2021
Static variables have a property of preserving their value even after they are out of their scope! Hence, static variables preserve their previous value in their previous scope and are not initialized again in the new scope. Syntax:
static data_type var_name = var_value;
Following are some interesting facts about static variables in C.1) A static int variable remains in memory while the program is running. A normal or auto variable is destroyed when a function call where the variable was declared is over. For example, we can use static int to count a number of times a function is called, but an auto variable can’t be used for this purpose.For example below program prints “1 2”
C
#include<stdio.h>int fun(){ static int count = 0; count++; return count;} int main(){ printf("%d ", fun()); printf("%d ", fun()); return 0;}
Output:
1 2
But below program prints 1 1
C
#include<stdio.h>int fun(){ int count = 0; count++; return count;} int main(){ printf("%d ", fun()); printf("%d ", fun()); return 0;}
Output:
1 1
2) Static variables are allocated memory in data segment, not stack segment. See memory layout of C programs for details.3) Static variables (like global variables) are initialized as 0 if not initialized explicitly. For example in the below program, value of x is printed as 0, while value of y is something garbage. See this for more details.
C
#include <stdio.h>int main(){ static int x; int y; printf("%d \n %d", x, y);}
Output:
0
[some_garbage_value]
4) In C, static variables can only be initialized using constant literals. For example, following program fails in compilation. See this for more details.
C
#include<stdio.h>int initializer(void){ return 50;} int main(){ static int i = initializer(); printf(" value of i = %d", i); getchar(); return 0;}
Output
In function 'main':
9:5: error: initializer element is not constant
static int i = initializer();
^
Please note that this condition doesn’t hold in C++. So if you save the program as a C++ program, it would compile and run fine. 5) Static global variables and functions are also possible in C/C++. The purpose of these is to limit scope of a variable or function to a file. Please refer Static functions in C for more details.6) Static variables should not be declared inside structure. The reason is C compiler requires the entire structure elements to be placed together (i.e.) memory allocation for structure members should be contiguous. It is possible to declare structure inside the function (stack segment) or allocate memory dynamically(heap segment) or it can be even global (BSS or data segment). Whatever might be the case, all structure members should reside in the same memory segment because the value for the structure element is fetched by counting the offset of the element from the beginning address of the structure. Separating out one member alone to data segment defeats the purpose of static variable and it is possible to have an entire structure as static.Related Articles:
Static Keyword in C++
Quiz on Static Keyword
Static data members in C++
When are static objects destroyed?
Interesting facts about static member functions
Can static functions be virtual?
Comparison of static keyword in C++ and Java
Static functions in C
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
DibyajyotiMohapatra
kani_26
rohitsharmaofficial42019
C Basics
C-Storage Classes and Type Qualifiers
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n19 Jul, 2021"
},
{
"code": null,
"e": 286,
"s": 52,
"text": "Static variables have a property of preserving their value even after they are out of their scope! Hence, static variables preserve their previous value in their previous sco... |
Java Swing | Creating Custom Message Dialogs | 24 Jun, 2021
Though Java Swing provides built-in message dialog to display messages, we can create custom message dialog by using JWindow and other Java Swing elements. The advantage of creating them is that they are highly customizable and we can add the desired look-and-feel and functionalities to them.In this article we will see how to create custom message in Java Swing .Examples:
First we create a simple JWindow and add label and button to it.
Output:
Then we will shape the window and background color to it.
Output:
Then will set the look and feel of the label and
button to System look and feel and then add glossy
appearance to the window by applying per pixel
translucency.
Output:
In the following programs we will see how to create a message dialog.1.Program to create a simple JWindow and add label and button to it.
Java
// Java Program to create a simple JWindow// and add label and button to it.import java.awt.*;import javax.swing.*;import java.awt.event.*;class message implements ActionListener { // window JWindow w; // constructor message() { // create a window w = new JWindow(); // create a label JLabel l = new JLabel("This is a message dialog"); // create a new button JButton b = new JButton("OK"); // add action listener b.addActionListener(this); // create a panel JPanel p = new JPanel(); // add contents to panel p.add(l); p.add(b); w.add(p); w.setSize(200, 100); w.setLocation(300, 300); w.show(); } // if button is pressed public void actionPerformed(ActionEvent evt) { w.setVisible(false); } // main class public static void main(String args[]) { // create aobject message m = new message(); }}
output:
2.Program to create a message window, shape the window and background color to it.
Java
// Java Program to create a message window,// and shape the window and add background color to itimport java.awt.*;import javax.swing.*;import java.awt.event.*;class message1 implements ActionListener { // window JWindow w; // constructor message1() { // create a window w = new JWindow(); // set background of window transparent w.setBackground(new Color(0, 0, 0, 0)); // create a label JLabel l = new JLabel("This is a message dialog"); // create a new button JButton b = new JButton("OK"); // add action listener b.addActionListener(this); try { // set windows look and feel UIManager.setLookAndFeel(UIManager. getSystemLookAndFeelClassName()); } catch (Exception e) { } // create a panel JPanel p = new JPanel() { public void paintComponent(Graphics g) { g.setColor(new Color(100, 100, 240)); g.fillRoundRect(0, 0, 200, 100, 20, 20); g.setColor(new Color(10, 10, 255)); g.drawRoundRect(0, 0, 200, 100, 20, 20); } }; // create a font Font f = new Font("BOLD", 1, 14); l.setFont(f); // add contents to panel p.add(l); p.add(b); w.add(p); w.setSize(200, 100); w.setLocation(300, 300); w.show(); } // if button is pressed public void actionPerformed(ActionEvent evt) { w.setVisible(false); } // main class public static void main(String args[]) { // create aobject message1 m = new message1(); }}
output:
3. Program to create a message window, shape the window, add background color to it and also add glossy appearance to the window by applying per pixel translucency
Java
// Java Program to create a message window, shape the window// add background color to it and also add// glossy appearance to the window by applying per pixel translucencyimport java.awt.*;import javax.swing.*;import java.awt.event.*;class message2 implements ActionListener { // window JWindow w; // constructor message2() { // create a window w = new JWindow(); // set background of window transparent w.setBackground(new Color(0, 0, 0, 0)); // create a label JLabel l = new JLabel("This is a message dialog"); // create a new button JButton b = new JButton("OK"); // add action listener b.addActionListener(this); try { // set windows look and feel UIManager.setLookAndFeel(UIManager .getSystemLookAndFeelClassName()); } catch (Exception e) { } // create a panel JPanel p = new JPanel() { public void paintComponent(Graphics g) { g.setColor(new Color(100, 100, 240)); g.fillRoundRect(0, 0, 200, 100, 20, 20); g.setColor(new Color(10, 10, 255)); g.drawRoundRect(0, 0, 200, 100, 20, 20); // create a glossy appearance for (int i = 0; i < 100; i++) { g.setColor(new Color(255, 255, 255, i)); g.drawLine(0, i, 200, i); } } }; // create a font Font f = new Font("BOLD", 1, 14); l.setFont(f); // add contents to panel p.add(l); p.add(b); w.add(p); w.setSize(200, 100); w.setLocation(300, 300); w.show(); } // if button is pressed public void actionPerformed(ActionEvent evt) { w.setVisible(false); } // main class public static void main(String args[]) { // create aobject message2 m = new message2(); }}
Output :
Note : The following program might not run in an online compiler please use an offline IDE.
clintra
java-swing
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Jun, 2021"
},
{
"code": null,
"e": 405,
"s": 28,
"text": "Though Java Swing provides built-in message dialog to display messages, we can create custom message dialog by using JWindow and other Java Swing elements. The advantage of cr... |
What is the first class function in JavaScript ? | 19 Sep, 2021
First-Class Function: A programming language is said to have First-class functions if functions in that language are treated like other variables. So the functions can be assigned to any other variable or passed as an argument or can be returned by another function. JavaScript treat function as a first-class-citizens. This means that functions are simply a value and are just another type of object.
Example: Let us take an example to understand more about the first-class function.
Javascript
<script> const Arithmetics = { add: (a, b) => { return `${a} + ${b} = ${a + b}`; }, subtract: (a, b) => { return `${a} - ${b} = ${a - b}` }, multiply: (a, b) => { return `${a} * ${b} = ${a * b}` }, division: (a, b) => { if (b != 0) return `${a} / ${b} = ${a / b}`; return `Cannot Divide by Zero!!!`; } } document.write(Arithmetics.add(100, 100) + "<br>"); document.write(Arithmetics.subtract(100, 7) + "<br>"); document.write(Arithmetics.multiply(5, 5) + "<br>"); document.write(Arithmetics.division(100, 5));</script>
Note: In the above example, functions are stored as a variable in an object.
Output:
100 + 100 = 200
100 - 7 = 93
5 * 5 = 25
100 / 5 = 20
Example 2:
Javascript
<script> const Geek = (a, b) => { return (a + " " + b); } document.write(Geek("Akshit", "Saxena"));</script>
Output:
Akshit Saxena
Blogathon-2021
javascript-basics
JavaScript-Questions
Picked
Blogathon
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Import JSON Data into SQL Server?
SQL Query to Convert Datetime to Date
Scrape LinkedIn Using Selenium And Beautiful Soup in Python
Python program to convert XML to Dictionary
Modes of DMA Transfer
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Hide or show elements in HTML using display property | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Sep, 2021"
},
{
"code": null,
"e": 430,
"s": 28,
"text": "First-Class Function: A programming language is said to have First-class functions if functions in that language are treated like other variables. So the functions can be assi... |
How to get a File Extension in PHP ? | 21 Jul, 2021
In this article, we will learn how to get the current file extensions in PHP.
Input : c:/xampp/htdocs/project/home
Output : ""
Input : c:/xampp/htdocs/project/index.php
Output : ".php"
Input : c:/xampp/htdocs/project/style.min.css
Output : ".css"
Using $_SERVER[‘SCRIPT_NAME’]:
$_SERVER is an array of stored information such as headers, paths, and script locations. These entries are created by the webserver. There is no other way that every web server will provide any of this information.
Syntax:
$_SERVER[‘SCRIPT_NAME’]
‘SCRIPT_NAME’ gives the path from the root to include the name of the directory.
Method 1: The following method uses the strpos() and substr() methods to print the values of the last occurrences.
PHP
<?phpfunction fileExtension($s) { // strrpos() function returns the position // of the last occurrence of a string inside // another string. $n = strrpos($s,"."); // The substr() function returns a part of a string. if($n===false) return ""; else return substr($s,$n+1);} // To Get the Current Filename.$currentPage= $_SERVER['SCRIPT_NAME']; //Function Callecho fileExtension($currentPage);?>
php
Method 2: The following method uses a predefined function pathinfo(). In the output, the “Name:” shows the name of the file and “Extension:” shows the file extension.
PHP code:
PHP
<?php // To Get the Current Filename.$path= $_SERVER['SCRIPT_NAME']; // path info function is used to get info// of The File Directory // PATHINFO_FILENAME parameter in// pathinfo() gives File Name$name = pathinfo($path, PATHINFO_FILENAME); // PATHINFO_EXTENSION parameter in pathinfo()// gives File Extension$ext = pathinfo($path, PATHINFO_EXTENSION); echo " Name: ", $name;echo "\n Extension: ", $ext; ?>
Name: 001510d47316b41e63f337e33f4aaea4
Extension: php
Method 3: The following code uses the predefined function parse_url() and pathinfo() for URLs.
PHP code:
PHP
<?php // This is sample url $url ="http://www.xyz.com/dir/file.index.php?Something+is+wrong=hello"; // Here parse_url is used to return the // components of a URL $url = parse_url($url); // path info function is used to get info // of The File Directory // PATHINFO_FILENAME parameter in pathinfo() // gives File Name $name = pathinfo($url['path'], PATHINFO_FILENAME); // PATHINFO_EXTENSION parameter in pathinfo() // gives File Extension $ext = pathinfo($url['path'], PATHINFO_EXTENSION); echo " Name: ", $name; echo "\n Extension: ", $ext;?>
Name: file.index
Extension: php
manikarora059
PHP-function
PHP-Questions
Picked
PHP
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": "\n21 Jul, 2021"
},
{
"code": null,
"e": 106,
"s": 28,
"text": "In this article, we will learn how to get the current file extensions in PHP."
},
{
"code": null,
"e": 280,
"s": 106,
"text": "Input : c:/xampp/htdocs/pro... |
Java Program For Finding Subarray With Given Sum – Set 1 (Nonnegative Numbers) | 21 Dec, 2021
Given an unsorted array of nonnegative integers, find a continuous subarray which adds to a given number. Examples :
Input: arr[] = {1, 4, 20, 3, 10, 5}, sum = 33
Output: Sum found between indexes 2 and 4
Sum of elements between indices
2 and 4 is 20 + 3 + 10 = 33
Input: arr[] = {1, 4, 0, 0, 3, 10, 5}, sum = 7
Output: Sum found between indexes 1 and 4
Sum of elements between indices
1 and 4 is 4 + 0 + 0 + 3 = 7
Input: arr[] = {1, 4}, sum = 0
Output: No subarray found
There is no subarray with 0 sum
There may be more than one subarrays with sum as the given sum. The following solutions print first such subarray.
Simple Approach: A simple solution is to consider all subarrays one by one and check the sum of every subarray. Following program implements the simple solution. Run two loops: the outer loop picks a starting point I and the inner loop tries all subarrays starting from i.Algorithm:
Traverse the array from start to end.From every index start another loop from i to the end of array to get all subarray starting from i, keep a variable sum to calculate the sum.For every index in inner loop update sum = sum + array[j]If the sum is equal to the given sum then print the subarray.
Traverse the array from start to end.
From every index start another loop from i to the end of array to get all subarray starting from i, keep a variable sum to calculate the sum.
For every index in inner loop update sum = sum + array[j]
If the sum is equal to the given sum then print the subarray.
Java
// Java program to implement// the above approachclass SubarraySum { /* Returns true if the there is a subarray of arr[] with a sum equal to 'sum' otherwise returns false. Also, prints the result */ int subArraySum(int arr[], int n, int sum) { int curr_sum, i, j; // Pick a starting point for (i = 0; i < n; i++) { curr_sum = arr[i]; // Try all subarrays starting with 'i' for (j = i + 1; j <= n; j++) { if (curr_sum == sum) { int p = j - 1; System.out.println( "Sum found between indexes " + i + " and " + p); return 1; } if (curr_sum > sum || j == n) break; curr_sum = curr_sum + arr[j]; } } System.out.println("No subarray found"); return 0; } // Driver code public static void main(String[] args) { SubarraySum arraysum = new SubarraySum(); int arr[] = {15, 2, 4, 8, 9, 5, 10, 23 }; int n = arr.length; int sum = 23; arraysum.subArraySum(arr, n, sum); }}// This code is contributed by Mayank Jaiswal(mayank_24)
Output :
Sum found between indexes 1 and 4
Complexity Analysis:
Time Complexity: O(n^2) in worst case. Nested loop is used to traverse the array so the time complexity is O(n^2)
Space Complexity: O(1). As constant extra space is required.
Efficient Approach: There is an idea if all the elements of the array are positive. If a subarray has sum greater than the given sum then there is no possibility that adding elements to the current subarray the sum will be x (given sum). Idea is to use a similar approach to a sliding window. Start with an empty subarray, add elements to the subarray until the sum is less than x. If the sum is greater than x, remove elements from the start of the current subarray.Algorithm:
Create three variables, l=0, sum = 0Traverse the array from start to end.Update the variable sum by adding current element, sum = sum + array[i]If the sum is greater than the given sum, update the variable sum as sum = sum – array[l], and update l as, l++.If the sum is equal to given sum, print the subarray and break the loop.
Create three variables, l=0, sum = 0
Traverse the array from start to end.
Update the variable sum by adding current element, sum = sum + array[i]
If the sum is greater than the given sum, update the variable sum as sum = sum – array[l], and update l as, l++.
If the sum is equal to given sum, print the subarray and break the loop.
Java
// Java program to implement// the above approachclass SubarraySum { /* Returns true if the there is a subarray of arr[] with sum equal to 'sum' otherwise returns false. Also, prints the result */ int subArraySum(int arr[], int n, int sum) { int curr_sum = arr[0], start = 0, i; // Pick a starting point for (i = 1; i <= n; i++) { // If curr_sum exceeds the sum, // then remove the starting elements while (curr_sum > sum && start < i - 1) { curr_sum = curr_sum - arr[start]; start++; } // If curr_sum becomes equal to sum, // then return true if (curr_sum == sum) { int p = i - 1; System.out.println( "Sum found between indexes " + start + " and " + p); return 1; } // Add this element to curr_sum if (i < n) curr_sum = curr_sum + arr[i]; } System.out.println("No subarray found"); return 0; } // Driver code public static void main(String[] args) { SubarraySum arraysum = new SubarraySum(); int arr[] = {15, 2, 4, 8, 9, 5, 10, 23}; int n = arr.length; int sum = 23; arraysum.subArraySum(arr, n, sum); }}// This code is contributed by Mayank Jaiswal(mayank_24)
Output :
Sum found between indexes 1 and 4
Complexity Analysis:
Time Complexity : O(n). Only one traversal of the array is required. So the time complexity is O(n).
Space Complexity: O(1). As constant extra space is required.
Please refer complete article on Find subarray with given sum | Set 1 (Nonnegative Numbers) for more details!
Amazon
Facebook
FactSet
Google
Morgan Stanley
sliding-window
subarray
subarray-sum
Visa
Zoho
Arrays
Java Programs
Zoho
Morgan Stanley
Amazon
FactSet
Visa
Google
Facebook
sliding-window
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n21 Dec, 2021"
},
{
"code": null,
"e": 172,
"s": 54,
"text": "Given an unsorted array of nonnegative integers, find a continuous subarray which adds to a given number. Examples : "
},
{
"code": null,
"e": 561,
"s": 172,
... |
Python program to add two binary numbers | 01 Jun, 2022
Given two binary numbers, write a Python program to compute their sum.
Examples:
Input: a = "11", b = "1"
Output: "100"
Input: a = "1101", b = "100"
Output: 10001
Approach:
Naive Approach: The idea is to start from the last characters of two strings and compute digit sum one by one. If the sum becomes more than 1, then store carry for the next digits.
Using inbuilt function: Calculate the result by using the inbuilt bin() and int() function.
Method 1: Naive Approach:
The idea is to start from the last characters of two strings and compute digit sum one by one. If the sum becomes more than 1, then store carry for the next digits.
Python3
# Python program to add two binary numbers. # Driver code# Declaring the variablesa = "1101"b = "100"max_len = max(len(a), len(b))a = a.zfill(max_len)b = b.zfill(max_len) # Initialize the resultresult = '' # Initialize the carrycarry = 0 # Traverse the stringfor i in range(max_len - 1, -1, -1): r = carry r += 1 if a[i] == '1' else 0 r += 1 if b[i] == '1' else 0 result = ('1' if r % 2 == 1 else '0') + result # Compute the carry. carry = 0 if r < 2 else 1 if carry != 0: result = '1' + result print(result.zfill(max_len))
10001
Output:
10001
Method 2: Using inbuilt functions:
We will first convert the binary string to a decimal using int() function in python. The int() function in Python and Python3 converts a number in the given base to decimal. Then we will add it and then again convert it into a binary number using bin() function.
Example 1:
Python3
# Python program to add two binary numbers. # Driver code# Declaring the variablesa = "1101"b = "100" # Calculating binary value using functionsum = bin(int(a, 2) + int(b, 2)) # Printing resultprint(sum[2:])
10001
Example 2:
Python3
# Python program to add two binary numbers. # Driver codeif __name__ == "__main__" : # Declaring the variables a = "1101" b = "100" # Calculating binary sum by using bin() and int() binary_sum = lambda a,b : bin(int(a, 2) + int(b, 2)) # calling binary_sum lambda function print(binary_sum(a,b)[2:]) # This code is contributed by AnkThon
10001
ankthon
school-programming
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n01 Jun, 2022"
},
{
"code": null,
"e": 123,
"s": 52,
"text": "Given two binary numbers, write a Python program to compute their sum."
},
{
"code": null,
"e": 133,
"s": 123,
"text": "Examples:"
},
{
"code": nu... |
How to change the text color of Menu item in Android? | This example demonstrates how do I change the text color of the menu item in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16sp"
tools:context=".MainActivity">
</RelativeLayout>
Step 3 – Right-click on res/drawable, create any Vector Asset (Example: ic_icon.xml)
Step 4 – Right-click on res, select New -> Android Resource Directory – menu.
Step 5 – Right Click on res/menu and create a new Menu Resource file and add the following code in res/menu/sample_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="@+id/item1"
android:icon="@drawable/ic_icon"
android:title="Item 1"
app:showAsAction="ifRoom"/>
<item android:id="@+id/item2"
android:title="Item 2"
app:showAsAction="never"/>
<item android:id="@+id/item3"
android:title="Item 3"
app:showAsAction="never"/>
<item android:id="@+id/item4"
android:title="Item 5"
app:showAsAction="never"/>
<item android:id="@+id/item5"
android:title="Item 5"
app:showAsAction="never"/>
</menu>
Step 6 – To change text color of the menu item, open res/values/styles.xml and add the following code
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="android:textColor">#ff000f</item>
</style>
</resources>
Step 7 − Add the following code to src/MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.sample_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case R.id.item1:
Toast.makeText(this, "Item 1 is selected", Toast.LENGTH_SHORT).show();
return true;
case R.id.item2:
Toast.makeText(this, "Item 2 is selected", Toast.LENGTH_SHORT).show();
return true;
case R.id.item3:
Toast.makeText(this, "Item 3 is selected", Toast.LENGTH_SHORT).show();
return true;
case R.id.item4:
Toast.makeText(this, "Item 4 is selected is selected", Toast.LENGTH_SHORT).show();
return true;
case R.id.item5:
Toast.makeText(this, "Item 5 is selected", Toast.LENGTH_SHORT).show();
return true;
default: return super.onOptionsItemSelected(item);
}
}
}
Step 8 - Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run Icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – | [
{
"code": null,
"e": 1148,
"s": 1062,
"text": "This example demonstrates how do I change the text color of the menu item in android."
},
{
"code": null,
"e": 1277,
"s": 1148,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required ... |
Real time face recognition with CPU | by Yirui Feng | Towards Data Science | Both the academic and industrial fields are putting in tremendous efforts to develop face recognition algorithms and models that are both, fast and accurate. Thanks to these efforts, it is now possible to accomplish accurate, real-time face recognition for multiple faces with CPU.
In this article, we will compose a real-time face recognition system with the Ultra-light face detector by Linzaer and MobileFaceNet1.
In order to recognize a face, we would first need to detect a face from an image. There are many ways to do so.
I have explored multiple face detectors. These include Face-recognition packge (containing Histogram of Oriented Gradients (HOG) and Convolutional Neural Network (CNN) detectors), MTCNN, Yoloface, Faced, and a ultra light face detector released recently.
I found that while Yoloface has the highest accuracy and most consistent execution time, the Ultra-light face detector was unrivalled in terms of speed and produces a relatively good accuracy.
In this post, we will be using the ultra light detector. But if you are interested in applying any of the other detection methods mentioned, you can refer to my Github repository here.
To use the ultra light model, the following python (python version 3.6) packages are required:
onnx==1.6.0 onnx-tf==1.3.0 onnxruntime==0.5.0 opencv-python==4.1.1.26 tensorflow==1.13.1
Use pip install to install all the dependencies.
After preparing the environments, we can get the frame feeds from our webcam using the OpenCV library via the following code:
For each of the frames we acquired, we need to follow the exact pre-process pipeline during the model training stage to achieve the expected performance.
As we will be using the pretrained ultra_light_640.onnx model, we have to resize the input image to 640x480. If you are using the 320 model, please rezise accordingly.
Code is shown below:
After pre-processing the image, we will have to prepare the ONNX model and create an ONNX inference session. To learn more about model inference, you can check the link here.
Codes to prepare the model and create an inference session are shown below:
Now it is time to detect some faces with the following code:
Variable confidences contains a list of confidence level for each box inside the boxes variable. The first and second values of one confidence pair indicate the probability of containing background and face respectively.
As the boxes value contains all the boxes generated, we will have to identify the boxes with high probability of containing a face and remove the duplicates according to the corresponding Jaccard Index (a.k.a. Intersection over Union).
Code to get the right boxes is shown below:
The predict function will take in an array of boxes and their corresponding confidence level for each labels. Filtering by confidence will then be performed to retain all the boxes with high probability of containing a face.
After that, intersection of union (IOU) value of each remaining boxes is calculated. Finally, boxes are filtered using non-maximum suppression with a hard IOU threshold to remove the similar ones.
Once we have the filtered boxes, we can draw and show in the video stream:
Result from laptop webcam with Intel(R) Core(TM) i7–8550U CPU @ 1.80GHz:
Full code for the detection part can be found here.
After detecting the faces, the next step is to recognize them. There are many techniques for facial recognition including OpenFace, FaceNet, VGGFace2, MobileNetV22 and etc. The model we will use in this article is MobileFaceNet, which is inspired by MobileNetV2. Details of this network architecture and how it is trained can be found here.
Generally, there are three steps taken to recognize a face: (1) Data pre-processing, (2) Facial feature extraction, and (3) Comparison of features between the target face and faces from database.
The data we will be using is a video clip of Jimmy Kimmel’s interview with Jennifer Aniston. We will take the video clip and extract Jennifer Aniston’s faces. You can add your own training data in the corresponding folders.
The file structure looks like the following:
train.pyfaces --training --rachel --rachel.mp4 --... --temp --embeddings
Once the training data is in place, we can perform face extraction on the video clips with the code below:
Faces are captured inside boxes. Now, we can start with face pre-processing.
We will identify five facial landmarks, align faces with proper transformation and resize them to 112x112.
We will be using dlib and imutils to accomplish these subtasks. Use pip install to install these two packages if you have not done so.
After meeting the requirements, we need to initiate shape_predictor (for facial landmark prediction) and FaceAligner with the following code:
shape_predictor_5_landmarks.dat used can be downloaded here. desiredLeftEye specifies how large you want your face to be extracted. Usually the value is ranged from 0.2 to 0.4. The smaller the value is, the larger the face will get.
Code below is how to apply face alignment on all the faces extracted and write to files:
Results:
Further pre-processing is required in order to use MobileFaceNet model. We will have to subtract the aligned face by 127.5 and divide the results by 128 as described in the paper.
Code for more pre-processing as depicted above:
It’s time to get the facial features (a.k.a. embeddings) from the pre-processed faces. We will begin by loading the TensorFlow model:
Next, we will define the network input, get the embeddings and save to a pickle file:
To recognize a face, simply load our embedding dataset with corresponding labels. Then use Euclidean distance and a threshold to determine who each detected face belongs to.
Code is shown below:
Let’s see our results:
Again, you will be able to find the full code here.
With that, we have created a system that can perform real-time face recognition with CPU. Although it is only running at around 13 FPS, it is comparably much faster than using complex CNNs.
However, there are still many things we could do to improve the performance (both the accuracy and speed) of this system. Potentially, we can apply knowledge distillation to compress the current model and further reduce the model size using low bit quantization. Moreover, we could improve the accuracy using other machine learning classification methods on the embeddings.
Thank you for reading! Hope you find this helpful.
Stay tuned and see ya~
[1]: Chen, Sheng, et al. “Mobilefacenets: Efficient cnns for accurate real-time face verification on mobile devices.” Chinese Conference on Biometric Recognition. Springer, Cham, 2018.
[2]: Sandler, Mark, et al. “Mobilenetv2: Inverted residuals and linear bottlenecks.” Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition. 2018 | [
{
"code": null,
"e": 454,
"s": 172,
"text": "Both the academic and industrial fields are putting in tremendous efforts to develop face recognition algorithms and models that are both, fast and accurate. Thanks to these efforts, it is now possible to accomplish accurate, real-time face recognition fo... |
Quick Install Guide: Nvidia RAPIDS + BlazingSQL on AWS SageMaker | by Iván Venzor | Towards Data Science | RAPIDS was announced on October 10, 2018 and since then the folks in NVIDIA have worked day and night to add an impressive number of features each release. The preferred installation methods supported in the current version (0.9) are Conda and Docker (pip support was dropped in 0.7). In addition, RAPIDS it’s available for free in Google Colab and Microsoft’s Azure Machine Learning Service is also supported.
However, there may be people like me that would like/need to use RAPIDS in AWS SageMaker (mainly because our data is already on S3). This guide is intended as a Quick Installation Guide. It’s far from perfect but it might save you several hours of trial and error.
I will also include BlazingSQL, an SQL-engine on top of cuDF. As a Data Scientist, the ability to query the data is extremely useful!
There are two main requirements to install RAPIDS on SageMaker:
Obviously you need a GPU instance. Currently in SageMaker there are only two types of Accelerated Instances: ml.p2 (NVIDIA K80) and ml.p3 (V100) instances. However, as RAPIDS requires NVIDIA Pascal architecture or newer we may only use ml.p3 instances.RAPIDS requires NVIDIA driver v410.48+ (in CUDA 10). AWS updated the driver in May. Therefore, RAPIDS v0.7 was the first version that could be installed in SageMaker.
Obviously you need a GPU instance. Currently in SageMaker there are only two types of Accelerated Instances: ml.p2 (NVIDIA K80) and ml.p3 (V100) instances. However, as RAPIDS requires NVIDIA Pascal architecture or newer we may only use ml.p3 instances.
RAPIDS requires NVIDIA driver v410.48+ (in CUDA 10). AWS updated the driver in May. Therefore, RAPIDS v0.7 was the first version that could be installed in SageMaker.
The installation procedure for the current RAPIDS stable release (0.9) is as follows:
Start or create your ml.p3 SageMaker instance. Once the instance is InService open it. I will be using JupyterLab for the remaining of this guide.In JupyterLab: Git -> Open Terminal, to open the shell and execute the following:
Start or create your ml.p3 SageMaker instance. Once the instance is InService open it. I will be using JupyterLab for the remaining of this guide.
In JupyterLab: Git -> Open Terminal, to open the shell and execute the following:
source /home/ec2-user/anaconda3/etc/profile.d/conda.shconda create --name rapids_blazing python=3.7conda activate rapids_blazing
I strongly recommend creating a new environment. If you try to install RAPIDS in SageMaker conda python3 environment it will take hours to solve the environment and it’s also likely it will yield strange actions (for example, to install python 2 which RAPIDS doesn’t support, etc.).
3. Conda installs RAPIDS (0.9) and BlazingSQL (0.4.3) and a few other packages (in particular boto3 and s3fs are needed to work S3 files) as well as some dependencies for the Sagemaker package which will be pip installed in the next step. In RAPIDS version 0.9 dask-cudf was merged into the cuDF branch. It will take about 8 minutes to solve this environment:
conda install -c rapidsai -c nvidia -c numba -c conda-forge \ -c anaconda -c rapidsai/label/xgboost \ -c blazingsql/label/cuda10.0 -c blazingsql \ "blazingsql-calcite" "blazingsql-orchestrator" \ "blazingsql-ral" "blazingsql-python" \ "rapidsai/label/xgboost::xgboost=>0.9" "cudf=0.9" \ "cuml=0.9" "cugraph=0.9" "dask-cudf=0.9" \ "python=3.7" "ipykernel" "boto3" \ "PyYAML>=3.10,<4.3" "urllib3<1.25,>=1.21" \ "idna<2.8,>=2.5" "boto" "s3fs" "dask" \ "anaconda::cudatoolkit=10.0"
4. Install Sagemaker and flatbuffers packages and register the kernel to be used in JupyterLab:
pip install flatbuffers sagemakeripython kernel install --user --name=rapids_blazing
5. Wait about a minute and then open or create a new notebook and you should be able to select the new kernel: Kernel -> Change Kernel -> conda_rapids_blazing. Note: please do not use rapids_blazing kernel instead of conda_rapids_blazing as BlazinSQL won’t work if that kernel is used.
6. Let’s first import RAPIDS and BlazingSQL packages:
import cudfimport cumlimport daskimport pandas as pdimport dask_cudffrom blazingsql import BlazingContextbc = BlazingContext()
We should get a “connection established” message.
7. Let’s do a first test to check cuDF is working:
df = cudf.DataFrame()df[‘key’] = [0, 1, 2, 3, 4]df[‘val’] = [float(i + 10) for i in range(5)]print(df)
8. Test cuML:
df_float = cudf.DataFrame()df_float[‘0’] = [1.0, 2.0, 5.0]df_float[‘1’] = [4.0, 2.0, 1.0]df_float[‘2’] = [4.0, 2.0, 1.0]dbscan_float = cuml.DBSCAN(eps=1.0, min_samples=1)dbscan_float.fit(df_float)print(dbscan_float.labels_)
9. If there are no errors we have successfully imported and used basic cuDF and cuML functionality. Next step is to read and use data stored in S3. For example, to read some csv files with gzip compression:
import boto3import sagemakerfrom sagemaker import get_execution_rolerole = get_execution_role()df= dask_cudf.read_csv(‘s3://your-bucket/your-path-to-files/files*.csv.gz’, compression=’gzip’)df2=df.compute()
9. Now we may use BlazinSQL to query our data:
bc.create_table(‘test’, df2)result = bc.sql(‘SELECT count(*) FROM test’).get()result_gdf = result.columnsprint(result_gdf)
I will try to update and extend this guide beyond the installing process. Meanwhile here are three interesting results I got:
7X improvement in cuDF (v0.10) read_csv compared to pandas read_csv.
32X improvement in cuML LogisticRegression vs sklearn LogisticRegression.
7X improvement in GPU xgboost (‘tree_method’:’gpu_hist’) vs non-GPU xgboost (‘tree_method’:’hist’).
Looking beyond, RAPIDS version 0.10 will include some nice features for AWS users. For example, cudf.read_csv will be able to read s3 files directly and also a bug in dask-cudf.read_parquet while reading s3 files has been fixed and will be included in 0.10. I thank the RAPIDS team for the quick attention and solution of some of the github issues I have reported.
Any comments to this guide are welcome. May the GPU speed your analysis!! | [
{
"code": null,
"e": 583,
"s": 172,
"text": "RAPIDS was announced on October 10, 2018 and since then the folks in NVIDIA have worked day and night to add an impressive number of features each release. The preferred installation methods supported in the current version (0.9) are Conda and Docker (pip... |
NativeScript - Widgets | NativeScript provides a large set of user interface components and are called as ‘widgets’. Each widget does a special task and comes with a set of methods. Let’s understand NativeScript widgets in detail in this section.
Button is a component to execute tap event action. When a user taps the button it performs the corresponding actions. It is defined below −
<Button text="Click here!" tap="onTap"></Button>
Let us add the button in our BlankNgApp as below −
Open the src\app\home\home.component.html. This is the UI design page of our home component.
Add a button inside the GirdLayout component. The complete code is as follows −
<ActionBar>
<Label text="Home"></Label>
</ActionBar>
<GridLayout>
<button text="Click Here!"></button>
</GridLayout>
Below is the output of the button −
We can style the button using CSS as specified below −
<ActionBar>
<Label text="Home"></Label>
</ActionBar>
<GridLayout>
<button text="Click Here!" class="-primary"></button>
</GridLayout>
Here, −primary class is used to represent the primary button.
Below is the output of ButtonPrimary −
NativeScript provides formatted option to provide custom icons in the button. The sample code is as follows −
<GridLayout>
<Button class="-primary">
<FormattedString>
<Span text="" class="fa"></Span>
<Span text=" Button.-primary with icon"></Span>
</FormattedString>
</Button>
</GridLayout>
.fa {
font-family: "FontAwesome", "fontawesome-webfont";
}
Here,
 specifies the location of the icon in the font, FontAwesome. Download the latest Font Awesome font and place the fontawesome-webfont.ttf in src\fonts folder.
Below is the output of ButtonPrimary −
Rounded button can be created using the below syntax −
<Button text="Button.-primary.-rounded-sm" class="-primary -rounded-sm"></Button>
Below is the output of ButtonPrimary −
Label component is used to display static text. Change the home page as below −
<GridLayout>
<Label text="NativeScript is an open source framework for creating native iOS and Android apps in TypeScript or JavaScript." textWrap="true">
</Label>
</GridLayout>
Here, textWrap wraps the content of the label, if the label extends beyond the screen width.
Below is the output of Label −
TextField component is used to get information from user. Let us change our home page as specified below −
<GridLayout>
<TextField hint="Username"
color="lightblue"
backgroundColor="lightyellow"
height="75px">
</TextField>
</GridLayout>
Here,
color represent text color
color represent text color
backgroundColor represent background of the text box
backgroundColor represent background of the text box
height represent the height of the text box
height represent the height of the text box
Below is the output of Text Field −
TextView Component is used to get multi-line text content from the user. Let us change our home page as specified below −
<GridLayout>
<TextView loaded="onTextViewLoaded" hint="Enter text" returnKeyType="done" autocorrect="false" maxLength="100">
</TextView>
</GridLayout>
Here, maxLength represent maximum length accepted by TextView.
Below is the output of TextView −
This component is used for search any queries or submit any request. It is defined below −
<StackLayout>
<SearchBar id="bar" hint="click here to search ..."></SearchBar>
<StackLayout>
We can apply styles −
<StackLayout>
<SearchBar id="bar" hint="click here to search ..." color="green" backgroundColor="green"></SearchBar>
</StackLayout>
Below is the output of SearchBarStyle −
Switch is based on toggle to choose between options. Default state is false. It is defined below −
<StackLayout>
<Switch checked="false" loaded="onSwitchLoaded"></Switch>
</StackLayout>
The output for the above program is shown below −
Slider is a sliding component to pick a numeric range. It is defined below −
<Slider value="30" minValue="0" maxValue="50" loaded="onSliderLoaded"></Slider>
The output for the above program is given below −
Progress widget indicates progress in an operation. Current progress is represented as bar. It is defined below −
<StackLayout verticalAlign="center" height="50">
<Progress value="90" maxValue="100" backgroundColor="red" color="green" row="0"></Progress>
</StackLayout>
Below is the output of Progress widget −
ActivityIndicator shows a task in a progress. It is defined below −
<StackLayout verticalAlign="center" height="50">
<ActivityIndicator busy="true" color="red" width="50"
height="50"></ActivityIndicator>
</StackLayout>
Below is the output for ActivityIndicator −
Image widget is used to display an image. It can be loaded using ‘ImageSource’ url. It is defined below −
<StackLayout class="m-15" backgroundColor="lightgray">
<Image src="~/images/logo.png" stretch="aspectFill"></Image>
</StackLayout>
The output for Image Widget is as shown below −
WebView shows web pages. Web pages can be loaded using URL. It is defined below −
<WebView row="1" loaded="onWebViewLoaded" id="myWebView" src="http://www.google.com"></WebView>
The output for the above code is as shown below −
DatePicker component is used to pick date. It is defined below −
<StackLayout class="m-15" backgroundColor="lightgray">
<DatePicker year="1980" month="4" day="20" verticalAlignment="center"></DatePicker>
</StackLayout>
The output of DatePicker component is as shown below −
TimePicker component is used to pick the time. It is defined below −
<StackLayout class="m-15" backgroundColor="lightgray">
<TimePicker hour="9"
minute="25"
maxHour="23"
maxMinute="59"
minuteInterval="5">
</TimePicker>
</StackLayout>
Below is the output of TimePicker component −
22 Lectures
1 hours
TELCOMA Global
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2327,
"s": 2105,
"text": "NativeScript provides a large set of user interface components and are called as ‘widgets’. Each widget does a special task and comes with a set of methods. Let’s understand NativeScript widgets in detail in this section."
},
{
"code": null,
... |
C Program to find sum of perfect square elements in an array using pointers. | Write a program to find the sum of perfect square elements in an array by using pointers.
Given a number of elements in array as input and the sum of all the perfect square of those elements present in the array is output.
For example,
Input= 1, 2, 3, 4, 5, 9,10,11,16
The perfect squares are 1, 4, 9,16.
Sum = 1 + 4 + 9 +16 = 30
Output: 30
Refer an algorithm given below to find the sum of perfect square elements in an array by using pointers.
Step 1 − Read number of elements in array at runtime.
Step 2 − Input the elements.
Step 3 − Declare and initialize the sum=0
Step 4 − Declare a pointer variable.
Step 5 − Check, whether the array element is a perfect square or not by using a pointer variable
Step 6 − If it is a perfect square, then, compute sum=sum+number
Step 7 − Return sum.
Following is the C program to find the sum of perfect square elements in an array by using pointers −
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int sumPositive(int n,int *a){
int i,sum=0,m;
for(i=0;i<n;i++){
m=sqrt(*(a+i));
if(pow(m,2)==*(a+i)){
sum+=*(a+i);
}
}
return sum;
}
int main(){
int i,*a,n;
printf("Enter the size of array:\n");
scanf("%d",&n);
a=(int*)malloc(n*sizeof(int));
printf("Enter the elements of array:\n");
for(i=0;i<n;i++){
scanf("%d",a+i);
}
printf("Sum of positive square elements is %d",sumPositive(n,a));
return 0;
}
When the above program is executed, it produces the following output −
Enter the size of array:
10
Enter the elements of array:
1
2
3
4
5
6
7
8
9
10
Sum of positive square elements is 14 | [
{
"code": null,
"e": 1152,
"s": 1062,
"text": "Write a program to find the sum of perfect square elements in an array by using pointers."
},
{
"code": null,
"e": 1285,
"s": 1152,
"text": "Given a number of elements in array as input and the sum of all the perfect square of those ... |
Mounting & accessing ADLS Gen2 in Azure Databricks using Service Principal and Secret Scopes | by Dhyanendra Singh Rathore | Towards Data Science | Azure Data Lake Storage and Azure Databricks are unarguably the backbones of the Azure cloud-based data analytics systems. Azure Data Lake Storage provides scalable and cost-effective storage, whereas Azure Databricks provides the means to build analytics on that storage.
The analytics procedure begins with mounting the storage to Databricks distributed file system (DBFS). There are several ways to mount Azure Data Lake Store Gen2 to Databricks. Perhaps one of the most secure ways is to delegate the Identity and access management tasks to the Azure AD.
This article looks at how to mount Azure Data Lake Storage to Databricks authenticated by Service Principal and OAuth 2.0 with Azure Key Vault-backed Secret Scopes.
Caution: Microsoft Azure is a paid service, and following this article can cause financial liability to you or your organization.
At the time of writing, Azure Key Vault-backed Secret Scopes is in ‘Public Preview.’ It is recommended not to use any ‘Preview’ feature in production or critical systems.
Please read our terms of use before proceeding with this article: https://dhyanintech.medium.com/disclaimer-disclosure-terms-of-use-fb3bfbd1e0e5
An active Microsoft Azure subscriptionAzure Data Lake Storage Gen2 accountAzure Databricks Workspace (Premium Pricing Tier)Azure Key Vault
An active Microsoft Azure subscription
Azure Data Lake Storage Gen2 account
Azure Databricks Workspace (Premium Pricing Tier)
Azure Key Vault
If you don’t have prerequisites set up yet, refer to our previous article to get started:
medium.com
To access resources secured by an Azure AD tenant (e.g., storage accounts), a security principal must represent the entity that requires access. A security principal defines the access policy and permissions for a user or an application in the Azure AD tenant. When an application is permitted to access resources in a tenant (e.g., upon registration), a service principal object is created automatically.
Further reading on service principals:
docs.microsoft.com
Let’s begin by registering an Azure AD application to create a service principal and store our application authentication key in the Azure Key Vault instance.
Find and select Azure Active Directory on the Azure Portal home page. Select App registrations and click + New registration.
On the Register an application page, enter the name ADLSAccess, signifying the purpose of the application, and click Register.
In the ADLSAccess screen, copy the Application (client) ID and the Directory (tenant) ID into notepad. Application ID refers to the app we just registered (i.e., ADLSAccess), and the Azure AD tenant our app ADLSAccess is registered to is the Directory ID.
Next, we need to generate an authentication key (aka application password or client secret or application secret) to authenticate the ADLSAccess app. Click on Certificates and secrets, and then click + New client secret. On the Add a client secret blade, type a description, and expiry of one year, click Add when done.
When you click on Add, the client secret (authentication key) will appear, as shown in the image below. You only have one opportunity to copy this key-value into notepad. You will not be able to retrieve it later if you perform another operation or leave this blade.
Next, we need to assign an access role to our service principal (recall that a service principal is created automatically upon registering an app) to access data in our storage account. Go to the Azure portal home and open the resource group in which your storage account exists. Click Access Control (IAM), on Access Control (IAM) page, select + Add and click Add role assignment. On the Add role assignment blade, assign the Storage Blob Data Contributor role to our service principal (i.e., ADLSAccess), as shown below.
Go to the Azure portal home and open your key vault. Click Secrets to add a new secret; select + Generate/Import. On Create a secret blade; give a Name, enter the client secret (i.e., ADLS Access Key we copied in the previous step) as Value and a Content type for easier readability and identification of the secret later. Repeat the creation process for the Application (client) ID and the Directory (tenant) ID we copied earlier. Your vault should have three secrets now.
Select Properties, copy the Vault URI and Resource ID to notepad; we will need them in the next step.
If you’ve followed our another article on creating a Secret Scope for Azure SQL Server credentials, you don’t have to perform this step as long as your key vault and Databricks instance in question remains the same.
Go to https://<DATABRICKS-INSTANCE>#secrets/createScopeand replace <DATABRICKS-INSTANCE> with your actual Databricks instance URL. Create a Secret Scope, as shown below.
This URL is case sensitive.
Finally, it’s time to mount our storage account to our Databricks cluster. Head back to your Databricks cluster and open the notebook we created earlier (or any notebook, if you are not following our entire series).
We will define some variables to generate our connection strings and fetch the secrets using Databricks utilities. You can copy-paste the below code to your notebook or type it on your own. We’re using Python for this notebook. Run your code using controls given at the top-right corner of the cell. Don’t forget to replace the variable assignments with your storage details and secret Names.
Further reading on Databricks utilities (dbutils) and accessing secrets:
docs.databricks.com
Further reading on how to use notebooks efficiently:
docs.databricks.com
We can override the default language of a notebook by specifying the language magic command at the beginning of a cell. The supported magic commands are %python, %r, %scala, and %sql. Notebooks also support few additional magic commands like %fs, %sh, and %md. We can use %fs ls to list the content of our mounted store.
Don’t forget to unmount your storage when you no longer need it.
# Unmount only if directory is mountedif any(mount.mountPoint == mountPoint for mount in dbutils.fs.mounts()): dbutils.fs.unmount(mountPoint)
Congratulations! You’ve successfully mounted your storage account to Databricks without revealing and storing your application secrets and access keys.
We looked at how to register a new Azure AD application to create a service principal, assigned access roles to a service principal, and stored our secrets to Azure Key Vault. We created an Azure Key Vault-backed Secret Scope in Azure Dataricks and securely mounted and listed the files stored in our ADLS Gen2 account in Databricks.
If you’re curious to know how we got those CSV files in our storage, please head to our other article to set up an innovative Azure Data Factory pipeline to copy files over HTTP from a GitHub repository.
medium.com
We have another exciting article on connecting and accessing the Azure Synapse analytic data warehouse from Datarbricks. Take a look:
medium.com
Dhyanendra Singh Rathore is a Microsoft-certified Data, BI, and power platform professional. He is passionate about solving problems and currently gravitating towards serverless computing and AI platforms. He has a Master’s degree in Computer Networking Engineering.
You can join him on Medium or connect with him on LinkedIn.
Got any topic-related issues you wish to discuss? Shoot an email to dhyan.singh@everydaybi.com for a private consultation. | [
{
"code": null,
"e": 320,
"s": 47,
"text": "Azure Data Lake Storage and Azure Databricks are unarguably the backbones of the Azure cloud-based data analytics systems. Azure Data Lake Storage provides scalable and cost-effective storage, whereas Azure Databricks provides the means to build analytics ... |
Improving Clustering Performance Using Feature Weight Learning | by Colin Sinclair | Towards Data Science | Clustering is an unsupervised machine learning methodology that aims to partition data into distinct groups, or clusters. There are a few different forms including hierarchical, density, and similarity based. Each have a few different algorithms associated with it as well. One of the hardest parts of any machine learning algorithm is feature engineering, which can especially be difficult with clustering as there is no easy way to figure out what best segments your data into separate but similar groups.
The guiding principle of similarity based clustering is that similar objects are within the same cluster and dissimilar objects are in different clusters. This is not different than the goal of most conventional clustering algorithms. With similarity based clustering, a measure must be given to determine how similar two objects are. This similarity measure is based off distance, and different distance metrics can be employed, but the similarity measure usually results in a value in [0,1] with 0 having no similarity and 1 being identical. To measure feature weight importance, we will have to use a weighted euclidean distance function. The similarity measure is defined in the following:
β here is a value that we will actually have to solve for, (w) represents the distance weight matrix, and d represents the pairwise distances between all objects. To solve for β, we have to use the assumption that if using the standard weights(all 1's), our similarity matrix would uniformly distributed between [0,1] resulting in a mean of .5. So to find β, we solve the equation:
If using a weighted euclidean distance, it is possible to use this similarity matrix to identify what features introduce more noise and which ones are important to clustering. The ultimate goal is to minimize the “fuzziness” of the similarity matrix, trying to move everything in the middle (ie .5) to either 1 or 0. For this purpose we use the loss metric:
Here (1) represents the base weights (all 1's), and ρ represents the resulting fuzzy partition matrix that is a product of the weights used in the euclidean distance function between points p and q.
We can then attempt to use Gradient Descent on this loss function to try and minimize it with respect to the similarity matrix. Gradient Descent is one of the most common optimization algorithms in machine learning that is used to find best parameters of a given function by using the function gradient, a combination of the partial derivatives. By taking steps proportional to the negative of the gradient, we can try to find the local minimum of the function. We will continually update the weights until either our maximum number of iterations has been met, or the function converges. So the gradient descent will be of our loss function with a partial derivative in respect to the weights. We will update the weights every iteration with respect to the gradient and learning rate.
Where n is the learning rate defined. n is a very important parameter, as something too small will require too much computation, while too big and the function may never converge.
If you can think of it in terms of a 3D graph, it would be like stretching or shrinking each axis, in a way that would put our points into tighter groups, that are further away from each other. We are not actually changing the locations of the data, we are solely transforming how we measure the distances that drive our similarity metrics.
Here is a created example where I introduce 3 clusters with separate centroids on the first two variables, but introduce a third noise variable that would make the clustering more difficult. These are colored by the actual cluster labels given when the data is created. When eliminating the third noise variable, we can see it would be much easier to identify clusters.
Although it mostly is difficult to see the differences because of the 3D perspective, you can see how much more defined the clusters are with the learned feature weights. By stretching out the main feature that can easily separate them, it was able to better identify clusters.
A good representation of its effectiveness is fuzzy c-means, a relative of the commonly used k-means algorithm. It works in a very similar fashion to k-means, but rather results in something called the fuzzy partition matrix instead of just a cluster label.
The fuzzy partition matrix is a set of weights that measure how similar a single point is to a given cluster center, close to how our similarity matrix is used previously. It can also be calculated using a weighted distance metric which we can feed our new found optimal weights. This will also then go back into updating the cluster centers. Like K-means, this results in the cluster centers shifting with each iteration, until the maximum number of iterations or a certain improvement threshold has been met.
In fuzzy c-means, you would have a very similar goal as to our original loss function. You would like less “fuzzyness” from points, and you want them all to be as close as possible to their cluster centers, and further away from others. A good measure of the fuzzy clustering algorithm is Dunn’s partition coefficient, a sum of all components of the fuzzy partition matrix.
Let’s try using fuzzy c-means on the Iris data set with and without our learned feature weights. Here the output of fuzzy c-means comparing all variables, assuming 3 clusters(since we know that from the data set).
Notice how the boundaries between some are less defined, and because we have multiple features equally weighted, it can be blurred. Now, when applying the feature weighted learning approach, we get normalized distance weights of:
{'sepal length': 0.0, 'sepal width': 0.0, 'petal length': 1.0, 'petal width': 0.0258}
There are still fuzzy boundaries, mostly on features where we deemed them 0 value in the distance weights, but the algorithm put a major focus on petal length. We resulted in similar clusters, stronger boundaries (on some features), and overall our fuzzy partition coefficient increased by ~23%!
We also now know that if we wanted to generate rules about classifying them, we could just focus on 2 features instead of 4!
Just because it is easiest to see the results using fuzzy c-means does not mean this improvement measure can only be used for that algorithm. You can use it in many ways, scaling or just better understanding your data before clustering. I recently used this feature reduction and importance technique in an application that used the OPTICS algorithm, and saw improved results by scaling my features in accordance with the feature weight learning algorithm.
I have built this feature weight learning into a stand alone repository if you would like to check it out yourself or use it.
github.com
Wang, Xizhao, Wang, Yadong, and Wang, Lijuan.”Improving fuzzy c-means clustering based on feature-weight learning”. 2004 Elsevier B. V. doi:10.1016/j.patrec.2004.03.008 | [
{
"code": null,
"e": 555,
"s": 47,
"text": "Clustering is an unsupervised machine learning methodology that aims to partition data into distinct groups, or clusters. There are a few different forms including hierarchical, density, and similarity based. Each have a few different algorithms associated... |
Bootstrap 4 Fixed Layout - GeeksforGeeks | 01 Feb, 2022
Bootstrap is a free and open-source tool collection for creating responsive websites and web applications. This is the most popular HTML, CSS, and JavaScript framework for developing responsive websites. It solves the cross-browser compatibility issue.
The following class sets a maximum width at each responsive breakpoint.
Syntax:
.container
Bootstrap Fixed Layout: This type of layout makes website page designs dependent on a decent number of pixels, container width differs depending upon the viewport width and the format is responsive. The most common way of creating the fixed layout begins with the “.container” class. You can make a row with the “.row” class to wrap the even gatherings of segments. Rows will be inserted inside a “.container” (fixed-width) for legitimate arrangement and padding.
Example: The following example explains a fixed layout using Bootstrap 4.
HTML
<!DOCTYPE html><html lang="en"><head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Bootstrap 4 Fixed Layout</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <script src="https://code.jquery.com/jquery-3.5.1.min.js"> </script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"> </script></head><body> <nav class="navbar navbar-expand-md navbar-dark bg-success mb-3"> <div class="container"> <a href="#" class="navbar-brand mr-3">GeeksforGeeks</a> <button type="button" class="navbar-toggler" data-toggle="collapse" data-target="#navbarCollapse"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarCollapse"> <div class="navbar-nav"> <a href="#" class="nav-item nav-link active"></a> <a href="#" class="nav-item nav-link">Courses</a> <a href="#" class="nav-item nav-link">DSA</a> <a href="#" class="nav-item nav-link">Articles</a> <a href="#" class="nav-item nav-link">Jobs</a> <a href="#" class="nav-item nav-link">Student</a> <a href="#" class="nav-item nav-link">Tutorials</a> </div> </div> </div> </nav> <div class="container"> <div class="jumbotron"> <h1>Get Hired With GeeksforGeeks and <strong>Win Exciting Rewards!</strong> </h1> <p class="lead"> Imagine a situation of visiting a game parlor or adventure park, having ultimate fun there, and coming back home without paying a single penny there and in fact, receiving some exciting rewards or cash benefits from them. </p> <p><a href="#" target="_blank" class="btn btn-success btn-lg"> Register here</a> </p> </div> <div class="row"> <div class="col-md-4"> <h2>Basic Concepts For Data Science</h2> <p> Data Scientist is one of the most lucrative career options that offers immense job satisfaction,insanely high salary, global recognition, and amazing growth opportunities </p> <p><a href="#" class="btn btn-success"> Read More »</a> </p> </div> <div class="col-md-4"> <h2>Stock Market APIs For Developers</h2> <p> Stock Market is all about the exchange of stocks (also pronounced as Shares) between various buyers and sellers. Since stocks of variable prices are prone </p> <p><a href="#" class="btn btn-success"> Read More »</a> </p> </div> <div class="col-md-4"> <h2>Is Quick Sort Algorithm Adaptive or not</h2> <p> Pre-Requisites: Quick Sort Algorithm Adaptiveness in the Quick Sort Algorithm refers to the decision that if we are given an array that is already sorted </p> <p><a href="#" class="btn btn-success"> Read More »</a> </p> </div> </div> </div></body></html>
Output:
surindertarika1234
Bootstrap-4
Bootstrap-Questions
Picked
Bootstrap
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
List group in bootstrap with examples
How to toggle password visibility in forms using Bootstrap-icons ?
BootStrap | Positioning an element with Examples
How to prevent inline-block divs from wrapping ?
How to use Bootstrap Datepicker to get date on change event ?
Express.js express.Router() Function
Installation of Node.js on Linux
How to set input type date in dd-mm-yyyy format using HTML ?
Differences between Functional Components and Class Components in React
How to create footer to stay at the bottom of a Web page? | [
{
"code": null,
"e": 25229,
"s": 25201,
"text": "\n01 Feb, 2022"
},
{
"code": null,
"e": 25482,
"s": 25229,
"text": "Bootstrap is a free and open-source tool collection for creating responsive websites and web applications. This is the most popular HTML, CSS, and JavaScript frame... |
Inter thread communication in Java | If you are aware of interprocess communication then it will be easy for you to understand interthread communication. Interthread communication is important when you develop an application where two or more threads exchange some information.
There are three simple methods and a little trick which makes thread communication possible. All the three methods are listed below −
These methods have been implemented as final methods in Object, so they are available in all the classes. All three methods can be called only from within a synchronized context.
This examples shows how two threads can communicate using wait() and notify() method. You can create a complex system using the same concept.
Live Demo
class Chat {
boolean flag = false;
public synchronized void Question(String msg) {
if (flag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(msg);
flag = true;
notify();
}
public synchronized void Answer(String msg) {
if (!flag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(msg);
flag = false;
notify();
}
}
class T1 implements Runnable {
Chat m;
String[] s1 = { "Hi", "How are you ?", "I am also doing fine!" };
public T1(Chat m1) {
this.m = m1;
new Thread(this, "Question").start();
}
public void run() {
for (int i = 0; i < s1.length; i++) {
m.Question(s1[i]);
}
}
}
class T2 implements Runnable {
Chat m;
String[] s2 = { "Hi", "I am good, what about you?", "Great!" };
public T2(Chat m2) {
this.m = m2;
new Thread(this, "Answer").start();
}
public void run() {
for (int i = 0; i < s2.length; i++) {
m.Answer(s2[i]);
}
}
}
public class TestThread {
public static void main(String[] args) {
Chat m = new Chat();
new T1(m);
new T2(m);
}
}
When the above program is complied and executed, it produces the following result −
Hi
Hi
How are you ?
I am good, what about you?
I am also doing fine!
Great!
Above example has been taken and then modified from https://stackoverflow.com/questions/2170520/inter-thread-communication-in-java | [
{
"code": null,
"e": 1303,
"s": 1062,
"text": "If you are aware of interprocess communication then it will be easy for you to understand interthread communication. Interthread communication is important when you develop an application where two or more threads exchange some information."
},
{
... |
Stack set() method in Java with Example - GeeksforGeeks | 24 Dec, 2018
The set() method of Java Stack is used to replace any particular element in the stack created using the Stack 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:
public E 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 stack.
element: It is the new element by which the existing element will be replaced and is of the same object type as the stack.
Return Value: The method returns the previous value from the stack that is replaced with the new value.
Exception: This method throws following exceptions:
UnsupportedOperationException: if the set operation is not supported by this stack
ClassCastException: if the class of the specified element prevents it from being added to this stack
NullPointerException: if the specified element is null and this stack does not permit null elements
IllegalArgumentException: if some property of the specified element prevents it from being added to this stack
IndexOutOfBoundsException: if the index is out of range (index = size())
Below program illustrate the Java.util.Stack.set() method:
Example 1:
// Java code to illustrate set() import java.io.*;import java.util.*; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<String> stack = new Stack<String>(); // Use add() method to add elements in the stack stack.add("Geeks"); stack.add("for"); stack.add("Geeks"); stack.add("10"); stack.add("20"); // Displaying the linkedstack System.out.println("Stack:" + stack); // Using set() method to replace Geeks with GFG System.out.println("The Object that is replaced is: " + stack.set(2, "GFG")); // Using set() method to replace 20 with 50 System.out.println("The Object that is replaced is: " + stack.set(4, "50")); // Displaying the modified linkedstack System.out.println("The new Stack is:" + stack); }}
Stack:[Geeks, for, Geeks, 10, 20]
The Object that is replaced is: Geeks
The Object that is replaced is: 20
The new Stack is:[Geeks, for, GFG, 10, 50]
Example 2: To demonstrate IndexOutOfBoundException
// Java code to illustrate set() import java.io.*;import java.util.*; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<String> stack = new Stack<String>(); // Use add() method to add elements in the stack stack.add("Geeks"); stack.add("for"); stack.add("Geeks"); stack.add("10"); stack.add("20"); // Displaying the linkedstack System.out.println("Stack:" + stack); // Using set() method to replace 10th with GFG // and the 10th element does not exist System.out.println("Trying to replace 10th " + "element with GFG"); try { stack.set(10, "GFG"); } catch (Exception e) { System.out.println(e); } }}
Stack:[Geeks, for, Geeks, 10, 20]
Trying to replace 10th element with GFG
java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 10
Java - util package
Java-Collections
Java-Functions
Java-Stack
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Reverse a string in Java
Arrays.sort() in Java with examples
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
How to iterate any Map in Java
Interfaces in Java
Initialize an ArrayList in Java | [
{
"code": null,
"e": 23249,
"s": 23221,
"text": "\n24 Dec, 2018"
},
{
"code": null,
"e": 23519,
"s": 23249,
"text": "The set() method of Java Stack is used to replace any particular element in the stack created using the Stack class with another element. This can be done by speci... |
Java & MySQL - CallableStatement | The CallableStatement interface is used to execute a call to a database stored procedure.
Suppose, you need to execute the following stored procedure in TUTORIALSPOINT database −
DELIMITER $$
DROP PROCEDURE IF EXISTS `TUTORIALSPOINT`.`getEmpName` $$
CREATE PROCEDURE `TUTORIALSPOINT`.`getEmpName`
(IN EMP_ID INT, OUT EMP_FIRST VARCHAR(255))
BEGIN
SELECT first INTO EMP_FIRST
FROM Employees
WHERE ID = EMP_ID;
END $$
DELIMITER ;
Three types of parameters exist: IN, OUT, and INOUT. The PreparedStatement object only uses the IN parameter. The CallableStatement object can use all the three.
Here are the definitions of each −
The following code snippet shows how to employ the Connection.prepareCall() method to instantiate a CallableStatement object based on the preceding stored procedure −
CallableStatement cstmt = null;
try {
String SQL = "{call getEmpName (?, ?)}";
cstmt = conn.prepareCall (SQL);
. . .
}
catch (SQLException e) {
. . .
}
finally {
. . .
}
The String variable SQL, represents the stored procedure, with parameter placeholders.
Using the CallableStatement objects is much like using the PreparedStatement objects. You must bind values to all the parameters before executing the statement, or you will receive an SQLException.
If you have IN parameters, just follow the same rules and techniques that apply to a PreparedStatement object; use the setXXX() method that corresponds to the Java data type you are binding.
When you use OUT and INOUT parameters you must employ an additional CallableStatement method, registerOutParameter(). The registerOutParameter() method binds the JDBC data type, to the data type that the stored procedure is expected to return.
Once you call your stored procedure, you retrieve the value from the OUT parameter with the appropriate getXXX() method. This method casts the retrieved value of SQL type to a Java data type.
Just as you close other Statement object, for the same reason you should also close the CallableStatement object.
A simple call to the close() method will do the job. If you close the Connection object first, it will close the CallableStatement object as well. However, you should always explicitly close the CallableStatement object to ensure proper cleanup.
CallableStatement cstmt = null;
try {
String SQL = "{call getEmpName (?, ?)}";
cstmt = conn.prepareCall (SQL);
. . .
}
catch (SQLException e) {
. . .
}
finally {
cstmt.close();
}
We're using try with resources which handles the resource closure automatically. Following example demonstrates all of the above said concepts.
This code has been written based on the environment and database setup done in the previous chapter.
Copy and paste the following example in TestApplication.java, compile and run as follows −
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class TestApplication {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
static final String QUERY = "{call getEmpName (?, ?)}";
public static void main(String[] args) {
// Open a connection
try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
CallableStatement stmt = conn.prepareCall(QUERY);
) {
// Bind values into the parameters.
stmt.setInt(1, 102); // This would set ID
// Because second parameter is OUT so register it
stmt.registerOutParameter(2, java.sql.Types.VARCHAR);
//Use execute method to run stored procedure.
System.out.println("Executing stored procedure..." );
stmt.execute();
//Retrieve employee name with getXXX method
String empName = stmt.getString(2);
System.out.println("Emp Name with ID: 102 is " + empName);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Now let us compile the above example as follows −
C:\>javac TestApplication.java
C:\>
When you run TestApplication, it produces the following result −
C:\>java TestApplication
Executing stored procedure...
Emp Name with ID: 102 is Zaid
C:\>
The escape syntax gives you the flexibility to use database specific features unavailable to you by using standard JDBC methods and properties.
The general SQL escape syntax format is as follows −
{keyword 'parameters'}
Here are the following escape sequences, which you would find very useful while performing the JDBC programming −
They help identify date, time, and timestamp literals. As you know, no two DBMSs represent time and date the same way. This escape syntax tells the driver to render the date or time in the target database's format. For Example −
{d 'yyyy-mm-dd'}
Where yyyy = year, mm = month; dd = date. Using this syntax {d '2009-09-03'} is March 9, 2009.
Here is a simple example showing how to INSERT date in a table −
//Create a Statement object
stmt = conn.createStatement();
//Insert data ==> ID, First Name, Last Name, DOB
String sql="INSERT INTO STUDENTS VALUES" +
"(100,'Zara','Ali', {d '2001-12-16'})";
stmt.executeUpdate(sql);
Similarly, you can use one of the following two syntaxes, either t or ts −
{t 'hh:mm:ss'}
Where hh = hour; mm = minute; ss = second. Using this syntax {t '13:30:29'} is 1:30:29 PM.
{ts 'yyyy-mm-dd hh:mm:ss'}
This is combined syntax of the above two syntax for 'd' and 't' to represent timestamp.
This keyword identifies the escape character used in LIKE clauses. Useful when using the SQL wildcard %, which matches zero or more characters. For example −
String sql = "SELECT symbol FROM MathSymbols WHERE symbol LIKE '\%' {escape '\'}";
stmt.execute(sql);
If you use the backslash character (\) as the escape character, you also have to use two backslash characters in your Java String literal, because the backslash is also a Java escape character.
This keyword represents scalar functions used in a DBMS. For example, you can use SQL function length to get the length of a string −
{fn length('Hello World')}
This returns 11, the length of the character string 'Hello World'.
This keyword is used to call the stored procedures. For example, for a stored procedure requiring an IN parameter, use the following syntax −
{call my_procedure(?)};
For a stored procedure requiring an IN parameter and returning an OUT parameter, use the following syntax −
{? = call my_procedure(?)};
This keyword is used to signify outer joins. The syntax is as follows −
{oj outer-join}
Where outer-join = table {LEFT|RIGHT|FULL} OUTERJOIN {table | outer-join} on search-condition. For example −
String sql = "SELECT Employees FROM {oj ThisTable RIGHT OUTER JOIN ThatTable on id = '100'}";
stmt.execute(sql);
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": 2776,
"s": 2686,
"text": "The CallableStatement interface is used to execute a call to a database stored procedure."
},
{
"code": null,
"e": 2865,
"s": 2776,
"text": "Suppose, you need to execute the following stored procedure in TUTORIALSPOINT database −"
... |
Count factorial numbers in a given range - GeeksforGeeks | 04 Mar, 2022
A number F is a factorial number if there exists some integer I >= 0 such that F = I! (that is, F is factorial of I). Examples of factorial numbers are 1, 2, 6, 24, 120, .... Write a program that takes as input two long integers ‘low’ and ‘high’ where 0 < low < high and finds count of factorial numbers in the closed interval [low, high]. Examples :
Input: 0 1
Output: 1 //Reason: Only factorial number is 1
Input: 12 122
Output: 2 // Reason: factorial numbers are 24, 120
Input: 2 720
Output: 5 // Factorial numbers are: 2, 6, 24, 120, 720
1) Find the first factorial that is greater than or equal to low. Let this factorial be x! (factorial of x) and value of this factorial be ‘fact’2) Keep incrementing x, and keep updating ‘fact’ while fact is smaller than or equal to high. Count the number of times, this loop runs.3) Return the count computed in step 2.Below is implementation of above algorithm. Thanks to Kartik for suggesting below solution.
C++
Java
Python3
C#
PHP
Javascript
// C++ Program to count factorial numbers in given range#include <iostream>using namespace std; int countFact(int low, int high){ // Find the first factorial number 'fact' greater than or // equal to 'low' int fact = 1, x = 1; while (fact < low) { fact = fact*x; x++; } // Count factorial numbers in range [low, high] int res = 0; while (fact <= high) { res++; fact = fact*x; x++; } // Return the count return res;} // Driver program to test above functionint main(){ cout << "Count is " << countFact(2, 720); return 0;}
// Java Program to count factorial// numbers in given range class GFG{ static int countFact(int low, int high) { // Find the first factorial number // 'fact' greater than or equal to 'low' int fact = 1, x = 1; while (fact < low) { fact = fact * x; x++; } // Count factorial numbers // in range [low, high] int res = 0; while (fact <= high) { res++; fact = fact * x; x++; } // Return the count return res; } // Driver code public static void main (String[] args) { System.out.print("Count is " + countFact(2, 720)); }} // This code is contributed by Anant Agarwal.
# Python3 Program to count factorial# numbers in given range def countFact(low,high): # Find the first factorial number # 'fact' greater than or # equal to 'low' fact = 1 x = 1 while (fact < low): fact = fact * x x += 1 # Count factorial numbers # in range [low, high] res = 0 while (fact <= high): res += 1 fact = fact * x x += 1 # Return the count return res # Driver code print("Count is ", countFact(2, 720)) # This code is contributed# by Anant Agarwal.
// C# Program to count factorial// numbers in given rangeusing System; public class GFG{ // Function to count factorial static int countFact(int low, int high) { // Find the first factorial number numbers // 'fact' greater than or equal to 'low' int fact = 1, x = 1; while (fact < low) { fact = fact * x; x++; } // Count factorial numbers // in range [low, high] int res = 0; while (fact <= high) { res++; fact = fact * x; x++; } // Return the count return res; } // Driver code public static void Main () { Console.Write("Count is " + countFact(2, 720)); }} // This code is contributed by Sam007
<?php// PHP Program to count factorial// numbers in given rangefunction countFact($low, $high){ // Find the first factorial // number 'fact' greater // than or equal to 'low' $fact = 1; $x = 1; while ($fact < $low) { $fact = $fact * $x; $x++; } // Count factorial numbers // in range [low, high] $res = 0; while ($fact <= $high) { $res++; $fact = $fact * $x; $x++; } // Return the count return $res;} // Driver Codeecho "Count is " , countFact(2, 720); // This code is contributed by ajit?>
<script>// Javascript Program to count factorial// numbers in given rangefunction countFact(low, high){ // Find the first factorial // number 'fact' greater // than or equal to 'low' let fact = 1; let x = 1; while (fact < low) { fact = fact * x; x++; } // Count factorial numbers // in range [low, high] let res = 0; while (fact <= high) { res++; fact = fact * x; x++; } // Return the count return res;} // Driver Codedocument.write("Count is " + countFact(2, 720)); // This code is contributed by _saurabh_jaiswal</script>
Output :
Count is 5
This article is contributed by Shivam. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Sam007
jit_t
_saurabh_jaiswal
surinderdawra388
simmytarika5
factorial
Mathematical
Mathematical
factorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Program to print prime numbers from 1 to N.
Fizz Buzz Implementation
Program to multiply two matrices
Modular multiplicative inverse
Check if a number is Palindrome
Find first and last digits of a number
Count ways to reach the n'th stair
Program to convert a given number to words
Find Union and Intersection of two unsorted arrays | [
{
"code": null,
"e": 24716,
"s": 24688,
"text": "\n04 Mar, 2022"
},
{
"code": null,
"e": 25068,
"s": 24716,
"text": "A number F is a factorial number if there exists some integer I >= 0 such that F = I! (that is, F is factorial of I). Examples of factorial numbers are 1, 2, 6, 24... |
How to measure elapsed time in nanoseconds with Java? | In general, the elapsed time is the time from the starting point to ending point of an event. Following are various ways to find elapsed time in Java −
The nanoTime() method returns the current time in nano seconds. To find the elapsed time for the execution of a method in nano seconds −
Retrieve the current time using the nanoTime() method.
Execute the desired method.
Again, retrieve the current time using the nanoTime() method.
Finally, Find the difference between the end value and the start value.
Live Demo
public class Example {
public void test(){
int num = 0;
for(int i=0; i<=50; i++){
num =num+i;
System.out.print(num+", ");
}
}
public static void main(String args[]){
//Start time
long begin = System.nanoTime();
//Starting the watch
new Example().test();
//End time
long end = System.nanoTime();
long time = end-begin;
System.out.println();
System.out.println("Elapsed Time: "+time);
}
}
0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136, 153, 171, 190, 210, 231, 253, 276, 300, 325, 351, 378, 406, 435, 465, 496, 528, 561, 595, 630, 666, 703, 741, 780, 820, 861, 903, 946, 990, 1035, 1081, 1128, 1176, 1225, 1275,
Elapsed Time: 1530200 | [
{
"code": null,
"e": 1214,
"s": 1062,
"text": "In general, the elapsed time is the time from the starting point to ending point of an event. Following are various ways to find elapsed time in Java −"
},
{
"code": null,
"e": 1351,
"s": 1214,
"text": "The nanoTime() method returns ... |
Biopython - Quick Guide | Biopython is the largest and most popular bioinformatics package for Python. It contains a number of different sub-modules for common bioinformatics tasks. It is developed by Chapman and Chang, mainly written in Python. It also contains C code to optimize the complex computation part of the software. It runs on Windows, Linux, Mac OS X, etc.
Basically, Biopython is a collection of python modules that provide functions to deal with DNA, RNA & protein sequence operations such as reverse complementing of a DNA string, finding motifs in protein sequences, etc. It provides lot of parsers to read all major genetic databases like GenBank, SwissPort, FASTA, etc., as well as wrappers/interfaces to run other popular bioinformatics software/tools like NCBI BLASTN, Entrez, etc., inside the python environment. It has sibling projects like BioPerl, BioJava and BioRuby.
Biopython is portable, clear and has easy to learn syntax. Some of the salient features are listed below −
Interpreted, interactive and object oriented.
Interpreted, interactive and object oriented.
Supports FASTA, PDB, GenBank, Blast, SCOP, PubMed/Medline, ExPASy-related formats.
Supports FASTA, PDB, GenBank, Blast, SCOP, PubMed/Medline, ExPASy-related formats.
Option to deal with sequence formats.
Option to deal with sequence formats.
Tools to manage protein structures.
Tools to manage protein structures.
BioSQL − Standard set of SQL tables for storing sequences plus features and annotations.
BioSQL − Standard set of SQL tables for storing sequences plus features and annotations.
Access to online services and database, including NCBI services (Blast, Entrez, PubMed) and ExPASY services (SwissProt, Prosite).
Access to online services and database, including NCBI services (Blast, Entrez, PubMed) and ExPASY services (SwissProt, Prosite).
Access to local services, including Blast, Clustalw, EMBOSS.
Access to local services, including Blast, Clustalw, EMBOSS.
The goal of Biopython is to provide simple, standard and extensive access to bioinformatics through python language. The specific goals of the Biopython are listed below −
Providing standardized access to bioinformatics resources.
Providing standardized access to bioinformatics resources.
High-quality, reusable modules and scripts.
High-quality, reusable modules and scripts.
Fast array manipulation that can be used in Cluster code, PDB, NaiveBayes and Markov Model.
Fast array manipulation that can be used in Cluster code, PDB, NaiveBayes and Markov Model.
Genomic data analysis.
Genomic data analysis.
Biopython requires very less code and comes up with the following advantages −
Provides microarray data type used in clustering.
Provides microarray data type used in clustering.
Reads and writes Tree-View type files.
Reads and writes Tree-View type files.
Supports structure data used for PDB parsing, representation and analysis.
Supports structure data used for PDB parsing, representation and analysis.
Supports journal data used in Medline applications.
Supports journal data used in Medline applications.
Supports BioSQL database, which is widely used standard database amongst all bioinformatics projects.
Supports BioSQL database, which is widely used standard database amongst all bioinformatics projects.
Supports parser development by providing modules to parse a bioinformatics file into a format specific record object or a generic class of sequence plus features.
Supports parser development by providing modules to parse a bioinformatics file into a format specific record object or a generic class of sequence plus features.
Clear documentation based on cookbook-style.
Clear documentation based on cookbook-style.
Let us check some of the use cases (population genetics, RNA structure, etc.,) and try to understand how Biopython plays an important role in this field −
Population genetics is the study of genetic variation within a population, and involves the examination and modeling of changes in the frequencies of genes and alleles in populations over space and time.
Biopython provides Bio.PopGen module for population genetics. This module contains all the necessary functions to gather information about classic population genetics.
Three major biological macromolecules that are essential for our life are DNA, RNA and Protein. Proteins are the workhorses of the cell and play an important role as enzymes. DNA (deoxyribonucleic acid) is considered as the “blueprint” of the cell. It carries all the genetic information required for the cell to grow, take in nutrients, and propagate. RNA (Ribonucleic acid) acts as “DNA photocopy” in the cell.
Biopython provides Bio.Sequence objects that represents nucleotides, building blocks of DNA and RNA.
This section explains how to install Biopython on your machine. It is very easy to install and it will not take more than five minutes.
Step 1 − Verifying Python Installation
Biopython is designed to work with Python 2.5 or higher versions. So, it is mandatory that python be installed first. Run the below command in your command prompt −
> python --version
It is defined below −
It shows the version of python, if installed properly. Otherwise, download the latest version of the python, install it and then run the command again.
Step 2 − Installing Biopython using pip
It is easy to install Biopython using pip from the command line on all platforms. Type the below command −
> pip install biopython
The following response will be seen on your screen −
For updating an older version of Biopython −
> pip install biopython –-upgrade
The following response will be seen on your screen −
After executing this command, the older versions of Biopython and NumPy (Biopython depends on it) will be removed before installing the recent versions.
Step 3 − Verifying Biopython Installation
Now, you have successfully installed Biopython on your machine. To verify that Biopython is installed properly, type the below command on your python console −
It shows the version of Biopython.
Alternate Way − Installing Biopython using Source
To install Biopython using source code, follow the below instructions −
Download the recent release of Biopython from the following link − https://biopython.org/wiki/Download
As of now, the latest version is biopython-1.72.
Download the file and unpack the compressed archive file, move into the source code folder and type the below command −
> python setup.py build
This will build Biopython from the source code as given below −
Now, test the code using the below command −
> python setup.py test
Finally, install using the below command −
> python setup.py install
Let us create a simple Biopython application to parse a bioinformatics file and print the content. This will help us understand the general concept of the Biopython and how it helps in the field of bioinformatics.
Step 1 − First, create a sample sequence file, “example.fasta” and put the below content into it.
>sp|P25730|FMS1_ECOLI CS1 fimbrial subunit A precursor (CS1 pilin)
MKLKKTIGAMALATLFATMGASAVEKTISVTASVDPTVDLLQSDGSALPNSVALTYSPAV
NNFEAHTINTVVHTNDSDKGVVVKLSADPVLSNVLNPTLQIPVSVNFAGKPLSTTGITID
SNDLNFASSGVNKVSSTQKLSIHADATRVTGGALTAGQYQGLVSIILTKSTTTTTTTKGT
>sp|P15488|FMS3_ECOLI CS3 fimbrial subunit A precursor (CS3 pilin)
MLKIKYLLIGLSLSAMSSYSLAAAGPTLTKELALNVLSPAALDATWAPQDNLTLSNTGVS
NTLVGVLTLSNTSIDTVSIASTNVSDTSKNGTVTFAHETNNSASFATTISTDNANITLDK
NAGNTIVKTTNGSQLPTNLPLKFITTEGNEHLVSGNYRANITITSTIKGGGTKKGTTDKK
The extension, fasta refers to the file format of the sequence file. FASTA originates from the bioinformatics software, FASTA and hence it gets its name. FASTA format has multiple sequence arranged one by one and each sequence will have its own id, name, description and the actual sequence data.
Step 2 − Create a new python script, *simple_example.py" and enter the below code and save it.
from Bio.SeqIO import parse
from Bio.SeqRecord import SeqRecord
from Bio.Seq import Seq
file = open("example.fasta")
records = parse(file, "fasta") for record in records:
print("Id: %s" % record.id)
print("Name: %s" % record.name)
print("Description: %s" % record.description)
print("Annotations: %s" % record.annotations)
print("Sequence Data: %s" % record.seq)
print("Sequence Alphabet: %s" % record.seq.alphabet)
Let us take a little deeper look into the code −
Line 1 imports the parse class available in the Bio.SeqIO module. Bio.SeqIO module is used to read and write the sequence file in different format and `parse’ class is used to parse the content of the sequence file.
Line 2 imports the SeqRecord class available in the Bio.SeqRecord module. This module is used to manipulate sequence records and SeqRecord class is used to represent a particular sequence available in the sequence file.
*Line 3" imports Seq class available in the Bio.Seq module. This module is used to manipulate sequence data and Seq class is used to represent the sequence data of a particular sequence record available in the sequence file.
Line 5 opens the “example.fasta” file using regular python function, open.
Line 7 parse the content of the sequence file and returns the content as the list of SeqRecord object.
Line 9-15 loops over the records using python for loop and prints the attributes of the sequence record (SqlRecord) such as id, name, description, sequence data, etc.
Line 15 prints the sequence’s type using Alphabet class.
Step 3 − Open a command prompt and go to the folder containing sequence file, “example.fasta” and run the below command −
> python simple_example.py
Step 4 − Python runs the script and prints all the sequence data available in the sample file, “example.fasta”. The output will be similar to the following content.
Id: sp|P25730|FMS1_ECOLI
Name: sp|P25730|FMS1_ECOLI
Decription: sp|P25730|FMS1_ECOLI CS1 fimbrial subunit A precursor (CS1 pilin)
Annotations: {}
Sequence Data: MKLKKTIGAMALATLFATMGASAVEKTISVTASVDPTVDLLQSDGSALPNSVALTYSPAVNNFEAHTINTVVHTNDSD
KGVVVKLSADPVLSNVLNPTLQIPVSVNFAGKPLSTTGITIDSNDLNFASSGVNKVSSTQKLSIHADATRVTGGALTA
GQYQGLVSIILTKSTTTTTTTKGT
Sequence Alphabet: SingleLetterAlphabet()
Id: sp|P15488|FMS3_ECOLI
Name: sp|P15488|FMS3_ECOLI
Decription: sp|P15488|FMS3_ECOLI CS3 fimbrial subunit A precursor (CS3 pilin)
Annotations: {}
Sequence Data: MLKIKYLLIGLSLSAMSSYSLAAAGPTLTKELALNVLSPAALDATWAPQDNLTLSNTGVSNTLVGVLTLSNTSIDTVS
IASTNVSDTSKNGTVTFAHETNNSASFATTISTDNANITLDKNAGNTIVKTTNGSQLPTNLPLKFITTEGNEHLVSGN
YRANITITSTIKGGGTKKGTTDKK
Sequence Alphabet: SingleLetterAlphabet()
We have seen three classes, parse, SeqRecord and Seq in this example. These three classes provide most of the functionality and we will learn those classes in the coming section.
A sequence is series of letters used to represent an organism’s protein, DNA or RNA. It is represented by Seq class. Seq class is defined in Bio.Seq module.
Let’s create a simple sequence in Biopython as shown below −
>>> from Bio.Seq import Seq
>>> seq = Seq("AGCT")
>>> seq
Seq('AGCT')
>>> print(seq)
AGCT
Here, we have created a simple protein sequence AGCT and each letter represents Alanine, Glycine, Cysteine and Threonine.
Each Seq object has two important attributes −
data − the actual sequence string (AGCT)
data − the actual sequence string (AGCT)
alphabet − used to represent the type of sequence. e.g. DNA sequence, RNA sequence, etc. By default, it does not represent any sequence and is generic in nature.
alphabet − used to represent the type of sequence. e.g. DNA sequence, RNA sequence, etc. By default, it does not represent any sequence and is generic in nature.
Seq objects contain Alphabet attribute to specify sequence type, letters and possible operations. It is defined in Bio.Alphabet module. Alphabet can be defined as below −
>>> from Bio.Seq import Seq
>>> myseq = Seq("AGCT")
>>> myseq
Seq('AGCT')
>>> myseq.alphabet
Alphabet()
Alphabet module provides below classes to represent different types of sequences. Alphabet - base class for all types of alphabets.
SingleLetterAlphabet - Generic alphabet with letters of size one. It derives from Alphabet and all other alphabets type derives from it.
>>> from Bio.Seq import Seq
>>> from Bio.Alphabet import single_letter_alphabet
>>> test_seq = Seq('AGTACACTGGT', single_letter_alphabet)
>>> test_seq
Seq('AGTACACTGGT', SingleLetterAlphabet())
ProteinAlphabet − Generic single letter protein alphabet.
>>> from Bio.Seq import Seq
>>> from Bio.Alphabet import generic_protein
>>> test_seq = Seq('AGTACACTGGT', generic_protein)
>>> test_seq
Seq('AGTACACTGGT', ProteinAlphabet())
NucleotideAlphabet − Generic single letter nucleotide alphabet.
>>> from Bio.Seq import Seq
>>> from Bio.Alphabet import generic_nucleotide
>>> test_seq = Seq('AGTACACTGGT', generic_nucleotide) >>> test_seq
Seq('AGTACACTGGT', NucleotideAlphabet())
DNAAlphabet − Generic single letter DNA alphabet.
>>> from Bio.Seq import Seq
>>> from Bio.Alphabet import generic_dna
>>> test_seq = Seq('AGTACACTGGT', generic_dna)
>>> test_seq
Seq('AGTACACTGGT', DNAAlphabet())
RNAAlphabet − Generic single letter RNA alphabet.
>>> from Bio.Seq import Seq
>>> from Bio.Alphabet import generic_rna
>>> test_seq = Seq('AGTACACTGGT', generic_rna)
>>> test_seq
Seq('AGTACACTGGT', RNAAlphabet())
Biopython module, Bio.Alphabet.IUPAC provides basic sequence types as defined by IUPAC community. It contains the following classes −
IUPACProtein (protein) − IUPAC protein alphabet of 20 standard amino acids.
IUPACProtein (protein) − IUPAC protein alphabet of 20 standard amino acids.
ExtendedIUPACProtein (extended_protein) − Extended uppercase IUPAC protein single letter alphabet including X.
ExtendedIUPACProtein (extended_protein) − Extended uppercase IUPAC protein single letter alphabet including X.
IUPACAmbiguousDNA (ambiguous_dna) − Uppercase IUPAC ambiguous DNA.
IUPACAmbiguousDNA (ambiguous_dna) − Uppercase IUPAC ambiguous DNA.
IUPACUnambiguousDNA (unambiguous_dna) − Uppercase IUPAC unambiguous DNA (GATC).
IUPACUnambiguousDNA (unambiguous_dna) − Uppercase IUPAC unambiguous DNA (GATC).
ExtendedIUPACDNA (extended_dna) − Extended IUPAC DNA alphabet.
ExtendedIUPACDNA (extended_dna) − Extended IUPAC DNA alphabet.
IUPACAmbiguousRNA (ambiguous_rna) − Uppercase IUPAC ambiguous RNA.
IUPACAmbiguousRNA (ambiguous_rna) − Uppercase IUPAC ambiguous RNA.
IUPACUnambiguousRNA (unambiguous_rna) − Uppercase IUPAC unambiguous RNA (GAUC).
IUPACUnambiguousRNA (unambiguous_rna) − Uppercase IUPAC unambiguous RNA (GAUC).
Consider a simple example for IUPACProtein class as shown below −
>>> from Bio.Alphabet import IUPAC
>>> protein_seq = Seq("AGCT", IUPAC.protein)
>>> protein_seq
Seq('AGCT', IUPACProtein())
>>> protein_seq.alphabet
Also, Biopython exposes all the bioinformatics related configuration data through Bio.Data module. For example, IUPACData.protein_letters has the possible letters of IUPACProtein alphabet.
>>> from Bio.Data import IUPACData
>>> IUPACData.protein_letters
'ACDEFGHIKLMNPQRSTVWY'
This section briefly explains about all the basic operations available in the Seq class. Sequences are similar to python strings. We can perform python string operations like slicing, counting, concatenation, find, split and strip in sequences.
Use the below codes to get various outputs.
To get the first value in sequence.
>>> seq_string = Seq("AGCTAGCT")
>>> seq_string[0]
'A'
To print the first two values.
>>> seq_string[0:2]
Seq('AG')
To print all the values.
>>> seq_string[ : ]
Seq('AGCTAGCT')
To perform length and count operations.
>>> len(seq_string)
8
>>> seq_string.count('A')
2
To add two sequences.
>>> from Bio.Alphabet import generic_dna, generic_protein
>>> seq1 = Seq("AGCT", generic_dna)
>>> seq2 = Seq("TCGA", generic_dna)
>>> seq1+seq2
Seq('AGCTTCGA', DNAAlphabet())
Here, the above two sequence objects, seq1, seq2 are generic DNA sequences and so you can add them and produce new sequence. You can’t add sequences with incompatible alphabets, such as a protein sequence and a DNA sequence as specified below −
>>> dna_seq = Seq('AGTACACTGGT', generic_dna)
>>> protein_seq = Seq('AGUACACUGGU', generic_protein)
>>> dna_seq + protein_seq
.....
.....
TypeError: Incompatible alphabets DNAAlphabet() and ProteinAlphabet()
>>>
To add two or more sequences, first store it in a python list, then retrieve it using ‘for loop’ and finally add it together as shown below −
>>> from Bio.Alphabet import generic_dna
>>> list = [Seq("AGCT",generic_dna),Seq("TCGA",generic_dna),Seq("AAA",generic_dna)]
>>> for s in list:
... print(s)
...
AGCT
TCGA
AAA
>>> final_seq = Seq(" ",generic_dna)
>>> for s in list:
... final_seq = final_seq + s
...
>>> final_seq
Seq('AGCTTCGAAAA', DNAAlphabet())
In the below section, various codes are given to get outputs based on the requirement.
To change the case of sequence.
>>> from Bio.Alphabet import generic_rna
>>> rna = Seq("agct", generic_rna)
>>> rna.upper()
Seq('AGCT', RNAAlphabet())
To check python membership and identity operator.
>>> rna = Seq("agct", generic_rna)
>>> 'a' in rna
True
>>> 'A' in rna
False
>>> rna1 = Seq("AGCT", generic_dna)
>>> rna is rna1
False
To find single letter or sequence of letter inside the given sequence.
>>> protein_seq = Seq('AGUACACUGGU', generic_protein)
>>> protein_seq.find('G')
1
>>> protein_seq.find('GG')
8
To perform splitting operation.
>>> protein_seq = Seq('AGUACACUGGU', generic_protein)
>>> protein_seq.split('A')
[Seq('', ProteinAlphabet()), Seq('GU', ProteinAlphabet()),
Seq('C', ProteinAlphabet()), Seq('CUGGU', ProteinAlphabet())]
To perform strip operations in the sequence.
>>> strip_seq = Seq(" AGCT ")
>>> strip_seq
Seq(' AGCT ')
>>> strip_seq.strip()
Seq('AGCT')
In this chapter, we shall discuss some of the advanced sequence features provided by Biopython.
Nucleotide sequence can be reverse complemented to get new sequence. Also, the complemented sequence can be reverse complemented to get the original sequence. Biopython provides two methods to do this functionality − complement and reverse_complement. The code for this is given below −
>>> from Bio.Alphabet import IUPAC
>>> nucleotide = Seq('TCGAAGTCAGTC', IUPAC.ambiguous_dna)
>>> nucleotide.complement()
Seq('AGCTTCAGTCAG', IUPACAmbiguousDNA())
>>>
Here, the complement() method allows to complement a DNA or RNA sequence. The reverse_complement() method complements and reverses the resultant sequence from left to right. It is shown below −
>>> nucleotide.reverse_complement()
Seq('GACTGACTTCGA', IUPACAmbiguousDNA())
Biopython uses the ambiguous_dna_complement variable provided by Bio.Data.IUPACData to do the complement operation.
>>> from Bio.Data import IUPACData
>>> import pprint
>>> pprint.pprint(IUPACData.ambiguous_dna_complement) {
'A': 'T',
'B': 'V',
'C': 'G',
'D': 'H',
'G': 'C',
'H': 'D',
'K': 'M',
'M': 'K',
'N': 'N',
'R': 'Y',
'S': 'S',
'T': 'A',
'V': 'B',
'W': 'W',
'X': 'X',
'Y': 'R'}
>>>
Genomic DNA base composition (GC content) is predicted to significantly affect genome functioning and species ecology. The GC content is the number of GC nucleotides divided by the total nucleotides.
To get the GC nucleotide content, import the following module and perform the following steps −
>>> from Bio.SeqUtils import GC
>>> nucleotide = Seq("GACTGACTTCGA",IUPAC.unambiguous_dna)
>>> GC(nucleotide)
50.0
Transcription is the process of changing DNA sequence into RNA sequence. The actual biological transcription process is performing a reverse complement (TCAG → CUGA) to get the mRNA considering the DNA as template strand. However, in bioinformatics and so in Biopython, we typically work directly with the coding strand and we can get the mRNA sequence by changing the letter T to U.
Simple example for the above is as follows −
>>> from Bio.Seq import Seq
>>> from Bio.Seq import transcribe
>>> from Bio.Alphabet import IUPAC
>>> dna_seq = Seq("ATGCCGATCGTAT",IUPAC.unambiguous_dna) >>> transcribe(dna_seq)
Seq('AUGCCGAUCGUAU', IUPACUnambiguousRNA())
>>>
To reverse the transcription, T is changed to U as shown in the code below −
>>> rna_seq = transcribe(dna_seq)
>>> rna_seq.back_transcribe()
Seq('ATGCCGATCGTAT', IUPACUnambiguousDNA())
To get the DNA template strand, reverse_complement the back transcribed RNA as given below −
>>> rna_seq.back_transcribe().reverse_complement()
Seq('ATACGATCGGCAT', IUPACUnambiguousDNA())
Translation is a process of translating RNA sequence to protein sequence. Consider a RNA sequence as shown below −
>>> rna_seq = Seq("AUGGCCAUUGUAAU",IUPAC.unambiguous_rna)
>>> rna_seq
Seq('AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAG', IUPACUnambiguousRNA())
Now, apply translate() function to the code above −
>>> rna_seq.translate()
Seq('MAIV', IUPACProtein())
The above RNA sequence is simple. Consider RNA sequence, AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGA and apply translate() −
>>> rna = Seq('AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGA', IUPAC.unambiguous_rna)
>>> rna.translate()
Seq('MAIVMGR*KGAR', HasStopCodon(IUPACProtein(), '*'))
Here, the stop codons are indicated with an asterisk ’*’.
It is possible in translate() method to stop at the first stop codon. To perform this, you can assign to_stop=True in translate() as follows −
>>> rna.translate(to_stop = True)
Seq('MAIVMGR', IUPACProtein())
Here, the stop codon is not included in the resulting sequence because it does not contain one.
The Genetic Codes page of the NCBI provides full list of translation tables used by Biopython. Let us see an example for standard table to visualize the code −
>>> from Bio.Data import CodonTable
>>> table = CodonTable.unambiguous_dna_by_name["Standard"]
>>> print(table)
Table 1 Standard, SGC0
| T | C | A | G |
--+---------+---------+---------+---------+--
T | TTT F | TCT S | TAT Y | TGT C | T
T | TTC F | TCC S | TAC Y | TGC C | C
T | TTA L | TCA S | TAA Stop| TGA Stop| A
T | TTG L(s)| TCG S | TAG Stop| TGG W | G
--+---------+---------+---------+---------+--
C | CTT L | CCT P | CAT H | CGT R | T
C | CTC L | CCC P | CAC H | CGC R | C
C | CTA L | CCA P | CAA Q | CGA R | A
C | CTG L(s)| CCG P | CAG Q | CGG R | G
--+---------+---------+---------+---------+--
A | ATT I | ACT T | AAT N | AGT S | T
A | ATC I | ACC T | AAC N | AGC S | C
A | ATA I | ACA T | AAA K | AGA R | A
A | ATG M(s)| ACG T | AAG K | AGG R | G
--+---------+---------+---------+---------+--
G | GTT V | GCT A | GAT D | GGT G | T
G | GTC V | GCC A | GAC D | GGC G | C
G | GTA V | GCA A | GAA E | GGA G | A
G | GTG V | GCG A | GAG E | GGG G | G
--+---------+---------+---------+---------+--
>>>
Biopython uses this table to translate the DNA to protein as well as to find the Stop codon.
Biopython provides a module, Bio.SeqIO to read and write sequences from and to a file (any stream) respectively. It supports nearly all file formats available in bioinformatics. Most of the software provides different approach for different file formats. But, Biopython consciously follows a single approach to present the parsed sequence data to the user through its SeqRecord object.
Let us learn more about SeqRecord in the following section.
Bio.SeqRecord module provides SeqRecord to hold meta information of the sequence as well as the sequence data itself as given below −
seq − It is an actual sequence.
seq − It is an actual sequence.
id − It is the primary identifier of the given sequence. The default type is string.
id − It is the primary identifier of the given sequence. The default type is string.
name − It is the Name of the sequence. The default type is string.
name − It is the Name of the sequence. The default type is string.
description − It displays human readable information about the sequence.
description − It displays human readable information about the sequence.
annotations − It is a dictionary of additional information about the sequence.
annotations − It is a dictionary of additional information about the sequence.
The SeqRecord can be imported as specified below
from Bio.SeqRecord import SeqRecord
Let us understand the nuances of parsing the sequence file using real sequence file in the coming sections.
This section explains about how to parse two of the most popular sequence file formats, FASTA and GenBank.
FASTA is the most basic file format for storing sequence data. Originally, FASTA is a software package for sequence alignment of DNA and protein developed during the early evolution of Bioinformatics and used mostly to search the sequence similarity.
Biopython provides an example FASTA file and it can be accessed at https://github.com/biopython/biopython/blob/master/Doc/examples/ls_orchid.fasta.
Download and save this file into your Biopython sample directory as ‘orchid.fasta’.
Bio.SeqIO module provides parse() method to process sequence files and can be imported as follows −
from Bio.SeqIO import parse
parse() method contains two arguments, first one is file handle and second is file format.
>>> file = open('path/to/biopython/sample/orchid.fasta')
>>> for record in parse(file, "fasta"):
... print(record.id)
...
gi|2765658|emb|Z78533.1|CIZ78533
gi|2765657|emb|Z78532.1|CCZ78532
..........
..........
gi|2765565|emb|Z78440.1|PPZ78440
gi|2765564|emb|Z78439.1|PBZ78439
>>>
Here, the parse() method returns an iterable object which returns SeqRecord on every iteration. Being iterable, it provides lot of sophisticated and easy methods and let us see some of the features.
next() method returns the next item available in the iterable object, which we can be used to get the first sequence as given below −
>>> first_seq_record = next(SeqIO.parse(open('path/to/biopython/sample/orchid.fasta'),'fasta'))
>>> first_seq_record.id 'gi|2765658|emb|Z78533.1|CIZ78533'
>>> first_seq_record.name 'gi|2765658|emb|Z78533.1|CIZ78533'
>>> first_seq_record.seq Seq('CGTAACAAGGTTTCCGTAGGTGAACCTGCGGAAGGATCATTGATGAGACCGTGG...CGC', SingleLetterAlphabet())
>>> first_seq_record.description 'gi|2765658|emb|Z78533.1|CIZ78533 C.irapeanum 5.8S rRNA gene and ITS1 and ITS2 DNA'
>>> first_seq_record.annotations
{}
>>>
Here, seq_record.annotations is empty because the FASTA format does not support sequence annotations.
We can convert the iterable object into list using list comprehension as given below
>>> seq_iter = SeqIO.parse(open('path/to/biopython/sample/orchid.fasta'),'fasta')
>>> all_seq = [seq_record for seq_record in seq_iter] >>> len(all_seq)
94
>>>
Here, we have used len method to get the total count. We can get sequence with maximum length as follows −
>>> seq_iter = SeqIO.parse(open('path/to/biopython/sample/orchid.fasta'),'fasta')
>>> max_seq = max(len(seq_record.seq) for seq_record in seq_iter)
>>> max_seq
789
>>>
We can filter the sequence as well using the below code −
>>> seq_iter = SeqIO.parse(open('path/to/biopython/sample/orchid.fasta'),'fasta')
>>> seq_under_600 = [seq_record for seq_record in seq_iter if len(seq_record.seq) < 600]
>>> for seq in seq_under_600:
... print(seq.id)
...
gi|2765606|emb|Z78481.1|PIZ78481
gi|2765605|emb|Z78480.1|PGZ78480
gi|2765601|emb|Z78476.1|PGZ78476
gi|2765595|emb|Z78470.1|PPZ78470
gi|2765594|emb|Z78469.1|PHZ78469
gi|2765564|emb|Z78439.1|PBZ78439
>>>
Writing a collection of SqlRecord objects (parsed data) into file is as simple as calling the SeqIO.write method as below −
file = open("converted.fasta", "w)
SeqIO.write(seq_record, file, "fasta")
This method can be effectively used to convert the format as specified below −
file = open("converted.gbk", "w)
SeqIO.write(seq_record, file, "genbank")
It is a richer sequence format for genes and includes fields for various kinds of annotations. Biopython provides an example GenBank file and it can be accessed at https://github.com/biopython/biopython/blob/master/Doc/examples/ls_orchid.fasta.
Download and save file into your Biopython sample directory as ‘orchid.gbk’
Since, Biopython provides a single function, parse to parse all bioinformatics format. Parsing GenBank format is as simple as changing the format option in the parse method.
The code for the same has been given below −
>>> from Bio import SeqIO
>>> from Bio.SeqIO import parse
>>> seq_record = next(parse(open('path/to/biopython/sample/orchid.gbk'),'genbank'))
>>> seq_record.id
'Z78533.1'
>>> seq_record.name
'Z78533'
>>> seq_record.seq Seq('CGTAACAAGGTTTCCGTAGGTGAACCTGCGGAAGGATCATTGATGAGACCGTGG...CGC', IUPACAmbiguousDNA())
>>> seq_record.description
'C.irapeanum 5.8S rRNA gene and ITS1 and ITS2 DNA'
>>> seq_record.annotations {
'molecule_type': 'DNA',
'topology': 'linear',
'data_file_division': 'PLN',
'date': '30-NOV-2006',
'accessions': ['Z78533'],
'sequence_version': 1,
'gi': '2765658',
'keywords': ['5.8S ribosomal RNA', '5.8S rRNA gene', 'internal transcribed spacer', 'ITS1', 'ITS2'],
'source': 'Cypripedium irapeanum',
'organism': 'Cypripedium irapeanum',
'taxonomy': [
'Eukaryota',
'Viridiplantae',
'Streptophyta',
'Embryophyta',
'Tracheophyta',
'Spermatophyta',
'Magnoliophyta',
'Liliopsida',
'Asparagales',
'Orchidaceae',
'Cypripedioideae',
'Cypripedium'],
'references': [
Reference(title = 'Phylogenetics of the slipper orchids (Cypripedioideae:
Orchidaceae): nuclear rDNA ITS sequences', ...),
Reference(title = 'Direct Submission', ...)
]
}
Sequence alignment is the process of arranging two or more sequences (of DNA, RNA or protein sequences) in a specific order to identify the region of similarity between them.
Identifying the similar region enables us to infer a lot of information like what traits are conserved between species, how close different species genetically are, how species evolve, etc. Biopython provides extensive support for sequence alignment.
Let us learn some of the important features provided by Biopython in this chapter −
Biopython provides a module, Bio.AlignIO to read and write sequence alignments. In bioinformatics, there are lot of formats available to specify the sequence alignment data similar to earlier learned sequence data. Bio.AlignIO provides API similar to Bio.SeqIO except that the Bio.SeqIO works on the sequence data and Bio.AlignIO works on the sequence alignment data.
Before starting to learn, let us download a sample sequence alignment file from the Internet.
To download the sample file, follow the below steps −
Step 1 − Open your favorite browser and go to http://pfam.xfam.org/family/browse website. It will show all the Pfam families in alphabetical order.
Step 2 − Choose any one family having less number of seed value. It contains minimal data and enables us to work easily with the alignment. Here, we have selected/clicked PF18225 and it opens go to http://pfam.xfam.org/family/PF18225 and shows complete details about it, including sequence alignments.
Step 3 − Go to alignment section and download the sequence alignment file in Stockholm format (PF18225_seed.txt).
Let us try to read the downloaded sequence alignment file using Bio.AlignIO as below −
>>> from Bio import AlignIO
Read alignment using read method. read method is used to read single alignment data available in the given file. If the given file contain many alignment, we can use parse method. parse method returns iterable alignment object similar to parse method in Bio.SeqIO module.
>>> alignment = AlignIO.read(open("PF18225_seed.txt"), "stockholm")
>>> print(alignment)
SingleLetterAlphabet() alignment with 6 rows and 65 columns
MQNTPAERLPAIIEKAKSKHDINVWLLDRQGRDLLEQRVPAKVA...EGP B7RZ31_9GAMM/59-123
AKQRGIAGLEEWLHRLDHSEAIPIFLIDEAGKDLLEREVPADIT...KKP A0A0C3NPG9_9PROT/58-119
ARRHGQEYFQQWLERQPKKVKEQVFAVDQFGRELLGRPLPEDMA...KKP A0A143HL37_9GAMM/57-121
TRRHGPESFRFWLERQPVEARDRIYAIDRSGAEILDRPIPRGMA...NKP A0A0X3UC67_9GAMM/57-121
AINRNTQQLTQDLRAMPNWSLRFVYIVDRNNQDLLKRPLPPGIM...NRK B3PFT7_CELJU/62-126
AVNATEREFTERIRTLPHWARRNVFVLDSQGFEIFDRELPSPVA...NRT K4KEM7_SIMAS/61-125
>>>
We can also check the sequences (SeqRecord) available in the alignment as well as below −
>>> for align in alignment:
... print(align.seq)
...
MQNTPAERLPAIIEKAKSKHDINVWLLDRQGRDLLEQRVPAKVATVANQLRGRKRRAFARHREGP
AKQRGIAGLEEWLHRLDHSEAIPIFLIDEAGKDLLEREVPADITA---RLDRRREHGEHGVRKKP
ARRHGQEYFQQWLERQPKKVKEQVFAVDQFGRELLGRPLPEDMAPMLIALNYRNRESHAQVDKKP
TRRHGPESFRFWLERQPVEARDRIYAIDRSGAEILDRPIPRGMAPLFKVLSFRNREDQGLVNNKP
AINRNTQQLTQDLRAMPNWSLRFVYIVDRNNQDLLKRPLPPGIMVLAPRLTAKHPYDKVQDRNRK
AVNATEREFTERIRTLPHWARRNVFVLDSQGFEIFDRELPSPVADLMRKLDLDRPFKKLERKNRT
>>>
In general, most of the sequence alignment files contain single alignment data and it is enough to use read method to parse it. In multiple sequence alignment concept, two or more sequences are compared for best subsequence matches between them and results in multiple sequence alignment in a single file.
If the input sequence alignment format contains more than one sequence alignment, then we need to use parse method instead of read method as specified below −
>>> from Bio import AlignIO
>>> alignments = AlignIO.parse(open("PF18225_seed.txt"), "stockholm")
>>> print(alignments)
<generator object parse at 0x000001CD1C7E0360>
>>> for alignment in alignments:
... print(alignment)
...
SingleLetterAlphabet() alignment with 6 rows and 65 columns
MQNTPAERLPAIIEKAKSKHDINVWLLDRQGRDLLEQRVPAKVA...EGP B7RZ31_9GAMM/59-123
AKQRGIAGLEEWLHRLDHSEAIPIFLIDEAGKDLLEREVPADIT...KKP A0A0C3NPG9_9PROT/58-119
ARRHGQEYFQQWLERQPKKVKEQVFAVDQFGRELLGRPLPEDMA...KKP A0A143HL37_9GAMM/57-121
TRRHGPESFRFWLERQPVEARDRIYAIDRSGAEILDRPIPRGMA...NKP A0A0X3UC67_9GAMM/57-121
AINRNTQQLTQDLRAMPNWSLRFVYIVDRNNQDLLKRPLPPGIM...NRK B3PFT7_CELJU/62-126
AVNATEREFTERIRTLPHWARRNVFVLDSQGFEIFDRELPSPVA...NRT K4KEM7_SIMAS/61-125
>>>
Here, parse method returns iterable alignment object and it can be iterated to get actual alignments.
Pairwise sequence alignment compares only two sequences at a time and provides best possible sequence alignments. Pairwise is easy to understand and exceptional to infer from the resulting sequence alignment.
Biopython provides a special module, Bio.pairwise2 to identify the alignment sequence using pairwise method. Biopython applies the best algorithm to find the alignment sequence and it is par with other software.
Let us write an example to find the sequence alignment of two simple and hypothetical sequences using pairwise module. This will help us understand the concept of sequence alignment and how to program it using Biopython.
Import the module pairwise2 with the command given below −
>>> from Bio import pairwise2
Create two sequences, seq1 and seq2 −
>>> from Bio.Seq import Seq
>>> seq1 = Seq("ACCGGT")
>>> seq2 = Seq("ACGT")
Call method pairwise2.align.globalxx along with seq1 and seq2 to find the alignments using the below line of code −
>>> alignments = pairwise2.align.globalxx(seq1, seq2)
Here, globalxx method performs the actual work and finds all the best possible alignments in the given sequences. Actually, Bio.pairwise2 provides quite a set of methods which follows the below convention to find alignments in different scenarios.
<sequence alignment type>XY
Here, the sequence alignment type refers to the alignment type which may be global or local. global type is finding sequence alignment by taking entire sequence into consideration. local type is finding sequence alignment by looking into the subset of the given sequences as well. This will be tedious but provides better idea about the similarity between the given sequences.
X refers to matching score. The possible values are x (exact match), m (score based on identical chars), d (user provided dictionary with character and match score) and finally c (user defined function to provide custom scoring algorithm).
X refers to matching score. The possible values are x (exact match), m (score based on identical chars), d (user provided dictionary with character and match score) and finally c (user defined function to provide custom scoring algorithm).
Y refers to gap penalty. The possible values are x (no gap penalties), s (same penalties for both sequences), d (different penalties for each sequence) and finally c (user defined function to provide custom gap penalties)
Y refers to gap penalty. The possible values are x (no gap penalties), s (same penalties for both sequences), d (different penalties for each sequence) and finally c (user defined function to provide custom gap penalties)
So, localds is also a valid method, which finds the sequence alignment using local alignment technique, user provided dictionary for matches and user provided gap penalty for both sequences.
>>> test_alignments = pairwise2.align.localds(seq1, seq2, blosum62, -10, -1)
Here, blosum62 refers to a dictionary available in the pairwise2 module to provide match score. -10 refers to gap open penalty and -1 refers to gap extension penalty.
Loop over the iterable alignments object and get each individual alignment object and print it.
>>> for alignment in alignments:
... print(alignment)
...
('ACCGGT', 'A-C-GT', 4.0, 0, 6)
('ACCGGT', 'AC--GT', 4.0, 0, 6)
('ACCGGT', 'A-CG-T', 4.0, 0, 6)
('ACCGGT', 'AC-G-T', 4.0, 0, 6)
Bio.pairwise2 module provides a formatting method, format_alignment to better visualize the result −
>>> from Bio.pairwise2 import format_alignment
>>> alignments = pairwise2.align.globalxx(seq1, seq2)
>>> for alignment in alignments:
... print(format_alignment(*alignment))
...
ACCGGT
| | ||
A-C-GT
Score=4
ACCGGT
|| ||
AC--GT
Score=4
ACCGGT
| || |
A-CG-T
Score=4
ACCGGT
|| | |
AC-G-T
Score=4
>>>
Biopython also provides another module to do sequence alignment, Align. This module provides a different set of API to simply the setting of parameter like algorithm, mode, match score, gap penalties, etc., A simple look into the Align object is as follows −
>>> from Bio import Align
>>> aligner = Align.PairwiseAligner()
>>> print(aligner)
Pairwise sequence aligner with parameters
match score: 1.000000
mismatch score: 0.000000
target open gap score: 0.000000
target extend gap score: 0.000000
target left open gap score: 0.000000
target left extend gap score: 0.000000
target right open gap score: 0.000000
target right extend gap score: 0.000000
query open gap score: 0.000000
query extend gap score: 0.000000
query left open gap score: 0.000000
query left extend gap score: 0.000000
query right open gap score: 0.000000
query right extend gap score: 0.000000
mode: global
>>>
Biopython provides interface to a lot of sequence alignment tools through Bio.Align.Applications module. Some of the tools are listed below −
ClustalW
MUSCLE
EMBOSS needle and water
Let us write a simple example in Biopython to create sequence alignment through the most popular alignment tool, ClustalW.
Step 1 − Download the Clustalw program from http://www.clustal.org/download/current/ and install it. Also, update the system PATH with the “clustal” installation path.
Step 2 − import ClustalwCommanLine from module Bio.Align.Applications.
>>> from Bio.Align.Applications import ClustalwCommandline
Step 3 − Set cmd by calling ClustalwCommanLine with input file, opuntia.fasta available in Biopython package.
https://raw.githubusercontent.com/biopython/biopython/master/Doc/examples/opuntia.fasta
>>> cmd = ClustalwCommandline("clustalw2",
infile="/path/to/biopython/sample/opuntia.fasta")
>>> print(cmd)
clustalw2 -infile=fasta/opuntia.fasta
Step 4 − Calling cmd() will run the clustalw command and give an output of the resultant
alignment file, opuntia.aln.
>>> stdout, stderr = cmd()
Step 5 − Read and print the alignment file as below −
>>> from Bio import AlignIO
>>> align = AlignIO.read("/path/to/biopython/sample/opuntia.aln", "clustal")
>>> print(align)
SingleLetterAlphabet() alignment with 7 rows and 906 columns
TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA
gi|6273285|gb|AF191659.1|AF191
TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA
gi|6273284|gb|AF191658.1|AF191
TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA
gi|6273287|gb|AF191661.1|AF191
TATACATAAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA
gi|6273286|gb|AF191660.1|AF191
TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA
gi|6273290|gb|AF191664.1|AF191
TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA
gi|6273289|gb|AF191663.1|AF191
TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA
gi|6273291|gb|AF191665.1|AF191
>>>
BLAST stands for Basic Local Alignment Search Tool. It finds regions of similarity between biological sequences. Biopython provides Bio.Blast module to deal with NCBI BLAST operation. You can run BLAST in either local connection or over Internet connection.
Let us understand these two connections in brief in the following section −
Biopython provides Bio.Blast.NCBIWWW module to call the online version of BLAST. To do this, we need to import the following module −
>>> from Bio.Blast import NCBIWWW
NCBIWW module provides qblast function to query the BLAST online version, https://blast.ncbi.nlm.nih.gov/Blast.cgi. qblast supports all the parameters supported by the online version.
To obtain any help about this module, use the below command and understand the features −
>>> help(NCBIWWW.qblast)
Help on function qblast in module Bio.Blast.NCBIWWW:
qblast(
program, database, sequence,
url_base = 'https://blast.ncbi.nlm.nih.gov/Blast.cgi',
auto_format = None,
composition_based_statistics = None,
db_genetic_code = None,
endpoints = None,
entrez_query = '(none)',
expect = 10.0,
filter = None,
gapcosts = None,
genetic_code = None,
hitlist_size = 50,
i_thresh = None,
layout = None,
lcase_mask = None,
matrix_name = None,
nucl_penalty = None,
nucl_reward = None,
other_advanced = None,
perc_ident = None,
phi_pattern = None,
query_file = None,
query_believe_defline = None,
query_from = None,
query_to = None,
searchsp_eff = None,
service = None,
threshold = None,
ungapped_alignment = None,
word_size = None,
alignments = 500,
alignment_view = None,
descriptions = 500,
entrez_links_new_window = None,
expect_low = None,
expect_high = None,
format_entrez_query = None,
format_object = None,
format_type = 'XML',
ncbi_gi = None,
results_file = None,
show_overview = None,
megablast = None,
template_type = None,
template_length = None
)
BLAST search using NCBI's QBLAST server or a cloud service provider.
Supports all parameters of the qblast API for Put and Get.
Please note that BLAST on the cloud supports the NCBI-BLAST Common
URL API (http://ncbi.github.io/blast-cloud/dev/api.html).
To use this feature, please set url_base to 'http://host.my.cloud.service.provider.com/cgi-bin/blast.cgi' and
format_object = 'Alignment'. For more details, please see 8. Biopython – Overview of BLAST
https://blast.ncbi.nlm.nih.gov/Blast.cgi?PAGE_TYPE = BlastDocs&DOC_TYPE = CloudBlast
Some useful parameters:
- program blastn, blastp, blastx, tblastn, or tblastx (lower case)
- database Which database to search against (e.g. "nr").
- sequence The sequence to search.
- ncbi_gi TRUE/FALSE whether to give 'gi' identifier.
- descriptions Number of descriptions to show. Def 500.
- alignments Number of alignments to show. Def 500.
- expect An expect value cutoff. Def 10.0.
- matrix_name Specify an alt. matrix (PAM30, PAM70, BLOSUM80, BLOSUM45).
- filter "none" turns off filtering. Default no filtering
- format_type "HTML", "Text", "ASN.1", or "XML". Def. "XML".
- entrez_query Entrez query to limit Blast search
- hitlist_size Number of hits to return. Default 50
- megablast TRUE/FALSE whether to use MEga BLAST algorithm (blastn only)
- service plain, psi, phi, rpsblast, megablast (lower case)
This function does no checking of the validity of the parameters
and passes the values to the server as is. More help is available at:
https://ncbi.github.io/blast-cloud/dev/api.html
Usually, the arguments of the qblast function are basically analogous to different parameters that you can set on the BLAST web page. This makes the qblast function easy to understand as well as reduces the learning curve to use it.
To understand the process of connecting and searching BLAST online version, let us do a simple sequence search (available in our local sequence file) against online BLAST server through Biopython.
Step 1 − Create a file named blast_example.fasta in the Biopython directory and give the below sequence information as input
Example of a single sequence in FASTA/Pearson format:
>sequence A ggtaagtcctctagtacaaacacccccaatattgtgatataattaaaattatattcatat
tctgttgccagaaaaaacacttttaggctatattagagccatcttctttgaagcgttgtc
>sequence B ggtaagtcctctagtacaaacacccccaatattgtgatataattaaaattatattca
tattctgttgccagaaaaaacacttttaggctatattagagccatcttctttgaagcgttgtc
Step 2 − Import the NCBIWWW module.
>>> from Bio.Blast import NCBIWWW
Step 3 − Open the sequence file, blast_example.fasta using python IO module.
>>> sequence_data = open("blast_example.fasta").read()
>>> sequence_data
'Example of a single sequence in FASTA/Pearson format:\n\n\n> sequence
A\nggtaagtcctctagtacaaacacccccaatattgtgatataattaaaatt
atattcatat\ntctgttgccagaaaaaacacttttaggctatattagagccatcttctttg aagcgttgtc\n\n'
Step 4 − Now, call the qblast function passing sequence data as main parameter. The other parameter represents the database (nt) and the internal program (blastn).
>>> result_handle = NCBIWWW.qblast("blastn", "nt", sequence_data)
>>> result_handle
<_io.StringIO object at 0x000001EC9FAA4558>
blast_results holds the result of our search. It can be saved to a file for later use and also, parsed to get the details. We will learn how to do it in the coming section.
Step 5 − The same functionality can be done using Seq object as well rather than using the whole fasta file as shown below −
>>> from Bio import SeqIO
>>> seq_record = next(SeqIO.parse(open('blast_example.fasta'),'fasta'))
>>> seq_record.id
'sequence'
>>> seq_record.seq
Seq('ggtaagtcctctagtacaaacacccccaatattgtgatataattaaaattatat...gtc',
SingleLetterAlphabet())
Now, call the qblast function passing Seq object, record.seq as main parameter.
>>> result_handle = NCBIWWW.qblast("blastn", "nt", seq_record.seq)
>>> print(result_handle)
<_io.StringIO object at 0x000001EC9FAA4558>
BLAST will assign an identifier for your sequence automatically.
Step 6 − result_handle object will have the entire result and can be saved into a file for later usage.
>>> with open('results.xml', 'w') as save_file:
>>> blast_results = result_handle.read()
>>> save_file.write(blast_results)
We will see how to parse the result file in the later section.
This section explains about how to run BLAST in local system. If you run BLAST in local system, it may be faster and also allows you to create your own database to search against sequences.
In general, running BLAST locally is not recommended due to its large size, extra effort needed to run the software, and the cost involved. Online BLAST is sufficient for basic and advanced purposes. Of course, sometime you may be required to install it locally.
Consider you are conducting frequent searches online which may require a lot of time and high network volume and if you have proprietary sequence data or IP related issues, then installing it locally is recommended.
To do this, we need to follow the below steps −
Step 1 − Download and install the latest blast binary using the given link − ftp://ftp.ncbi.nlm.nih.gov/blast/executables/blast+/LATEST/
Step 2 − Download and unpack the latest and necessary database using the below link − ftp://ftp.ncbi.nlm.nih.gov/blast/db/
BLAST software provides lot of databases in their site. Let us download alu.n.gz file from the blast database site and unpack it into alu folder. This file is in FASTA format. To use this file in our blast application, we need to first convert the file from FASTA format into blast database format. BLAST provides makeblastdb application to do this conversion.
Use the below code snippet −
cd /path/to/alu
makeblastdb -in alu.n -parse_seqids -dbtype nucl -out alun
Running the above code will parse the input file, alu.n and create BLAST database as multiple files alun.nsq, alun.nsi, etc. Now, we can query this database to find the sequence.
We have installed the BLAST in our local server and also have sample BLAST database, alun to query against it.
Step 3 − Let us create a sample sequence file to query the database. Create a file search.fsa and put the below data into it.
>gnl|alu|Z15030_HSAL001056 (Alu-J)
AGGCTGGCACTGTGGCTCATGCTGAAATCCCAGCACGGCGGAGGACGGCGGAAGATTGCT
TGAGCCTAGGAGTTTGCGACCAGCCTGGGTGACATAGGGAGATGCCTGTCTCTACGCAAA
AGAAAAAAAAAATAGCTCTGCTGGTGGTGCATGCCTATAGTCTCAGCTATCAGGAGGCTG
GGACAGGAGGATCACTTGGGCCCGGGAGTTGAGGCTGTGGTGAGCCACGATCACACCACT
GCACTCCAGCCTGGGTGACAGAGCAAGACCCTGTCTCAAAACAAACAAATAA
>gnl|alu|D00596_HSAL003180 (Alu-Sx)
AGCCAGGTGTGGTGGCTCACGCCTGTAATCCCACCGCTTTGGGAGGCTGAGTCAGATCAC
CTGAGGTTAGGAATTTGGGACCAGCCTGGCCAACATGGCGACACCCCAGTCTCTACTAAT
AACACAAAAAATTAGCCAGGTGTGCTGGTGCATGTCTGTAATCCCAGCTACTCAGGAGGC
TGAGGCATGAGAATTGCTCACGAGGCGGAGGTTGTAGTGAGCTGAGATCGTGGCACTGTA
CTCCAGCCTGGCGACAGAGGGAGAACCCATGTCAAAAACAAAAAAAGACACCACCAAAGG
TCAAAGCATA
>gnl|alu|X55502_HSAL000745 (Alu-J)
TGCCTTCCCCATCTGTAATTCTGGCACTTGGGGAGTCCAAGGCAGGATGATCACTTATGC
CCAAGGAATTTGAGTACCAAGCCTGGGCAATATAACAAGGCCCTGTTTCTACAAAAACTT
TAAACAATTAGCCAGGTGTGGTGGTGCGTGCCTGTGTCCAGCTACTCAGGAAGCTGAGGC
AAGAGCTTGAGGCTACAGTGAGCTGTGTTCCACCATGGTGCTCCAGCCTGGGTGACAGGG
CAAGACCCTGTCAAAAGAAAGGAAGAAAGAACGGAAGGAAAGAAGGAAAGAAACAAGGAG
AG
The sequence data are gathered from the alu.n file; hence, it matches with our database.
Step 4 − BLAST software provides many applications to search the database and we use blastn. blastn application requires minimum of three arguments, db, query and out. db refers to the database against to search; query is the sequence to match and out is the file to store results. Now, run the below command to perform this simple query −
blastn -db alun -query search.fsa -out results.xml -outfmt 5
Running the above command will search and give output in the results.xml file as given below (partially data) −
<?xml version = "1.0"?>
<!DOCTYPE BlastOutput PUBLIC "-//NCBI//NCBI BlastOutput/EN"
"http://www.ncbi.nlm.nih.gov/dtd/NCBI_BlastOutput.dtd">
<BlastOutput>
<BlastOutput_program>blastn</BlastOutput_program>
<BlastOutput_version>BLASTN 2.7.1+</BlastOutput_version>
<BlastOutput_reference>Zheng Zhang, Scott Schwartz, Lukas Wagner, and Webb
Miller (2000), "A greedy algorithm for aligning DNA sequences", J
Comput Biol 2000; 7(1-2):203-14.
</BlastOutput_reference>
<BlastOutput_db>alun</BlastOutput_db>
<BlastOutput_query-ID>Query_1</BlastOutput_query-ID>
<BlastOutput_query-def>gnl|alu|Z15030_HSAL001056 (Alu-J)</BlastOutput_query-def>
<BlastOutput_query-len>292</BlastOutput_query-len>
<BlastOutput_param>
<Parameters>
<Parameters_expect>10</Parameters_expect>
<Parameters_sc-match>1</Parameters_sc-match>
<Parameters_sc-mismatch>-2</Parameters_sc-mismatch>
<Parameters_gap-open>0</Parameters_gap-open>
<Parameters_gap-extend>0</Parameters_gap-extend>
<Parameters_filter>L;m;</Parameters_filter>
</Parameters>
</BlastOutput_param>
<BlastOutput_iterations>
<Iteration>
<Iteration_iter-num>1</Iteration_iter-num><Iteration_query-ID>Query_1</Iteration_query-ID>
<Iteration_query-def>gnl|alu|Z15030_HSAL001056 (Alu-J)</Iteration_query-def>
<Iteration_query-len>292</Iteration_query-len>
<Iteration_hits>
<Hit>
<Hit_num>1</Hit_num>
<Hit_id>gnl|alu|Z15030_HSAL001056</Hit_id>
<Hit_def>(Alu-J)</Hit_def>
<Hit_accession>Z15030_HSAL001056</Hit_accession>
<Hit_len>292</Hit_len>
<Hit_hsps>
<Hsp>
<Hsp_num>1</Hsp_num>
<Hsp_bit-score>540.342</Hsp_bit-score>
<Hsp_score>292</Hsp_score>
<Hsp_evalue>4.55414e-156</Hsp_evalue>
<Hsp_query-from>1</Hsp_query-from>
<Hsp_query-to>292</Hsp_query-to>
<Hsp_hit-from>1</Hsp_hit-from>
<Hsp_hit-to>292</Hsp_hit-to>
<Hsp_query-frame>1</Hsp_query-frame>
<Hsp_hit-frame>1</Hsp_hit-frame>
<Hsp_identity>292</Hsp_identity>
<Hsp_positive>292</Hsp_positive>
<Hsp_gaps>0</Hsp_gaps>
<Hsp_align-len>292</Hsp_align-len>
<Hsp_qseq>
AGGCTGGCACTGTGGCTCATGCTGAAATCCCAGCACGGCGGAGGACGGCGGAAGATTGCTTGAGCCTAGGAGTTTG
CGACCAGCCTGGGTGACATAGGGAGATGCCTGTCTCTACGCAAAAGAAAAAAAAAATAGCTCTGCTGGTGGTGCATG
CCTATAGTCTCAGCTATCAGGAGGCTGGGACAGGAGGATCACTTGGGCCCGGGAGTTGAGGCTGTGGTGAGCC
ACGATCACACCACTGCACTCCAGCCTGGGTGACAGAGCAAGACCCTGTCTCAAAACAAACAAATAA
</Hsp_qseq>
<Hsp_hseq>
AGGCTGGCACTGTGGCTCATGCTGAAATCCCAGCACGGCGGAGGACGGCGGAAGATTGCTTGAGCCTAGGA
GTTTGCGACCAGCCTGGGTGACATAGGGAGATGCCTGTCTCTACGCAAAAGAAAAAAAAAATAGCTCTGCT
GGTGGTGCATGCCTATAGTCTCAGCTATCAGGAGGCTGGGACAGGAGGATCACTTGGGCCCGGGAGTTGAGG
CTGTGGTGAGCCACGATCACACCACTGCACTCCAGCCTGGGTGACAGAGCAAGACCCTGTCTCAAAACAAAC
AAATAA
</Hsp_hseq>
<Hsp_midline>
|||||||||||||||||||||||||||||||||||||||||||||||||||||
|||||||||||||||||||||||||||||||||||||||||||||||||||||
|||||||||||||||||||||||||||||||||||||||||||||||||||||
|||||||||||||||||||||||||||||||||||||||||||||||||||||
|||||||||||||||||||||||||||||||||||||||||||||||||||||
|||||||||||||||||||||||||||
</Hsp_midline>
</Hsp>
</Hit_hsps>
</Hit>
.........................
.........................
.........................
</Iteration_hits>
<Iteration_stat>
<Statistics>
<Statistics_db-num>327</Statistics_db-num>
<Statistics_db-len>80506</Statistics_db-len>
<Statistics_hsp-lenv16</Statistics_hsp-len>
<Statistics_eff-space>21528364</Statistics_eff-space>
<Statistics_kappa>0.46</Statistics_kappa>
<Statistics_lambda>1.28</Statistics_lambda>
<Statistics_entropy>0.85</Statistics_entropy>
</Statistics>
</Iteration_stat>
</Iteration>
</BlastOutput_iterations>
</BlastOutput>
The above command can be run inside the python using the below code −
>>> from Bio.Blast.Applications import NcbiblastnCommandline
>>> blastn_cline = NcbiblastnCommandline(query = "search.fasta", db = "alun",
outfmt = 5, out = "results.xml")
>>> stdout, stderr = blastn_cline()
Here, the first one is a handle to the blast output and second one is the possible error output generated by the blast command.
Since we have provided the output file as command line argument (out = “results.xml”) and sets the output format as XML (outfmt = 5), the output file will be saved in the current working directory.
Generally, BLAST output is parsed as XML format using the NCBIXML module. To do this, we need to import the following module −
>>> from Bio.Blast import NCBIXML
Now, open the file directly using python open method and use NCBIXML parse method as given below −
>>> E_VALUE_THRESH = 1e-20
>>> for record in NCBIXML.parse(open("results.xml")):
>>> if record.alignments:
>>> print("\n")
>>> print("query: %s" % record.query[:100])
>>> for align in record.alignments:
>>> for hsp in align.hsps:
>>> if hsp.expect < E_VALUE_THRESH:
>>> print("match: %s " % align.title[:100])
This will produce an output as follows −
query: gnl|alu|Z15030_HSAL001056 (Alu-J)
match: gnl|alu|Z15030_HSAL001056 (Alu-J)
match: gnl|alu|L12964_HSAL003860 (Alu-J)
match: gnl|alu|L13042_HSAL003863 (Alu-FLA?)
match: gnl|alu|M86249_HSAL001462 (Alu-FLA?)
match: gnl|alu|M29484_HSAL002265 (Alu-J)
query: gnl|alu|D00596_HSAL003180 (Alu-Sx)
match: gnl|alu|D00596_HSAL003180 (Alu-Sx)
match: gnl|alu|J03071_HSAL001860 (Alu-J)
match: gnl|alu|X72409_HSAL005025 (Alu-Sx)
query: gnl|alu|X55502_HSAL000745 (Alu-J)
match: gnl|alu|X55502_HSAL000745 (Alu-J)
Entrez is an online search system provided by NCBI. It provides access to nearly all known molecular biology databases with an integrated global query supporting Boolean operators and field search. It returns results from all the databases with information like the number of hits from each databases, records with links to the originating database, etc.
Some of the popular databases which can be accessed through Entrez are listed below −
Pubmed
Pubmed Central
Nucleotide (GenBank Sequence Database)
Protein (Sequence Database)
Genome (Whole Genome Database)
Structure (Three Dimensional Macromolecular Structure)
Taxonomy (Organisms in GenBank)
SNP (Single Nucleotide Polymorphism)
UniGene (Gene Oriented Clusters of Transcript Sequences)
CDD (Conserved Protein Domain Database)
3D Domains (Domains from Entrez Structure)
In addition to the above databases, Entrez provides many more databases to perform the field search.
Biopython provides an Entrez specific module, Bio.Entrez to access Entrez database. Let us learn how to access Entrez using Biopython in this chapter −
To add the features of Entrez, import the following module −
>>> from Bio import Entrez
Next set your email to identify who is connected with the code given below −
>>> Entrez.email = '<youremail>'
Then, set the Entrez tool parameter and by default, it is Biopython.
>>> Entrez.tool = 'Demoscript'
Now, call einfo function to find index term counts, last update, and available links for each database as defined below −
>>> info = Entrez.einfo()
The einfo method returns an object, which provides access to the information through its read method as shown below −
>>> data = info.read()
>>> print(data)
<?xml version = "1.0" encoding = "UTF-8" ?>
<!DOCTYPE eInfoResult PUBLIC "-//NLM//DTD einfo 20130322//EN"
"https://eutils.ncbi.nlm.nih.gov/eutils/dtd/20130322/einfo.dtd">
<eInfoResult>
<DbList>
<DbName>pubmed</DbName>
<DbName>protein</DbName>
<DbName>nuccore</DbName>
<DbName>ipg</DbName>
<DbName>nucleotide</DbName>
<DbName>nucgss</DbName>
<DbName>nucest</DbName>
<DbName>structure</DbName>
<DbName>sparcle</DbName>
<DbName>genome</DbName>
<DbName>annotinfo</DbName>
<DbName>assembly</DbName>
<DbName>bioproject</DbName>
<DbName>biosample</DbName>
<DbName>blastdbinfo</DbName>
<DbName>books</DbName>
<DbName>cdd</DbName>
<DbName>clinvar</DbName>
<DbName>clone</DbName>
<DbName>gap</DbName>
<DbName>gapplus</DbName>
<DbName>grasp</DbName>
<DbName>dbvar</DbName>
<DbName>gene</DbName>
<DbName>gds</DbName>
<DbName>geoprofiles</DbName>
<DbName>homologene</DbName>
<DbName>medgen</DbName>
<DbName>mesh</DbName>
<DbName>ncbisearch</DbName>
<DbName>nlmcatalog</DbName>
<DbName>omim</DbName>
<DbName>orgtrack</DbName>
<DbName>pmc</DbName>
<DbName>popset</DbName>
<DbName>probe</DbName>
<DbName>proteinclusters</DbName>
<DbName>pcassay</DbName>
<DbName>biosystems</DbName>
<DbName>pccompound</DbName>
<DbName>pcsubstance</DbName>
<DbName>pubmedhealth</DbName>
<DbName>seqannot</DbName>
<DbName>snp</DbName>
<DbName>sra</DbName>
<DbName>taxonomy</DbName>
<DbName>biocollections</DbName>
<DbName>unigene</DbName>
<DbName>gencoll</DbName>
<DbName>gtr</DbName>
</DbList>
</eInfoResult>
The data is in XML format, and to get the data as python object, use Entrez.read method as soon as Entrez.einfo() method is invoked −
>>> info = Entrez.einfo()
>>> record = Entrez.read(info)
Here, record is a dictionary which has one key, DbList as shown below −
>>> record.keys()
[u'DbList']
Accessing the DbList key returns the list of database names shown below −
>>> record[u'DbList']
['pubmed', 'protein', 'nuccore', 'ipg', 'nucleotide', 'nucgss',
'nucest', 'structure', 'sparcle', 'genome', 'annotinfo', 'assembly',
'bioproject', 'biosample', 'blastdbinfo', 'books', 'cdd', 'clinvar',
'clone', 'gap', 'gapplus', 'grasp', 'dbvar', 'gene', 'gds', 'geoprofiles',
'homologene', 'medgen', 'mesh', 'ncbisearch', 'nlmcatalog', 'omim',
'orgtrack', 'pmc', 'popset', 'probe', 'proteinclusters', 'pcassay',
'biosystems', 'pccompound', 'pcsubstance', 'pubmedhealth', 'seqannot',
'snp', 'sra', 'taxonomy', 'biocollections', 'unigene', 'gencoll', 'gtr']
>>>
Basically, Entrez module parses the XML returned by Entrez search system and provide it as python dictionary and lists.
To search any of one the Entrez databases, we can use Bio.Entrez.esearch() module. It is defined below −
>>> info = Entrez.einfo()
>>> info = Entrez.esearch(db = "pubmed",term = "genome")
>>> record = Entrez.read(info)
>>>print(record)
DictElement({u'Count': '1146113', u'RetMax': '20', u'IdList':
['30347444', '30347404', '30347317', '30347292',
'30347286', '30347249', '30347194', '30347187',
'30347172', '30347088', '30347075', '30346992',
'30346990', '30346982', '30346980', '30346969',
'30346962', '30346954', '30346941', '30346939'],
u'TranslationStack': [DictElement({u'Count':
'927819', u'Field': 'MeSH Terms', u'Term': '"genome"[MeSH Terms]',
u'Explode': 'Y'}, attributes = {})
, DictElement({u'Count': '422712', u'Field':
'All Fields', u'Term': '"genome"[All Fields]', u'Explode': 'N'}, attributes = {}),
'OR', 'GROUP'], u'TranslationSet': [DictElement({u'To': '"genome"[MeSH Terms]
OR "genome"[All Fields]', u'From': 'genome'}, attributes = {})], u'RetStart': '0',
u'QueryTranslation': '"genome"[MeSH Terms] OR "genome"[All Fields]'},
attributes = {})
>>>
If you assign incorrect db then it returns
>>> info = Entrez.esearch(db = "blastdbinfo",term = "books")
>>> record = Entrez.read(info)
>>> print(record)
DictElement({u'Count': '0', u'RetMax': '0', u'IdList': [],
u'WarningList': DictElement({u'OutputMessage': ['No items found.'],
u'PhraseIgnored': [], u'QuotedPhraseNotFound': []}, attributes = {}),
u'ErrorList': DictElement({u'FieldNotFound': [], u'PhraseNotFound':
['books']}, attributes = {}), u'TranslationSet': [], u'RetStart': '0',
u'QueryTranslation': '(books[All Fields])'}, attributes = {})
If you want to search across database, then you can use Entrez.egquery. This is similar to Entrez.esearch except it is enough to specify the keyword and skip the database parameter.
>>>info = Entrez.egquery(term = "entrez")
>>> record = Entrez.read(info)
>>> for row in record["eGQueryResult"]:
... print(row["DbName"], row["Count"])
...
pubmed 458
pmc 12779 mesh 1
...
...
...
biosample 7
biocollections 0
Enterz provides a special method, efetch to search and download the full details of a record from Entrez. Consider the following simple example −
>>> handle = Entrez.efetch(
db = "nucleotide", id = "EU490707", rettype = "fasta")
Now, we can simply read the records using SeqIO object
>>> record = SeqIO.read( handle, "fasta" )
>>> record
SeqRecord(seq = Seq('ATTTTTTACGAACCTGTGGAAATTTTTGGTTATGACAATAAATCTAGTTTAGTA...GAA',
SingleLetterAlphabet()), id = 'EU490707.1', name = 'EU490707.1',
description = 'EU490707.1
Selenipedium aequinoctiale maturase K (matK) gene, partial cds; chloroplast',
dbxrefs = [])
Biopython provides Bio.PDB module to manipulate polypeptide structures. The PDB (Protein Data Bank) is the largest protein structure resource available online. It hosts a lot of distinct protein structures, including protein-protein, protein-DNA, protein-RNA complexes.
In order to load the PDB, type the below command −
from Bio.PDB import *
The PDB distributes protein structures in three different formats −
The XML-based file format which is not supported by Biopython
The pdb file format, which is a specially formatted text file
PDBx/mmCIF files format
PDB files distributed by the Protein Data Bank may contain formatting errors that make them ambiguous or difficult to parse. The Bio.PDB module attempts to deal with these errors automatically.
The Bio.PDB module implements two different parsers, one is mmCIF format and second one is pdb format.
Let us learn how to parser each of the format in detail −
Let us download an example database in mmCIF format from pdb server using the below command −
>>> pdbl = PDBList()
>>> pdbl.retrieve_pdb_file('2FAT', pdir = '.', file_format = 'mmCif')
This will download the specified file (2fat.cif) from the server and store it in the current working directory.
Here, PDBList provides options to list and download files from online PDB FTP server. retrieve_pdb_file method needs the name of the file to be downloaded without extension. retrieve_pdb_file also have option to specify download directory, pdir and format of the file, file_format. The possible values of file format are as follows −
“mmCif” (default, PDBx/mmCif file)
“pdb” (format PDB)
“xml” (PMDML/XML format)
“mmtf” (highly compressed)
“bundle” (PDB formatted archive for large structure)
To load a cif file, use Bio.MMCIF.MMCIFParser as specified below −
>>> parser = MMCIFParser(QUIET = True)
>>> data = parser.get_structure("2FAT", "2FAT.cif")
Here, QUIET suppresses the warning during parsing the file. get_structure will parse the file and return the structure with id as 2FAT (first argument).
After running the above command, it parses the file and prints possible warning, if available.
Now, check the structure using the below command −
>>> data
<Structure id = 2FAT>
To get the type, use type method as specified below,
>>> print(type(data))
<class 'Bio.PDB.Structure.Structure'>
We have successfully parsed the file and got the structure of the protein. We will learn the details of the protein structure and how to get it in the later chapter.
Let us download an example database in PDB format from pdb server using the below command −
>>> pdbl = PDBList()
>>> pdbl.retrieve_pdb_file('2FAT', pdir = '.', file_format = 'pdb')
This will download the specified file (pdb2fat.ent) from the server and store it in the current working directory.
To load a pdb file, use Bio.PDB.PDBParser as specified below −
>>> parser = PDBParser(PERMISSIVE = True, QUIET = True)
>>> data = parser.get_structure("2fat","pdb2fat.ent")
Here, get_structure is similar to MMCIFParser. PERMISSIVE option try to parse the protein data as flexible as possible.
Now, check the structure and its type with the code snippet given below −
>>> data
<Structure id = 2fat>
>>> print(type(data))
<class 'Bio.PDB.Structure.Structure'>
Well, the header structure stores the dictionary information. To perform this, type the below command −
>>> print(data.header.keys()) dict_keys([
'name', 'head', 'deposition_date', 'release_date', 'structure_method', 'resolution',
'structure_reference', 'journal_reference', 'author', 'compound', 'source',
'keywords', 'journal'])
>>>
To get the name, use the following code −
>>> print(data.header["name"])
an anti-urokinase plasminogen activator receptor (upar) antibody: crystal
structure and binding epitope
>>>
You can also check the date and resolution with the below code −
>>> print(data.header["release_date"]) 2006-11-14
>>> print(data.header["resolution"]) 1.77
PDB structure is composed of a single model, containing two chains.
chain L, containing number of residues
chain H, containing number of residues
Each residue is composed of multiple atoms, each having a 3D position represented by (x, y, z) coordinates.
Let us learn how to get the structure of the atom in detail in the below section −
The Structure.get_models() method returns an iterator over the models. It is defined below −
>>> model = data.get_models()
>>> model
<generator object get_models at 0x103fa1c80>
>>> models = list(model)
>>> models [<Model id = 0>]
>>> type(models[0])
<class 'Bio.PDB.Model.Model'>
Here, a Model describes exactly one 3D conformation. It contains one or more chains.
The Model.get_chain() method returns an iterator over the chains. It is defined below −
>>> chains = list(models[0].get_chains())
>>> chains
[<Chain id = L>, <Chain id = H>]
>>> type(chains[0])
<class 'Bio.PDB.Chain.Chain'>
Here, Chain describes a proper polypeptide structure, i.e., a consecutive sequence of bound residues.
The Chain.get_residues() method returns an iterator over the residues. It is defined below −
>>> residue = list(chains[0].get_residues())
>>> len(residue)
293
>>> residue1 = list(chains[1].get_residues())
>>> len(residue1)
311
Well, Residue holds the atoms that belong to an amino acid.
The Residue.get_atom() returns an iterator over the atoms as defined below −
>>> atoms = list(residue[0].get_atoms())
>>> atoms
[<Atom N>, <Atom CA>, <Atom C>, <Atom Ov, <Atom CB>, <Atom CG>, <Atom OD1>, <Atom OD2>]
An atom holds the 3D coordinate of an atom and it is called a Vector. It is defined below
>>> atoms[0].get_vector()
<Vector 18.49, 73.26, 44.16>
It represents x, y and z co-ordinate values.
A sequence motif is a nucleotide or amino-acid sequence pattern. Sequence motifs are formed by three-dimensional arrangement of amino acids which may not be adjacent. Biopython provides a separate module, Bio.motifs to access the functionalities of sequence motif as specified below −
from Bio import motifs
Let us create a simple DNA motif sequence using the below command −
>>> from Bio import motifs
>>> from Bio.Seq import Seq
>>> DNA_motif = [ Seq("AGCT"),
... Seq("TCGA"),
... Seq("AACT"),
... ]
>>> seq = motifs.create(DNA_motif)
>>> print(seq) AGCT TCGA AACT
To count the sequence values, use the below command −
>>> print(seq.counts)
0 1 2 3
A: 2.00 1.00 0.00 1.00
C: 0.00 1.00 2.00 0.00
G: 0.00 1.00 1.00 0.00
T: 1.00 0.00 0.00 2.00
Use the following code to count ‘A’ in the sequence −
>>> seq.counts["A", :]
(2, 1, 0, 1)
If you want to access the columns of counts, use the below command −
>>> seq.counts[:, 3]
{'A': 1, 'C': 0, 'T': 2, 'G': 0}
We shall now discuss how to create a Sequence Logo.
Consider the below sequence −
AGCTTACG
ATCGTACC
TTCCGAAT
GGTACGTA
AAGCTTGG
You can create your own logo using the following link − http://weblogo.berkeley.edu/
Add the above sequence and create a new logo and save the image named seq.png in your biopython folder.
seq.png
After creating the image, now run the following command −
>>> seq.weblogo("seq.png")
This DNA sequence motif is represented as a sequence logo for the LexA-binding motif.
JASPAR is one of the most popular databases. It provides facilities of any of the motif formats for reading, writing and scanning sequences. It stores meta-information for each motif. The module Bio.motifs contains a specialized class jaspar.Motif to represent meta-information attributes.
It has the following notable attributes types −
matrix_id − Unique JASPAR motif ID
name − The name of the motif
tf_family − The family of motif, e.g. ’Helix-Loop-Helix’
data_type − the type of data used in motif.
Let us create a JASPAR sites format named in sample.sites in biopython folder. It is defined below −
sample.sites
>MA0001 ARNT 1
AACGTGatgtccta
>MA0001 ARNT 2
CAGGTGggatgtac
>MA0001 ARNT 3
TACGTAgctcatgc
>MA0001 ARNT 4
AACGTGacagcgct
>MA0001 ARNT 5
CACGTGcacgtcgt
>MA0001 ARNT 6
cggcctCGCGTGc
In the above file, we have created motif instances. Now, let us create a motif object from the above instances −
>>> from Bio import motifs
>>> with open("sample.sites") as handle:
... data = motifs.read(handle,"sites")
...
>>> print(data)
TF name None
Matrix ID None
Matrix:
0 1 2 3 4 5
A: 2.00 5.00 0.00 0.00 0.00 1.00
C: 3.00 0.00 5.00 0.00 0.00 0.00
G: 0.00 1.00 1.00 6.00 0.00 5.00
T: 1.00 0.00 0.00 0.00 6.00 0.00
Here, data reads all the motif instances from sample.sites file.
To print all the instances from data, use the below command −
>>> for instance in data.instances:
... print(instance)
...
AACGTG
CAGGTG
TACGTA
AACGTG
CACGTG
CGCGTG
Use the below command to count all the values −
>>> print(data.counts)
0 1 2 3 4 5
A: 2.00 5.00 0.00 0.00 0.00 1.00
C: 3.00 0.00 5.00 0.00 0.00 0.00
G: 0.00 1.00 1.00 6.00 0.00 5.00
T: 1.00 0.00 0.00 0.00 6.00 0.00
>>>
BioSQL is a generic database schema designed mainly to store sequences and its related data for all RDBMS engine. It is designed in such a way that it holds the data from all popular bioinformatics databases like GenBank, Swissport, etc. It can be used to store in-house data as well.
BioSQL currently provides specific schema for the below databases −
MySQL (biosqldb-mysql.sql)
PostgreSQL (biosqldb-pg.sql)
Oracle (biosqldb-ora/*.sql)
SQLite (biosqldb-sqlite.sql)
It also provides minimal support for Java based HSQLDB and Derby databases.
BioPython provides very simple, easy and advanced ORM capabilities to work with BioSQL based database. BioPython provides a module, BioSQL to do the following functionality −
Create/remove a BioSQL database
Connect to a BioSQL database
Parse a sequence database like GenBank, Swisport, BLAST result, Entrez result, etc., and directly load it into the BioSQL database
Fetch the sequence data from the BioSQL database
Fetch taxonomy data from NCBI BLAST and store it in the BioSQL database
Run any SQL query against the BioSQL database
Before going deep into the BioSQL, let us understand the basics of BioSQL schema. BioSQL schema provides 25+ tables to hold sequence data, sequence feature, sequence category/ontology and taxonomy information. Some of the important tables are as follows −
biodatabase
bioentry
biosequence
seqfeature
taxon
taxon_name
antology
term
dxref
In this section, let us create a sample BioSQL database, biosql using the schema provided by the BioSQL team. We shall work with SQLite database as it is really easy to get started and does not have complex setup.
Here, we shall create a SQLite based BioSQL database using the below steps.
Step 1 − Download the SQLite databse engine and install it.
Step 2 − Download the BioSQL project from the GitHub URL.
https://github.com/biosql/biosql
Step 3 − Open a console and create a directory using mkdir and enter into it.
cd /path/to/your/biopython/sample
mkdir sqlite-biosql
cd sqlite-biosql
Step 4 − Run the below command to create a new SQLite database.
> sqlite3.exe mybiosql.db
SQLite version 3.25.2 2018-09-25 19:08:10
Enter ".help" for usage hints.
sqlite>
Step 5 − Copy the biosqldb-sqlite.sql file from the BioSQL project (/sql/biosqldb-sqlite.sql`) and store it in the current directory.
Step 6 − Run the below command to create all the tables.
sqlite> .read biosqldb-sqlite.sql
Now, all tables are created in our new database.
Step 7 − Run the below command to see all the new tables in our database.
sqlite> .headers on
sqlite> .mode column
sqlite> .separator ROW "\n"
sqlite> SELECT name FROM sqlite_master WHERE type = 'table';
biodatabase
taxon
taxon_name
ontology
term
term_synonym
term_dbxref
term_relationship
term_relationship_term
term_path
bioentry
bioentry_relationship
bioentry_path
biosequence
dbxref
dbxref_qualifier_value
bioentry_dbxref
reference
bioentry_reference
comment
bioentry_qualifier_value
seqfeature
seqfeature_relationship
seqfeature_path
seqfeature_qualifier_value
seqfeature_dbxref
location
location_qualifier_value
sqlite>
The first three commands are configuration commands to configure SQLite to show the result in a formatted manner.
Step 8 − Copy the sample GenBank file, ls_orchid.gbk provided by BioPython team https://raw.githubusercontent.com/biopython/biopython/master/Doc/examples/ls_orchid.gbk into the current directory and save it as orchid.gbk.
Step 9 − Create a python script, load_orchid.py using the below code and execute it.
from Bio import SeqIO
from BioSQL import BioSeqDatabase
import os
server = BioSeqDatabase.open_database(driver = 'sqlite3', db = "orchid.db")
db = server.new_database("orchid")
count = db.load(SeqIO.parse("orchid.gbk", "gb"), True) server.commit()
server.close()
The above code parses the record in the file and converts it into python objects and inserts it into BioSQL database. We will analyze the code in later section.
Finally, we created a new BioSQL database and load some sample data into it. We shall discuss the important tables in the next chapter.
biodatabase table is in the top of the hierarchy and its main purpose is to organize a set of sequence data into a single group/virtual database. Every entry in the biodatabase refers to a separate database and it does not mingle with another database. All the related tables in the BioSQL database have references to biodatabase entry.
bioentry table holds all the details about a sequence except the sequence data. sequence data of a particular bioentry will be stored in biosequence table.
taxon and taxon_name are taxonomy details and every entry refers this table to specify its taxon information.
After understanding the schema, let us look into some queries in the next section.
Let us delve into some SQL queries to better understand how the data are organized and the tables are related to each other. Before proceeding, let us open the database using the below command and set some formatting commands −
> sqlite3 orchid.db
SQLite version 3.25.2 2018-09-25 19:08:10
Enter ".help" for usage hints.
sqlite> .header on
sqlite> .mode columns
.header and .mode are formatting options to better visualize the data. You can also use any SQLite editor to run the query.
List the virtual sequence database available in the system as given below −
select
*
from
biodatabase;
*** Result ***
sqlite> .width 15 15 15 15
sqlite> select * from biodatabase;
biodatabase_id name authority description
--------------- --------------- --------------- ---------------
1 orchid
sqlite>
Here, we have only one database, orchid.
List the entries (top 3) available in the database orchid with the below given code
select
be.*,
bd.name
from
bioentry be
inner join
biodatabase bd
on bd.biodatabase_id = be.biodatabase_id
where
bd.name = 'orchid' Limit 1,
3;
*** Result ***
sqlite> .width 15 15 10 10 10 10 10 50 10 10
sqlite> select be.*, bd.name from bioentry be inner join biodatabase bd on
bd.biodatabase_id = be.biodatabase_id where bd.name = 'orchid' Limit 1,3;
bioentry_id biodatabase_id taxon_id name accession identifier division description version name
--------------- --------------- ---------- ---------- ---------- ---------- ----------
---------- ---------- ----------- ---------- --------- ---------- ----------
2 1 19 Z78532 Z78532 2765657 PLN
C.californicum 5.8S rRNA gene and ITS1 and ITS2 DN 1
orchid
3 1 20 Z78531 Z78531 2765656 PLN
C.fasciculatum 5.8S rRNA gene and ITS1 and ITS2 DN 1
orchid
4 1 21 Z78530 Z78530 2765655 PLN
C.margaritaceum 5.8S rRNA gene and ITS1 and ITS2 D 1
orchid
sqlite>
List the sequence details associated with an entry (accession − Z78530, name − C. fasciculatum 5.8S rRNA gene and ITS1 and ITS2 DNA) with the given code −
select
substr(cast(bs.seq as varchar), 0, 10) || '...' as seq,
bs.length,
be.accession,
be.description,
bd.name
from
biosequence bs
inner join
bioentry be
on be.bioentry_id = bs.bioentry_id
inner join
biodatabase bd
on bd.biodatabase_id = be.biodatabase_id
where
bd.name = 'orchid'
and be.accession = 'Z78532';
*** Result ***
sqlite> .width 15 5 10 50 10
sqlite> select substr(cast(bs.seq as varchar), 0, 10) || '...' as seq,
bs.length, be.accession, be.description, bd.name from biosequence bs inner
join bioentry be on be.bioentry_id = bs.bioentry_id inner join biodatabase bd
on bd.biodatabase_id = be.biodatabase_id where bd.name = 'orchid' and
be.accession = 'Z78532';
seq length accession description name
------------ ---------- ---------- ------------ ------------ ---------- ---------- -----------------
CGTAACAAG... 753 Z78532 C.californicum 5.8S rRNA gene and ITS1 and ITS2 DNA orchid
sqlite>
Get the complete sequence associated with an entry (accession − Z78530, name − C. fasciculatum 5.8S rRNA gene and ITS1 and ITS2 DNA) using the below code −
select
bs.seq
from
biosequence bs
inner join
bioentry be
on be.bioentry_id = bs.bioentry_id
inner join
biodatabase bd
on bd.biodatabase_id = be.biodatabase_id
where
bd.name = 'orchid'
and be.accession = 'Z78532';
*** Result ***
sqlite> .width 1000
sqlite> select bs.seq from biosequence bs inner join bioentry be on
be.bioentry_id = bs.bioentry_id inner join biodatabase bd on bd.biodatabase_id =
be.biodatabase_id where bd.name = 'orchid' and be.accession = 'Z78532';
seq
----------------------------------------------------------------------------------------
----------------------------
CGTAACAAGGTTTCCGTAGGTGAACCTGCGGAAGGATCATTGTTGAGACAACAGAATATATGATCGAGTGAATCT
GGAGGACCTGTGGTAACTCAGCTCGTCGTGGCACTGCTTTTGTCGTGACCCTGCTTTGTTGTTGGGCCTCC
TCAAGAGCTTTCATGGCAGGTTTGAACTTTAGTACGGTGCAGTTTGCGCCAAGTCATATAAAGCATCACTGATGAATGACATTATTGT
CAGAAAAAATCAGAGGGGCAGTATGCTACTGAGCATGCCAGTGAATTTTTATGACTCTCGCAACGGATATCTTGGCTC
TAACATCGATGAAGAACGCAG
sqlite>
List taxon associated with bio database, orchid
select distinct
tn.name
from
biodatabase d
inner join
bioentry e
on e.biodatabase_id = d.biodatabase_id
inner join
taxon t
on t.taxon_id = e.taxon_id
inner join
taxon_name tn
on tn.taxon_id = t.taxon_id
where
d.name = 'orchid' limit 10;
*** Result ***
sqlite> select distinct tn.name from biodatabase d inner join bioentry e on
e.biodatabase_id = d.biodatabase_id inner join taxon t on t.taxon_id =
e.taxon_id inner join taxon_name tn on tn.taxon_id = t.taxon_id where d.name =
'orchid' limit 10;
name
------------------------------
Cypripedium irapeanum
Cypripedium californicum
Cypripedium fasciculatum
Cypripedium margaritaceum
Cypripedium lichiangense
Cypripedium yatabeanum
Cypripedium guttatum
Cypripedium acaule
pink lady's slipper
Cypripedium formosanum
sqlite>
Let us learn how to load sequence data into the BioSQL database in this chapter. We already have the code to load data into the database in previous section and the code is as follows −
from Bio import SeqIO
from BioSQL import BioSeqDatabase
import os
server = BioSeqDatabase.open_database(driver = 'sqlite3', db = "orchid.db")
DBSCHEMA = "biosqldb-sqlite.sql"
SQL_FILE = os.path.join(os.getcwd(), DBSCHEMA)
server.load_database_sql(SQL_FILE)
server.commit()
db = server.new_database("orchid")
count = db.load(SeqIO.parse("orchid.gbk", "gb"), True) server.commit()
server.close()
We will have a deeper look at every line of the code and its purpose −
Line 1 − Loads the SeqIO module.
Line 2 − Loads the BioSeqDatabase module. This module provides all the functionality to interact with BioSQL database.
Line 3 − Loads os module.
Line 5 − open_database opens the specified database (db) with the configured driver (driver) and returns a handle to the BioSQL database (server). Biopython supports sqlite, mysql, postgresql and oracle databases.
Line 6-10 − load_database_sql method loads the sql from the external file and executes it. commit method commits the transaction. We can skip this step because we already created the database with schema.
Line 12 − new_database methods creates new virtual database, orchid and returns a handle db to execute the command against the orchid database.
Line 13 − load method loads the sequence entries (iterable SeqRecord) into the orchid database. SqlIO.parse parses the GenBank database and returns all the sequences in it as iterable SeqRecord. Second parameter (True) of the load method instructs it to fetch the taxonomy details of the sequence data from NCBI blast website, if it is not already available in the system.
Line 14 − commit commits the transaction.
Line 15 − close closes the database connection and destroys the server handle.
Let us fetch a sequence with identifier, 2765658 from the orchid database as below −
from BioSQL import BioSeqDatabase
server = BioSeqDatabase.open_database(driver = 'sqlite3', db = "orchid.db")
db = server["orchid"]
seq_record = db.lookup(gi = 2765658)
print(seq_record.id, seq_record.description[:50] + "...")
print("Sequence length %i," % len(seq_record.seq))
Here, server["orchid"] returns the handle to fetch data from virtual databaseorchid. lookup method provides an option to select sequences based on criteria and we have selected the sequence with identifier, 2765658. lookup returns the sequence information as SeqRecordobject. Since, we already know how to work with SeqRecord`, it is easy to get data from it.
Removing a database is as simple as calling remove_database method with proper database name and then committing it as specified below −
from BioSQL import BioSeqDatabase
server = BioSeqDatabase.open_database(driver = 'sqlite3', db = "orchid.db")
server.remove_database("orchids")
server.commit()
Population genetics plays an important role in evolution theory. It analyses the genetic difference between species as well as two or more individuals within the same species.
Biopython provides Bio.PopGen module for population genetics and mainly supports `GenePop, a popular genetics package developed by Michel Raymond and Francois Rousset.
Let us write a simple application to parse the GenePop format and understand the concept.
Download the genePop file provided by Biopython team in the link given below −https://raw.githubusercontent.com/biopython/biopython/master/Tests/PopGen/c3line.gen
Load the GenePop module using the below code snippet −
from Bio.PopGen import GenePop
Parse the file using GenePop.read method as below −
record = GenePop.read(open("c3line.gen"))
Show the loci and population information as given below −
>>> record.loci_list
['136255903', '136257048', '136257636']
>>> record.pop_list
['4', 'b3', '5']
>>> record.populations
[[('1', [(3, 3), (4, 4), (2, 2)]), ('2', [(3, 3), (3, 4), (2, 2)]),
('3', [(3, 3), (4, 4), (2, 2)]), ('4', [(3, 3), (4, 3), (None, None)])],
[('b1', [(None, None), (4, 4), (2, 2)]), ('b2', [(None, None), (4, 4), (2, 2)]),
('b3', [(None, None), (4, 4), (2, 2)])],
[('1', [(3, 3), (4, 4), (2, 2)]), ('2', [(3, 3), (1, 4), (2, 2)]),
('3', [(3, 2), (1, 1), (2, 2)]), ('4',
[(None, None), (4, 4), (2, 2)]), ('5', [(3, 3), (4, 4), (2, 2)])]]
>>>
Here, there are three loci available in the file and three sets of population: First population has 4 records, second population has 3 records and third population has 5 records. record.populations shows all sets of population with alleles data for each locus.
Biopython provides options to remove locus and population data.
Remove a population set by position,
>>> record.remove_population(0)
>>> record.populations
[[('b1', [(None, None), (4, 4), (2, 2)]),
('b2', [(None, None), (4, 4), (2, 2)]),
('b3', [(None, None), (4, 4), (2, 2)])],
[('1', [(3, 3), (4, 4), (2, 2)]),
('2', [(3, 3), (1, 4), (2, 2)]),
('3', [(3, 2), (1, 1), (2, 2)]),
('4', [(None, None), (4, 4), (2, 2)]),
('5', [(3, 3), (4, 4), (2, 2)])]]
>>>
Remove a locus by position,
>>> record.remove_locus_by_position(0)
>>> record.loci_list
['136257048', '136257636']
>>> record.populations
[[('b1', [(4, 4), (2, 2)]), ('b2', [(4, 4), (2, 2)]), ('b3', [(4, 4), (2, 2)])],
[('1', [(4, 4), (2, 2)]), ('2', [(1, 4), (2, 2)]),
('3', [(1, 1), (2, 2)]), ('4', [(4, 4), (2, 2)]), ('5', [(4, 4), (2, 2)])]]
>>>
Remove a locus by name,
>>> record.remove_locus_by_name('136257636') >>> record.loci_list
['136257048']
>>> record.populations
[[('b1', [(4, 4)]), ('b2', [(4, 4)]), ('b3', [(4, 4)])],
[('1', [(4, 4)]), ('2', [(1, 4)]),
('3', [(1, 1)]), ('4', [(4, 4)]), ('5', [(4, 4)])]]
>>>
Biopython provides interfaces to interact with GenePop software and thereby exposes lot of functionality from it. Bio.PopGen.GenePop module is used for this purpose. One such easy to use interface is EasyController. Let us check how to parse GenePop file and do some analysis using EasyController.
First, install the GenePop software and place the installation folder in the system path. To get basic information about GenePop file, create a EasyController object and then call get_basic_info method as specified below −
>>> from Bio.PopGen.GenePop.EasyController import EasyController
>>> ec = EasyController('c3line.gen')
>>> print(ec.get_basic_info())
(['4', 'b3', '5'], ['136255903', '136257048', '136257636'])
>>>
Here, the first item is population list and second item is loci list.
To get all allele list of a particular locus, call get_alleles_all_pops method by passing locus name as specified below −
>>> allele_list = ec.get_alleles_all_pops("136255903")
>>> print(allele_list)
[2, 3]
To get allele list by specific population and locus, call get_alleles by passing locus name and population position as given below −
>>> allele_list = ec.get_alleles(0, "136255903")
>>> print(allele_list)
[]
>>> allele_list = ec.get_alleles(1, "136255903")
>>> print(allele_list)
[]
>>> allele_list = ec.get_alleles(2, "136255903")
>>> print(allele_list)
[2, 3]
>>>
Similarly, EasyController exposes many functionalities: allele frequency, genotype frequency, multilocus F statistics, Hardy-Weinberg equilibrium, Linkage Disequilibrium, etc.
A genome is complete set of DNA, including all of its genes. Genome analysis refers to the study of individual genes and their roles in inheritance.
Genome diagram represents the genetic information as charts. Biopython uses Bio.Graphics.GenomeDiagram module to represent GenomeDiagram. The GenomeDiagram module requires ReportLab to be installed.
The process of creating a diagram generally follows the below simple pattern −
Create a FeatureSet for each separate set of features you want to display, and add Bio.SeqFeature objects to them.
Create a FeatureSet for each separate set of features you want to display, and add Bio.SeqFeature objects to them.
Create a GraphSet for each graph you want to display, and add graph data to them.
Create a GraphSet for each graph you want to display, and add graph data to them.
Create a Track for each track you want on the diagram, and add GraphSets and FeatureSets to the tracks you require.
Create a Track for each track you want on the diagram, and add GraphSets and FeatureSets to the tracks you require.
Create a Diagram, and add the Tracks to it.
Create a Diagram, and add the Tracks to it.
Tell the Diagram to draw the image.
Tell the Diagram to draw the image.
Write the image to a file.
Write the image to a file.
Let us take an example of input GenBank file −
https://raw.githubusercontent.com/biopython/biopython/master/Doc/examples/ls_orchid.gbk and read records from SeqRecord object then finally draw a genome diagram. It is explained below,
We shall import all the modules first as shown below −
>>> from reportlab.lib import colors
>>> from reportlab.lib.units import cm
>>> from Bio.Graphics import GenomeDiagram
Now, import SeqIO module to read data −
>>> from Bio import SeqIO
record = SeqIO.read("example.gb", "genbank")
Here, the record reads the sequence from genbank file.
Now, create an empty diagram to add track and feature set −
>>> diagram = GenomeDiagram.Diagram(
"Yersinia pestis biovar Microtus plasmid pPCP1")
>>> track = diagram.new_track(1, name="Annotated Features")
>>> feature = track.new_set()
Now, we can apply color theme changes using alternative colors from green to grey as defined below −
>>> for feature in record.features:
>>> if feature.type != "gene":
>>> continue
>>> if len(feature) % 2 == 0:
>>> color = colors.blue
>>> else:
>>> color = colors.red
>>>
>>> feature.add_feature(feature, color=color, label=True)
Now you could see the below response on your screen −
<Bio.Graphics.GenomeDiagram._Feature.Feature object at 0x105d3dc90>
<Bio.Graphics.GenomeDiagram._Feature.Feature object at 0x105d3dfd0>
<Bio.Graphics.GenomeDiagram._Feature.Feature object at 0x1007627d0>
<Bio.Graphics.GenomeDiagram._Feature.Feature object at 0x105d57290>
<Bio.Graphics.GenomeDiagram._Feature.Feature object at 0x105d57050>
<Bio.Graphics.GenomeDiagram._Feature.Feature object at 0x105d57390>
<Bio.Graphics.GenomeDiagram._Feature.Feature object at 0x105d57590>
<Bio.Graphics.GenomeDiagram._Feature.Feature object at 0x105d57410>
<Bio.Graphics.GenomeDiagram._Feature.Feature object at 0x105d57490>
<Bio.Graphics.GenomeDiagram._Feature.Feature object at 0x105d574d0>
Let us draw a diagram for the above input records −
>>> diagram.draw(
format = "linear", orientation = "landscape", pagesize = 'A4',
... fragments = 4, start = 0, end = len(record))
>>> diagram.write("orchid.pdf", "PDF")
>>> diagram.write("orchid.eps", "EPS")
>>> diagram.write("orchid.svg", "SVG")
>>> diagram.write("orchid.png", "PNG")
After executing the above command, you could see the following image saved in your Biopython directory.
** Result **
genome.png
You can also draw the image in circular format by making the below changes −
>>> diagram.draw(
format = "circular", circular = True, pagesize = (20*cm,20*cm),
... start = 0, end = len(record), circle_core = 0.7)
>>> diagram.write("circular.pdf", "PDF")
DNA molecule is packaged into thread-like structures called chromosomes. Each chromosome is made up of DNA tightly coiled many times around proteins called histones that support its structure.
Chromosomes are not visible in the cell’s nucleus — not even under a microscope —when the cell is not dividing. However, the DNA that makes up chromosomes becomes more tightly packed during cell division and is then visible under a microscope.
In humans, each cell normally contains 23 pairs of chromosomes, for a total of 46. Twenty-two of these pairs, called autosomes, look the same in both males and females. The 23rd pair, the sex chromosomes, differ between males and females. Females have two copies of the X chromosome, while males have one X and one Y chromosome.
Phenotype is defined as an observable character or trait exhibited by an organism against a particular chemical or environment. Phenotype microarray simultaneously measures the reaction of an organism against a larger number of chemicals & environment and analyses the data to understand the gene mutation, gene characters, etc.
Biopython provides an excellent module, Bio.Phenotype to analyze phenotypic data. Let us learn how to parse, interpolate, extract and analyze the phenotype microarray data in this chapter.
Phenotype microarray data can be in two formats: CSV and JSON. Biopython supports both the formats. Biopython parser parses the phenotype microarray data and returns as a collection of PlateRecord objects. Each PlateRecord object contains a collection of WellRecord objects. Each WellRecord object holds data in 8 rows and 12 columns format. The eight rows are represented by A to H and 12 columns are represented by 01 to 12. For example, 4th row and 6th column are represented by D06.
Let us understand the format and the concept of parsing with the following example −
Step 1 − Download the Plates.csv file provided by Biopython team − https://raw.githubusercontent.com/biopython/biopython/master/Doc/examples/Plates.csv
Step 2 − Load the phenotpe module as below −
>>> from Bio import phenotype
Step 3 − Invoke phenotype.parse method passing the data file and format option (“pm-csv”). It returns the iterable PlateRecord as below,
>>> plates = list(phenotype.parse('Plates.csv', "pm-csv"))
>>> plates
[PlateRecord('WellRecord['A01'], WellRecord['A02'], WellRecord['A03'], ..., WellRecord['H12']'),
PlateRecord('WellRecord['A01'], WellRecord['A02'], WellRecord['A03'], ..., WellRecord['H12']'),
PlateRecord('WellRecord['A01'], WellRecord['A02'], WellRecord['A03'], ..., WellRecord['H12']'),
PlateRecord('WellRecord['A01'], WellRecord['A02'],WellRecord['A03'], ..., WellRecord['H12']')]
>>>
Step 4 − Access the first plate from the list as below −
>>> plate = plates[0]
>>> plate
PlateRecord('WellRecord['A01'], WellRecord['A02'], WellRecord['A03'], ...,
WellRecord['H12']')
>>>
Step 5 − As discussed earlier, a plate contains 8 rows each having 12 items. WellRecord can be access in two ways as specified below −
>>> well = plate["A04"]
>>> well = plate[0, 4]
>>> well WellRecord('(0.0, 0.0), (0.25, 0.0), (0.5, 0.0), (0.75, 0.0),
(1.0, 0.0), ..., (71.75, 388.0)')
>>>
Step 6 − Each well will have series of measurement at different time points and it can be accessed using for loop as specified below −
>>> for v1, v2 in well:
... print(v1, v2)
...
0.0 0.0
0.25 0.0
0.5 0.0
0.75 0.0
1.0 0.0
...
71.25 388.0
71.5 388.0
71.75 388.0
>>>
Interpolation gives more insight into the data. Biopython provides methods to interpolate WellRecord data to get information for intermediate time points. The syntax is similar to list indexing and so, easy to learn.
To get the data at 20.1 hours, just pass as index values as specified below −
>>> well[20.10]
69.40000000000003
>>>
We can pass start time point and end time point as well as specified below −
>>> well[20:30]
[67.0, 84.0, 102.0, 119.0, 135.0, 147.0, 158.0, 168.0, 179.0, 186.0]
>>>
The above command interpolate data from 20 hour to 30 hours with 1 hour interval. By default, the interval is 1 hour and we can change it to any value. For example, let us give 15 minutes (0.25 hour) interval as specified below −
>>> well[20:21:0.25]
[67.0, 73.0, 75.0, 81.0]
>>>
Biopython provides a method fit to analyze the WellRecord data using Gompertz, Logistic and Richards sigmoid functions. By default, the fit method uses Gompertz function. We need to call the fit method of the WellRecord object to get the task done. The coding is as follows −
>>> well.fit()
Traceback (most recent call last):
...
Bio.MissingPythonDependencyError: Install scipy to extract curve parameters.
>>> well.model
>>> getattr(well, 'min') 0.0
>>> getattr(well, 'max') 388.0
>>> getattr(well, 'average_height')
205.42708333333334
>>>
Biopython depends on scipy module to do advanced analysis. It will calculate min, max and average_height details without using scipy module.
This chapter explains about how to plot sequences. Before moving to this topic, let us understand the basics of plotting.
Matplotlib is a Python plotting library which produces quality figures in a variety of formats. We can create different types of plots like line chart, histograms, bar chart, pie chart, scatter chart, etc.
pyLab is a module that belongs to the matplotlib which combines the numerical module numpy with the graphical plotting module pyplot.Biopython uses pylab module for plotting sequences. To do this, we need to import the below code −
import pylab
Before importing, we need to install the matplotlib package using pip command with the command given below −
pip install matplotlib
Create a sample file named plot.fasta in your Biopython directory and add the following changes −
>seq0 FQTWEEFSRAAEKLYLADPMKVRVVLKYRHVDGNLCIKVTDDLVCLVYRTDQAQDVKKIEKF
>seq1 KYRTWEEFTRAAEKLYQADPMKVRVVLKYRHCDGNLCIKVTDDVVCLLYRTDQAQDVKKIEKFHSQLMRLME
>seq2 EEYQTWEEFARAAEKLYLTDPMKVRVVLKYRHCDGNLCMKVTDDAVCLQYKTDQAQDVKKVEKLHGK
>seq3 MYQVWEEFSRAVEKLYLTDPMKVRVVLKYRHCDGNLCIKVTDNSVCLQYKTDQAQDV
>seq4 EEFSRAVEKLYLTDPMKVRVVLKYRHCDGNLCIKVTDNSVVSYEMRLFGVQKDNFALEHSLL
>seq5 SWEEFAKAAEVLYLEDPMKCRMCTKYRHVDHKLVVKLTDNHTVLKYVTDMAQDVKKIEKLTTLLMR
>seq6 FTNWEEFAKAAERLHSANPEKCRFVTKYNHTKGELVLKLTDDVVCLQYSTNQLQDVKKLEKLSSTLLRSI
>seq7 SWEEFVERSVQLFRGDPNATRYVMKYRHCEGKLVLKVTDDRECLKFKTDQAQDAKKMEKLNNIFF
>seq8 SWDEFVDRSVQLFRADPESTRYVMKYRHCDGKLVLKVTDNKECLKFKTDQAQEAKKMEKLNNIFFTLM
>seq9 KNWEDFEIAAENMYMANPQNCRYTMKYVHSKGHILLKMSDNVKCVQYRAENMPDLKK
>seq10 FDSWDEFVSKSVELFRNHPDTTRYVVKYRHCEGKLVLKVTDNHECLKFKTDQAQDAKKMEK
Now, let us create a simple line plot for the above fasta file.
Step 1 − Import SeqIO module to read fasta file.
>>> from Bio import SeqIO
Step 2 − Parse the input file.
>>> records = [len(rec) for rec in SeqIO.parse("plot.fasta", "fasta")]
>>> len(records)
11
>>> max(records)
72
>>> min(records)
57
Step 3 − Let us import pylab module.
>>> import pylab
Step 4 − Configure the line chart by assigning x and y axis labels.
>>> pylab.xlabel("sequence length")
Text(0.5, 0, 'sequence length')
>>> pylab.ylabel("count")
Text(0, 0.5, 'count')
>>>
Step 5 − Configure the line chart by setting grid display.
>>> pylab.grid()
Step 6 − Draw simple line chart by calling plot method and supplying records as input.
>>> pylab.plot(records)
[<matplotlib.lines.Line2D object at 0x10b6869d 0>]
Step 7 − Finally save the chart using the below command.
>>> pylab.savefig("lines.png")
After executing the above command, you could see the following image saved in your Biopython directory.
A histogram is used for continuous data, where the bins represent ranges of data. Drawing histogram is same as line chart except pylab.plot. Instead, call hist method of pylab module with records and some custum value for bins (5). The complete coding is as follows −
Step 1 − Import SeqIO module to read fasta file.
>>> from Bio import SeqIO
Step 2 − Parse the input file.
>>> records = [len(rec) for rec in SeqIO.parse("plot.fasta", "fasta")]
>>> len(records)
11
>>> max(records)
72
>>> min(records)
57
Step 3 − Let us import pylab module.
>>> import pylab
Step 4 − Configure the line chart by assigning x and y axis labels.
>>> pylab.xlabel("sequence length")
Text(0.5, 0, 'sequence length')
>>> pylab.ylabel("count")
Text(0, 0.5, 'count')
>>>
Step 5 − Configure the line chart by setting grid display.
>>> pylab.grid()
Step 6 − Draw simple line chart by calling plot method and supplying records as input.
>>> pylab.hist(records,bins=5)
(array([2., 3., 1., 3., 2.]), array([57., 60., 63., 66., 69., 72.]), <a list
of 5 Patch objects>)
>>>
Step 7 − Finally save the chart using the below command.
>>> pylab.savefig("hist.png")
After executing the above command, you could see the following image saved in your Biopython directory.
GC percentage is one of the commonly used analytic data to compare different sequences. We can do a simple line chart using GC Percentage of a set of sequences and immediately compare it. Here, we can just change the data from sequence length to GC percentage. The complete coding is given below −
Step 1 − Import SeqIO module to read fasta file.
>>> from Bio import SeqIO
Step 2 − Parse the input file.
>>> from Bio.SeqUtils import GC
>>> gc = sorted(GC(rec.seq) for rec in SeqIO.parse("plot.fasta", "fasta"))
Step 3 − Let us import pylab module.
>>> import pylab
Step 4 − Configure the line chart by assigning x and y axis labels.
>>> pylab.xlabel("Genes")
Text(0.5, 0, 'Genes')
>>> pylab.ylabel("GC Percentage")
Text(0, 0.5, 'GC Percentage')
>>>
Step 5 − Configure the line chart by setting grid display.
>>> pylab.grid()
Step 6 − Draw simple line chart by calling plot method and supplying records as input.
>>> pylab.plot(gc)
[<matplotlib.lines.Line2D object at 0x10b6869d 0>]
Step 7 − Finally save the chart using the below command.
>>> pylab.savefig("gc.png")
After executing the above command, you could see the following image saved in your Biopython directory.
In general, Cluster analysis is grouping a set of objects in the same group. This concept is mainly used in data mining, statistical data analysis, machine learning, pattern recognition, image analysis, bioinformatics, etc. It can be achieved by various algorithms to understand how the cluster is widely used in different analysis.
According to Bioinformatics, cluster analysis is mainly used in gene expression data analysis to find groups of genes with similar gene expression.
In this chapter, we will check out important algorithms in Biopython to understand the fundamentals of clustering on a real dataset.
Biopython uses Bio.Cluster module for implementing all the algorithms. It supports the following algorithms −
Hierarchical Clustering
K - Clustering
Self-Organizing Maps
Principal Component Analysis
Let us have a brief introduction on the above algorithms.
Hierarchical clustering is used to link each node by a distance measure to its nearest neighbor and create a cluster. Bio.Cluster node has three attributes: left, right and distance. Let us create a simple cluster as shown below −
>>> from Bio.Cluster import Node
>>> n = Node(1,10)
>>> n.left = 11
>>> n.right = 0
>>> n.distance = 1
>>> print(n)
(11, 0): 1
If you want to construct Tree based clustering, use the below command −
>>> n1 = [Node(1, 2, 0.2), Node(0, -1, 0.5)] >>> n1_tree = Tree(n1)
>>> print(n1_tree)
(1, 2): 0.2
(0, -1): 0.5
>>> print(n1_tree[0])
(1, 2): 0.2
Let us perform hierarchical clustering using Bio.Cluster module.
Consider the distance is defined in an array.
>>> import numpy as np
>>> distance = array([[1,2,3],[4,5,6],[3,5,7]])
Now add the distance array in tree cluster.
>>> from Bio.Cluster import treecluster
>>> cluster = treecluster(distance)
>>> print(cluster)
(2, 1): 0.666667
(-1, 0): 9.66667
The above function returns a Tree cluster object. This object contains nodes where the number of items are clustered as rows or columns.
It is a type of partitioning algorithm and classified into k - means, medians and medoids clustering. Let us understand each of the clustering in brief.
This approach is popular in data mining. The goal of this algorithm is to find groups in the data, with the number of groups represented by the variable K.
The algorithm works iteratively to assign each data point to one of the K groups based on the features that are provided. Data points are clustered based on feature similarity.
>>> from Bio.Cluster import kcluster
>>> from numpy import array
>>> data = array([[1, 2], [3, 4], [5, 6]])
>>> clusterid, error,found = kcluster(data)
>>> print(clusterid) [0 0 1]
>>> print(found)
1
It is another type of clustering algorithm which calculates the mean for each cluster to determine its centroid.
This approach is based on a given set of items, using the distance matrix and the number of clusters passed by the user.
Consider the distance matrix as defined below −
>>> distance = array([[1,2,3],[4,5,6],[3,5,7]])
We can calculate k-medoids clustering using the below command −
>>> from Bio.Cluster import kmedoids
>>> clusterid, error, found = kmedoids(distance)
Let us consider an example.
The kcluster function takes a data matrix as input and not Seq instances. You need to convert your sequences to a matrix and provide that to the kcluster function.
One way of converting the data to a matrix containing numerical elements only is by using the numpy.fromstring function. It basically translates each letter in a sequence to its ASCII counterpart.
This creates a 2D array of encoded sequences that the kcluster function recognized and uses to cluster your sequences.
>>> from Bio.Cluster import kcluster
>>> import numpy as np
>>> sequence = [ 'AGCT','CGTA','AAGT','TCCG']
>>> matrix = np.asarray([np.fromstring(s, dtype=np.uint8) for s in sequence])
>>> clusterid,error,found = kcluster(matrix)
>>> print(clusterid) [1 0 0 1]
This approach is a type of artificial neural network. It is developed by Kohonen and often called as Kohonen map. It organizes items into clusters based on rectangular topology.
Let us create a simple cluster using the same array distance as shown below −
>>> from Bio.Cluster import somcluster
>>> from numpy import array
>>> data = array([[1, 2], [3, 4], [5, 6]])
>>> clusterid,map = somcluster(data)
>>> print(map)
[[[-1.36032469 0.38667395]]
[[-0.41170578 1.35295911]]]
>>> print(clusterid)
[[1 0]
[1 0]
[1 0]]
Here, clusterid is an array with two columns, where the number of rows is equal to the number of items that were clustered, and data is an array with dimensions either rows or columns.
Principal Component Analysis is useful to visualize high-dimensional data. It is a method that uses simple matrix operations from linear algebra and statistics to calculate a projection of the original data into the same number or fewer dimensions.
Principal Component Analysis returns a tuple columnmean, coordinates, components, and eigenvalues. Let us look into the basics of this concept.
>>> from numpy import array
>>> from numpy import mean
>>> from numpy import cov
>>> from numpy.linalg import eig
# define a matrix
>>> A = array([[1, 2], [3, 4], [5, 6]])
>>> print(A)
[[1 2]
[3 4]
[5 6]]
# calculate the mean of each column
>>> M = mean(A.T, axis = 1)
>>> print(M)
[ 3. 4.]
# center columns by subtracting column means
>>> C = A - M
>>> print(C)
[[-2. -2.]
[ 0. 0.]
[ 2. 2.]]
# calculate covariance matrix of centered matrix
>>> V = cov(C.T)
>>> print(V)
[[ 4. 4.]
[ 4. 4.]]
# eigendecomposition of covariance matrix
>>> values, vectors = eig(V)
>>> print(vectors)
[[ 0.70710678 -0.70710678]
[ 0.70710678 0.70710678]]
>>> print(values)
[ 8. 0.]
Let us apply the same rectangular matrix data to Bio.Cluster module as defined below −
>>> from Bio.Cluster import pca
>>> from numpy import array
>>> data = array([[1, 2], [3, 4], [5, 6]])
>>> columnmean, coordinates, components, eigenvalues = pca(data)
>>> print(columnmean)
[ 3. 4.]
>>> print(coordinates)
[[-2.82842712 0. ]
[ 0. 0. ]
[ 2.82842712 0. ]]
>>> print(components)
[[ 0.70710678 0.70710678]
[ 0.70710678 -0.70710678]]
>>> print(eigenvalues)
[ 4. 0.]
Bioinformatics is an excellent area to apply machine learning algorithms. Here, we have genetic information of large number of organisms and it is not possible to manually analyze all this information. If proper machine learning algorithm is used, we can extract lot of useful information from these data. Biopython provides useful set of algorithm to do supervised machine learning.
Supervised learning is based on input variable (X) and output variable (Y). It uses an algorithm to learn the mapping function from the input to the output. It is defined below −
Y = f(X)
The main objective of this approach is to approximate the mapping function and when you have new input data (x), you can predict the output variables (Y) for that data.
Logistic regression is a supervised machine Learning algorithm. It is used to find out the difference between K classes using weighted sum of predictor variables. It computes the probability of an event occurrence and can be used for cancer detection.
Biopython provides Bio.LogisticRegression module to predict variables based on Logistic regression algorithm. Currently, Biopython implements logistic regression algorithm for two classes only (K = 2).
k-Nearest neighbors is also a supervised machine learning algorithm. It works by categorizing the data based on nearest neighbors. Biopython provides Bio.KNN module to predict variables based on k-nearest neighbors algorithm.
Naive Bayes classifiers are a collection of classification algorithms based on Bayes’ Theorem. It is not a single algorithm but a family of algorithms where all of them share a common principle, i.e. every pair of features being classified is independent of each other. Biopython provides Bio.NaiveBayes module to work with Naive Bayes algorithm.
A Markov model is a mathematical system defined as a collection of random variables, that experiences transition from one state to another according to certain probabilistic rules. Biopython provides Bio.MarkovModel and Bio.HMM.MarkovModel modules to work with Markov models.
Biopython have extensive test script to test the software under different conditions to make sure that the software is bug-free. To run the test script, download the source code of the Biopython and then run the below command −
python run_tests.py
This will run all the test scripts and gives the following output −
Python version: 2.7.12 (v2.7.12:d33e0cf91556, Jun 26 2016, 12:10:39)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)]
Operating system: posix darwin
test_Ace ... ok
test_Affy ... ok
test_AlignIO ... ok
test_AlignIO_ClustalIO ... ok
test_AlignIO_EmbossIO ... ok
test_AlignIO_FastaIO ... ok
test_AlignIO_MauveIO ... ok
test_AlignIO_PhylipIO ... ok
test_AlignIO_convert ... ok
...........................................
...........................................
We can also run individual test script as specified below −
python test_AlignIO.py
As we have learned, Biopython is one of the important software in the field of bioinformatics. Being written in python (easy to learn and write), It provides extensive functionality to deal with any computation and operation in the field of bioinformatics. It also provides easy and flexible interface to almost all the popular bioinformatics software to exploit the its functionality as well.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2450,
"s": 2106,
"text": "Biopython is the largest and most popular bioinformatics package for Python. It contains a number of different sub-modules for common bioinformatics tasks. It is developed by Chapman and Chang, mainly written in Python. It also contains C code to optimi... |
Making your first map in javascript | Suppose you are a business owner and your offices are located in 10 different Indian states. Now you want to display this data on your website, then this article is for you, where I am going to cover the process of creating an interactive map using FusionCharts core JavaScript charts library and it’s maps package.
Firstly, there are two ways to display data on your website −
A list with all the addresses or
A list with all the addresses or
An interactive map?
An interactive map?
If you are a visual learner like most people, you will go with the second option – an interactive map.
And if you want to learn how to make an interactive map, you are at the right place.
To make it easy to understand I have divided this tutorial intro into four steps −
Step 1 − Structuring data
Step 1 − Structuring data
Step 2 − Including FusionCharts JavaScript files
Step 2 − Including FusionCharts JavaScript files
Step 3 − Creating Container Element for Chart
Step 3 − Creating Container Element for Chart
Step 4 − Rendering the Map
Step 4 − Rendering the Map
We are going to plot map of India representing number of computers with internet per state for 2013. Below is the tabular data for the same −
FusionCharts understands XML and JSON data and we are going to use JSON for this tutorial.
As we have the data now, we will form the data array in JSON for our map. Data array for maps consists of one object for each state/entity which includes a unique id and value for that state. This id acts as identifier for the state and its corresponding value.
Here is how we will form data for our map −
"data": [
{ "id": "015", "value": "58438" },
{ "id": "014", "value": "41344" },
{ "id": "028", "value": "292124" },
// more map data...
]
This is the first thing that every web developer has to do before actual programming of web-app starts – including dependencies for the project.
In this step we will include JavaScript files provided by FusionCharts using <script> tags in head section of our web page.
We will be including these three files −
FusionCharts core JavaScript file
FusionCharts core JavaScript file
FusionCharts core maps file
FusionCharts core maps file
Map definition file for India
Map definition file for India
And here’s how we do it −
<head>
<script type="text/javascript" src="location/of/fusioncharts.js"></script>
<script type="text/javascript" src="location/of/fusioncharts.maps.js"></script>
<script type="text/javascript" src="location/of/fusioncharts.india.js"></script>
</head>
fusioncharts.js and fusioncharts.maps.js are required to plot any map, while fusioncharts.india.js is required to plot map of India.
To plot map for any other country or state you will have to include JavaScript file for that particular country or state which are available under map definition package provided by FusionCharts.
Our map will occupy its position on web page inside an HTML <div> element. Here is how we do it −
<div id="indian-map">Just a Second!</div>
id for each map or chart on a web page must be unique.
Now that all the things we need to render the map are in place, we will finally use FusionCharts instance to create an object for our chart.
Here is the syntax for the same −
FusionCharts.ready(function() { // // FusionCharts instance
var mapObj=new FusionCharts({ // Map Object // map definition });
});
Now we will implement the above syntax to create object for our map and use render() method to render the chart.
FusionCharts.ready(function() {
var mapOfIndia = new FusionCharts({
type: "maps/india",
renderAt: "indian-map", // div container for our map
height: "650",
width: "100%",
dataFormat: "json",
dataSource: {
"chart": {
"caption": "No. of Computers with Internet in India",
"subCaption": "Census 2011",
"captionFontSize": "25",
// other chart configurations
},
"colorrange": {
"minvalue": "300",
"startlabel": "Low",
"endlabel": "High",
"code": "#efedf5",
"gradient": "1",
"color": [{
"maxvalue": "220000",
"displayvalue": "Avg.",
"code": "#bcbddc"
}, {
"maxvalue": "1400000",
"code": "#756bb1"
}]
},
"data": [{
"id": "015",
"value": "58438"
}, {
"id": "014",
"value": "41344"
}, {
"id": "028",
"value": "292124"
},
// more data
]
}
}).render(); // render method
});
If you have followed all the steps described above, you should have a great looking map of India with you like the one below –
Basic map is good to represent the data, but there are a lot of things that can be done using maps and charts. I am discussing some of them below −
Customizing the Design − FusionCharts provides tons of attributes to customize the map’s look and feel.Here are some of attributes I used to enhance the above mapcaptionFontSize − (int) It is used to change caption’s font size.baseFont − (string) It is used to change the font style across the chart. You are not restricted only to use system fonts, but can also opt for any font family you like. All you have to do is include it in HTML and declare it using this attribute.
Customizing the Design − FusionCharts provides tons of attributes to customize the map’s look and feel.Here are some of attributes I used to enhance the above map
captionFontSize − (int) It is used to change caption’s font size.
captionFontSize − (int) It is used to change caption’s font size.
baseFont − (string) It is used to change the font style across the chart. You are not restricted only to use system fonts, but can also opt for any font family you like. All you have to do is include it in HTML and declare it using this attribute.
baseFont − (string) It is used to change the font style across the chart. You are not restricted only to use system fonts, but can also opt for any font family you like. All you have to do is include it in HTML and declare it using this attribute.
Adding Markers − FusionCharts provides an awesome feature in maps to add markers which can be used to represent locations like cities, malls and landmarks.
Adding Markers − FusionCharts provides an awesome feature in maps to add markers which can be used to represent locations like cities, malls and landmarks.
Moving to Next Level − FusionCharts allows you to take your data viz experience to next level by adding awesome features like drill-down, annotations and events to your map or chart.
Moving to Next Level − FusionCharts allows you to take your data viz experience to next level by adding awesome features like drill-down, annotations and events to your map or chart. | [
{
"code": null,
"e": 1378,
"s": 1062,
"text": "Suppose you are a business owner and your offices are located in 10 different Indian states. Now you want to display this data on your website, then this article is for you, where I am going to cover the process of creating an interactive map using Fusi... |
JavaScript | Object.fromEntries() Method - GeeksforGeeks | 22 Dec, 2021
The Object.fromEntries() method in JavaScript is standard built-in objects which is used to transforms a list of key-value pairs into an object. This method returns a new object whose properties are given by the entries of the iterable
Syntax:
Object.fromEntries( iterable )
Parameters: This method accept single parameter iterable which holds an iterable such as Array or Map or other objects implementing the iterable protocol.
Return value: This method always returns a new object whose properties are given by the entries of the iterable.
Below examples illustrate the Object.fromEntries() method in JavaScript:
Example 1: Conversion of a Map into an Object.
const map1 = new Map([ ['big', 'small'], [1, 0] ]);const geek = Object.fromEntries(map1);console.log(geek); const map2 = new Map( [['Geek1', 'Intern'], ['stipend', 'Works basis']]);const geek1 = Object.fromEntries(map2);console.log(geek1);
Output:
Object { 1: 0, big: "small" }
Object { Geek1: "Intern", stipend: "Works basis" }
Example 2: Conversion of a Array into an Object.
const arr1 = [ ['big', 'small'], [1, 0], ['a', 'z' ]];const geek = Object.fromEntries(arr1);console.log(geek); const arr2 = [ ['Geek1', 'Intern'], ['stipend', 'Works basis'] ];const geek1 = Object.fromEntries(arr2);console.log(geek1);
Output:
Object { 1: 0, big: "small", a: "z" }
Object { Geek1: "Intern", stipend: "Works basis" }
Example 3: Other Conversions
const params = 'type=Get_the Value&geekno=34&paid=10';const searchParams = new URLSearchParams(params); console.log(Object.fromEntries(searchParams)); const object1 = { val1: 112, val2: 345, val3: 76 };const object2 = Object.fromEntries( Object.entries(object1) .map(([ key, val ]) => [ key, val * 3 ]));console.log(object2);
Output:
Object { type: "Get_the Value", geekno: "34", paid: "10" }
Object { val1: 336, val2: 1035, val3: 228 }
Supported Browsers: The browsers supported by Object.fromEntries() method are listed below:
Google Chrome 73 and above
Firefox 63 and above
Opera 60 and above
Safari 12.1 and above
Edge 79 and above
ysachin2314
javascript-functions
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
How to filter object array based on attributes?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 25300,
"s": 25272,
"text": "\n22 Dec, 2021"
},
{
"code": null,
"e": 25536,
"s": 25300,
"text": "The Object.fromEntries() method in JavaScript is standard built-in objects which is used to transforms a list of key-value pairs into an object. This method return... |
MongoDB - Text Search | Starting from version 2.4, MongoDB started supporting text indexes to search inside string content. The Text Search uses stemming techniques to look for specified words in the string fields by dropping stemming stop words like a, an, the, etc. At present, MongoDB supports around 15 languages.
Initially, Text Search was an experimental feature but starting from version 2.6, the configuration is enabled by default.
Consider the following document under posts collection containing the post text and its tags −
> db.posts.insert({
"post_text": "enjoy the mongodb articles on tutorialspoint",
"tags": ["mongodb", "tutorialspoint"]
}
{
"post_text" : "writing tutorials on mongodb",
"tags" : [ "mongodb", "tutorial" ]
})
WriteResult({ "nInserted" : 1 })
We will create a text index on post_text field so that we can search inside our posts' text −
>db.posts.createIndex({post_text:"text"})
{
"createdCollectionAutomatically" : true,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
Now that we have created the text index on post_text field, we will search for all the posts having the word tutorialspoint in their text.
> db.posts.find({$text:{$search:"tutorialspoint"}}).pretty()
{
"_id" : ObjectId("5dd7ce28f1dd4583e7103fe0"),
"post_text" : "enjoy the mongodb articles on tutorialspoint",
"tags" : [
"mongodb",
"tutorialspoint"
]
}
The above command returned the following result documents having the word tutorialspoint in their post text −
{
"_id" : ObjectId("53493d14d852429c10000002"),
"post_text" : "enjoy the mongodb articles on tutorialspoint",
"tags" : [ "mongodb", "tutorialspoint" ]
}
To delete an existing text index, first find the name of index using the following query −
>db.posts.getIndexes()
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "mydb.posts"
},
{
"v" : 2,
"key" : {
"fts" : "text",
"ftsx" : 1
},
"name" : "post_text_text",
"ns" : "mydb.posts",
"weights" : {
"post_text" : 1
},
"default_language" : "english",
"language_override" : "language",
"textIndexVersion" : 3
}
]
>
After getting the name of your index from above query, run the following command. Here, post_text_text is the name of the index.
>db.posts.dropIndex("post_text_text")
{ "nIndexesWas" : 2, "ok" : 1 }
44 Lectures
3 hours
Arnab Chakraborty
54 Lectures
5.5 hours
Eduonix Learning Solutions
44 Lectures
4.5 hours
Kaushik Roy Chowdhury
40 Lectures
2.5 hours
University Code
26 Lectures
8 hours
Bassir Jafarzadeh
70 Lectures
2.5 hours
Skillbakerystudios
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2847,
"s": 2553,
"text": "Starting from version 2.4, MongoDB started supporting text indexes to search inside string content. The Text Search uses stemming techniques to look for specified words in the string fields by dropping stemming stop words like a, an, the, etc. At presen... |
Creating Joy Plots Using JoyPy. Using JoyPy for creating series of... | by Himanshu Sharma | Towards Data Science | Visualization is a core part of finding insights and can be used for storytelling. While creating visualization we need to think about which plot to use, which features to consider, what story will be coming out, or finding root cause analysis. Have you ever been stuck with these problems?
There are different python libraries that can be used for data visualization. In this article, will be discussing a rare type of plot known as Joy Plots. They are a series of histograms, density plots, or time series data in which we create stacked visualization by fixing the data point on the X-axis and creating a stack on the Y-axis.
In this article, we will explore JoyPy an open-source python library that is used to create Joy Plots.
Let’s get started...
We will start by installing a Joy Plots library by using pip. The command given below will do that.
!pip install joypy
In this step, we will import the required libraries for loading the dataset and visualizing it.
import joypyimport seaborn as sns
Fo this article, we will use the famous “Tips” dataset which is already defined in the seaborn library.
df = sns.load_dataset('tips')df
Now we will start by creating different types of joy plots using different columns of the data.
fig, axes = joypy.joyplot(df)
This plot shows the distribution of all the numerical columns in the dataset.
fig, axes = joypy.joyplot(df, by="smoker")
This graph shows the distribution of the numerical columns with respect to the smoker column.
fig, axes = joypy.joyplot(df, by="size", ylim='day')
fig, axes = joypy.joyplot(df, by="day", overlap=10)
Go ahead try this with different datasets and create different visualizations using JoyPy. In case you find any difficulty please let me know in the response section.
This article is in collaboration with Piyush Ingale.
Thanks for reading! If you want to get in touch with me, feel free to reach me at hmix13@gmail.com or my LinkedIn Profile. You can view my Github profile for different data science projects and packages tutorials. Also, feel free to explore my profile and read different articles I have written related to Data Science. | [
{
"code": null,
"e": 463,
"s": 172,
"text": "Visualization is a core part of finding insights and can be used for storytelling. While creating visualization we need to think about which plot to use, which features to consider, what story will be coming out, or finding root cause analysis. Have you e... |
java.lang.reflect.Field Class in Java - GeeksforGeeks | 09 Mar, 2021
The ability of the software to analyze itself is known as Reflection. This is provided by the java.lang.reflect package and elements in Class .Field serves the same purpose as the whole reflection mechanism, analyze a software component and describe its capabilities dynamically, at run time rather than at compile time .Java, like many other languages, is statically typed. Reflection mechanisms allow one to bypass it to some degree, and introduce some more dynamic features, like, say, retrieval of the value of the field by name. The package java.lang.reflect includes several interfaces. Of special interest is Member which defines methods that allow getting information about a field, constructor or method of a class. There are also ten classes in this package i.e. AccessibleObject, Array, Constructor, Executable, Field, Method, Modifier, Parameter, Proxy, ReflectPermission.
The following application illustrates a simple use of java reflection. It prints the fields of the class java.awt.Dimension. The program begins with forName() method of Class to get a class object for java.awt.Dimension. Once this is obtained, getFields() is used to analyze the class object. They return an array of Field objects that provide information about the object.
Example 1:
Java
import java.lang.reflect.Field; public class GFG { public static void main(String[] args) throws Exception { // Create the User class object User user = new User(); // Get the all field objects of User class Field[] fields = User.class.getFields(); for (int i = 0; i < fields.length; i++) { // get value of the fields Object value = fields[i].get(user); // print result System.out.println("Value of Field " + fields[i].getName() + " is " + value); } } } // sample User class class User { public static String name = "Dipsundar"; public static String getName() { return name; } public static void setName(String name) { User.name = name; } }
Value of Field name is Dipsundar
Example 2:
Java
import java.lang.reflect.Field; public class GFG { public static void main(String[] args) throws Exception { // Create the User class object User user = new User(); // Get the all field objects of User class Field[] fields = User.class.getFields(); for (int i = 0; i < fields.length; i++) { // get value of the fields Object value = fields[i].get(user); // print result System.out.println("Value of Field " + fields[i].getName() + " is " + value); } }} // sample User classclass User { public static String name = "Dipsundar"; public static String getName() { return name; } public static void setName(String name) { User.name = name; }}
Value of Field booleanValue is false
java-lang-reflect-package
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways of Reading a text file in Java
Stream In Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
HashMap get() Method in Java
Comparator Interface in Java with Examples
Strings in Java
StringBuilder Class in Java with Examples | [
{
"code": null,
"e": 23948,
"s": 23920,
"text": "\n09 Mar, 2021"
},
{
"code": null,
"e": 24833,
"s": 23948,
"text": "The ability of the software to analyze itself is known as Reflection. This is provided by the java.lang.reflect package and elements in Class .Field serves the sam... |
Number of Triangles in Directed and Undirected Graphs - GeeksforGeeks | 21 Jan, 2022
Given a Graph, count number of triangles in it. The graph is can be directed or undirected.
Example:
Input: digraph[V][V] = { {0, 0, 1, 0},
{1, 0, 0, 1},
{0, 1, 0, 0},
{0, 0, 1, 0}
};
Output: 2
Give adjacency matrix represents following
directed graph.
We have discussed a method based on graph trace that works for undirected graphs. In this post a new method is discussed with that is simpler and works for both directed and undirected graphs.The idea is to use three nested loops to consider every triplet (i, j, k) and check for the above condition (there is an edge from i to j, j to k and k to i) However in an undirected graph, the triplet (i, j, k) can be permuted to give six combination (See previous post for details). Hence we divide the total count by 6 to get the actual number of triangles. In case of directed graph, the number of permutation would be 3 (as order of nodes becomes relevant). Hence in this case the total number of triangles will be obtained by dividing total count by 3. For example consider the directed graph given below
Following is the implementation.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to count triangles// in a graph. The program is for// adjacency matrix representation// of the graph.#include<bits/stdc++.h> // Number of vertices in the graph#define V 4 using namespace std; // function to calculate the// number of triangles in a// simple directed/undirected// graph. isDirected is true if// the graph is directed, its// false otherwiseint countTriangle(int graph[V][V], bool isDirected){ // Initialize result int count_Triangle = 0; // Consider every possible // triplet of edges in graph for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { for (int k = 0; k < V; k++) { // Check the triplet if // it satisfies the condition if (graph[i][j] && graph[j][k] && graph[k][i]) count_Triangle++; } } } // If graph is directed , // division is done by 3, // else division by 6 is done isDirected? count_Triangle /= 3 : count_Triangle /= 6; return count_Triangle;} //driver function to check the programint main(){ // Create adjacency matrix // of an undirected graph int graph[][V] = { {0, 1, 1, 0}, {1, 0, 1, 1}, {1, 1, 0, 1}, {0, 1, 1, 0} }; // Create adjacency matrix // of a directed graph int digraph[][V] = { {0, 0, 1, 0}, {1, 0, 0, 1}, {0, 1, 0, 0}, {0, 0, 1, 0} }; cout << "The Number of triangles in undirected graph : " << countTriangle(graph, false); cout << "\n\nThe Number of triangles in directed graph : " << countTriangle(digraph, true); return 0;}
// Java program to count triangles// in a graph. The program is// for adjacency matrix// representation of the graph.import java.io.*; class GFG { // Number of vertices in the graph int V = 4; // function to calculate the number // of triangles in a simple // directed/undirected graph. isDirected // is true if the graph is directed, // its false otherwise. int countTriangle(int graph[][], boolean isDirected) { // Initialize result int count_Triangle = 0; // Consider every possible // triplet of edges in graph for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { for (int k=0; k<V; k++) { // Check the triplet if it // satisfies the condition if (graph[i][j] == 1 && graph[j][k] == 1 && graph[k][i] == 1) count_Triangle++; } } } // If graph is directed , division // is done by 3 else division // by 6 is done if(isDirected == true) { count_Triangle /= 3; } else { count_Triangle /= 6; } return count_Triangle; } // Driver code public static void main(String args[]) { // Create adjacency matrix // of an undirected graph int graph[][] = {{0, 1, 1, 0}, {1, 0, 1, 1}, {1, 1, 0, 1}, {0, 1, 1, 0} }; // Create adjacency matrix // of a directed graph int digraph[][] = { {0, 0, 1, 0}, {1, 0, 0, 1}, {0, 1, 0, 0}, {0, 0, 1, 0} }; GFG obj = new GFG(); System.out.println("The Number of triangles "+ "in undirected graph : " + obj.countTriangle(graph, false)); System.out.println("\n\nThe Number of triangles"+ " in directed graph : "+ obj.countTriangle(digraph, true)); }} // This code is contributed by Anshika Goyal.
# Python program to count triangles# in a graph. The program is# for adjacency matrix# representation of the graph. # function to calculate the number# of triangles in a simple# directed/undirected graph.# isDirected is true if the graph# is directed, its false otherwisedef countTriangle(g, isDirected): nodes = len(g) count_Triangle = 0 # Consider every possible # triplet of edges in graph for i in range(nodes): for j in range(nodes): for k in range(nodes): # check the triplet # if it satisfies the condition if(i != j and i != k and j != k and g[i][j] and g[j][k] and g[k][i]): count_Triangle += 1 # If graph is directed , division is done by 3 # else division by 6 is done if isDirected: return count_Triangle//3 else: return count_Triangle//6 # Create adjacency matrix of an undirected graphgraph = [[0, 1, 1, 0], [1, 0, 1, 1], [1, 1, 0, 1], [0, 1, 1, 0]]# Create adjacency matrix of a directed graphdigraph = [[0, 0, 1, 0], [1, 0, 0, 1], [0, 1, 0, 0], [0, 0, 1, 0]] print("The Number of triangles in undirected graph : %d" % countTriangle(graph, False)) print("The Number of triangles in directed graph : %d" % countTriangle(digraph, True)) # This code is contributed by Neelam Yadav
// C# program to count triangles in a graph.// The program is for adjacency matrix// representation of the graph.using System; class GFG { // Number of vertices in the graph const int V = 4; // function to calculate the // number of triangles in a // simple directed/undirected // graph. isDirected is true if // the graph is directed, its // false otherwise static int countTriangle(int[, ] graph, bool isDirected) { // Initialize result int count_Triangle = 0; // Consider every possible // triplet of edges in graph for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { for (int k = 0; k < V; k++) { // check the triplet if // it satisfies the condition if (graph[i, j] != 0 && graph[j, k] != 0 && graph[k, i] != 0) count_Triangle++; } } } // if graph is directed , // division is done by 3, // else division by 6 is done if (isDirected != false) count_Triangle = count_Triangle / 3; else count_Triangle = count_Triangle / 6; return count_Triangle; } // Driver code static void Main() { // Create adjacency matrix // of an undirected graph int[, ] graph = new int[4, 4] { { 0, 1, 1, 0 }, { 1, 0, 1, 1 }, { 1, 1, 0, 1 }, { 0, 1, 1, 0 } }; // Create adjacency matrix // of a directed graph int[, ] digraph = new int[4, 4] { { 0, 0, 1, 0 }, { 1, 0, 0, 1 }, { 0, 1, 0, 0 }, { 0, 0, 1, 0 } }; Console.Write("The Number of triangles" + " in undirected graph : " + countTriangle(graph, false)); Console.Write("\n\nThe Number of " + "triangles in directed graph : " + countTriangle(digraph, true)); }} // This code is contributed by anuj_67
<?php// PHP program to count triangles// in a graph. The program is for// adjacency matrix representation// of the graph. // Number of vertices in the graph$V = 4; // function to calculate the// number of triangles in a// simple directed/undirected// graph. isDirected is true if// the graph is directed, its// false otherwisefunction countTriangle($graph, $isDirected){ global $V; // Initialize result $count_Triangle = 0; // Consider every possible // triplet of edges in graph for($i = 0; $i < $V; $i++) { for($j = 0; $j < $V; $j++) { for($k = 0; $k < $V; $k++) { // check the triplet if // it satisfies the condition if ($graph[$i][$j] and $graph[$j][$k] and $graph[$k][$i]) $count_Triangle++; } } } // if graph is directed , // division is done by 3, // else division by 6 is done $isDirected? $count_Triangle /= 3 : $count_Triangle /= 6; return $count_Triangle;} // Driver Code // Create adjacency matrix // of an undirected graph $graph = array(array(0, 1, 1, 0), array(1, 0, 1, 1), array(1, 1, 0, 1), array(0, 1, 1, 0)); // Create adjacency matrix // of a directed graph $digraph = array(array(0, 0, 1, 0), array(1, 0, 0, 1), array(0, 1, 0, 0), array(0, 0, 1, 0)); echo "The Number of triangles in undirected graph : " , countTriangle($graph, false); echo "\nThe Number of triangles in directed graph : " , countTriangle($digraph, true); // This code is contributed by anuj_67?>
<script> // Javascript program to count triangles// in a graph. The program is for// adjacency matrix representation// of the graph. // Number of vertices in the graphlet V = 4; // Function to calculate the// number of triangles in a// simple directed/undirected// graph. isDirected is true if// the graph is directed, its// false otherwisefunction countTriangle(graph, isDirected){ // Initialize result let count_Triangle = 0; // Consider every possible // triplet of edges in graph for(let i = 0; i < V; i++) { for(let j = 0; j < V; j++) { for(let k = 0; k < V; k++) { // Check the triplet if // it satisfies the condition if (graph[i][j] && graph[j][k] && graph[k][i]) count_Triangle++; } } } // If graph is directed , // division is done by 3, // else division by 6 is done isDirected ? count_Triangle /= 3 : count_Triangle /= 6; return count_Triangle;} // Driver code // Create adjacency matrix// of an undirected graphlet graph = [ [ 0, 1, 1, 0 ], [ 1, 0, 1, 1 ], [ 1, 1, 0, 1 ], [ 0, 1, 1, 0 ] ]; // Create adjacency matrix// of a directed graphlet digraph = [ [ 0, 0, 1, 0 ], [ 1, 0, 0, 1 ], [ 0, 1, 0, 0 ], [ 0, 0, 1, 0 ] ]; document.write("The Number of triangles " + "in undirected graph : " + countTriangle(graph, false) + "</br></br>");document.write("The Number of triangles " + "in directed graph : " + countTriangle(digraph, true)); // This code is contributed by divyesh072019 </script>
The Number of triangles in undirected graph : 2
The Number of triangles in directed graph : 2
Comparison of this approach with previous approach: Advantages:
No need to calculate Trace.
Matrix- multiplication is not required.
Auxiliary matrices are not required hence optimized in space.
Works for directed graphs.
Disadvantages:
The time complexity is O(n3) and can’t be reduced any further.
This article is contributed by Ashutosh 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
vt_m
cybertrone
divyesh072019
amartyaghoshgfg
triangle
Graph
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Topological Sorting
Detect Cycle in a Directed Graph
Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Check whether a given graph is Bipartite or not
Ford-Fulkerson Algorithm for Maximum Flow Problem
Traveling Salesman Problem (TSP) Implementation
Detect cycle in an undirected graph
Shortest path in an unweighted graph
Union-Find Algorithm | Set 2 (Union By Rank and Path Compression) | [
{
"code": null,
"e": 25016,
"s": 24988,
"text": "\n21 Jan, 2022"
},
{
"code": null,
"e": 25108,
"s": 25016,
"text": "Given a Graph, count number of triangles in it. The graph is can be directed or undirected."
},
{
"code": null,
"e": 25118,
"s": 25108,
"text":... |
How to check object is an array in JavaScript? - GeeksforGeeks | 25 Apr, 2019
Method 1: Using Array.isArray() function: The Array.isArray() function determines whether the value passed to this function is an array or not. This function returns true if the argument passed is array else it returns false.
Syntax:
Array.isArray(obj)
Here, obj is any valid object in JavaScript like map, list, array, string, etc.
Return Value: It returns Boolean value true if the object passed is an array or false if the object passed is not an array.
Example 1: This example uses Array.isArray() function to check the object is array or not.
<!DOCTYPE html><html> <head> <title> check object is an array </title></head> <body> <p> Click on button to check for array </p> <button onclick="myFunction()"> Try it </button> <p id="GFG"></p> <script> function myFunction() { var countries = ["India", "USA", "Canada"]; var x = document.getElementById("GFG"); x.innerHTML = Array.isArray(countries); } </script></body> </html>
Output:
Example 2: This example uses Array.isArray() function to check the object is array or not.
<!DOCTYPE html><html> <head> <title> check object is an array </title></head> <body> <p> Click on button to check for array </p> <button onclick="myFunction()"> Try it </button> <p id="GFG"></p> <script> function myFunction() { // It returns false as the object passed is // String not an array document.write(Array.isArray( 'hello GeeksForGeeks')); } </script></body> </html>
Output:
Before Clicking the button:
After Clicking the button:
Example 3: This example uses Array.isArray() function to check the object is array or not.
<!DOCTYPE html><html> <head> <title> check object is an array </title></head> <body> <p> Click on button to check for array </p> <button onclick="myFunction()"> Try it </button> <p id="GFG"></p> <script> function myFunction() { // It returns false as the object passed is // String not an array document.write(Array.isArray({k:12})); } </script></body> </html>
Output:
Before Clicking the button:
After Clicking the button:
Method 2: Using typeof operator: In JavaScript, the typeof operator returns the data type of its operand in the form of a string where an operand can be any object, function or variable. However, the problem with this is that it isn’t applicable for determining array.
Syntax:
typeof operand or typeof(operand)
Example:
<!DOCTYPE html><html> <head> <title> check object is an array </title></head> <body> <p id="GFG"></p> <script> document.getElementById("GFG").innerHTML = typeof "Geeks" + "<br>" + typeof [1, 2, 3, 4] + "<br>" + typeof {name:'Kartik', age:20} + "<br>" + typeof new Date() + "<br>" + typeof function () {} + "<br>" + typeof job + "<br>" + typeof null; </script> </body> </html>
Output:
JavaScript-Misc
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Difference Between PUT and PATCH Request
Set the value of an input field in JavaScript
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 24472,
"s": 24444,
"text": "\n25 Apr, 2019"
},
{
"code": null,
"e": 24698,
"s": 24472,
"text": "Method 1: Using Array.isArray() function: The Array.isArray() function determines whether the value passed to this function is an array or not. This function retur... |
How to implement Clustering in Power BI using PyCaret | by Moez Ali | Towards Data Science | In our last post, we demonstrated how to build an anomaly detector in Power BI by integrating it with PyCaret, thus allowing analysts and data scientists to add a layer of machine learning to their reports and dashboards without any additional license costs.
In this post, we will see how we can implement Clustering Analysis in Power BI using PyCaret. If you haven’t heard about PyCaret before, please read this announcement to learn more.
What is Clustering? Types of Clustering.
Train and implement an unsupervised Clustering model in Power BI.
Analyze results and visualize information in a dashboard.
How to deploy the Clustering model in Power BI production?
If you have used Python before, it is likely that you already have Anaconda Distribution installed on your computer. If not, click here to download Anaconda Distribution with Python 3.7 or greater.
Before we start using PyCaret’s machine learning capabilities in Power BI we have to create a virtual environment and install pycaret. It’s a three-step process:
✅ Step 1 — Create an anaconda environment
Open Anaconda Prompt from start menu and execute the following code:
conda create --name myenv python=3.7
✅ Step 2 — Install PyCaret
Execute the following code in Anaconda Prompt:
pip install pycaret
Installation may take 15–20 minutes. If you are having issues with installation, please see our GitHub page for known issues and resolutions.
✅Step 3 — Set Python Directory in Power BI
The virtual environment created must be linked with Power BI. This can be done using Global Settings in Power BI Desktop (File → Options → Global → Python scripting). Anaconda Environment by default is installed under:
C:\Users\username\AppData\Local\Continuum\anaconda3\envs\myenv
Clustering is a technique that groups data points with similar characteristics. These groupings are useful for exploring data, identifying patterns and analyzing a subset of data. Organising data into clusters helps in identify underlying structures in the data and finds applications across many industries. Some common business use cases for clustering are:
✔ Customer segmentation for the purpose of marketing.
✔ Customer purchasing behavior analysis for promotions and discounts.
✔ Identifying geo-clusters in an epidemic outbreak such as COVID-19.
Given the subjective nature of clustering tasks, there are various algorithms that suit different types of problems. Each algorithm has its own rules and the mathematics behind how clusters are calculated.
This tutorial is about implementing a clustering analysis in Power BI using a Python library called PyCaret. Discussion of the specific algorithmic details and mathematics behind these algorithms are out-of-scope for this tutorial.
In this tutorial we will use a K-Means algorithm which is one of the simplest and most popular unsupervised machine learning algorithms. If you would like to learn more about K-Means, you can read this paper.
In this tutorial we will use the current health expenditure dataset from the World Health Organization’s Global Health Expenditure database. The dataset contains health expenditure as a % of National GDP for over 200 countries from year 2000 through 2017.
Our objective is to find patterns and groups in this data by using a K-Means clustering algorithm.
Source Data
Now that you have set up the Anaconda Environment, installed PyCaret, understand the basics of Clustering Analysis and have the business context for this tutorial, let’s get started.
The first step is importing the dataset into Power BI Desktop. You can load the data using a web connector. (Power BI Desktop → Get Data → From Web).
Link to csv file: https://github.com/pycaret/powerbi-clustering/blob/master/clustering.csv
To train a clustering model in Power BI we will have to execute a Python script in Power Query Editor (Power Query Editor → Transform → Run python script). Run the following code as a Python script:
from pycaret.clustering import *dataset = get_clusters(dataset, num_clusters=5, ignore_features=['Country'])
We have ignored the ‘Country’ column in the dataset using the ignore_features parameter. There could be many reasons for which you might not want to use certain columns for training a machine learning algorithm.
PyCaret allows you to hide instead of drop unneeded columns from a dataset as you might require those columns for later analysis. For example, in this case we don’t want to use ‘Country’ for training an algorithm and hence we have passed it under ignore_features.
There are over 8 ready-to-use clustering algorithms available in PyCaret.
By default, PyCaret trains a K-Means Clustering model with 4 clusters. Default values can be changed easily:
To change the model type use the model parameter within get_clusters().
To change the cluster number, use the num_clusters parameter.
See the example code for K-Modes Clustering with 6 clusters.
from pycaret.clustering import *dataset = get_clusters(dataset, model='kmodes', num_clusters=6, ignore_features=['Country'])
Output:
A new column which contains the cluster label is attached to the original dataset. All the year columns are then unpivoted to normalize the data so it can be used for visualization in Power BI.
Here’s how the final output looks like in Power BI.
Once you have cluster labels in Power BI, here’s an example of how you can visualize it in dashboard to generate insights:
You can download the PBIX file and the data set from our GitHub.
What has been demonstrated above was one simple way to implement Clustering in Power BI. However, it is important to note that the method shown above trains the clustering model every time the Power BI dataset is refreshed. This may be a problem for two reasons:
When the model is re-trained with new data, the cluster labels may change (eg: some data points that were labeled as Cluster 1 earlier might be labelled as Cluster 2 when re-trained)
You don’t want to spend hours of time everyday re-training the model.
A more productive way to implement clustering in Power BI is to use a pre-trained model for generating cluster labels instead of re-training the model every time.
You can use any Integrated Development Environment (IDE)or Notebook for training machine learning models. In this example, we have used Visual Studio Code to train a clustering model.
A trained model is then saved as a pickle file and imported into Power Query for generating cluster labels.
If you would like to learn more about implementing Clustering Analysis in Jupyter notebook using PyCaret, watch this 2 minute video tutorial:
Execute the below code as a Python script to generate labels from the pre-trained model.
from pycaret.clustering import *dataset = predict_model('c:/.../clustering_deployment_20052020, data = dataset)
The output of this will be the same as the one we saw above. The difference is that when you use a pre-trained model, the label is generated on a new dataset using the same model instead of re-training the model.
Once you’ve uploaded the .pbix file to the Power BI service, a couple more steps are necessary to enable seamless integration of the machine learning pipeline into your data pipeline. These include:
Enable scheduled refresh for the dataset — to enable a scheduled refresh for the workbook that contains your dataset with Python scripts, see Configuring scheduled refresh, which also includes information about Personal Gateway.
Install the Personal Gateway — you need a Personal Gateway installed on the machine where the file is located, and where Python is installed; the Power BI service must have access to that Python environment. You can get more information on how to install and configure Personal Gateway.
If you are Interested in learning more about Clustering Analysis, checkout our Notebook Tutorial.
We have received overwhelming support and feedback from the community. We are actively working on improving PyCaret and preparing for our next release. PyCaret 1.0.1 will be bigger and better. If you would like to share your feedback and help us improve further, you may fill this form on the website or leave a comment on our GitHub or LinkedIn page.
Follow our LinkedIn and subscribe to our Youtube channel to learn more about PyCaret.
User Guide / DocumentationGitHub RepositoryInstall PyCaretNotebook TutorialsContribute in PyCaret
As of the first release 1.0.0, PyCaret has the following modules available for use. Click on the links below to see the documentation and working examples in Python.
ClassificationRegressionClusteringAnomaly DetectionNatural Language ProcessingAssociation Rule Mining
PyCaret getting started tutorials in Notebook:
ClusteringAnomaly DetectionNatural Language ProcessingAssociation Rule MiningRegressionClassification
PyCaret is an open source project. Everybody is welcome to contribute. If you would like to contribute, please feel free to work on open issues. Pull requests are accepted with unit tests on dev-1.0.1 branch.
Please give us ⭐️ on our GitHub repo if you like PyCaret.
Medium : https://medium.com/@moez_62905/
LinkedIn : https://www.linkedin.com/in/profile-moez/
Twitter : https://twitter.com/moezpycaretorg1 | [
{
"code": null,
"e": 431,
"s": 172,
"text": "In our last post, we demonstrated how to build an anomaly detector in Power BI by integrating it with PyCaret, thus allowing analysts and data scientists to add a layer of machine learning to their reports and dashboards without any additional license cos... |
JavaScript Object.keys( ) Function - GeeksforGeeks | 30 Nov, 2021
In this article, we will learn the Object.keys() method in Javascript, along with understanding its implementation through the examples.
Object and Object Constructors in JavaScript: In object-oriented programming, JavaScript has the concept of objects and constructors that work mostly in the same manner & can perform similar kinds of operations, likewise in other programming languages. An Object in JavaScript may be defined as an unordered collection of related data, of primitive or reference types, in the form of “key: value” pairs. These keys can be variables or functions and are called properties and methods, respectively, in the context of an object.
Constructors are general JavaScript functions used with the new keyword & have two types i.e. built-in constructors(array and object) and custom constructors(defined properties and methods for specific objects). Constructors can be useful to create an object “type” that can be used multiple times without having to redefine the object every time and this could be achieved using the Object Constructor function. It’s a convention to capitalize the name of constructors to distinguish them from regular functions.
For instance, consider the following code:
function Automobile(color) {
this.color=color;
}
var vehicle1 = new Automobile ("red");
The function “Automobile()” is an object constructor, and its properties and methods i.e “color” is declared inside it by prefixing it with the keyword “this”. Objects defined using an object constructor are then made instants using the keyword “new”. When new Automobile() is called, JavaScript does two things:
It creates a fresh new object(instance) Automobile() and assigns it to a variable.
It sets the constructor property i.e “color” of the object to Automobile.
Object.keys() Method: The Object.keys() method is used to return an array whose elements are strings corresponding to the enumerable properties found directly upon an object. The ordering of the properties is the same as that given by the object manually in a loop is applied to the properties. Object.keys() takes the object as an argument of which the enumerable own properties are to be returned and returns an array of strings that represent all the enumerable properties of the given object.
Syntax:
Object.keys(obj);
Parameter value:
obj: It is the object whose enumerable properties are to be returned.
Return Value: It returns an array of strings that represent all the enumerable properties of the given object.
Applications: It can be used for returning enumerable properties of a simple array, an array-like object & an array-like object with random key ordering.
We will understand the concept of the above function through the examples.
Example 1: In this example, an array “check” has three property values [‘x’, ‘y’, ‘z’] and the object.keys() method returns the enumerable properties of this array. The ordering of the properties is the same as that given by the object manually.
Javascript
<script> // Returning enumerable properties // of a simple array var check = ['x', 'y', 'z']; console.log(Object.keys(check));</script>
Output:
['0', '1', '2']
Example 2: In this example, an array-like object “check” has three property values { 0: ‘x’, 1: ‘y’, 2: ‘z’ } and the object.keys() method returns the enumerable properties of this array. The ordering of the properties is the same as that given by the object manually.
Javascript
<script> // Returning enumerable properties // of an array like object. var object = { 0: 'x', 1: 'y', 2: 'z' }; console.log(Object.keys(object));</script>
Output:
['0', '1', '2']
Example 3: In this example, an array-like object “check” has three property values { 70: ‘x’, 21: ‘y’, 35: ‘z’ } in random ordering and the object.keys() method returns the enumerable properties of this array in the ascending order of the value of indices.
Javascript
<script> // Returning enumerable properties of an array // like object with random key ordering. var object = { 70: 'x', 21: 'y', 35: 'z' }; console.log(Object.keys(object));</script>
Output:
['21', '35', '70']
Exceptions:
It causes a TypeError if the argument passed is not an object.
If an object is not passed as an argument to the method, then it persuades it and treats it as an object.
Supported Browser:
Google Chrome 5.0
Microsoft Edge 12.0
Firefox 4.0
Internet Explorer 9.0
Opera 12.0
Safari 5.0
ysachin2314
bhaskargeeksforgeeks
javascript-functions
javascript-object
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Difference Between PUT and PATCH Request
JavaScript | console.log() with Examples
Node.js | fs.writeFileSync() Method
Set the value of an input field in JavaScript
How to read a local text file using JavaScript? | [
{
"code": null,
"e": 24662,
"s": 24634,
"text": "\n30 Nov, 2021"
},
{
"code": null,
"e": 24799,
"s": 24662,
"text": "In this article, we will learn the Object.keys() method in Javascript, along with understanding its implementation through the examples."
},
{
"code": null... |
How to switch between dark and light mode with CSS and JavaScript?
| To switch between dark and light mode with JavaScript, the code is as follows −
Live Demo
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
body {
padding: 25px;
background-color: white;
color: black;
font-size: 25px;
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.dark-mode {
background-color: black;
color: white;
}
.toggleButton {
padding: 12px;
font-size: 18px;
border: 2px solid green;
}
</style>
</head>
<body>
<h1>Toggle Dark/Light Mode Example</h1>
<button class="toggleButton">Toggle dark mode</button>
<h2>Click the above button to toggle dark mode</h2>
<script>
document .querySelector(".toggleButton") .addEventListener("click", toggleDarKMode);
function toggleDarKMode() {
var element = document.body;
element.classList.toggle("dark-mode");
}
</script>
</body>
</html>
The above code will produce the following output −
On clicking the “Toggle dark mode” button − | [
{
"code": null,
"e": 1142,
"s": 1062,
"text": "To switch between dark and light mode with JavaScript, the code is as follows −"
},
{
"code": null,
"e": 1153,
"s": 1142,
"text": " Live Demo"
},
{
"code": null,
"e": 2021,
"s": 1153,
"text": "<!DOCTYPE html>\n<ht... |
Writing UTF8 data to a file using Java | In general, data is stored in a computer in the form of bits (1 or, 0). There are various coding schemes available specifying the set of bytes represented by each character.
Unicode (UTF) − Stands for Unicode Translation Format. It is developed by The Unicode Consortium. if you want to create documents that use characters from multiple character sets, you will be able to do so using the single Unicode character encodings. It provides 3 types of encodings.
UTF-8 − It comes in 8-bit units (bytes), a character in UTF8 can be from 1 to 4 bytes long, making UTF8 variable width.
UTF-8 − It comes in 8-bit units (bytes), a character in UTF8 can be from 1 to 4 bytes long, making UTF8 variable width.
UTF-16 − It comes in 16-bit units (shorts), it can be 1 or 2 shorts long, making UTF16 variable width.
UTF-16 − It comes in 16-bit units (shorts), it can be 1 or 2 shorts long, making UTF16 variable width.
UTF-32 − It comes in 32-bit units (longs). It is a fixed-width format and is always 1 "long" in length.
UTF-32 − It comes in 32-bit units (longs). It is a fixed-width format and is always 1 "long" in length.
The write UTF() method of the java.io.DataOutputStream class accepts a String value as a parameter and writes it in using modified UTF-8 encoding, to the current output stream. Therefore to write UTF-8 data to a file −
Instantiate the FileOutputStream class by passing a String value representing the path of the required file, as a parameter.
Instantiate the FileOutputStream class by passing a String value representing the path of the required file, as a parameter.
Instantiate the DataOutputStream class bypassing the above created FileOutputStream object as a parameter.
Instantiate the DataOutputStream class bypassing the above created FileOutputStream object as a parameter.
Write UTF data to the above created OutputStream object using the write UTF() method.
Write UTF data to the above created OutputStream object using the write UTF() method.
Flush the contents of the OutputStream object to the file (destination) using the flush() method
Flush the contents of the OutputStream object to the file (destination) using the flush() method
Live Demo
import java.io.DataOutputStream;
import java.io.FileOutputStream;
public class UTF8Example {
public static void main(String args[]) throws Exception{
//Instantiating the FileOutputStream class
FileOutputStream fileOut = new FileOutputStream("D:\\samplefile.txt");
//Instantiating the DataOutputStream class
DataOutputStream outputStream = new DataOutputStream(fileOut);
//Writing UTF data to the output stream
outputStream.writeUTF("టుటోరియల్స్ పాయింట్ కి స్వాగతిం");
outputStream.flush();
System.out.println("Data entered into the file");
}
}
Data entered into the file
The newBufferedWriter() method of the java.nio.file.Files class accepts an object of the class Path representing the path of the file and an object of the class Charset representing the type of the character sequences that are to be read() and, returns a BufferedWriter object that could write the data in the specified format
The value for the Charset could be StandardCharsets.UTF_8 or, StandardCharsets.UTF_16LE or, StandardCharsets.UTF_16BE or, StandardCharsets.UTF_16 or, StandardCharsets.US_ASCII or, StandardCharsets.ISO_8859_1
Therefore to write UTF-8 data to a file −
Create/get an object of the Path class representing the required path using the get() method of the java.nio.file.Paths class.
Create/get an object of the Path class representing the required path using the get() method of the java.nio.file.Paths class.
Create/get a BufferedWriter object, that could write UtF-8 data, bypassing the above-created Path object and StandardCharsets.UTF_8 as parameters.
Create/get a BufferedWriter object, that could write UtF-8 data, bypassing the above-created Path object and StandardCharsets.UTF_8 as parameters.
Append the UTF-8 data to the above created BufferedWriter object using the append().
Append the UTF-8 data to the above created BufferedWriter object using the append().
Flush the contents of the BufferedWriter to the (destination) file using the flush() method.
Flush the contents of the BufferedWriter to the (destination) file using the flush() method.
Live Demo
import java.io.BufferedWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class UTF8Example {
public static void main(String args[]) throws Exception{
//Getting the Path object
Path path = Paths.get("D:\\samplefile.txt");
//Creating a BufferedWriter object
BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8);
//Appending the UTF-8 String to the file
writer.append("టుటోరియల్స్ పాయింట్ కి స్వాగతిం");
//Flushing data to the file
writer.flush();
System.out.println("Data entered into the file");
}
}
Data entered into the file | [
{
"code": null,
"e": 1236,
"s": 1062,
"text": "In general, data is stored in a computer in the form of bits (1 or, 0). There are various coding schemes available specifying the set of bytes represented by each character."
},
{
"code": null,
"e": 1522,
"s": 1236,
"text": "Unicode ... |
C library function - cos() | The C library function double cos(double x) returns the cosine of a radian angle x.
Following is the declaration for cos() function.
double cos(double x)
x − This is the floating point value representing an angle expressed in radians.
x − This is the floating point value representing an angle expressed in radians.
This function returns the cosine of x.
The following example shows the usage of cos() function.
#include <stdio.h>
#include <math.h>
#define PI 3.14159265
int main () {
double x, ret, val;
x = 60.0;
val = PI / 180.0;
ret = cos( x*val );
printf("The cosine of %lf is %lf degrees\n", x, ret);
x = 90.0;
val = PI / 180.0;
ret = cos( x*val );
printf("The cosine of %lf is %lf degrees\n", x, ret);
return(0);
}
Let us compile and run the above program that will produce the following result −
The cosine of 60.000000 is 0.500000 degrees
The cosine of 90.000000 is 0.000000 degrees
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": 2091,
"s": 2007,
"text": "The C library function double cos(double x) returns the cosine of a radian angle x."
},
{
"code": null,
"e": 2140,
"s": 2091,
"text": "Following is the declaration for cos() function."
},
{
"code": null,
"e": 2161,
"s... |
ArrayList get(index) Method in Java with Examples - GeeksforGeeks | 01 Nov, 2021
The get() method of ArrayList in Java is used to get the element of a specified index within the list.
Syntax:
get(index)
Parameter: Index of the elements to be returned. It is of data-type int.
Return Type: The element at the specified index in the given list.
Exception: It throws IndexOutOfBoundsException if the index is out of range (index=size())
Note: Time Complexity: ArrayList is one of the List implementations built a top an array. Hence, get(index) is always a constant time O(1) operation.
Example:
Java
// Java Program to Demonstrate the working of// get() method in ArrayList // Importing ArrayList classimport java.util.ArrayList; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an Empty Integer ArrayList ArrayList<Integer> arr = new ArrayList<Integer>(4); // Using add() to initialize values // [10, 20, 30, 40] arr.add(10); arr.add(20); arr.add(30); arr.add(40); // Printing elements of list System.out.println("List: " + arr); // Getting element at index 2 int element = arr.get(2); // Displaying element at specified index // on console inside list System.out.println("the element at index 2 is " + element); }}
List: [10, 20, 30, 40]
the element at index 2 is 30
Example 2: Program to demonstrate the error
Java
// Java Program to Demonstrate Error Generated// while using get() method in ArrayList // Importing ArrayList classimport java.util.ArrayList; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an Empty Integer ArrayList ArrayList<Integer> arr = new ArrayList<Integer>(4); // Using add() method to insert elements // and adding custom values arr.add(10); arr.add(20); arr.add(30); arr.add(40); // Getting element at index 2 int element = arr.get(5); // Print all the elements of ArrayList System.out.println("the element at index 2 is " + element); }}
Output :
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 5, Size: 4
at java.util.ArrayList.rangeCheck(ArrayList.java:657)
at java.util.ArrayList.get(ArrayList.java:433)
at GFG.main(GFG.java:22)
shivnagarsoge
Java - util package
Java-ArrayList
Java-Collections
Java-Functions
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Multidimensional Arrays in Java
Stream In Java
Stack Class in Java
Singleton Class in Java | [
{
"code": null,
"e": 25015,
"s": 24987,
"text": "\n01 Nov, 2021"
},
{
"code": null,
"e": 25118,
"s": 25015,
"text": "The get() method of ArrayList in Java is used to get the element of a specified index within the list."
},
{
"code": null,
"e": 25127,
"s": 25118,
... |
4 Dimensional Array in C/C++ | A 4 dimensional array is an array of 3Darrays.
Begin.
Declare the variables.
Declare the array elements.
Take the no of elements as input.
Take the elements as input.
Print the elements stored in array.
End.
Here is an example of 4D array.
#include<iostream>
using namespace std;
int main() {
int a[2][2][3][2];
cout << "Enter the elements of array: \n";
for(int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
for(int k = 0; k < 3; ++k ) {
for(int l = 0; l < 2; ++l ) {
cin >> a[i][j][k][l];
}
}
}
}
cout<<"\narray elements are stored as:"<<endl;
for(int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
for(int k = 0; k < 3; ++k) {
for(int l = 0; l < 2; ++l) {
cout << "a[" << i << "][" << j << "][" << k << "] [" <<l<<"]= " << a[i][j][k][l] << endl;
}
}
}
}
return 0;
}
Enter the elements of array:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
array elements are stored as:
a[0][0][0] [0]= 1
a[0][0][0] [1]= 2
a[0][0][1] [0]= 3
a[0][0][1] [1]= 4
a[0][0][2] [0]= 5
a[0][0][2] [1]= 6
a[0][1][0] [0]= 7
a[0][1][0] [1]= 8
a[0][1][1] [0]= 9
a[0][1][1] [1]= 10
a[0][1][2] [0]= 11
a[0][1][2] [1]= 12
a[1][0][0] [0]= 13
a[1][0][0] [1]= 14
a[1][0][1] [0]= 15
a[1][0][1] [1]= 16
a[1][0][2] [0]= 17
a[1][0][2] [1]= 18
a[1][1][0] [0]= 19
a[1][1][0] [1]= 20
a[1][1][1] [0]= 21
a[1][1][1] [1]= 22
a[1][1][2] [0]= 23
a[1][1][2] [1]= 24 | [
{
"code": null,
"e": 1109,
"s": 1062,
"text": "A 4 dimensional array is an array of 3Darrays."
},
{
"code": null,
"e": 1285,
"s": 1109,
"text": "Begin.\n Declare the variables.\n Declare the array elements.\n Take the no of elements as input.\n Take the elements as input.... |
Swing Examples - Slider with custom labels | Following example showcase how to use a slider with custom labels in a Java Swing application.
We are using the following APIs.
JSlider(orientation, min, max, value) − To create a slider while orientation set the vertical orientation.
JSlider(orientation, min, max, value) − To create a slider while orientation set the vertical orientation.
JSlider.getValue() − To get the current value of slider.
JSlider.getValue() − To get the current value of slider.
JSlider.setLabelTable() − To set the labels.
JSlider.setLabelTable() − To set the labels.
JSlider.setPaintLabels(true) − To show the labels.
JSlider.setPaintLabels(true) − To show the labels.
Create the following Java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >
SwingControlDemo.java
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.Hashtable;
public class SwingControlDemo {
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
public SwingControlDemo(){
prepareGUI();
}
public static void main(String[] args){
SwingControlDemo swingControlDemo = new SwingControlDemo();
swingControlDemo.showSliderDemo();
}
private void prepareGUI(){
mainFrame = new JFrame("Java Swing Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new JLabel("", JLabel.CENTER);
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(350,100);
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showSliderDemo(){
headerLabel.setText("Control in action: JSlider");
JSlider slider = new JSlider(JSlider.HORIZONTAL,0,100,10);
Hashtable<Integer, JLabel> labelTable =
new Hashtable<Integer, JLabel>();
labelTable.put(new Integer( 0 ),
new JLabel("Stop") );
labelTable.put(new Integer( 50 ),
new JLabel("Slow") );
labelTable.put(new Integer( 100 ),
new JLabel("Fast") );
slider.setLabelTable(labelTable);
slider.setPaintLabels(true);
slider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
statusLabel.setText("Value : " + ((JSlider)e.getSource()).getValue());
}
});
controlPanel.add(slider);
mainFrame.setVisible(true);
}
}
Compile the program using the command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingControlDemo.java
If no error occurs, it means the compilation is successful. Run the program using the following command.
D:\SWING>java com.tutorialspoint.gui.SwingControlDemo
Verify the following output.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2134,
"s": 2039,
"text": "Following example showcase how to use a slider with custom labels in a Java Swing application."
},
{
"code": null,
"e": 2167,
"s": 2134,
"text": "We are using the following APIs."
},
{
"code": null,
"e": 2274,
"s": 21... |
Python | sympy.Rational() method | 02 Aug, 2019
With the help of sympy.Rational() method, we can find the rational form of any float value that is passed as parameter in sympy.Rational() method.
Syntax : sympy.Rational(val)Return : Return Rational form of float value.
Example #1 :In this example we can see that by using sympy.Rational() method, we are able to find the rational form of any float value that is passed as parameters.
# import sympyfrom sympy import * # Using sympy.Rational() methodgfg = Rational(0.2) print(gfg)
Output :
1/5
Example #2 :
# import sympyfrom sympy import * # Using sympy.Rational() methodgfg = Rational(0.12) print(gfg)
Output :
12/100
SymPy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Aug, 2019"
},
{
"code": null,
"e": 175,
"s": 28,
"text": "With the help of sympy.Rational() method, we can find the rational form of any float value that is passed as parameter in sympy.Rational() method."
},
{
"code": null,
... |
Program to find sum of series 1 + 2 + 2 + 3 + 3 + 3 + . . . + n | 30 Nov, 2021
Given a positive integer n and the task is to find sum of series 1 + 2 + 2 + 3 + 3 + 3 + . . . + n. Examples:
Input : n = 5
Output : 55
= 1 + 2 + 2 + 3 + 3 + 3 + 4 + 4 + 4 +
4 + 5 + 5 + 5 + 5 + 5.
= 55
Input : n = 10
Output : 385
Addition method: In addition method sum all the elements one by one. Below is the implementation of this approach.
C++
Java
Python3
C#
PHP
Javascript
// Program to find// sum of series// 1 + 2 + 2 + 3 +// . . . + n#include <bits/stdc++.h>using namespace std; // Function that find// sum of series.int sumOfSeries(int n){ int sum = 0; for (int i = 1; i <= n; i++) for (int j = 1; j <= i; j++) sum = sum + i; return sum;} // Driver functionint main(){ int n = 10; // Function call cout << sumOfSeries(n); return 0;}
// Java Program to// find sum of// series// 1 + 2 + 2 + 3 +// . . . + npublic class GfG{ // Function that find // sum of series. static int sumOfSeries(int n) { int sum = 0; for (int i = 1; i <= n; i++) for (int j = 1; j <= i; j++) sum = sum + i; return sum; } // Driver Code public static void main(String s[]) { int n = 10; System.out.println(sumOfSeries(n)); }} // This code is contributed by Gitanjali
# Python3 Program to# find sum of series# 1 + 2 + 2 + 3 +# . . . + nimport math # Function that find# sum of series.def sumOfSeries( n): sum = 0 for i in range(1, n+1): sum = sum + i * i return sum # Driver methodn = 10 # Function callprint (sumOfSeries(n)) # This code is contributed by Gitanjali
// C# Program to find sum of// series 1 + 2 + 2 + 3 + . . . + nusing System; public class GfG { // Function that find // sum of series. static int sumOfSeries(int n) { int sum = 0; for (int i = 1; i <= n; i++) for (int j = 1; j <= i; j++) sum = sum + i; return sum; } // Driver Code public static void Main() { int n = 10; Console.Write(sumOfSeries(n)); }} // This code is contributed by vt_m.
<?php// Program to find// sum of series// 1 + 2 + 2 + 3 +// . . . + n // Function that find// sum of series.function sumOfSeries($n){ $sum = 0; for ($i = 1; $i <= $n; $i++) for ($j = 1; $j <= $i; $j++) $sum = $sum + $i; return $sum;} // Driver Code$n = 10; // Function callecho(sumOfSeries($n)); // This code is contributed by Ajit.?>
<script>// Javascript Program to// find sum of// series// 1 + 2 + 2 + 3 +// . . . + n // Function that find // sum of series. function sumOfSeries( n) { let sum = 0; for (let i = 1; i <= n; i++) for (let j = 1; j <= i; j++) sum = sum + i; return sum; } // Driver Code let n = 10; document.write(sumOfSeries(n)); // This code contributed by Princi Singh </script>
Output:
385
Time Complexity: O(n2)
Auxiliary Space: O(1)Multiplication method:In multiplication method every elements multiply by itself and then add them.
Input n = 10
sum = 1 + 2 + 2 + 3 + 3 + 3 + 4 + . . . + 10
= 1 + 2 * 2 + 3 * 3 + 4 * 4 + . . . + 10 * 10
= 1 + 4 + 9 + 16 + . . . + 100
= 385
C++
Java
Python3
C#
PHP
Javascript
// Program to find// sum of series// 1 + 2 + 2 + 3 +// . . . + n#include <bits/stdc++.h>using namespace std; // Function to find// sum of series.int sumOfSeries(int n){ int sum = 0; for (int i = 1; i <= n; i++) sum = sum + i * i; return sum;} // Driver function.int main(){ int n = 10; // Function call cout << sumOfSeries(n); return 0;}
// Java Program to// find sum of series// 1 + 2 + 2 + 3 +// . . . + npublic class GfG{ // Function that find sum of series. static int sumOfSeries(int n) { int sum = 0; for (int i = 1; i <= n; i++) sum = sum + i * i; return sum; } // Driver Code public static void main(String args[]) { int n = 10; System.out.println(sumOfSeries(n)); }} // This code is contributed by Gitanjali
# Python3 Program to# find sum of series# 1 + 2 + 2 + 3 +# . . . + nimport math # Function that find# sum of series.def sumOfSeries( n): sum = 0 for i in range(1, n+1): sum = sum + i * i return sum # Driver methodn = 10# Function callprint (sumOfSeries(n)) # This code is contributed by Gitanjali.
// C# Program to find sum of series// 1 + 2 + 2 + 3 + . . . + nusing System; class GfG { // Function that find sum of series. static int sumOfSeries(int n) { int sum = 0; for (int i = 1; i <= n; i++) sum = sum + i * i; return sum; } // Driver Code public static void Main() { int n = 10; Console.WriteLine(sumOfSeries(n)); }} // This code is contributed by anuj_67.
<?php// Program to find// sum of series// 1 + 2 + 2 + 3 +// . . . + n // Function to find// sum of series.function sumOfSeries($n){ $sum = 0; for ($i = 1; $i <= $n; $i++) $sum = $sum + $i * $i; return $sum;} // Driver Code$n = 10; // Function callecho(sumOfSeries($n)); // This code is contributed by Ajit.?>
<script>// javascript Program to// find sum of series// 1 + 2 + 2 + 3 +// . . . + n // Function that find sum of series. function sumOfSeries(n) { var sum = 0; for (let i = 1; i <= n; i++) sum = sum + i * i; return sum; } // Driver Code var n = 10; document.write(sumOfSeries(n)); // This code is contributed by Amit Katiyar</script>
Output:
385
Time Complexity: O(n)
Auxiliary Space: O(1)Using formula: We also use formula to find the sum of series.
Input n = 10;
Sum of series = (n * (n + 1) * (2 * n + 1)) / 6
put n = 10 in the above formula
sum = (10 * (10 + 1) * (2 * 10 + 1)) / 6
= (10 * 11 * 21) / 6
= 385
C++
Java
Python3
C#
PHP
Javascript
// C++ Program to// find sum of series// 1 + 2 + 2 + 3 +// . . . + n#include <bits/stdc++.h>using namespace std; // Function to find// sum of series.int sumOfSeries(int n){ return (n * (n + 1) * (2 * n + 1)) / 6;} // Driver functionint main(){ int n = 10; // Function call cout << sumOfSeries(n); return 0;}
// Java Program to// find sum of series// 1 + 2 + 2 + 3 +// . . . + npublic class GfG{ // Function that find // sum of series. static int sumOfSeries(int n) { return (n * (n + 1) * (2 * n + 1)) / 6; } // Driver Code public static void main(String s[]) { int n = 10; System.out.println(sumOfSeries(n)); }} // This code is contributed by 'Gitanjali'.
# Python3 Program to# find sum of series# 1 + 2 + 2 + 3 +# . . . + nimport math # Function that find# sum of series.def sumOfSeries( n): return ((n * (n + 1) * (2 * n + 1)) / 6) # Driver methodn = 10 # Function callprint (sumOfSeries(n)) # This code is contributed by Gitanjali
// C# Program to find sum of series// 1 + 2 + 2 + 3 + . . . + nusing System; public class GfG { // Function that find // sum of series. static int sumOfSeries(int n) { return (n * (n + 1) * (2 * n + 1)) / 6; } // Driver Code public static void Main() { int n = 10; Console.WriteLine(sumOfSeries(n)); }} // This code is contributed by 'vt_m'.
<?php// PHP Program to// find sum of series// 1 + 2 + 2 + 3 +// . . . + n // Function to find// sum of series.function sumOfSeries($n){ return ($n * ($n + 1) * (2 * $n + 1)) / 6;} // Driver Code$n = 10; // Function callecho(sumOfSeries($n)); // This code is contributed by Ajit.?>
<script>// javascript Program to// find sum of series// 1 + 2 + 2 + 3 +// . . . + n // Function that find// sum of series.function sumOfSeries(n){ return (n * (n + 1) * (2 * n + 1)) / 6;} // Driver Codevar n = 10;document.write(sumOfSeries(n)); // This code is contributed by Amit Katiyar</script>
Output :
385
Time Complexity: O(1)
Auxiliary Space: O(1)Please refer sum of squares of natural numbers for details of above formula and more optimizations.
jit_t
vt_m
princi singh
amit143katiyar
souravmahato348
avtarkumar719
series
Mathematical
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Merge two sorted arrays with O(1) extra space
Program to print prime numbers from 1 to N.
Find next greater number with same set of digits
Segment Tree | Set 1 (Sum of given range)
Check if a number is Palindrome
Count ways to reach the n'th stair
Fizz Buzz Implementation
Count all possible paths from top left to bottom right of a mXn matrix
Product of Array except itself | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n30 Nov, 2021"
},
{
"code": null,
"e": 165,
"s": 53,
"text": "Given a positive integer n and the task is to find sum of series 1 + 2 + 2 + 3 + 3 + 3 + . . . + n. Examples: "
},
{
"code": null,
"e": 298,
"s": 165,
"t... |
Form the Cubic equation from the given roots | 15 Nov, 2021
Given the roots of a cubic equation A, B and C, the task is to form the Cubic equation from the given roots.Note: The given roots are integral.Examples:
Input: A = 1, B = 2, C = 3 Output: x^3 – 6x^2 + 11x – 6 = 0 Explanation: Since 1, 2, and 3 are roots of the cubic equations, Then equation is given by: (x – 1)(x – 2)(x – 3) = 0 (x – 1)(x^2 – 5x + 6) = 0 x^3 – 5x^2 + 6x – x^2 + 5x – 6 = 0 x^3 – 6x^2 + 11x – 6 = 0.Input: A = 5, B = 2, C = 3 Output: x^3 – 10x^2 + 31x – 30 = 0 Explanation: Since 5, 2, and 3 are roots of the cubic equations, Then equation is given by: (x – 5)(x – 2)(x – 3) = 0 (x – 5)(x^2 – 5x + 6) = 0 x^3 – 5x^2 + 6x – 5x^2 + 25x – 30 = 0 x^3 – 10x^2 + 31x – 30 = 0.
Approach: Let the root of the cubic equation (ax3 + bx2 + cx + d = 0) be A, B and C. Then the given cubic equation can be represents as:
ax3 + bx2 + cx + d = x3 – (A + B + C)x2 + (AB + BC +CA)x + A*B*C = 0. Let X = (A + B + C) Y = (AB + BC +CA) Z = A*B*C
Therefore using the above relation find the value of X, Y, and Z and form the required cubic equation.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the approach #include <bits/stdc++.h>using namespace std; // Function to find the cubic// equation whose roots are a, b and cvoid findEquation(int a, int b, int c){ // Find the value of coefficient int X = (a + b + c); int Y = (a * b) + (b * c) + (c * a); int Z = a * b * c; // Print the equation as per the // above coefficients cout << "x^3 - " << X << "x^2 + " << Y << "x - " << Z << " = 0";} // Driver Codeint main(){ int a = 5, b = 2, c = 3; // Function Call findEquation(a, b, c); return 0;}
// Java program for the approach class GFG{ // Function to find the cubic equation// whose roots are a, b and cstatic void findEquation(int a, int b, int c){ // Find the value of coefficient int X = (a + b + c); int Y = (a * b) + (b * c) + (c * a); int Z = a * b * c; // Print the equation as per the // above coefficients System.out.print("x^3 - " + X+ "x^2 + " + Y+ "x - " + Z+ " = 0");} // Driver Codepublic static void main(String[] args){ int a = 5, b = 2, c = 3; // Function Call findEquation(a, b, c);}} // This code contributed by PrinciRaj1992
# Python3 program for the approach # Function to find the cubic equation# whose roots are a, b and cdef findEquation(a, b, c): # Find the value of coefficient X = (a + b + c); Y = (a * b) + (b * c) + (c * a); Z = (a * b * c); # Print the equation as per the # above coefficients print("x^3 - " , X , "x^2 + " ,Y , "x - " , Z , " = 0"); # Driver Codeif __name__ == '__main__': a = 5; b = 2; c = 3; # Function Call findEquation(a, b, c); # This code is contributed by sapnasingh4991
// C# program for the approachusing System; class GFG{ // Function to find the cubic equation// whose roots are a, b and cstatic void findEquation(int a, int b, int c){ // Find the value of coefficient int X = (a + b + c); int Y = (a * b) + (b * c) + (c * a); int Z = a * b * c; // Print the equation as per the // above coefficients Console.Write("x^3 - " + X + "x^2 + " + Y + "x - " + Z + " = 0");} // Driver Codepublic static void Main(){ int a = 5, b = 2, c = 3; // Function Call findEquation(a, b, c);}} // This code is contributed by shivanisinghss2110
<script> // Javascript program for the approach // Function to find the cubic // equation whose roots are a, b and c function findEquation(a, b, c) { // Find the value of coefficient let X = (a + b + c); let Y = (a * b) + (b * c) + (c * a); let Z = a * b * c; // Print the equation as per the // above coefficients document.write("x^3 - " + X + "x^2 + " + Y + "x - " + Z + " = 0"); } let a = 5, b = 2, c = 3; // Function Call findEquation(a, b, c); </script>
x^3 - 10x^2 + 31x - 30 = 0
Time Complexity: O(1)
Auxiliary Space: O(1)
princiraj1992
shivanisinghss2110
sapnasingh4991
divyesh072019
souravmahato348
Algebra
root
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Nov, 2021"
},
{
"code": null,
"e": 183,
"s": 28,
"text": "Given the roots of a cubic equation A, B and C, the task is to form the Cubic equation from the given roots.Note: The given roots are integral.Examples: "
},
{
"code"... |
numpy.fmin() in Python | 28 Nov, 2018
numpy.fmin() function is used to compute element-wise minimum of array elements. This function compare two arrays and returns a new array containing the element-wise minima.
If one of the elements being compared is a NaN, then the non-nan element is returned. If both elements are NaNs then the first is returned.
Syntax : numpy.fmin(arr1, arr2, /, out=None, *, where=True, casting=’same_kind’, order=’K’, dtype=None, ufunc ‘fmin’)
Parameters :arr1 : [array_like] The array holding the elements to be compared.arr2 : [array_like] The array holding the elements to be compared.out : [ndarray, optional] A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned.**kwargs : Allows you to pass keyword variable length of argument to a function. It is used when we want to handle named argument in a function.where : [array_like, optional] True value means to calculate the universal functions(ufunc) at that position, False value means to leave the value in the output alone.
Return : [ndarray or scalar] The minimum of arr1 and arr2, element-wise. Returns scalar if both arr1 and arr2 are scalars.
Code #1 : Working
# Python program explaining# fmin() function import numpy as geekin_num1 = 10in_num2 = 11 print ("Input number1 : ", in_num1)print ("Input number2 : ", in_num2) out_num = geek.fmin(in_num1, in_num2) print ("minimum of 10 and 11 : ", out_num)
Output :
Input number1 : 10
Input number2 : 11
minimum of 10 and 11 : 10
Code #2 :
# Python program explaining# fmin() function import numpy as geek in_arr1 = [2, 8, 125, geek.nan]in_arr2 = [geek.nan, 3, 115, geek.nan] print ("Input array1 : ", in_arr1) print ("Input array2 : ", in_arr2) out_arr = geek.fmin(in_arr1, in_arr2) print ("Output array : ", out_arr)
Output :
Input array1 : [2, 8, 125, nan]
Input array2 : [nan, 3, 115, nan]
Output array : [ 2. 3. 115. nan]
Code #3 :
# Python program explaining# fmin() function import numpy as geek in_arr1 = [2, 8, 125]in_arr2 = [3, 3, 115] print ("Input array1 : ", in_arr1) print ("Input array2 : ", in_arr2) out_arr = geek.fmin(in_arr1, in_arr2) print ("Output array: ", out_arr)
Output :
Input array1 : [2, 8, 125]
Input array2 : [3, 3, 115]
Output array: [ 2 3 115]
Python numpy-Mathematical Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Nov, 2018"
},
{
"code": null,
"e": 202,
"s": 28,
"text": "numpy.fmin() function is used to compute element-wise minimum of array elements. This function compare two arrays and returns a new array containing the element-wise minima."
... |
Smallest substring occurring only once in a given string | 18 Apr, 2022
Given a string S consisting of N lowercase alphabets, the task is to find the length of the smallest substring in S whose occurrence is exactly 1.
Examples:
Input: S = “abaaba”Output: 2Explanation: The smallest substring in the string S, whose occurrence is exactly 1 is “aa” . Length of this substring is 2.Therefore, print 2.
Input: S = “zyzyzyz”Output: 5
Approach: To solve the problem, the idea is to generate all possible substring of the given string S and store the frequency of each substring in a HashMap. Now, traverse the HashMap and print the substring of minimum length whose frequency is 1.
Below is the implementation of the above approach:
C++
Java
Python3
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the smallest// substring occurring only onceint smallestSubstring(string a){ // Stores all occurrences vector<string> subStrings; int n = a.size(); // Generate all the substrings for (int i = 0; i < n; i++) for (int len = 1; len <= n - i; len++) subStrings.push_back(a.substr(i, len)); // Take into account // all the substrings map<string,int> subStringsFreq; for(string i: subStrings) { subStringsFreq[i]++; } // Iterate over all // unique substrings int ans = INT_MAX; for (auto str : subStringsFreq) { if (str.second == 1){ //Find minimum length of substring int str_len = str.first.size(); ans = min(ans, str_len); } } // return 0 if no such substring exists return ans == INT_MAX ? 0 : ans;} // Driver Codeint main(){ string S = "ababaabba"; cout<<smallestSubstring(S); return 0;} // This code is contributed by mohit kumar 29.
// Java program for the above approachimport java.io.*;import java.lang.*;import java.util.*; class GFG{ // Function to find the smallest// substring occurring only oncestatic int smallestSubstring(String a){ // Stores all occurrences ArrayList<String> a1 = new ArrayList<>(); // Generate all the substrings for(int i = 0; i < a.length(); i++) { for(int j = i + 1; j <= a.length(); j++) { // Avoid multiple occurences if (i != j) // Append all substrings a1.add(a.substring(i, j)); } } // Take into account // all the substrings TreeMap<String, Integer> a2 = new TreeMap<>(); for(String s : a1) a2.put(s, a2.getOrDefault(s, 0) + 1); ArrayList<String> freshlist = new ArrayList<>(); // Iterate over all // unique substrings for(String s : a2.keySet()) { // If frequency is 1 if (a2.get(s) == 1) // Append into fresh list freshlist.add(s); } // Initialize a dictionary TreeMap<String, Integer> dictionary = new TreeMap<>(); for(String s : freshlist) { // Append the keys dictionary.put(s, s.length()); } ArrayList<Integer> newlist = new ArrayList<>(); // Traverse the dictionary for(String s : dictionary.keySet()) newlist.add(dictionary.get(s)); int ans = Integer.MAX_VALUE; for(int i : newlist) ans = Math.min(ans, i); // Return the minimum of dictionary return ans == Integer.MAX_VALUE ? 0 : ans;} // Driver Codepublic static void main(String[] args){ String S = "ababaabba"; System.out.println(smallestSubstring(S));}} // This code is contributed by Kingash
# Python3 program of the above approachfrom collections import Counter # Function to find the smallest# substring occurring only oncedef smallestSubstring(a): # Stores all occurrences a1 = [] # Generate all the substrings for i in range(len(a)): for j in range(i+1, len(a)): # Avoid multiple occurrences if i != j: # Append all substrings a1.append(a[i:j+1]) # Take into account # all the substrings a2 = Counter(a1) freshlist = [] # Iterate over all # unique substrings for i in a2: # If frequency is 1 if a2[i] == 1: # Append into fresh list freshlist.append(i) # Initialize a dictionary dictionary = dict() for i in range(len(freshlist)): # Append the keys dictionary[freshlist[i]] = len(freshlist[i]) newlist = [] # Traverse the dictionary for i in dictionary: newlist.append(dictionary[i]) # Print the minimum of dictionary return(min(newlist)) # Driver CodeS = "ababaabba"print(smallestSubstring(S))
<script> // JavaScript program for the above approach // Function to find the smallest// substring occurring only oncefunction smallestSubstring(a){ // Stores all occurrences let a1 = []; // Generate all the substrings for(let i = 0; i < a.length; i++) { for(let j = i + 1; j <= a.length; j++) { // Avoid multiple occurrences if (i != j) // Append all substrings a1.push(a.substring(i, j)); } } // Take into account // all the substrings let a2 = new Map(); for(let s=0;s<a1.length;s++) { if(a2.has(a1[s])) a2.set(a1[s],a2.get(a1[s])+1); else a2.set(a1[s],1); } let freshlist = []; // Iterate over all // unique substrings for(let s of a2.keys()) { // If frequency is 1 if (a2.get(s) == 1) // Append into fresh list freshlist.push(s); } // Initialize a dictionary let dictionary = new Map(); for(let s=0;s<freshlist.length;s++) { // Append the keys dictionary.set(freshlist[s], freshlist[s].length); } let newlist = []; // Traverse the dictionary for(let s of dictionary.keys()) newlist.push(dictionary.get(s)); let ans = Number.MAX_VALUE; for(let i=0;i<newlist.length;i++) ans = Math.min(ans, newlist[i]); // Return the minimum of dictionary return ans == Number.MAX_VALUE ? 0 : ans;} // Driver Codelet S = "ababaabba";document.write(smallestSubstring(S)); // This code is contributed by unknown2108 </script>
2
Time Complexity: O(N2)Auxiliary Space: O(N2)
mohit kumar 29
Kingash
unknown2108
anilk
sweetyty
frequency-counting
substring
Greedy
Hash
Searching
Sorting
Strings
Searching
Hash
Strings
Greedy
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Policemen catch thieves
K Centers Problem | Set 1 (Greedy Approximate Algorithm)
Number of indices pair such that element pair sum from first Array is greater than second Array
Minimize Cash Flow among a given set of friends who have borrowed money from each other
Maximize difference between the Sum of the two halves of the Array after removal of N elements
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
What is Hashing | A Complete Tutorial
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Count pairs with given sum | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n18 Apr, 2022"
},
{
"code": null,
"e": 199,
"s": 52,
"text": "Given a string S consisting of N lowercase alphabets, the task is to find the length of the smallest substring in S whose occurrence is exactly 1."
},
{
"code": null,... |
Byte Objects vs String in Python | 24 Jan, 2022
In Python 2, both str and bytes are the same typeByte objects whereas in Python 3 Byte objects, defined in Python 3 are “sequence of bytes” and similar to “unicode” objects from Python 2. However, there are many differences in strings and Byte objects. Some of them are depicted below: `
Byte objects are sequence of Bytes, whereas Strings are sequence of characters.
Byte objects are in machine readable form internally, Strings are only in human readable form.
Since Byte objects are machine readable, they can be directly stored on the disk. Whereas, Strings need encoding before which they can be stored on disk.
There are methods to convert a byte object to String and String to byte objects.
PNG, JPEG, MP3, WAV, ASCII, UTF-8 etc are different forms of encodings. An encoding is a format to represent audio, images, text, etc in bytes. Converting Strings to byte objects is termed as encoding. This is necessary so that the text can be stored on disk using mapping using ASCII or UTF-8 encoding techniques.This task is achieved using encode(). It take encoding technique as argument. Default technique is “UTF-8” technique.
Python3
# Python code to demonstrate String encoding # initialising a Stringa = 'GeeksforGeeks' # initialising a byte objectc = b'GeeksforGeeks' # using encode() to encode the String# encoded version of a is stored in d# using ASCII mappingd = a.encode('ASCII') # checking if a is converted to bytes or notif (d==c): print ("Encoding successful")else : print ("Encoding Unsuccessful")
Output:
Encoding successful
Similarly, Decoding is process to convert a Byte object to String. It is implemented using decode() . A byte string can be decoded back into a character string, if you know which encoding was used to encode it. Encoding and Decoding are inverse processes.
Python3
# Python code to demonstrate Byte Decoding # initialising a Stringa = 'GeeksforGeeks' # initialising a byte objectc = b'GeeksforGeeks' # using decode() to decode the Byte object# decoded version of c is stored in d# using ASCII mappingd = c.decode('ASCII') # checking if c is converted to String or notif (d==a): print ("Decoding successful")else : print ("Decoding Unsuccessful")
Output:
Decoding successful
This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
simmytarika5
amartyaghoshgfg
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Convert integer to string in Python | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n24 Jan, 2022"
},
{
"code": null,
"e": 342,
"s": 52,
"text": "In Python 2, both str and bytes are the same typeByte objects whereas in Python 3 Byte objects, defined in Python 3 are “sequence of bytes” and similar to “unicode” objects f... |
Python Pandas - Create a time interval and use Timestamps as the bounds | To create a time interval and use Timestamps as the bounds, use pandas.Interval and set timestamp within it using pandas.Timestamp.
At first, import the required libraries −
import pandas as pd
Use Timestamps as the bounds to create a time interval. Closed interval set using the "closed" parameter with value "left"
interval = pd.Interval(pd.Timestamp('2020-01-01 00:00:00'), pd.Timestamp('2021-01-01 00:00:00'), closed='left')
Above, we have used Timestamps as the bounds. Display the interval
print("Interval...\n",interval)
Following is the code
import pandas as pd
# Use Timestamps as the bounds to create a time interval
# closed interval set using the "closed" parameter with value "left"
interval = pd.Interval(pd.Timestamp('2020-01-01 00:00:00'), pd.Timestamp('2021-01-01 00:00:00'), closed='left')
# display the interval
print("Interval...\n",interval)
# display the interval length
print("\nInterval length...\n",interval.length)
This will produce the following code
Interval...
[2020-01-01, 2021-01-01)
Interval length...
366 days 00:00:00 | [
{
"code": null,
"e": 1319,
"s": 1187,
"text": "To create a time interval and use Timestamps as the bounds, use pandas.Interval and set timestamp within it using pandas.Timestamp."
},
{
"code": null,
"e": 1361,
"s": 1319,
"text": "At first, import the required libraries −"
},
... |
Ruby on Rails - AJAX | Ajax stands for Asynchronous JavaScript and XML. Ajax is not a single technology; it is a suite of several technologies. Ajax incorporates the following −
XHTML for the markup of web pages
CSS for the styling
Dynamic display and interaction using the DOM
Data manipulation and interchange using XML
Data retrieval using XMLHttpRequest
JavaScript as the glue that meshes all this together
Ajax enables you to retrieve data for a web page without having to refresh the contents of the entire page. In the basic web architecture, the user clicks a link or submits a form. The form is submitted to the server, which then sends back a response. The response is then displayed for the user on a new page.
When you interact with an Ajax-powered web page, it loads an Ajax engine in the background. The engine is written in JavaScript and its responsibility is to both communicate with the web server and display the results to the user. When you submit data using an Ajax-powered form, the server returns an HTML fragment that contains the server's response and displays only the data that is new or changed as opposed to refreshing the entire page.
For a complete detail on AJAX you can go through our AJAX Tutorial
Rails has a simple, consistent model for how it implements Ajax operations. Once the browser has rendered and displayed the initial web page, different user actions cause it to display a new web page (like any traditional web application) or trigger an Ajax operation −
Some trigger fires − This trigger could be the user clicking on a button or link, the user making changes to the data on a form or in a field, or just a periodic trigger (based on a timer).
Some trigger fires − This trigger could be the user clicking on a button or link, the user making changes to the data on a form or in a field, or just a periodic trigger (based on a timer).
The web client calls the server − A JavaScript method, XMLHttpRequest, sends data associated with the trigger to an action handler on the server. The data might be the ID of a checkbox, the text in an entry field, or a whole form.
The web client calls the server − A JavaScript method, XMLHttpRequest, sends data associated with the trigger to an action handler on the server. The data might be the ID of a checkbox, the text in an entry field, or a whole form.
The server does processing − The server-side action handler ( Rails controller action )-- does something with the data and returns an HTML fragment to the web client.
The server does processing − The server-side action handler ( Rails controller action )-- does something with the data and returns an HTML fragment to the web client.
The client receives the response − The client-side JavaScript, which Rails creates automatically, receives the HTML fragment and uses it to update a specified part of the current page's HTML, often the content of a <div> tag.
The client receives the response − The client-side JavaScript, which Rails creates automatically, receives the HTML fragment and uses it to update a specified part of the current page's HTML, often the content of a <div> tag.
These steps are the simplest way to use Ajax in a Rails application, but with a little extra work, you can have the server return any kind of data in response to an Ajax request, and you can create custom JavaScript in the browser to perform more involved interactions.
This example works based on scaffold, Destroy concept works based on ajax.
In this example, we will provide, list, show and create operations on ponies table. If you did not understand the scaffold technology then we would suggest you to go through the previous chapters first and then continue with AJAX on Rails.
Let us start with the creation of an application It will be done as follows −
rails new ponies
The above command creates an application, now we need to call the app directory using with cd command. It will enter in to an application directory then we need to call a scaffold command. It will be done as follows −
rails generate scaffold Pony name:string profession:string
Above command generates the scaffold with name and profession column. We need to migrate the data base as follows command
rake db:migrate
Now Run the Rails application as follows command
rails s
Now open the web browser and call a url as http://localhost:3000/ponies/new, The output will be as follows
Now open app/views/ponies/index.html.erb with suitable text editors. Update your destroy line with :remote => true, :class => 'delete_pony'.At finally, it looks like as follows.
Create a file, destroy.js.erb, put it next to your other .erb files (under app/views/ponies). It should look like this −
Now enter the code as shown below in destroy.js.erb
$('.delete_pony').bind('ajax:success', function() {
$(this).closest('tr').fadeOut();
});
Now Open your controller file which is placed at app/controllers/ponies_controller.rb and add the following code in destroy method as shown below −
# DELETE /ponies/1
# DELETE /ponies/1.json
def destroy
@pony = Pony.find(params[:id])
@pony.destroy
respond_to do |format|
format.html { redirect_to ponies_url }
format.json { head :no_content }
format.js { render :layout => false }
end
end
At finally controller page is as shown image.
Now run an application, Output called from http://localhost:3000/ponies/new, it will looks like as following image
Press on create pony button, it will generate the result as follows
Now click on back button, it will show all pony created information as shown image
Till now, we are working on scaffold, now click on destroy button, it will call a pop-up as shown below image, the pop-up works based on Ajax.
If Click on ok button, it will delete the record from pony. Here I have clicked ok button. Final output will be as follows − | [
{
"code": null,
"e": 2392,
"s": 2237,
"text": "Ajax stands for Asynchronous JavaScript and XML. Ajax is not a single technology; it is a suite of several technologies. Ajax incorporates the following −"
},
{
"code": null,
"e": 2426,
"s": 2392,
"text": "XHTML for the markup of web... |
JavaScript Math floor() Method | 23 Feb, 2022
Below is the example of the Math floor() Method.
Example:
javascript
<script type="text/javascript"> document.write("Result : " + Math.floor(.89));</script>
Output:
Result : 0
The Math.floor method is used to round off the number passed as a parameter to its nearest integer in Downward direction of rounding i.e. towards the lesser value.Syntax:
Math.floor(value)
Parameters: This method accepts single parameter asmentioned above and described below:
Value: It is the value which is to be tested for Math.floor.
Return Value: The Math.floor() method returns the smallest integer greater than or equal to the given number.Below examples illustrate the Math floor() method in JavaScript:
Example 1:
Input : Math.floor(.89)
Output: 0
Example 2:
Input : Math.floor(-89.02)
Output : -90
Example 3:
Input : Math.floor(0)
Output : 0
More codes for the above method are as follows:Program 1: When a negative number is passed as a parameter.
javascript
<script type="text/javascript"> document.write("Result : " + Math.floor(-89.02));</script>
Output:
Result : -90
Program 2: When zero is passed as a parameter.
javascript
<script type="text/javascript"> document.write("Result : " + Math.floor(0));</script>
Output:
Result : 0
Supported Browsers:
Google Chrome 1 and above
Internet Explorer 3 and above
Firefox 1 and above
Opera 3 and above
Safari 1 and above
sumitgumber28
ysachin2314
javascript-math
JavaScript-Methods
JavaScript
Mathematical
Web Technologies
Mathematical
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
Hide or show elements in HTML using display property
How to append HTML code to a div using JavaScript ?
Set in C++ Standard Template Library (STL)
Program for Fibonacci numbers
C++ Data Types
Write a program to print all permutations of a given string
Merge two sorted arrays | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n23 Feb, 2022"
},
{
"code": null,
"e": 105,
"s": 54,
"text": "Below is the example of the Math floor() Method. "
},
{
"code": null,
"e": 116,
"s": 105,
"text": "Example: "
},
{
"code": null,
"e": 127,
... |
Importance of function prototype in C | 07 Oct, 2021
Function prototype tells the compiler about a number of parameters function takes data-types of parameters, and return type of function. By using this information, the compiler cross-checks function parameters and their data type with function definition and function call. If we ignore the function prototype, a program may compile with a warning and may work properly. But sometimes, it will give strange output and it is very hard to find such programming mistakes. Let us see with examples
C
#include <errno.h>#include <stdio.h> int main(int argc, char *argv[]){ FILE *fp; fp = fopen(argv[1], "r"); if (fp == NULL) { fprintf(stderr, "%s\n", strerror(errno)); return errno; } printf("file exist\n"); fclose(fp); return 0;}
The above program checks the existence of a file, provided from the command line, if a given file exists, then the program prints “file exists”, otherwise it prints an appropriate error message. Let us provide a filename, which does not exist in a file system, and check the output of the program on x86_64 architecture.
[narendra@/media/partition/GFG]$ ./file_existence hello.c
Segmentation fault (core dumped)
Why this program crashed, instead it should show an appropriate error message. This program will work fine on x86 architecture but will crash on x86_64 architecture. Let us see what was wrong with the code. Carefully go through the program, deliberately I haven’t included the prototype of the “strerror()” function. This function returns “pointer to the character”, which will print an error message which depends on errno passed to this function. Note that x86 architecture is an ILP-32 model, which means integer, pointers and long are 32-bit wide, that’s why the program will work correctly on this architecture. But x86_64 is the LP-64 model, which means long and pointers are 64 bit wide. In C language, when we don’t provide a prototype of a function, the compiler assumes that function returns an integer. In our example, we haven’t included the “string.h” header file (strerror’s prototype is declared in this file), that’s why the compiler assumed that function returns an integer. But its return type is a pointer to a character. In x86_64, pointers are 64-bit wide and integers are 32-bits wide, that’s why while returning from a function, the returned address gets truncated (i.e. 32-bit wide address, which is the size of integer on x86_64) which is invalid and when we try to dereference this address, the result is a segmentation fault.Now include the “string.h” header file and check the output, the program will work correctly.
[narendra@/media/partition/GFG]$ ./file_existence hello.c
No such file or directory
Consider one more example.
C
#include <stdio.h> int main(void){ int *p = malloc(sizeof(int)); if (p == NULL) { perror("malloc()"); return -1; } *p = 10; free(p); return 0;}
The above code will work fine on the IA-32 model but will fail on the IA-64 model. The reason for the failure of this code is we haven’t included a prototype of the malloc() function and the returned value is truncated in the IA-64 model.This article is compiled by Narendra Kangralkar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
marcosarcticseal
C-Functions
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
std::string class in C++
Unordered Sets in C++ Standard Template Library
rand() and srand() in C/C++
Enumeration (or enum) in C
C Language Introduction | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n07 Oct, 2021"
},
{
"code": null,
"e": 549,
"s": 54,
"text": "Function prototype tells the compiler about a number of parameters function takes data-types of parameters, and return type of function. By using this information, the compil... |
Builder Pattern in java | 08 Aug, 2018
Method Chaining: In java, Method Chaining is used to invoke multiple methods on the same object which occurs as a single statement. Method-chaining is implemented by a series of methods that return the this reference for a class instance.
Implementation: As return values of methods in a chain is this reference, this implementation allows us to invoke methods in chain by having the next method invocation on the return value of the previous method in the chain.
// Java code to demonstrate method chainingfinal class Student { // instance fields private int id; private String name; private String address; // Setter Methods // Note that all setters method // return this reference public Student setId(int id) { this.id = id; return this; } public Student setName(String name) { this.name = name; return this; } public Student setAddress(String address) { this.address = address; return this; } @Override public String toString() { return "id = " + this.id + ", name = " + this.name + ", address = " + this.address; }} // Driver classpublic class MethodChainingDemo { public static void main(String args[]) { Student student1 = new Student(); Student student2 = new Student(); student1.setId(1).setName("Ram").setAddress("Noida"); student2.setId(2).setName("Shyam").setAddress("Delhi"); System.out.println(student1); System.out.println(student2); }}
Output:
id = 1, name = Ram, address = Noida
id = 2, name = Shyam, address = Delhi
Need of Builder Pattern : Method chaining is a useful design pattern but however if accessed concurrently, a thread may observe some fields to contain inconsistent values. Although all setter methods in above example are atomic, but calls in the method chaining can lead to inconsistent object state when the object is modified concurrently. The below example can lead us to a Student instance in an inconsistent state, for example, a student with name Ram and address Delhi.
// Java code to demonstrate need of Builder Pattern // Server Side Codefinal class Student { // instance fields private int id; private String name; private String address; // Setter Methods // Note that all setters method // return this reference public Student setId(int id) { this.id = id; return this; } public Student setName(String name) { this.name = name; return this; } public Student setAddress(String address) { this.address = address; return this; } @Override public String toString() { return "id = " + this.id + ", name = " + this.name + ", address = " + this.address; }} // Client Side Codeclass StudentReceiver { private final Student student = new Student(); public StudentReceiver() { Thread t1 = new Thread(new Runnable() { @Override public void run() { student.setId(1).setName("Ram").setAddress("Noida"); } }); Thread t2 = new Thread(new Runnable() { @Override public void run() { student.setId(2).setName("Shyam").setAddress("Delhi"); } }); t1.start(); t2.start(); } public Student getStudent() { return student; }} // Driver classpublic class BuilderNeedDemo { public static void main(String args[]) { StudentReceiver sr = new StudentReceiver(); System.out.println(sr.getStudent()); }}
Output may be:
id = 2, name = Shyam, address = Noida
Another inconsistent output may be
id = 0, name = null, address = null
Note : Try running main method statements in loop(i.e. multiple requests to server simultaneously).
To solve this problem, there is Builder pattern to ensure the thread-safety and atomicity of object creation.
Implementation : In Builder pattern, we have a inner static class named Builder inside our Server class with instance fields for that class and also have a factory method to return an new instance of Builder class on every invocation. The setter methods will now return Builder class reference. We will also have a build method to return instances of Server side class, i.e. outer class.
// Java code to demonstrate Builder Pattern // Server Side Codefinal class Student { // final instance fields private final int id; private final String name; private final String address; public Student(Builder builder) { this.id = builder.id; this.name = builder.name; this.address = builder.address; } // Static class Builder public static class Builder { /// instance fields private int id; private String name; private String address; public static Builder newInstance() { return new Builder(); } private Builder() {} // Setter methods public Builder setId(int id) { this.id = id; return this; } public Builder setName(String name) { this.name = name; return this; } public Builder setAddress(String address) { this.address = address; return this; } // build method to deal with outer class // to return outer instance public Student build() { return new Student(this); } } @Override public String toString() { return "id = " + this.id + ", name = " + this.name + ", address = " + this.address; }} // Client Side Codeclass StudentReceiver { // volatile student instance to ensure visibility // of shared reference to immutable objects private volatile Student student; public StudentReceiver() { Thread t1 = new Thread(new Runnable() { @Override public void run() { student = Student.Builder.newInstance() .setId(1) .setName("Ram") .setAddress("Noida") .build(); } }); Thread t2 = new Thread(new Runnable() { @Override public void run() { student = Student.Builder.newInstance() .setId(2) .setName("Shyam") .setAddress("Delhi") .build(); } }); t1.start(); t2.start(); } public Student getStudent() { return student; }} // Driver classpublic class BuilderDemo { public static void main(String args[]) { StudentReceiver sr = new StudentReceiver(); System.out.println(sr.getStudent()); }}
Output is guaranteed to be one of below:
id = 1, name = Ram, address = Noida
OR
id = 2, name = Shyam, address = Delhi
The Builder.newInstance() factory method can also be called with any required arguments to obtain a Builder instance by overloading it. The object of Student class is constructed with the invocation of the build() method.The above implementation of Builder pattern makes the Student class immutable and consequently thread-safe.
Also note that the student field in client side code cannot be declared final because it is assigned a new immutable object. But it be declared volatile to ensure visibility of shared reference to immutable objects. Also private members of Builder class maintain encapsulation.
Please have a look at append method of StringBuilder class in java.lang package to understand implementations of Builder pattern more.
Java-Multithreading
Process Synchronization
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate any Map in Java
HashMap in Java with Examples
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
Stack Class in Java
Initialize an ArrayList in Java | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n08 Aug, 2018"
},
{
"code": null,
"e": 293,
"s": 54,
"text": "Method Chaining: In java, Method Chaining is used to invoke multiple methods on the same object which occurs as a single statement. Method-chaining is implemented by a series... |
Program to construct a DFA which accepts the language L = {aN | N ≥ 1} | 28 Jun, 2021
Prerequisite: Finite Automata
Given a string S of size N, the task is to design a Deterministic Finite Automata (DFA) for accepting the language L = {aN | N ≥ 1}. The regular language L is {a, aa, aaa, aaaaaaa..., }. If the given string follows the given language L, then print “Accepted”. Otherwise, print “Not Accepted”.
Examples:
Input: S = “aaabbb”Output: Not AcceptedExplanation: String must only contain a.
Input: S = “aa”Output: Accepted
Approach: The idea by which the automata lead to acceptance of string is stated below in steps:
The automata will accept all the strings containing only the character ‘a’. If the user tried to input any character other than ‘a’, the machine will reject it.
Let the state q0 is the initial state represent the set of all strings of length 0, state q1 is the final state represent the set of all strings from 1 to N.
State q1 contains a self-loop of a which indicates that it can be repeated as required.
The logic for code is very basic as it has only a for loop which counts the number of a’s in a given string, if the count of a is the same as N then it will be accepted. Otherwise, the string will be rejected.
DFA State Transition Diagram:
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to check whether the string// S satisfy the given DFA or notvoid isAcceptedDFA(string s, int N){ // Stores the count of characters int count = 0; // Iterate over the range [0, N] for (int i = 0; i < N; i++) { // Count and check every // element for 'a' if (s[i] == 'a') count++; } // If string matches with DFA if (count == N && count != 0) { cout << "Accepted"; } // If not matches else { cout << "Not Accepted"; }} // Driver Codeint main(){ string S = "aaaaa"; // Function Call isAcceptedDFA(S, S.size()); return 0;}
// Java program for the above approachclass GFG{ // Function to check whether the String// S satisfy the given DFA or notstatic void isAcceptedDFA(String s, int N){ // Stores the count of characters int count = 0; // Iterate over the range [0, N] for (int i = 0; i < N; i++) { // Count and check every // element for 'a' if (s.charAt(i) == 'a') count++; } // If String matches with DFA if (count == N && count != 0) { System.out.print("Accepted"); } // If not matches else { System.out.print("Not Accepted"); }} // Driver Codepublic static void main(String[] args){ String S = "aaaaa"; // Function Call isAcceptedDFA(S, S.length());}} // This code is contributed by 29AjayKumar
# Python3 program for the above approach # Function to check whether the string# S satisfy the given DFA or notdef isAcceptedDFA(s, N): # Stores the count of characters count = 0 # Iterate over the range [0, N] for i in range(N): # Count and check every # element for 'a' if (s[i] == 'a'): count += 1 # If string matches with DFA if (count == N and count != 0): print ("Accepted") # If not matches else : print ("Not Accepted") # Driver Codeif __name__ == '__main__': S = "aaaaa" # Function Call isAcceptedDFA(S, len(S)) # This code is contributed by mohit kumar 29
// C# program for the above approachusing System;class GFG{ // Function to check whether the String// S satisfy the given DFA or notstatic void isAcceptedDFA(String s, int N){ // Stores the count of characters int count = 0; // Iterate over the range [0, N] for (int i = 0; i < N; i++) { // Count and check every // element for 'a' if (s[i] == 'a') count++; } // If String matches with DFA if (count == N && count != 0) { Console.Write("Accepted"); } // If not matches else { Console.Write("Not Accepted"); }} // Driver Codepublic static void Main(String[] args){ String S = "aaaaa"; // Function Call isAcceptedDFA(S, S.Length);}} // This code is contributed by 29AjayKumar
<script> // JavaScript program for the above approach // Function to check whether the String // S satisfy the given DFA or not function isAcceptedDFA(s, N) { // Stores the count of characters var count = 0; // Iterate over the range [0, N] for (var i = 0; i < N; i++) { // Count and check every // element for 'a' if (s[i] === "a") count++; } // If String matches with DFA if (count === N && count !== 0) { document.write("Accepted"); } // If not matches else { document.write("Not Accepted"); } } // Driver Code var S = "aaaaa"; // Function Call isAcceptedDFA(S, S.length); </script>
Accepted
Time Complexity: O(N)Auxiliary Space: O(1)
mohit kumar 29
29AjayKumar
rdtank
as5853535
Strings
Theory of Computation & Automata
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 58,
"s": 28,
"text": "Prerequisite: Finite Automata"
},
{
"code": null,
"e": 351,
"s": 58,
"text": "Given a string S of size N, the task is to design a Deterministic Finite Autom... |
Python program to Sort a List of Tuples in Increasing Order by the Last Element in Each Tuple | 19 May, 2022
The task is to write a Python Program to sort a list of tuples in increasing order by the last element in each tuple.
Input: [(1, 3), (3, 2), (2, 1)]
Output: [(2, 1), (3, 2), (1, 3)]
Explanation: sort tuple based on the last digit of each tuple.
Methods #1: Using sorted().
Sorted() method sorts a list and always returns a list with the elements in a sorted manner, without modifying the original sequence.
Approach:
Take a list of tuples from the user.
Define a function that returns the last element of each tuple in the list of tuples.
Define another function with the previous function as the key and sort the list.
Print the sorted list.
Python3
def last(n): return n[-1] def sort(tuples): return sorted(tuples, key=last) a=[(1, 3), (3, 2), (2, 1)]print("Sorted:")print(sort(a))
Output:
Sorted:
[(2, 1), (3, 2), (1, 3)]
Methods #2: Using Bubble Sort.
Access the last element of each tuple using the nested loops. This performs the in-place method of sorting. The time complexity is similar to the Bubble Sort i.e. O(n^2).
Python3
# Python program to sort# a list of tuples by the second Item # Function to sort the list# of tuples by its second itemdef Sort_Tuple(tup): # getting length of list of tuples lst = len(tup) for i in range(0, lst): for j in range(0, lst-i-1): if (tup[j][-1] > tup[j + 1][-1]): temp = tup[j] tup[j]= tup[j + 1] tup[j + 1]= temp return tup # Driver Code tup =[(1, 3), (3, 2), (2, 1)] print(Sort_Tuple(tup))
Output:
[(2, 1), (3, 2), (1, 3)]
Methods #3: Using sort().
The sort() method sorts the elements of a given list in a specific ascending or descending order.
Python3
# Python program to sort a list of# tuples by the second Item using sort() # Function to sort the list by second item of tupledef Sort_Tuple(tup): # reverse = None (Sorts in Ascending order) # key is set to sort using second element of # sublist lambda has been used tup.sort(key = lambda x: x[-1]) return tup # Driver Code tup = [(1, 3), (3, 2), (2, 1)] # printing the sorted list of tuplesprint(Sort_Tuple(tup))
Output:
[(2, 1), (3, 2), (1, 3)]
sumitgumber28
Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n19 May, 2022"
},
{
"code": null,
"e": 172,
"s": 54,
"text": "The task is to write a Python Program to sort a list of tuples in increasing order by the last element in each tuple."
},
{
"code": null,
"e": 300,
"s": 172,
... |
numpy.floor() in Python | 04 Dec, 2020
The numpy.floor) is a mathematical function that returns the floor of the elements of array. The floor of the scalar x is the largest integer i, such that i <= x.
Syntax : numpy.floor(x[, out]) = ufunc ‘floor’)Parameters :a : [array_like] Input array
Return : The floor of each element.
Code #1 : Working
# Python program explaining# floor() function import numpy as np in_array = [.5, 1.5, 2.5, 3.5, 4.5, 10.1]print ("Input array : \n", in_array) flooroff_values = np.floor(in_array)print ("\nRounded values : \n", flooroff_values) in_array = [.53, 1.54, .71]print ("\nInput array : \n", in_array) flooroff_values = np.floor(in_array)print ("\nRounded values : \n", flooroff_values) in_array = [.5538, 1.33354, .71445]print ("\nInput array : \n", in_array) flooroff_values = np.floor(in_array)print ("\nRounded values : \n", flooroff_values)
Output :
Input array :
[0.5, 1.5, 2.5, 3.5, 4.5, 10.1]
Rounded values :
[ 0. 1. 2. 3. 4. 10.]
Input array :
[0.53, 1.54, 0.71]
Rounded values :
[ 0. 1. 0.]
Input array :
[0.5538, 1.33354, 0.71445]
Rounded values :
[ 0. 1. 0.]
Code #2 : Working
# Python program explaining# floor() functionimport numpy as np in_array = [1.67, 4.5, 7, 9, 12]print ("Input array : \n", in_array) flooroff_values = np.floor(in_array)print ("\nRounded values : \n", flooroff_values) in_array = [133.000, 344.54, 437.56, 44.9, 1.2]print ("\nInput array : \n", in_array) flooroff_values = np.floor(in_array)print ("\nRounded values upto 2: \n", flooroff_values)
Output :
Input array :
[1.67, 4.5, 7, 9, 12]
Rounded values :
[ 1. 4. 7. 9. 12.]
Input array :
[133.0, 344.54, 437.56, 44.9, 1.2]
Rounded values upto 2:
[ 133. 344. 437. 44. 1.]
References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.floor.html#numpy.floor.
Python numpy-Mathematical Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate through Excel rows in Python?
Rotate axis tick labels in Seaborn and Matplotlib
Deque in Python
Queue in Python
Defaultdict in Python
Check if element exists in list in Python
Python Classes and Objects
Bar Plot in Matplotlib
reduce() in Python
Python | Get unique values from a list | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Dec, 2020"
},
{
"code": null,
"e": 191,
"s": 28,
"text": "The numpy.floor) is a mathematical function that returns the floor of the elements of array. The floor of the scalar x is the largest integer i, such that i <= x."
},
{
... |
Program for Gauss Seidel Method (Computational Mathematics) | 24 Oct, 2021
The Gauss Seidel method is an iterative process to solve a square system of (multiple) linear equations. It is also prominently known as ‘Liebmann’ method. In any iterative method in numerical analysis, every solution attempt is started with an approximate solution of an equation and iteration is performed until the desired accuracy is obtained. In Gauss-Seidel method, the most recent values are used in successive iterations. The Gauss-Seidel Method allows the user to control round-off error.The Gauss Seidel method is very similar to Jacobi method and is called as the method of successive displacement. (Since recently obtained values are used in the subsequent equations). The Gauss Seidel convergence criteria depend upon the following two properties: (must be satisfied).
The matrix is diagonally dominant.
The matrix is symmetrical and positive.
Steps involved:
Step 1: Compute value for all the linear equations for Xi. (Initial array must be available)
Step 2: Compute each Xi and repeat the above steps.
Step 3: Make use of the absolute relative approximate error after every step to check if the error occurs within a pre-specified tolerance.
Code for Gauss Seidel method:
C
#include <stdio.h> int main(){ int count, t, limit; float temp, error, a, sum = 0; float matrix[10][10], y[10], allowed_error; printf("\nEnter the Total Number of Equations:\t"); scanf("%d", & limit); // maximum error limit till which errors are considered, // or desired accuracy is obtained) printf("Enter Allowed Error:\t"); scanf("%f", & allowed_error); printf("\nEnter the Co-Efficients\n"); for(count = 1; count < = limit; count++) { for(t = 1; t < = limit + 1; t++) { printf(" Matrix[%d][%d] = " , count, t); scanf(" %f" , & matrix[count][t]); } } for(count = 1; count < = limit; count++) { y[count] = 0; } do { a = 0; for(count = 1; count < = limit; count++) { sum = 0; for(t = 1; t a) { a = error; } y[count] = temp; printf("\nY[%d]=\t%f", count, y[count]); } printf("\n"); } while(a > = allowed_error); printf("\n\nSolution\n\n"); for(count = 1; count < = limit; count++) { printf(" \nY[%d]:\t%f" , count, y[count]); } return 0;}
Output:
Enter the Total Number of Equations: 1
Enter Allowed Error: 0.5
Enter the Co-Efficients
Matrix[1][1] = 1
Matrix[1][2] = 4
Y[1]= 4.000000
Y[1]= 4.000000
Solution
Y[1]: 4.000000
Advantages:
Faster iteration process. (than other methods)
Simple and easy to implement.
Low on memory requirements.
Disadvantages:
Slower rate of convergence. (than other methods)
Requires a large number of iterations to reach the convergence point.
clintra
sooda367
Articles
Engineering Mathematics
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n24 Oct, 2021"
},
{
"code": null,
"e": 838,
"s": 54,
"text": "The Gauss Seidel method is an iterative process to solve a square system of (multiple) linear equations. It is also prominently known as ‘Liebmann’ method. In any iterative m... |
How To Extract Data From Common File Formats in Python? - GeeksforGeeks | 13 Jan, 2021
Sometimes work with some datasets must have mostly worked with .csv(Comma Separated Value) files only. They are really a great starting point in applying Data Science techniques and algorithms. But many of us will land up in Data Science firms or take up real-world projects in Data Science sooner or later. Unfortunately in real-world projects, the data won’t be available to us in a neat .csv file. There we have to extract data from different sources like images, pdf files, doc files, image files, etc. In this article, we will see the perfect start to tackle those situations.
Below we will see how to extract relevant information from multiple such sources.
Note that if the Excel file has a single sheet then the same method to read CSV file (pd.read_csv(‘File.xlsx’)) might work. But it won’t in the case of multiple sheet files as shown in the below image where there are 3 sheets( Sheet1, Sheet2, Sheet3). In this case, it will just return the first sheet.
Excel sheet used: Click Here.
Example: We will see how to read this excel-file.
Python3
# import Pandas libraryimport pandas as pd # Read our file. Here sheet_name=1# means we are reading the 2nd sheet or Sheet2df = pd.read_excel('Sample1.xlsx', sheet_name = 1)df.head()
Output:
Now let’s read a selected column of the same sheet:
Python3
# Read only column A, B, C of all# the four columns A,B,C,D in Sheet2df=pd.read_excel('Sample1.xlsx', sheet_name = 1, usecols = 'A : C')df.head()
Output:
Now let’s read all sheet together:
Sheet1 contains columns A, B, C; Sheet2 contains A, B, C, D and Sheet3 contains B, D. We will see a simple example below on how to read all the 3 sheets together and merge them into common columns.
Python3
df2 = pd.DataFrame()for i in df.keys(): df2 = pd.concat([df2, df[i]], axis = 0) display(df2)
Output:
Now we will discuss how to extract text from images.
For enabling our python program to have Character recognition capabilities, we would be making use of pytesseract OCR library. The library could be installed onto our python environment by executing the following command in the command interpreter of the OS:-
pip install pytesseract
The library (if used on Windows OS) requires the tesseract.exe binary to be also present for proper installation of the library. During the installation of the aforementioned executable, we would be prompted to specify a path for it. This path needs to be remembered as it would be utilized later on in the code. For most installations the path would be C:\\Program Files (x86)\\Tesseract-OCR\\tesseract.exe.
Image for demonstration:
Python3
# We import necessary libraries. # The PIL Library is used to read the imagesfrom PIL import Imageimport pytesseract # Read the imageimage = Image.open(r'pic.png') # Perform the information extraction from images# Note below, put the address where tesseract.exe # file is located in your systempytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe' print(pytesseract.image_to_string(image))
Output:
GeeksforGeeks
Here we will extract text from the doc file using docx module.
For installation:
pip install python-docx
Image for demonstration: Aniket_Doc.docx
Example 1: First we’ll extract the title:
Python3
# Importing our library and reading the doc fileimport docxdoc = docx.Document('csv/g.docx') # Printing the titleprint(doc.paragraphs[0].text)
Output:
My Name Aniket
Example 2: Then we’ll extract the different texts present(excluding the table).
Python3
# Getting all the text in the doc filel=[doc.paragraphs[i].text for i in range(len(doc.paragraphs))] # There might be many useless empty# strings present so removing theml=[i for i in l if len(i)!=0]print(l)
Output:
[‘My Name Aniket’, ‘ Hello I am Aniket’, ‘I am giving tutorial on how to extract text from MS Doc.’, ‘Please go through it carefully.’]
Example 3: Now we’ll extract the table:
Python3
# Since there are only one table in# our doc file we are using 0. For multiple tables# you can use suitable for tooptable = doc.tables[0] # Initializing some empty listlist1 = []list2 = [] # Looping through each row of tablefor i in range(len(table.rows)): # Looping through each column of a row for j in range(len(table.columns)): # Extracting the required text list1.append(table.rows[i].cells[j].paragraphs[0].text) list2.append(list1[:]) list1.clear() print(list2)
Output:
[['A', 'B', 'C'], ['12', 'aNIKET', '@@@'], ['3', 'SOM', '+12&']]
The task is to extract Data( Image, text) from PDF in Python. We will extract the images from PDF files and save them using PyMuPDF library. First, we would have to install the PyMuPDF library using Pillow.
pip install PyMuPDF Pillow
Example 1:
Now we will extract data from the pdf version of the same doc file.
Python3
# import moduleimport fitz # Reading our pdf filedocu=fitz.open('file.pdf') # Initializing an empty list where we will put all texttext_list=[] # Looping through all pages of the pdf filefor i in range(docu.pageCount): # Loading each page pg=docu.loadPage(i) # Extracting text from each page pg_txt=pg.getText('text') # Appending text to the empty list text_list.append(pg_txt) # Cleaning the text by removing useless# empty strings and unicode character '\u200b'text_list=[i.replace(u'\u200b','') for i in text_list[0].split('\n') if len(i.strip()) ! = 0]print(text_list)
Output:
[‘My Name Aniket ‘, ‘ Hello I am Aniket ‘, ‘I am giving tutorial on how to extract text from MS Doc. ‘, ‘Please go through it carefully. ‘, ‘A ‘, ‘B ‘, ‘C ‘, ’12 ‘, ‘aNIKET ‘, ‘@@@ ‘, ‘3 ‘, ‘SOM ‘, ‘+12& ‘]
Example 2: Extract image from PDF.
Python3
# Iterating through the pagesfor current_page in range(len(docu)): # Getting the images in that page for image in docu.getPageImageList(current_page): # get the XREF of the image . XREF can be thought of a # container holding the location of the image xref=image[0] # extract the object i.e, # the image in our pdf file at that XREF pix=fitz.Pixmap(docu,xref) # Storing the image as .png pix.writePNG('page %s - %s.png'%(current_page,xref))
The image is stored in our current file location as in format page_no.-xref.png. In our case, its name is page 0-7.png.
Now let’s plot view the image.
Python3
# Import necessary libraryimport matplotlib.pyplot as plt # Read and display the imageimg=plt.imread('page 0 - 7.png')plt.imshow(img)
Output:
python-utility
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
Python | Get unique values from a list
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n13 Jan, 2021"
},
{
"code": null,
"e": 26119,
"s": 25537,
"text": "Sometimes work with some datasets must have mostly worked with .csv(Comma Separated Value) files only. They are really a great starting point in applying Data Scie... |
How to Add Bootstrap in a Project ? - GeeksforGeeks | 21 Oct, 2021
A bootstrap is an open-source tool consisting of HTML, CSS, JavaScript frameworks. It is a dedicated responsive web development tool consisting of ready-to-use templates. It was originally named Twitter Blueprint which was developed by Mark Otto and Jacob Thornton. Over time bootstrap has evolved over version 5. So the basic website can be developed using bootstrap due to the ready-made templates available.
Reason to choose Bootstrap:
Faster and Easier Web-Development.
It creates Platform-independent web pages.
It creates Responsive Web-pages.
It’s designed to be responsive to mobile devices too.
It’s Free! Available on www.getbootstrap.com
Websites that were built with a lot of CSS and JavaScript can now be built with a few lines of code using Bootstrap. Bootstrap comprises of mainly three components:
CSS
Fonts
Javascript
The bootstrap can be used in 2 ways:
Using Bootstrap CDN Link.
By downloading the Bootstrap file.
We can easily get the resources for both approaches from the official website. Let’s begin the discussion with the first approach.
Method 1: Using CDN links – This method of installing Bootstrap is fairly easy but it requires a stable internet connection. It is highly recommended that you follow this method.
Step 1: Goto getbootstrap and click Getting Started. There you will find the below CDN links.
Step 2: Copy the links & paste it inside the <head> tag.
CSS link:
<link href=”https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css” rel=”stylesheet” integrity=”sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU” crossorigin=”anonymous”>
JavaScript link:
<script src=”https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.bundle.min.js” integrity=”sha384-/bQdsTh/da6pkI1MST/rWKFNjaCP5gBSY4sEBT38Q/9RBh9AH40zEOg7Hlq2THRZ” crossorigin=”anonymous”></script>
Step 3: After completing the above steps, the code will be like the following:
HTML
<!DOCTYPE html><html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8" /> <meta name="viewport" content= "width=device-width, initial-scale=1" /> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous" /></head> <body> <h1>Hello, world!</h1> <div> You're learning Bootstrap on Geeksforgeeks.org </div> <!-- Optional JavaScript; choose one of the two! --> <!-- Option 1: Bootstrap Bundle with Popper --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-/bQdsTh/da6pkI1MST/rWKFNjaCP5gBSY4sEBT38Q/9RBh9AH40zEOg7Hlq2THRZ" crossorigin="anonymous"> </script> <!-- Option 2: Separate Popper and Bootstrap JS --> <!-- <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.3/dist/umd/popper.min.js" integrity="sha384-W8fXfP3gkOKtndU4JGtKDvXbO53Wy8SZCQHczT5FMiiqmQfUpWbYdTil/SxwZgAN" crossorigin="anonymous"> </script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.min.js" integrity="sha384-skAcpIdS7UcVUC05LJ9Dxay8AXcDYfBJqt1CJ85S/CFujBsIzCIv+l9liuYLaMQ/" crossorigin="anonymous"> </script> --></body> </html>
At this stage, we have completed the installation process & we can now start to implement the logic.
Example: This example illustrates the use of the Bootstrap CDN link, in order to use the Bootstrap with the HTML document.
HTML
<!DOCTYPE html><html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous"/> <title>Welcome to GeeksforGeeks</title></head> <body> <h1>GeeksforGeeks</h1> <h3>Bootstrap Button</h3> <hr /> <button type="button" class="btn btn-primary">Primary </button> <button type="button" class="btn btn-secondary">Secondary </button> <button type="button" class="btn btn-success">Success </button> <button type="button" class="btn btn-danger">Danger </button> <button type="button" class="btn btn-warning">Warning </button> <button type="button" class="btn btn-info">Info </button> <button type="button" class="btn btn-light">Light </button> <button type="button" class="btn btn-dark">Dark </button> <button type="button" class="btn btn-link">Link </button></body> </html>
Output:
Method 2: By downloading Bootstrap – This method of installing bootstrap is also easy but it can work offline ( doesn’t require an internet connection ) but it might not work for some browsers.
Step 1: Goto getbootstrap and click Getting Started. Click on the Download Bootstrap button and download the compiled CSS and JS.
Step 2: A .zip file would get downloaded. Extract it and go into the distribution folder. You would see 2 folders named CSS and JS. You can make your HTML file there and then you must paste these links in their respective sections. Under CSS files the most important files to be used are bootstrap and bootstrap.min. Under JS files, the most important are bootstrap.min.js and bootstrap.js.
Step 3: Make a separate project folder and create an HTML file. Under the folder, copy the extracted files downloaded from bootstrap. Under the head tag of the HTML file, the CSS needs to be linked. The jQuery downloaded should also be copied under the JS file. Make sure that under the project file, the downloaded files and HTML page must be present in that folder.
Step 4: After completing the above steps, the final code will look like the following code example. The final code after saving files under the same folder and adding links under the head and body tag respectively.
HTML
<!DOCTYPE html><html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" type="text/css" href="css/bootstrap.css" /></head> <body> <h1>Welcome to gfg</h1> <script type="text/javascript" href="js/jquery.js"> </script> <script type="text/javascript" href="js/bootstrap.min.js"> </script></body> </html>
Example: In the example, it can be observed that the downloaded files from bootstrap are included under the head and body section. Now the bootstrap classes can directly be used. As it is downloaded, thus no need for an internet connection required to load classes of bootstrap.
HTML
<!DOCTYPE html><html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8" /> <meta name="viewport" content= "width=device-width, initial-scale=1" /> <link rel="stylesheet" type="text/css" href="css/bootstrap.css" /></head> <body> <h1>Welcome to GeeksforGeeks</h1> <div class="mb-3"> <label for="exampleFormControlInput1" class="form-label"> Email address </label> <input type="email" class="form-control" id="exampleFormControlInput1" placeholder="name@example.com" /> </div> <div class="mb-3"> <label for="exampleFormControlTextarea1" class="form-label"> Example textarea </label> <textarea class="form-control" id="exampleFormControlTextarea1" rows="3"> </textarea> </div> <script type="text/javascript" href="js/jquery.js"> </script> <script type="text/javascript" href="js/bootstrap.min.js"> </script></body> </html>
Output:
kalrap615
sagartomar9927
Bootstrap-4
Bootstrap-Questions
HTML-Questions
Picked
Bootstrap
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Show Images on Click using HTML ?
How to set Bootstrap Timepicker using datetimepicker library ?
How to Use Bootstrap with React?
How to keep gap between columns using Bootstrap?
Tailwind CSS vs Bootstrap
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": 26865,
"s": 26837,
"text": "\n21 Oct, 2021"
},
{
"code": null,
"e": 27277,
"s": 26865,
"text": "A bootstrap is an open-source tool consisting of HTML, CSS, JavaScript frameworks. It is a dedicated responsive web development tool consisting of ready-to-use tem... |
fmt command in Linux with examples - GeeksforGeeks | 15 May, 2019
fmt command in LINUX actually works as a formatter for simplifying and optimizing text files. Formatting of text files can also be done manually, but it can be really time consuming when it comes to large text files, this is where fmt comes to rescue.
fmt re formats each paragraph in the file specified, writing to standard output. Here’s the syntax of fmt command :
// syntax of fmt command
$fmt [-WIDTH] [OPTION]... [FILE]...
where, the -WIDTH is an abbreviated firm of –width=DIGITS and OPTION refers to the options compatible with the fmt command and FILE refers to the file name.
If no FILE is specified, or if FILE is a dash(“-“), fmt reads from the standard input.
fmt by default with no option used format all the words present in the given file in a single line.
$ cat kt.txt
hello
everyone.
Have
a
nice
day.
/* fmt by default puts all words
in a single line and prints on
stdout. */
$fmt kt.txt
hello everyone. Have a nice day.
To save or write the formatted output you can use fmt as :
/* Here the formatted output gets
written in dv.txt */
$fmt kt.txt > dv.txt
-w, – -width=WIDTH option : By default, the maximum width is 75 that fmt command produces in output but with the help of -w option it can be changed, it just requires a numerical value for the width you want to specify.$cat kt.txt
hello everyone. Have a nice day.
/* the width gets reduced to 10
with -e option */
$fmt -w 10 kt.txt
hello ever
yone. Have
a nice day.
$cat kt.txt
hello everyone. Have a nice day.
/* the width gets reduced to 10
with -e option */
$fmt -w 10 kt.txt
hello ever
yone. Have
a nice day.
-t, – -tagged-paragraph option : There can be a need for highlighting the very first line in a text file which can be done by making the indentation of first line different from the other lines which can be done with -t command.$cat kt.txt
hello everyone. Have a nice
and prosperous day.
/*-t makes the indentation
of first line different
from others */
$fmt -t kt.txt
hello everyone. Have a nice
and prosperous day.
$cat kt.txt
hello everyone. Have a nice
and prosperous day.
/*-t makes the indentation
of first line different
from others */
$fmt -t kt.txt
hello everyone. Have a nice
and prosperous day.
-s option : This option split long lines, but don’t refill them.$cat kt.txt
Love is patient, love is kind. It does not envy,
it does not boast, it is not proud. It is not rude,
it is not self-seeking, it is not easily angered,
it keeps no record of wrongs. Love does not delight
in evil but rejoices with the truth. It always protects,
always trusts, always hopes, always perseveres.
Love never fails.
/* long lines get splited with -s option */
$fmt -s kt.txt
Love is patient, love is kind.
It does not envy, it does not boast, it is not proud.
It is not rude, it is not self-seeking,
it is not easily angered, it keeps no record of wrongs.
Love does not delight in evil but rejoices with the truth.
It always protects, always trusts, always hopes, always perseveres.
Love never fails.
$cat kt.txt
Love is patient, love is kind. It does not envy,
it does not boast, it is not proud. It is not rude,
it is not self-seeking, it is not easily angered,
it keeps no record of wrongs. Love does not delight
in evil but rejoices with the truth. It always protects,
always trusts, always hopes, always perseveres.
Love never fails.
/* long lines get splited with -s option */
$fmt -s kt.txt
Love is patient, love is kind.
It does not envy, it does not boast, it is not proud.
It is not rude, it is not self-seeking,
it is not easily angered, it keeps no record of wrongs.
Love does not delight in evil but rejoices with the truth.
It always protects, always trusts, always hopes, always perseveres.
Love never fails.
-u, – -uniform-spacing option : This option uses one space between words and two spaces after sentences for formatting.$cat kt.txt
Love is patient, love is kind.
It does not envy, it does not boast,
it is not proud.
/* Spaces are uniformed with -u option */
$fmt -u kt.txt
Love is patient, love is kind. It does not envy,
it does not boast, it is not proud.
$cat kt.txt
Love is patient, love is kind.
It does not envy, it does not boast,
it is not proud.
/* Spaces are uniformed with -u option */
$fmt -u kt.txt
Love is patient, love is kind. It does not envy,
it does not boast, it is not proud.
-c, – -crown-margin option : This option preserves the indentation of the first two lines.
-p, – -prefix=STRING option : This option takes a STRING as an argument and reformat only lines beginning with STRING, reattaching the prefix to reformatted lines.
-g, – -goal=WIDTH option : This option refers to the goal width i.e default of 93% of width.
– -help option : This display a help message and exit.
– -version option : This display version information and exit.
fmt lets you format the large text files easily with the options like -u which can be very difficult task if done manually.
fmt also lets you change the default width with the help of -w option.
It is a good way to save time when it comes to format the files.
linux-command
Linux-file-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
Docker - COPY Instruction
mv command in Linux with examples
SED command in Linux | Set 2
chown command in Linux with Examples
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
Thread functions in C/C++
uniq Command in LINUX with examples
Start/Stop/Restart Services Using Systemctl in Linux | [
{
"code": null,
"e": 25651,
"s": 25623,
"text": "\n15 May, 2019"
},
{
"code": null,
"e": 25903,
"s": 25651,
"text": "fmt command in LINUX actually works as a formatter for simplifying and optimizing text files. Formatting of text files can also be done manually, but it can be rea... |
Data Structures | Linked List | Question 12 - GeeksforGeeks | 28 Jun, 2021
A circularly linked list is used to represent a Queue. A single variable p is used to access the Queue. To which node should p point such that both the operations enQueue and deQueue can be performed in constant time? (GATE 2004)
(A) rear node(B) front node(C) not possible with a single pointer(D) node next to frontAnswer: (A)Explanation: Answer is not “(b) front node”, as we can not get rear from front in O(1), but if p is rear we can implement both enQueue and deQueue in O(1) because from rear we can get front in O(1). Below are sample functions. Note that these functions are just sample are not working. Code to handle base cases is missing.
/* p is pointer to address of rear (double pointer). This function adds new node after rear and updates rear which is *p to point to new node */void enQueue(struct node **p, struct node *new_node){ /* Missing code to handle base cases like *p is NULL */ new_node->next = (*p)->next; (*p)->next = new_node; (*p) = new_node /* new is now rear */ /* Note that p->next is again front and p is rear */ } /* p is pointer to rear. This function removes the front element and returns the dequeued element from the queue */struct node *deQueue(struct node *p){ /* Missing code to handle base cases like p is NULL, p->next is NULL,... etc */ struct node *temp = p->next; p->next = p->next->next; return temp; /* Note that p->next is again front and p is rear */}
Quiz of this QuestionQuiz of this Question
harshilmarwah
amansinghrocks81
Data Structures
Data Structures-Linked List
Linked Lists
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++
Data Structures | Hash | Question 5
Encryption and Decryption of String according to given technique
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": 26121,
"s": 26093,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 26351,
"s": 26121,
"text": "A circularly linked list is used to represent a Queue. A single variable p is used to access the Queue. To which node should p point such that both the operations ... |
JavaScript | Check if a variable is a string - GeeksforGeeks | 15 Apr, 2019
Checking the type of a variable can be done by using typeof operator. It directly applies either to a variable name or to a variable.
Syntax:
typeof varName;
varName: It is the name of variable.
Example-1:This Example checks if the variable boolValue and numValue is string.
<!DOCTYPE html><html> <head> <title> Javascript | Check if a variable is a string </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p> var boolValue = true; <br> var numValue = 17; </p> <button onclick="Geeks()"> Click to check </button> <p id="GFG_P" style="color:green; font-size: 20px;"> </p> <script> function Geeks() { <!-- "boolean" value. --> var boolValue = true; <!-- "integer " value. --> var numValue = 17; var el = document.getElementById("GFG_P"); var bool, num; if (typeof boolValue == "string") { bool = "is a string"; } else { bool = "is not a string"; } if (typeof numValue == "string") { num = "is a string"; } else { num = "is not a string"; } el.innerHTML = "boolValue " + bool + "<br>numValue " + num; } </script></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Example-2:This Example checks if the variable strValue and objGFG is string.
<!DOCTYPE html><html> <head> <title> Javascript | Check if a variable is a string </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p> <!-- "String" value. --> var strValue = "This is GeeksForGeeks"; <br> <!-- "Object" value. --> var objGFG = new String( "This is GeeksForGeeks" ); </p> <button onclick="Geeks()"> Click to check </button> <p id="GFG_P" style="color:green; font-size: 20px;"> </p> <script> function Geeks() { var strValue = "This is GeeksForGeeks"; var objGFG = new String("This is GeeksForGeeks"); var el = document.getElementById("GFG_P"); var str, obj; if (typeof strValue == 'string') { str = "is a string"; } else { str = "is not a string"; } if (typeof objGFG == "string") { obj = "is a string"; } else { obj = "is not a string"; } el.innerHTML = "strValue " + str + "<br>objGFG " + obj; } </script></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
javascript-basics
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 26399,
"s": 26371,
"text": "\n15 Apr, 2019"
},
{
"code": null,
"e": 26533,
"s": 26399,
"text": "Checking the type of a variable can be done by using typeof operator. It directly applies either to a variable name or to a variable."
},
{
"code": null,
... |
Oracle Interview Experience for Associate Software Developer | On-Campus 2021 - GeeksforGeeks | 05 Oct, 2021
Oracle visited our campus in early August 2021 for the role of Associate Software Developer for the CGBU vertical. The selection process consisted of 4 rounds. The cutoff was 7.0 CGPA and CSE, ECE and EE can only apply.
There were a total of 4 rounds which include 1 online test and 3 interview rounds conducted in Zoom.
ROUND 1(MCQ TEST): This was an MCQ round conducted on Oracle’s Assessment Platform with 92 questions and for 107 minutes.
There were a total of 4 sections, each had multiple sub-sections which had questions from various topics.
Each sub-section has its own time limit.
So managing your time effectively is the key to clear this round(Later in this article I will tell you how to do it).
In some sub-sections, you may submit before the time ends and in other sub-sections, you may not even reach up to the last que.
One more important thing about this round is you cannot go backward which means you cannot go from que 5 to que 3.
Let’s suppose there are 10 que in a sub-section. Then in each que you can either answer it or skip it. once you answer a que, you cannot revisit it, So answer only if you are sure otherwise skip it for now. After answer/skip last que, you will automatically come to first Skipped que. Then you can answer it or skip it again. In this way you will move in cyclic order.
The sections were:
Aptitude Test
Sub section Time(min) Questions
Math Reasoning 12 10
Data Analysis 9 8
Persistence and Attention to detail 5 6
Programming ability 13 9
Logical Thinking 8 6
Coding Skills(16 que 25 minutes no subsections)
Computer Science Knowledge
17 que 15 minutes
3 – 4 subsections of OOPS, DBMS, OS, Data Structures
MCQ on BST, AVL tree will definitely come. Red-Black tree may also come.
Contextual Communication
3 sub-sections were there.
Data comprehension, vocabulary etc.
Total 35 students were selected
Tips to manage time in this round:
After reading a que, if you think you can definitely solve it in under 2min(depend on time and no of que remaining), solve it else immediately skip it without wasting your time. In this way, you will at least solve all the que which you know or are easy. After one Iteration, you can again attempt skipped que.
Try to increase your speed of solving aptitude que before attempting test.
ROUND 2(Tech Interview): This round went for about 1 hour 30 min.
Install an IDE on you laptop beforehand
The interview started with a basic introduction. Then I was asked to explain one of my projects and I was asked some questions on it. Not much cross-questioning was done on project.
Then he asked me about Inheritance, polymorphism, and other oops concepts. He was checking my conceptual understanding. Try to give a real-life example of each and every concept you explain. In this way, he will be sure that you really understand the concept in detail.
A lot of cross-questioning was done on from his side.
Then he asked about virtual pointer and vtable
Hash table vs BST. why we use BST if we can search a key in o(1) in hast table.
Explain operation of stack and queue and give real-life examples where they are used.
Explain multiple and multilevel inheritances.
If class C is inherited from 2 classes A and B and both has display function, then which class’s display function will be called if I write C.display(). Watch this video in case you dint know the answer (https://youtu.be/h3INeRqf2vU)
What is problem with multiple inheritance.(Diamond Problem)
Data hiding vs abstraction
cursor in Database
What will be the size of an object whose class has just 1 variable.
Normalisation and Denormalisation
Do you know linux ( I replied no and he said no problem)
Detect Loop in Linked List(You will have to write its full code from scratch so go through it once)https://www.geeksforgeeks.org/detect-loop-in-a-linked-list/
There are two threads one printing even no. and one odd no. Implement this in CPP.
Find no of words in a paragraph (input should be taken from a file and not through cin function)
A program has a global variable and a function. Inside that function, two local variables were declared and an object was created. Draw the memory diagram.
ROUND 3(Tech Interview): A brief discussion on my projects
Your role in your project
How did you divide work
Did any conflict arise between team members during project and if yes how did you resolved them
Why did you choose C++?
advantages of CPP over C.
Are you familiar with Linux Operating system ( I replied no and he said no problem)
In which order the keywords of an sql query are executed. (ANS: First FROM is executed then WHERE, then SELECT then GROUP BY, ORDER BY)
He Asked me this puzzle. https://www.ritambhara.in/3-basket-puzzle-appleorange-puzzle/
Another puzzle: https://www.geeksforgeeks.org/puzzle-9-find-the-fastest-3-horses/
ROUND 4(Tech + HR): A brief discussion about my projects
Would you prefer to work in a team or alone
A client wants you to design a product(like app/website), so what are the thing which you will ask him about it before actually start coding.
Are you familiar with cloud computing.
Some other HR que like hobbies etc.
Verdict: Selected
TIPS FOR CLEARING INTERVIEWS-
They do a lot of cross-questioning, so think before answering a question and do not use very heavy technical terms which you don’t know.
You should definitely attend PPT. Answers to many HR que are told in PPT.
If you don’t know something just admit it. They don’t want you to know everything.
They mainly try to check whether your concepts are clear or not so explain them properly and try to give a real-life example wherever you can.
Prepare everything written on your resume.
Marketing
On-Campus
Oracle
Interview Experiences
Oracle
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Amazon Interview Experience for SDE-1 (Off-Campus)
Amazon AWS Interview Experience for SDE-1
Amazon Interview Experience for SDE-1 (Off-Campus) 2022
Amazon Interview Experience
Amazon Interview Experience for SDE-1
Freshworks/Freshdesk Interview Experience for Software Developer (On-Campus)
Amazon Interview Experience (Off-Campus) 2022
Amazon Interview Experience for SDE-1 (On-Campus)
JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021
EPAM Interview Experience (Off-Campus) | [
{
"code": null,
"e": 26261,
"s": 26233,
"text": "\n05 Oct, 2021"
},
{
"code": null,
"e": 26481,
"s": 26261,
"text": "Oracle visited our campus in early August 2021 for the role of Associate Software Developer for the CGBU vertical. The selection process consisted of 4 rounds. The... |
How to create an Avatar generator app in ReactJS ? - GeeksforGeeks | 23 Dec, 2021
In this article, we are going to make a simple avatar generator app that generates random images. In this avatar generator, we have several buttons for different categories to choose from, the next button to generate random images, and a download button to finally download your favorite avatar.
Prerequisites: The pre-requisites for this project are:
React
Functional components
React Hooks
React Axios & API
Javascript ES6
Basic setup: Start a project by the following command:
npx create-react-app avatarApp
Now, go to the project folder i.e avatarApp:
cd avatarApp
Now, go to the src folder and create a Components folder and a Styles folder. Under the Components folder, create a file ‘Avatar.jsx‘ and under the Styles folder, create a file ‘Avatar.css‘
Now, open the console and install the Axios npm package:
npm install axios
index.js:
Javascript
import React from 'react';import ReactDOM from 'react-dom';import './index.css';import App from './App'; ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById('root'));
App.js: App component renders a single Avatar component
Javascript
import './App.css';import Avatar from './Components/Avatar'; function App() { return ( <div className="App"> <Avatar /> </div> );}export default App;
App.css: This sets the background of our app to a nice CSS gradient
.App {
margin: 0;
padding: 0;
background-color: #b8c6db;
background-image: linear-gradient(315deg, #b8c6db 0%, #f5f7fa 74%);
}
Avatar.jsx: This file contains all the logic. We will be using a free opensource API (no auth required) called ‘DiceBear Avatars’ to fetch random avatars based on several parameters.
Javascript
import React, { useState } from 'react';import '../Styles/Avatar.css';import Axios from 'axios'; const Avatar = () => { // Setting up the initial states using react hook 'useState' const [sprite, setSprite] = useState("bottts"); const [seed, setSeed] = useState(1000); // Function to set the current sprite type function handleSprite(spritetype) { setSprite(spritetype); } // Function to generate random seeds for the API function handleGenerate() { let x = Math.floor(Math.random() * 1000); setSeed(x); } // Function to download image and save it in our computer function downloadImage() { Axios({ method: "get", url: `https://avatars.dicebear.com/api/${sprite}/${seed}.svg`, responseType: "arraybuffer" }) .then((response) => { var link = document.createElement("a"); link.href = window.URL.createObjectURL( new Blob([response.data], { type: "application/octet-stream" }) ); link.download = `${seed}.svg`; document.body.appendChild(link); link.click(); setTimeout(function () { window.URL.revokeObjectURL(link); }, 200); }) .catch((error) => { }); } return ( <div className="container"> <div className="nav"> <p>Random Avatar Generator</p> </div> <div className="home"> <div className="btns"> <button onClick={() => { handleSprite("avataaars") }}>Human</button> <button onClick={() => { handleSprite("human") }}>Pixel</button> <button onClick={() => { handleSprite("bottts") }}>Bots</button> <button onClick={() => { handleSprite("jdenticon") }}>Vector</button> <button onClick={() => { handleSprite("identicon") }}>Identi</button> <button onClick={() => { handleSprite("gridy") }}>Alien</button> <button onClick={() => { handleSprite("micah") }}>Avatars</button> </div> <div className="avatar"> <img src={`https://avatars.dicebear.com/api/${sprite}/${seed}.svg`} alt="Sprite" /> </div> <div className="generate"> <button id="gen" onClick={() => { handleGenerate() }}>Next</button> <button id="down" onClick={() => { downloadImage() }}>Download</button> </div> </div> </div> )} export default Avatar;
Avatar.css: Use this file to decorate our app
@import url('https://fonts.googleapis.com/css2?family=Roboto+Mono:wght@400;600;700&display=swap');
@import url('https://fonts.googleapis.com/css2?family=Zen+Tokyo+Zoo&display=swap');
.nav{
height: 6vh;
width: 100%;
background-color: #313442;
display: flex;
justify-content: center;
align-items: center;
color: white;
font-family: 'Zen Tokyo Zoo', cursive;
font-size: 35px;
}
.home{
box-sizing: border-box;
height: 94vh;
width: 100%;
gap: 15px;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.avatar{
height: 50%;
width: 50%;
max-width: 400px;
max-height: 400px;
margin-top: 40px;
margin-bottom: 45px;
}
.btns{
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: center;
}
button{
width: 6em;
height: 2.5em;
margin: 10px;
font-size: 20px;
font-weight: 600;
font-family: 'Roboto Mono', monospace;
background-color: rgb(231, 231, 231);
box-shadow: 2px 3px 5px rgb(102, 101, 101);
border-radius: 15px;
border: none;
transition: 0.2s;
}
button:active{
box-shadow: none;
}
.btns > button:hover{
background-color: #ffffff;
}
#gen{
background-color: #4361ee;
color: white;
}
#down{
background-color: #EB3349;
color: white;
}
Save all the files and start the server:
npm start
Open http://localhost:3000/ URL in the browser. It will display the result. Our app is now complete and it should be working now.
ruhelaa48
CSS-Properties
React-Questions
CSS
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a web page using HTML and CSS
How to set space between the flexbox ?
Form validation using jQuery
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
How to pass data from child component to its parent in ReactJS ?
How to pass data from one component to other component in ReactJS ?
ReactJS Functional Components | [
{
"code": null,
"e": 26681,
"s": 26653,
"text": "\n23 Dec, 2021"
},
{
"code": null,
"e": 26977,
"s": 26681,
"text": "In this article, we are going to make a simple avatar generator app that generates random images. In this avatar generator, we have several buttons for different c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.