title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Python - How to install the Flask framework? - onlinetutorialspoint
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws Flask is a micro web framework written in Python that widely used. Here the Micro doesn’t mean that your entire web application fits into a single python file, nor it’s lacking in functionality compared to other web frameworks. The intention of saying the micro framework is, it aims the core platform as simple and extendable. It doesn’t come with any heavy inbuilt package abstractions such as database layers and templating frameworks etc. It lets you decide the things you want to use and it supports extensions to add such dependencies into your application. It’s always highly recommended to install Flask on the latest Python at least 3.6 and newer. Installing Python is different for different operating systems, I have written a separate article for windows installation. On Mac OS you can use the brew command. % brew install python3 The above command installs the python3 latest version. $ sudo apt-get install python3 python-env The above Linux command will install the python3 and python virtual environment. After you install the Python, let’s install the Flask in your application. Its always recommended to create a python virtual environment whenever we start a new project. % mkdir flask-hello-world # create application root folder % cd flask-hello-world # get into application folder % python3 -m venv venv # create virtual environment(venv) The above command python -m venv venv creates the virtual environment with venv name. It’s up to you to decide the name of the virtual environment. % source venv/bin/activate # Mac/Linux users > venv\Scripts\activate # Windows users Soon after activating the virtual environment, you would have noticed that your prompt is being modified with your virtual environment name like below. (venv) flask-hello-world % Now we are all set to install the Flask web framework. Flask can be installed by using python package installer that is pip (venv) flask-hello-world % pip install flask Collecting flask Using cached Flask-2.0.1-py3-none-any.whl (94 kB) Requirement already satisfied: Jinja2>=3.0 in ./venv/lib/python3.8/site-packages (from flask) (3.0.1) Requirement already satisfied: itsdangerous>=2.0 in ./venv/lib/python3.8/site-packages (from flask) (2.0.1) Requirement already satisfied: Werkzeug>=2.0 in ./venv/lib/python3.8/site-packages (from flask) (2.0.1) Requirement already satisfied: click>=7.1.2 in ./venv/lib/python3.8/site-packages (from flask) (8.0.1) Requirement already satisfied: MarkupSafe>=2.0 in ./venv/lib/python3.8/site-packages (from Jinja2>=3.0->flask) (2.0.1) Installing collected packages: flask Successfully installed flask-2.0.1 The above pip install flask command is going to bring Flask from the python package repository along with the number of other packages that Flask depends on. Werkzeug – implements WSGI framework Jinja – A templating language that used to render the web pages on the server MarkupSafe – Cones along with jinja ItsDangerous – For security integrity Click – For writing command-line applications You can verify the Flask installation by importing the flask into the python interpreter like below. (venv) flask-hello-world % python Python 3.8.5 (v3.8.5:580fbb018f, Jul 20 2020, 12:11:27) [Clang 6.0 (clang-600.0.57)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import flask >>> The import flask will bring the flask packages into the python session, if you did not get any errors while importing the flask that means it successfully installed 🙂 More on Flask dependencies Python Installation Python Virtual environment Happy Learning 🙂 How to setup Python VirtualEnv Python Django Helloworld Example How to upgrade Python PIP version on Windows How install Python on Windows 10 Python Selenium HelloWorld Example Python – How to read environment variables ? Where can I find Python PIP in windows ? Python – AWS SAM Lambda Example Python – Selenium Download a File in Headless Mode Python Operators Example Python Selenium Automate the Login Form Python MySQL create database and table How to install Maven on Ubuntu 14.x How to Remove Spaces from String in Python How to connect MySQL DB with Python How to setup Python VirtualEnv Python Django Helloworld Example How to upgrade Python PIP version on Windows How install Python on Windows 10 Python Selenium HelloWorld Example Python – How to read environment variables ? Where can I find Python PIP in windows ? Python – AWS SAM Lambda Example Python – Selenium Download a File in Headless Mode Python Operators Example Python Selenium Automate the Login Form Python MySQL create database and table How to install Maven on Ubuntu 14.x How to Remove Spaces from String in Python How to connect MySQL DB with Python
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 627, "s": 398, "text": "Flask is a micro web framework written in Python that widely used. Here the Micro doesn’t mean that your entire web application fits into a single python file, nor it’s lacking in functionality compared to other web frameworks." }, { "code": null, "e": 963, "s": 627, "text": "The intention of saying the micro framework is, it aims the core platform as simple and extendable. It doesn’t come with any heavy inbuilt package abstractions such as database layers and templating frameworks etc. It lets you decide the things you want to use and it supports extensions to add such dependencies into your application." }, { "code": null, "e": 1056, "s": 963, "text": "It’s always highly recommended to install Flask on the latest Python at least 3.6 and newer." }, { "code": null, "e": 1180, "s": 1056, "text": "Installing Python is different for different operating systems, I have written a separate article for windows installation." }, { "code": null, "e": 1220, "s": 1180, "text": "On Mac OS you can use the brew command." }, { "code": null, "e": 1243, "s": 1220, "text": "% brew install python3" }, { "code": null, "e": 1298, "s": 1243, "text": "The above command installs the python3 latest version." }, { "code": null, "e": 1340, "s": 1298, "text": "$ sudo apt-get install python3 python-env" }, { "code": null, "e": 1421, "s": 1340, "text": "The above Linux command will install the python3 and python virtual environment." }, { "code": null, "e": 1591, "s": 1421, "text": "After you install the Python, let’s install the Flask in your application. Its always recommended to create a python virtual environment whenever we start a new project." }, { "code": null, "e": 1773, "s": 1591, "text": "% mkdir flask-hello-world # create application root folder\n% cd flask-hello-world # get into application folder\n% python3 -m venv venv # create virtual environment(venv)" }, { "code": null, "e": 1921, "s": 1773, "text": "The above command python -m venv venv creates the virtual environment with venv name. It’s up to you to decide the name of the virtual environment." }, { "code": null, "e": 2018, "s": 1921, "text": "% source venv/bin/activate # Mac/Linux users\n\n> venv\\Scripts\\activate # Windows users" }, { "code": null, "e": 2170, "s": 2018, "text": "Soon after activating the virtual environment, you would have noticed that your prompt is being modified with your virtual environment name like below." }, { "code": null, "e": 2197, "s": 2170, "text": "(venv) flask-hello-world %" }, { "code": null, "e": 2252, "s": 2197, "text": "Now we are all set to install the Flask web framework." }, { "code": null, "e": 2321, "s": 2252, "text": "Flask can be installed by using python package installer that is pip" }, { "code": null, "e": 3043, "s": 2321, "text": "(venv) flask-hello-world % pip install flask\nCollecting flask\n Using cached Flask-2.0.1-py3-none-any.whl (94 kB)\nRequirement already satisfied: Jinja2>=3.0 in ./venv/lib/python3.8/site-packages (from flask) (3.0.1)\nRequirement already satisfied: itsdangerous>=2.0 in ./venv/lib/python3.8/site-packages (from flask) (2.0.1)\nRequirement already satisfied: Werkzeug>=2.0 in ./venv/lib/python3.8/site-packages (from flask) (2.0.1)\nRequirement already satisfied: click>=7.1.2 in ./venv/lib/python3.8/site-packages (from flask) (8.0.1)\nRequirement already satisfied: MarkupSafe>=2.0 in ./venv/lib/python3.8/site-packages (from Jinja2>=3.0->flask) (2.0.1)\nInstalling collected packages: flask\nSuccessfully installed flask-2.0.1" }, { "code": null, "e": 3201, "s": 3043, "text": "The above pip install flask command is going to bring Flask from the python package repository along with the number of other packages that Flask depends on." }, { "code": null, "e": 3238, "s": 3201, "text": "Werkzeug – implements WSGI framework" }, { "code": null, "e": 3316, "s": 3238, "text": "Jinja – A templating language that used to render the web pages on the server" }, { "code": null, "e": 3352, "s": 3316, "text": "MarkupSafe – Cones along with jinja" }, { "code": null, "e": 3390, "s": 3352, "text": "ItsDangerous – For security integrity" }, { "code": null, "e": 3436, "s": 3390, "text": "Click – For writing command-line applications" }, { "code": null, "e": 3537, "s": 3436, "text": "You can verify the Flask installation by importing the flask into the python interpreter like below." }, { "code": null, "e": 3759, "s": 3537, "text": "(venv) flask-hello-world % python\nPython 3.8.5 (v3.8.5:580fbb018f, Jul 20 2020, 12:11:27) \n[Clang 6.0 (clang-600.0.57)] on darwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import flask\n>>>" }, { "code": null, "e": 3926, "s": 3759, "text": "The import flask will bring the flask packages into the python session, if you did not get any errors while importing the flask that means it successfully installed 🙂" }, { "code": null, "e": 3953, "s": 3926, "text": "More on Flask dependencies" }, { "code": null, "e": 3973, "s": 3953, "text": "Python Installation" }, { "code": null, "e": 4000, "s": 3973, "text": "Python Virtual environment" }, { "code": null, "e": 4017, "s": 4000, "text": "Happy Learning 🙂" }, { "code": null, "e": 4584, "s": 4017, "text": "\nHow to setup Python VirtualEnv\nPython Django Helloworld Example\nHow to upgrade Python PIP version on Windows\nHow install Python on Windows 10\nPython Selenium HelloWorld Example\nPython – How to read environment variables ?\nWhere can I find Python PIP in windows ?\nPython – AWS SAM Lambda Example\nPython – Selenium Download a File in Headless Mode\nPython Operators Example\nPython Selenium Automate the Login Form\nPython MySQL create database and table\nHow to install Maven on Ubuntu 14.x\nHow to Remove Spaces from String in Python\nHow to connect MySQL DB with Python\n" }, { "code": null, "e": 4615, "s": 4584, "text": "How to setup Python VirtualEnv" }, { "code": null, "e": 4648, "s": 4615, "text": "Python Django Helloworld Example" }, { "code": null, "e": 4693, "s": 4648, "text": "How to upgrade Python PIP version on Windows" }, { "code": null, "e": 4726, "s": 4693, "text": "How install Python on Windows 10" }, { "code": null, "e": 4761, "s": 4726, "text": "Python Selenium HelloWorld Example" }, { "code": null, "e": 4806, "s": 4761, "text": "Python – How to read environment variables ?" }, { "code": null, "e": 4847, "s": 4806, "text": "Where can I find Python PIP in windows ?" }, { "code": null, "e": 4879, "s": 4847, "text": "Python – AWS SAM Lambda Example" }, { "code": null, "e": 4930, "s": 4879, "text": "Python – Selenium Download a File in Headless Mode" }, { "code": null, "e": 4955, "s": 4930, "text": "Python Operators Example" }, { "code": null, "e": 4995, "s": 4955, "text": "Python Selenium Automate the Login Form" }, { "code": null, "e": 5034, "s": 4995, "text": "Python MySQL create database and table" }, { "code": null, "e": 5070, "s": 5034, "text": "How to install Maven on Ubuntu 14.x" }, { "code": null, "e": 5113, "s": 5070, "text": "How to Remove Spaces from String in Python" } ]
Mobile Ads Click-Through Rate (CTR) Prediction | by Susan Li | Towards Data Science
In Internet marketing, click-through rate (CTR) is a metric that measures the number of clicks advertisers receive on their ads per number of impressions. Mobile has become seamless with all channels, and mobile is the driving force with what’s driving all commerce. Mobile ads are expected to generate $1.08 billion this year, which would be a 122% jump from last year. In this research analysis, Criteo Labs is sharing 10 days’ worth of Avazu data for us to develop models predicting ad click-through rate (CTR). Given a user and the page he (or she) is visiting. what is the probability that he (or she) will click on a given ad? The goal of this analysis is to benchmark the most accurate ML algorithms for CTR estimation. Let’s get started! The data set can be found here. id: ad identifier click: 0/1 for non-click/click hour: format is YYMMDDHH, so 14091123 means 23:00 on Sept. 11, 2014 UTC. C1 — anonymized categorical variable banner_pos site_id site_domain site_category app_id app_domain app_category device_id device_ip device_model device_type device_conn_type C14-C21 — anonymized categorical variables The training set contains over 40 millions of records, to be able to process locally, we will randomly sample 1 million of them. import numpy as nimport randomimport pandas as pdimport gzipn = 40428967 #total number of records in the clickstream data sample_size = 1000000skip_values = sorted(random.sample(range(1,n), n-sample_size))parse_date = lambda val : pd.datetime.strptime(val, '%y%m%d%H')with gzip.open('train.gz') as f: train = pd.read_csv(f, parse_dates = ['hour'], date_parser = parse_date, dtype=types_train, skiprows = skip_values) Because of the anonymization, we don’t know what each value means in each feature. In addition, most of the features are categorical and most of the categorical features have a lot of values. This makes EDA less intuitive easier to confuse, but we will try the best. Features We can group all the features in the data into the following categories: Target feature : click site features : site_id, site_domain, site_category app feature: app_id, app_domain, app_category device feature: device_id, device_ip, device_model, device_type, device_conn_type anonymized categorical features: C14-C21 import seaborn as snsimport matplotlib.pyplot as pltsns.countplot(x='click',data=train, palette='hls')plt.show(); train['click'].value_counts()/len(train) The overall click through rate is approx. 17%, and approx. 83% is not clicked. train.hour.describe() The data covers 10 days of click streams data from 2014–10–21 to 2014–10–30, that is 240 hours. train.groupby('hour').agg({'click':'sum'}).plot(figsize=(12,6))plt.ylabel('Number of clicks')plt.title('Number of clicks by hour'); The hourly clicks pattern looks pretty similar every day. However, there were a couple of peak hours, one is sometime in the mid of the day on Oct 22, and another is sometime in the mid of the day on Oct 28. And one very low click hour is close to mid-night on Oct 24. Hour Extract hour from date time feature. train['hour_of_day'] = train.hour.apply(lambda x: x.hour)train.groupby('hour_of_day').agg({'click':'sum'}).plot(figsize=(12,6))plt.ylabel('Number of clicks')plt.title('click trends by hour of day'); In general, the highest number of clicks is at hour 13 and 14 (1pm and 2pm), and the lowest number of clicks is at hour 0 (mid-night). It seems a useful feature for roughly estimation. Let’s take impressions into consideration. train.groupby(['hour_of_day', 'click']).size().unstack().plot(kind='bar', title="Hour of Day", figsize=(12,6))plt.ylabel('count')plt.title('Hourly impressions vs. clicks'); There is nothing shocking here. Now that we have looked at clicks and impressions. We can calculate click-through rate (CTR). CTR is the ratio of ad clicks to impressions. It measures the rate of clicks on each ad. Hourly CTR import seaborn as snsdf_click = train[train['click'] == 1]df_hour = train[['hour_of_day','click']].groupby(['hour_of_day']).count().reset_index()df_hour = df_hour.rename(columns={'click': 'impressions'})df_hour['clicks'] = df_click[['hour_of_day','click']].groupby(['hour_of_day']).count().reset_index()['click']df_hour['CTR'] = df_hour['clicks']/df_hour['impressions']*100plt.figure(figsize=(12,6))sns.barplot(y='CTR', x='hour_of_day', data=df_hour)plt.title('Hourly CTR'); One of the interesting observations here is that the highest CTR happened in the hour of mid-night, 1, 7 and 15. If you remember, around mid-night has the least number of impressions and clicks. Day of week train['day_of_week'] = train['hour'].apply(lambda val: val.weekday_name)cats = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']train.groupby('day_of_week').agg({'click':'sum'}).reindex(cats).plot(figsize=(12,6))ticks = list(range(0, 7, 1)) # points on the x axis where you want the label to appearlabels = "Mon Tues Weds Thurs Fri Sat Sun".split()plt.xticks(ticks, labels)plt.title('click trends by day of week'); train.groupby(['day_of_week','click']).size().unstack().reindex(cats).plot(kind='bar', title="Day of the Week", figsize=(12,6))ticks = list(range(0, 7, 1)) # points on the x axis where you want the label to appearlabels = "Mon Tues Weds Thurs Fri Sat Sun".split()plt.xticks(ticks, labels)plt.title('Impressions vs. clicks by day of week'); Tuesdays have the most number of impressions and clicks, then Wednesdays, followed by Thursdays. Mondays and Fridays have the least number of impressions and clicks. Day of week CTR df_click = train[train['click'] == 1]df_dayofweek = train[['day_of_week','click']].groupby(['day_of_week']).count().reset_index()df_dayofweek = df_dayofweek.rename(columns={'click': 'impressions'})df_dayofweek['clicks'] = df_click[['day_of_week','click']].groupby(['day_of_week']).count().reset_index()['click']df_dayofweek['CTR'] = df_dayofweek['clicks']/df_dayofweek['impressions']*100plt.figure(figsize=(12,6))sns.barplot(y='CTR', x='day_of_week', data=df_dayofweek, order=['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'])plt.title('Day of week CTR'); While Tuesdays and Wednesdays have the highest number of impressions and clicks, their CTR are among the lowest. Saturdays and Sundays enjoy the highest CTR. Apparently, people have more time to click over the weekend. C1 feature C1 is one of the anonymized categorical features. Although we don’t know its meaning, we still want to take a look its distribution. print(train.C1.value_counts()/len(train)) C1 value = 1005 has the most data, almost 92% of all the data we are using. Let’s see whether we can find value of C1 indicates something about CTR. C1_values = train.C1.unique()C1_values.sort()ctr_avg_list=[]for i in C1_values: ctr_avg=train.loc[np.where((train.C1 == i))].click.mean() ctr_avg_list.append(ctr_avg) print("for C1 value: {}, click through rate: {}".format(i,ctr_avg)) train.groupby(['C1', 'click']).size().unstack().plot(kind='bar', figsize=(12,6), title='C1 histogram'); df_c1 = train[['C1','click']].groupby(['C1']).count().reset_index()df_c1 = df_c1.rename(columns={'click': 'impressions'})df_c1['clicks'] = df_click[['C1','click']].groupby(['C1']).count().reset_index()['click']df_c1['CTR'] = df_c1['clicks']/df_c1['impressions']*100plt.figure(figsize=(12,6))sns.barplot(y='CTR', x='C1', data=df_c1)plt.title('CTR by C1'); The important C1 values and CTR pairs are: C1=1005: 92% of the data and 0.17 CTR C1=1002: 5.5% of the data and 0.21 CTR C1=1010: 2.2% of the data and 0.095 CTR C1 = 1002 has a much higher than average CTR, and C1=1010 has a much lower than average CTR, it seems these two C1 values are important for predicting CTR. Banner position I have heard that there are many factors that affect the performance of your banner ads, but the most influential one is the banner position. Let’s see whether it is true. print(train.banner_pos.value_counts()/len(train)) banner_pos = train.banner_pos.unique()banner_pos.sort()ctr_avg_list=[]for i in banner_pos: ctr_avg=train.loc[np.where((train.banner_pos == i))].click.mean() ctr_avg_list.append(ctr_avg) print("for banner position: {}, click through rate: {}".format(i,ctr_avg)) The important banner positions are: position 0: 72% of the data and 0.16 CTR position 1: 28% of the data and 0.18 CTR train.groupby(['banner_pos', 'click']).size().unstack().plot(kind='bar', figsize=(12,6), title='banner position histogram'); df_banner = train[['banner_pos','click']].groupby(['banner_pos']).count().reset_index()df_banner = df_banner.rename(columns={'click': 'impressions'})df_banner['clicks'] = df_click[['banner_pos','click']].groupby(['banner_pos']).count().reset_index()['click']df_banner['CTR'] = df_banner['clicks']/df_banner['impressions']*100sort_banners = df_banner.sort_values(by='CTR',ascending=False)['banner_pos'].tolist()plt.figure(figsize=(12,6))sns.barplot(y='CTR', x='banner_pos', data=df_banner, order=sort_banners)plt.title('CTR by banner position'); Although banner position 0 has the highest number of impressions and clicks, banner position 7 enjoys the highest CTR. Increasing the number of ads placed on banner position 7 seems to be a good idea. Device type print('The impressions by device types')print((train.device_type.value_counts()/len(train))) train[['device_type','click']].groupby(['device_type','click']).size().unstack().plot(kind='bar', title='device types'); Device type 1 gets the most impressions and clicks, and the other device types only get the minimum impressions and clicks. We may want to look in more details about device type 1. df_click[df_click['device_type']==1].groupby(['hour_of_day', 'click']).size().unstack().plot(kind='bar', title="Clicks from device type 1 by hour of day", figsize=(12,6)); As expected, most clicks happened during the business hours from device type 1. device_type_click = df_click.groupby('device_type').agg({'click':'sum'}).reset_index()device_type_impression = train.groupby('device_type').agg({'click':'count'}).reset_index().rename(columns={'click': 'impressions'})merged_device_type = pd.merge(left = device_type_click , right = device_type_impression, how = 'inner', on = 'device_type')merged_device_type['CTR'] = merged_device_type['click'] / merged_device_type['impressions']*100merged_device_type The highest CTR comes from device type 0. Using the same way, I explored all the other categorical features such as site features, app features and C14-C21 features. The way of exploring are similar, the details can be found on Github, I will not repeat here. A hash function is a function that maps a set of objects to a set of integers. When using a hash function, this mapping is performed which takes a key of arbitrary length as input and outputs an integer in a specific range. Our reduced dataset still contains 1M samples and ~2M feature values. The purposes of the hashing is to minimize memory consumption by the features. There is an excellent article on hashing tricks by Lucas Bernardi if you want to learn more. Python has a built in function that performs a hash called hash(). For the objects in our data, the hash is not surprising. def convert_obj_to_int(self): object_list_columns = self.columns object_list_dtypes = self.dtypes new_col_suffix = '_int' for index in range(0,len(object_list_columns)): if object_list_dtypes[index] == object : self[object_list_columns[index]+new_col_suffix] = self[object_list_columns[index]].map( lambda x: hash(x)) self.drop([object_list_columns[index]],inplace=True,axis=1) return selftrain = convert_obj_to_int(train) The final output after training: It will train until eval-logloss hasn’t improved in 20 rounds. And the final output: Jupyter notebook can be found on Github. Have a great weekend!
[ { "code": null, "e": 326, "s": 171, "text": "In Internet marketing, click-through rate (CTR) is a metric that measures the number of clicks advertisers receive on their ads per number of impressions." }, { "code": null, "e": 542, "s": 326, "text": "Mobile has become seamless with all channels, and mobile is the driving force with what’s driving all commerce. Mobile ads are expected to generate $1.08 billion this year, which would be a 122% jump from last year." }, { "code": null, "e": 917, "s": 542, "text": "In this research analysis, Criteo Labs is sharing 10 days’ worth of Avazu data for us to develop models predicting ad click-through rate (CTR). Given a user and the page he (or she) is visiting. what is the probability that he (or she) will click on a given ad? The goal of this analysis is to benchmark the most accurate ML algorithms for CTR estimation. Let’s get started!" }, { "code": null, "e": 949, "s": 917, "text": "The data set can be found here." }, { "code": null, "e": 967, "s": 949, "text": "id: ad identifier" }, { "code": null, "e": 998, "s": 967, "text": "click: 0/1 for non-click/click" }, { "code": null, "e": 1071, "s": 998, "text": "hour: format is YYMMDDHH, so 14091123 means 23:00 on Sept. 11, 2014 UTC." }, { "code": null, "e": 1108, "s": 1071, "text": "C1 — anonymized categorical variable" }, { "code": null, "e": 1119, "s": 1108, "text": "banner_pos" }, { "code": null, "e": 1127, "s": 1119, "text": "site_id" }, { "code": null, "e": 1139, "s": 1127, "text": "site_domain" }, { "code": null, "e": 1153, "s": 1139, "text": "site_category" }, { "code": null, "e": 1160, "s": 1153, "text": "app_id" }, { "code": null, "e": 1171, "s": 1160, "text": "app_domain" }, { "code": null, "e": 1184, "s": 1171, "text": "app_category" }, { "code": null, "e": 1194, "s": 1184, "text": "device_id" }, { "code": null, "e": 1204, "s": 1194, "text": "device_ip" }, { "code": null, "e": 1217, "s": 1204, "text": "device_model" }, { "code": null, "e": 1229, "s": 1217, "text": "device_type" }, { "code": null, "e": 1246, "s": 1229, "text": "device_conn_type" }, { "code": null, "e": 1289, "s": 1246, "text": "C14-C21 — anonymized categorical variables" }, { "code": null, "e": 1418, "s": 1289, "text": "The training set contains over 40 millions of records, to be able to process locally, we will randomly sample 1 million of them." }, { "code": null, "e": 1839, "s": 1418, "text": "import numpy as nimport randomimport pandas as pdimport gzipn = 40428967 #total number of records in the clickstream data sample_size = 1000000skip_values = sorted(random.sample(range(1,n), n-sample_size))parse_date = lambda val : pd.datetime.strptime(val, '%y%m%d%H')with gzip.open('train.gz') as f: train = pd.read_csv(f, parse_dates = ['hour'], date_parser = parse_date, dtype=types_train, skiprows = skip_values)" }, { "code": null, "e": 2106, "s": 1839, "text": "Because of the anonymization, we don’t know what each value means in each feature. In addition, most of the features are categorical and most of the categorical features have a lot of values. This makes EDA less intuitive easier to confuse, but we will try the best." }, { "code": null, "e": 2115, "s": 2106, "text": "Features" }, { "code": null, "e": 2188, "s": 2115, "text": "We can group all the features in the data into the following categories:" }, { "code": null, "e": 2211, "s": 2188, "text": "Target feature : click" }, { "code": null, "e": 2263, "s": 2211, "text": "site features : site_id, site_domain, site_category" }, { "code": null, "e": 2309, "s": 2263, "text": "app feature: app_id, app_domain, app_category" }, { "code": null, "e": 2391, "s": 2309, "text": "device feature: device_id, device_ip, device_model, device_type, device_conn_type" }, { "code": null, "e": 2432, "s": 2391, "text": "anonymized categorical features: C14-C21" }, { "code": null, "e": 2546, "s": 2432, "text": "import seaborn as snsimport matplotlib.pyplot as pltsns.countplot(x='click',data=train, palette='hls')plt.show();" }, { "code": null, "e": 2587, "s": 2546, "text": "train['click'].value_counts()/len(train)" }, { "code": null, "e": 2666, "s": 2587, "text": "The overall click through rate is approx. 17%, and approx. 83% is not clicked." }, { "code": null, "e": 2688, "s": 2666, "text": "train.hour.describe()" }, { "code": null, "e": 2784, "s": 2688, "text": "The data covers 10 days of click streams data from 2014–10–21 to 2014–10–30, that is 240 hours." }, { "code": null, "e": 2916, "s": 2784, "text": "train.groupby('hour').agg({'click':'sum'}).plot(figsize=(12,6))plt.ylabel('Number of clicks')plt.title('Number of clicks by hour');" }, { "code": null, "e": 3185, "s": 2916, "text": "The hourly clicks pattern looks pretty similar every day. However, there were a couple of peak hours, one is sometime in the mid of the day on Oct 22, and another is sometime in the mid of the day on Oct 28. And one very low click hour is close to mid-night on Oct 24." }, { "code": null, "e": 3190, "s": 3185, "text": "Hour" }, { "code": null, "e": 3227, "s": 3190, "text": "Extract hour from date time feature." }, { "code": null, "e": 3426, "s": 3227, "text": "train['hour_of_day'] = train.hour.apply(lambda x: x.hour)train.groupby('hour_of_day').agg({'click':'sum'}).plot(figsize=(12,6))plt.ylabel('Number of clicks')plt.title('click trends by hour of day');" }, { "code": null, "e": 3611, "s": 3426, "text": "In general, the highest number of clicks is at hour 13 and 14 (1pm and 2pm), and the lowest number of clicks is at hour 0 (mid-night). It seems a useful feature for roughly estimation." }, { "code": null, "e": 3654, "s": 3611, "text": "Let’s take impressions into consideration." }, { "code": null, "e": 3827, "s": 3654, "text": "train.groupby(['hour_of_day', 'click']).size().unstack().plot(kind='bar', title=\"Hour of Day\", figsize=(12,6))plt.ylabel('count')plt.title('Hourly impressions vs. clicks');" }, { "code": null, "e": 3859, "s": 3827, "text": "There is nothing shocking here." }, { "code": null, "e": 4042, "s": 3859, "text": "Now that we have looked at clicks and impressions. We can calculate click-through rate (CTR). CTR is the ratio of ad clicks to impressions. It measures the rate of clicks on each ad." }, { "code": null, "e": 4053, "s": 4042, "text": "Hourly CTR" }, { "code": null, "e": 4528, "s": 4053, "text": "import seaborn as snsdf_click = train[train['click'] == 1]df_hour = train[['hour_of_day','click']].groupby(['hour_of_day']).count().reset_index()df_hour = df_hour.rename(columns={'click': 'impressions'})df_hour['clicks'] = df_click[['hour_of_day','click']].groupby(['hour_of_day']).count().reset_index()['click']df_hour['CTR'] = df_hour['clicks']/df_hour['impressions']*100plt.figure(figsize=(12,6))sns.barplot(y='CTR', x='hour_of_day', data=df_hour)plt.title('Hourly CTR');" }, { "code": null, "e": 4723, "s": 4528, "text": "One of the interesting observations here is that the highest CTR happened in the hour of mid-night, 1, 7 and 15. If you remember, around mid-night has the least number of impressions and clicks." }, { "code": null, "e": 4735, "s": 4723, "text": "Day of week" }, { "code": null, "e": 5179, "s": 4735, "text": "train['day_of_week'] = train['hour'].apply(lambda val: val.weekday_name)cats = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']train.groupby('day_of_week').agg({'click':'sum'}).reindex(cats).plot(figsize=(12,6))ticks = list(range(0, 7, 1)) # points on the x axis where you want the label to appearlabels = \"Mon Tues Weds Thurs Fri Sat Sun\".split()plt.xticks(ticks, labels)plt.title('click trends by day of week');" }, { "code": null, "e": 5519, "s": 5179, "text": "train.groupby(['day_of_week','click']).size().unstack().reindex(cats).plot(kind='bar', title=\"Day of the Week\", figsize=(12,6))ticks = list(range(0, 7, 1)) # points on the x axis where you want the label to appearlabels = \"Mon Tues Weds Thurs Fri Sat Sun\".split()plt.xticks(ticks, labels)plt.title('Impressions vs. clicks by day of week');" }, { "code": null, "e": 5685, "s": 5519, "text": "Tuesdays have the most number of impressions and clicks, then Wednesdays, followed by Thursdays. Mondays and Fridays have the least number of impressions and clicks." }, { "code": null, "e": 5701, "s": 5685, "text": "Day of week CTR" }, { "code": null, "e": 6286, "s": 5701, "text": "df_click = train[train['click'] == 1]df_dayofweek = train[['day_of_week','click']].groupby(['day_of_week']).count().reset_index()df_dayofweek = df_dayofweek.rename(columns={'click': 'impressions'})df_dayofweek['clicks'] = df_click[['day_of_week','click']].groupby(['day_of_week']).count().reset_index()['click']df_dayofweek['CTR'] = df_dayofweek['clicks']/df_dayofweek['impressions']*100plt.figure(figsize=(12,6))sns.barplot(y='CTR', x='day_of_week', data=df_dayofweek, order=['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'])plt.title('Day of week CTR');" }, { "code": null, "e": 6505, "s": 6286, "text": "While Tuesdays and Wednesdays have the highest number of impressions and clicks, their CTR are among the lowest. Saturdays and Sundays enjoy the highest CTR. Apparently, people have more time to click over the weekend." }, { "code": null, "e": 6516, "s": 6505, "text": "C1 feature" }, { "code": null, "e": 6649, "s": 6516, "text": "C1 is one of the anonymized categorical features. Although we don’t know its meaning, we still want to take a look its distribution." }, { "code": null, "e": 6691, "s": 6649, "text": "print(train.C1.value_counts()/len(train))" }, { "code": null, "e": 6840, "s": 6691, "text": "C1 value = 1005 has the most data, almost 92% of all the data we are using. Let’s see whether we can find value of C1 indicates something about CTR." }, { "code": null, "e": 7085, "s": 6840, "text": "C1_values = train.C1.unique()C1_values.sort()ctr_avg_list=[]for i in C1_values: ctr_avg=train.loc[np.where((train.C1 == i))].click.mean() ctr_avg_list.append(ctr_avg) print(\"for C1 value: {}, click through rate: {}\".format(i,ctr_avg))" }, { "code": null, "e": 7189, "s": 7085, "text": "train.groupby(['C1', 'click']).size().unstack().plot(kind='bar', figsize=(12,6), title='C1 histogram');" }, { "code": null, "e": 7544, "s": 7189, "text": "df_c1 = train[['C1','click']].groupby(['C1']).count().reset_index()df_c1 = df_c1.rename(columns={'click': 'impressions'})df_c1['clicks'] = df_click[['C1','click']].groupby(['C1']).count().reset_index()['click']df_c1['CTR'] = df_c1['clicks']/df_c1['impressions']*100plt.figure(figsize=(12,6))sns.barplot(y='CTR', x='C1', data=df_c1)plt.title('CTR by C1');" }, { "code": null, "e": 7587, "s": 7544, "text": "The important C1 values and CTR pairs are:" }, { "code": null, "e": 7625, "s": 7587, "text": "C1=1005: 92% of the data and 0.17 CTR" }, { "code": null, "e": 7664, "s": 7625, "text": "C1=1002: 5.5% of the data and 0.21 CTR" }, { "code": null, "e": 7704, "s": 7664, "text": "C1=1010: 2.2% of the data and 0.095 CTR" }, { "code": null, "e": 7860, "s": 7704, "text": "C1 = 1002 has a much higher than average CTR, and C1=1010 has a much lower than average CTR, it seems these two C1 values are important for predicting CTR." }, { "code": null, "e": 7876, "s": 7860, "text": "Banner position" }, { "code": null, "e": 8048, "s": 7876, "text": "I have heard that there are many factors that affect the performance of your banner ads, but the most influential one is the banner position. Let’s see whether it is true." }, { "code": null, "e": 8098, "s": 8048, "text": "print(train.banner_pos.value_counts()/len(train))" }, { "code": null, "e": 8369, "s": 8098, "text": "banner_pos = train.banner_pos.unique()banner_pos.sort()ctr_avg_list=[]for i in banner_pos: ctr_avg=train.loc[np.where((train.banner_pos == i))].click.mean() ctr_avg_list.append(ctr_avg) print(\"for banner position: {}, click through rate: {}\".format(i,ctr_avg))" }, { "code": null, "e": 8405, "s": 8369, "text": "The important banner positions are:" }, { "code": null, "e": 8446, "s": 8405, "text": "position 0: 72% of the data and 0.16 CTR" }, { "code": null, "e": 8487, "s": 8446, "text": "position 1: 28% of the data and 0.18 CTR" }, { "code": null, "e": 8612, "s": 8487, "text": "train.groupby(['banner_pos', 'click']).size().unstack().plot(kind='bar', figsize=(12,6), title='banner position histogram');" }, { "code": null, "e": 9157, "s": 8612, "text": "df_banner = train[['banner_pos','click']].groupby(['banner_pos']).count().reset_index()df_banner = df_banner.rename(columns={'click': 'impressions'})df_banner['clicks'] = df_click[['banner_pos','click']].groupby(['banner_pos']).count().reset_index()['click']df_banner['CTR'] = df_banner['clicks']/df_banner['impressions']*100sort_banners = df_banner.sort_values(by='CTR',ascending=False)['banner_pos'].tolist()plt.figure(figsize=(12,6))sns.barplot(y='CTR', x='banner_pos', data=df_banner, order=sort_banners)plt.title('CTR by banner position');" }, { "code": null, "e": 9358, "s": 9157, "text": "Although banner position 0 has the highest number of impressions and clicks, banner position 7 enjoys the highest CTR. Increasing the number of ads placed on banner position 7 seems to be a good idea." }, { "code": null, "e": 9370, "s": 9358, "text": "Device type" }, { "code": null, "e": 9463, "s": 9370, "text": "print('The impressions by device types')print((train.device_type.value_counts()/len(train)))" }, { "code": null, "e": 9584, "s": 9463, "text": "train[['device_type','click']].groupby(['device_type','click']).size().unstack().plot(kind='bar', title='device types');" }, { "code": null, "e": 9765, "s": 9584, "text": "Device type 1 gets the most impressions and clicks, and the other device types only get the minimum impressions and clicks. We may want to look in more details about device type 1." }, { "code": null, "e": 9937, "s": 9765, "text": "df_click[df_click['device_type']==1].groupby(['hour_of_day', 'click']).size().unstack().plot(kind='bar', title=\"Clicks from device type 1 by hour of day\", figsize=(12,6));" }, { "code": null, "e": 10017, "s": 9937, "text": "As expected, most clicks happened during the business hours from device type 1." }, { "code": null, "e": 10471, "s": 10017, "text": "device_type_click = df_click.groupby('device_type').agg({'click':'sum'}).reset_index()device_type_impression = train.groupby('device_type').agg({'click':'count'}).reset_index().rename(columns={'click': 'impressions'})merged_device_type = pd.merge(left = device_type_click , right = device_type_impression, how = 'inner', on = 'device_type')merged_device_type['CTR'] = merged_device_type['click'] / merged_device_type['impressions']*100merged_device_type" }, { "code": null, "e": 10513, "s": 10471, "text": "The highest CTR comes from device type 0." }, { "code": null, "e": 10731, "s": 10513, "text": "Using the same way, I explored all the other categorical features such as site features, app features and C14-C21 features. The way of exploring are similar, the details can be found on Github, I will not repeat here." }, { "code": null, "e": 10955, "s": 10731, "text": "A hash function is a function that maps a set of objects to a set of integers. When using a hash function, this mapping is performed which takes a key of arbitrary length as input and outputs an integer in a specific range." }, { "code": null, "e": 11104, "s": 10955, "text": "Our reduced dataset still contains 1M samples and ~2M feature values. The purposes of the hashing is to minimize memory consumption by the features." }, { "code": null, "e": 11197, "s": 11104, "text": "There is an excellent article on hashing tricks by Lucas Bernardi if you want to learn more." }, { "code": null, "e": 11321, "s": 11197, "text": "Python has a built in function that performs a hash called hash(). For the objects in our data, the hash is not surprising." }, { "code": null, "e": 11793, "s": 11321, "text": "def convert_obj_to_int(self): object_list_columns = self.columns object_list_dtypes = self.dtypes new_col_suffix = '_int' for index in range(0,len(object_list_columns)): if object_list_dtypes[index] == object : self[object_list_columns[index]+new_col_suffix] = self[object_list_columns[index]].map( lambda x: hash(x)) self.drop([object_list_columns[index]],inplace=True,axis=1) return selftrain = convert_obj_to_int(train)" }, { "code": null, "e": 11826, "s": 11793, "text": "The final output after training:" }, { "code": null, "e": 11911, "s": 11826, "text": "It will train until eval-logloss hasn’t improved in 20 rounds. And the final output:" } ]
Extract, Transform, Load (ETL) — AWS Glue | by Furqan Butt | Towards Data Science
AWS Glue is a fully managed, server-less ETL service which can be used to prepare and load data for data analytics purposes. The service can be used to catalog data, clean it, enrich it, and move it reliably between different data stores. In this article I will be explaining how we can use AWS Glue to perform ETL operations in Spark on the Novel Corona Virus Dataset. The article will cover the following topics: Glue Components. Complete tutorial to author a Glue Spark Job. Extracting data from AWS S3. Transforming Data using Spark. Storing Transformed data back to S3 in parquet format. In a nutshell, AWS Glue has following important components: Data Source and Data Target: the data store that is provided as input, from where data is loaded for ETL is called the data source and the data store where the transformed data is stored is the data target. Data Catalog: Data Catalog is AWS Glue’s central metadata repository that is shared across all the services in a region. This catalog has table definitions, job definitions, and other control information to manage your AWS Glue environment. Crawlers and Classifiers: A crawler is a program that retrieves the schema of data from the data store(s3). Crawler uses custom or built-in classifiers to identify data formats and populates the metadata tables in the catalog. Database and Table: Each successful crawler run populates a table of a database in the data catalog. A database in the catalog is a set of associated tables. Each table only has metadata information of the data such as names of columns, data type definitions, partition information and the actual data remains in the data store. One or more tables in the database are used by the source and target in an ETL job run. Job and Triggers: It is the actual business logic to carry out the ETL task. A job is composed of a transformation script, data sources and data targets. We can define our Jobs either in python or pyspark. Job runs are initiated by triggers that can be scheduled or triggered by events. I have left a few components as they are not under the scope of this article. For a detailed study of AWS Glue you can visit the official developer guide. Now that we have an understanding of what are the different components of Glue we can now jump into how to author Glue Jobs in AWS and perform the actual extract, transform and load (ETL) operations. The dataset is obtained from Kaggle Datasets. The version I’m using was last updated on May 02, 2020. Main file in this dataset is covid_19_data.csv The detailed descriptions of the dataset are below. Sno — Serial number ObservationDate — Date of the observation in MM/DD/YYYY Province/State — Province or state of the observation (Could be empty when missing) Country/Region — Country of observation Last Update — Time in UTC at which the row is updated for the given province or country. (Not standardized and so please clean before using it) Confirmed — Cumulative number of confirmed cases till that date Deaths — Cumulative number of of deaths till that date Recovered — Cumulative number of recovered cases till that date As a first step of developing our end to end ETL job we will first setup our data stores. Goto yout s3 console and create a bucket there. We’ll upload the dataset file in the bucket with the following partition scheme: s3://bucket-name/dataset/year=<year>/month=<month>/day=<day>/hour=<hour>/ Right now we are dealing with a single file so you can create partitions and upload file manually but if working with a large number of files you can use my FTP file ingestion code that I explained in my last article to do this work for you. Partitioning data in this way helps in query optimization while working with AWS Athena. Create a Glue role that will allow Glue to access different AWS resources e.g s3. Goto the IAM console and add a new role and attach the AWSGlueServiceRole policy to this role. This policy contains permissions to access Glue, CloudWatch, EC2, S3, and IAM. For more details about how to setup IAM role for Glue consider the following link. Perform the following steps to add a crawler: On the left menu click on databases and add a database. Now goto crawlers and and a new crawler Select data store Provide the s3 bucket path Select the Glue role Set frequency to Run on Demand Select the database Finally review and click finish Now your crawler is created. Click on “Run Crawler” to catalog the dataset Crawler can take sometime to catalog the data. After successful run you must have tables created in your specified database Now that we have cataloged our dataset we can now move towards adding a Glue Job that will do the ETL work on our dataset. On the left menu click on “Jobs” and add a new job. Glue can auto generate a python or pyspark script that we can use to perform ETL operations. However, in our case we’ll be providing a new script. Set the job properties as follows Leave the following as default Set the maximum capacity to 2 and Job Timeout to 40 mins. The higher the number of DPUs(maximum capacity) you set the more cost you will incur. Since we are not connecting to any RDBMS we don’t have to setup any connections. Click “Save Job and edit script”. We will have the following screen. Copy and Paste the code from my GitHub repository in the editor below and hit save. Now click the run job button. Depending upon the work, the Job can take sometime to execute (between 15 to 30 mins in this case). As of now, Glue Jobs have a cold start time of at least 10 mins after which the job execution starts. If the job execution is successful, you will have aggregated results in parquet format in your destination bucket that is specified in the Glue Job. If you followed all the above mentioned steps then you should have a successful ETL job execution via AWS Glue. In this section, I will dive into the Spark Code that is doing the actual ETL operations. At the very top we have the necessary Glue and Spark imports. After the imports we have a few parameters setup. This includes getting job name, setting up spark and glue contexts, initializing job and defining the catalog database and table names and s3 output path. The “extract” part of an ETL operation does nothing but connecting to some data store and getting the data from there. The extract portion of the code does following: creates a Glue DynamicFrame using from the glue catalog. The catalog database and table name are already provided. After creation of DynamicFrame we covert it to Spark dataframe using the toDF() method. Converting to spark dataframe will allow us to use all the spark transformations and actions. In the “transform” part of an ETL operation we apply different transformations on our data. The transform part of the code does the following: First we drop the “last update” column(for no particular reason) using the drop() method in spark. Then drop any row having more then 4 null fields using the dropna() method in spark. Then we populate the missing values in “province/state” column with a custom value of “na_province_state” using the fillna() method in spark. Next we perform aggregations on our dataset. 3 different aggregations have been performed. We check which province/state of a country/region had the most cases, most deaths and most recoveries. This was done by grouping the records by Province/State and Country/Region column using the groupBy() method, aggregating with max(Confirmed),max(Deaths) and max(Recovered) columns using the max() method then sorting them in descending order using the orderBy() method. Finally we convert our dataframe back to Glue DynamicFrame using the fromDF() method to save the results in S3. It takes three parameters the dataframe, glue context and the name of the resulting DynamicFrame. In the load part of and ETL operation we store the transformed data to some persistent store such as s3. The load part of code does the following: We save the results to s3 using the from_options() method of DynamicFrame(). This method takes following parameters: frame: the DynamicFrame we want to write. connection_type: the target data store we are writing to in this case s3. connection_options: here we specify the target s3 path and data the format(parquet in this case) to save the data. transformation_ctx: optional transformation context. All the 3 aggregated results are saved on the destination paths in parquet format. In this article we learned how we can use AWS Glue to do ETL operations in Spark. We learned how we can setup data source and data target, creating crawlers to catalog the data on s3 and authoring Glue Spark Job to perform extract, transform and load(ETL) operations. The complete spark code can be found on my GitHub repository: github.com Thank you for reading ❤.
[ { "code": null, "e": 542, "s": 172, "text": "AWS Glue is a fully managed, server-less ETL service which can be used to prepare and load data for data analytics purposes. The service can be used to catalog data, clean it, enrich it, and move it reliably between different data stores. In this article I will be explaining how we can use AWS Glue to perform ETL operations in Spark on the Novel Corona Virus Dataset." }, { "code": null, "e": 587, "s": 542, "text": "The article will cover the following topics:" }, { "code": null, "e": 604, "s": 587, "text": "Glue Components." }, { "code": null, "e": 650, "s": 604, "text": "Complete tutorial to author a Glue Spark Job." }, { "code": null, "e": 679, "s": 650, "text": "Extracting data from AWS S3." }, { "code": null, "e": 710, "s": 679, "text": "Transforming Data using Spark." }, { "code": null, "e": 765, "s": 710, "text": "Storing Transformed data back to S3 in parquet format." }, { "code": null, "e": 825, "s": 765, "text": "In a nutshell, AWS Glue has following important components:" }, { "code": null, "e": 1032, "s": 825, "text": "Data Source and Data Target: the data store that is provided as input, from where data is loaded for ETL is called the data source and the data store where the transformed data is stored is the data target." }, { "code": null, "e": 1273, "s": 1032, "text": "Data Catalog: Data Catalog is AWS Glue’s central metadata repository that is shared across all the services in a region. This catalog has table definitions, job definitions, and other control information to manage your AWS Glue environment." }, { "code": null, "e": 1500, "s": 1273, "text": "Crawlers and Classifiers: A crawler is a program that retrieves the schema of data from the data store(s3). Crawler uses custom or built-in classifiers to identify data formats and populates the metadata tables in the catalog." }, { "code": null, "e": 1917, "s": 1500, "text": "Database and Table: Each successful crawler run populates a table of a database in the data catalog. A database in the catalog is a set of associated tables. Each table only has metadata information of the data such as names of columns, data type definitions, partition information and the actual data remains in the data store. One or more tables in the database are used by the source and target in an ETL job run." }, { "code": null, "e": 2204, "s": 1917, "text": "Job and Triggers: It is the actual business logic to carry out the ETL task. A job is composed of a transformation script, data sources and data targets. We can define our Jobs either in python or pyspark. Job runs are initiated by triggers that can be scheduled or triggered by events." }, { "code": null, "e": 2359, "s": 2204, "text": "I have left a few components as they are not under the scope of this article. For a detailed study of AWS Glue you can visit the official developer guide." }, { "code": null, "e": 2559, "s": 2359, "text": "Now that we have an understanding of what are the different components of Glue we can now jump into how to author Glue Jobs in AWS and perform the actual extract, transform and load (ETL) operations." }, { "code": null, "e": 2760, "s": 2559, "text": "The dataset is obtained from Kaggle Datasets. The version I’m using was last updated on May 02, 2020. Main file in this dataset is covid_19_data.csv The detailed descriptions of the dataset are below." }, { "code": null, "e": 2780, "s": 2760, "text": "Sno — Serial number" }, { "code": null, "e": 2836, "s": 2780, "text": "ObservationDate — Date of the observation in MM/DD/YYYY" }, { "code": null, "e": 2920, "s": 2836, "text": "Province/State — Province or state of the observation (Could be empty when missing)" }, { "code": null, "e": 2960, "s": 2920, "text": "Country/Region — Country of observation" }, { "code": null, "e": 3104, "s": 2960, "text": "Last Update — Time in UTC at which the row is updated for the given province or country. (Not standardized and so please clean before using it)" }, { "code": null, "e": 3168, "s": 3104, "text": "Confirmed — Cumulative number of confirmed cases till that date" }, { "code": null, "e": 3223, "s": 3168, "text": "Deaths — Cumulative number of of deaths till that date" }, { "code": null, "e": 3287, "s": 3223, "text": "Recovered — Cumulative number of recovered cases till that date" }, { "code": null, "e": 3506, "s": 3287, "text": "As a first step of developing our end to end ETL job we will first setup our data stores. Goto yout s3 console and create a bucket there. We’ll upload the dataset file in the bucket with the following partition scheme:" }, { "code": null, "e": 3580, "s": 3506, "text": "s3://bucket-name/dataset/year=<year>/month=<month>/day=<day>/hour=<hour>/" }, { "code": null, "e": 3911, "s": 3580, "text": "Right now we are dealing with a single file so you can create partitions and upload file manually but if working with a large number of files you can use my FTP file ingestion code that I explained in my last article to do this work for you. Partitioning data in this way helps in query optimization while working with AWS Athena." }, { "code": null, "e": 4250, "s": 3911, "text": "Create a Glue role that will allow Glue to access different AWS resources e.g s3. Goto the IAM console and add a new role and attach the AWSGlueServiceRole policy to this role. This policy contains permissions to access Glue, CloudWatch, EC2, S3, and IAM. For more details about how to setup IAM role for Glue consider the following link." }, { "code": null, "e": 4296, "s": 4250, "text": "Perform the following steps to add a crawler:" }, { "code": null, "e": 4352, "s": 4296, "text": "On the left menu click on databases and add a database." }, { "code": null, "e": 4392, "s": 4352, "text": "Now goto crawlers and and a new crawler" }, { "code": null, "e": 4410, "s": 4392, "text": "Select data store" }, { "code": null, "e": 4437, "s": 4410, "text": "Provide the s3 bucket path" }, { "code": null, "e": 4458, "s": 4437, "text": "Select the Glue role" }, { "code": null, "e": 4489, "s": 4458, "text": "Set frequency to Run on Demand" }, { "code": null, "e": 4509, "s": 4489, "text": "Select the database" }, { "code": null, "e": 4541, "s": 4509, "text": "Finally review and click finish" }, { "code": null, "e": 4616, "s": 4541, "text": "Now your crawler is created. Click on “Run Crawler” to catalog the dataset" }, { "code": null, "e": 4740, "s": 4616, "text": "Crawler can take sometime to catalog the data. After successful run you must have tables created in your specified database" }, { "code": null, "e": 4863, "s": 4740, "text": "Now that we have cataloged our dataset we can now move towards adding a Glue Job that will do the ETL work on our dataset." }, { "code": null, "e": 5062, "s": 4863, "text": "On the left menu click on “Jobs” and add a new job. Glue can auto generate a python or pyspark script that we can use to perform ETL operations. However, in our case we’ll be providing a new script." }, { "code": null, "e": 5096, "s": 5062, "text": "Set the job properties as follows" }, { "code": null, "e": 5127, "s": 5096, "text": "Leave the following as default" }, { "code": null, "e": 5271, "s": 5127, "text": "Set the maximum capacity to 2 and Job Timeout to 40 mins. The higher the number of DPUs(maximum capacity) you set the more cost you will incur." }, { "code": null, "e": 5386, "s": 5271, "text": "Since we are not connecting to any RDBMS we don’t have to setup any connections. Click “Save Job and edit script”." }, { "code": null, "e": 5535, "s": 5386, "text": "We will have the following screen. Copy and Paste the code from my GitHub repository in the editor below and hit save. Now click the run job button." }, { "code": null, "e": 5737, "s": 5535, "text": "Depending upon the work, the Job can take sometime to execute (between 15 to 30 mins in this case). As of now, Glue Jobs have a cold start time of at least 10 mins after which the job execution starts." }, { "code": null, "e": 5886, "s": 5737, "text": "If the job execution is successful, you will have aggregated results in parquet format in your destination bucket that is specified in the Glue Job." }, { "code": null, "e": 6088, "s": 5886, "text": "If you followed all the above mentioned steps then you should have a successful ETL job execution via AWS Glue. In this section, I will dive into the Spark Code that is doing the actual ETL operations." }, { "code": null, "e": 6150, "s": 6088, "text": "At the very top we have the necessary Glue and Spark imports." }, { "code": null, "e": 6355, "s": 6150, "text": "After the imports we have a few parameters setup. This includes getting job name, setting up spark and glue contexts, initializing job and defining the catalog database and table names and s3 output path." }, { "code": null, "e": 6522, "s": 6355, "text": "The “extract” part of an ETL operation does nothing but connecting to some data store and getting the data from there. The extract portion of the code does following:" }, { "code": null, "e": 6637, "s": 6522, "text": "creates a Glue DynamicFrame using from the glue catalog. The catalog database and table name are already provided." }, { "code": null, "e": 6819, "s": 6637, "text": "After creation of DynamicFrame we covert it to Spark dataframe using the toDF() method. Converting to spark dataframe will allow us to use all the spark transformations and actions." }, { "code": null, "e": 6962, "s": 6819, "text": "In the “transform” part of an ETL operation we apply different transformations on our data. The transform part of the code does the following:" }, { "code": null, "e": 7061, "s": 6962, "text": "First we drop the “last update” column(for no particular reason) using the drop() method in spark." }, { "code": null, "e": 7146, "s": 7061, "text": "Then drop any row having more then 4 null fields using the dropna() method in spark." }, { "code": null, "e": 7288, "s": 7146, "text": "Then we populate the missing values in “province/state” column with a custom value of “na_province_state” using the fillna() method in spark." }, { "code": null, "e": 7752, "s": 7288, "text": "Next we perform aggregations on our dataset. 3 different aggregations have been performed. We check which province/state of a country/region had the most cases, most deaths and most recoveries. This was done by grouping the records by Province/State and Country/Region column using the groupBy() method, aggregating with max(Confirmed),max(Deaths) and max(Recovered) columns using the max() method then sorting them in descending order using the orderBy() method." }, { "code": null, "e": 7962, "s": 7752, "text": "Finally we convert our dataframe back to Glue DynamicFrame using the fromDF() method to save the results in S3. It takes three parameters the dataframe, glue context and the name of the resulting DynamicFrame." }, { "code": null, "e": 8109, "s": 7962, "text": "In the load part of and ETL operation we store the transformed data to some persistent store such as s3. The load part of code does the following:" }, { "code": null, "e": 8226, "s": 8109, "text": "We save the results to s3 using the from_options() method of DynamicFrame(). This method takes following parameters:" }, { "code": null, "e": 8268, "s": 8226, "text": "frame: the DynamicFrame we want to write." }, { "code": null, "e": 8342, "s": 8268, "text": "connection_type: the target data store we are writing to in this case s3." }, { "code": null, "e": 8457, "s": 8342, "text": "connection_options: here we specify the target s3 path and data the format(parquet in this case) to save the data." }, { "code": null, "e": 8510, "s": 8457, "text": "transformation_ctx: optional transformation context." }, { "code": null, "e": 8593, "s": 8510, "text": "All the 3 aggregated results are saved on the destination paths in parquet format." }, { "code": null, "e": 8861, "s": 8593, "text": "In this article we learned how we can use AWS Glue to do ETL operations in Spark. We learned how we can setup data source and data target, creating crawlers to catalog the data on s3 and authoring Glue Spark Job to perform extract, transform and load(ETL) operations." }, { "code": null, "e": 8923, "s": 8861, "text": "The complete spark code can be found on my GitHub repository:" }, { "code": null, "e": 8934, "s": 8923, "text": "github.com" } ]
\geq - Tex Command
\geq - Used to draw geq symbol. { \geq } \geq command draws geq symbol. \geq ≥ \geq ≥ \geq 14 Lectures 52 mins Ashraf Said 11 Lectures 1 hours Ashraf Said 9 Lectures 1 hours Emenwa Global, Ejike IfeanyiChukwu 29 Lectures 2.5 hours Mohammad Nauman 14 Lectures 1 hours Daniel Stern 15 Lectures 47 mins Nishant Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 8018, "s": 7986, "text": "\\geq - Used to draw geq symbol." }, { "code": null, "e": 8027, "s": 8018, "text": "{ \\geq }" }, { "code": null, "e": 8058, "s": 8027, "text": "\\geq command draws geq symbol." }, { "code": null, "e": 8070, "s": 8058, "text": "\n\\geq\n\n≥\n\n\n" }, { "code": null, "e": 8080, "s": 8070, "text": "\\geq\n\n≥\n\n" }, { "code": null, "e": 8085, "s": 8080, "text": "\\geq" }, { "code": null, "e": 8117, "s": 8085, "text": "\n 14 Lectures \n 52 mins\n" }, { "code": null, "e": 8130, "s": 8117, "text": " Ashraf Said" }, { "code": null, "e": 8163, "s": 8130, "text": "\n 11 Lectures \n 1 hours \n" }, { "code": null, "e": 8176, "s": 8163, "text": " Ashraf Said" }, { "code": null, "e": 8208, "s": 8176, "text": "\n 9 Lectures \n 1 hours \n" }, { "code": null, "e": 8244, "s": 8208, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 8279, "s": 8244, "text": "\n 29 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8296, "s": 8279, "text": " Mohammad Nauman" }, { "code": null, "e": 8329, "s": 8296, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 8343, "s": 8329, "text": " Daniel Stern" }, { "code": null, "e": 8375, "s": 8343, "text": "\n 15 Lectures \n 47 mins\n" }, { "code": null, "e": 8390, "s": 8375, "text": " Nishant Kumar" }, { "code": null, "e": 8397, "s": 8390, "text": " Print" }, { "code": null, "e": 8408, "s": 8397, "text": " Add Notes" } ]
Gaming: A goldmine for datasets | Towards Data Science
This post tells the story of how I got sidetracked from a project and built a thing or a program, which is unsupervised (and I guess supervised at the same time). Using GTA V mods, I created a dataset for computer vision tasks consisting of objects seen in the game. I will also show how well a small object detector trained on objects from GTA V works in the real world. TLDR, Object detectors trained on game images, generalize really well on real-world images. The article is divided into the following sections: Introduction to Machine learningAre datasets important for Machine learning?Can games and gamers help make better datasets?Training an object detectorDemo, showing the results on object detection Introduction to Machine learning Are datasets important for Machine learning? Can games and gamers help make better datasets? Training an object detector Demo, showing the results on object detection I should stress that this is not a tutorial for modding GTAV, I will not be able to explain and provide the code (maybe later, someday when I get more time) for using the GTAV APIs get the game world information. A small demo where you can play with the object detector on a single class can be found here. This guide can help you get started with modding in Grand Theft Auto V. And this tool can act as the starting point if you wanna dig deeper into extracting information from the game world. If you have prior knowledge of machine learning then you may skip this section. Since this article is not about learning machine learning, but about an application so I cannot go in-depth about the concepts of machine learning here. The following are some great articles to help you understand this field of computer science: Machine learning is funWhy Machine learning matters Machine learning is fun Why Machine learning matters If I were to ELI5(explain like I am five) Machine Learning is a form of Artificial Intelligence in which the program or algorithm is designed to learn on its own. Like in humans, small logic units called neurons (the circles in the diagram below) help algorithms to learn from experiences (or talking in terms of computers, data). The parameters in the algorithm change and learn the patterns in the dataset. Data is the basic necessity for any form of learning. We humans learn the ability to perceive or understand actions after experiencing them or reading/hearing about their experiences. Datasets, labeled or not labeled, act as the base of all the machine learning tasks. To train the machine learning models, a lot of data is required. The saying: “more the merrier” has never been more true. The current state-of-the-art (SOTA) machine learning models require a gigantic amount of data, for example, BERT, SOTA for many NLP tasks, are trained on 10s of GBs of data. Imagenet a standard image classification dataset is around 144 gigs of data compressed and >300 gigs uncompressed. Needless to say, that labeled data is very important for the advancement of artificial intelligence. While working on a project, I came across a problem where the object detector that I was using did not recognize all the objects in the image frame. I was trying to index all the objects present in the images frame, which later would make searching of images easier. But all the images are labeled human, not being able to detect the other objects in the image frames, the search was not working as I wanted. The ideal solution for this problem would be to gather data for those objects and re-train the object detector to also identify the new objects. This would not only be boring but time-consuming. I could use GANs, a type of machine learning algorithm famous for its use of creating artificial and similar examples to its inputs, to create more samples after organizing a few samples manually, but this is also boring and will require resources to train the GANs to generate more data. Now the only thing I could do was using internet services, like ScaleAI and Google Cloud Platform, to create a dataset. But these services charge ~$0.05 for each image annotated. Creating a dataset of 100 images for 15 categories each would mean that I will have to spend $120 just for the dataset. Spending this amount of $$$ just for a simple project is not a viable option. Out of all options, I started wishing if there was an artificial world, where all the objects already have the respective labels assigned to them. Then I won’t have to spend time searching for samples and then meticulously generating annotations for them. Then I realized that game worlds are the best example of such an artificial or virtual world. When the world is created the game engine has all the necessary information, it knows which textures are located where and it knows the location of all the other objects. Looking at the current state of gaming, where the developers are pushing the limits and creating game environments that are hardly distinguishable from the real world. Unreal Engine 5 demo on PS5 shows the graphical fidelity coming generation of consoles will boast. Having a virtual world, which closely resembles the real world, should act as a great simulation for testing and learning for algorithms. It would be great to allow algorithms to get access to the game world’s information and let it learn the nooks and crannies. The first game that came to my mind was Uncharted 4: The Thieves End. A stunning game with a good story, it has all the elements that we would like from testing environment. It has all the natural terrain types: Plains, Plateaus, Caves, Shores, it also sports great graphics which are nearly photo-realistic which would mean object detector would be learning features and shapes closer to that in the real world. But the problem is that I do not have my ps4 here at the university and nor is there a way to access Uncharted 4 assets in the way I’d like. The other choice for a game which could fulfill my demands of: PhotorealismModding interface to allow accessing of the game world data Photorealism Modding interface to allow accessing of the game world data was Grand Theft Auto: V. The base, though now 7 years old, resembles the real world more than most other games. This game has extensive support for mods and making changes/interacting with the game world. The game, after using some mods, can look extremely stunning with all of its lighting and reflections GTA V community has made some outrageous mods wherein the default player models are replaced by custom models. This is a really really awesome thing, which I will continue upon later. I started by reading some articles and guides to using the APIs of Rage Engine the engine used by GTA. There are very few good examples or guides to help me with what I was trying to achieve. But luckily, there was an amazing tool that does something close to what I was trying to achieve, it gives the locations of many objects in the current image frame of the user. The greatest thing about this tool is that its source code is available on Github. After getting this solid starting point, the task had come down to figuring out how to access the object information from the game world like it’s location and type. This was achieved after hours and hours of reading code, compiling erroneous code. I was able to log the results from the game screen. I started with simple logging: # the first log file that was created script running inside of GTA V[{ "label": "car", "location": [ [248.42533936651586, 173.41176470588235], [442.5429864253394, 278.841628959276] ], "group_id": "non-living"},{ "label": "trevor", ..... "group_id": living"},{ "label": "cat", ..... "group_id": living"}] Some things were easy, like getting the location of named objects like characters that were individually identified using hashes. Progressively I learned to interact with the API to get the location of pedestrians and things like cars running close by. I was not able to fully hack the game world to get location information for all the objects that I wanted but this was a good starting point. Initial results looked promising, the scripts took screenshots of the game when an object was detected and saved the location of the same. Results looked something like: With these satisfactory results, I went ahead with creating more samples. I decided to use 14 objects: Human-like: pedestrians or humans, dogs and cats (3)Living things but not human-like: trees (4)Non-living things: cars, trucks, bikes, trains, boats, traffic signals, billboard (6) Human-like: pedestrians or humans, dogs and cats (3) Living things but not human-like: trees (4) Non-living things: cars, trucks, bikes, trains, boats, traffic signals, billboard (6) After acquiring enough data to train a model. I started training a RetinaNet model on my university server, a moderately powerful machine with Quadro P5000 and an Intel Xeon G6132. There was no specific reason for choosing RetinaNet, I had prior experience of using it. I trained the network from scratch, as using the pre-trained weights would kill the idea of this project which was to use game world knowledge and apply that to the real world. After hours and hours of waiting, I realized that looking at the slow training progress would not speed up it up and decided to call it a day and sleep. After waiting for an eternity, the training was completed and it was showtime. Testing the model on a test-set comprising of images from the game. The results seemed fair: The results were as expected and now was the time for testing the performance on real-world objects. I think this experiment can be concluded as a sort of success by looking at the outcomes: Most objects are identified well, but I noticed a blunder: The reason for this, which I assume, is that the lack of different player models in the game for cats and dogs. The model is able to learn the shapes of different objects in the dataset, but since the variety of samples in cats and dogs was limited things do not go well for these classes. It is not able to learn features allowing it to differentiate between dogs and cats. The number of models for dogs and cats is limited, modding, and adding new models for these can be a remedy for this situation. The model performed well on the images, but don’t take my word for it. I have created a colab notebook where you can train your own model in just 5 minutes to recognize humans from an image. To keep the runtime as low as possible, the notebook only has a small dataset of 200 samples of human objects from the game. This low number of samples is sufficient to show the potential of such a model. After getting the object detection up and running I wanted to get semantic segmentation working as this is where the real potential of automatic labeling would shine. Exploiting the game engine’s knowledge of the textures to obtain pixel-level segmentation. I have not yet figured out how to obtain the texture-based information from the RAGE engine, the game engine used by GTA V. Getting the location of objects is one thing, and getting the location and area coverage of the object is another. The latter is where I am currently stuck. I believe the potential of this is huge, with the use of mods we can easily replace player models with those of things that we want to build detectors for. This technique, wherein we can replace the character models of a simple ragdoll which can act as the base for creating a large database of the character’s appearances in varied environments. With my GSoC selection, my time has been reduced and the dev environment changed. I would love to come back to this project in the future. I was planning on uploading the 31GB dataset of all the images and their labels but this is not possible currently as my University's internet service is unbearably slow. My next blog here would be either a dev-log for another project that I am working on or a starter blog for the GSoC blogs that I will be posting during the coming 3 months to show the progress of my work with CERN. No rights reserved by the author.
[ { "code": null, "e": 544, "s": 172, "text": "This post tells the story of how I got sidetracked from a project and built a thing or a program, which is unsupervised (and I guess supervised at the same time). Using GTA V mods, I created a dataset for computer vision tasks consisting of objects seen in the game. I will also show how well a small object detector trained on objects from GTA V works in the real world." }, { "code": null, "e": 636, "s": 544, "text": "TLDR, Object detectors trained on game images, generalize really well on real-world images." }, { "code": null, "e": 688, "s": 636, "text": "The article is divided into the following sections:" }, { "code": null, "e": 884, "s": 688, "text": "Introduction to Machine learningAre datasets important for Machine learning?Can games and gamers help make better datasets?Training an object detectorDemo, showing the results on object detection" }, { "code": null, "e": 917, "s": 884, "text": "Introduction to Machine learning" }, { "code": null, "e": 962, "s": 917, "text": "Are datasets important for Machine learning?" }, { "code": null, "e": 1010, "s": 962, "text": "Can games and gamers help make better datasets?" }, { "code": null, "e": 1038, "s": 1010, "text": "Training an object detector" }, { "code": null, "e": 1084, "s": 1038, "text": "Demo, showing the results on object detection" }, { "code": null, "e": 1580, "s": 1084, "text": "I should stress that this is not a tutorial for modding GTAV, I will not be able to explain and provide the code (maybe later, someday when I get more time) for using the GTAV APIs get the game world information. A small demo where you can play with the object detector on a single class can be found here. This guide can help you get started with modding in Grand Theft Auto V. And this tool can act as the starting point if you wanna dig deeper into extracting information from the game world." }, { "code": null, "e": 1906, "s": 1580, "text": "If you have prior knowledge of machine learning then you may skip this section. Since this article is not about learning machine learning, but about an application so I cannot go in-depth about the concepts of machine learning here. The following are some great articles to help you understand this field of computer science:" }, { "code": null, "e": 1958, "s": 1906, "text": "Machine learning is funWhy Machine learning matters" }, { "code": null, "e": 1982, "s": 1958, "text": "Machine learning is fun" }, { "code": null, "e": 2011, "s": 1982, "text": "Why Machine learning matters" }, { "code": null, "e": 2420, "s": 2011, "text": "If I were to ELI5(explain like I am five) Machine Learning is a form of Artificial Intelligence in which the program or algorithm is designed to learn on its own. Like in humans, small logic units called neurons (the circles in the diagram below) help algorithms to learn from experiences (or talking in terms of computers, data). The parameters in the algorithm change and learn the patterns in the dataset." }, { "code": null, "e": 2689, "s": 2420, "text": "Data is the basic necessity for any form of learning. We humans learn the ability to perceive or understand actions after experiencing them or reading/hearing about their experiences. Datasets, labeled or not labeled, act as the base of all the machine learning tasks." }, { "code": null, "e": 2985, "s": 2689, "text": "To train the machine learning models, a lot of data is required. The saying: “more the merrier” has never been more true. The current state-of-the-art (SOTA) machine learning models require a gigantic amount of data, for example, BERT, SOTA for many NLP tasks, are trained on 10s of GBs of data." }, { "code": null, "e": 3201, "s": 2985, "text": "Imagenet a standard image classification dataset is around 144 gigs of data compressed and >300 gigs uncompressed. Needless to say, that labeled data is very important for the advancement of artificial intelligence." }, { "code": null, "e": 3610, "s": 3201, "text": "While working on a project, I came across a problem where the object detector that I was using did not recognize all the objects in the image frame. I was trying to index all the objects present in the images frame, which later would make searching of images easier. But all the images are labeled human, not being able to detect the other objects in the image frames, the search was not working as I wanted." }, { "code": null, "e": 4094, "s": 3610, "text": "The ideal solution for this problem would be to gather data for those objects and re-train the object detector to also identify the new objects. This would not only be boring but time-consuming. I could use GANs, a type of machine learning algorithm famous for its use of creating artificial and similar examples to its inputs, to create more samples after organizing a few samples manually, but this is also boring and will require resources to train the GANs to generate more data." }, { "code": null, "e": 4471, "s": 4094, "text": "Now the only thing I could do was using internet services, like ScaleAI and Google Cloud Platform, to create a dataset. But these services charge ~$0.05 for each image annotated. Creating a dataset of 100 images for 15 categories each would mean that I will have to spend $120 just for the dataset. Spending this amount of $$$ just for a simple project is not a viable option." }, { "code": null, "e": 5522, "s": 4471, "text": "Out of all options, I started wishing if there was an artificial world, where all the objects already have the respective labels assigned to them. Then I won’t have to spend time searching for samples and then meticulously generating annotations for them. Then I realized that game worlds are the best example of such an artificial or virtual world. When the world is created the game engine has all the necessary information, it knows which textures are located where and it knows the location of all the other objects. Looking at the current state of gaming, where the developers are pushing the limits and creating game environments that are hardly distinguishable from the real world. Unreal Engine 5 demo on PS5 shows the graphical fidelity coming generation of consoles will boast. Having a virtual world, which closely resembles the real world, should act as a great simulation for testing and learning for algorithms. It would be great to allow algorithms to get access to the game world’s information and let it learn the nooks and crannies." }, { "code": null, "e": 5592, "s": 5522, "text": "The first game that came to my mind was Uncharted 4: The Thieves End." }, { "code": null, "e": 6076, "s": 5592, "text": "A stunning game with a good story, it has all the elements that we would like from testing environment. It has all the natural terrain types: Plains, Plateaus, Caves, Shores, it also sports great graphics which are nearly photo-realistic which would mean object detector would be learning features and shapes closer to that in the real world. But the problem is that I do not have my ps4 here at the university and nor is there a way to access Uncharted 4 assets in the way I’d like." }, { "code": null, "e": 6139, "s": 6076, "text": "The other choice for a game which could fulfill my demands of:" }, { "code": null, "e": 6211, "s": 6139, "text": "PhotorealismModding interface to allow accessing of the game world data" }, { "code": null, "e": 6224, "s": 6211, "text": "Photorealism" }, { "code": null, "e": 6284, "s": 6224, "text": "Modding interface to allow accessing of the game world data" }, { "code": null, "e": 6591, "s": 6284, "text": "was Grand Theft Auto: V. The base, though now 7 years old, resembles the real world more than most other games. This game has extensive support for mods and making changes/interacting with the game world. The game, after using some mods, can look extremely stunning with all of its lighting and reflections" }, { "code": null, "e": 6775, "s": 6591, "text": "GTA V community has made some outrageous mods wherein the default player models are replaced by custom models. This is a really really awesome thing, which I will continue upon later." }, { "code": null, "e": 7144, "s": 6775, "text": "I started by reading some articles and guides to using the APIs of Rage Engine the engine used by GTA. There are very few good examples or guides to help me with what I was trying to achieve. But luckily, there was an amazing tool that does something close to what I was trying to achieve, it gives the locations of many objects in the current image frame of the user." }, { "code": null, "e": 7559, "s": 7144, "text": "The greatest thing about this tool is that its source code is available on Github. After getting this solid starting point, the task had come down to figuring out how to access the object information from the game world like it’s location and type. This was achieved after hours and hours of reading code, compiling erroneous code. I was able to log the results from the game screen. I started with simple logging:" }, { "code": null, "e": 7879, "s": 7559, "text": "# the first log file that was created script running inside of GTA V[{ \"label\": \"car\", \"location\": [ [248.42533936651586, 173.41176470588235], [442.5429864253394, 278.841628959276] ], \"group_id\": \"non-living\"},{ \"label\": \"trevor\", ..... \"group_id\": living\"},{ \"label\": \"cat\", ..... \"group_id\": living\"}]" }, { "code": null, "e": 8444, "s": 7879, "text": "Some things were easy, like getting the location of named objects like characters that were individually identified using hashes. Progressively I learned to interact with the API to get the location of pedestrians and things like cars running close by. I was not able to fully hack the game world to get location information for all the objects that I wanted but this was a good starting point. Initial results looked promising, the scripts took screenshots of the game when an object was detected and saved the location of the same. Results looked something like:" }, { "code": null, "e": 8547, "s": 8444, "text": "With these satisfactory results, I went ahead with creating more samples. I decided to use 14 objects:" }, { "code": null, "e": 8728, "s": 8547, "text": "Human-like: pedestrians or humans, dogs and cats (3)Living things but not human-like: trees (4)Non-living things: cars, trucks, bikes, trains, boats, traffic signals, billboard (6)" }, { "code": null, "e": 8781, "s": 8728, "text": "Human-like: pedestrians or humans, dogs and cats (3)" }, { "code": null, "e": 8825, "s": 8781, "text": "Living things but not human-like: trees (4)" }, { "code": null, "e": 8911, "s": 8825, "text": "Non-living things: cars, trucks, bikes, trains, boats, traffic signals, billboard (6)" }, { "code": null, "e": 9358, "s": 8911, "text": "After acquiring enough data to train a model. I started training a RetinaNet model on my university server, a moderately powerful machine with Quadro P5000 and an Intel Xeon G6132. There was no specific reason for choosing RetinaNet, I had prior experience of using it. I trained the network from scratch, as using the pre-trained weights would kill the idea of this project which was to use game world knowledge and apply that to the real world." }, { "code": null, "e": 9683, "s": 9358, "text": "After hours and hours of waiting, I realized that looking at the slow training progress would not speed up it up and decided to call it a day and sleep. After waiting for an eternity, the training was completed and it was showtime. Testing the model on a test-set comprising of images from the game. The results seemed fair:" }, { "code": null, "e": 9874, "s": 9683, "text": "The results were as expected and now was the time for testing the performance on real-world objects. I think this experiment can be concluded as a sort of success by looking at the outcomes:" }, { "code": null, "e": 9933, "s": 9874, "text": "Most objects are identified well, but I noticed a blunder:" }, { "code": null, "e": 10436, "s": 9933, "text": "The reason for this, which I assume, is that the lack of different player models in the game for cats and dogs. The model is able to learn the shapes of different objects in the dataset, but since the variety of samples in cats and dogs was limited things do not go well for these classes. It is not able to learn features allowing it to differentiate between dogs and cats. The number of models for dogs and cats is limited, modding, and adding new models for these can be a remedy for this situation." }, { "code": null, "e": 10832, "s": 10436, "text": "The model performed well on the images, but don’t take my word for it. I have created a colab notebook where you can train your own model in just 5 minutes to recognize humans from an image. To keep the runtime as low as possible, the notebook only has a small dataset of 200 samples of human objects from the game. This low number of samples is sufficient to show the potential of such a model." }, { "code": null, "e": 11371, "s": 10832, "text": "After getting the object detection up and running I wanted to get semantic segmentation working as this is where the real potential of automatic labeling would shine. Exploiting the game engine’s knowledge of the textures to obtain pixel-level segmentation. I have not yet figured out how to obtain the texture-based information from the RAGE engine, the game engine used by GTA V. Getting the location of objects is one thing, and getting the location and area coverage of the object is another. The latter is where I am currently stuck." }, { "code": null, "e": 11718, "s": 11371, "text": "I believe the potential of this is huge, with the use of mods we can easily replace player models with those of things that we want to build detectors for. This technique, wherein we can replace the character models of a simple ragdoll which can act as the base for creating a large database of the character’s appearances in varied environments." }, { "code": null, "e": 12028, "s": 11718, "text": "With my GSoC selection, my time has been reduced and the dev environment changed. I would love to come back to this project in the future. I was planning on uploading the 31GB dataset of all the images and their labels but this is not possible currently as my University's internet service is unbearably slow." }, { "code": null, "e": 12243, "s": 12028, "text": "My next blog here would be either a dev-log for another project that I am working on or a starter blog for the GSoC blogs that I will be posting during the coming 3 months to show the progress of my work with CERN." }, { "code": null, "e": 12262, "s": 12243, "text": "No rights reserved" } ]
HISTCONTROL Command in Linux with Examples - GeeksforGeeks
27 Oct, 2020 In Linux, the history command can be used to show the list of commands which have been recently executed. HISTCONTROL variable is a colon-separated list of values controlling how commands are saved in the history list. HISTCONTROL variable allows us to store the bash history more efficiently. It can be used to ignore the duplicate commands or commands with leading white space or both. Uses of HISTCONTROL command: Several commands are executed multiple times while working at the command line. The default History size is 500. So storage of multiple commands will be a wastage of memory. Though the default history size can be changed using HISTFILESIZE, it is favorable to eliminate the duplicates. This can be achieved using HISTCONTROL. When we don’t want certain commands to appear in History, it can be accomplished using HISTCONTROL variable. We can instruct history to ignore the command by giving a white space before the command. 1. ignoredups: It causes lines matching the previous history entry to not be included. It does not add a command to history if it’s the same as the immediate previous command. It doesn’t look further back in the history list. HISTCONTROL=ignoredups The history after this command is executed will not store a command which is the same as the most recent command used. Consider that the below commands are added in sequence after using ignoredups: pwd whoami date pwd pwd whoami When two pwd commands are entered consecutively, the second command is ignored and not added to the history. But if the immediate previous command is not pwd, then it will not be ignored. 2. ignorespace: causes lines which begin with a white space character to not be included in the history list. If we don’t want a command to be included in history we can use white space characters before the command to avoid its inclusion in the history list. HISTCONTROL=ignorespace Consider that the below commands are added in sequence after using ignorespace and we don’t want to include the date command, so a white space character can be added before it: pwd whoami date ls -l | wc -l As there is a white space before the date command, it will not appear in the history list. 3. ignoreboth: is used when we want to use both ignorespace and ignoredups. HISTCONTROL=ignoreboth It is the same as: HISTCONTROL=ignorespace:ignoredups The history will not include commands with leading white space characters and duplicates. Consider that the below commands are added in sequence after using ignoreboth: whoami pwd pwd pwd Only one pwd command is added to the history list as one pwd command has a white space character before it while the other is the same as the most recent command included in the history list. 4. erasedups: It allows all previous lines matching the current line to be eliminated from the history list before that line is saved. The second and subsequent lines of a multi-line compound command are not tested and are added to the history in any case of the value of HISTCONTROL. Its syntax is: HISTCONTROL=erasedups The history after this command is used will not store any duplicate element. After a command is executed, it will match it with other recent commands before appending it to the history and if the match is found, then the command is ignored and not stored in the history. Consider that the below commands are added in sequence after using erasedups : pwd whoami date ls -l | wc -l pwd whoami whoami and pwd commands have been used twice but it won’t append to the history twice after erasedups have been implemented. Output can be seen in the image below: linux-command Linux-misc-commands Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C ZIP command in Linux with examples tar command in Linux with examples SORT command in Linux/Unix with examples curl command in Linux with Examples UDP Server-Client implementation in C tee command in Linux with examples Conditional Statements | Shell Script 'crontab' in Linux with Examples diff command in Linux with examples
[ { "code": null, "e": 24596, "s": 24568, "text": "\n27 Oct, 2020" }, { "code": null, "e": 24984, "s": 24596, "text": "In Linux, the history command can be used to show the list of commands which have been recently executed. HISTCONTROL variable is a colon-separated list of values controlling how commands are saved in the history list. HISTCONTROL variable allows us to store the bash history more efficiently. It can be used to ignore the duplicate commands or commands with leading white space or both." }, { "code": null, "e": 25013, "s": 24984, "text": "Uses of HISTCONTROL command:" }, { "code": null, "e": 25339, "s": 25013, "text": "Several commands are executed multiple times while working at the command line. The default History size is 500. So storage of multiple commands will be a wastage of memory. Though the default history size can be changed using HISTFILESIZE, it is favorable to eliminate the duplicates. This can be achieved using HISTCONTROL." }, { "code": null, "e": 25538, "s": 25339, "text": "When we don’t want certain commands to appear in History, it can be accomplished using HISTCONTROL variable. We can instruct history to ignore the command by giving a white space before the command." }, { "code": null, "e": 25764, "s": 25538, "text": "1. ignoredups: It causes lines matching the previous history entry to not be included. It does not add a command to history if it’s the same as the immediate previous command. It doesn’t look further back in the history list." }, { "code": null, "e": 25788, "s": 25764, "text": "HISTCONTROL=ignoredups\n" }, { "code": null, "e": 25987, "s": 25788, "text": "The history after this command is executed will not store a command which is the same as the most recent command used. Consider that the below commands are added in sequence after using ignoredups:" }, { "code": null, "e": 26019, "s": 25987, "text": "pwd\nwhoami\ndate\npwd\npwd\nwhoami\n" }, { "code": null, "e": 26207, "s": 26019, "text": "When two pwd commands are entered consecutively, the second command is ignored and not added to the history. But if the immediate previous command is not pwd, then it will not be ignored." }, { "code": null, "e": 26467, "s": 26207, "text": "2. ignorespace: causes lines which begin with a white space character to not be included in the history list. If we don’t want a command to be included in history we can use white space characters before the command to avoid its inclusion in the history list." }, { "code": null, "e": 26492, "s": 26467, "text": "HISTCONTROL=ignorespace\n" }, { "code": null, "e": 26669, "s": 26492, "text": "Consider that the below commands are added in sequence after using ignorespace and we don’t want to include the date command, so a white space character can be added before it:" }, { "code": null, "e": 26700, "s": 26669, "text": "pwd\nwhoami\ndate\nls -l | wc -l\n" }, { "code": null, "e": 26791, "s": 26700, "text": "As there is a white space before the date command, it will not appear in the history list." }, { "code": null, "e": 26867, "s": 26791, "text": "3. ignoreboth: is used when we want to use both ignorespace and ignoredups." }, { "code": null, "e": 26891, "s": 26867, "text": "HISTCONTROL=ignoreboth\n" }, { "code": null, "e": 26910, "s": 26891, "text": "It is the same as:" }, { "code": null, "e": 26946, "s": 26910, "text": "HISTCONTROL=ignorespace:ignoredups\n" }, { "code": null, "e": 27115, "s": 26946, "text": "The history will not include commands with leading white space characters and duplicates. Consider that the below commands are added in sequence after using ignoreboth:" }, { "code": null, "e": 27135, "s": 27115, "text": "whoami\npwd\npwd\npwd\n" }, { "code": null, "e": 27327, "s": 27135, "text": "Only one pwd command is added to the history list as one pwd command has a white space character before it while the other is the same as the most recent command included in the history list." }, { "code": null, "e": 27627, "s": 27327, "text": "4. erasedups: It allows all previous lines matching the current line to be eliminated from the history list before that line is saved. The second and subsequent lines of a multi-line compound command are not tested and are added to the history in any case of the value of HISTCONTROL. Its syntax is:" }, { "code": null, "e": 27650, "s": 27627, "text": "HISTCONTROL=erasedups\n" }, { "code": null, "e": 28000, "s": 27650, "text": "The history after this command is used will not store any duplicate element. After a command is executed, it will match it with other recent commands before appending it to the history and if the match is found, then the command is ignored and not stored in the history. Consider that the below commands are added in sequence after using erasedups :" }, { "code": null, "e": 28042, "s": 28000, "text": "pwd\nwhoami\ndate\nls -l | wc -l\npwd\nwhoami\n" }, { "code": null, "e": 28206, "s": 28042, "text": "whoami and pwd commands have been used twice but it won’t append to the history twice after erasedups have been implemented. Output can be seen in the image below:" }, { "code": null, "e": 28220, "s": 28206, "text": "linux-command" }, { "code": null, "e": 28240, "s": 28220, "text": "Linux-misc-commands" }, { "code": null, "e": 28251, "s": 28240, "text": "Linux-Unix" }, { "code": null, "e": 28349, "s": 28251, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28387, "s": 28349, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 28422, "s": 28387, "text": "ZIP command in Linux with examples" }, { "code": null, "e": 28457, "s": 28422, "text": "tar command in Linux with examples" }, { "code": null, "e": 28498, "s": 28457, "text": "SORT command in Linux/Unix with examples" }, { "code": null, "e": 28534, "s": 28498, "text": "curl command in Linux with Examples" }, { "code": null, "e": 28572, "s": 28534, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 28607, "s": 28572, "text": "tee command in Linux with examples" }, { "code": null, "e": 28645, "s": 28607, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 28678, "s": 28645, "text": "'crontab' in Linux with Examples" } ]
Tryit Editor v3.7
Tryit: Center vertically with padding
[]
C/C++ program to print Hello World without using main() and semicolon - GeeksforGeeks
25 Nov, 2019 The task is to write a program to print Hello World without using main() and semicolon. As we already know how to print Hello World without the use of a semicolon. Now for writing without main() method, we will need a Macro. C C++ // C program to print Hello World// without using main() and semicolon #include <stdio.h> #define x main void x(){ if (printf("Hello World")) { }} // C++ program to print Hello World// without using main() and semicolon #include <bits/stdc++.h>using namespace std; #define x main void x(){ if (cout << "Hello World") { }} Hello World C/C++ program to print Hello World without using main() and semicolon c-input-output cpp-input-output C Programs C++ Programs School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C Program to read contents of Whole File Producer Consumer Problem in C C program to find the length of a string Exit codes in C/C++ with Examples Regular expressions in C C++ Program for QuickSort Sorting a Map by value in C++ STL cin in C++ delete keyword in C++ CSV file management using C++
[ { "code": null, "e": 24954, "s": 24926, "text": "\n25 Nov, 2019" }, { "code": null, "e": 25042, "s": 24954, "text": "The task is to write a program to print Hello World without using main() and semicolon." }, { "code": null, "e": 25179, "s": 25042, "text": "As we already know how to print Hello World without the use of a semicolon. Now for writing without main() method, we will need a Macro." }, { "code": null, "e": 25181, "s": 25179, "text": "C" }, { "code": null, "e": 25185, "s": 25181, "text": "C++" }, { "code": "// C program to print Hello World// without using main() and semicolon #include <stdio.h> #define x main void x(){ if (printf(\"Hello World\")) { }}", "e": 25341, "s": 25185, "text": null }, { "code": "// C++ program to print Hello World// without using main() and semicolon #include <bits/stdc++.h>using namespace std; #define x main void x(){ if (cout << \"Hello World\") { }}", "e": 25525, "s": 25341, "text": null }, { "code": null, "e": 25538, "s": 25525, "text": "Hello World\n" }, { "code": null, "e": 25608, "s": 25538, "text": "C/C++ program to print Hello World without using main() and semicolon" }, { "code": null, "e": 25623, "s": 25608, "text": "c-input-output" }, { "code": null, "e": 25640, "s": 25623, "text": "cpp-input-output" }, { "code": null, "e": 25651, "s": 25640, "text": "C Programs" }, { "code": null, "e": 25664, "s": 25651, "text": "C++ Programs" }, { "code": null, "e": 25683, "s": 25664, "text": "School Programming" }, { "code": null, "e": 25781, "s": 25683, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25822, "s": 25781, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 25853, "s": 25822, "text": "Producer Consumer Problem in C" }, { "code": null, "e": 25894, "s": 25853, "text": "C program to find the length of a string" }, { "code": null, "e": 25928, "s": 25894, "text": "Exit codes in C/C++ with Examples" }, { "code": null, "e": 25953, "s": 25928, "text": "Regular expressions in C" }, { "code": null, "e": 25979, "s": 25953, "text": "C++ Program for QuickSort" }, { "code": null, "e": 26013, "s": 25979, "text": "Sorting a Map by value in C++ STL" }, { "code": null, "e": 26024, "s": 26013, "text": "cin in C++" }, { "code": null, "e": 26046, "s": 26024, "text": "delete keyword in C++" } ]
Bootstrap and Statistical Inference in Python | by Leihua Ye, PhD | Towards Data Science
The complete Jupyter Notebook is available at my Github. Bootstrap is a resampling strategy with replacement that requires no assumptions about the data distribution. It is a powerful tool that allows us to make inferences about the population statistics (e.g., mean, variance) when we only have a finite number of samples. Even when we only have one sample, the bootstrap method provides a good enough approximation to the true population statistics. Amazing! This is a follow-up post on the bootstrap method. I’ve introduced the fundamentals (e.g., the what, when, and why) and applications in another post. Please check it out for detailed walkthrough. towardsdatascience.com In today’s post, we shift gears and primarily focus on its utilities in statistical inference and Python implementation. Bootstrap is a resampling process of the original sample with the same sample size and replacement for a lot of iterations. This is a straightforward question, which fits the requirements of the bootstrap method (from a single sample to population statistics). We will use a simulated example for this question. Hypothetically, we have collected data on body weights of half a million male adults in America, and it ranges from 100 to 240. # step 1: simulate population distribution array([209, 226, 166, ..., 197, 175, 121]# weight_pop169.633012 # population mean40.39571209680374 # population std First, we simulate a population distribution from 100 to 240, with a mean of 169 and a standard deviation of 40. Realistically speaking, the population parameters (mean and standard deviation) should remain unknown. Here, we play God and reserve these population parameters for later-on comparisons with the bootstrapped results. # step 2: take a random sample from the population 169.127 # sample_mean40.466218886869086 # sample std Second, we take a random sample of the population and obtain the sample mean 169.127, and sample standard error, 40.466. step 3: bootstrap for 10,000 times array([169.023, 168.843, 168.031, ..., 169.98 , 167.204, 172.015]) Third, we repeat the resampling process for 10K times and construct a bootstrapped sampling data, which should follow a normal distribution (Central Limit Theorem). # step 4: analysis and interpretation 169.13262949999998 # bootstrapped sample means169.633012 # recall: true population mean1.2729552820228016 # bootstrapped stdarray([166.627975, 171.60705 ]) # 95% C.I. Here are the breakdowns. After 10K iterations, the bootstrapped sample mean is 169.13, which is very close to the true population mean, 169.6. The bootstrapped sample standard error is 1.27, and the 95% Confidence Interval is [166, 171]. In other words, 95% of the time, the true population mean lies between 166 and 171. Actually, this is true if you check the population parameters obtained in Step 1. Distribution and C.I. in Graph: As you can see here, we have successfully used the bootstrap method and “reverse-engineered” the population parameters from one single sample. This is amazing! Let’s see how it can solve more realistic questions. This is a real Data Science interview question that I was asked by a FAANG company. It is a super smart question and I love it. Here is why. First, it is subtle. We probably do not think about using bootstrap in the first place, but the question asks us to perform an inference on a small dataset. What is the method that allows us to make such inferences? Bingo! Bootstrap! Also, this question contains limited information, and we have to ask clarification questions, like if a confidence interval is needed, how many samples we should do before we move on to solutions. It tests good communication besides testing our statistics. # step 0: create a population distribution of 100 random numbers from 0 to 200 At ground zero, we randomly generate a population distribution of 100 random numbers from 0 to 200. # step 1: take a random sample of size 10 array([134, 139, 3, 153, 51, 146, 48, 139, 3, 168]) Then, we take a random sample of the population and obtain a small sample of 10 numbers. # step 2: what’s the median of this sample (sample_1)? 115.0 n = len(some): returns the length of some. some.sort(): for any arrays, we have to sort the values before we calculate the median value. if n%2==0: if the length of some is even, then we calculate the median as such. else: if the length is odd, then we calculate the median as such. After calculations, sample_1 has a median value is 115. Alternatively, we can use numpy.median(some) to obtain the median value, if the interviewers allow you to import Python libraries. Otherwise, we can still obtain the median value using the above self-defined function. # step 3: repeatedly sample from the sample (sample_1) with replacement, aka. bootstrap In step 3, we introduce bootstrap to repeatedly resample from the previous sample (sample_1) for 10,000 times and obtain a resampling distribution of the median values, called boot_sample_medians. Let’s break down the for loop. boot_sample_medians = []: create an empty list to store values for i in range(10000): iterate over 10K times boot_sample = np.random.choice(sample_1, replace =True, size = 10): collect a resample of 6 values from sample_1 with replacement. boot_median: calculate the median value for each iteration boot_sample_medians.append(boot_median): attach the median value to the list. # step 4: stand error and confidence interval 36.24544558530768 #std106.5054 # the average value of repeated samples' median valuesarray([ 27., 146.]) #95% C.I. As the results show, the repeated samples has a standard error of 36, an average value of 106.5, and its 95% confidence interval is [27, 146]. Recall, the original sample (sample_1) has a median of 115. So, the bootstrap methods offers a really close approximation to the original distribution. The reason why the C.I, is so wide is because of the small sample size and considerably large variations among numbers. In each iteration, any different selections of numbers would result in a different median value, which explains the variation and the wide C.I. If the interview question asks you to do any form of statistical inferences with a limited sample size (e.g., one sample), the bootstrap comes in handy. To disentangle the Python programming part, the key is to understand the statistical procedures well and code it up with each step. Ask for clarification questions before doing any programming, and ask for hints or help if got stuck. It’s highly encouraged to do so in interviews. Good Luck! Understand the questions well before proposing solutions. Ask for clarification questions if key information is missing. Practice these advanced topics before your next Data Science interview. Medium recently evolved its Writer Partner Program, which supports ordinary writers like myself. If you are not a subscriber yet and sign up via the following link, I’ll receive a portion of the membership fees. leihua-ye.medium.com towardsdatascience.com towardsdatascience.com towardsdatascience.com Please find me on LinkedIn and Youtube. Also, check my other posts on Artificial Intelligence and Machine Learning.
[ { "code": null, "e": 104, "s": 47, "text": "The complete Jupyter Notebook is available at my Github." }, { "code": null, "e": 499, "s": 104, "text": "Bootstrap is a resampling strategy with replacement that requires no assumptions about the data distribution. It is a powerful tool that allows us to make inferences about the population statistics (e.g., mean, variance) when we only have a finite number of samples. Even when we only have one sample, the bootstrap method provides a good enough approximation to the true population statistics." }, { "code": null, "e": 508, "s": 499, "text": "Amazing!" }, { "code": null, "e": 703, "s": 508, "text": "This is a follow-up post on the bootstrap method. I’ve introduced the fundamentals (e.g., the what, when, and why) and applications in another post. Please check it out for detailed walkthrough." }, { "code": null, "e": 726, "s": 703, "text": "towardsdatascience.com" }, { "code": null, "e": 847, "s": 726, "text": "In today’s post, we shift gears and primarily focus on its utilities in statistical inference and Python implementation." }, { "code": null, "e": 971, "s": 847, "text": "Bootstrap is a resampling process of the original sample with the same sample size and replacement for a lot of iterations." }, { "code": null, "e": 1287, "s": 971, "text": "This is a straightforward question, which fits the requirements of the bootstrap method (from a single sample to population statistics). We will use a simulated example for this question. Hypothetically, we have collected data on body weights of half a million male adults in America, and it ranges from 100 to 240." }, { "code": null, "e": 1330, "s": 1287, "text": "# step 1: simulate population distribution" }, { "code": null, "e": 1446, "s": 1330, "text": "array([209, 226, 166, ..., 197, 175, 121]# weight_pop169.633012 # population mean40.39571209680374 # population std" }, { "code": null, "e": 1559, "s": 1446, "text": "First, we simulate a population distribution from 100 to 240, with a mean of 169 and a standard deviation of 40." }, { "code": null, "e": 1776, "s": 1559, "text": "Realistically speaking, the population parameters (mean and standard deviation) should remain unknown. Here, we play God and reserve these population parameters for later-on comparisons with the bootstrapped results." }, { "code": null, "e": 1827, "s": 1776, "text": "# step 2: take a random sample from the population" }, { "code": null, "e": 1880, "s": 1827, "text": "169.127 # sample_mean40.466218886869086 # sample std" }, { "code": null, "e": 2001, "s": 1880, "text": "Second, we take a random sample of the population and obtain the sample mean 169.127, and sample standard error, 40.466." }, { "code": null, "e": 2036, "s": 2001, "text": "step 3: bootstrap for 10,000 times" }, { "code": null, "e": 2103, "s": 2036, "text": "array([169.023, 168.843, 168.031, ..., 169.98 , 167.204, 172.015])" }, { "code": null, "e": 2268, "s": 2103, "text": "Third, we repeat the resampling process for 10K times and construct a bootstrapped sampling data, which should follow a normal distribution (Central Limit Theorem)." }, { "code": null, "e": 2307, "s": 2268, "text": "# step 4: analysis and interpretation " }, { "code": null, "e": 2474, "s": 2307, "text": "169.13262949999998 # bootstrapped sample means169.633012 # recall: true population mean1.2729552820228016 # bootstrapped stdarray([166.627975, 171.60705 ]) # 95% C.I." }, { "code": null, "e": 2499, "s": 2474, "text": "Here are the breakdowns." }, { "code": null, "e": 2712, "s": 2499, "text": "After 10K iterations, the bootstrapped sample mean is 169.13, which is very close to the true population mean, 169.6. The bootstrapped sample standard error is 1.27, and the 95% Confidence Interval is [166, 171]." }, { "code": null, "e": 2878, "s": 2712, "text": "In other words, 95% of the time, the true population mean lies between 166 and 171. Actually, this is true if you check the population parameters obtained in Step 1." }, { "code": null, "e": 2910, "s": 2878, "text": "Distribution and C.I. in Graph:" }, { "code": null, "e": 3053, "s": 2910, "text": "As you can see here, we have successfully used the bootstrap method and “reverse-engineered” the population parameters from one single sample." }, { "code": null, "e": 3070, "s": 3053, "text": "This is amazing!" }, { "code": null, "e": 3123, "s": 3070, "text": "Let’s see how it can solve more realistic questions." }, { "code": null, "e": 3251, "s": 3123, "text": "This is a real Data Science interview question that I was asked by a FAANG company. It is a super smart question and I love it." }, { "code": null, "e": 3264, "s": 3251, "text": "Here is why." }, { "code": null, "e": 3421, "s": 3264, "text": "First, it is subtle. We probably do not think about using bootstrap in the first place, but the question asks us to perform an inference on a small dataset." }, { "code": null, "e": 3480, "s": 3421, "text": "What is the method that allows us to make such inferences?" }, { "code": null, "e": 3498, "s": 3480, "text": "Bingo! Bootstrap!" }, { "code": null, "e": 3755, "s": 3498, "text": "Also, this question contains limited information, and we have to ask clarification questions, like if a confidence interval is needed, how many samples we should do before we move on to solutions. It tests good communication besides testing our statistics." }, { "code": null, "e": 3834, "s": 3755, "text": "# step 0: create a population distribution of 100 random numbers from 0 to 200" }, { "code": null, "e": 3934, "s": 3834, "text": "At ground zero, we randomly generate a population distribution of 100 random numbers from 0 to 200." }, { "code": null, "e": 3976, "s": 3934, "text": "# step 1: take a random sample of size 10" }, { "code": null, "e": 4034, "s": 3976, "text": "array([134, 139, 3, 153, 51, 146, 48, 139, 3, 168])" }, { "code": null, "e": 4123, "s": 4034, "text": "Then, we take a random sample of the population and obtain a small sample of 10 numbers." }, { "code": null, "e": 4178, "s": 4123, "text": "# step 2: what’s the median of this sample (sample_1)?" }, { "code": null, "e": 4184, "s": 4178, "text": "115.0" }, { "code": null, "e": 4227, "s": 4184, "text": "n = len(some): returns the length of some." }, { "code": null, "e": 4321, "s": 4227, "text": "some.sort(): for any arrays, we have to sort the values before we calculate the median value." }, { "code": null, "e": 4401, "s": 4321, "text": "if n%2==0: if the length of some is even, then we calculate the median as such." }, { "code": null, "e": 4467, "s": 4401, "text": "else: if the length is odd, then we calculate the median as such." }, { "code": null, "e": 4523, "s": 4467, "text": "After calculations, sample_1 has a median value is 115." }, { "code": null, "e": 4741, "s": 4523, "text": "Alternatively, we can use numpy.median(some) to obtain the median value, if the interviewers allow you to import Python libraries. Otherwise, we can still obtain the median value using the above self-defined function." }, { "code": null, "e": 4829, "s": 4741, "text": "# step 3: repeatedly sample from the sample (sample_1) with replacement, aka. bootstrap" }, { "code": null, "e": 5026, "s": 4829, "text": "In step 3, we introduce bootstrap to repeatedly resample from the previous sample (sample_1) for 10,000 times and obtain a resampling distribution of the median values, called boot_sample_medians." }, { "code": null, "e": 5057, "s": 5026, "text": "Let’s break down the for loop." }, { "code": null, "e": 5120, "s": 5057, "text": "boot_sample_medians = []: create an empty list to store values" }, { "code": null, "e": 5166, "s": 5120, "text": "for i in range(10000): iterate over 10K times" }, { "code": null, "e": 5297, "s": 5166, "text": "boot_sample = np.random.choice(sample_1, replace =True, size = 10): collect a resample of 6 values from sample_1 with replacement." }, { "code": null, "e": 5356, "s": 5297, "text": "boot_median: calculate the median value for each iteration" }, { "code": null, "e": 5434, "s": 5356, "text": "boot_sample_medians.append(boot_median): attach the median value to the list." }, { "code": null, "e": 5480, "s": 5434, "text": "# step 4: stand error and confidence interval" }, { "code": null, "e": 5595, "s": 5480, "text": "36.24544558530768 #std106.5054 # the average value of repeated samples' median valuesarray([ 27., 146.]) #95% C.I." }, { "code": null, "e": 5890, "s": 5595, "text": "As the results show, the repeated samples has a standard error of 36, an average value of 106.5, and its 95% confidence interval is [27, 146]. Recall, the original sample (sample_1) has a median of 115. So, the bootstrap methods offers a really close approximation to the original distribution." }, { "code": null, "e": 6154, "s": 5890, "text": "The reason why the C.I, is so wide is because of the small sample size and considerably large variations among numbers. In each iteration, any different selections of numbers would result in a different median value, which explains the variation and the wide C.I." }, { "code": null, "e": 6307, "s": 6154, "text": "If the interview question asks you to do any form of statistical inferences with a limited sample size (e.g., one sample), the bootstrap comes in handy." }, { "code": null, "e": 6439, "s": 6307, "text": "To disentangle the Python programming part, the key is to understand the statistical procedures well and code it up with each step." }, { "code": null, "e": 6588, "s": 6439, "text": "Ask for clarification questions before doing any programming, and ask for hints or help if got stuck. It’s highly encouraged to do so in interviews." }, { "code": null, "e": 6599, "s": 6588, "text": "Good Luck!" }, { "code": null, "e": 6657, "s": 6599, "text": "Understand the questions well before proposing solutions." }, { "code": null, "e": 6720, "s": 6657, "text": "Ask for clarification questions if key information is missing." }, { "code": null, "e": 6792, "s": 6720, "text": "Practice these advanced topics before your next Data Science interview." }, { "code": null, "e": 7004, "s": 6792, "text": "Medium recently evolved its Writer Partner Program, which supports ordinary writers like myself. If you are not a subscriber yet and sign up via the following link, I’ll receive a portion of the membership fees." }, { "code": null, "e": 7025, "s": 7004, "text": "leihua-ye.medium.com" }, { "code": null, "e": 7048, "s": 7025, "text": "towardsdatascience.com" }, { "code": null, "e": 7071, "s": 7048, "text": "towardsdatascience.com" }, { "code": null, "e": 7094, "s": 7071, "text": "towardsdatascience.com" }, { "code": null, "e": 7134, "s": 7094, "text": "Please find me on LinkedIn and Youtube." } ]
Sass - Output Style
In this chapter, we will study about SASS Output Style. The CSS file that the SASS generates consists of default CSS style, which reflects the structure of document. The default CSS styling is good but might not be suitable for all situations; on other hand, SASS supports many other styles. It supports the following different output styles − Nested style is default styling of SASS. This way of styling is very useful when you are dealing with large CSS files. It makes the structure of the file more readable and can be easily understood. Every property takes its own line and indentation of each rule is based on how deeply it is nested. For instance, we can nest the code in SASS file as shown below − #first { background-color: #00FFFF; color: #C0C0C0; } #first p { width: 10em; } .highlight { text-decoration: underline; font-size: 5em; background-color: #FFFF00; } In expanded type of CSS styling each property and rule has its own line. It takes more space compared to the Nested CSS style. The Rules section consists of properties, which are all intended within the rules, whereas rules does not follow any indentation. For instance, we can expand the code in the SASS file as shown below − #first { background-color: #00FFFF; color: #C0C0C0; } #first p { width: 10em; } .highlight { text-decoration: underline; font-size: 5em; background-color: #FFFF00; } Compact CSS style competitively takes less space than Expanded and Nested. It focuses mainly on selectors rather than its properties. Each selector takes up one line and its properties are also placed in the same line. Nested rules are positioned next to each other without a newline and the separate groups of rules will have new lines between them. For instance, we can compact the code in the SASS file as shown below − #first { background-color: #00FFFF; color: #C0C0C0; } #first p { width: 10em; } .highlight { text-decoration: underline; font-size: 5em; background-color: #FFFF00; } Compressed CSS style takes the least amount of space compared to all other styles discussed above. It provides whitespaces only to separate selectors and newline at the end of the file. This way of styling is confusing and is not easily readable. For instance, we can compress the code in SASS file as shown below − #first { background-color:#00FFFF;color:#C0C0C0 } #first p { width:10em } .highlight { text-decoration:underline;font-size:5em;background-color:#FFFF00 } 50 Lectures 5.5 hours Code And Create 124 Lectures 30 hours Juan Galvan 162 Lectures 31.5 hours Yossef Ayman Zedan 167 Lectures 45.5 hours Muslim Helalee Print Add Notes Bookmark this page
[ { "code": null, "e": 2144, "s": 1852, "text": "In this chapter, we will study about SASS Output Style. The CSS file that the SASS generates consists of default CSS style, which reflects the structure of document. The default CSS styling is good but might not be suitable for all situations; on other hand, SASS supports many other styles." }, { "code": null, "e": 2196, "s": 2144, "text": "It supports the following different output styles −" }, { "code": null, "e": 2494, "s": 2196, "text": "Nested style is default styling of SASS. This way of styling is very useful when you are dealing with large CSS files. It makes the structure of the file more readable and can be easily understood. Every property takes its own line and indentation of each rule is based on how deeply it is nested." }, { "code": null, "e": 2559, "s": 2494, "text": "For instance, we can nest the code in SASS file as shown below −" }, { "code": null, "e": 2748, "s": 2559, "text": "#first {\n background-color: #00FFFF;\n color: #C0C0C0; \n}\n\n#first p {\n width: 10em; \n}\n\n.highlight {\n text-decoration: underline;\n font-size: 5em;\n background-color: #FFFF00; \n}" }, { "code": null, "e": 3005, "s": 2748, "text": "In expanded type of CSS styling each property and rule has its own line. It takes more space compared to the Nested CSS style. The Rules section consists of properties, which are all intended within the rules, whereas rules does not follow any indentation." }, { "code": null, "e": 3076, "s": 3005, "text": "For instance, we can expand the code in the SASS file as shown below −" }, { "code": null, "e": 3262, "s": 3076, "text": "#first {\n background-color: #00FFFF;\n color: #C0C0C0;\n}\n\n#first p {\n width: 10em;\n}\n\n.highlight {\n text-decoration: underline;\n font-size: 5em;\n background-color: #FFFF00;\n}" }, { "code": null, "e": 3613, "s": 3262, "text": "Compact CSS style competitively takes less space than Expanded and Nested. It focuses mainly on selectors rather than its properties. Each selector takes up one line and its properties are also placed in the same line. Nested rules are positioned next to each other without a newline and the separate groups of rules will have new lines between them." }, { "code": null, "e": 3685, "s": 3613, "text": "For instance, we can compact the code in the SASS file as shown below −" }, { "code": null, "e": 3868, "s": 3685, "text": "#first { \n background-color: #00FFFF; color: #C0C0C0; \n}\n\n#first p { \n width: 10em; \n}\n\n.highlight { \n text-decoration: underline; font-size: 5em; background-color: #FFFF00; \n}" }, { "code": null, "e": 4115, "s": 3868, "text": "Compressed CSS style takes the least amount of space compared to all other styles discussed above. It provides whitespaces only to separate selectors and newline at the end of the file. This way of styling is confusing and is not easily readable." }, { "code": null, "e": 4184, "s": 4115, "text": "For instance, we can compress the code in SASS file as shown below −" }, { "code": null, "e": 4356, "s": 4184, "text": "#first { \n background-color:#00FFFF;color:#C0C0C0\n} \n\n#first p { \n width:10em \n} \n\n.highlight { \n text-decoration:underline;font-size:5em;background-color:#FFFF00 \n}" }, { "code": null, "e": 4391, "s": 4356, "text": "\n 50 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4408, "s": 4391, "text": " Code And Create" }, { "code": null, "e": 4443, "s": 4408, "text": "\n 124 Lectures \n 30 hours \n" }, { "code": null, "e": 4456, "s": 4443, "text": " Juan Galvan" }, { "code": null, "e": 4493, "s": 4456, "text": "\n 162 Lectures \n 31.5 hours \n" }, { "code": null, "e": 4513, "s": 4493, "text": " Yossef Ayman Zedan" }, { "code": null, "e": 4550, "s": 4513, "text": "\n 167 Lectures \n 45.5 hours \n" }, { "code": null, "e": 4566, "s": 4550, "text": " Muslim Helalee" }, { "code": null, "e": 4573, "s": 4566, "text": " Print" }, { "code": null, "e": 4584, "s": 4573, "text": " Add Notes" } ]
Node.js Local Module - GeeksforGeeks
13 Oct, 2021 Node.js comes with different predefined modules (e.g. http, fs, path, etc.) that we use and scale our project. We can define modules locally as Local Module. It consists different functions declared inside a JavaScript object and we reuse them according to the requirement. We can also package it and distribute it using NPM. Defining local module: Local module must be written in a separate JavaScript file. In the separate file, we can declare a JavaScript object with different properties and methods. Step 1: Creating a local module with filename Welcome.js const welcome = { sayHello : function() { console.log("Hello GeekforGeeks user"); }, currTime : new Date().toLocaleDateString(), companyName : "GeekforGeeks"} module.exports = welcome Explanation: Here, we declared an object ‘welcome’ with a function sayHello and two variables currTime and companyName. We use the module.export to make the object available globally. Part 2: In this part, use the above module in app.js file. var local = require("./Welcome.js");local.sayHello();console.log(local.currTime);console.log(local.companyName); Explanation: Here, we import our local module ‘sayHello’ in a variable ‘local’ and consume the function and variables of the created modules.Output: Hello GeekforGeeks user 12/6/2019 GeekforGeeks Node.js-Basics Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Node.js fs.readFileSync() Method How to update Node.js and NPM to next version ? Node.js fs.writeFile() Method How to update NPM ? Difference between promise and async await in Node.js Roadmap to Become a Web Developer in 2022 How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills Convert a string to an integer in JavaScript
[ { "code": null, "e": 37256, "s": 37228, "text": "\n13 Oct, 2021" }, { "code": null, "e": 37582, "s": 37256, "text": "Node.js comes with different predefined modules (e.g. http, fs, path, etc.) that we use and scale our project. We can define modules locally as Local Module. It consists different functions declared inside a JavaScript object and we reuse them according to the requirement. We can also package it and distribute it using NPM." }, { "code": null, "e": 37761, "s": 37582, "text": "Defining local module: Local module must be written in a separate JavaScript file. In the separate file, we can declare a JavaScript object with different properties and methods." }, { "code": null, "e": 37818, "s": 37761, "text": "Step 1: Creating a local module with filename Welcome.js" }, { "code": "const welcome = { sayHello : function() { console.log(\"Hello GeekforGeeks user\"); }, currTime : new Date().toLocaleDateString(), companyName : \"GeekforGeeks\"} module.exports = welcome", "e": 38022, "s": 37818, "text": null }, { "code": null, "e": 38206, "s": 38022, "text": "Explanation: Here, we declared an object ‘welcome’ with a function sayHello and two variables currTime and companyName. We use the module.export to make the object available globally." }, { "code": null, "e": 38265, "s": 38206, "text": "Part 2: In this part, use the above module in app.js file." }, { "code": "var local = require(\"./Welcome.js\");local.sayHello();console.log(local.currTime);console.log(local.companyName);", "e": 38378, "s": 38265, "text": null }, { "code": null, "e": 38527, "s": 38378, "text": "Explanation: Here, we import our local module ‘sayHello’ in a variable ‘local’ and consume the function and variables of the created modules.Output:" }, { "code": null, "e": 38575, "s": 38527, "text": "Hello GeekforGeeks user\n12/6/2019\nGeekforGeeks\n" }, { "code": null, "e": 38590, "s": 38575, "text": "Node.js-Basics" }, { "code": null, "e": 38597, "s": 38590, "text": "Picked" }, { "code": null, "e": 38605, "s": 38597, "text": "Node.js" }, { "code": null, "e": 38622, "s": 38605, "text": "Web Technologies" }, { "code": null, "e": 38720, "s": 38622, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38753, "s": 38720, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 38801, "s": 38753, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 38831, "s": 38801, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 38851, "s": 38831, "text": "How to update NPM ?" }, { "code": null, "e": 38905, "s": 38851, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 38947, "s": 38905, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 38990, "s": 38947, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 39040, "s": 38990, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 39102, "s": 39040, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
How to search for the exact string value in MySQL?
To search for the exact string value, use the concept of COLLATE. Let us first create a table − mysql> create table DemoTable1620 -> ( -> Subject varchar(20) -> ); Query OK, 0 rows affected (0.42 sec) Insert some records in the table using insert command − mysql> insert into DemoTable1620 values('mysql'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable1620 values('MySql'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable1620 values('mYSQL'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable1620 values('MySQL'); Query OK, 1 row affected (0.26 sec) mysql> insert into DemoTable1620 values('MYSQL'); Query OK, 1 row affected (0.20 sec) Display all records from the table using select statement − mysql> select * from DemoTable1620; This will produce the following output − +---------+ | Subject | +---------+ | mysql | | MySql | | mYSQL | | MySQL | | MYSQL | +---------+ 5 rows in set (0.00 sec) Following is the query to search for the exact string value in MySQL − mysql> select * from DemoTable1620 where Subject collate utf8_bin = 'MySQL'; This will produce the following output − +---------+ | Subject | +---------+ | MySQL | +---------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1158, "s": 1062, "text": "To search for the exact string value, use the concept of COLLATE. Let us first create a table −" }, { "code": null, "e": 1275, "s": 1158, "text": "mysql> create table DemoTable1620\n -> (\n -> Subject varchar(20)\n -> );\nQuery OK, 0 rows affected (0.42 sec)" }, { "code": null, "e": 1331, "s": 1275, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1761, "s": 1331, "text": "mysql> insert into DemoTable1620 values('mysql');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable1620 values('MySql');\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into DemoTable1620 values('mYSQL');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into DemoTable1620 values('MySQL');\nQuery OK, 1 row affected (0.26 sec)\nmysql> insert into DemoTable1620 values('MYSQL');\nQuery OK, 1 row affected (0.20 sec)" }, { "code": null, "e": 1821, "s": 1761, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1857, "s": 1821, "text": "mysql> select * from DemoTable1620;" }, { "code": null, "e": 1898, "s": 1857, "text": "This will produce the following output −" }, { "code": null, "e": 2031, "s": 1898, "text": "+---------+\n| Subject |\n+---------+\n| mysql |\n| MySql |\n| mYSQL |\n| MySQL |\n| MYSQL |\n+---------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 2102, "s": 2031, "text": "Following is the query to search for the exact string value in MySQL −" }, { "code": null, "e": 2179, "s": 2102, "text": "mysql> select * from DemoTable1620 where Subject collate utf8_bin = 'MySQL';" }, { "code": null, "e": 2220, "s": 2179, "text": "This will produce the following output −" }, { "code": null, "e": 2304, "s": 2220, "text": "+---------+\n| Subject |\n+---------+\n| MySQL |\n+---------+\n1 row in set (0.00 sec)" } ]
Objective-C Functions
A function is a group of statements that together perform a task. Every Objective-C program has one C function, which is main(), and all of the most trivial programs can define additional functions. You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically the division usually is so each function performs a specific task. A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function. Basically in Objective-C, we call the function as method. The Objective-C foundation framework provides numerous built-in methods that your program can call. For example, method appendString() to append string to another string. A method is known with various names like a function or a sub-routine or a procedure, etc. The general form of a method definition in Objective-C programming language is as follows − - (return_type) method_name:( argumentType1 )argumentName1 joiningArgument2:( argumentType2 )argumentName2 ... joiningArgumentn:( argumentTypen )argumentNamen { body of the function } A method definition in Objective-C programming language consists of a method header and a method body. Here are all the parts of a method − Return Type − A method may return a value. The return_type is the data type of the value the function returns. Some methods perform the desired operations without returning a value. In this case, the return_type is the keyword void. Return Type − A method may return a value. The return_type is the data type of the value the function returns. Some methods perform the desired operations without returning a value. In this case, the return_type is the keyword void. Method Name − This is the actual name of the method. The method name and the parameter list together constitute the method signature. Method Name − This is the actual name of the method. The method name and the parameter list together constitute the method signature. Arguments − A argument is like a placeholder. When a function is invoked, you pass a value to the argument. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the arguments of a method. Arguments are optional; that is, a method may contain no argument. Arguments − A argument is like a placeholder. When a function is invoked, you pass a value to the argument. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the arguments of a method. Arguments are optional; that is, a method may contain no argument. Joining Argument − A joining argument is to make it easier to read and to make it clear while calling it. Joining Argument − A joining argument is to make it easier to read and to make it clear while calling it. Method Body − The method body contains a collection of statements that define what the method does. Method Body − The method body contains a collection of statements that define what the method does. Following is the source code for a method called max(). This method takes two parameters num1 and num2 and returns the maximum between the two − /* function returning the max between two numbers */ - (int) max:(int) num1 secondNumber:(int) num2 { /* local variable declaration */ int result; if (num1 > num2) { result = num1; } else { result = num2; } return result; } A method declaration tells the compiler about a function name and how to call the method. The actual body of the function can be defined separately. A method declaration has the following parts − - (return_type) function_name:( argumentType1 )argumentName1 joiningArgument2:( argumentType2 )argumentName2 ... joiningArgumentn:( argumentTypen )argumentNamen; For the above-defined function max(), following is the method declaration − -(int) max:(int)num1 andNum2:(int)num2; Method declaration is required when you define a method in one source file and you call that method in another file. In such case you should declare the function at the top of the file calling the function. While creating a Objective-C method, you give a definition of what the function has to do. To use a method, you will have to call that function to perform the defined task. When a program calls a function, program control is transferred to the called method. A called method performs defined task, and when its return statement is executed or when its function-ending closing brace is reached, it returns program control back to the main program. To call a method, you simply need to pass the required parameters along with method name, and if method returns a value, then you can store returned value. For example − #import <Foundation/Foundation.h> @interface SampleClass:NSObject /* method declaration */ - (int)max:(int)num1 andNum2:(int)num2; @end @implementation SampleClass /* method returning the max between two numbers */ - (int)max:(int)num1 andNum2:(int)num2 { /* local variable declaration */ int result; if (num1 > num2) { result = num1; } else { result = num2; } return result; } @end int main () { /* local variable definition */ int a = 100; int b = 200; int ret; SampleClass *sampleClass = [[SampleClass alloc]init]; /* calling a method to get max value */ ret = [sampleClass max:a andNum2:b]; NSLog(@"Max value is : %d\n", ret ); return 0; } I kept max() function along with main() function and complied the source code. While running final executable, it would produce the following result − 2013-09-07 22:28:45.912 demo[26080] Max value is : 200 If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function. The formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit. While calling a function, there are two ways that arguments can be passed to a function − This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument. This method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument. By default, Objective-C uses call by value to pass arguments. In general, this means that code within a function cannot alter the arguments used to call the function, and above-mentioned example while calling max() function used the same method. 18 Lectures 1 hours PARTHA MAJUMDAR 6 Lectures 25 mins Ken Burke Print Add Notes Bookmark this page
[ { "code": null, "e": 2759, "s": 2560, "text": "A function is a group of statements that together perform a task. Every Objective-C program has one C function, which is main(), and all of the most trivial programs can define additional functions." }, { "code": null, "e": 2961, "s": 2759, "text": "You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically the division usually is so each function performs a specific task." }, { "code": null, "e": 3121, "s": 2961, "text": "A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function." }, { "code": null, "e": 3179, "s": 3121, "text": "Basically in Objective-C, we call the function as method." }, { "code": null, "e": 3350, "s": 3179, "text": "The Objective-C foundation framework provides numerous built-in methods that your program can call. For example, method appendString() to append string to another string." }, { "code": null, "e": 3442, "s": 3350, "text": "A method is known with various names like a function or a sub-routine or a procedure, etc." }, { "code": null, "e": 3534, "s": 3442, "text": "The general form of a method definition in Objective-C programming language is as follows −" }, { "code": null, "e": 3723, "s": 3534, "text": "- (return_type) method_name:( argumentType1 )argumentName1 \njoiningArgument2:( argumentType2 )argumentName2 ... \njoiningArgumentn:( argumentTypen )argumentNamen {\n body of the function\n}" }, { "code": null, "e": 3863, "s": 3723, "text": "A method definition in Objective-C programming language consists of a method header and a method body. Here are all the parts of a method −" }, { "code": null, "e": 4096, "s": 3863, "text": "Return Type − A method may return a value. The return_type is the data type of the value the function returns. Some methods perform the desired operations without returning a value. In this case, the return_type is the keyword void." }, { "code": null, "e": 4329, "s": 4096, "text": "Return Type − A method may return a value. The return_type is the data type of the value the function returns. Some methods perform the desired operations without returning a value. In this case, the return_type is the keyword void." }, { "code": null, "e": 4463, "s": 4329, "text": "Method Name − This is the actual name of the method. The method name and the parameter list together constitute the method signature." }, { "code": null, "e": 4597, "s": 4463, "text": "Method Name − This is the actual name of the method. The method name and the parameter list together constitute the method signature." }, { "code": null, "e": 4918, "s": 4597, "text": "Arguments − A argument is like a placeholder. When a function is invoked, you pass a value to the argument. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the arguments of a method. Arguments are optional; that is, a method may contain no argument." }, { "code": null, "e": 5239, "s": 4918, "text": "Arguments − A argument is like a placeholder. When a function is invoked, you pass a value to the argument. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the arguments of a method. Arguments are optional; that is, a method may contain no argument." }, { "code": null, "e": 5345, "s": 5239, "text": "Joining Argument − A joining argument is to make it easier to read and to make it clear while calling it." }, { "code": null, "e": 5451, "s": 5345, "text": "Joining Argument − A joining argument is to make it easier to read and to make it clear while calling it." }, { "code": null, "e": 5551, "s": 5451, "text": "Method Body − The method body contains a collection of statements that define what the method does." }, { "code": null, "e": 5651, "s": 5551, "text": "Method Body − The method body contains a collection of statements that define what the method does." }, { "code": null, "e": 5796, "s": 5651, "text": "Following is the source code for a method called max(). This method takes two parameters num1 and num2 and returns the maximum between the two −" }, { "code": null, "e": 6059, "s": 5796, "text": "/* function returning the max between two numbers */\n- (int) max:(int) num1 secondNumber:(int) num2 {\n \n /* local variable declaration */\n int result;\n \n if (num1 > num2) {\n result = num1;\n } else {\n result = num2;\n }\n \n return result; \n}" }, { "code": null, "e": 6208, "s": 6059, "text": "A method declaration tells the compiler about a function name and how to call the method. The actual body of the function can be defined separately." }, { "code": null, "e": 6255, "s": 6208, "text": "A method declaration has the following parts −" }, { "code": null, "e": 6419, "s": 6255, "text": "- (return_type) function_name:( argumentType1 )argumentName1 \njoiningArgument2:( argumentType2 )argumentName2 ... \njoiningArgumentn:( argumentTypen )argumentNamen;" }, { "code": null, "e": 6495, "s": 6419, "text": "For the above-defined function max(), following is the method declaration −" }, { "code": null, "e": 6535, "s": 6495, "text": "-(int) max:(int)num1 andNum2:(int)num2;" }, { "code": null, "e": 6742, "s": 6535, "text": "Method declaration is required when you define a method in one source file and you call that method in another file. In such case you should declare the function at the top of the file calling the function." }, { "code": null, "e": 6915, "s": 6742, "text": "While creating a Objective-C method, you give a definition of what the function has to do. To use a method, you will have to call that function to perform the defined task." }, { "code": null, "e": 7189, "s": 6915, "text": "When a program calls a function, program control is transferred to the called method. A called method performs defined task, and when its return statement is executed or when its function-ending closing brace is reached, it returns program control back to the main program." }, { "code": null, "e": 7359, "s": 7189, "text": "To call a method, you simply need to pass the required parameters along with method name, and if method returns a value, then you can store returned value. For example −" }, { "code": null, "e": 8082, "s": 7359, "text": "#import <Foundation/Foundation.h>\n\n@interface SampleClass:NSObject\n/* method declaration */\n- (int)max:(int)num1 andNum2:(int)num2;\n@end\n\n@implementation SampleClass\n\n/* method returning the max between two numbers */\n- (int)max:(int)num1 andNum2:(int)num2 {\n\n /* local variable declaration */\n int result;\n \n if (num1 > num2) {\n result = num1;\n } else {\n result = num2;\n }\n \n return result; \n}\n\n@end\n\nint main () {\n \n /* local variable definition */\n int a = 100;\n int b = 200;\n int ret;\n \n SampleClass *sampleClass = [[SampleClass alloc]init];\n\n /* calling a method to get max value */\n ret = [sampleClass max:a andNum2:b];\n \n NSLog(@\"Max value is : %d\\n\", ret );\n return 0;\n}" }, { "code": null, "e": 8233, "s": 8082, "text": "I kept max() function along with main() function and complied the source code. While running final executable, it would produce the following result −" }, { "code": null, "e": 8289, "s": 8233, "text": "2013-09-07 22:28:45.912 demo[26080] Max value is : 200\n" }, { "code": null, "e": 8457, "s": 8289, "text": "If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function." }, { "code": null, "e": 8603, "s": 8457, "text": "The formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit." }, { "code": null, "e": 8693, "s": 8603, "text": "While calling a function, there are two ways that arguments can be passed to a function −" }, { "code": null, "e": 8883, "s": 8693, "text": "This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument." }, { "code": null, "e": 9112, "s": 8883, "text": "This method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument." }, { "code": null, "e": 9358, "s": 9112, "text": "By default, Objective-C uses call by value to pass arguments. In general, this means that code within a function cannot alter the arguments used to call the function, and above-mentioned example while calling max() function used the same method." }, { "code": null, "e": 9391, "s": 9358, "text": "\n 18 Lectures \n 1 hours \n" }, { "code": null, "e": 9408, "s": 9391, "text": " PARTHA MAJUMDAR" }, { "code": null, "e": 9439, "s": 9408, "text": "\n 6 Lectures \n 25 mins\n" }, { "code": null, "e": 9450, "s": 9439, "text": " Ken Burke" }, { "code": null, "e": 9457, "s": 9450, "text": " Print" }, { "code": null, "e": 9468, "s": 9457, "text": " Add Notes" } ]
C++ Boolean Expressions
A Boolean expression is a C++ expression that returns a boolean value: 1 (true) or 0 (false). You can use a comparison operator, such as the greater than (>) operator to find out if an expression (or a variable) is true: Or even easier: In the examples below, we use the equal to (==) operator to evaluate an expression: Booleans are the basis for all C++ comparisons and conditions. You will learn more about conditions (if...else) in the next chapter. Fill in the missing parts to print the values 1 (for true) and 0 (for false): isCodingFun = true; isFishTasty = false; cout << ; cout << ; Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 94, "s": 0, "text": "A Boolean expression is a C++ expression that returns a boolean value: 1 (true) or 0 (false)." }, { "code": null, "e": 221, "s": 94, "text": "You can use a comparison operator, such as the greater than (>) operator to find out if an expression (or a variable) is true:" }, { "code": null, "e": 237, "s": 221, "text": "Or even easier:" }, { "code": null, "e": 321, "s": 237, "text": "In the examples below, we use the equal to (==) operator to evaluate an expression:" }, { "code": null, "e": 384, "s": 321, "text": "Booleans are the basis for all C++ comparisons and conditions." }, { "code": null, "e": 454, "s": 384, "text": "You will learn more about conditions (if...else) in the next chapter." }, { "code": null, "e": 532, "s": 454, "text": "Fill in the missing parts to print the values 1 (for true) and 0 (for false):" }, { "code": null, "e": 596, "s": 532, "text": " isCodingFun = true;\n isFishTasty = false;\ncout << ;\ncout << ;\n" }, { "code": null, "e": 615, "s": 596, "text": "Start the Exercise" }, { "code": null, "e": 648, "s": 615, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 690, "s": 648, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 797, "s": 690, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 816, "s": 797, "text": "help@w3schools.com" } ]
Reading Keyboard Input in Python
Python provides two built-in functions to read a line of text from standard input, which by default comes from the keyboard. These functions are − raw_input input The raw_input([prompt]) function reads one line from standard input and returns it as a string (removing the trailing newline). #!/usr/bin/python str = raw_input("Enter your input: ") print "Received input is : ", str This prompts you to enter any string and it would display same string on the screen. When I typed "Hello Python!", its output is like this − Enter your input: Hello Python Received input is : Hello Python The input([prompt]) function is equivalent to raw_input, except that it assumes the input is a valid Python expression and returns the evaluated result to you. #!/usr/bin/python str = input("Enter your input: ") print "Received input is : ", str This would produce the following result against the entered input − Enter your input: [x*5 for x in range(2,10,2)] Recieved input is : [10, 20, 30, 40]
[ { "code": null, "e": 1209, "s": 1062, "text": "Python provides two built-in functions to read a line of text from standard input, which by default comes from the keyboard. These functions are −" }, { "code": null, "e": 1219, "s": 1209, "text": "raw_input" }, { "code": null, "e": 1225, "s": 1219, "text": "input" }, { "code": null, "e": 1353, "s": 1225, "text": "The raw_input([prompt]) function reads one line from standard input and returns it as a string (removing the trailing newline)." }, { "code": null, "e": 1443, "s": 1353, "text": "#!/usr/bin/python\nstr = raw_input(\"Enter your input: \")\nprint \"Received input is : \", str" }, { "code": null, "e": 1584, "s": 1443, "text": "This prompts you to enter any string and it would display same string on the screen. When I typed \"Hello Python!\", its output is like this −" }, { "code": null, "e": 1648, "s": 1584, "text": "Enter your input: Hello Python\nReceived input is : Hello Python" }, { "code": null, "e": 1808, "s": 1648, "text": "The input([prompt]) function is equivalent to raw_input, except that it assumes the input is a valid Python expression and returns the evaluated result to you." }, { "code": null, "e": 1894, "s": 1808, "text": "#!/usr/bin/python\nstr = input(\"Enter your input: \")\nprint \"Received input is : \", str" }, { "code": null, "e": 1962, "s": 1894, "text": "This would produce the following result against the entered input −" }, { "code": null, "e": 2046, "s": 1962, "text": "Enter your input: [x*5 for x in range(2,10,2)]\nRecieved input is : [10, 20, 30, 40]" } ]
Writing OS Independent Code in C/C++
A program that can interact with the operating system irrespective of the OS on which it runs. Most of the compilers of c/c++ have the power to define macros that detect OS. Some Macros of GCC compiler are − _WIN32: macros for 32 bit and 64-bit Windows OS. _WIN32: macros for 32 bit and 64-bit Windows OS. _WIN64: macros for 64-bit Windows OS. _WIN64: macros for 64-bit Windows OS. _UNIX: macros for UNIX OS. _UNIX: macros for UNIX OS. _APPLE_: macros for macOS. _APPLE_: macros for macOS. Based on these macros defined, let’s create a program that will work irrespective of the OS − Live Demo #include <iostream> using namespace std; int main() { #ifdef _WIN32 system("dir"); #else system("ls"); #endif return 0; } This lists all files of the directory to the output screen irrespective of OS.
[ { "code": null, "e": 1157, "s": 1062, "text": "A program that can interact with the operating system irrespective of the OS on which it runs." }, { "code": null, "e": 1236, "s": 1157, "text": "Most of the compilers of c/c++ have the power to define macros that detect OS." }, { "code": null, "e": 1270, "s": 1236, "text": "Some Macros of GCC compiler are −" }, { "code": null, "e": 1319, "s": 1270, "text": "_WIN32: macros for 32 bit and 64-bit Windows OS." }, { "code": null, "e": 1368, "s": 1319, "text": "_WIN32: macros for 32 bit and 64-bit Windows OS." }, { "code": null, "e": 1406, "s": 1368, "text": "_WIN64: macros for 64-bit Windows OS." }, { "code": null, "e": 1444, "s": 1406, "text": "_WIN64: macros for 64-bit Windows OS." }, { "code": null, "e": 1471, "s": 1444, "text": "_UNIX: macros for UNIX OS." }, { "code": null, "e": 1498, "s": 1471, "text": "_UNIX: macros for UNIX OS." }, { "code": null, "e": 1525, "s": 1498, "text": "_APPLE_: macros for macOS." }, { "code": null, "e": 1552, "s": 1525, "text": "_APPLE_: macros for macOS." }, { "code": null, "e": 1646, "s": 1552, "text": "Based on these macros defined, let’s create a program that will work irrespective of the OS −" }, { "code": null, "e": 1657, "s": 1646, "text": " Live Demo" }, { "code": null, "e": 1806, "s": 1657, "text": "#include <iostream>\nusing namespace std;\nint main() {\n #ifdef _WIN32\n system(\"dir\");\n #else\n system(\"ls\");\n #endif\n return 0;\n}" }, { "code": null, "e": 1885, "s": 1806, "text": "This lists all files of the directory to the output screen irrespective of OS." } ]
Rotate by 90 degree | Practice | GeeksforGeeks
Given a square matrix[][] of size N x N. The task is to rotate it by 90 degrees in an anti-clockwise direction without using any extra space. Example 1: Input: N = 3 matrix[][] = [[1 2 3], [4 5 6], [7 8 9]] Output: 3 6 9 2 5 8 1 4 7 Your Task: You only need to implement the given function rotate(). Do not read input, instead use the arguments given in the function. Expected Time Complexity: O(N*N) Expected Auxiliary Space: O(1) Constraints: 1 ≤ N ≤ 50 1 <= matrix[][] <= 100 +1 21ceuos083in 2 hours //C++ CODE void rotate(vector<vector<int> >& matrix){ int n = matrix.size(); vector<vector<int>> v{matrix}; for(int i = 0 ; i < n ; i++) { for(int j = 0 ; j < n ; j++) { v[i][j] = matrix[j][n-1-i]; } } for(int i = 0 ; i < n ; i++) { for(int j = 0 ; j < n ; j++) { matrix[i][j] = v[i][j]; } } } 0 tanashah1 day ago its 1 point question but you need to change approach https://practice.geeksforgeeks.org/problems/rotate-by-90-degree-1587115621/1/?page=1&difficulty[]=-1&difficulty[]=0&difficulty[]=1&difficulty[]=2&status[]=unsolved&category[]=Matrix&sortBy=submissions# +2 bhardwajji6 days ago void rotate(vector<vector<int> >& mat) { // step1 transpose // step2 interchange row from up and down int n = mat.size(); int m = mat[0].size(); for(int i=0 ;i<n;i++){ for(int j=0 ;j<i;j++){ swap(mat[i][j],mat[j][i]); } } for(int i=0;i<n/2;i++){ for(int j=0;j<m;j++){ swap(mat[i][j], mat[n-i-1][j]); } } } 0 illiyazzr2 weeks ago Easy C++ Solution in within main() function:-- int main(){ int r=3,c=3; int mat[r][c] = {{1,2,3}, {4,5,6}, {7,8,9}}; cout<<"Input matrix "<<endl<<endl; for(int i=0;i<r;i++){ for(int j=0;j<c;j++){ cout<<mat[i][j]<<" "; } cout<<endl; } cout<<endl; int transpose[r][c]; for(int i=0;i<r;i++){ for(int j=0;j<c;j++){ transpose[i][j] = mat[j][i]; } } cout<<"Transpose of the matrix "<<endl<<endl; for(int i=0;i<r;i++){ for(int j=0;j<c;j++){ cout<<transpose[i][j]<<" "; } cout<<endl; } cout<<endl; cout<<"Matrix rotated by 90 deg anti-clockwise"<<endl<<endl; int start = r-1; int end = 0; while(start>=end){ for(int i=0;i<c;i++){ cout<<transpose[start][i]<<" "; } start--; cout<<endl; }} 0 rashmit pankhania3 weeks ago guys simplest c++ solution 0.1 secs o(n**2) tc and o(1) sc idea is to rotate four corners of square(in inner loop) anticlockwise(given) and go to inside of matrix from outside in each iteration of outer loop simple :) void rotate(int n,int a[][n]) { int tl,tr,bl,br; for(int i=0;i<n;i++){ for(int j=i;j<n-i-1;j++){ tl=a[i][j]; // top left tr=a[j][n-i-1]; // top right br=a[n-i-1][n-j-1]; // bottom right bl=a[n-j-1][i]; // bottom left a[i][j] = tr; // tl becomes tr a[j][n-i-1] = br; // tr becomes br a[n-i-1][n-j-1] = bl; // br becomes bl a[n-j-1][i]=tl; // bl becomes tl } } } -1 gurucharanchouhan171 month ago Accepted Solution in java :) class GFG { static void rotate(int a[][]) { int n=a.length; int temp[][]=new int[n][n]; int k=0; for(int j=n-1;j>=0;j--,k++) { for(int i=0;i<n;i++) { temp[k][i]=a[i][j]; } } for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { a[i][j]=temp[i][j]; } } } } 0 bajpayeevinayak2281 month ago hello coder hope you are doing well this code is one of the simplest method hope you will understand easily you can ask doubt!! don't lose hope or don't give up this line is for me hahhaaa! // { Driver Code Starts//Initial template for C++ #include<bits/stdc++.h>using namespace std;void rotate (vector<vector<int> >& matrix); // } Driver Code Ends//User function template for C++ /* matrix : given input matrix, you are require to change it in place without using extra space */void rotate(vector<vector<int> >& matrix){ // Your code goes here int k=1; int j; int n=matrix.size(); for(int i=0;i<n;i++) { if(i==0) { j=0; } else{ j=i+1; } for(j;j<n;j++) { swap(matrix[i][j],matrix[j][i]);// arrange the rows into column which } } for(int col=0;col<n;col++) { for(int row=0;row<n/2;row++) { swap(matrix[row][col],matrix[n-row-1][col]);//swap every column elements } }} // { Driver Code Starts. int main(){ int t; cin>>t; while(t--) { int n; cin>>n; vector<vector<int> > matrix(n); for(int i=0; i<n; i++) { matrix[i].resize(n); for(int j=0; j<n; j++) cin>>matrix[i][j]; } rotate(matrix); for (int i = 0; i < n; ++i) { for(int j=0; j<n; j++) cout<<matrix[i][j]<<" "; cout<<"\n"; } } return 0;} // } Driver Code Ends 0 jayesh291 month ago Easy Java Solution class GFG{ static void rotate(int mat[][]) { tranpose(mat); for(int i=0;i<mat.length;i++){ rev(mat,i); } } static void rev(int[][] mat ,int c){ int lo = 0,hi=mat.length-1; while(lo<hi){ int temp = mat[lo][c]; mat[lo][c]=mat[hi][c]; mat[hi][c]=temp; lo++;hi--; } } static void tranpose(int [][] mat){ for(int i =0;i<mat.length;i++){ for(int j=i+1;j<mat.length;j++){ int temp = mat[i][j]; mat[i][j]=mat[j][i]; mat[j][i]=temp; } } } } 0 dsaconquered2 months ago Algo- first transpose the matrix then reverse individual column void transpose(vector<vector<int> >& matrix, int n) { // code here for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ swap(matrix[i][j],matrix[j][i]); } } }void rotate(vector<vector<int> >& matrix){ // Your code goes here int n=matrix.size(); transpose(matrix,n); for(int i=0;i<n;i++){ int low=0,high=n-1; while(low<high){ swap(matrix[low][i],matrix[high][i]); low++;high--; } } } 0 visveswar19012612 months ago #include<stdio.h>void rotate(int a[3][3]){int i,j;printf("The Matrix\n");for(i=0;i<3;i++){ for(j=0;j<3;j++) { printf("%2d",a[i][j]); } printf("\n");}printf("Transpose of Matrix\n");for(i=0;i<3;i++){ for(j=i;j<3;j++) { if(i!=j) { int t=a[i][j]; a[i][j]=a[j][i]; a[j][i]=t; } // printf("%d",a[i][j]); } //printf("\n");} for(i=0;i<3;i++){ for(j=0;j<3;j++) { printf("%2d",a[i][j]); } printf("\n");}printf("Rotation of the Matrix\n");for(i=0;i<3;i++){ for(j=i;j<3;j++) { if(i==0) { int t=a[i][j]; a[i][j]=a[i+2][j]; a[i+2][j]=t; } else { break; } }}for(i=0;i<3;i++){ for(j=0;j<3;j++) { printf("%2d",a[i][j]); } printf("\n");} }int main(){int a[3][3]= {{1 ,2, 3}, {4 ,5, 6}, {7,8,9}}; rotate(a); } 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": 380, "s": 238, "text": "Given a square matrix[][] of size N x N. The task is to rotate it by 90 degrees in an anti-clockwise direction without using any extra space." }, { "code": null, "e": 391, "s": 380, "text": "Example 1:" }, { "code": null, "e": 502, "s": 391, "text": "Input:\nN = 3\nmatrix[][] = [[1 2 3],\n [4 5 6],\n [7 8 9]]\nOutput:\n3 6 9 \n2 5 8 \n1 4 7\n" }, { "code": null, "e": 638, "s": 502, "text": "Your Task:\nYou only need to implement the given function rotate(). Do not read input, instead use the arguments given in the function. " }, { "code": null, "e": 702, "s": 638, "text": "Expected Time Complexity: O(N*N)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 749, "s": 702, "text": "Constraints:\n1 ≤ N ≤ 50\n1 <= matrix[][] <= 100" }, { "code": null, "e": 754, "s": 751, "text": "+1" }, { "code": null, "e": 775, "s": 754, "text": "21ceuos083in 2 hours" }, { "code": null, "e": 788, "s": 777, "text": "//C++ CODE" }, { "code": null, "e": 1149, "s": 788, "text": "void rotate(vector<vector<int> >& matrix){ int n = matrix.size(); vector<vector<int>> v{matrix}; for(int i = 0 ; i < n ; i++) { for(int j = 0 ; j < n ; j++) { v[i][j] = matrix[j][n-1-i]; } } for(int i = 0 ; i < n ; i++) { for(int j = 0 ; j < n ; j++) { matrix[i][j] = v[i][j]; } } }" }, { "code": null, "e": 1151, "s": 1149, "text": "0" }, { "code": null, "e": 1169, "s": 1151, "text": "tanashah1 day ago" }, { "code": null, "e": 1222, "s": 1169, "text": "its 1 point question but you need to change approach" }, { "code": null, "e": 1425, "s": 1222, "text": "https://practice.geeksforgeeks.org/problems/rotate-by-90-degree-1587115621/1/?page=1&difficulty[]=-1&difficulty[]=0&difficulty[]=1&difficulty[]=2&status[]=unsolved&category[]=Matrix&sortBy=submissions# " }, { "code": null, "e": 1430, "s": 1427, "text": "+2" }, { "code": null, "e": 1451, "s": 1430, "text": "bhardwajji6 days ago" }, { "code": null, "e": 1862, "s": 1451, "text": "void rotate(vector<vector<int> >& mat)\n{\n // step1 transpose\n // step2 interchange row from up and down \n \n int n = mat.size();\n int m = mat[0].size();\n \n for(int i=0 ;i<n;i++){\n for(int j=0 ;j<i;j++){\n swap(mat[i][j],mat[j][i]);\n }\n }\n \n for(int i=0;i<n/2;i++){\n for(int j=0;j<m;j++){\n swap(mat[i][j], mat[n-i-1][j]);\n }\n }\n \n}" }, { "code": null, "e": 1864, "s": 1862, "text": "0" }, { "code": null, "e": 1885, "s": 1864, "text": "illiyazzr2 weeks ago" }, { "code": null, "e": 1932, "s": 1885, "text": "Easy C++ Solution in within main() function:--" }, { "code": null, "e": 2728, "s": 1934, "text": "int main(){ int r=3,c=3; int mat[r][c] = {{1,2,3}, {4,5,6}, {7,8,9}}; cout<<\"Input matrix \"<<endl<<endl; for(int i=0;i<r;i++){ for(int j=0;j<c;j++){ cout<<mat[i][j]<<\" \"; } cout<<endl; } cout<<endl; int transpose[r][c]; for(int i=0;i<r;i++){ for(int j=0;j<c;j++){ transpose[i][j] = mat[j][i]; } } cout<<\"Transpose of the matrix \"<<endl<<endl; for(int i=0;i<r;i++){ for(int j=0;j<c;j++){ cout<<transpose[i][j]<<\" \"; } cout<<endl; } cout<<endl; cout<<\"Matrix rotated by 90 deg anti-clockwise\"<<endl<<endl; int start = r-1; int end = 0; while(start>=end){ for(int i=0;i<c;i++){ cout<<transpose[start][i]<<\" \"; } start--; cout<<endl; }}" }, { "code": null, "e": 2732, "s": 2730, "text": "0" }, { "code": null, "e": 2761, "s": 2732, "text": "rashmit pankhania3 weeks ago" }, { "code": null, "e": 2820, "s": 2761, "text": "guys simplest c++ solution 0.1 secs o(n**2) tc and o(1) sc" }, { "code": null, "e": 2898, "s": 2820, "text": "idea is to rotate four corners of square(in inner loop) anticlockwise(given) " }, { "code": null, "e": 2972, "s": 2900, "text": "and go to inside of matrix from outside in each iteration of outer loop" }, { "code": null, "e": 2984, "s": 2974, "text": "simple :)" }, { "code": null, "e": 3408, "s": 2984, "text": "void rotate(int n,int a[][n])\n{\n int tl,tr,bl,br;\n for(int i=0;i<n;i++){\n for(int j=i;j<n-i-1;j++){\n tl=a[i][j]; // top left\n tr=a[j][n-i-1]; // top right\n br=a[n-i-1][n-j-1]; // bottom right\n bl=a[n-j-1][i]; // bottom left\n \n a[i][j] = tr; // tl becomes tr\n a[j][n-i-1] = br; // tr becomes br\n a[n-i-1][n-j-1] = bl; // br becomes bl\n a[n-j-1][i]=tl; // bl becomes tl\n }\n }\n}" }, { "code": null, "e": 3411, "s": 3408, "text": "-1" }, { "code": null, "e": 3442, "s": 3411, "text": "gurucharanchouhan171 month ago" }, { "code": null, "e": 3473, "s": 3442, "text": "Accepted Solution in java :)" }, { "code": null, "e": 3913, "s": 3475, "text": "class GFG\n{\n static void rotate(int a[][]) \n {\n int n=a.length;\n \n int temp[][]=new int[n][n];\n \n int k=0;\n for(int j=n-1;j>=0;j--,k++)\n {\n for(int i=0;i<n;i++)\n {\n temp[k][i]=a[i][j];\n }\n }\n for(int i=0;i<n;i++)\n {\n for(int j=0;j<n;j++)\n {\n a[i][j]=temp[i][j];\n }\n }\n }\n}" }, { "code": null, "e": 3915, "s": 3913, "text": "0" }, { "code": null, "e": 3945, "s": 3915, "text": "bajpayeevinayak2281 month ago" }, { "code": null, "e": 4074, "s": 3945, "text": "hello coder hope you are doing well this code is one of the simplest method hope you will understand easily you can ask doubt!! " }, { "code": null, "e": 4136, "s": 4074, "text": "don't lose hope or don't give up this line is for me hahhaaa!" }, { "code": null, "e": 4186, "s": 4136, "text": "// { Driver Code Starts//Initial template for C++" }, { "code": null, "e": 4273, "s": 4186, "text": "#include<bits/stdc++.h>using namespace std;void rotate (vector<vector<int> >& matrix);" }, { "code": null, "e": 4327, "s": 4273, "text": "// } Driver Code Ends//User function template for C++" }, { "code": null, "e": 4942, "s": 4327, "text": "/* matrix : given input matrix, you are require to change it in place without using extra space */void rotate(vector<vector<int> >& matrix){ // Your code goes here int k=1; int j; int n=matrix.size(); for(int i=0;i<n;i++) { if(i==0) { j=0; } else{ j=i+1; } for(j;j<n;j++) { swap(matrix[i][j],matrix[j][i]);// arrange the rows into column which } } for(int col=0;col<n;col++) { for(int row=0;row<n/2;row++) { swap(matrix[row][col],matrix[n-row-1][col]);//swap every column elements } }}" }, { "code": null, "e": 4967, "s": 4942, "text": "// { Driver Code Starts." }, { "code": null, "e": 5408, "s": 4967, "text": "int main(){ int t; cin>>t; while(t--) { int n; cin>>n; vector<vector<int> > matrix(n); for(int i=0; i<n; i++) { matrix[i].resize(n); for(int j=0; j<n; j++) cin>>matrix[i][j]; } rotate(matrix); for (int i = 0; i < n; ++i) { for(int j=0; j<n; j++) cout<<matrix[i][j]<<\" \"; cout<<\"\\n\"; } } return 0;}" }, { "code": null, "e": 5431, "s": 5408, "text": " // } Driver Code Ends" }, { "code": null, "e": 5435, "s": 5433, "text": "0" }, { "code": null, "e": 5455, "s": 5435, "text": "jayesh291 month ago" }, { "code": null, "e": 5474, "s": 5455, "text": "Easy Java Solution" }, { "code": null, "e": 6126, "s": 5474, "text": "class GFG{\n static void rotate(int mat[][]) {\n tranpose(mat);\n for(int i=0;i<mat.length;i++){\n rev(mat,i);\n }\n }\n static void rev(int[][] mat ,int c){\n int lo = 0,hi=mat.length-1;\n while(lo<hi){\n int temp = mat[lo][c];\n mat[lo][c]=mat[hi][c];\n mat[hi][c]=temp;\n lo++;hi--;\n }\n }\n static void tranpose(int [][] mat){\n for(int i =0;i<mat.length;i++){\n for(int j=i+1;j<mat.length;j++){\n int temp = mat[i][j];\n mat[i][j]=mat[j][i];\n mat[j][i]=temp;\n }\n }\n }\n}" }, { "code": null, "e": 6128, "s": 6126, "text": "0" }, { "code": null, "e": 6153, "s": 6128, "text": "dsaconquered2 months ago" }, { "code": null, "e": 6159, "s": 6153, "text": "Algo-" }, { "code": null, "e": 6219, "s": 6159, "text": " first transpose the matrix then reverse individual column " }, { "code": null, "e": 6709, "s": 6221, "text": " void transpose(vector<vector<int> >& matrix, int n) { // code here for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ swap(matrix[i][j],matrix[j][i]); } } }void rotate(vector<vector<int> >& matrix){ // Your code goes here int n=matrix.size(); transpose(matrix,n); for(int i=0;i<n;i++){ int low=0,high=n-1; while(low<high){ swap(matrix[low][i],matrix[high][i]); low++;high--; } } }" }, { "code": null, "e": 6711, "s": 6709, "text": "0" }, { "code": null, "e": 6740, "s": 6711, "text": "visveswar19012612 months ago" }, { "code": null, "e": 7391, "s": 6740, "text": "#include<stdio.h>void rotate(int a[3][3]){int i,j;printf(\"The Matrix\\n\");for(i=0;i<3;i++){ for(j=0;j<3;j++) { printf(\"%2d\",a[i][j]); } printf(\"\\n\");}printf(\"Transpose of Matrix\\n\");for(i=0;i<3;i++){ for(j=i;j<3;j++) { if(i!=j) { int t=a[i][j]; a[i][j]=a[j][i]; a[j][i]=t; } // printf(\"%d\",a[i][j]); } //printf(\"\\n\");} for(i=0;i<3;i++){ for(j=0;j<3;j++) { printf(\"%2d\",a[i][j]); } printf(\"\\n\");}printf(\"Rotation of the Matrix\\n\");for(i=0;i<3;i++){ for(j=i;j<3;j++) { if(i==0) { int t=a[i][j]; a[i][j]=a[i+2][j]; a[i+2][j]=t; } else { break; } }}for(i=0;i<3;i++){ for(j=0;j<3;j++) { printf(\"%2d\",a[i][j]); } printf(\"\\n\");}" }, { "code": null, "e": 7473, "s": 7391, "text": "}int main(){int a[3][3]= {{1 ,2, 3}, {4 ,5, 6}, {7,8,9}};" }, { "code": null, "e": 7501, "s": 7473, "text": " rotate(a); }" }, { "code": null, "e": 7647, "s": 7501, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 7683, "s": 7647, "text": " Login to access your submissions. " }, { "code": null, "e": 7693, "s": 7683, "text": "\nProblem\n" }, { "code": null, "e": 7703, "s": 7693, "text": "\nContest\n" }, { "code": null, "e": 7766, "s": 7703, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 7914, "s": 7766, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 8122, "s": 7914, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 8228, "s": 8122, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
BabylonJS - Cameras
BabylonJS has many cameras that can be used. At a time, only one camera will be active for a scene. In this chapter, we will learn how to go about using cameras in BabylonJS. Let us now see how the FreeCamera works. Following is the syntax for the FreeCamera − var camera = new BABYLON.FreeCamera("FreeCamera", new BABYLON.Vector3(0, 1, -15), scene); This is the position in which the camera is placed - new BABYLON.Vector3(0, 1, -15). Changing the direction will change the direction. You can change the values and see how the camera behaves on the scene. Following are the parameters used by the FreeCamera − Name Position Scene This camera rotates around a given target pivot. It can be controlled with cursors and mouse, or with touch events. Parameters are name, alpha, beta, radius and target. var camera = new BABYLON.ArcRotateCamera("ArcRotateCamera", 1, 0.8, 10, new BABYLON.Vector3(0, 0, 0), scene); ArcRotateCamera points in the +x direction. To change the position of the camera, use the setPosition property. camera.setPosition(new BABYLON.Vector3(0, 0, -100)); The ArcRotateCamera is an excellent camera to animate. The following command will help you rotate the camera around the target − scene.activeCamera.alpha += .01; Touch is a type of a'gesture'. It can be on a pad or screen, with finger(s), stylus, glove, feet, or laser pointer. Any movement that can be sensed... can be considered a gesture. Following is the syntax for TouchCamera − var camera = new BABYLON.TouchCamera("TouchCamera", new BABYLON.Vector3(0, 1, -15), scene); This camera is specially designed to be used with gamepad. Following is the syntax for the Gamepad Camera − var camera = new BABYLON.GamepadCamera("Camera", new BABYLON.Vector3(0, 15, -45), scene); This camera is specially designed to react to device orientation events cases like when you tilt your device forward or backward, left or right, etc. var camera = new BABYLON.DeviceOrientationCamera("DevOr_camera", new BABYLON.Vector3(0, 1, -15), scene); FollowCamera is designed to follow any scene item with a position. It can follow from rear, front or from any angle. Following is the syntax for the FollowCamera − var camera = new BABYLON.FollowCamera("FollowCam", new BABYLON.Vector3(0, 15, -45), scene); This camera is designed to react to Virtual Joystick events. The Virtual Joysticks are on-screen 2D graphics that are used to control cameras or other scene items. Following is the syntax for the VirtualJoysticksCamera − var camera = new BABYLON.VirtualJoysticksCamera("VJ_camera", new BABYLON.Vector3(0, 1, -15), scene); The AnaglyphCamera is for use with red and cyan 3D glasses. It uses post-processing filtering techniques. Following is the syntax for the AnaglyphArcRotateCamera − var camera = new BABYLON.AnaglyphArcRotateCamera("aar_cam", -Math.PI/2, Math.PI/4, 20, new BABYLON.Vector3.Zero(), 0.033, scene); Following is the syntax for the AnaglyphFreeCamera − var camera = new BABYLON.AnaglyphFreeCamera("af_cam", new BABYLON.Vector3(0, 1, -15), 0.033, scene); The VRDeviceOrientationFreeCamera uses FreeCamera as its basis, so the properties and methods of FreeCamera are also found on our VRDeviceOrientationFreeCamera. Following is the syntax for the VRDeviceOrientationFreeCamera − var camera = new BABYLON.VRDeviceOrientationFreeCamera ("Camera", new BABYLON.Vector3 (-6.7, 1.2, -1.3), scene, 0); The WebVRFreeCamera uses FreeCamera as its basis, so the properties and methods of FreeCamera are also found on our WebVRFreeCamera. Following is the syntax for the WebVRFreeCamera − var camera = new BABYLON.WebVRFreeCamera("WVR", new BABYLON.Vector3(0, 1, -15), scene); In most of the demos, you will see attachControl where the camera is attached to the canvas. camera.attachControl(canvas, true); Print Add Notes Bookmark this page
[ { "code": null, "e": 2283, "s": 2183, "text": "BabylonJS has many cameras that can be used. At a time, only one camera will be active for a scene." }, { "code": null, "e": 2358, "s": 2283, "text": "In this chapter, we will learn how to go about using cameras in BabylonJS." }, { "code": null, "e": 2399, "s": 2358, "text": "Let us now see how the FreeCamera works." }, { "code": null, "e": 2444, "s": 2399, "text": "Following is the syntax for the FreeCamera −" }, { "code": null, "e": 2535, "s": 2444, "text": "var camera = new BABYLON.FreeCamera(\"FreeCamera\", new BABYLON.Vector3(0, 1, -15), scene);\n" }, { "code": null, "e": 2620, "s": 2535, "text": "This is the position in which the camera is placed - new BABYLON.Vector3(0, 1, -15)." }, { "code": null, "e": 2741, "s": 2620, "text": "Changing the direction will change the direction. You can change the values and see how the camera behaves on the scene." }, { "code": null, "e": 2795, "s": 2741, "text": "Following are the parameters used by the FreeCamera −" }, { "code": null, "e": 2800, "s": 2795, "text": "Name" }, { "code": null, "e": 2809, "s": 2800, "text": "Position" }, { "code": null, "e": 2815, "s": 2809, "text": "Scene" }, { "code": null, "e": 2984, "s": 2815, "text": "This camera rotates around a given target pivot. It can be controlled with cursors and mouse, or with touch events. Parameters are name, alpha, beta, radius and target." }, { "code": null, "e": 3095, "s": 2984, "text": "var camera = new BABYLON.ArcRotateCamera(\"ArcRotateCamera\", 1, 0.8, 10, new BABYLON.Vector3(0, 0, 0), scene);\n" }, { "code": null, "e": 3207, "s": 3095, "text": "ArcRotateCamera points in the +x direction. To change the position of the camera, use the setPosition property." }, { "code": null, "e": 3261, "s": 3207, "text": "camera.setPosition(new BABYLON.Vector3(0, 0, -100));\n" }, { "code": null, "e": 3390, "s": 3261, "text": "The ArcRotateCamera is an excellent camera to animate. The following command will help you rotate the camera around the target −" }, { "code": null, "e": 3424, "s": 3390, "text": "scene.activeCamera.alpha += .01;\n" }, { "code": null, "e": 3604, "s": 3424, "text": "Touch is a type of a'gesture'. It can be on a pad or screen, with finger(s), stylus, glove, feet, or laser pointer. Any movement that can be sensed... can be considered a gesture." }, { "code": null, "e": 3646, "s": 3604, "text": "Following is the syntax for TouchCamera −" }, { "code": null, "e": 3739, "s": 3646, "text": "var camera = new BABYLON.TouchCamera(\"TouchCamera\", new BABYLON.Vector3(0, 1, -15), scene);\n" }, { "code": null, "e": 3798, "s": 3739, "text": "This camera is specially designed to be used with gamepad." }, { "code": null, "e": 3847, "s": 3798, "text": "Following is the syntax for the Gamepad Camera −" }, { "code": null, "e": 3938, "s": 3847, "text": "var camera = new BABYLON.GamepadCamera(\"Camera\", new BABYLON.Vector3(0, 15, -45), scene);\n" }, { "code": null, "e": 4088, "s": 3938, "text": "This camera is specially designed to react to device orientation events cases like when you tilt your device forward or backward, left or right, etc." }, { "code": null, "e": 4194, "s": 4088, "text": "var camera = new BABYLON.DeviceOrientationCamera(\"DevOr_camera\", new BABYLON.Vector3(0, 1, -15), scene);\n" }, { "code": null, "e": 4311, "s": 4194, "text": "FollowCamera is designed to follow any scene item with a position. It can follow from rear, front or from any angle." }, { "code": null, "e": 4358, "s": 4311, "text": "Following is the syntax for the FollowCamera −" }, { "code": null, "e": 4451, "s": 4358, "text": "var camera = new BABYLON.FollowCamera(\"FollowCam\", new BABYLON.Vector3(0, 15, -45), scene);\n" }, { "code": null, "e": 4615, "s": 4451, "text": "This camera is designed to react to Virtual Joystick events. The Virtual Joysticks are on-screen 2D graphics that are used to control cameras or other scene items." }, { "code": null, "e": 4672, "s": 4615, "text": "Following is the syntax for the VirtualJoysticksCamera −" }, { "code": null, "e": 4774, "s": 4672, "text": "var camera = new BABYLON.VirtualJoysticksCamera(\"VJ_camera\", new BABYLON.Vector3(0, 1, -15), scene);\n" }, { "code": null, "e": 4880, "s": 4774, "text": "The AnaglyphCamera is for use with red and cyan 3D glasses. It uses post-processing filtering techniques." }, { "code": null, "e": 4938, "s": 4880, "text": "Following is the syntax for the AnaglyphArcRotateCamera −" }, { "code": null, "e": 5069, "s": 4938, "text": "var camera = new BABYLON.AnaglyphArcRotateCamera(\"aar_cam\", -Math.PI/2, Math.PI/4, 20, new BABYLON.Vector3.Zero(), 0.033, scene);\n" }, { "code": null, "e": 5122, "s": 5069, "text": "Following is the syntax for the AnaglyphFreeCamera −" }, { "code": null, "e": 5224, "s": 5122, "text": "var camera = new BABYLON.AnaglyphFreeCamera(\"af_cam\", new BABYLON.Vector3(0, 1, -15), 0.033, scene);\n" }, { "code": null, "e": 5385, "s": 5224, "text": "The VRDeviceOrientationFreeCamera uses FreeCamera as its basis, so the properties and methods of FreeCamera are also found on our VRDeviceOrientationFreeCamera." }, { "code": null, "e": 5449, "s": 5385, "text": "Following is the syntax for the VRDeviceOrientationFreeCamera −" }, { "code": null, "e": 5566, "s": 5449, "text": "var camera = new BABYLON.VRDeviceOrientationFreeCamera (\"Camera\", new BABYLON.Vector3 (-6.7, 1.2, -1.3), scene, 0);\n" }, { "code": null, "e": 5699, "s": 5566, "text": "The WebVRFreeCamera uses FreeCamera as its basis, so the properties and methods of FreeCamera are also found on our WebVRFreeCamera." }, { "code": null, "e": 5749, "s": 5699, "text": "Following is the syntax for the WebVRFreeCamera −" }, { "code": null, "e": 5838, "s": 5749, "text": "var camera = new BABYLON.WebVRFreeCamera(\"WVR\", new BABYLON.Vector3(0, 1, -15), scene);\n" }, { "code": null, "e": 5931, "s": 5838, "text": "In most of the demos, you will see attachControl where the camera is attached to the canvas." }, { "code": null, "e": 5968, "s": 5931, "text": "camera.attachControl(canvas, true);\n" }, { "code": null, "e": 5975, "s": 5968, "text": " Print" }, { "code": null, "e": 5986, "s": 5975, "text": " Add Notes" } ]
Arduino - Data Types
Data types in C refers to an extensive system used for declaring variables or functions of different types. The type of a variable determines how much space it occupies in the storage and how the bit pattern stored is interpreted. The following table provides all the data types that you will use during Arduino programming. The void keyword is used only in function declarations. It indicates that the function is expected to return no information to the function from which it was called. Void Loop ( ) { // rest of the code } A Boolean holds one of two values, true or false. Each Boolean variable occupies one byte of memory. boolean val = false ; // declaration of variable with type boolean and initialize it with false boolean state = true ; // declaration of variable with type boolean and initialize it with true A data type that takes up one byte of memory that stores a character value. Character literals are written in single quotes like this: 'A' and for multiple characters, strings use double quotes: "ABC". However, characters are stored as numbers. You can see the specific encoding in the ASCII chart. This means that it is possible to do arithmetic operations on characters, in which the ASCII value of the character is used. For example, 'A' + 1 has the value 66, since the ASCII value of the capital letter A is 65. Char chr_a = ‘a’ ;//declaration of variable with type char and initialize it with character a Char chr_c = 97 ;//declaration of variable with type char and initialize it with character 97 Unsigned char is an unsigned data type that occupies one byte of memory. The unsigned char data type encodes numbers from 0 to 255. Unsigned Char chr_y = 121 ; // declaration of variable with type Unsigned char and initialize it with character y A byte stores an 8-bit unsigned number, from 0 to 255. byte m = 25 ;//declaration of variable with type byte and initialize it with 25 Integers are the primary data-type for number storage. int stores a 16-bit (2-byte) value. This yields a range of -32,768 to 32,767 (minimum value of -2^15 and a maximum value of (2^15) - 1). The int size varies from board to board. On the Arduino Due, for example, an int stores a 32-bit (4-byte) value. This yields a range of -2,147,483,648 to 2,147,483,647 (minimum value of -2^31 and a maximum value of (2^31) - 1). int counter = 32 ;// declaration of variable with type int and initialize it with 32 Unsigned ints (unsigned integers) are the same as int in the way that they store a 2 byte value. Instead of storing negative numbers, however, they only store positive values, yielding a useful range of 0 to 65,535 (2^16) - 1). The Due stores a 4 byte (32-bit) value, ranging from 0 to 4,294,967,295 (2^32 - 1). Unsigned int counter = 60 ; // declaration of variable with type unsigned int and initialize it with 60 On the Uno and other ATMEGA based boards, a word stores a 16-bit unsigned number. On the Due and Zero, it stores a 32-bit unsigned number. word w = 1000 ;//declaration of variable with type word and initialize it with 1000 Long variables are extended size variables for number storage, and store 32 bits (4 bytes), from -2,147,483,648 to 2,147,483,647. Long velocity = 102346 ;//declaration of variable with type Long and initialize it with 102346 Unsigned long variables are extended size variables for number storage and store 32 bits (4 bytes). Unlike standard longs, unsigned longs will not store negative numbers, making their range from 0 to 4,294,967,295 (2^32 - 1). Unsigned Long velocity = 101006 ;// declaration of variable with type Unsigned Long and initialize it with 101006 A short is a 16-bit data-type. On all Arduinos (ATMega and ARM based), a short stores a 16-bit (2-byte) value. This yields a range of -32,768 to 32,767 (minimum value of -2^15 and a maximum value of (2^15) - 1). short val = 13 ;//declaration of variable with type short and initialize it with 13 Data type for floating-point number is a number that has a decimal point. Floating-point numbers are often used to approximate the analog and continuous values because they have greater resolution than integers. Floating-point numbers can be as large as 3.4028235E+38 and as low as -3.4028235E+38. They are stored as 32 bits (4 bytes) of information. float num = 1.352;//declaration of variable with type float and initialize it with 1.352 On the Uno and other ATMEGA based boards, Double precision floating-point number occupies four bytes. That is, the double implementation is exactly the same as the float, with no gain in precision. On the Arduino Due, doubles have 8-byte (64 bit) precision. double num = 45.352 ;// declaration of variable with type double and initialize it with 45.352 65 Lectures 6.5 hours Amit Rana 43 Lectures 3 hours Amit Rana 20 Lectures 2 hours Ashraf Said 19 Lectures 1.5 hours Ashraf Said 11 Lectures 47 mins Ashraf Said 9 Lectures 41 mins Ashraf Said Print Add Notes Bookmark this page
[ { "code": null, "e": 3101, "s": 2870, "text": "Data types in C refers to an extensive system used for declaring variables or functions of different types. The type of a variable determines how much space it occupies in the storage and how the bit pattern stored is interpreted." }, { "code": null, "e": 3195, "s": 3101, "text": "The following table provides all the data types that you will use during Arduino programming." }, { "code": null, "e": 3361, "s": 3195, "text": "The void keyword is used only in function declarations. It indicates that the function is expected to return no information to the function from which it was called." }, { "code": null, "e": 3403, "s": 3361, "text": "Void Loop ( ) {\n // rest of the code\n}\n" }, { "code": null, "e": 3504, "s": 3403, "text": "A Boolean holds one of two values, true or false. Each Boolean variable occupies one byte of memory." }, { "code": null, "e": 3697, "s": 3504, "text": "boolean val = false ; // declaration of variable with type boolean and initialize it with false\nboolean state = true ; // declaration of variable with type boolean and initialize it with true\n" }, { "code": null, "e": 3899, "s": 3697, "text": "A data type that takes up one byte of memory that stores a character value. Character literals are written in single quotes like this: 'A' and for multiple characters, strings use double quotes: \"ABC\"." }, { "code": null, "e": 4213, "s": 3899, "text": "However, characters are stored as numbers. You can see the specific encoding in the ASCII chart. This means that it is possible to do arithmetic operations on characters, in which the ASCII value of the character is used. For example, 'A' + 1 has the value 66, since the ASCII value of the capital letter A is 65." }, { "code": null, "e": 4402, "s": 4213, "text": "Char chr_a = ‘a’ ;//declaration of variable with type char and initialize it with character a\nChar chr_c = 97 ;//declaration of variable with type char and initialize it with character 97\n" }, { "code": null, "e": 4534, "s": 4402, "text": "Unsigned char is an unsigned data type that occupies one byte of memory. The unsigned char data type encodes numbers from 0 to 255." }, { "code": null, "e": 4649, "s": 4534, "text": "Unsigned Char chr_y = 121 ; // declaration of variable with type Unsigned char and initialize it with character y\n" }, { "code": null, "e": 4704, "s": 4649, "text": "A byte stores an 8-bit unsigned number, from 0 to 255." }, { "code": null, "e": 4785, "s": 4704, "text": "byte m = 25 ;//declaration of variable with type byte and initialize it with 25\n" }, { "code": null, "e": 4977, "s": 4785, "text": "Integers are the primary data-type for number storage. int stores a 16-bit (2-byte) value. This yields a range of -32,768 to 32,767 (minimum value of -2^15 and a maximum value of (2^15) - 1)." }, { "code": null, "e": 5205, "s": 4977, "text": "The int size varies from board to board. On the Arduino Due, for example, an int stores a 32-bit (4-byte) value. This yields a range of -2,147,483,648 to 2,147,483,647 (minimum value of -2^31 and a maximum value of (2^31) - 1)." }, { "code": null, "e": 5291, "s": 5205, "text": "int counter = 32 ;// declaration of variable with type int and initialize it with 32\n" }, { "code": null, "e": 5603, "s": 5291, "text": "Unsigned ints (unsigned integers) are the same as int in the way that they store a 2 byte value. Instead of storing negative numbers, however, they only store positive values, yielding a useful range of 0 to 65,535 (2^16) - 1). The Due stores a 4 byte (32-bit) value, ranging from 0 to 4,294,967,295 (2^32 - 1)." }, { "code": null, "e": 5712, "s": 5603, "text": "Unsigned int counter = 60 ; // declaration of variable with \n type unsigned int and initialize it with 60\n" }, { "code": null, "e": 5851, "s": 5712, "text": "On the Uno and other ATMEGA based boards, a word stores a 16-bit unsigned number. On the Due and Zero, it stores a 32-bit unsigned number." }, { "code": null, "e": 5936, "s": 5851, "text": "word w = 1000 ;//declaration of variable with type word and initialize it with 1000\n" }, { "code": null, "e": 6066, "s": 5936, "text": "Long variables are extended size variables for number storage, and store 32 bits (4 bytes), from -2,147,483,648 to 2,147,483,647." }, { "code": null, "e": 6162, "s": 6066, "text": "Long velocity = 102346 ;//declaration of variable with type Long and initialize it with 102346\n" }, { "code": null, "e": 6388, "s": 6162, "text": "Unsigned long variables are extended size variables for number storage and store 32 bits (4 bytes). Unlike standard longs, unsigned longs will not store negative numbers, making their range from 0 to 4,294,967,295 (2^32 - 1)." }, { "code": null, "e": 6507, "s": 6388, "text": "Unsigned Long velocity = 101006 ;// declaration of variable with \n type Unsigned Long and initialize it with 101006\n" }, { "code": null, "e": 6719, "s": 6507, "text": "A short is a 16-bit data-type. On all Arduinos (ATMega and ARM based), a short stores a 16-bit (2-byte) value. This yields a range of -32,768 to 32,767 (minimum value of -2^15 and a maximum value of (2^15) - 1)." }, { "code": null, "e": 6804, "s": 6719, "text": "short val = 13 ;//declaration of variable with type short and initialize it with 13\n" }, { "code": null, "e": 7016, "s": 6804, "text": "Data type for floating-point number is a number that has a decimal point. Floating-point numbers are often used to approximate the analog and continuous values because they have greater resolution than integers." }, { "code": null, "e": 7155, "s": 7016, "text": "Floating-point numbers can be as large as 3.4028235E+38 and as low as -3.4028235E+38. They are stored as 32 bits (4 bytes) of information." }, { "code": null, "e": 7245, "s": 7155, "text": "float num = 1.352;//declaration of variable with type float and initialize it with 1.352\n" }, { "code": null, "e": 7503, "s": 7245, "text": "On the Uno and other ATMEGA based boards, Double precision floating-point number occupies four bytes. That is, the double implementation is exactly the same as the float, with no gain in precision. On the Arduino Due, doubles have 8-byte (64 bit) precision." }, { "code": null, "e": 7599, "s": 7503, "text": "double num = 45.352 ;// declaration of variable with type double and initialize it with 45.352\n" }, { "code": null, "e": 7634, "s": 7599, "text": "\n 65 Lectures \n 6.5 hours \n" }, { "code": null, "e": 7645, "s": 7634, "text": " Amit Rana" }, { "code": null, "e": 7678, "s": 7645, "text": "\n 43 Lectures \n 3 hours \n" }, { "code": null, "e": 7689, "s": 7678, "text": " Amit Rana" }, { "code": null, "e": 7722, "s": 7689, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 7735, "s": 7722, "text": " Ashraf Said" }, { "code": null, "e": 7770, "s": 7735, "text": "\n 19 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7783, "s": 7770, "text": " Ashraf Said" }, { "code": null, "e": 7815, "s": 7783, "text": "\n 11 Lectures \n 47 mins\n" }, { "code": null, "e": 7828, "s": 7815, "text": " Ashraf Said" }, { "code": null, "e": 7859, "s": 7828, "text": "\n 9 Lectures \n 41 mins\n" }, { "code": null, "e": 7872, "s": 7859, "text": " Ashraf Said" }, { "code": null, "e": 7879, "s": 7872, "text": " Print" }, { "code": null, "e": 7890, "s": 7879, "text": " Add Notes" } ]
What are the differences between public, protected and private access specifiers in C#?
Public access specifier allows a class to expose its member variables and member functions to other functions and objects. Any public member can be accessed from outside the class. Live Demo using System; namespace Demo { class Rectangle { public double length; public double width; public double GetArea() { return length * width; } public void Display() { Console.WriteLine("Length: {0}", length); Console.WriteLine("Width: {0}", width); Console.WriteLine("Area: {0}", GetArea()); } } //end class Rectangle class ExecuteRectangle { static void Main(string[] args) { Rectangle r = new Rectangle(); r.length = 7; r.width = 10; r.Display(); Console.ReadLine(); } } } Length: 7 Width: 10 Area: 70 Protected access specifier allows a child class to access the member variables and member functions of its base class. Let us see an example of protected access modifier, accessing the protected members. Live Demo using System; namespace MySpecifiers { class Demo { protected string name = "Website"; protected void Display(string str) { Console.WriteLine("Tabs: " + str); } } class Test : Demo { static void Main(string[] args) { Test t = new Test(); Console.WriteLine("Details: " + t.name); t.Display("Product"); t.Display("Services"); t.Display("Tools"); t.Display("Plugins"); } } } Details: Website Tabs: Product Tabs: Services Tabs: Tools Tabs: Plugins Private access specifier allows a class to hide its member variables and member functions from other functions and objects. Only functions of the same class can access its private members. Even an instance of a class cannot access its private members. Live Demo using System; namespace Demo { class Rectangle { //member variables private double length; private double width; public void Acceptdetails() { length = 10; width = 15; } public double GetArea() { return length * width; } public void Display() { Console.WriteLine("Length: {0}", length); Console.WriteLine("Width: {0}", width); Console.WriteLine("Area: {0}", GetArea()); } }//end class Rectangle class ExecuteRectangle { static void Main(string[] args) { Rectangle r = new Rectangle(); r.Acceptdetails(); r.Display(); Console.ReadLine(); } } } Length: 10 Width: 15 Area: 150
[ { "code": null, "e": 1243, "s": 1062, "text": "Public access specifier allows a class to expose its member variables and member functions to other functions and objects. Any public member can be accessed from outside the class." }, { "code": null, "e": 1254, "s": 1243, "text": " Live Demo" }, { "code": null, "e": 1872, "s": 1254, "text": "using System;\nnamespace Demo {\n class Rectangle {\n public double length;\n public double width;\n public double GetArea() {\n return length * width;\n } \n public void Display() {\n Console.WriteLine(\"Length: {0}\", length);\n Console.WriteLine(\"Width: {0}\", width);\n Console.WriteLine(\"Area: {0}\", GetArea());\n }\n } //end class Rectangle\n class ExecuteRectangle {\n static void Main(string[] args) {\n Rectangle r = new Rectangle();\n r.length = 7;\n r.width = 10;\n r.Display();\n Console.ReadLine();\n }\n }\n}" }, { "code": null, "e": 1901, "s": 1872, "text": "Length: 7\nWidth: 10\nArea: 70" }, { "code": null, "e": 2020, "s": 1901, "text": "Protected access specifier allows a child class to access the member variables and member functions of its base class." }, { "code": null, "e": 2105, "s": 2020, "text": "Let us see an example of protected access modifier, accessing the protected members." }, { "code": null, "e": 2116, "s": 2105, "text": " Live Demo" }, { "code": null, "e": 2593, "s": 2116, "text": "using System;\nnamespace MySpecifiers {\n class Demo {\n protected string name = \"Website\";\n protected void Display(string str) {\n Console.WriteLine(\"Tabs: \" + str);\n }\n }\n class Test : Demo {\n static void Main(string[] args) {\n Test t = new Test();\n Console.WriteLine(\"Details: \" + t.name);\n t.Display(\"Product\");\n t.Display(\"Services\");\n t.Display(\"Tools\");\n t.Display(\"Plugins\");\n }\n }\n}" }, { "code": null, "e": 2665, "s": 2593, "text": "Details: Website\nTabs: Product\nTabs: Services\nTabs: Tools\nTabs: Plugins" }, { "code": null, "e": 2917, "s": 2665, "text": "Private access specifier allows a class to hide its member variables and member functions from other functions and objects. Only functions of the same class can access its private members. Even an instance of a class cannot access its private members." }, { "code": null, "e": 2928, "s": 2917, "text": " Live Demo" }, { "code": null, "e": 3641, "s": 2928, "text": "using System;\nnamespace Demo {\n class Rectangle {\n //member variables\n private double length;\n private double width;\n public void Acceptdetails() {\n length = 10;\n width = 15;\n }\n public double GetArea() {\n return length * width;\n }\n public void Display() {\n Console.WriteLine(\"Length: {0}\", length);\n Console.WriteLine(\"Width: {0}\", width);\n Console.WriteLine(\"Area: {0}\", GetArea());\n }\n }//end class Rectangle\n class ExecuteRectangle {\n static void Main(string[] args) {\n Rectangle r = new Rectangle();\n r.Acceptdetails();\n r.Display();\n Console.ReadLine();\n } \n }\n}" }, { "code": null, "e": 3672, "s": 3641, "text": "Length: 10\nWidth: 15\nArea: 150" } ]
How to Print the Next N Leap Years in Java? - GeeksforGeeks
28 May, 2021 Concept: The basic assertion in problem-solving for the leap year is an interval of 4 years which is wrong in itself. For any random year in the calendar to be a leap year it must hold below conditions. Now if the year is a leap year the goal is simply to print the consecutive same kinds of years in a calendar year that is all years should be leap year prior or adhering the leap year to be taken into consideration to illustrate and implement the same. Approach: Problem-solving is simple to break into two halves. The first half is the focus to figure out a leap year or not and writing the code for the same. The second half simply emphasis to maintain a count whenever leap year is encountered and synchronized with the first half. Mandatory conditions to be satisfied for a year to refer as a leap year The year should be multiple of 400. The year should be a multiple of 4 and should not a multiple of 100. Algorithm: Condition checking divisibility with 4- If the number is divisible by 4 the check will proceed further and if the number is not divisible by 4 then for sure not a leap year.Condition checking divisibility with 100-The year obtained here is already divisible by 4.Now further if the year satisfies the above condition then if the year is divisible by 100, the year proceeds for further conditionality check. If the number is not divisible by 100 then for sure not a leap year.Condition checking divisibility with 400- The year obtained here is already divisible by 4 and 100. Now further if the year is divisible by 400 then for sure a leap year else for sure not a leap year.As of now the year obtained here is a Leap year, the approach to print leap year is very simpleInitializing a variable with zero to maintain lap year countIncrementing the count when it is for sure that the year is a leap yearIterating taking count into consideration for condition statement and where the condition fails out simply return all the years that satisfied the condition previously. Condition checking divisibility with 4- If the number is divisible by 4 the check will proceed further and if the number is not divisible by 4 then for sure not a leap year. Condition checking divisibility with 100-The year obtained here is already divisible by 4.Now further if the year satisfies the above condition then if the year is divisible by 100, the year proceeds for further conditionality check. If the number is not divisible by 100 then for sure not a leap year. Condition checking divisibility with 400- The year obtained here is already divisible by 4 and 100. Now further if the year is divisible by 400 then for sure a leap year else for sure not a leap year. As of now the year obtained here is a Leap year, the approach to print leap year is very simpleInitializing a variable with zero to maintain lap year countIncrementing the count when it is for sure that the year is a leap yearIterating taking count into consideration for condition statement and where the condition fails out simply return all the years that satisfied the condition previously. Initializing a variable with zero to maintain lap year count Incrementing the count when it is for sure that the year is a leap year Iterating taking count into consideration for condition statement and where the condition fails out simply return all the years that satisfied the condition previously. Illustration: Input 1: year = 2020, N = 15 Output: 2024 2028 2032 2036 2040 2044 2048 2052 2056 2060 2064 2068 2072 2076 2080 Input 2: year = 2022, N = 2 Output: 2024 2028 Implementation: Below is the example to illustrate the above illustration in Java: Java // Java program to print the next n leap years // Importing generic Classes/Filesimport java.io.*; class GFG { // Main driver method public static void main(String[] args) { // Considering current year & initializing same int year = 2020; // Considering user entered custom leap year int n = 15; // n is the no of leap years after year 2020 // that is needed to print int count = 0; // Creating and initializing a variable // to maintain count of leap years while (count != n) // Conditionality check- Count variable should never // equals number of leap years to be printed { year = year + 1; // Incrementing the year count by 1 if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0)) { // If the year is leap year,then increment // the count count++; // Print the leap year System.out.println(year); } } }} 2024 2028 2032 2036 2040 2044 2048 2052 2056 2060 2064 2068 2072 2076 2080 gabaa406 Technical Scripter 2020 Java Java Programs Technical Scripter 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 Convert a String to Character array in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Factory method design pattern in Java
[ { "code": null, "e": 23557, "s": 23529, "text": "\n28 May, 2021" }, { "code": null, "e": 24013, "s": 23557, "text": "Concept: The basic assertion in problem-solving for the leap year is an interval of 4 years which is wrong in itself. For any random year in the calendar to be a leap year it must hold below conditions. Now if the year is a leap year the goal is simply to print the consecutive same kinds of years in a calendar year that is all years should be leap year prior or adhering the leap year to be taken into consideration to illustrate and implement the same." }, { "code": null, "e": 24295, "s": 24013, "text": "Approach: Problem-solving is simple to break into two halves. The first half is the focus to figure out a leap year or not and writing the code for the same. The second half simply emphasis to maintain a count whenever leap year is encountered and synchronized with the first half." }, { "code": null, "e": 24367, "s": 24295, "text": "Mandatory conditions to be satisfied for a year to refer as a leap year" }, { "code": null, "e": 24403, "s": 24367, "text": "The year should be multiple of 400." }, { "code": null, "e": 24472, "s": 24403, "text": "The year should be a multiple of 4 and should not a multiple of 100." }, { "code": null, "e": 24484, "s": 24472, "text": "Algorithm: " }, { "code": null, "e": 25554, "s": 24484, "text": "Condition checking divisibility with 4- If the number is divisible by 4 the check will proceed further and if the number is not divisible by 4 then for sure not a leap year.Condition checking divisibility with 100-The year obtained here is already divisible by 4.Now further if the year satisfies the above condition then if the year is divisible by 100, the year proceeds for further conditionality check. If the number is not divisible by 100 then for sure not a leap year.Condition checking divisibility with 400- The year obtained here is already divisible by 4 and 100. Now further if the year is divisible by 400 then for sure a leap year else for sure not a leap year.As of now the year obtained here is a Leap year, the approach to print leap year is very simpleInitializing a variable with zero to maintain lap year countIncrementing the count when it is for sure that the year is a leap yearIterating taking count into consideration for condition statement and where the condition fails out simply return all the years that satisfied the condition previously." }, { "code": null, "e": 25728, "s": 25554, "text": "Condition checking divisibility with 4- If the number is divisible by 4 the check will proceed further and if the number is not divisible by 4 then for sure not a leap year." }, { "code": null, "e": 26031, "s": 25728, "text": "Condition checking divisibility with 100-The year obtained here is already divisible by 4.Now further if the year satisfies the above condition then if the year is divisible by 100, the year proceeds for further conditionality check. If the number is not divisible by 100 then for sure not a leap year." }, { "code": null, "e": 26232, "s": 26031, "text": "Condition checking divisibility with 400- The year obtained here is already divisible by 4 and 100. Now further if the year is divisible by 400 then for sure a leap year else for sure not a leap year." }, { "code": null, "e": 26627, "s": 26232, "text": "As of now the year obtained here is a Leap year, the approach to print leap year is very simpleInitializing a variable with zero to maintain lap year countIncrementing the count when it is for sure that the year is a leap yearIterating taking count into consideration for condition statement and where the condition fails out simply return all the years that satisfied the condition previously." }, { "code": null, "e": 26688, "s": 26627, "text": "Initializing a variable with zero to maintain lap year count" }, { "code": null, "e": 26760, "s": 26688, "text": "Incrementing the count when it is for sure that the year is a leap year" }, { "code": null, "e": 26929, "s": 26760, "text": "Iterating taking count into consideration for condition statement and where the condition fails out simply return all the years that satisfied the condition previously." }, { "code": null, "e": 26943, "s": 26929, "text": "Illustration:" }, { "code": null, "e": 27224, "s": 26943, "text": "Input 1: year = 2020, N = 15\nOutput: 2024\n 2028\n 2032\n 2036\n 2040\n 2044\n 2048\n 2052\n 2056\n 2060\n 2064\n 2068\n 2072\n 2076\n 2080\n \nInput 2: year = 2022, N = 2\nOutput: 2024\n 2028" }, { "code": null, "e": 27307, "s": 27224, "text": "Implementation: Below is the example to illustrate the above illustration in Java:" }, { "code": null, "e": 27312, "s": 27307, "text": "Java" }, { "code": "// Java program to print the next n leap years // Importing generic Classes/Filesimport java.io.*; class GFG { // Main driver method public static void main(String[] args) { // Considering current year & initializing same int year = 2020; // Considering user entered custom leap year int n = 15; // n is the no of leap years after year 2020 // that is needed to print int count = 0; // Creating and initializing a variable // to maintain count of leap years while (count != n) // Conditionality check- Count variable should never // equals number of leap years to be printed { year = year + 1; // Incrementing the year count by 1 if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0)) { // If the year is leap year,then increment // the count count++; // Print the leap year System.out.println(year); } } }}", "e": 28378, "s": 27312, "text": null }, { "code": null, "e": 28453, "s": 28378, "text": "2024\n2028\n2032\n2036\n2040\n2044\n2048\n2052\n2056\n2060\n2064\n2068\n2072\n2076\n2080" }, { "code": null, "e": 28464, "s": 28455, "text": "gabaa406" }, { "code": null, "e": 28488, "s": 28464, "text": "Technical Scripter 2020" }, { "code": null, "e": 28493, "s": 28488, "text": "Java" }, { "code": null, "e": 28507, "s": 28493, "text": "Java Programs" }, { "code": null, "e": 28526, "s": 28507, "text": "Technical Scripter" }, { "code": null, "e": 28531, "s": 28526, "text": "Java" }, { "code": null, "e": 28629, "s": 28531, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28638, "s": 28629, "text": "Comments" }, { "code": null, "e": 28651, "s": 28638, "text": "Old Comments" }, { "code": null, "e": 28681, "s": 28651, "text": "Functional Interfaces in Java" }, { "code": null, "e": 28696, "s": 28681, "text": "Stream In Java" }, { "code": null, "e": 28717, "s": 28696, "text": "Constructors in Java" }, { "code": null, "e": 28763, "s": 28717, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 28782, "s": 28763, "text": "Exceptions in Java" }, { "code": null, "e": 28826, "s": 28782, "text": "Convert a String to Character array in Java" }, { "code": null, "e": 28852, "s": 28826, "text": "Java Programming Examples" }, { "code": null, "e": 28886, "s": 28852, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 28933, "s": 28886, "text": "Implementing a Linked List in Java using Class" } ]
Tryit Editor v3.7
HTML Computer Code Tryit: HTML var element
[ { "code": null, "e": 29, "s": 10, "text": "HTML Computer Code" } ]
Teradata - JOIN Index
JOIN INDEX is a materialized view. Its definition is permanently stored and the data is updated whenever the base tables referred in the join index is updated. JOIN INDEX may contain one or more tables and also contain pre-aggregated data. Join indexes are mainly used for improving the performance. There are different types of join indexes available. Single Table Join Index (STJI) Multi Table Join Index (MTJI) Aggregated Join Index (AJI) Single Table Join index allows to partition a large table based on the different primary index columns than the one from the base table. Following is the syntax of a JOIN INDEX. CREATE JOIN INDEX <index name> AS <SELECT Query> <Index Definition>; Consider the following Employee and Salary tables. CREATE SET TABLE EMPLOYEE,FALLBACK ( EmployeeNo INTEGER, FirstName VARCHAR(30) , LastName VARCHAR(30) , DOB DATE FORMAT 'YYYY-MM-DD', JoinedDate DATE FORMAT 'YYYY-MM-DD', DepartmentNo BYTEINT ) UNIQUE PRIMARY INDEX ( EmployeeNo ); CREATE SET TABLE SALARY,FALLBACK ( EmployeeNo INTEGER, Gross INTEGER, Deduction INTEGER, NetPay INTEGER ) PRIMARY INDEX ( EmployeeNo ) UNIQUE INDEX (EmployeeNo); Following is an example that creates a Join index named Employee_JI on Employee table. CREATE JOIN INDEX Employee_JI AS SELECT EmployeeNo,FirstName,LastName, BirthDate,JoinedDate,DepartmentNo FROM Employee PRIMARY INDEX(FirstName); If the user submits a query with a WHERE clause on EmployeeNo, then the system will query the Employee table using the unique primary index. If the user queries the employee table using employee_name, then the system may access the join index Employee_JI using employee_name. The rows of the join index are hashed on employee_name column. If the join index is not defined and the employee_name is not defined as secondary index, then the system will perform full table scan to access the rows which is time consuming. You can run the following EXPLAIN plan and verify the optimizer plan. In the following example you can see that the optimizer is using the Join Index instead of base Employee table when the table queries using the Employee_Name column. EXPLAIN SELECT * FROM EMPLOYEE WHERE FirstName='Mike'; *** Help information returned. 8 rows. *** Total elapsed time was 1 second. Explanation ------------------------------------------------------------------------ 1) First, we do a single-AMP RETRIEVE step from EMPLOYEE_JI by way of the primary index "EMPLOYEE_JI.FirstName = 'Mike'" with no residual conditions into Spool 1 (one-amp), which is built locally on that AMP. The size of Spool 1 is estimated with low confidence to be 2 rows (232 bytes). The estimated time for this step is 0.02 seconds. → The contents of Spool 1 are sent back to the user as the result of statement 1. The total estimated time is 0.02 seconds. A multi-table join index is created by joining more than one table. Multi-table join index can be used to store the result set of frequently joined tables to improve the performance. The following example creates a JOIN INDEX named Employee_Salary_JI by joining Employee and Salary tables. CREATE JOIN INDEX Employee_Salary_JI AS SELECT a.EmployeeNo,a.FirstName,a.LastName, a.BirthDate,a.JoinedDate,a.DepartmentNo,b.Gross,b.Deduction,b.NetPay FROM Employee a INNER JOIN Salary b ON(a.EmployeeNo = b.EmployeeNo) PRIMARY INDEX(FirstName); Whenever the base tables Employee or Salary are updated, then the Join index Employee_Salary_JI is also automatically updated. If you are running a query joining Employee and Salary tables, then the optimizer may choose to access the data from Employee_Salary_JI directly instead of joining the tables. EXPLAIN plan on the query can be used to verify if the optimizer will choose the base table or Join index. If a table is consistently aggregated on certain columns, then aggregate join index can be defined on the table to improve the performance. One limitation of aggregate join index is that it supports only SUM and COUNT functions. In the following example Employee and Salary is joined to identify the total salary per Department. CREATE JOIN INDEX Employee_Salary_JI AS SELECT a.DepartmentNo,SUM(b.NetPay) AS TotalPay FROM Employee a INNER JOIN Salary b ON(a.EmployeeNo = b.EmployeeNo) GROUP BY a.DepartmentNo Primary Index(DepartmentNo); Print Add Notes Bookmark this page
[ { "code": null, "e": 2930, "s": 2630, "text": "JOIN INDEX is a materialized view. Its definition is permanently stored and the data is updated whenever the base tables referred in the join index is updated. JOIN INDEX may contain one or more tables and also contain pre-aggregated data. Join indexes are mainly used for improving the performance." }, { "code": null, "e": 2983, "s": 2930, "text": "There are different types of join indexes available." }, { "code": null, "e": 3014, "s": 2983, "text": "Single Table Join Index (STJI)" }, { "code": null, "e": 3044, "s": 3014, "text": "Multi Table Join Index (MTJI)" }, { "code": null, "e": 3072, "s": 3044, "text": "Aggregated Join Index (AJI)" }, { "code": null, "e": 3209, "s": 3072, "text": "Single Table Join index allows to partition a large table based on the different primary index columns than the one from the base table." }, { "code": null, "e": 3250, "s": 3209, "text": "Following is the syntax of a JOIN INDEX." }, { "code": null, "e": 3323, "s": 3250, "text": "CREATE JOIN INDEX <index name> \nAS \n<SELECT Query> \n<Index Definition>;\n" }, { "code": null, "e": 3374, "s": 3323, "text": "Consider the following Employee and Salary tables." }, { "code": null, "e": 3813, "s": 3374, "text": "CREATE SET TABLE EMPLOYEE,FALLBACK ( \n EmployeeNo INTEGER, \n FirstName VARCHAR(30) , \n LastName VARCHAR(30) , \n DOB DATE FORMAT 'YYYY-MM-DD', \n JoinedDate DATE FORMAT 'YYYY-MM-DD', \n DepartmentNo BYTEINT \n) \nUNIQUE PRIMARY INDEX ( EmployeeNo );\n\nCREATE SET TABLE SALARY,FALLBACK ( \n EmployeeNo INTEGER, \n Gross INTEGER, \n Deduction INTEGER, \n NetPay INTEGER \n) \nPRIMARY INDEX ( EmployeeNo ) \nUNIQUE INDEX (EmployeeNo);" }, { "code": null, "e": 3900, "s": 3813, "text": "Following is an example that creates a Join index named Employee_JI on Employee table." }, { "code": null, "e": 4050, "s": 3900, "text": "CREATE JOIN INDEX Employee_JI \nAS \nSELECT EmployeeNo,FirstName,LastName, \nBirthDate,JoinedDate,DepartmentNo \nFROM Employee \nPRIMARY INDEX(FirstName);" }, { "code": null, "e": 4568, "s": 4050, "text": "If the user submits a query with a WHERE clause on EmployeeNo, then the system will query the Employee table using the unique primary index. If the user queries the employee table using employee_name, then the system may access the join index Employee_JI using employee_name. The rows of the join index are hashed on employee_name column. If the join index is not defined and the employee_name is not defined as secondary index, then the system will perform full table scan to access the rows which is time consuming." }, { "code": null, "e": 4804, "s": 4568, "text": "You can run the following EXPLAIN plan and verify the optimizer plan. In the following example you can see that the optimizer is using the Join Index instead of base Employee table when the table queries using the Employee_Name column." }, { "code": null, "e": 5540, "s": 4804, "text": "EXPLAIN SELECT * FROM EMPLOYEE WHERE FirstName='Mike'; \n*** Help information returned. 8 rows. \n*** Total elapsed time was 1 second. \nExplanation \n------------------------------------------------------------------------ \n 1) First, we do a single-AMP RETRIEVE step from EMPLOYEE_JI by \n way of the primary index \"EMPLOYEE_JI.FirstName = 'Mike'\" \n with no residual conditions into Spool 1 (one-amp), which is built \n locally on that AMP. The size of Spool 1 is estimated with low \n confidence to be 2 rows (232 bytes). The estimated time for this \n step is 0.02 seconds.\n → The contents of Spool 1 are sent back to the user as the result of \n statement 1. The total estimated time is 0.02 seconds. \n" }, { "code": null, "e": 5723, "s": 5540, "text": "A multi-table join index is created by joining more than one table. Multi-table join index can be used to store the result set of frequently joined tables to improve the performance." }, { "code": null, "e": 5830, "s": 5723, "text": "The following example creates a JOIN INDEX named Employee_Salary_JI by joining Employee and Salary tables." }, { "code": null, "e": 6084, "s": 5830, "text": "CREATE JOIN INDEX Employee_Salary_JI \nAS \nSELECT a.EmployeeNo,a.FirstName,a.LastName, \na.BirthDate,a.JoinedDate,a.DepartmentNo,b.Gross,b.Deduction,b.NetPay \nFROM Employee a \nINNER JOIN Salary b \nON(a.EmployeeNo = b.EmployeeNo) \nPRIMARY INDEX(FirstName);" }, { "code": null, "e": 6494, "s": 6084, "text": "Whenever the base tables Employee or Salary are updated, then the Join index Employee_Salary_JI is also automatically updated. If you are running a query joining Employee and Salary tables, then the optimizer may choose to access the data from Employee_Salary_JI directly instead of joining the tables. EXPLAIN plan on the query can be used to verify if the optimizer will choose the base table or Join index." }, { "code": null, "e": 6723, "s": 6494, "text": "If a table is consistently aggregated on certain columns, then aggregate join index can be defined on the table to improve the performance. One limitation of aggregate join index is that it supports only SUM and COUNT functions." }, { "code": null, "e": 6823, "s": 6723, "text": "In the following example Employee and Salary is joined to identify the total salary per Department." }, { "code": null, "e": 7039, "s": 6823, "text": "CREATE JOIN INDEX Employee_Salary_JI \nAS \nSELECT a.DepartmentNo,SUM(b.NetPay) AS TotalPay \nFROM Employee a \nINNER JOIN Salary b \nON(a.EmployeeNo = b.EmployeeNo)\nGROUP BY a.DepartmentNo \nPrimary Index(DepartmentNo); " }, { "code": null, "e": 7046, "s": 7039, "text": " Print" }, { "code": null, "e": 7057, "s": 7046, "text": " Add Notes" } ]
Tryit Editor v3.7
Tryit: SVG polygon
[]
Setup a Python Environment for Machine Learning and Deep Learning | by Hussnain Fareed | Towards Data Science
Interest in Machine Learning and Deep Learning has exploded over the past decade. You see machine learning in computer science programs, industry conferences, and in many applications in daily life. I am assuming you already know about Machine Learning, therefore I will not be explaining What and Why. So, I find many beginners facing problems while installing libraries and setting up the environment. As I have faced the first time when I was trying. So this guide is totally for beginners. In this story, I will tell you how you can easily set up a python environment on your system. I am using Windows but this guide is also suitable for Ubuntu & Linux users. After completing this tutorial, you will have a working Python environment to begin learning and developing machine learning and deep learning software. First of all to perform machine learning and deep learning on any dataset, the software/program requires a computer system powerful enough to handle the computing power necessary. So the following is required: Central Processing Unit (CPU) — Intel Core i5 6th Generation processor or higher. An AMD equivalent processor will also be optimal.RAM — 8 GB minimum, 16 GB or higher is recommended.Graphics Processing Unit (GPU) — NVIDIA GeForce GTX 960 or higher. AMD GPUs are not able to perform deep learning regardless. For more information on NVIDIA GPUs for deep learning please visit https://developer.nvidia.com/cuda-gpus.Operating System — Ubuntu or Microsoft Windows 10. I recommend updating Windows 10 to the latest version before proceeding forward. Central Processing Unit (CPU) — Intel Core i5 6th Generation processor or higher. An AMD equivalent processor will also be optimal. RAM — 8 GB minimum, 16 GB or higher is recommended. Graphics Processing Unit (GPU) — NVIDIA GeForce GTX 960 or higher. AMD GPUs are not able to perform deep learning regardless. For more information on NVIDIA GPUs for deep learning please visit https://developer.nvidia.com/cuda-gpus. Operating System — Ubuntu or Microsoft Windows 10. I recommend updating Windows 10 to the latest version before proceeding forward. Note: In the case of laptops, the ideal option would be to purchase a gaming laptop from any vendor deemed suitable such as Alienware, ASUS, Lenovo Legion, Acer Predator, etc. Let’s just get straight to the installation process. we are gonna hit the rock 😉 This tool is designed to update your NVIDIA GPU drivers and it is far easier to do it like this and it is highly recommended to be installed if you have an NVIDIA GPU. Download NVIDIA GeForce Experience In this tutorial, we will cover the following steps: Download AnacondaInstall Anaconda & PythonStart and Update AnacondaInstall CUDA Toolkit & cuDNNCreate an Anaconda EnvironmentInstall Deep Learning API’s (TensorFlow & Keras) Download Anaconda Install Anaconda & Python Start and Update Anaconda Install CUDA Toolkit & cuDNN Create an Anaconda Environment Install Deep Learning API’s (TensorFlow & Keras) In this step, we will download the Anaconda Python package for your platform. Anaconda is a free and easy-to-use environment for scientific Python. 1.Install Anaconda (Python 3.6 version) Download I am using Windows you can choose according to your OS. In this step, we will install the Anaconda Python software on your system. Installation is very easy and quick once you download the setup. Open the setup and follow the wizard instructions. #Note: It will automatically install Python and some basic libraries with it. It might take 5 to 10 minutes or some more time according to your system. Open Anaconda Prompt to type the following command(s). Don’t worry Anaconda Prompt works the same as cmd. conda update condaconda update --all Install CUDA Toolkit 9.0 or 8.0 Download Install CUDA Toolkit 9.0 or 8.0 Download Choose your version depending on your Operating System and GPU. #Version Support: Here is a guide to check that if your version supports your Nvidia Graphic Card For downloading other versions you can follow this link: https://developer.nvidia.com/cuda-toolkit-archive #Note: CUDA 9.0 is recommended as TensorFlow is NOT compatible with CUDA Toolkit 9.1 and 9.2 versions. Kindly choose the CUDA version according to your Nvidia GPU version to avoid errors. #Note: People with version 9.0 Download can also install the given patch in any case of error while proceeding. 2. Download cuDNN Download Download the latest version of cuDNN. Choose your version depending on your Operating System and CUDA. Membership registration is required. Don’t worry you can easily create an account using your email. Put your unzipped folder in C drive as follows: C:\cudnn-9.0-windows10-x64-v7 Open Run dialogue using (Win + R) and run the command sysdm.cplIn Window-10 System Properties, please select the Tab Advanced.Select Environment VariablesAdd the following path to your Environment. Open Run dialogue using (Win + R) and run the command sysdm.cpl In Window-10 System Properties, please select the Tab Advanced. Select Environment Variables Add the following path to your Environment. C:\cudnn-9.0-windows10-x64-v7\cuda\bin Here we will create a new anaconda environment for our specific usage so that it will not affect the root of Anaconda. Amazing!! isn’t it? 😛 Open Anaconda Prompt to type the following commands. Create a conda environment named “tensorflow” (you can change the name) by invoking the following command: Create a conda environment named “tensorflow” (you can change the name) by invoking the following command: conda create -n tensorflow pip python=3.6 2. Activate the conda environment by issuing the following command: activate tensorflow (tensorflow)C:> # Your prompt should change In this step, we will install Python libraries used for deep learning, specifically: TensorFlow, and Keras. TensorFlow TensorFlow TensorFlow is a tool for machine learning. While it contains a wide range of functionality, TensorFlow is mainly designed for deep neural network models. => For installing TensorFlow, Open Anaconda Prompt to type the following commands. To install the GPU version of TensorFlow: C:\> pip install tensorflow-gpu To install the CPU-only version of TensorFlow: C:\> pip install tensorflow If your machine or system is the only CPU supported you can install CPU version for basic learning and practice. => You can test the installation by running this program on shell: >>> import tensorflow as tf>>> hello = tf.constant('Hello, TensorFlow!')>>> sess = tf.Session()>>> print(sess.run(hello)) For getting started and documentation you can visit TensorFlow website. 2. Keras Keras is a high-level neural networks API, written in Python and capable of running on top of TensorFlow, CNTK, or Theano. => For installing Keras Open Anaconda Prompt to type the following commands. pip install keras => Let’s try running Mnist_Mlp.Py in your prompt. you can use other examples as well. Open Anaconda Prompt to type the following commands. activate tensorflowpython mnist_mlp.py For getting started and documentation you can visit Keras website. Here is an implementation of Keras Standard Fully Connected Neural Network using Python for Digit Recognition I have done. There are some other famous libraries like Pytorch, Theano, and Caffe2 you can use as per your choice and use. Congratulations! 😉 You have successfully created the environment using TensorFlow, Keras (with Tensorflow backend) over GPU on Windows!
[ { "code": null, "e": 371, "s": 172, "text": "Interest in Machine Learning and Deep Learning has exploded over the past decade. You see machine learning in computer science programs, industry conferences, and in many applications in daily life." }, { "code": null, "e": 475, "s": 371, "text": "I am assuming you already know about Machine Learning, therefore I will not be explaining What and Why." }, { "code": null, "e": 666, "s": 475, "text": "So, I find many beginners facing problems while installing libraries and setting up the environment. As I have faced the first time when I was trying. So this guide is totally for beginners." }, { "code": null, "e": 837, "s": 666, "text": "In this story, I will tell you how you can easily set up a python environment on your system. I am using Windows but this guide is also suitable for Ubuntu & Linux users." }, { "code": null, "e": 990, "s": 837, "text": "After completing this tutorial, you will have a working Python environment to begin learning and developing machine learning and deep learning software." }, { "code": null, "e": 1200, "s": 990, "text": "First of all to perform machine learning and deep learning on any dataset, the software/program requires a computer system powerful enough to handle the computing power necessary. So the following is required:" }, { "code": null, "e": 1746, "s": 1200, "text": "Central Processing Unit (CPU) — Intel Core i5 6th Generation processor or higher. An AMD equivalent processor will also be optimal.RAM — 8 GB minimum, 16 GB or higher is recommended.Graphics Processing Unit (GPU) — NVIDIA GeForce GTX 960 or higher. AMD GPUs are not able to perform deep learning regardless. For more information on NVIDIA GPUs for deep learning please visit https://developer.nvidia.com/cuda-gpus.Operating System — Ubuntu or Microsoft Windows 10. I recommend updating Windows 10 to the latest version before proceeding forward." }, { "code": null, "e": 1878, "s": 1746, "text": "Central Processing Unit (CPU) — Intel Core i5 6th Generation processor or higher. An AMD equivalent processor will also be optimal." }, { "code": null, "e": 1930, "s": 1878, "text": "RAM — 8 GB minimum, 16 GB or higher is recommended." }, { "code": null, "e": 2163, "s": 1930, "text": "Graphics Processing Unit (GPU) — NVIDIA GeForce GTX 960 or higher. AMD GPUs are not able to perform deep learning regardless. For more information on NVIDIA GPUs for deep learning please visit https://developer.nvidia.com/cuda-gpus." }, { "code": null, "e": 2295, "s": 2163, "text": "Operating System — Ubuntu or Microsoft Windows 10. I recommend updating Windows 10 to the latest version before proceeding forward." }, { "code": null, "e": 2471, "s": 2295, "text": "Note: In the case of laptops, the ideal option would be to purchase a gaming laptop from any vendor deemed suitable such as Alienware, ASUS, Lenovo Legion, Acer Predator, etc." }, { "code": null, "e": 2552, "s": 2471, "text": "Let’s just get straight to the installation process. we are gonna hit the rock 😉" }, { "code": null, "e": 2720, "s": 2552, "text": "This tool is designed to update your NVIDIA GPU drivers and it is far easier to do it like this and it is highly recommended to be installed if you have an NVIDIA GPU." }, { "code": null, "e": 2755, "s": 2720, "text": "Download NVIDIA GeForce Experience" }, { "code": null, "e": 2808, "s": 2755, "text": "In this tutorial, we will cover the following steps:" }, { "code": null, "e": 2982, "s": 2808, "text": "Download AnacondaInstall Anaconda & PythonStart and Update AnacondaInstall CUDA Toolkit & cuDNNCreate an Anaconda EnvironmentInstall Deep Learning API’s (TensorFlow & Keras)" }, { "code": null, "e": 3000, "s": 2982, "text": "Download Anaconda" }, { "code": null, "e": 3026, "s": 3000, "text": "Install Anaconda & Python" }, { "code": null, "e": 3052, "s": 3026, "text": "Start and Update Anaconda" }, { "code": null, "e": 3081, "s": 3052, "text": "Install CUDA Toolkit & cuDNN" }, { "code": null, "e": 3112, "s": 3081, "text": "Create an Anaconda Environment" }, { "code": null, "e": 3161, "s": 3112, "text": "Install Deep Learning API’s (TensorFlow & Keras)" }, { "code": null, "e": 3239, "s": 3161, "text": "In this step, we will download the Anaconda Python package for your platform." }, { "code": null, "e": 3309, "s": 3239, "text": "Anaconda is a free and easy-to-use environment for scientific Python." }, { "code": null, "e": 3358, "s": 3309, "text": "1.Install Anaconda (Python 3.6 version) Download" }, { "code": null, "e": 3414, "s": 3358, "text": "I am using Windows you can choose according to your OS." }, { "code": null, "e": 3489, "s": 3414, "text": "In this step, we will install the Anaconda Python software on your system." }, { "code": null, "e": 3605, "s": 3489, "text": "Installation is very easy and quick once you download the setup. Open the setup and follow the wizard instructions." }, { "code": null, "e": 3683, "s": 3605, "text": "#Note: It will automatically install Python and some basic libraries with it." }, { "code": null, "e": 3757, "s": 3683, "text": "It might take 5 to 10 minutes or some more time according to your system." }, { "code": null, "e": 3863, "s": 3757, "text": "Open Anaconda Prompt to type the following command(s). Don’t worry Anaconda Prompt works the same as cmd." }, { "code": null, "e": 3900, "s": 3863, "text": "conda update condaconda update --all" }, { "code": null, "e": 3941, "s": 3900, "text": "Install CUDA Toolkit 9.0 or 8.0 Download" }, { "code": null, "e": 3982, "s": 3941, "text": "Install CUDA Toolkit 9.0 or 8.0 Download" }, { "code": null, "e": 4046, "s": 3982, "text": "Choose your version depending on your Operating System and GPU." }, { "code": null, "e": 4144, "s": 4046, "text": "#Version Support: Here is a guide to check that if your version supports your Nvidia Graphic Card" }, { "code": null, "e": 4251, "s": 4144, "text": "For downloading other versions you can follow this link: https://developer.nvidia.com/cuda-toolkit-archive" }, { "code": null, "e": 4439, "s": 4251, "text": "#Note: CUDA 9.0 is recommended as TensorFlow is NOT compatible with CUDA Toolkit 9.1 and 9.2 versions. Kindly choose the CUDA version according to your Nvidia GPU version to avoid errors." }, { "code": null, "e": 4551, "s": 4439, "text": "#Note: People with version 9.0 Download can also install the given patch in any case of error while proceeding." }, { "code": null, "e": 4578, "s": 4551, "text": "2. Download cuDNN Download" }, { "code": null, "e": 4781, "s": 4578, "text": "Download the latest version of cuDNN. Choose your version depending on your Operating System and CUDA. Membership registration is required. Don’t worry you can easily create an account using your email." }, { "code": null, "e": 4829, "s": 4781, "text": "Put your unzipped folder in C drive as follows:" }, { "code": null, "e": 4859, "s": 4829, "text": "C:\\cudnn-9.0-windows10-x64-v7" }, { "code": null, "e": 5057, "s": 4859, "text": "Open Run dialogue using (Win + R) and run the command sysdm.cplIn Window-10 System Properties, please select the Tab Advanced.Select Environment VariablesAdd the following path to your Environment." }, { "code": null, "e": 5121, "s": 5057, "text": "Open Run dialogue using (Win + R) and run the command sysdm.cpl" }, { "code": null, "e": 5185, "s": 5121, "text": "In Window-10 System Properties, please select the Tab Advanced." }, { "code": null, "e": 5214, "s": 5185, "text": "Select Environment Variables" }, { "code": null, "e": 5258, "s": 5214, "text": "Add the following path to your Environment." }, { "code": null, "e": 5297, "s": 5258, "text": "C:\\cudnn-9.0-windows10-x64-v7\\cuda\\bin" }, { "code": null, "e": 5438, "s": 5297, "text": "Here we will create a new anaconda environment for our specific usage so that it will not affect the root of Anaconda. Amazing!! isn’t it? 😛" }, { "code": null, "e": 5491, "s": 5438, "text": "Open Anaconda Prompt to type the following commands." }, { "code": null, "e": 5598, "s": 5491, "text": "Create a conda environment named “tensorflow” (you can change the name) by invoking the following command:" }, { "code": null, "e": 5705, "s": 5598, "text": "Create a conda environment named “tensorflow” (you can change the name) by invoking the following command:" }, { "code": null, "e": 5747, "s": 5705, "text": "conda create -n tensorflow pip python=3.6" }, { "code": null, "e": 5815, "s": 5747, "text": "2. Activate the conda environment by issuing the following command:" }, { "code": null, "e": 5880, "s": 5815, "text": "activate tensorflow (tensorflow)C:> # Your prompt should change" }, { "code": null, "e": 5988, "s": 5880, "text": "In this step, we will install Python libraries used for deep learning, specifically: TensorFlow, and Keras." }, { "code": null, "e": 5999, "s": 5988, "text": "TensorFlow" }, { "code": null, "e": 6010, "s": 5999, "text": "TensorFlow" }, { "code": null, "e": 6164, "s": 6010, "text": "TensorFlow is a tool for machine learning. While it contains a wide range of functionality, TensorFlow is mainly designed for deep neural network models." }, { "code": null, "e": 6247, "s": 6164, "text": "=> For installing TensorFlow, Open Anaconda Prompt to type the following commands." }, { "code": null, "e": 6289, "s": 6247, "text": "To install the GPU version of TensorFlow:" }, { "code": null, "e": 6321, "s": 6289, "text": "C:\\> pip install tensorflow-gpu" }, { "code": null, "e": 6368, "s": 6321, "text": "To install the CPU-only version of TensorFlow:" }, { "code": null, "e": 6396, "s": 6368, "text": "C:\\> pip install tensorflow" }, { "code": null, "e": 6509, "s": 6396, "text": "If your machine or system is the only CPU supported you can install CPU version for basic learning and practice." }, { "code": null, "e": 6576, "s": 6509, "text": "=> You can test the installation by running this program on shell:" }, { "code": null, "e": 6698, "s": 6576, "text": ">>> import tensorflow as tf>>> hello = tf.constant('Hello, TensorFlow!')>>> sess = tf.Session()>>> print(sess.run(hello))" }, { "code": null, "e": 6770, "s": 6698, "text": "For getting started and documentation you can visit TensorFlow website." }, { "code": null, "e": 6779, "s": 6770, "text": "2. Keras" }, { "code": null, "e": 6902, "s": 6779, "text": "Keras is a high-level neural networks API, written in Python and capable of running on top of TensorFlow, CNTK, or Theano." }, { "code": null, "e": 6979, "s": 6902, "text": "=> For installing Keras Open Anaconda Prompt to type the following commands." }, { "code": null, "e": 6997, "s": 6979, "text": "pip install keras" }, { "code": null, "e": 7083, "s": 6997, "text": "=> Let’s try running Mnist_Mlp.Py in your prompt. you can use other examples as well." }, { "code": null, "e": 7136, "s": 7083, "text": "Open Anaconda Prompt to type the following commands." }, { "code": null, "e": 7175, "s": 7136, "text": "activate tensorflowpython mnist_mlp.py" }, { "code": null, "e": 7242, "s": 7175, "text": "For getting started and documentation you can visit Keras website." }, { "code": null, "e": 7365, "s": 7242, "text": "Here is an implementation of Keras Standard Fully Connected Neural Network using Python for Digit Recognition I have done." }, { "code": null, "e": 7476, "s": 7365, "text": "There are some other famous libraries like Pytorch, Theano, and Caffe2 you can use as per your choice and use." } ]
Difference between Left, Right and Full Outer Join - GeeksforGeeks
03 May, 2020 Database Management System (DBMS) allows retrieving data from more than one table using joins. Joins are mainly Cartesian product of two or more relations (or tables). SQL Joins are broadly categorized as Inner Join and Outer Join. Inner Join selects rows from the tables that fulfills the join condition. But using inner join the data specifically the rows from both the tables that do not satisfy the condition are lost. Outer Join can be used to prevent the loss of data from the tables. Types of Outer Join :Outer join is again classified into 3 types: Left Outer Join, Right Outer Join, and Full Outer Join. These are explained as following below. Left Outer Join:Left Outer Join returns all the rows from the table on the left and columns of the table on the right is null padded. Left Outer Join retrieves all the rows from both the tables that satisfy the join condition along with the unmatched rows of the left table.Syntax:SELECT [column1, column2, ....] FROM table1 LEFT OUTER JOIN table2 ON table1.matching_column = table2.matching_column WHERE [condition]; OrSELECT [column1, column2, ....] FROM table1 LEFT OUTER JOIN table2 ON table1.matching_column = table2.matching_column WHERE [condition]; Diagrammatic Representation :Right Outer Join:Right Outer Join returns all the rows from the table on the right and columns of the table on the left is null padded. Right Outer Join retrieves all the rows from both the tables that satisfy the join condition along with the unmatched rows of the right table.Syntax:SELECT [column1, column2, ....] FROM table1 RIGHT OUTER JOIN table2 ON table1.matching_column = table2.matching_column WHERE [condition]; Or,SELECT [column1, column2, ....] FROM table1 RIGHT OUTER JOIN table2 ON table1.matching_column(+) = table2.matching_column WHERE [condition]; Diagrammatic Representation :Full Outer Join:Full Outer Join returns all the rows from both the table. When no matching rows exist for the row in the left table, the columns of the right table are null padded. Similarly, when no matching rows exist for the row in the right table, the columns of the left table are null padded. Full outer join is the union of left outer join and right outer join.Syntax:SELECT [column1, column2, ....] FROM table1 FULL OUTER JOIN table2 ON table1.matching_column = table2.matching_column WHERE [condition]; Diagrammatic Representation : Left Outer Join:Left Outer Join returns all the rows from the table on the left and columns of the table on the right is null padded. Left Outer Join retrieves all the rows from both the tables that satisfy the join condition along with the unmatched rows of the left table.Syntax:SELECT [column1, column2, ....] FROM table1 LEFT OUTER JOIN table2 ON table1.matching_column = table2.matching_column WHERE [condition]; OrSELECT [column1, column2, ....] FROM table1 LEFT OUTER JOIN table2 ON table1.matching_column = table2.matching_column WHERE [condition]; Diagrammatic Representation : Syntax: SELECT [column1, column2, ....] FROM table1 LEFT OUTER JOIN table2 ON table1.matching_column = table2.matching_column WHERE [condition]; Or SELECT [column1, column2, ....] FROM table1 LEFT OUTER JOIN table2 ON table1.matching_column = table2.matching_column WHERE [condition]; Diagrammatic Representation : Right Outer Join:Right Outer Join returns all the rows from the table on the right and columns of the table on the left is null padded. Right Outer Join retrieves all the rows from both the tables that satisfy the join condition along with the unmatched rows of the right table.Syntax:SELECT [column1, column2, ....] FROM table1 RIGHT OUTER JOIN table2 ON table1.matching_column = table2.matching_column WHERE [condition]; Or,SELECT [column1, column2, ....] FROM table1 RIGHT OUTER JOIN table2 ON table1.matching_column(+) = table2.matching_column WHERE [condition]; Diagrammatic Representation : Syntax: SELECT [column1, column2, ....] FROM table1 RIGHT OUTER JOIN table2 ON table1.matching_column = table2.matching_column WHERE [condition]; Or, SELECT [column1, column2, ....] FROM table1 RIGHT OUTER JOIN table2 ON table1.matching_column(+) = table2.matching_column WHERE [condition]; Diagrammatic Representation : Full Outer Join:Full Outer Join returns all the rows from both the table. When no matching rows exist for the row in the left table, the columns of the right table are null padded. Similarly, when no matching rows exist for the row in the right table, the columns of the left table are null padded. Full outer join is the union of left outer join and right outer join.Syntax:SELECT [column1, column2, ....] FROM table1 FULL OUTER JOIN table2 ON table1.matching_column = table2.matching_column WHERE [condition]; Diagrammatic Representation : Syntax: SELECT [column1, column2, ....] FROM table1 FULL OUTER JOIN table2 ON table1.matching_column = table2.matching_column WHERE [condition]; Diagrammatic Representation : Example:Consider following employee table, Department Table : Now,1. Left Outer Join query – Select empid, ename, deptid, deptname from employee left outer join department on employee.empdept = department.deptname; Output: 2. Right Outer Join query – Select empid, ename, deptid, deptname from employee right outer join department on employee.empdept = department.deptname; 3. Full Outer Join query – Select empid, ename, deptid, deptname from employee full outer join department on employee.empdept = department.deptname; Differences between Left Outer Join, Right Outer Join, Full Outer Join : DBMS-Join Picked DBMS Difference Between GATE CS SQL DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Introduction of B-Tree Difference between Clustered and Non-clustered index Introduction of DBMS (Database Management System) | Set 1 Introduction of ER Model CTE in SQL Difference between BFS and DFS Class method vs Static method in Python Difference between var, let and const keywords in JavaScript Differences between TCP and UDP Difference between Process and Thread
[ { "code": null, "e": 23531, "s": 23503, "text": "\n03 May, 2020" }, { "code": null, "e": 23626, "s": 23531, "text": "Database Management System (DBMS) allows retrieving data from more than one table using joins." }, { "code": null, "e": 23699, "s": 23626, "text": "Joins are mainly Cartesian product of two or more relations (or tables)." }, { "code": null, "e": 24022, "s": 23699, "text": "SQL Joins are broadly categorized as Inner Join and Outer Join. Inner Join selects rows from the tables that fulfills the join condition. But using inner join the data specifically the rows from both the tables that do not satisfy the condition are lost. Outer Join can be used to prevent the loss of data from the tables." }, { "code": null, "e": 24184, "s": 24022, "text": "Types of Outer Join :Outer join is again classified into 3 types: Left Outer Join, Right Outer Join, and Full Outer Join. These are explained as following below." }, { "code": null, "e": 25933, "s": 24184, "text": "Left Outer Join:Left Outer Join returns all the rows from the table on the left and columns of the table on the right is null padded. Left Outer Join retrieves all the rows from both the tables that satisfy the join condition along with the unmatched rows of the left table.Syntax:SELECT [column1, column2, ....]\nFROM table1\n\nLEFT OUTER JOIN table2 ON \ntable1.matching_column = table2.matching_column\n\nWHERE [condition]; OrSELECT [column1, column2, ....]\nFROM table1\n\nLEFT OUTER JOIN table2 \nON table1.matching_column = table2.matching_column\n\nWHERE [condition]; Diagrammatic Representation :Right Outer Join:Right Outer Join returns all the rows from the table on the right and columns of the table on the left is null padded. Right Outer Join retrieves all the rows from both the tables that satisfy the join condition along with the unmatched rows of the right table.Syntax:SELECT [column1, column2, ....]\nFROM table1\n\nRIGHT OUTER JOIN table2 ON \ntable1.matching_column = table2.matching_column\n\nWHERE [condition]; Or,SELECT [column1, column2, ....]\nFROM table1\n\nRIGHT OUTER JOIN table2 \nON table1.matching_column(+) = table2.matching_column\n\nWHERE [condition]; Diagrammatic Representation :Full Outer Join:Full Outer Join returns all the rows from both the table. When no matching rows exist for the row in the left table, the columns of the right table are null padded. Similarly, when no matching rows exist for the row in the right table, the columns of the left table are null padded. Full outer join is the union of left outer join and right outer join.Syntax:SELECT [column1, column2, ....]\nFROM table1\n\nFULL OUTER JOIN table2 \nON table1.matching_column = table2.matching_column\n\nWHERE [condition]; Diagrammatic Representation :" }, { "code": null, "e": 26530, "s": 25933, "text": "Left Outer Join:Left Outer Join returns all the rows from the table on the left and columns of the table on the right is null padded. Left Outer Join retrieves all the rows from both the tables that satisfy the join condition along with the unmatched rows of the left table.Syntax:SELECT [column1, column2, ....]\nFROM table1\n\nLEFT OUTER JOIN table2 ON \ntable1.matching_column = table2.matching_column\n\nWHERE [condition]; OrSELECT [column1, column2, ....]\nFROM table1\n\nLEFT OUTER JOIN table2 \nON table1.matching_column = table2.matching_column\n\nWHERE [condition]; Diagrammatic Representation :" }, { "code": null, "e": 26538, "s": 26530, "text": "Syntax:" }, { "code": null, "e": 26681, "s": 26538, "text": "SELECT [column1, column2, ....]\nFROM table1\n\nLEFT OUTER JOIN table2 ON \ntable1.matching_column = table2.matching_column\n\nWHERE [condition]; " }, { "code": null, "e": 26684, "s": 26681, "text": "Or" }, { "code": null, "e": 26827, "s": 26684, "text": "SELECT [column1, column2, ....]\nFROM table1\n\nLEFT OUTER JOIN table2 \nON table1.matching_column = table2.matching_column\n\nWHERE [condition]; " }, { "code": null, "e": 26857, "s": 26827, "text": "Diagrammatic Representation :" }, { "code": null, "e": 27464, "s": 26857, "text": "Right Outer Join:Right Outer Join returns all the rows from the table on the right and columns of the table on the left is null padded. Right Outer Join retrieves all the rows from both the tables that satisfy the join condition along with the unmatched rows of the right table.Syntax:SELECT [column1, column2, ....]\nFROM table1\n\nRIGHT OUTER JOIN table2 ON \ntable1.matching_column = table2.matching_column\n\nWHERE [condition]; Or,SELECT [column1, column2, ....]\nFROM table1\n\nRIGHT OUTER JOIN table2 \nON table1.matching_column(+) = table2.matching_column\n\nWHERE [condition]; Diagrammatic Representation :" }, { "code": null, "e": 27472, "s": 27464, "text": "Syntax:" }, { "code": null, "e": 27616, "s": 27472, "text": "SELECT [column1, column2, ....]\nFROM table1\n\nRIGHT OUTER JOIN table2 ON \ntable1.matching_column = table2.matching_column\n\nWHERE [condition]; " }, { "code": null, "e": 27620, "s": 27616, "text": "Or," }, { "code": null, "e": 27767, "s": 27620, "text": "SELECT [column1, column2, ....]\nFROM table1\n\nRIGHT OUTER JOIN table2 \nON table1.matching_column(+) = table2.matching_column\n\nWHERE [condition]; " }, { "code": null, "e": 27797, "s": 27767, "text": "Diagrammatic Representation :" }, { "code": null, "e": 28344, "s": 27797, "text": "Full Outer Join:Full Outer Join returns all the rows from both the table. When no matching rows exist for the row in the left table, the columns of the right table are null padded. Similarly, when no matching rows exist for the row in the right table, the columns of the left table are null padded. Full outer join is the union of left outer join and right outer join.Syntax:SELECT [column1, column2, ....]\nFROM table1\n\nFULL OUTER JOIN table2 \nON table1.matching_column = table2.matching_column\n\nWHERE [condition]; Diagrammatic Representation :" }, { "code": null, "e": 28352, "s": 28344, "text": "Syntax:" }, { "code": null, "e": 28495, "s": 28352, "text": "SELECT [column1, column2, ....]\nFROM table1\n\nFULL OUTER JOIN table2 \nON table1.matching_column = table2.matching_column\n\nWHERE [condition]; " }, { "code": null, "e": 28525, "s": 28495, "text": "Diagrammatic Representation :" }, { "code": null, "e": 28568, "s": 28525, "text": "Example:Consider following employee table," }, { "code": null, "e": 28587, "s": 28568, "text": "Department Table :" }, { "code": null, "e": 28618, "s": 28587, "text": "Now,1. Left Outer Join query –" }, { "code": null, "e": 28744, "s": 28618, "text": "Select empid, ename, deptid, deptname \nfrom employee \nleft outer join department \non employee.empdept = department.deptname; " }, { "code": null, "e": 28752, "s": 28744, "text": "Output:" }, { "code": null, "e": 28780, "s": 28752, "text": "2. Right Outer Join query –" }, { "code": null, "e": 28905, "s": 28780, "text": "Select empid, ename, deptid, deptname \nfrom employee right outer join department \non employee.empdept = department.deptname;" }, { "code": null, "e": 28932, "s": 28905, "text": "3. Full Outer Join query –" }, { "code": null, "e": 29056, "s": 28932, "text": "Select empid, ename, deptid, deptname \nfrom employee full outer join department \non employee.empdept = department.deptname;" }, { "code": null, "e": 29129, "s": 29056, "text": "Differences between Left Outer Join, Right Outer Join, Full Outer Join :" }, { "code": null, "e": 29139, "s": 29129, "text": "DBMS-Join" }, { "code": null, "e": 29146, "s": 29139, "text": "Picked" }, { "code": null, "e": 29151, "s": 29146, "text": "DBMS" }, { "code": null, "e": 29170, "s": 29151, "text": "Difference Between" }, { "code": null, "e": 29178, "s": 29170, "text": "GATE CS" }, { "code": null, "e": 29182, "s": 29178, "text": "SQL" }, { "code": null, "e": 29187, "s": 29182, "text": "DBMS" }, { "code": null, "e": 29191, "s": 29187, "text": "SQL" }, { "code": null, "e": 29289, "s": 29191, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29298, "s": 29289, "text": "Comments" }, { "code": null, "e": 29311, "s": 29298, "text": "Old Comments" }, { "code": null, "e": 29334, "s": 29311, "text": "Introduction of B-Tree" }, { "code": null, "e": 29387, "s": 29334, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 29445, "s": 29387, "text": "Introduction of DBMS (Database Management System) | Set 1" }, { "code": null, "e": 29470, "s": 29445, "text": "Introduction of ER Model" }, { "code": null, "e": 29481, "s": 29470, "text": "CTE in SQL" }, { "code": null, "e": 29512, "s": 29481, "text": "Difference between BFS and DFS" }, { "code": null, "e": 29552, "s": 29512, "text": "Class method vs Static method in Python" }, { "code": null, "e": 29613, "s": 29552, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29645, "s": 29613, "text": "Differences between TCP and UDP" } ]
Java program to merge contents of all the files in a directory - GeeksforGeeks
25 Aug, 2021 Prerequisite : PrintWriter, BufferedReader. We are given a directory/folder in which n number of files are stored(We dont know the number of files) and we want to merge the contents of all the files into a single file lets say output.txt For the below example lets say the folder is stored at the path: F:\GeeksForGeeksFollowing are the steps: Create instance of directory.Create a PrintWriter object for “output.txt”.Get list of all the files in form of String Array.Loop for reading the contents of all the files in the directory GeeksForGeeks.Inside the loop for every file doCreate instance of file from Name of the file stored in string Array.Create object of BufferedReader for reading from current file.Read from current file.Write to the output file. Create instance of directory. Create a PrintWriter object for “output.txt”. Get list of all the files in form of String Array. Loop for reading the contents of all the files in the directory GeeksForGeeks. Inside the loop for every file do Create instance of file from Name of the file stored in string Array.Create object of BufferedReader for reading from current file.Read from current file.Write to the output file. Create instance of file from Name of the file stored in string Array.Create object of BufferedReader for reading from current file.Read from current file.Write to the output file. Create instance of file from Name of the file stored in string Array. Create object of BufferedReader for reading from current file. Read from current file. Write to the output file. Java // Java program to merge all files of a directoryimport java.io.*;class sample { public static void main(String[] args) throws IOException { // create instance of directory File dir = new File("F:\\GeeksForGeeks"); // create object of PrintWriter for output file PrintWriter pw = new PrintWriter("output.txt"); // Get list of all the files in form of String Array String[] fileNames = dir.list(); // loop for reading the contents of all the files // in the directory GeeksForGeeks for (String fileName : fileNames) { System.out.println("Reading from " + fileName); // create instance of file from Name of // the file stored in string Array File f = new File(dir, fileName); // create object of BufferedReader BufferedReader br = new BufferedReader(new FileReader(f)); pw.println("Contents of file " + fileName); // Read from current file String line = br.readLine(); while (line != null) { // write to the output file pw.println(line); line = br.readLine(); } pw.flush(); } System.out.println("Reading from all files" + " in directory " + dir.getName() + " Completed"); }} Contents of folder F\GeeksForGeeks Contents of 3 files in GeeksForGeeks folder: Output file: sumitgumber28 java-file-handling Technical Scripter 2018 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Initialize an ArrayList in Java Interfaces in Java ArrayList in Java Multidimensional Arrays in Java Stack Class in Java Convert a String to Character array in Java Initializing a List in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 24493, "s": 24465, "text": "\n25 Aug, 2021" }, { "code": null, "e": 24839, "s": 24493, "text": "Prerequisite : PrintWriter, BufferedReader. We are given a directory/folder in which n number of files are stored(We dont know the number of files) and we want to merge the contents of all the files into a single file lets say output.txt For the below example lets say the folder is stored at the path: F:\\GeeksForGeeksFollowing are the steps: " }, { "code": null, "e": 25254, "s": 24839, "text": "Create instance of directory.Create a PrintWriter object for “output.txt”.Get list of all the files in form of String Array.Loop for reading the contents of all the files in the directory GeeksForGeeks.Inside the loop for every file doCreate instance of file from Name of the file stored in string Array.Create object of BufferedReader for reading from current file.Read from current file.Write to the output file." }, { "code": null, "e": 25284, "s": 25254, "text": "Create instance of directory." }, { "code": null, "e": 25330, "s": 25284, "text": "Create a PrintWriter object for “output.txt”." }, { "code": null, "e": 25381, "s": 25330, "text": "Get list of all the files in form of String Array." }, { "code": null, "e": 25460, "s": 25381, "text": "Loop for reading the contents of all the files in the directory GeeksForGeeks." }, { "code": null, "e": 25494, "s": 25460, "text": "Inside the loop for every file do" }, { "code": null, "e": 25674, "s": 25494, "text": "Create instance of file from Name of the file stored in string Array.Create object of BufferedReader for reading from current file.Read from current file.Write to the output file." }, { "code": null, "e": 25854, "s": 25674, "text": "Create instance of file from Name of the file stored in string Array.Create object of BufferedReader for reading from current file.Read from current file.Write to the output file." }, { "code": null, "e": 25924, "s": 25854, "text": "Create instance of file from Name of the file stored in string Array." }, { "code": null, "e": 25987, "s": 25924, "text": "Create object of BufferedReader for reading from current file." }, { "code": null, "e": 26011, "s": 25987, "text": "Read from current file." }, { "code": null, "e": 26037, "s": 26011, "text": "Write to the output file." }, { "code": null, "e": 26044, "s": 26039, "text": "Java" }, { "code": "// Java program to merge all files of a directoryimport java.io.*;class sample { public static void main(String[] args) throws IOException { // create instance of directory File dir = new File(\"F:\\\\GeeksForGeeks\"); // create object of PrintWriter for output file PrintWriter pw = new PrintWriter(\"output.txt\"); // Get list of all the files in form of String Array String[] fileNames = dir.list(); // loop for reading the contents of all the files // in the directory GeeksForGeeks for (String fileName : fileNames) { System.out.println(\"Reading from \" + fileName); // create instance of file from Name of // the file stored in string Array File f = new File(dir, fileName); // create object of BufferedReader BufferedReader br = new BufferedReader(new FileReader(f)); pw.println(\"Contents of file \" + fileName); // Read from current file String line = br.readLine(); while (line != null) { // write to the output file pw.println(line); line = br.readLine(); } pw.flush(); } System.out.println(\"Reading from all files\" + \" in directory \" + dir.getName() + \" Completed\"); }}", "e": 27395, "s": 26044, "text": null }, { "code": null, "e": 27431, "s": 27395, "text": "Contents of folder F\\GeeksForGeeks " }, { "code": null, "e": 27479, "s": 27433, "text": "Contents of 3 files in GeeksForGeeks folder: " }, { "code": null, "e": 27499, "s": 27485, "text": "Output file: " }, { "code": null, "e": 27515, "s": 27501, "text": "sumitgumber28" }, { "code": null, "e": 27534, "s": 27515, "text": "java-file-handling" }, { "code": null, "e": 27558, "s": 27534, "text": "Technical Scripter 2018" }, { "code": null, "e": 27563, "s": 27558, "text": "Java" }, { "code": null, "e": 27577, "s": 27563, "text": "Java Programs" }, { "code": null, "e": 27596, "s": 27577, "text": "Technical Scripter" }, { "code": null, "e": 27601, "s": 27596, "text": "Java" }, { "code": null, "e": 27699, "s": 27601, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27708, "s": 27699, "text": "Comments" }, { "code": null, "e": 27721, "s": 27708, "text": "Old Comments" }, { "code": null, "e": 27753, "s": 27721, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 27772, "s": 27753, "text": "Interfaces in Java" }, { "code": null, "e": 27790, "s": 27772, "text": "ArrayList in Java" }, { "code": null, "e": 27822, "s": 27790, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 27842, "s": 27822, "text": "Stack Class in Java" }, { "code": null, "e": 27886, "s": 27842, "text": "Convert a String to Character array in Java" }, { "code": null, "e": 27914, "s": 27886, "text": "Initializing a List in Java" }, { "code": null, "e": 27940, "s": 27914, "text": "Java Programming Examples" }, { "code": null, "e": 27974, "s": 27940, "text": "Convert Double to Integer in Java" } ]
Dart Programming - List.reversed Method
Returns an iterable object containing the list values in the reverse order. List.reversed void main() { var lst = new List(); lst.add(12); lst.add(13); print("The list values in reverse order: ${lst.reversed}"); } It will produce the following output − The list values in reverse order: (13, 12) 44 Lectures 4.5 hours Sriyank Siddhartha 34 Lectures 4 hours Sriyank Siddhartha 69 Lectures 4 hours Frahaan Hussain 117 Lectures 10 hours Frahaan Hussain 22 Lectures 1.5 hours Pranjal Srivastava 34 Lectures 3 hours Pranjal Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2601, "s": 2525, "text": "Returns an iterable object containing the list values in the reverse order." }, { "code": null, "e": 2617, "s": 2601, "text": "List.reversed \n" }, { "code": null, "e": 2760, "s": 2617, "text": "void main() { \n var lst = new List(); \n lst.add(12); \n lst.add(13); \n print(\"The list values in reverse order: ${lst.reversed}\"); \n} " }, { "code": null, "e": 2799, "s": 2760, "text": "It will produce the following output −" }, { "code": null, "e": 2844, "s": 2799, "text": "The list values in reverse order: (13, 12) \n" }, { "code": null, "e": 2879, "s": 2844, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 2899, "s": 2879, "text": " Sriyank Siddhartha" }, { "code": null, "e": 2932, "s": 2899, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 2952, "s": 2932, "text": " Sriyank Siddhartha" }, { "code": null, "e": 2985, "s": 2952, "text": "\n 69 Lectures \n 4 hours \n" }, { "code": null, "e": 3002, "s": 2985, "text": " Frahaan Hussain" }, { "code": null, "e": 3037, "s": 3002, "text": "\n 117 Lectures \n 10 hours \n" }, { "code": null, "e": 3054, "s": 3037, "text": " Frahaan Hussain" }, { "code": null, "e": 3089, "s": 3054, "text": "\n 22 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3109, "s": 3089, "text": " Pranjal Srivastava" }, { "code": null, "e": 3142, "s": 3109, "text": "\n 34 Lectures \n 3 hours \n" }, { "code": null, "e": 3162, "s": 3142, "text": " Pranjal Srivastava" }, { "code": null, "e": 3169, "s": 3162, "text": " Print" }, { "code": null, "e": 3180, "s": 3169, "text": " Add Notes" } ]
How to prevent class inheritance in C++
Here we will see how to prevent inheritance in C++. The concept of preventing the inheritance is known as final class. In Java or C#, we can use final classes. In C++ there are no such direct way. Here we will see how to simulate the final class in C++. Here we will create one extra class called MakeFinalClass (its default constructor is private). This function is used to solve our purpose. The main Class MyClass can call the constructor of the MakeFinalClass as they are friend classes. One thing we have to notice, that the MakeFinalClass is also a virtual base class. We will make it virtual base class because we want to call the constructor of the MakeFinalClass through the constructor of MyDerivedClass, not MyClass (The constructor of a virtual base class is not called by the class that inherits from it, instead of the constructor that is called by the constructor of the concrete class). #include <iostream> using namespace std; class MyClass; class MakeFinalClass { private: MakeFinalClass() { cout << "This is constructor of the MakeFinalClass" << endl; } friend class MyClass; }; class MyClass : virtual MakeFinalClass { //this will be final class public: MyClass() { cout << "This is constructor of the final Class" << endl; } }; //try to make derived class class MyDerivedClass : MyClass { public: MyDerivedClass() { cout << "Constructor of the Derived Class" << endl; } }; main() { MyDerivedClass derived; } In constructor 'MyDerivedClass::MyDerivedClass()': [Error] 'MakeFinalClass::MakeFinalClass()' is private We can create the objects of the MyClass as this is friend of the MakeFinalClass, and has access to its constructors. #include <iostream> using namespace std; class MyClass; class MakeFinalClass { private: MakeFinalClass() { cout << "This is constructor of the MakeFinalClass" << endl; } friend class MyClass; }; class MyClass : virtual MakeFinalClass { //this will be final class public: MyClass() { cout << "This is constructor of the final Class" << endl; } }; main() { MyClass obj; } This is constructor of the MakeFinalClass This is constructor of the final Class
[ { "code": null, "e": 1181, "s": 1062, "text": "Here we will see how to prevent inheritance in C++. The concept of preventing the inheritance is known as final class." }, { "code": null, "e": 1316, "s": 1181, "text": "In Java or C#, we can use final classes. In C++ there are no such direct way. Here we will see how to simulate the final class in C++." }, { "code": null, "e": 1554, "s": 1316, "text": "Here we will create one extra class called MakeFinalClass (its default constructor is private). This function is used to solve our purpose. The main Class MyClass can call the constructor of the MakeFinalClass as they are friend classes." }, { "code": null, "e": 1965, "s": 1554, "text": "One thing we have to notice, that the MakeFinalClass is also a virtual base class. We will make it virtual base class because we want to call the constructor of the MakeFinalClass through the constructor of MyDerivedClass, not MyClass (The constructor of a virtual base class is not called by the class that inherits from it, instead of the constructor that is called by the constructor of the concrete class)." }, { "code": null, "e": 2572, "s": 1965, "text": "#include <iostream>\nusing namespace std;\nclass MyClass;\nclass MakeFinalClass {\n private:\n MakeFinalClass() {\n cout << \"This is constructor of the MakeFinalClass\" << endl;\n }\n friend class MyClass;\n};\nclass MyClass : virtual MakeFinalClass { //this will be final class\n public:\n MyClass() {\n cout << \"This is constructor of the final Class\" << endl;\n }\n};\n//try to make derived class\nclass MyDerivedClass : MyClass {\n public:\n MyDerivedClass() {\n cout << \"Constructor of the Derived Class\" << endl;\n }\n};\nmain() {\n MyDerivedClass derived;\n}" }, { "code": null, "e": 2677, "s": 2572, "text": "In constructor 'MyDerivedClass::MyDerivedClass()':\n[Error] 'MakeFinalClass::MakeFinalClass()' is private" }, { "code": null, "e": 2795, "s": 2677, "text": "We can create the objects of the MyClass as this is friend of the MakeFinalClass, and has access to its constructors." }, { "code": null, "e": 3222, "s": 2795, "text": "#include <iostream>\nusing namespace std;\nclass MyClass;\nclass MakeFinalClass {\n private:\n MakeFinalClass() {\n cout << \"This is constructor of the MakeFinalClass\" << endl;\n }\n friend class MyClass;\n};\nclass MyClass : virtual MakeFinalClass { //this will be final class\n public:\n MyClass() {\n cout << \"This is constructor of the final Class\" << endl;\n }\n};\nmain() {\n MyClass obj;\n}" }, { "code": null, "e": 3303, "s": 3222, "text": "This is constructor of the MakeFinalClass\nThis is constructor of the final Class" } ]
Count of numbers in given Array greater than next K elements - GeeksforGeeks
21 Dec, 2021 Given an array arr[] of integers of size N, the task is to count the number of elements whose value is greater than all the K elements to its immediate right. If there are less than K numbers to the right of the ith element, then the value of all of them must be lesser than that of the ith person. Examples: Input: arr[] = {4, 3, 1, 2, 5}, N = 5, K = 1Output: 3Explanation: The 1st ,2nd and 5th are the elements whose values are greater than the element to its right(As k = 1 consider only the next). While the 3rd element can not be considered because of the 4th element whose value is greater than the 3rd element’s value. Input: arr[] = {9, 7, 7, 7, 4}, N = 5, K = 3Output: 3Explanation: The 1st ,4th and the 5th element will be the elements whose values are greater than all 3 elements elements after it. Naive Approach: For each element check K elements to their immediate right and see if it is greater than all of those or not. Time Complexity: O(N2)Auxiliary Space: O(1) Efficient Approach: This problem can be solved using the following steps: Consider a queue for storing K elements. Add K elements from the last to the queue and keep the max of the last K values in a variable (say, max_value). Iterate over the remaining array in the backward direction from the position (N – K).While iterating pop an element from the queue and push the current element in the queue.If the current element has a value greater than max_value, then increment the count and update max_value to the current element.Else If the popped value is the same as the max_value then find the new max from the queue. While iterating pop an element from the queue and push the current element in the queue. If the current element has a value greater than max_value, then increment the count and update max_value to the current element. Else If the popped value is the same as the max_value then find the new max from the queue. Return the count value as the count of the element whose value is greater than all the k elements to its immediate right. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ code to implement the above approach#include <bits/stdc++.h>using namespace std; // Function to find// maximum element in queueint find_max(queue<int> q){ int ans = INT_MIN; // Loop to find maximum from queue while (!q.empty()) { ans = max(ans, q.front()); q.pop(); } return ans;} // Function to count the elements// whose values are greater than// all the k elements to its immediate rightint solve(int n, int k, vector<int> arr){ int max_value = INT_MIN; queue<int> q; int count = 0; int p = n - k; // Checking base cases if (n == 0) return 0; else if (k == 0) return n; // Traversing last k elements for (int i = n - 1; i >= p; i--) { q.push(arr[i]); if (arr[i] > max_value) { max_value = arr[i]; count++; } } // Traversing rest of the elements for (int i = p - 1; i >= 0; i--) { int x = q.front(); q.pop(); q.push(arr[i]); if (arr[i] > max_value) { count++; max_value = arr[i]; } else { if (x == max_value) { // If popped value // is same as max value // then update max value max_value = find_max(q); } } } return count;} // Driver Code Starts.int main(){ int N, K; N = 5; K = 1; vector<int> arr = { 4, 3, 1, 2, 5}; cout << solve(N, K, arr) << "\n"; return 0;} // Java code to implement the above approachimport java.util.ArrayList;import java.util.LinkedList;import java.util.Queue; class GFG { // Function to find // maximum element in queue public static int find_max(Queue<Integer> q) { int ans = Integer.MIN_VALUE; // Loop to find maximum from queue while (!q.isEmpty()) { ans = Math.max(ans, q.peek()); q.remove(); } return ans; } // Function to count the elements // whose values are greater than // all the k elements to its immediate right public static int solve(int n, int k, ArrayList<Integer> arr) { int max_value = Integer.MIN_VALUE; Queue<Integer> q = new LinkedList<Integer>(); int count = 0; int p = n - k; // Checking base cases if (n == 0) return 0; else if (k == 0) return n; // Traversing last k elements for (int i = n - 1; i >= p; i--) { q.add(arr.get(i)); if (arr.get(i) > max_value) { max_value = arr.get(i); count++; } } // Traversing rest of the elements for (int i = p - 1; i >= 0; i--) { int x = 0; if (q.size() > 0) { x = q.peek(); q.remove(); } q.add(arr.get(i)); if (arr.get(i) > max_value) { count++; max_value = arr.get(i); } else { if (x == max_value) { // If popped value // is same as max value // then update max value max_value = find_max(q); } } } return count; } // Driver Code Starts. public static void main(String args[]) { int N, K; N = 5; K = 1; ArrayList<Integer> arr = new ArrayList<>(); arr.add(4); arr.add(3); arr.add(1); arr.add(2); arr.add(5); System.out.println(solve(N, K, arr)); }} // This code is contributed by saurabh_jaiswal. # Python3 code to implement the above approachfrom queue import Queueimport copyINT_MIN = -2147483648 # Function to find# maximum element in queuedef find_max(q): ans = INT_MIN # Loop to find maximum from queue while (not q.empty()): ans = max(ans, q.get()) return ans # Function to count the elements# whose values are greater than# all the k elements to its immediate rightdef solve(n, k, arr): max_value = INT_MIN q = Queue() count = 0 p = n - k # Checking base cases if (n == 0): return 0 elif (k == 0): return n # Traversing last k elements for i in range(n - 1, p - 1, -1): q.put(arr[i]) if (arr[i] > max_value): max_value = arr[i] count += 1 # Traversing rest of the elements for i in range(p - 1, -1, -1): x = q.get() q.put(arr[i]) if (arr[i] > max_value): count += 1 max_value = arr[i] else: if (x == max_value): # If popped value is same # as max value then update # max value temp = Queue() for i in q.queue: temp.put(i) max_value = find_max(temp) return count # Driver codeif __name__ == "__main__": N = 5 K = 1 arr = [ 4, 3, 1, 2, 5 ] print(solve(N, K, arr)) # This code is contributed by rakeshsahni // C# code to implement the above approachusing System;using System.Collections.Generic; public class GFG { // Function to find // maximum element in queue public static int find_max(Queue<int> q) { int ans = int.MinValue; // Loop to find maximum from queue while (q.Count != 0) { ans = Math.Max(ans, q.Peek()); q.Dequeue(); } return ans; } // Function to count the elements // whose values are greater than // all the k elements to its immediate right public static int solve(int n, int k, List<int> arr) { int max_value = int.MinValue; Queue<int> q = new Queue<int>(); int count = 0; int p = n - k; // Checking base cases if (n == 0) return 0; else if (k == 0) return n; // Traversing last k elements for (int i = n - 1; i >= p; i--) { q.Enqueue(arr[i]); if (arr[i] > max_value) { max_value = arr[i]; count++; } } // Traversing rest of the elements for (int i = p - 1; i >= 0; i--) { int x = 0; if (q.Count > 0) { x = q.Peek(); q.Dequeue(); } q.Enqueue(arr[i]); if (arr[i] > max_value) { count++; max_value = arr[i]; } else { if (x == max_value) { // If popped value // is same as max value // then update max value max_value = find_max(q); } } } return count; } // Driver Code Starts. public static void Main(String []args) { int N, K; N = 5; K = 1; List<int> arr = new List<int>(); arr.Add(4); arr.Add(3); arr.Add(1); arr.Add(2); arr.Add(5); Console.WriteLine(solve(N, K, arr)); }} // This code is contributed by shikhasingrajput <script>// Javascript code to implement the above approach // Function to find// maximum element in queuefunction find_max(q) { let ans = Number.MIN_SAFE_INTEGER; // Loop to find maximum from queue while (q.length) { ans = Math.max(ans, q[0]); q.pop(); } return ans;} // Function to count the elements// whose values are greater than// all the k elements to its immediate rightfunction solve(n, k, arr) { let max_value = Number.MIN_SAFE_INTEGER; let q = []; let count = 0; let p = n - k; // Checking base cases if (n == 0) return 0; else if (k == 0) return n; // Traversing last k elements for (let i = n - 1; i >= p; i--) { q.push(arr[i]); if (arr[i] > max_value) { max_value = arr[i]; count++; } } // Traversing rest of the elements for (let i = p - 1; i >= 0; i--) { let x = q[0]; q.pop(); q.push(arr[i]); if (arr[i] > max_value) { count++; max_value = arr[i]; } else { if (x == max_value) { // If popped value // is same as max value // then update max value max_value = find_max(q); } } } return count;} // Driver Code Starts. let N, K;N = 5;K = 1;let arr = [4, 3, 1, 2, 5]; document.write(solve(N, K, arr)) // This code is contributed by gfgking.</script> 3 Time Complexity: O(N)Auxiliary Space: O(K) Space Optimized Approach: The problem can be solved with lesser space using two pointer approach. Follow the steps mentioned below. Initialize two-pointer (say “left” and “right”) pointing to the end of the array. The left pointer points to the starting index of the K-sized window and the right pointer points to the maximum value in that window. If the value at the left pointer is greater than the value at the right pointer, increase answer count by 1. (Because it means it is greater than all the K elements to its immediate right) If at any point the window size exceeds K, decrement the right pointer by one and adjust it to point to the maximum value of the current window. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ code to implement the above approach#include <bits/stdc++.h>using namespace std; // Function to count the elements// whose values are greater than// all k elements to its immediate rightint solve(int n, int k, vector<int> arr){ int count = 1; int left = n - 2, right = n - 1; // Checking base cases if (n == 0) return 0; else if (k == 0) return n; // Loop to implement two-pointer approach for (; left >= 0; left--) { if (right - left > k) { right--; while (arr[left] > arr[right]) right--; if (right == left) count++; } else if (arr[left] > arr[right]) { count++; right = left; } } return count;} // Driver Code Starts.int main(){ int N, K; N = 5; K = 1; vector<int> arr = { 4, 3, 1, 2, 5}; cout << solve(N, K, arr); return 0;} // Java code to implement the above approachimport java.io.*; class GFG{ // Function to count the elements// whose values are greater than// all k elements to its immediate rightstatic int solve(int n, int k, int[] arr){ int count = 1; int left = n - 2, right = n - 1; // Checking base cases if (n == 0) return 0; else if (k == 0) return n; // Loop to implement two-pointer approach for(; left >= 0; left--) { if (right - left > k) { right--; while (arr[left] > arr[right]) right--; if (right == left) count++; } else if (arr[left] > arr[right]) { count++; right = left; } } return count;} // Driver Codepublic static void main(String[] args){ int N, K; N = 5; K = 1; int[] arr = { 4, 3, 1, 2, 5 }; System.out.println(solve(N, K, arr));}} // This code is contributed by Potta Lokesh # Python 3 code to implement the above approach # Function to count the elements# whose values are greater than# all k elements to its immediate rightdef solve(n, k, arr): count = 1 left = n - 2 right = n - 1 # Checking base cases if (n == 0): return 0 elif (k == 0): return n # Loop to implement two-pointer approach while left >= 0: if (right - left > k): right -= 1 while (arr[left] > arr[right]): right -= 1 if (right == left): count += 1 elif (arr[left] > arr[right]): count += 1 right = left left -= 1 return count # Driver Codeif __name__ == "__main__": N = 5 K = 1 arr = [4, 3, 1, 2, 5] print(solve(N, K, arr)) # This code is contributed by ukasp. // C# code to implement the above approachusing System; public class GFG{ // Function to count the elements// whose values are greater than// all k elements to its immediate rightstatic int solve(int n, int k, int[] arr){ int count = 1; int left = n - 2, right = n - 1; // Checking base cases if (n == 0) return 0; else if (k == 0) return n; // Loop to implement two-pointer approach for(; left >= 0; left--) { if (right - left > k) { right--; while (arr[left] > arr[right]) right--; if (right == left) count++; } else if (arr[left] > arr[right]) { count++; right = left; } } return count;} // Driver Codepublic static void Main(String[] args){ int N, K; N = 5; K = 1; int[] arr = { 4, 3, 1, 2, 5 }; Console.WriteLine(solve(N, K, arr));}} // This code is contributed by 29AjayKumar <script>// javascript code to implement the above approach // Function to count the elements// whose values are greater than// all k elements to its immediate rightfunction solve(n , k, arr){ var count = 1; var left = n - 2, right = n - 1; // Checking base cases if (n == 0) return 0; else if (k == 0) return n; // Loop to implement two-pointer approach for(; left >= 0; left--) { if (right - left > k) { right--; while (arr[left] > arr[right]) right--; if (right == left) count++; } else if (arr[left] > arr[right]) { count++; right = left; } } return count;} // Driver Codevar N, K;N = 5;K = 1;var arr = [ 4, 3, 1, 2, 5 ]; document.write(solve(N, K, arr)); // This code is contributed by 29AjayKumar</script> 3 Time Complexity: O(N)Auxiliary Space: O(1) lokeshpotta20 rakeshsahni 29AjayKumar gfgking _saurabh_jaiswal shikhasingrajput ukasp two-pointer-algorithm Arrays Queue two-pointer-algorithm Arrays Queue Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Next Greater Element Window Sliding Technique Count pairs with given sum Program to find sum of elements in a given array Reversal algorithm for array rotation Breadth First Search or BFS for a Graph Level Order Binary Tree Traversal Queue in Python Queue Interface In Java Queue using Stacks
[ { "code": null, "e": 24431, "s": 24403, "text": "\n21 Dec, 2021" }, { "code": null, "e": 24730, "s": 24431, "text": "Given an array arr[] of integers of size N, the task is to count the number of elements whose value is greater than all the K elements to its immediate right. If there are less than K numbers to the right of the ith element, then the value of all of them must be lesser than that of the ith person." }, { "code": null, "e": 24740, "s": 24730, "text": "Examples:" }, { "code": null, "e": 25058, "s": 24740, "text": "Input: arr[] = {4, 3, 1, 2, 5}, N = 5, K = 1Output: 3Explanation: The 1st ,2nd and 5th are the elements whose values are greater than the element to its right(As k = 1 consider only the next). While the 3rd element can not be considered because of the 4th element whose value is greater than the 3rd element’s value. " }, { "code": null, "e": 25242, "s": 25058, "text": "Input: arr[] = {9, 7, 7, 7, 4}, N = 5, K = 3Output: 3Explanation: The 1st ,4th and the 5th element will be the elements whose values are greater than all 3 elements elements after it." }, { "code": null, "e": 25368, "s": 25242, "text": "Naive Approach: For each element check K elements to their immediate right and see if it is greater than all of those or not." }, { "code": null, "e": 25412, "s": 25368, "text": "Time Complexity: O(N2)Auxiliary Space: O(1)" }, { "code": null, "e": 25486, "s": 25412, "text": "Efficient Approach: This problem can be solved using the following steps:" }, { "code": null, "e": 25527, "s": 25486, "text": "Consider a queue for storing K elements." }, { "code": null, "e": 25639, "s": 25527, "text": "Add K elements from the last to the queue and keep the max of the last K values in a variable (say, max_value)." }, { "code": null, "e": 26032, "s": 25639, "text": "Iterate over the remaining array in the backward direction from the position (N – K).While iterating pop an element from the queue and push the current element in the queue.If the current element has a value greater than max_value, then increment the count and update max_value to the current element.Else If the popped value is the same as the max_value then find the new max from the queue." }, { "code": null, "e": 26121, "s": 26032, "text": "While iterating pop an element from the queue and push the current element in the queue." }, { "code": null, "e": 26250, "s": 26121, "text": "If the current element has a value greater than max_value, then increment the count and update max_value to the current element." }, { "code": null, "e": 26342, "s": 26250, "text": "Else If the popped value is the same as the max_value then find the new max from the queue." }, { "code": null, "e": 26464, "s": 26342, "text": "Return the count value as the count of the element whose value is greater than all the k elements to its immediate right." }, { "code": null, "e": 26516, "s": 26464, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26520, "s": 26516, "text": "C++" }, { "code": null, "e": 26525, "s": 26520, "text": "Java" }, { "code": null, "e": 26533, "s": 26525, "text": "Python3" }, { "code": null, "e": 26536, "s": 26533, "text": "C#" }, { "code": null, "e": 26547, "s": 26536, "text": "Javascript" }, { "code": "// C++ code to implement the above approach#include <bits/stdc++.h>using namespace std; // Function to find// maximum element in queueint find_max(queue<int> q){ int ans = INT_MIN; // Loop to find maximum from queue while (!q.empty()) { ans = max(ans, q.front()); q.pop(); } return ans;} // Function to count the elements// whose values are greater than// all the k elements to its immediate rightint solve(int n, int k, vector<int> arr){ int max_value = INT_MIN; queue<int> q; int count = 0; int p = n - k; // Checking base cases if (n == 0) return 0; else if (k == 0) return n; // Traversing last k elements for (int i = n - 1; i >= p; i--) { q.push(arr[i]); if (arr[i] > max_value) { max_value = arr[i]; count++; } } // Traversing rest of the elements for (int i = p - 1; i >= 0; i--) { int x = q.front(); q.pop(); q.push(arr[i]); if (arr[i] > max_value) { count++; max_value = arr[i]; } else { if (x == max_value) { // If popped value // is same as max value // then update max value max_value = find_max(q); } } } return count;} // Driver Code Starts.int main(){ int N, K; N = 5; K = 1; vector<int> arr = { 4, 3, 1, 2, 5}; cout << solve(N, K, arr) << \"\\n\"; return 0;}", "e": 28024, "s": 26547, "text": null }, { "code": "// Java code to implement the above approachimport java.util.ArrayList;import java.util.LinkedList;import java.util.Queue; class GFG { // Function to find // maximum element in queue public static int find_max(Queue<Integer> q) { int ans = Integer.MIN_VALUE; // Loop to find maximum from queue while (!q.isEmpty()) { ans = Math.max(ans, q.peek()); q.remove(); } return ans; } // Function to count the elements // whose values are greater than // all the k elements to its immediate right public static int solve(int n, int k, ArrayList<Integer> arr) { int max_value = Integer.MIN_VALUE; Queue<Integer> q = new LinkedList<Integer>(); int count = 0; int p = n - k; // Checking base cases if (n == 0) return 0; else if (k == 0) return n; // Traversing last k elements for (int i = n - 1; i >= p; i--) { q.add(arr.get(i)); if (arr.get(i) > max_value) { max_value = arr.get(i); count++; } } // Traversing rest of the elements for (int i = p - 1; i >= 0; i--) { int x = 0; if (q.size() > 0) { x = q.peek(); q.remove(); } q.add(arr.get(i)); if (arr.get(i) > max_value) { count++; max_value = arr.get(i); } else { if (x == max_value) { // If popped value // is same as max value // then update max value max_value = find_max(q); } } } return count; } // Driver Code Starts. public static void main(String args[]) { int N, K; N = 5; K = 1; ArrayList<Integer> arr = new ArrayList<>(); arr.add(4); arr.add(3); arr.add(1); arr.add(2); arr.add(5); System.out.println(solve(N, K, arr)); }} // This code is contributed by saurabh_jaiswal.", "e": 30145, "s": 28024, "text": null }, { "code": "# Python3 code to implement the above approachfrom queue import Queueimport copyINT_MIN = -2147483648 # Function to find# maximum element in queuedef find_max(q): ans = INT_MIN # Loop to find maximum from queue while (not q.empty()): ans = max(ans, q.get()) return ans # Function to count the elements# whose values are greater than# all the k elements to its immediate rightdef solve(n, k, arr): max_value = INT_MIN q = Queue() count = 0 p = n - k # Checking base cases if (n == 0): return 0 elif (k == 0): return n # Traversing last k elements for i in range(n - 1, p - 1, -1): q.put(arr[i]) if (arr[i] > max_value): max_value = arr[i] count += 1 # Traversing rest of the elements for i in range(p - 1, -1, -1): x = q.get() q.put(arr[i]) if (arr[i] > max_value): count += 1 max_value = arr[i] else: if (x == max_value): # If popped value is same # as max value then update # max value temp = Queue() for i in q.queue: temp.put(i) max_value = find_max(temp) return count # Driver codeif __name__ == \"__main__\": N = 5 K = 1 arr = [ 4, 3, 1, 2, 5 ] print(solve(N, K, arr)) # This code is contributed by rakeshsahni", "e": 31616, "s": 30145, "text": null }, { "code": "// C# code to implement the above approachusing System;using System.Collections.Generic; public class GFG { // Function to find // maximum element in queue public static int find_max(Queue<int> q) { int ans = int.MinValue; // Loop to find maximum from queue while (q.Count != 0) { ans = Math.Max(ans, q.Peek()); q.Dequeue(); } return ans; } // Function to count the elements // whose values are greater than // all the k elements to its immediate right public static int solve(int n, int k, List<int> arr) { int max_value = int.MinValue; Queue<int> q = new Queue<int>(); int count = 0; int p = n - k; // Checking base cases if (n == 0) return 0; else if (k == 0) return n; // Traversing last k elements for (int i = n - 1; i >= p; i--) { q.Enqueue(arr[i]); if (arr[i] > max_value) { max_value = arr[i]; count++; } } // Traversing rest of the elements for (int i = p - 1; i >= 0; i--) { int x = 0; if (q.Count > 0) { x = q.Peek(); q.Dequeue(); } q.Enqueue(arr[i]); if (arr[i] > max_value) { count++; max_value = arr[i]; } else { if (x == max_value) { // If popped value // is same as max value // then update max value max_value = find_max(q); } } } return count; } // Driver Code Starts. public static void Main(String []args) { int N, K; N = 5; K = 1; List<int> arr = new List<int>(); arr.Add(4); arr.Add(3); arr.Add(1); arr.Add(2); arr.Add(5); Console.WriteLine(solve(N, K, arr)); }} // This code is contributed by shikhasingrajput", "e": 33647, "s": 31616, "text": null }, { "code": "<script>// Javascript code to implement the above approach // Function to find// maximum element in queuefunction find_max(q) { let ans = Number.MIN_SAFE_INTEGER; // Loop to find maximum from queue while (q.length) { ans = Math.max(ans, q[0]); q.pop(); } return ans;} // Function to count the elements// whose values are greater than// all the k elements to its immediate rightfunction solve(n, k, arr) { let max_value = Number.MIN_SAFE_INTEGER; let q = []; let count = 0; let p = n - k; // Checking base cases if (n == 0) return 0; else if (k == 0) return n; // Traversing last k elements for (let i = n - 1; i >= p; i--) { q.push(arr[i]); if (arr[i] > max_value) { max_value = arr[i]; count++; } } // Traversing rest of the elements for (let i = p - 1; i >= 0; i--) { let x = q[0]; q.pop(); q.push(arr[i]); if (arr[i] > max_value) { count++; max_value = arr[i]; } else { if (x == max_value) { // If popped value // is same as max value // then update max value max_value = find_max(q); } } } return count;} // Driver Code Starts. let N, K;N = 5;K = 1;let arr = [4, 3, 1, 2, 5]; document.write(solve(N, K, arr)) // This code is contributed by gfgking.</script>", "e": 35095, "s": 33647, "text": null }, { "code": null, "e": 35097, "s": 35095, "text": "3" }, { "code": null, "e": 35140, "s": 35097, "text": "Time Complexity: O(N)Auxiliary Space: O(K)" }, { "code": null, "e": 35273, "s": 35140, "text": "Space Optimized Approach: The problem can be solved with lesser space using two pointer approach. Follow the steps mentioned below. " }, { "code": null, "e": 35355, "s": 35273, "text": "Initialize two-pointer (say “left” and “right”) pointing to the end of the array." }, { "code": null, "e": 35489, "s": 35355, "text": "The left pointer points to the starting index of the K-sized window and the right pointer points to the maximum value in that window." }, { "code": null, "e": 35678, "s": 35489, "text": "If the value at the left pointer is greater than the value at the right pointer, increase answer count by 1. (Because it means it is greater than all the K elements to its immediate right)" }, { "code": null, "e": 35823, "s": 35678, "text": "If at any point the window size exceeds K, decrement the right pointer by one and adjust it to point to the maximum value of the current window." }, { "code": null, "e": 35875, "s": 35823, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 35879, "s": 35875, "text": "C++" }, { "code": null, "e": 35884, "s": 35879, "text": "Java" }, { "code": null, "e": 35892, "s": 35884, "text": "Python3" }, { "code": null, "e": 35895, "s": 35892, "text": "C#" }, { "code": null, "e": 35906, "s": 35895, "text": "Javascript" }, { "code": "// C++ code to implement the above approach#include <bits/stdc++.h>using namespace std; // Function to count the elements// whose values are greater than// all k elements to its immediate rightint solve(int n, int k, vector<int> arr){ int count = 1; int left = n - 2, right = n - 1; // Checking base cases if (n == 0) return 0; else if (k == 0) return n; // Loop to implement two-pointer approach for (; left >= 0; left--) { if (right - left > k) { right--; while (arr[left] > arr[right]) right--; if (right == left) count++; } else if (arr[left] > arr[right]) { count++; right = left; } } return count;} // Driver Code Starts.int main(){ int N, K; N = 5; K = 1; vector<int> arr = { 4, 3, 1, 2, 5}; cout << solve(N, K, arr); return 0;}", "e": 36821, "s": 35906, "text": null }, { "code": "// Java code to implement the above approachimport java.io.*; class GFG{ // Function to count the elements// whose values are greater than// all k elements to its immediate rightstatic int solve(int n, int k, int[] arr){ int count = 1; int left = n - 2, right = n - 1; // Checking base cases if (n == 0) return 0; else if (k == 0) return n; // Loop to implement two-pointer approach for(; left >= 0; left--) { if (right - left > k) { right--; while (arr[left] > arr[right]) right--; if (right == left) count++; } else if (arr[left] > arr[right]) { count++; right = left; } } return count;} // Driver Codepublic static void main(String[] args){ int N, K; N = 5; K = 1; int[] arr = { 4, 3, 1, 2, 5 }; System.out.println(solve(N, K, arr));}} // This code is contributed by Potta Lokesh", "e": 37806, "s": 36821, "text": null }, { "code": "# Python 3 code to implement the above approach # Function to count the elements# whose values are greater than# all k elements to its immediate rightdef solve(n, k, arr): count = 1 left = n - 2 right = n - 1 # Checking base cases if (n == 0): return 0 elif (k == 0): return n # Loop to implement two-pointer approach while left >= 0: if (right - left > k): right -= 1 while (arr[left] > arr[right]): right -= 1 if (right == left): count += 1 elif (arr[left] > arr[right]): count += 1 right = left left -= 1 return count # Driver Codeif __name__ == \"__main__\": N = 5 K = 1 arr = [4, 3, 1, 2, 5] print(solve(N, K, arr)) # This code is contributed by ukasp.", "e": 38633, "s": 37806, "text": null }, { "code": "// C# code to implement the above approachusing System; public class GFG{ // Function to count the elements// whose values are greater than// all k elements to its immediate rightstatic int solve(int n, int k, int[] arr){ int count = 1; int left = n - 2, right = n - 1; // Checking base cases if (n == 0) return 0; else if (k == 0) return n; // Loop to implement two-pointer approach for(; left >= 0; left--) { if (right - left > k) { right--; while (arr[left] > arr[right]) right--; if (right == left) count++; } else if (arr[left] > arr[right]) { count++; right = left; } } return count;} // Driver Codepublic static void Main(String[] args){ int N, K; N = 5; K = 1; int[] arr = { 4, 3, 1, 2, 5 }; Console.WriteLine(solve(N, K, arr));}} // This code is contributed by 29AjayKumar", "e": 39617, "s": 38633, "text": null }, { "code": "<script>// javascript code to implement the above approach // Function to count the elements// whose values are greater than// all k elements to its immediate rightfunction solve(n , k, arr){ var count = 1; var left = n - 2, right = n - 1; // Checking base cases if (n == 0) return 0; else if (k == 0) return n; // Loop to implement two-pointer approach for(; left >= 0; left--) { if (right - left > k) { right--; while (arr[left] > arr[right]) right--; if (right == left) count++; } else if (arr[left] > arr[right]) { count++; right = left; } } return count;} // Driver Codevar N, K;N = 5;K = 1;var arr = [ 4, 3, 1, 2, 5 ]; document.write(solve(N, K, arr)); // This code is contributed by 29AjayKumar</script>", "e": 40514, "s": 39617, "text": null }, { "code": null, "e": 40516, "s": 40514, "text": "3" }, { "code": null, "e": 40559, "s": 40516, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 40575, "s": 40561, "text": "lokeshpotta20" }, { "code": null, "e": 40587, "s": 40575, "text": "rakeshsahni" }, { "code": null, "e": 40599, "s": 40587, "text": "29AjayKumar" }, { "code": null, "e": 40607, "s": 40599, "text": "gfgking" }, { "code": null, "e": 40624, "s": 40607, "text": "_saurabh_jaiswal" }, { "code": null, "e": 40641, "s": 40624, "text": "shikhasingrajput" }, { "code": null, "e": 40647, "s": 40641, "text": "ukasp" }, { "code": null, "e": 40669, "s": 40647, "text": "two-pointer-algorithm" }, { "code": null, "e": 40676, "s": 40669, "text": "Arrays" }, { "code": null, "e": 40682, "s": 40676, "text": "Queue" }, { "code": null, "e": 40704, "s": 40682, "text": "two-pointer-algorithm" }, { "code": null, "e": 40711, "s": 40704, "text": "Arrays" }, { "code": null, "e": 40717, "s": 40711, "text": "Queue" }, { "code": null, "e": 40815, "s": 40717, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40824, "s": 40815, "text": "Comments" }, { "code": null, "e": 40837, "s": 40824, "text": "Old Comments" }, { "code": null, "e": 40858, "s": 40837, "text": "Next Greater Element" }, { "code": null, "e": 40883, "s": 40858, "text": "Window Sliding Technique" }, { "code": null, "e": 40910, "s": 40883, "text": "Count pairs with given sum" }, { "code": null, "e": 40959, "s": 40910, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 40997, "s": 40959, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 41037, "s": 40997, "text": "Breadth First Search or BFS for a Graph" }, { "code": null, "e": 41071, "s": 41037, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 41087, "s": 41071, "text": "Queue in Python" }, { "code": null, "e": 41111, "s": 41087, "text": "Queue Interface In Java" } ]
How to prepare a Python date object to be inserted into MongoDB?
You can use the pymongo library in Python to connect to a MongoDB database and use it to insert, update, delete, etc objects in Python. The library supports Python datetime objects out of the box and you dont need to do anything special to insert dates in Mongo using PyMongo. from pymongo import MongoClient # This will try to connect to MongoDB on the default port and host client = MongoClient() db = client.test_database # Insert the given dictionary to the objects collection: result = db.objects.insert_one({"last_modified": datetime.datetime.utcnow()}) print("Object inserted!") This will give the output − Object inserted! Note − Always use datetime.datetime.utcnow(), which returns the current time in UTC, instead of datetime.datetime.now(), which returns the current local time.
[ { "code": null, "e": 1339, "s": 1062, "text": "You can use the pymongo library in Python to connect to a MongoDB database and use it to insert, update, delete, etc objects in Python. The library supports Python datetime objects out of the box and you dont need to do anything special to insert dates in Mongo using PyMongo." }, { "code": null, "e": 1648, "s": 1339, "text": "from pymongo import MongoClient\n# This will try to connect to MongoDB on the default port and host\nclient = MongoClient()\ndb = client.test_database\n# Insert the given dictionary to the objects collection:\nresult = db.objects.insert_one({\"last_modified\": datetime.datetime.utcnow()})\nprint(\"Object inserted!\")" }, { "code": null, "e": 1676, "s": 1648, "text": "This will give the output −" }, { "code": null, "e": 1693, "s": 1676, "text": "Object inserted!" }, { "code": null, "e": 1852, "s": 1693, "text": "Note − Always use datetime.datetime.utcnow(), which returns the current time in UTC, instead of datetime.datetime.now(), which returns the current local time." } ]
F# - Options
The option type in F# is used in calculations when there may or may not exist a value for a variable or function. Option types are used for representing optional values in calculations. They can have two possible values − Some(x) or None. For example, a function performing a division will return a value in normal situation, but will throw exceptions in case of a zero denominator. Using options here will help to indicate whether the function has succeeded or failed. An option has an underlying type and can hold a value of that type, or it might not have a value. Let us take the example of division function. The following program explains this − Let us write a function div, and send two arguments to it 20 and 5 − let div x y = x / y let res = div 20 5 printfn "Result: %d" res When you compile and execute the program, it yields the following output − Result: 4 If the second argument is zero, then the program throws an exception − let div x y = x / y let res = div 20 0 printfn "Result: %d" res When you compile and execute the program, it yields the following output − Unhandled Exception: System.DivideByZeroException: Division by zero In such cases, we can use option types to return Some (value) when the operation is successful or None if the operation fails. The following example demonstrates the use of options − let div x y = match y with | 0 -> None | _ -> Some(x/y) let res : int option = div 20 4 printfn "Result: %A " res When you compile and execute the program, it yields the following output − Result: Some 5 The option type supports the following properties and methods − let checkPositive (a : int) = if a > 0 then Some(a) else None let res : int option = checkPositive(-31) printfn "Result: %A " res When you compile and execute the program, it yields the following output − Result: <null> let div x y = match y with | 0 -> None | _ -> Some(x/y) let res : int option = div 20 4 printfn "Result: %A " res printfn "Result: %A " res.Value When you compile and execute the program, it yields the following output − Result: Some 5 Result: 5 let isHundred = function | Some(100) -> true | Some(_) | None -> false printfn "%A" (isHundred (Some(45))) printfn "%A" (isHundred (Some(100))) printfn "%A" (isHundred None) When you compile and execute the program, it yields the following output − false true false Print Add Notes Bookmark this page
[ { "code": null, "e": 2400, "s": 2161, "text": "The option type in F# is used in calculations when there may or may not exist a value for a variable or function. Option types are used for representing optional values in calculations. They can have two possible values − Some(x) or None." }, { "code": null, "e": 2631, "s": 2400, "text": "For example, a function performing a division will return a value in normal situation, but will throw exceptions in case of a zero denominator. Using options here will help to indicate whether the function has succeeded or failed." }, { "code": null, "e": 2729, "s": 2631, "text": "An option has an underlying type and can hold a value of that type, or it might not have a value." }, { "code": null, "e": 2813, "s": 2729, "text": "Let us take the example of division function. The following program explains this −" }, { "code": null, "e": 2882, "s": 2813, "text": "Let us write a function div, and send two arguments to it 20 and 5 −" }, { "code": null, "e": 2946, "s": 2882, "text": "let div x y = x / y\nlet res = div 20 5\nprintfn \"Result: %d\" res" }, { "code": null, "e": 3021, "s": 2946, "text": "When you compile and execute the program, it yields the following output −" }, { "code": null, "e": 3032, "s": 3021, "text": "Result: 4\n" }, { "code": null, "e": 3103, "s": 3032, "text": "If the second argument is zero, then the program throws an exception −" }, { "code": null, "e": 3167, "s": 3103, "text": "let div x y = x / y\nlet res = div 20 0\nprintfn \"Result: %d\" res" }, { "code": null, "e": 3242, "s": 3167, "text": "When you compile and execute the program, it yields the following output −" }, { "code": null, "e": 3311, "s": 3242, "text": "Unhandled Exception:\nSystem.DivideByZeroException: Division by zero\n" }, { "code": null, "e": 3438, "s": 3311, "text": "In such cases, we can use option types to return Some (value) when the operation is successful or None if the operation fails." }, { "code": null, "e": 3494, "s": 3438, "text": "The following example demonstrates the use of options −" }, { "code": null, "e": 3618, "s": 3494, "text": "let div x y =\n match y with\n | 0 -> None\n | _ -> Some(x/y)\n\nlet res : int option = div 20 4\nprintfn \"Result: %A \" res" }, { "code": null, "e": 3693, "s": 3618, "text": "When you compile and execute the program, it yields the following output −" }, { "code": null, "e": 3709, "s": 3693, "text": "Result: Some 5\n" }, { "code": null, "e": 3773, "s": 3709, "text": "The option type supports the following properties and methods −" }, { "code": null, "e": 3922, "s": 3773, "text": "let checkPositive (a : int) =\n if a > 0 then\n Some(a)\n else\n None\n\nlet res : int option = checkPositive(-31)\nprintfn \"Result: %A \" res" }, { "code": null, "e": 3997, "s": 3922, "text": "When you compile and execute the program, it yields the following output −" }, { "code": null, "e": 4013, "s": 3997, "text": "Result: <null>\n" }, { "code": null, "e": 4169, "s": 4013, "text": "let div x y =\n match y with\n | 0 -> None\n | _ -> Some(x/y)\n\nlet res : int option = div 20 4\nprintfn \"Result: %A \" res\nprintfn \"Result: %A \" res.Value" }, { "code": null, "e": 4244, "s": 4169, "text": "When you compile and execute the program, it yields the following output −" }, { "code": null, "e": 4270, "s": 4244, "text": "Result: Some 5\nResult: 5\n" }, { "code": null, "e": 4451, "s": 4270, "text": "let isHundred = function\n | Some(100) -> true\n | Some(_) | None -> false\n\nprintfn \"%A\" (isHundred (Some(45)))\nprintfn \"%A\" (isHundred (Some(100)))\nprintfn \"%A\" (isHundred None)" }, { "code": null, "e": 4526, "s": 4451, "text": "When you compile and execute the program, it yields the following output −" }, { "code": null, "e": 4544, "s": 4526, "text": "false\ntrue\nfalse\n" }, { "code": null, "e": 4551, "s": 4544, "text": " Print" }, { "code": null, "e": 4562, "s": 4551, "text": " Add Notes" } ]
What is MIME in the Computer Network?
MIME represents Multi-Purpose Internet Mail Extensions. It is a development to the Internet email protocol that enables its users to exchange several kinds of data files over the Internet, including images, audio, and video. The MIME is required if the text in character sets other than the American Standard Code for Information Interchange (ASCII). Virtually, all human-written Internet email and a fairly large proportion of automated email is transmitted via Simple Mail Transfer Protocol (SMTP) in MIME format. MIME was designed mainly for SMTP, but the content types defined by MIME standards are important also in communication protocols outside of email, such as Hypertext Transfer Protocol (HTTP). There are five header fields represented in MIME which are as follows − MIME-version − It denotes the MIME version being used. The current version is 1.1. It is defined as MIME-version: 1.1. MIME-version − It denotes the MIME version being used. The current version is 1.1. It is defined as MIME-version: 1.1. Content-type − It defines the type and subtype of the data in the body of the message. The content type and content subtype are divided by a slash. This field defines how the object in the body is to be executed. The default value is plaintext in US ASCII. Content-type − It defines the type and subtype of the data in the body of the message. The content type and content subtype are divided by a slash. This field defines how the object in the body is to be executed. The default value is plaintext in US ASCII. The content-type field is represented as follows − Context-type: <type/subtype; parameters> Content-transfer encoding − It defines how the object inside the body has been encoded to US ASCII to create it acceptable for mail transfer. Thus, it determines the method used to encode the message into 0s and 1s for transport. Content-transfer encoding − It defines how the object inside the body has been encoded to US ASCII to create it acceptable for mail transfer. Thus, it determines the method used to encode the message into 0s and 1s for transport. The content transfer encoding field is represented as follows − Content-transfer-encoding : <type> Content-Description − This field tells what the message is. It is the form of ASCII recipient will know whether it is worth decoding and reading the message. Content-Description − This field tells what the message is. It is the form of ASCII recipient will know whether it is worth decoding and reading the message. Content-ID − This field identifies the contents. Its format is the same as the format of the standard Message-Id header. Content-ID − This field identifies the contents. Its format is the same as the format of the standard Message-Id header.
[ { "code": null, "e": 1287, "s": 1062, "text": "MIME represents Multi-Purpose Internet Mail Extensions. It is a development to the Internet email protocol that enables its users to exchange several kinds of data files over the Internet, including images, audio, and video." }, { "code": null, "e": 1578, "s": 1287, "text": "The MIME is required if the text in character sets other than the American Standard Code for Information Interchange (ASCII). Virtually, all human-written Internet email and a fairly large proportion of automated email is transmitted via Simple Mail Transfer Protocol (SMTP) in MIME format." }, { "code": null, "e": 1769, "s": 1578, "text": "MIME was designed mainly for SMTP, but the content types defined by MIME standards are important also in communication protocols outside of email, such as Hypertext Transfer Protocol (HTTP)." }, { "code": null, "e": 1841, "s": 1769, "text": "There are five header fields represented in MIME which are as follows −" }, { "code": null, "e": 1960, "s": 1841, "text": "MIME-version − It denotes the MIME version being used. The current version is 1.1. It is defined as MIME-version: 1.1." }, { "code": null, "e": 2079, "s": 1960, "text": "MIME-version − It denotes the MIME version being used. The current version is 1.1. It is defined as MIME-version: 1.1." }, { "code": null, "e": 2336, "s": 2079, "text": "Content-type − It defines the type and subtype of the data in the body of the message. The content type and content subtype are divided by a slash. This field defines how the object in the body is to be executed. The default value is plaintext in US ASCII." }, { "code": null, "e": 2593, "s": 2336, "text": "Content-type − It defines the type and subtype of the data in the body of the message. The content type and content subtype are divided by a slash. This field defines how the object in the body is to be executed. The default value is plaintext in US ASCII." }, { "code": null, "e": 2644, "s": 2593, "text": "The content-type field is represented as follows −" }, { "code": null, "e": 2685, "s": 2644, "text": "Context-type: <type/subtype; parameters>" }, { "code": null, "e": 2915, "s": 2685, "text": "Content-transfer encoding − It defines how the object inside the body has been encoded to US ASCII to create it acceptable for mail transfer. Thus, it determines the method used to encode the message into 0s and 1s for transport." }, { "code": null, "e": 3145, "s": 2915, "text": "Content-transfer encoding − It defines how the object inside the body has been encoded to US ASCII to create it acceptable for mail transfer. Thus, it determines the method used to encode the message into 0s and 1s for transport." }, { "code": null, "e": 3209, "s": 3145, "text": "The content transfer encoding field is represented as follows −" }, { "code": null, "e": 3244, "s": 3209, "text": "Content-transfer-encoding : <type>" }, { "code": null, "e": 3402, "s": 3244, "text": "Content-Description − This field tells what the message is. It is the form of ASCII recipient will know whether it is worth decoding and reading the message." }, { "code": null, "e": 3560, "s": 3402, "text": "Content-Description − This field tells what the message is. It is the form of ASCII recipient will know whether it is worth decoding and reading the message." }, { "code": null, "e": 3681, "s": 3560, "text": "Content-ID − This field identifies the contents. Its format is the same as the format of the standard Message-Id header." }, { "code": null, "e": 3802, "s": 3681, "text": "Content-ID − This field identifies the contents. Its format is the same as the format of the standard Message-Id header." } ]
Feature Selection Techniques. An end to end guide on how to reduce... | by Pier Paolo Ippolito | Towards Data Science
1 2 3 4 5 6 7 8 9 10 Powered by Play.ht Create audio with Play.ht Create Audio Narrations with Play.ht According to Forbes, about 2.5 quintillion bytes of data is generated every day [1]. This data can then be analysed using Data Science and Machine Learning techniques in order to provide insights and make predictions. Although, in most of the cases, the originally gathered data needs to be first preprocessed before starting any statistical analysis with it. There are many different reasons why it might be necessary to carry out a preprocessing analysis, some examples are: The gathered data is not in the right format (eg. SQL Database, JSON, CSV, etc...). Missing values and Outliers. Scaling and Normalization. Reduce Intrinsic Noise present in the dataset (part of the stored data might be corrupted). Some features in the dataset might not gather any information to our analysis. In this article, I will walk you through how to reduce the number of features in a dataset in Python using the Kaggle Mushroom Classification Dataset. All the code used in this post (and more!) is available on Kaggle and on my GitHub Account. Reducing the number of features to use during a statistical analysis can possibly lead to several benefits such as: Accuracy improvements. Overfitting risk reduction. Speed up in training. Improved Data Visualization. Increase in explainability of our model. In fact, it is statistically proven that when performing a Machine Learning task there exist an optimal number of features which should be used for every specific task (Figure 1). If more features are added than the ones which are strictly necessary, then our model performance will just decrease (because of the added noise). The real challenge is to find out what is the optimal number of features to use (this is, in fact, dependent on the amount of data we have available and by the complexity of the task we are trying to achieve). That’s where Feature Selections techniques come to our rescue! There are many different methods which can be applied for Feature Selection. Some of the most important ones are: Filter Method = filtering our dataset and taking only a subset of it containing all the relevant features (eg. correlation matrix using Pearson Correlation).Wrapper Method = follows the same objective of the FIlter Method but uses a Machine Learning model as it’s evaluation criteria (eg. Forward/Backward/Bidirectional/Recursive Feature Elimination). We feed some features to our Machine Learning model, evaluate their performance and then decide if add or remove the feature to increase accuracy. As a result, this method can be more accurate than filtering but is more computationally expensive.Embedded Method = like the FIlter Method also the Embedded Method makes use of a Machine Learning model. The difference between the two methods is that the Embedded Method examines the different training iterations of our ML model and then ranks the importance of each feature based on how much each of the features contributed to the ML model training (eg. LASSO Regularization). Filter Method = filtering our dataset and taking only a subset of it containing all the relevant features (eg. correlation matrix using Pearson Correlation). Wrapper Method = follows the same objective of the FIlter Method but uses a Machine Learning model as it’s evaluation criteria (eg. Forward/Backward/Bidirectional/Recursive Feature Elimination). We feed some features to our Machine Learning model, evaluate their performance and then decide if add or remove the feature to increase accuracy. As a result, this method can be more accurate than filtering but is more computationally expensive. Embedded Method = like the FIlter Method also the Embedded Method makes use of a Machine Learning model. The difference between the two methods is that the Embedded Method examines the different training iterations of our ML model and then ranks the importance of each feature based on how much each of the features contributed to the ML model training (eg. LASSO Regularization). In this article, I will make use of the Mushroom Classification dataset to try to predict if a Mushroom is poisonous or not by looking at the given features. While doing so, we will try different feature elimination techniques to see how this can affect training times and overall model accuracy. First of all, we need to import all the necessary libraries. The dataset we will be using in this example is shown in the figure below. Before feeding this data into our Machine Learning models I decided to One Hot Encode all the Categorical Variables, divide our data into features (X) and labels (Y), and finally in training and test sets. Decision Trees models which are based on ensembles (eg. Extra Trees and Random Forest) can be used to rank the importance of the different features. Knowing which features our model is giving most importance can be of vital importance to understand how our model is making it’s predictions (therefore making it more explainable). At the same time, we can get rid of the features which do not bring any benefit to our model (or confuse it to make a wrong decision!). As shown below, training a Random Forest classifier using all the features, led to 100% Accuracy in about 2.2s of training time. In each of the following examples, the training time of each model will be printed out on the first line of each snippet for your reference. 2.2676709799999992[[1274 0] [ 0 1164]] precision recall f1-score support 0 1.00 1.00 1.00 1274 1 1.00 1.00 1.00 1164 accuracy 1.00 2438 macro avg 1.00 1.00 1.00 2438weighted avg 1.00 1.00 1.00 2438 Once our Random Forest Classifier has been trained, we can then create a Feature Importance plot to see which features have been considered as most important for our model to make its predictions (Figure 4). In this example, just the top 7 features are shown below. Now that we know which features are considered to be most important by our Random Forest, we can try to train our model just using the top 3. As we can see below, using just 3 features lead to a decrease of just 0.03% in accuracy and halved the training time. 1.1874146949999993[[1248 26] [ 53 1111]] precision recall f1-score support 0 0.96 0.98 0.97 1274 1 0.98 0.95 0.97 1164 accuracy 0.97 2438 macro avg 0.97 0.97 0.97 2438weighted avg 0.97 0.97 0.97 2438 We can also understand how to perform Feature Selection by visualizing a trained Decision Tree structure. 0.02882629099999967[[1274 0] [ 0 1164]] precision recall f1-score support 0 1.00 1.00 1.00 1274 1 1.00 1.00 1.00 1164 accuracy 1.00 2438 macro avg 1.00 1.00 1.00 2438weighted avg 1.00 1.00 1.00 2438 The features which will be at the top of the tree structure are the ones our model retained most important in order to perform its classification. Therefore by picking just the first few features at the top and discarding the others could possibly lead to creating a model which an appreciable accuracy score. Recursive Feature Elimination (RFE) takes as input the instance of a Machine Learning model and the final desired number of features to use. It then recursively reduces the number of features to use by ranking them using the Machine Learning model accuracy as metrics. Creating a for loop in which the number of input features is our variable, it could then be possible to find out the optimal number of features our model needs by keeping track of the accuracy registered in each loop iteration. Using RFE support method, we can then find out the names of the features which have been evaluated as most important (rfe.support return a boolean list in which TRUE represent that a feature is considered as important and FALSE represent that a feature is not considered important). 210.85839133899998Overall Accuracy using RFE: 0.9675963904840033 SelectFromModel is another Scikit-learn method which can be used for Feature Selection. This method can be used with all the different types of Scikit-learn models (after fitting) which have a coef_ or feature_importances_ attribute. Compared to RFE, SelectFromModel is a less robust solution. In fact, SelectFromModel just removes less important features based on a calculated threshold (no optimization iteration process involved). In order to test SelectFromModel efficacy, I decided to use an ExtraTreesClassifier in this example. ExtraTreesClassifier (Extremely Randomized Trees) is tree-based ensemble classifier which can yield less variance compared to Random Forest methods (reducing, therefore, the risk of overfitting). The main difference between Random Forest and Extremely Randomized Trees is that in Extremely Randomized Trees nodes are sampled without replacement. 1.6003950479999958[[1274 0] [ 0 1164]] precision recall f1-score support 0 1.00 1.00 1.00 1274 1 1.00 1.00 1.00 1164 accuracy 1.00 2438 macro avg 1.00 1.00 1.00 2438weighted avg 1.00 1.00 1.00 2438 Another possible method which can be used in order to reduce the number of features in our dataset is to inspect the correlation of our features with our labels. Using Pearson correlation our returned coefficient values will vary between -1 and 1: If the correlation between two features is 0 this means that changing any of these two features will not affect the other. If the correlation between two features is greater than 0 this means that increasing the values in one feature will make increase also the values in the other feature (the closer the correlation coefficient is to 1 and the stronger is going to be this bond between the two different features). If the correlation between two features is less than 0 this means that increasing the values in one feature will make decrease the values in the other feature (the closer the correlation coefficient is to -1 and the stronger is going to be this relationship between the two different features). In this case, we will consider just the features which are at least 0.5 correlated with the output variable. bruises_f 0.501530bruises_t 0.501530gill-color_b 0.538808gill-size_b 0.540024gill-size_n 0.540024ring-type_p 0.540469stalk-surface-below-ring_k 0.573524stalk-surface-above-ring_k 0.587658odor_f 0.623842odor_n 0.785557Y 1.000000Name: Y, dtype: float64 We can now try to take a closer look at the relationship between the different correlated features by creating a Correlation Matrix. Another possible aspect to control in this analysis would be to check if the selected variables are highly correlated with each other. If they are, we would then need to keep just one of the correlated ones and drop the others. Finally, we can now select just the features which are most correlated with Y and train/test an SVM model to evaluate the results of this approach. 0.06655320300001222[[1248 26] [ 46 1118]] precision recall f1-score support 0 0.96 0.98 0.97 1274 1 0.98 0.96 0.97 1164 accuracy 0.97 2438 macro avg 0.97 0.97 0.97 2438weighted avg 0.97 0.97 0.97 2438 Univariate Feature Selection is a statistical method used to select the features which have the strongest relationship with our correspondent labels. Using the SelectKBest method we can decide which metrics to use to evaluate our features and the number of K best features we want to keep. Different types of scoring functions are available depending on our needs: Classification = chi2, f_classif, mutual_info_classif Regression = f_regression, mutual_info_regression In this example, we will be using chi2 (Figure 7). Chi-squared (Chi2) can take as input just non-negative values, therefore, first of all, we scale our input data in a range between 0 and 1. 1.1043402509999964[[1015 259] [ 41 1123]] precision recall f1-score support 0 0.96 0.80 0.87 1274 1 0.81 0.96 0.88 1164 accuracy 0.88 2438 macro avg 0.89 0.88 0.88 2438weighted avg 0.89 0.88 0.88 2438 When applying regularization to a Machine Learning model, we add a penalty to the model parameters to avoid that our model tries to resemble too closely our input data. In this way, we can make our model less complex and we can avoid overfitting (making learn to our model, not just the key data characteristics but also it’s intrinsic noise). One of the possible Regularization Methods is Lasso (L1) Regression. When using Lasso Regression, the coefficients of the inputs features gets shrunken if they are not positively contributing to our Machine Learning model training. In this way, some of the features might get automatically discarded assigning them coefficients equal to zero. LassoCV Best Alpha Scored: 0.00039648980844788386LassoCV Model Accuracy: 0.9971840741918596Variables Eliminated: 73Variables Kept: 44 Once trained our model, we can again create a Feature Importance plot to understand which features have been considered most important by our model (Figure 8). This can be really useful especially when trying to understand how our model decided to make its predictions, therefore making our model more explainable. Thanks for reading! If you want to keep updated with my latest articles and projects follow me on Medium and subscribe to my mailing list. These are some of my contacts details: Linkedin Personal Blog Personal Website Medium Profile GitHub Kaggle [1] What is Big Data? — A Beginner’s Guide to the World of Big Data. Anushree Subramaniam, edureka! . Accessed at: https://www.edureka.co/blog/what-is-big-data/ [2] The Curse of Dimensionality in classification, Computer vision for dummies. Accessed at: https://www.visiondummy.com/2014/04/curse-dimensionality-affect-classification/ [3] Integrated Chemometrics and Statistics to Drive Successful Proteomics Biomarker Discovery, ResearchGate. Accessed at: https://www.researchgate.net/publication/324800823_Integrated_Chemometrics_and_Statistics_to_Drive_Successful_Proteomics_Biomarker_Discovery [4] Chi-squared test, Life in Freshwater. Accessed at: https://www.lifeinfreshwater.org.uk/Stats%20for%20twits/Chi-Squared.html
[ { "code": null, "e": 173, "s": 171, "text": "1" }, { "code": null, "e": 175, "s": 173, "text": "2" }, { "code": null, "e": 177, "s": 175, "text": "3" }, { "code": null, "e": 179, "s": 177, "text": "4" }, { "code": null, "e": 181, "s": 179, "text": "5" }, { "code": null, "e": 183, "s": 181, "text": "6" }, { "code": null, "e": 185, "s": 183, "text": "7" }, { "code": null, "e": 187, "s": 185, "text": "8" }, { "code": null, "e": 189, "s": 187, "text": "9" }, { "code": null, "e": 192, "s": 189, "text": "10" }, { "code": null, "e": 211, "s": 192, "text": "Powered by Play.ht" }, { "code": null, "e": 237, "s": 211, "text": "Create audio with Play.ht" }, { "code": null, "e": 274, "s": 237, "text": "Create Audio Narrations with Play.ht" }, { "code": null, "e": 751, "s": 274, "text": "According to Forbes, about 2.5 quintillion bytes of data is generated every day [1]. This data can then be analysed using Data Science and Machine Learning techniques in order to provide insights and make predictions. Although, in most of the cases, the originally gathered data needs to be first preprocessed before starting any statistical analysis with it. There are many different reasons why it might be necessary to carry out a preprocessing analysis, some examples are:" }, { "code": null, "e": 835, "s": 751, "text": "The gathered data is not in the right format (eg. SQL Database, JSON, CSV, etc...)." }, { "code": null, "e": 864, "s": 835, "text": "Missing values and Outliers." }, { "code": null, "e": 891, "s": 864, "text": "Scaling and Normalization." }, { "code": null, "e": 983, "s": 891, "text": "Reduce Intrinsic Noise present in the dataset (part of the stored data might be corrupted)." }, { "code": null, "e": 1062, "s": 983, "text": "Some features in the dataset might not gather any information to our analysis." }, { "code": null, "e": 1305, "s": 1062, "text": "In this article, I will walk you through how to reduce the number of features in a dataset in Python using the Kaggle Mushroom Classification Dataset. All the code used in this post (and more!) is available on Kaggle and on my GitHub Account." }, { "code": null, "e": 1421, "s": 1305, "text": "Reducing the number of features to use during a statistical analysis can possibly lead to several benefits such as:" }, { "code": null, "e": 1444, "s": 1421, "text": "Accuracy improvements." }, { "code": null, "e": 1472, "s": 1444, "text": "Overfitting risk reduction." }, { "code": null, "e": 1494, "s": 1472, "text": "Speed up in training." }, { "code": null, "e": 1523, "s": 1494, "text": "Improved Data Visualization." }, { "code": null, "e": 1564, "s": 1523, "text": "Increase in explainability of our model." }, { "code": null, "e": 2164, "s": 1564, "text": "In fact, it is statistically proven that when performing a Machine Learning task there exist an optimal number of features which should be used for every specific task (Figure 1). If more features are added than the ones which are strictly necessary, then our model performance will just decrease (because of the added noise). The real challenge is to find out what is the optimal number of features to use (this is, in fact, dependent on the amount of data we have available and by the complexity of the task we are trying to achieve). That’s where Feature Selections techniques come to our rescue!" }, { "code": null, "e": 2278, "s": 2164, "text": "There are many different methods which can be applied for Feature Selection. Some of the most important ones are:" }, { "code": null, "e": 3257, "s": 2278, "text": "Filter Method = filtering our dataset and taking only a subset of it containing all the relevant features (eg. correlation matrix using Pearson Correlation).Wrapper Method = follows the same objective of the FIlter Method but uses a Machine Learning model as it’s evaluation criteria (eg. Forward/Backward/Bidirectional/Recursive Feature Elimination). We feed some features to our Machine Learning model, evaluate their performance and then decide if add or remove the feature to increase accuracy. As a result, this method can be more accurate than filtering but is more computationally expensive.Embedded Method = like the FIlter Method also the Embedded Method makes use of a Machine Learning model. The difference between the two methods is that the Embedded Method examines the different training iterations of our ML model and then ranks the importance of each feature based on how much each of the features contributed to the ML model training (eg. LASSO Regularization)." }, { "code": null, "e": 3415, "s": 3257, "text": "Filter Method = filtering our dataset and taking only a subset of it containing all the relevant features (eg. correlation matrix using Pearson Correlation)." }, { "code": null, "e": 3857, "s": 3415, "text": "Wrapper Method = follows the same objective of the FIlter Method but uses a Machine Learning model as it’s evaluation criteria (eg. Forward/Backward/Bidirectional/Recursive Feature Elimination). We feed some features to our Machine Learning model, evaluate their performance and then decide if add or remove the feature to increase accuracy. As a result, this method can be more accurate than filtering but is more computationally expensive." }, { "code": null, "e": 4238, "s": 3857, "text": "Embedded Method = like the FIlter Method also the Embedded Method makes use of a Machine Learning model. The difference between the two methods is that the Embedded Method examines the different training iterations of our ML model and then ranks the importance of each feature based on how much each of the features contributed to the ML model training (eg. LASSO Regularization)." }, { "code": null, "e": 4535, "s": 4238, "text": "In this article, I will make use of the Mushroom Classification dataset to try to predict if a Mushroom is poisonous or not by looking at the given features. While doing so, we will try different feature elimination techniques to see how this can affect training times and overall model accuracy." }, { "code": null, "e": 4596, "s": 4535, "text": "First of all, we need to import all the necessary libraries." }, { "code": null, "e": 4671, "s": 4596, "text": "The dataset we will be using in this example is shown in the figure below." }, { "code": null, "e": 4877, "s": 4671, "text": "Before feeding this data into our Machine Learning models I decided to One Hot Encode all the Categorical Variables, divide our data into features (X) and labels (Y), and finally in training and test sets." }, { "code": null, "e": 5343, "s": 4877, "text": "Decision Trees models which are based on ensembles (eg. Extra Trees and Random Forest) can be used to rank the importance of the different features. Knowing which features our model is giving most importance can be of vital importance to understand how our model is making it’s predictions (therefore making it more explainable). At the same time, we can get rid of the features which do not bring any benefit to our model (or confuse it to make a wrong decision!)." }, { "code": null, "e": 5613, "s": 5343, "text": "As shown below, training a Random Forest classifier using all the features, led to 100% Accuracy in about 2.2s of training time. In each of the following examples, the training time of each model will be printed out on the first line of each snippet for your reference." }, { "code": null, "e": 5975, "s": 5613, "text": "2.2676709799999992[[1274 0] [ 0 1164]] precision recall f1-score support 0 1.00 1.00 1.00 1274 1 1.00 1.00 1.00 1164 accuracy 1.00 2438 macro avg 1.00 1.00 1.00 2438weighted avg 1.00 1.00 1.00 2438" }, { "code": null, "e": 6241, "s": 5975, "text": "Once our Random Forest Classifier has been trained, we can then create a Feature Importance plot to see which features have been considered as most important for our model to make its predictions (Figure 4). In this example, just the top 7 features are shown below." }, { "code": null, "e": 6383, "s": 6241, "text": "Now that we know which features are considered to be most important by our Random Forest, we can try to train our model just using the top 3." }, { "code": null, "e": 6501, "s": 6383, "text": "As we can see below, using just 3 features lead to a decrease of just 0.03% in accuracy and halved the training time." }, { "code": null, "e": 6863, "s": 6501, "text": "1.1874146949999993[[1248 26] [ 53 1111]] precision recall f1-score support 0 0.96 0.98 0.97 1274 1 0.98 0.95 0.97 1164 accuracy 0.97 2438 macro avg 0.97 0.97 0.97 2438weighted avg 0.97 0.97 0.97 2438" }, { "code": null, "e": 6969, "s": 6863, "text": "We can also understand how to perform Feature Selection by visualizing a trained Decision Tree structure." }, { "code": null, "e": 7332, "s": 6969, "text": "0.02882629099999967[[1274 0] [ 0 1164]] precision recall f1-score support 0 1.00 1.00 1.00 1274 1 1.00 1.00 1.00 1164 accuracy 1.00 2438 macro avg 1.00 1.00 1.00 2438weighted avg 1.00 1.00 1.00 2438" }, { "code": null, "e": 7642, "s": 7332, "text": "The features which will be at the top of the tree structure are the ones our model retained most important in order to perform its classification. Therefore by picking just the first few features at the top and discarding the others could possibly lead to creating a model which an appreciable accuracy score." }, { "code": null, "e": 7911, "s": 7642, "text": "Recursive Feature Elimination (RFE) takes as input the instance of a Machine Learning model and the final desired number of features to use. It then recursively reduces the number of features to use by ranking them using the Machine Learning model accuracy as metrics." }, { "code": null, "e": 8422, "s": 7911, "text": "Creating a for loop in which the number of input features is our variable, it could then be possible to find out the optimal number of features our model needs by keeping track of the accuracy registered in each loop iteration. Using RFE support method, we can then find out the names of the features which have been evaluated as most important (rfe.support return a boolean list in which TRUE represent that a feature is considered as important and FALSE represent that a feature is not considered important)." }, { "code": null, "e": 8488, "s": 8422, "text": "210.85839133899998Overall Accuracy using RFE: 0.9675963904840033" }, { "code": null, "e": 8922, "s": 8488, "text": "SelectFromModel is another Scikit-learn method which can be used for Feature Selection. This method can be used with all the different types of Scikit-learn models (after fitting) which have a coef_ or feature_importances_ attribute. Compared to RFE, SelectFromModel is a less robust solution. In fact, SelectFromModel just removes less important features based on a calculated threshold (no optimization iteration process involved)." }, { "code": null, "e": 9023, "s": 8922, "text": "In order to test SelectFromModel efficacy, I decided to use an ExtraTreesClassifier in this example." }, { "code": null, "e": 9369, "s": 9023, "text": "ExtraTreesClassifier (Extremely Randomized Trees) is tree-based ensemble classifier which can yield less variance compared to Random Forest methods (reducing, therefore, the risk of overfitting). The main difference between Random Forest and Extremely Randomized Trees is that in Extremely Randomized Trees nodes are sampled without replacement." }, { "code": null, "e": 9731, "s": 9369, "text": "1.6003950479999958[[1274 0] [ 0 1164]] precision recall f1-score support 0 1.00 1.00 1.00 1274 1 1.00 1.00 1.00 1164 accuracy 1.00 2438 macro avg 1.00 1.00 1.00 2438weighted avg 1.00 1.00 1.00 2438" }, { "code": null, "e": 9893, "s": 9731, "text": "Another possible method which can be used in order to reduce the number of features in our dataset is to inspect the correlation of our features with our labels." }, { "code": null, "e": 9979, "s": 9893, "text": "Using Pearson correlation our returned coefficient values will vary between -1 and 1:" }, { "code": null, "e": 10102, "s": 9979, "text": "If the correlation between two features is 0 this means that changing any of these two features will not affect the other." }, { "code": null, "e": 10396, "s": 10102, "text": "If the correlation between two features is greater than 0 this means that increasing the values in one feature will make increase also the values in the other feature (the closer the correlation coefficient is to 1 and the stronger is going to be this bond between the two different features)." }, { "code": null, "e": 10691, "s": 10396, "text": "If the correlation between two features is less than 0 this means that increasing the values in one feature will make decrease the values in the other feature (the closer the correlation coefficient is to -1 and the stronger is going to be this relationship between the two different features)." }, { "code": null, "e": 10800, "s": 10691, "text": "In this case, we will consider just the features which are at least 0.5 correlated with the output variable." }, { "code": null, "e": 11242, "s": 10800, "text": "bruises_f 0.501530bruises_t 0.501530gill-color_b 0.538808gill-size_b 0.540024gill-size_n 0.540024ring-type_p 0.540469stalk-surface-below-ring_k 0.573524stalk-surface-above-ring_k 0.587658odor_f 0.623842odor_n 0.785557Y 1.000000Name: Y, dtype: float64" }, { "code": null, "e": 11375, "s": 11242, "text": "We can now try to take a closer look at the relationship between the different correlated features by creating a Correlation Matrix." }, { "code": null, "e": 11603, "s": 11375, "text": "Another possible aspect to control in this analysis would be to check if the selected variables are highly correlated with each other. If they are, we would then need to keep just one of the correlated ones and drop the others." }, { "code": null, "e": 11751, "s": 11603, "text": "Finally, we can now select just the features which are most correlated with Y and train/test an SVM model to evaluate the results of this approach." }, { "code": null, "e": 12114, "s": 11751, "text": "0.06655320300001222[[1248 26] [ 46 1118]] precision recall f1-score support 0 0.96 0.98 0.97 1274 1 0.98 0.96 0.97 1164 accuracy 0.97 2438 macro avg 0.97 0.97 0.97 2438weighted avg 0.97 0.97 0.97 2438" }, { "code": null, "e": 12479, "s": 12114, "text": "Univariate Feature Selection is a statistical method used to select the features which have the strongest relationship with our correspondent labels. Using the SelectKBest method we can decide which metrics to use to evaluate our features and the number of K best features we want to keep. Different types of scoring functions are available depending on our needs:" }, { "code": null, "e": 12533, "s": 12479, "text": "Classification = chi2, f_classif, mutual_info_classif" }, { "code": null, "e": 12583, "s": 12533, "text": "Regression = f_regression, mutual_info_regression" }, { "code": null, "e": 12634, "s": 12583, "text": "In this example, we will be using chi2 (Figure 7)." }, { "code": null, "e": 12774, "s": 12634, "text": "Chi-squared (Chi2) can take as input just non-negative values, therefore, first of all, we scale our input data in a range between 0 and 1." }, { "code": null, "e": 13136, "s": 12774, "text": "1.1043402509999964[[1015 259] [ 41 1123]] precision recall f1-score support 0 0.96 0.80 0.87 1274 1 0.81 0.96 0.88 1164 accuracy 0.88 2438 macro avg 0.89 0.88 0.88 2438weighted avg 0.89 0.88 0.88 2438" }, { "code": null, "e": 13480, "s": 13136, "text": "When applying regularization to a Machine Learning model, we add a penalty to the model parameters to avoid that our model tries to resemble too closely our input data. In this way, we can make our model less complex and we can avoid overfitting (making learn to our model, not just the key data characteristics but also it’s intrinsic noise)." }, { "code": null, "e": 13823, "s": 13480, "text": "One of the possible Regularization Methods is Lasso (L1) Regression. When using Lasso Regression, the coefficients of the inputs features gets shrunken if they are not positively contributing to our Machine Learning model training. In this way, some of the features might get automatically discarded assigning them coefficients equal to zero." }, { "code": null, "e": 13961, "s": 13823, "text": "LassoCV Best Alpha Scored: 0.00039648980844788386LassoCV Model Accuracy: 0.9971840741918596Variables Eliminated: 73Variables Kept: 44" }, { "code": null, "e": 14276, "s": 13961, "text": "Once trained our model, we can again create a Feature Importance plot to understand which features have been considered most important by our model (Figure 8). This can be really useful especially when trying to understand how our model decided to make its predictions, therefore making our model more explainable." }, { "code": null, "e": 14296, "s": 14276, "text": "Thanks for reading!" }, { "code": null, "e": 14454, "s": 14296, "text": "If you want to keep updated with my latest articles and projects follow me on Medium and subscribe to my mailing list. These are some of my contacts details:" }, { "code": null, "e": 14463, "s": 14454, "text": "Linkedin" }, { "code": null, "e": 14477, "s": 14463, "text": "Personal Blog" }, { "code": null, "e": 14494, "s": 14477, "text": "Personal Website" }, { "code": null, "e": 14509, "s": 14494, "text": "Medium Profile" }, { "code": null, "e": 14516, "s": 14509, "text": "GitHub" }, { "code": null, "e": 14523, "s": 14516, "text": "Kaggle" }, { "code": null, "e": 14684, "s": 14523, "text": "[1] What is Big Data? — A Beginner’s Guide to the World of Big Data. Anushree Subramaniam, edureka! . Accessed at: https://www.edureka.co/blog/what-is-big-data/" }, { "code": null, "e": 14857, "s": 14684, "text": "[2] The Curse of Dimensionality in classification, Computer vision for dummies. Accessed at: https://www.visiondummy.com/2014/04/curse-dimensionality-affect-classification/" }, { "code": null, "e": 15120, "s": 14857, "text": "[3] Integrated Chemometrics and Statistics to Drive Successful Proteomics Biomarker Discovery, ResearchGate. Accessed at: https://www.researchgate.net/publication/324800823_Integrated_Chemometrics_and_Statistics_to_Drive_Successful_Proteomics_Biomarker_Discovery" } ]
C/C++ Program to Count Inversions in an array using Merge Sort?
The inversions of an array indicate; how many changes are required to convert the array into its sorted form. When an array is already sorted, it needs 0 inversions, and in other case, the number of inversions will be maximum, if the array is reversed. To solve this problem, we will follow the Merge sort approach to reduce the time complexity, and make it in Divide and Conquer algorithm. A sequence of numbers. (1, 5, 6, 4, 20). The number of inversions required to arrange the numbers into ascending order. Here the number of inversions are 2. First inversion: (1, 5, 4, 6, 20) Second inversion: (1, 4, 5, 6, 20) Input - Two arrays, who have merged, the left, right and the mid indexes.Output -The merged array in sorted order. Begin i := left, j := mid, k := right count := 0 while i <= mid -1 and j <= right, do if array[i] <= array[j], then tempArray[k] := array[i] increase i and k by 1 else tempArray[k] := array[j] increase j and k by 1 count := count + (mid - i) done while left part of the array has some extra element, do tempArray[k] := array[i] increase i and k by 1 done while right part of the array has some extra element, do tempArray[k] := array[j] increase j and k by 1 done return count End Input - Given array and temporary array, left and right index of the array.Output - Number of inversions after sorting. Begin count := 0 if right > left, then mid := (right + left)/2 count := mergeSort(array, tempArray, left, mid) count := count + mergeSort(array, tempArray, mid+1, right) count := count + merge(array, tempArray, left, mid+1, right) return count End Live Demo #include <iostream> using namespace std; int merge(int arr[], int temp[], int left, int mid, int right) { int i, j, k; int count = 0; i = left; //i to locate first array location j = mid; //i to locate second array location k = left; //i to locate merged array location while ((i <= mid - 1) && (j <= right)) { if (arr[i] <= arr[j]){ //when left item is less than right item temp[k++] = arr[i++]; } else { temp[k++] = arr[j++]; count += (mid - i); //find how many convertion is performed } } while (i <= mid - 1) //if first list has remaining item, add them in the list temp[k++] = arr[i++]; while (j <= right) //if second list has remaining item, add them in the list temp[k++] = arr[j++]; for (i=left; i <= right; i++) arr[i] = temp[i]; //store temp Array to main array return count; } int mergeSort(int arr[], int temp[], int left, int right){ int mid, count = 0; if (right > left) { mid = (right + left)/2; //find mid index of the array count = mergeSort(arr, temp, left, mid); //merge sort left sub array count += mergeSort(arr, temp, mid+1, right); //merge sort right sub array count += merge(arr, temp, left, mid+1, right); //merge two sub arrays } return count; } int arrInversion(int arr[], int n) { int temp[n]; return mergeSort(arr, temp, 0, n - 1); } int main() { int arr[] = {1, 5, 6, 4, 20}; int n = 5; cout << "Number of inversions are "<< arrInversion(arr, n); } Number of inversions are 2
[ { "code": null, "e": 1315, "s": 1062, "text": "The inversions of an array indicate; how many changes are required to convert the array into its sorted form. When an array is already sorted, it needs 0 inversions, and in other case, the number of inversions will be maximum, if the array is reversed." }, { "code": null, "e": 1453, "s": 1315, "text": "To solve this problem, we will follow the Merge sort approach to reduce the time complexity, and make it in Divide and Conquer algorithm." }, { "code": null, "e": 1494, "s": 1453, "text": "A sequence of numbers. (1, 5, 6, 4, 20)." }, { "code": null, "e": 1573, "s": 1494, "text": "The number of inversions required to arrange the numbers into ascending order." }, { "code": null, "e": 1679, "s": 1573, "text": "Here the number of inversions are 2.\nFirst inversion: (1, 5, 4, 6, 20)\nSecond inversion: (1, 4, 5, 6, 20)" }, { "code": null, "e": 1794, "s": 1679, "text": "Input - Two arrays, who have merged, the left, right and the mid indexes.Output -The merged array in sorted order." }, { "code": null, "e": 2383, "s": 1794, "text": "Begin\n i := left, j := mid, k := right\n count := 0\n while i <= mid -1 and j <= right, do\n if array[i] <= array[j], then\n tempArray[k] := array[i]\n increase i and k by 1\n else\n tempArray[k] := array[j]\n increase j and k by 1\n count := count + (mid - i)\n done\n while left part of the array has some extra element, do\n tempArray[k] := array[i]\n increase i and k by 1\n done\n while right part of the array has some extra element, do\n tempArray[k] := array[j]\n increase j and k by 1\n done\n return count\nEnd" }, { "code": null, "e": 2503, "s": 2383, "text": "Input - Given array and temporary array, left and right index of the array.Output - Number of inversions after sorting." }, { "code": null, "e": 2784, "s": 2503, "text": "Begin\n count := 0\n if right > left, then\n mid := (right + left)/2\n count := mergeSort(array, tempArray, left, mid)\n count := count + mergeSort(array, tempArray, mid+1, right)\n count := count + merge(array, tempArray, left, mid+1, right)\n return count\nEnd" }, { "code": null, "e": 2795, "s": 2784, "text": " Live Demo" }, { "code": null, "e": 4318, "s": 2795, "text": "#include <iostream>\nusing namespace std;\nint merge(int arr[], int temp[], int left, int mid, int right) {\n int i, j, k;\n int count = 0;\n i = left; //i to locate first array location\n j = mid; //i to locate second array location\n k = left; //i to locate merged array location\n while ((i <= mid - 1) && (j <= right)) {\n if (arr[i] <= arr[j]){ //when left item is less than right item\n temp[k++] = arr[i++];\n } else {\n temp[k++] = arr[j++];\n count += (mid - i); //find how many convertion is performed\n }\n }\n while (i <= mid - 1) //if first list has remaining item, add them in the list\n temp[k++] = arr[i++];\n while (j <= right) //if second list has remaining item, add them in the list\n temp[k++] = arr[j++];\n for (i=left; i <= right; i++)\n arr[i] = temp[i]; //store temp Array to main array\n return count;\n}\nint mergeSort(int arr[], int temp[], int left, int right){\n int mid, count = 0;\n if (right > left) {\n mid = (right + left)/2; //find mid index of the array\n count = mergeSort(arr, temp, left, mid); //merge sort left sub array\n count += mergeSort(arr, temp, mid+1, right); //merge sort right sub array\n count += merge(arr, temp, left, mid+1, right); //merge two sub arrays\n }\n return count;\n}\nint arrInversion(int arr[], int n) {\n int temp[n];\n return mergeSort(arr, temp, 0, n - 1);\n}\nint main() {\n int arr[] = {1, 5, 6, 4, 20};\n int n = 5;\n cout << \"Number of inversions are \"<< arrInversion(arr, n);\n}" }, { "code": null, "e": 4345, "s": 4318, "text": "Number of inversions are 2" } ]
Possible moves of knight - GeeksforGeeks
04 May, 2021 Given a chess board of dimension m * n. Find number of possible moves where knight can be moved on a chessboard from given position. If mat[i][j] = 1 then the block is filled by something else, otherwise empty. Assume that board consist of all pieces of same color, i.e., there are no blocks being attacked. Examples: Input : mat[][] = {{1, 0, 1, 0}, {0, 1, 1, 1}, {1, 1, 0, 1}, {0, 1, 1, 1}} pos = (2, 2) Output : 4 Knight can moved from (2, 2) to (0, 1), (0, 3), (1, 0) ans (3, 0). We can observe that knight on a chessboard moves either: 1. Two moves horizontal and one move vertical 2. Two moves vertical and one move horizontalThe idea is to store all possible moves of knight and then count number of valid moves. A move will be invalid if: 1. A block is already occupied by another piece. 2. Move is out of chessboard. C++ Java Python3 C# PHP Javascript // CPP program to find number of possible moves of knight#include <bits/stdc++.h>#define n 4#define m 4using namespace std; // To calculate possible movesint findPossibleMoves(int mat[n][m], int p, int q){ // All possible moves of a knight int X[8] = { 2, 1, -1, -2, -2, -1, 1, 2 }; int Y[8] = { 1, 2, 2, 1, -1, -2, -2, -1 }; int count = 0; // Check if each possible move is valid or not for (int i = 0; i < 8; i++) { // Position of knight after move int x = p + X[i]; int y = q + Y[i]; // count valid moves if (x >= 0 && y >= 0 && x < n && y < m && mat[x][y] == 0) count++; } // Return number of possible moves return count;} // Driver program to check findPossibleMoves()int main(){ int mat[n][m] = { { 1, 0, 1, 0 }, { 0, 1, 1, 1 }, { 1, 1, 0, 1 }, { 0, 1, 1, 1 } }; int p = 2, q = 2; cout << findPossibleMoves(mat, p, q); return 0;} // Java program to find number of possible moves of knightpublic class Main {public static final int n = 4;public static final int m = 4; // To calculate possible moves static int findPossibleMoves(int mat[][], int p, int q) { // All possible moves of a knight int X[] = { 2, 1, -1, -2, -2, -1, 1, 2 }; int Y[] = { 1, 2, 2, 1, -1, -2, -2, -1 }; int count = 0; // Check if each possible move is valid or not for (int i = 0; i < 8; i++) { // Position of knight after move int x = p + X[i]; int y = q + Y[i]; // count valid moves if (x >= 0 && y >= 0 && x < n && y < m && mat[x][y] == 0) count++; } // Return number of possible moves return count; } // Driver program to check findPossibleMoves() public static void main(String[] args) { int mat[][] = { { 1, 0, 1, 0 }, { 0, 1, 1, 1 }, { 1, 1, 0, 1 }, { 0, 1, 1, 1 } }; int p = 2, q = 2; System.out.println(findPossibleMoves(mat, p, q)); }} # Python3 program to find number# of possible moves of knightn = 4;m = 4; # To calculate possible movesdef findPossibleMoves(mat, p, q): global n, m; # All possible moves of a knight X = [2, 1, -1, -2, -2, -1, 1, 2]; Y = [1, 2, 2, 1, -1, -2, -2, -1]; count = 0; # Check if each possible move # is valid or not for i in range(8): # Position of knight after move x = p + X[i]; y = q + Y[i]; # count valid moves if(x >= 0 and y >= 0 and x < n and y < m and mat[x][y] == 0): count += 1; # Return number of possible moves return count; # Driver codeif __name__ == '__main__': mat = [[1, 0, 1, 0], [0, 1, 1, 1], [1, 1, 0, 1], [0, 1, 1, 1]]; p, q = 2, 2; print(findPossibleMoves(mat, p, q)); # This code is contributed by 29AjayKumar // C# program to find number of// possible moves of knightusing System; class GFG{ static int n = 4; static int m = 4; // To calculate // possible moves static int findPossibleMoves(int [,]mat, int p, int q) { // All possible moves // of a knight int []X = { 2, 1, -1, -2, -2, -1, 1, 2 }; int []Y = { 1, 2, 2, 1, -1, -2, -2, -1 }; int count = 0; // Check if each possible // move is valid or not for (int i = 0; i < 8; i++) { // Position of knight // after move int x = p + X[i]; int y = q + Y[i]; // count valid moves if (x >= 0 && y >= 0 && x < n && y < m && mat[x, y] == 0) count++; } // Return number // of possible moves return count; } // Driver Code static public void Main () { int [,]mat = { { 1, 0, 1, 0 }, { 0, 1, 1, 1 }, { 1, 1, 0, 1 }, { 0, 1, 1, 1 }}; int p = 2, q = 2; Console.WriteLine(findPossibleMoves(mat, p, q)); }} // This code is contributed by m_kit <?php// PHP program to find number// of possible moves of knight$n = 4;$m = 4; // To calculate possible movesfunction findPossibleMoves($mat, $p, $q){ global $n; global $m; // All possible moves // of a knight $X = array(2, 1, -1, -2, -2, -1, 1, 2); $Y = array(1, 2, 2, 1, -1, -2, -2, -1); $count = 0; // Check if each possible // move is valid or not for ($i = 0; $i < 8; $i++) { // Position of // knight after move $x = $p + $X[$i]; $y = $q + $Y[$i]; // count valid moves if ($x >= 0 && $y >= 0 && $x < $n && $y < $m && $mat[$x][$y] == 0) $count++; } // Return number // of possible moves return $count;} // Driver Code$mat = array(array(1, 0, 1, 0), array(0, 1, 1, 1), array(1, 1, 0, 1), array(0, 1, 1, 1)); $p = 2; $q = 2; echo findPossibleMoves($mat, $p, $q); // This code is contributed by ajit?> <script> // Javascript program to find number of possible moves of knight let n = 4; let m = 4; // To calculate possible moves function findPossibleMoves(mat, p, q) { // All possible moves of a knight let X = [ 2, 1, -1, -2, -2, -1, 1, 2 ]; let Y = [ 1, 2, 2, 1, -1, -2, -2, -1 ]; let count = 0; // Check if each possible move is valid or not for (let i = 0; i < 8; i++) { // Position of knight after move let x = p + X[i]; let y = q + Y[i]; // count valid moves if (x >= 0 && y >= 0 && x < n && y < m && mat[x][y] == 0) count++; } // Return number of possible moves return count; } let mat = [ [ 1, 0, 1, 0 ], [ 0, 1, 1, 1 ], [ 1, 1, 0, 1 ], [ 0, 1, 1, 1 ] ]; let p = 2, q = 2; document.write(findPossibleMoves(mat, p, q)); </script> Output: 4 References: https://en.wikipedia.org/wiki/Knight_(chess)This article is contributed by nuclode. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. jit_t 29AjayKumar divyeshrabadiya07 chessboard-problems Matrix Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sudoku | Backtracking-7 Divide and Conquer | Set 5 (Strassen's Matrix Multiplication) Program to multiply two matrices Inplace rotate square matrix by 90 degrees | Set 1 Count all possible paths from top left to bottom right of a mXn matrix Min Cost Path | DP-6 Printing all solutions in N-Queen Problem Efficiently compute sums of diagonals of a matrix Rotate a matrix by 90 degree in clockwise direction without using any extra space Python program to multiply two matrices
[ { "code": null, "e": 26301, "s": 26273, "text": "\n04 May, 2021" }, { "code": null, "e": 26610, "s": 26301, "text": "Given a chess board of dimension m * n. Find number of possible moves where knight can be moved on a chessboard from given position. If mat[i][j] = 1 then the block is filled by something else, otherwise empty. Assume that board consist of all pieces of same color, i.e., there are no blocks being attacked. " }, { "code": null, "e": 26622, "s": 26610, "text": "Examples: " }, { "code": null, "e": 26854, "s": 26622, "text": "Input : mat[][] = {{1, 0, 1, 0},\n {0, 1, 1, 1},\n {1, 1, 0, 1},\n {0, 1, 1, 1}}\n pos = (2, 2)\nOutput : 4\nKnight can moved from (2, 2) to (0, 1), (0, 3), \n(1, 0) ans (3, 0)." }, { "code": null, "e": 27199, "s": 26856, "text": "We can observe that knight on a chessboard moves either: 1. Two moves horizontal and one move vertical 2. Two moves vertical and one move horizontalThe idea is to store all possible moves of knight and then count number of valid moves. A move will be invalid if: 1. A block is already occupied by another piece. 2. Move is out of chessboard. " }, { "code": null, "e": 27203, "s": 27199, "text": "C++" }, { "code": null, "e": 27208, "s": 27203, "text": "Java" }, { "code": null, "e": 27216, "s": 27208, "text": "Python3" }, { "code": null, "e": 27219, "s": 27216, "text": "C#" }, { "code": null, "e": 27223, "s": 27219, "text": "PHP" }, { "code": null, "e": 27234, "s": 27223, "text": "Javascript" }, { "code": "// CPP program to find number of possible moves of knight#include <bits/stdc++.h>#define n 4#define m 4using namespace std; // To calculate possible movesint findPossibleMoves(int mat[n][m], int p, int q){ // All possible moves of a knight int X[8] = { 2, 1, -1, -2, -2, -1, 1, 2 }; int Y[8] = { 1, 2, 2, 1, -1, -2, -2, -1 }; int count = 0; // Check if each possible move is valid or not for (int i = 0; i < 8; i++) { // Position of knight after move int x = p + X[i]; int y = q + Y[i]; // count valid moves if (x >= 0 && y >= 0 && x < n && y < m && mat[x][y] == 0) count++; } // Return number of possible moves return count;} // Driver program to check findPossibleMoves()int main(){ int mat[n][m] = { { 1, 0, 1, 0 }, { 0, 1, 1, 1 }, { 1, 1, 0, 1 }, { 0, 1, 1, 1 } }; int p = 2, q = 2; cout << findPossibleMoves(mat, p, q); return 0;}", "e": 28237, "s": 27234, "text": null }, { "code": "// Java program to find number of possible moves of knightpublic class Main {public static final int n = 4;public static final int m = 4; // To calculate possible moves static int findPossibleMoves(int mat[][], int p, int q) { // All possible moves of a knight int X[] = { 2, 1, -1, -2, -2, -1, 1, 2 }; int Y[] = { 1, 2, 2, 1, -1, -2, -2, -1 }; int count = 0; // Check if each possible move is valid or not for (int i = 0; i < 8; i++) { // Position of knight after move int x = p + X[i]; int y = q + Y[i]; // count valid moves if (x >= 0 && y >= 0 && x < n && y < m && mat[x][y] == 0) count++; } // Return number of possible moves return count; } // Driver program to check findPossibleMoves() public static void main(String[] args) { int mat[][] = { { 1, 0, 1, 0 }, { 0, 1, 1, 1 }, { 1, 1, 0, 1 }, { 0, 1, 1, 1 } }; int p = 2, q = 2; System.out.println(findPossibleMoves(mat, p, q)); }}", "e": 29396, "s": 28237, "text": null }, { "code": "# Python3 program to find number# of possible moves of knightn = 4;m = 4; # To calculate possible movesdef findPossibleMoves(mat, p, q): global n, m; # All possible moves of a knight X = [2, 1, -1, -2, -2, -1, 1, 2]; Y = [1, 2, 2, 1, -1, -2, -2, -1]; count = 0; # Check if each possible move # is valid or not for i in range(8): # Position of knight after move x = p + X[i]; y = q + Y[i]; # count valid moves if(x >= 0 and y >= 0 and x < n and y < m and mat[x][y] == 0): count += 1; # Return number of possible moves return count; # Driver codeif __name__ == '__main__': mat = [[1, 0, 1, 0], [0, 1, 1, 1], [1, 1, 0, 1], [0, 1, 1, 1]]; p, q = 2, 2; print(findPossibleMoves(mat, p, q)); # This code is contributed by 29AjayKumar", "e": 30248, "s": 29396, "text": null }, { "code": "// C# program to find number of// possible moves of knightusing System; class GFG{ static int n = 4; static int m = 4; // To calculate // possible moves static int findPossibleMoves(int [,]mat, int p, int q) { // All possible moves // of a knight int []X = { 2, 1, -1, -2, -2, -1, 1, 2 }; int []Y = { 1, 2, 2, 1, -1, -2, -2, -1 }; int count = 0; // Check if each possible // move is valid or not for (int i = 0; i < 8; i++) { // Position of knight // after move int x = p + X[i]; int y = q + Y[i]; // count valid moves if (x >= 0 && y >= 0 && x < n && y < m && mat[x, y] == 0) count++; } // Return number // of possible moves return count; } // Driver Code static public void Main () { int [,]mat = { { 1, 0, 1, 0 }, { 0, 1, 1, 1 }, { 1, 1, 0, 1 }, { 0, 1, 1, 1 }}; int p = 2, q = 2; Console.WriteLine(findPossibleMoves(mat, p, q)); }} // This code is contributed by m_kit", "e": 31563, "s": 30248, "text": null }, { "code": "<?php// PHP program to find number// of possible moves of knight$n = 4;$m = 4; // To calculate possible movesfunction findPossibleMoves($mat, $p, $q){ global $n; global $m; // All possible moves // of a knight $X = array(2, 1, -1, -2, -2, -1, 1, 2); $Y = array(1, 2, 2, 1, -1, -2, -2, -1); $count = 0; // Check if each possible // move is valid or not for ($i = 0; $i < 8; $i++) { // Position of // knight after move $x = $p + $X[$i]; $y = $q + $Y[$i]; // count valid moves if ($x >= 0 && $y >= 0 && $x < $n && $y < $m && $mat[$x][$y] == 0) $count++; } // Return number // of possible moves return $count;} // Driver Code$mat = array(array(1, 0, 1, 0), array(0, 1, 1, 1), array(1, 1, 0, 1), array(0, 1, 1, 1)); $p = 2; $q = 2; echo findPossibleMoves($mat, $p, $q); // This code is contributed by ajit?>", "e": 32606, "s": 31563, "text": null }, { "code": "<script> // Javascript program to find number of possible moves of knight let n = 4; let m = 4; // To calculate possible moves function findPossibleMoves(mat, p, q) { // All possible moves of a knight let X = [ 2, 1, -1, -2, -2, -1, 1, 2 ]; let Y = [ 1, 2, 2, 1, -1, -2, -2, -1 ]; let count = 0; // Check if each possible move is valid or not for (let i = 0; i < 8; i++) { // Position of knight after move let x = p + X[i]; let y = q + Y[i]; // count valid moves if (x >= 0 && y >= 0 && x < n && y < m && mat[x][y] == 0) count++; } // Return number of possible moves return count; } let mat = [ [ 1, 0, 1, 0 ], [ 0, 1, 1, 1 ], [ 1, 1, 0, 1 ], [ 0, 1, 1, 1 ] ]; let p = 2, q = 2; document.write(findPossibleMoves(mat, p, q)); </script>", "e": 33584, "s": 32606, "text": null }, { "code": null, "e": 33594, "s": 33584, "text": "Output: " }, { "code": null, "e": 33596, "s": 33594, "text": "4" }, { "code": null, "e": 34067, "s": 33596, "text": "References: https://en.wikipedia.org/wiki/Knight_(chess)This article is contributed by nuclode. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 34073, "s": 34067, "text": "jit_t" }, { "code": null, "e": 34085, "s": 34073, "text": "29AjayKumar" }, { "code": null, "e": 34103, "s": 34085, "text": "divyeshrabadiya07" }, { "code": null, "e": 34123, "s": 34103, "text": "chessboard-problems" }, { "code": null, "e": 34130, "s": 34123, "text": "Matrix" }, { "code": null, "e": 34137, "s": 34130, "text": "Matrix" }, { "code": null, "e": 34235, "s": 34137, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34259, "s": 34235, "text": "Sudoku | Backtracking-7" }, { "code": null, "e": 34321, "s": 34259, "text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)" }, { "code": null, "e": 34354, "s": 34321, "text": "Program to multiply two matrices" }, { "code": null, "e": 34405, "s": 34354, "text": "Inplace rotate square matrix by 90 degrees | Set 1" }, { "code": null, "e": 34476, "s": 34405, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 34497, "s": 34476, "text": "Min Cost Path | DP-6" }, { "code": null, "e": 34539, "s": 34497, "text": "Printing all solutions in N-Queen Problem" }, { "code": null, "e": 34589, "s": 34539, "text": "Efficiently compute sums of diagonals of a matrix" }, { "code": null, "e": 34671, "s": 34589, "text": "Rotate a matrix by 90 degree in clockwise direction without using any extra space" } ]
Function Overloading and Return Type in C++ - GeeksforGeeks
03 Jan, 2022 Function overloading is possible in C++ and Java but only if the functions must differ from each other by the types and the number of arguments in the argument list. However, functions can not be overloaded if they differ only in the return type. Why is Function overloading not possible with different return types? Function overloading comes under the compile-time polymorphism. During compilation, the function signature is checked. So, functions can be overloaded, if the signatures are not the same. The return type of a function has no effect on function overloading, therefore the same function signature with different return type will not be overloaded. Example: if there are two functions: int sum() and float sum(), these two will generate a compile-time error as function overloading is not possible here. Let’s understand this further through the following programs in C++ and Java: C++ Program: CPP // CPP Program to demonstrate that function overloading// fails if only return types are different#include <iostream>int fun() { return 10; } char fun() { return 'a'; }// compiler error as it is a new declaration of fun() // Driver Codeint main(){ char x = fun(); getchar(); return 0;} Output prog.cpp: In function ‘char fun()’: prog.cpp:6:10: error: ambiguating new declaration of ‘char fun()’ char fun() { return 'a'; } ^ prog.cpp:4:5: note: old declaration ‘int fun()’ int fun() { return 10; } ^ Java Program: Java // Java Program to demonstrate that function overloading// fails if only return types are different // filename Main.javapublicclass Main {public int foo() { return 10; }public char foo() { return 'a'; } // compiler error as it is a new declaration of fun()public static void main(String args[]) {}} Output prog.java:10: error: method foo() is already defined in class Main char foo() { return 'a'; } ^ 1 error Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. anshikajain26 CPP-Functions cpp-overloading C++ Java Java CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Virtual Function in C++ Templates in C++ with Examples Constructors in C++ Operator Overloading in C++ Socket Programming in C/C++ Arrays in Java Split() String method in Java with examples For-each loop in Java HashMap in Java with Examples Reverse a string in Java
[ { "code": null, "e": 25564, "s": 25536, "text": "\n03 Jan, 2022" }, { "code": null, "e": 25812, "s": 25564, "text": "Function overloading is possible in C++ and Java but only if the functions must differ from each other by the types and the number of arguments in the argument list. However, functions can not be overloaded if they differ only in the return type. " }, { "code": null, "e": 25883, "s": 25812, "text": "Why is Function overloading not possible with different return types? " }, { "code": null, "e": 26230, "s": 25883, "text": "Function overloading comes under the compile-time polymorphism. During compilation, the function signature is checked. So, functions can be overloaded, if the signatures are not the same. The return type of a function has no effect on function overloading, therefore the same function signature with different return type will not be overloaded. " }, { "code": null, "e": 26385, "s": 26230, "text": "Example: if there are two functions: int sum() and float sum(), these two will generate a compile-time error as function overloading is not possible here." }, { "code": null, "e": 26463, "s": 26385, "text": "Let’s understand this further through the following programs in C++ and Java:" }, { "code": null, "e": 26476, "s": 26463, "text": "C++ Program:" }, { "code": null, "e": 26480, "s": 26476, "text": "CPP" }, { "code": "// CPP Program to demonstrate that function overloading// fails if only return types are different#include <iostream>int fun() { return 10; } char fun() { return 'a'; }// compiler error as it is a new declaration of fun() // Driver Codeint main(){ char x = fun(); getchar(); return 0;}", "e": 26777, "s": 26480, "text": null }, { "code": null, "e": 26784, "s": 26777, "text": "Output" }, { "code": null, "e": 27003, "s": 26784, "text": "prog.cpp: In function ‘char fun()’:\nprog.cpp:6:10: error: ambiguating new declaration of ‘char fun()’\nchar fun() { return 'a'; }\n ^\nprog.cpp:4:5: note: old declaration ‘int fun()’\nint fun() { return 10; }\n ^" }, { "code": null, "e": 27017, "s": 27003, "text": "Java Program:" }, { "code": null, "e": 27022, "s": 27017, "text": "Java" }, { "code": "// Java Program to demonstrate that function overloading// fails if only return types are different // filename Main.javapublicclass Main {public int foo() { return 10; }public char foo() { return 'a'; } // compiler error as it is a new declaration of fun()public static void main(String args[]) {}}", "e": 27335, "s": 27022, "text": null }, { "code": null, "e": 27342, "s": 27335, "text": "Output" }, { "code": null, "e": 27457, "s": 27342, "text": "prog.java:10: error: method foo() is already defined in class Main\n char foo() { return 'a'; }\n ^\n1 error" }, { "code": null, "e": 27582, "s": 27457, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 27596, "s": 27582, "text": "anshikajain26" }, { "code": null, "e": 27610, "s": 27596, "text": "CPP-Functions" }, { "code": null, "e": 27626, "s": 27610, "text": "cpp-overloading" }, { "code": null, "e": 27630, "s": 27626, "text": "C++" }, { "code": null, "e": 27635, "s": 27630, "text": "Java" }, { "code": null, "e": 27640, "s": 27635, "text": "Java" }, { "code": null, "e": 27644, "s": 27640, "text": "CPP" }, { "code": null, "e": 27742, "s": 27644, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27766, "s": 27742, "text": "Virtual Function in C++" }, { "code": null, "e": 27797, "s": 27766, "text": "Templates in C++ with Examples" }, { "code": null, "e": 27817, "s": 27797, "text": "Constructors in C++" }, { "code": null, "e": 27845, "s": 27817, "text": "Operator Overloading in C++" }, { "code": null, "e": 27873, "s": 27845, "text": "Socket Programming in C/C++" }, { "code": null, "e": 27888, "s": 27873, "text": "Arrays in Java" }, { "code": null, "e": 27932, "s": 27888, "text": "Split() String method in Java with examples" }, { "code": null, "e": 27954, "s": 27932, "text": "For-each loop in Java" }, { "code": null, "e": 27984, "s": 27954, "text": "HashMap in Java with Examples" } ]
C/C++ program to shutdown a system - GeeksforGeeks
07 Nov, 2019 How to shutdown your computer in Linux and/or Windows? The idea is to use system() in C. This function is used to invoke operating system commands from C program. Linux OS: // C program to shutdown in Linux#include <stdio.h>#include <stdlib.h> int main(){ // Running Linux OS command using system system("shutdown -P now"); return 0;} Windows OS: Shutdown/ Log off/ Restart a Windows OS We will make use of system() from < stdlib.h > to perform a system operation with the help of a C program.To perform any of the afore-mentioned system operation we will code as: #include <stdio.h>#include <stdlib.h> int main(){ system("c:\\windows\\system32\\shutdown /i"); return 0;} The argument to the system function is the path to OS and /i is one of the entity from the vast options available to us.To view the options, we run cmd and type: C:\Users\User>shutdown The shutdown command presents us with a list of options available for us.These are :To perform different operations, we just replace the last “/path” in system() argument.The common operations are: Shutdown system("c:\\windows\\system32\\shutdown /s"); Restart system("c:\\windows\\system32\\shutdown /r"); Logoff system("c:\\windows\\system32\\shutdown /l"); This article is contributed by Sahil Chhabra and Amartya Ranjan Saikia. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. CPP-Library cpp-puzzle C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Sorting a vector in C++ Friend class and function in C++ std::string class in C++ Pair in C++ Standard Template Library (STL) Queue in C++ Standard Template Library (STL) Inline Functions in C++ Array of Strings in C++ (5 Different Ways to Create) Convert string to char array in C++
[ { "code": null, "e": 25369, "s": 25341, "text": "\n07 Nov, 2019" }, { "code": null, "e": 25424, "s": 25369, "text": "How to shutdown your computer in Linux and/or Windows?" }, { "code": null, "e": 25532, "s": 25424, "text": "The idea is to use system() in C. This function is used to invoke operating system commands from C program." }, { "code": null, "e": 25542, "s": 25532, "text": "Linux OS:" }, { "code": "// C program to shutdown in Linux#include <stdio.h>#include <stdlib.h> int main(){ // Running Linux OS command using system system(\"shutdown -P now\"); return 0;}", "e": 25715, "s": 25542, "text": null }, { "code": null, "e": 25728, "s": 25715, "text": " Windows OS:" }, { "code": null, "e": 25768, "s": 25728, "text": "Shutdown/ Log off/ Restart a Windows OS" }, { "code": null, "e": 25946, "s": 25768, "text": "We will make use of system() from < stdlib.h > to perform a system operation with the help of a C program.To perform any of the afore-mentioned system operation we will code as:" }, { "code": "#include <stdio.h>#include <stdlib.h> int main(){ system(\"c:\\\\windows\\\\system32\\\\shutdown /i\"); return 0;}", "e": 26056, "s": 25946, "text": null }, { "code": null, "e": 26218, "s": 26056, "text": "The argument to the system function is the path to OS and /i is one of the entity from the vast options available to us.To view the options, we run cmd and type:" }, { "code": null, "e": 26242, "s": 26218, "text": "C:\\Users\\User>shutdown\n" }, { "code": null, "e": 26440, "s": 26242, "text": "The shutdown command presents us with a list of options available for us.These are :To perform different operations, we just replace the last “/path” in system() argument.The common operations are:" }, { "code": null, "e": 26449, "s": 26440, "text": "Shutdown" }, { "code": null, "e": 26495, "s": 26449, "text": "system(\"c:\\\\windows\\\\system32\\\\shutdown /s\");" }, { "code": null, "e": 26503, "s": 26495, "text": "Restart" }, { "code": null, "e": 26549, "s": 26503, "text": "system(\"c:\\\\windows\\\\system32\\\\shutdown /r\");" }, { "code": null, "e": 26556, "s": 26549, "text": "Logoff" }, { "code": null, "e": 26602, "s": 26556, "text": "system(\"c:\\\\windows\\\\system32\\\\shutdown /l\");" }, { "code": null, "e": 26929, "s": 26602, "text": "This article is contributed by Sahil Chhabra and Amartya Ranjan Saikia. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 27054, "s": 26929, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 27066, "s": 27054, "text": "CPP-Library" }, { "code": null, "e": 27077, "s": 27066, "text": "cpp-puzzle" }, { "code": null, "e": 27081, "s": 27077, "text": "C++" }, { "code": null, "e": 27085, "s": 27081, "text": "CPP" }, { "code": null, "e": 27183, "s": 27085, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27211, "s": 27183, "text": "Operator Overloading in C++" }, { "code": null, "e": 27231, "s": 27211, "text": "Polymorphism in C++" }, { "code": null, "e": 27255, "s": 27231, "text": "Sorting a vector in C++" }, { "code": null, "e": 27288, "s": 27255, "text": "Friend class and function in C++" }, { "code": null, "e": 27313, "s": 27288, "text": "std::string class in C++" }, { "code": null, "e": 27357, "s": 27313, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 27402, "s": 27357, "text": "Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 27426, "s": 27402, "text": "Inline Functions in C++" }, { "code": null, "e": 27479, "s": 27426, "text": "Array of Strings in C++ (5 Different Ways to Create)" } ]
jQuery | removeAttr() with Examples - GeeksforGeeks
03 Aug, 2021 The removeAttr() method is an inbuilt method in jQuery which is used to remove one or more attributes from the selected elements. Syntax: $(selector).removeAttr(attribute) Parameters: This function accepts single parameter attribute which is mandatory. It is used to specify one or more attributes to remove. Several attributes can be separated using space operator. Return Value: This method returns the selected element with the removed attribute. Below example illustrates the removeAttr() method in jQuery: Example: <!DOCTYPE html><html> <head> <title>The removeAttr Method</title> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <!-- jQuery code to show the working of this method --> <script> $(document).ready(function() { $("button").click(function() { $("p").removeAttr("style"); }); }); </script> <style> div { width: 300px; min-height: 150px; border: 2px solid green; padding: 20px; text-align:center; } </style> </head> <body> <div> <!-- click on the any of the paragraph and see the change --> <p style="font-size:35px;font-weight:bold; color:green;">Welcome to</p> <p style="font-size:35px;font-weight:bold; color:green;">GeeksforGeeks!.</p> <button>Click Here!</button> </div> </body></html> Output: jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples. jQuery-HTML/CSS JavaScript JQuery Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? JQuery | Set the value of an input text field Form validation using jQuery How to change the background color after clicking the button in JavaScript ? How to fetch data from JSON file and display in HTML table using jQuery ? How to Dynamically Add/Remove Table Rows using jQuery ?
[ { "code": null, "e": 26336, "s": 26308, "text": "\n03 Aug, 2021" }, { "code": null, "e": 26466, "s": 26336, "text": "The removeAttr() method is an inbuilt method in jQuery which is used to remove one or more attributes from the selected elements." }, { "code": null, "e": 26474, "s": 26466, "text": "Syntax:" }, { "code": null, "e": 26508, "s": 26474, "text": "$(selector).removeAttr(attribute)" }, { "code": null, "e": 26703, "s": 26508, "text": "Parameters: This function accepts single parameter attribute which is mandatory. It is used to specify one or more attributes to remove. Several attributes can be separated using space operator." }, { "code": null, "e": 26786, "s": 26703, "text": "Return Value: This method returns the selected element with the removed attribute." }, { "code": null, "e": 26847, "s": 26786, "text": "Below example illustrates the removeAttr() method in jQuery:" }, { "code": null, "e": 26856, "s": 26847, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title>The removeAttr Method</title> <script src= \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <!-- jQuery code to show the working of this method --> <script> $(document).ready(function() { $(\"button\").click(function() { $(\"p\").removeAttr(\"style\"); }); }); </script> <style> div { width: 300px; min-height: 150px; border: 2px solid green; padding: 20px; text-align:center; } </style> </head> <body> <div> <!-- click on the any of the paragraph and see the change --> <p style=\"font-size:35px;font-weight:bold; color:green;\">Welcome to</p> <p style=\"font-size:35px;font-weight:bold; color:green;\">GeeksforGeeks!.</p> <button>Click Here!</button> </div> </body></html>", "e": 27877, "s": 26856, "text": null }, { "code": null, "e": 27885, "s": 27877, "text": "Output:" }, { "code": null, "e": 28153, "s": 27885, "text": "jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples." }, { "code": null, "e": 28169, "s": 28153, "text": "jQuery-HTML/CSS" }, { "code": null, "e": 28180, "s": 28169, "text": "JavaScript" }, { "code": null, "e": 28187, "s": 28180, "text": "JQuery" }, { "code": null, "e": 28285, "s": 28187, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28325, "s": 28285, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28370, "s": 28325, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28431, "s": 28370, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28503, "s": 28431, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 28555, "s": 28503, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 28601, "s": 28555, "text": "JQuery | Set the value of an input text field" }, { "code": null, "e": 28630, "s": 28601, "text": "Form validation using jQuery" }, { "code": null, "e": 28707, "s": 28630, "text": "How to change the background color after clicking the button in JavaScript ?" }, { "code": null, "e": 28781, "s": 28707, "text": "How to fetch data from JSON file and display in HTML table using jQuery ?" } ]
PyQtGraph - Extensive Examples - GeeksforGeeks
24 Sep, 2020 In this article we will see how we can access the PyQtGraph extensive examples. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) and second is to provide tools to aid in rapid application development (for example, property trees such as used in Qt Designer). PyQtGraph includes an extensive set of examples which can be accessed by the import pyqtgraph.examples module In order to do this we use run method with the pyqtgraph.examples Syntax : examples.run() Argument : It takes no argument Return : It returns None Below is the implementation # importing the pyqtgraph.examples moduleimport pyqtgraph.examples # run this examplespyqtgraph.examples.run() Output : when we run this code this window appears which has lots of options, on the left hand side we have the basic functions and on main screen it shows the code and explanation of the widget/function and on the lower left corner we have the option to try the example Now lets traverse the fields on the left side and see how the example will work We can try as many examples anytime for better understanding of the PyQtGraph module Python-gui Python-PyQtGraph Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n24 Sep, 2020" }, { "code": null, "e": 25995, "s": 25537, "text": "In this article we will see how we can access the PyQtGraph extensive examples. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) and second is to provide tools to aid in rapid application development (for example, property trees such as used in Qt Designer)." }, { "code": null, "e": 26105, "s": 25995, "text": "PyQtGraph includes an extensive set of examples which can be accessed by the import pyqtgraph.examples module" }, { "code": null, "e": 26171, "s": 26105, "text": "In order to do this we use run method with the pyqtgraph.examples" }, { "code": null, "e": 26195, "s": 26171, "text": "Syntax : examples.run()" }, { "code": null, "e": 26227, "s": 26195, "text": "Argument : It takes no argument" }, { "code": null, "e": 26252, "s": 26227, "text": "Return : It returns None" }, { "code": null, "e": 26280, "s": 26252, "text": "Below is the implementation" }, { "code": "# importing the pyqtgraph.examples moduleimport pyqtgraph.examples # run this examplespyqtgraph.examples.run()", "e": 26392, "s": 26280, "text": null }, { "code": null, "e": 26401, "s": 26392, "text": "Output :" }, { "code": null, "e": 26663, "s": 26401, "text": "when we run this code this window appears which has lots of options, on the left hand side we have the basic functions and on main screen it shows the code and explanation of the widget/function and on the lower left corner we have the option to try the example" }, { "code": null, "e": 26743, "s": 26663, "text": "Now lets traverse the fields on the left side and see how the example will work" }, { "code": null, "e": 26828, "s": 26743, "text": "We can try as many examples anytime for better understanding of the PyQtGraph module" }, { "code": null, "e": 26839, "s": 26828, "text": "Python-gui" }, { "code": null, "e": 26856, "s": 26839, "text": "Python-PyQtGraph" }, { "code": null, "e": 26863, "s": 26856, "text": "Python" }, { "code": null, "e": 26961, "s": 26863, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26993, "s": 26961, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27035, "s": 26993, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27077, "s": 27035, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27104, "s": 27077, "text": "Python Classes and Objects" }, { "code": null, "e": 27160, "s": 27104, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27199, "s": 27160, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27221, "s": 27199, "text": "Defaultdict in Python" }, { "code": null, "e": 27252, "s": 27221, "text": "Python | os.path.join() method" }, { "code": null, "e": 27281, "s": 27252, "text": "Create a directory in Python" } ]
D3.js selection.remove() Function - GeeksforGeeks
31 Aug, 2020 The selection.remove() function is used to remove the selected elements from the document and return a new selection with the removed elements. Also, new selection are now detached from the DOM Syntax: selection.remove(); Parameters: This function does not accept any parameters. Return Values: This function returns a new selection. Example 1: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" path1tent= "width=device-width, initial-scale=1.0"> <script src="https://d3js.org/d3.v4.min.js"> </script> <style> h1 { color: green; } div { width: 300px; color: #ffffff; height: 50px; background-color: green; margin: 10px; } </style> <body> <h1>GeeksforGeeks</h1> <h4>D3.js selection.remove() Function</h4> <p>The divs will be removed.</p> <div><span>1. This div will be removed.</span></div> <div><span>2. This div will be removed.</span></div> <button>Click Here!</button> <script> function func() { // Selecting div and // Removing the div var div = d3.selectAll("div") .remove(); } btn = document.querySelector("button"); btn.addEventListener("click", func); </script></body> </html> Output: Before clicking the “Click Here!” element: After clicking the “Click Here!” element: Example 2: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" path1tent= "width=device-width, initial-scale=1.0"> <script src="https://d3js.org/d3.v4.min.js"> </script> <style> h1 { color: green; } div { width: 300px; color: #ffffff; height: 50px; background-color: green; margin: 10px; } </style> <body> <h1>Geeks for geeks</h1> <h4>D3.js selection.remove() Function</h4> <p>The <span> from div will be removed.</p> <div><span>1. This text will be removed.</span></div> <div><span>2. This div will not be removed.</span></div> <button>Click Here!</button> <script> function func() { // Selecting div and // The text inside the div will be removed. var div = d3.select("span") .remove(); } btn = document.querySelector("button"); btn.addEventListener("click", func); </script></body> </html> Output: Before clicking the click Here button: After clicking the click Here button: D3.js 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 Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? Remove elements from a JavaScript Array Installation of Node.js on Linux How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26545, "s": 26517, "text": "\n31 Aug, 2020" }, { "code": null, "e": 26739, "s": 26545, "text": "The selection.remove() function is used to remove the selected elements from the document and return a new selection with the removed elements. Also, new selection are now detached from the DOM" }, { "code": null, "e": 26747, "s": 26739, "text": "Syntax:" }, { "code": null, "e": 26767, "s": 26747, "text": "selection.remove();" }, { "code": null, "e": 26825, "s": 26767, "text": "Parameters: This function does not accept any parameters." }, { "code": null, "e": 26879, "s": 26825, "text": "Return Values: This function returns a new selection." }, { "code": null, "e": 26890, "s": 26879, "text": "Example 1:" }, { "code": null, "e": 26895, "s": 26890, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" path1tent= \"width=device-width, initial-scale=1.0\"> <script src=\"https://d3js.org/d3.v4.min.js\"> </script> <style> h1 { color: green; } div { width: 300px; color: #ffffff; height: 50px; background-color: green; margin: 10px; } </style> <body> <h1>GeeksforGeeks</h1> <h4>D3.js selection.remove() Function</h4> <p>The divs will be removed.</p> <div><span>1. This div will be removed.</span></div> <div><span>2. This div will be removed.</span></div> <button>Click Here!</button> <script> function func() { // Selecting div and // Removing the div var div = d3.selectAll(\"div\") .remove(); } btn = document.querySelector(\"button\"); btn.addEventListener(\"click\", func); </script></body> </html>", "e": 27914, "s": 26895, "text": null }, { "code": null, "e": 27922, "s": 27914, "text": "Output:" }, { "code": null, "e": 27965, "s": 27922, "text": "Before clicking the “Click Here!” element:" }, { "code": null, "e": 28007, "s": 27965, "text": "After clicking the “Click Here!” element:" }, { "code": null, "e": 28018, "s": 28007, "text": "Example 2:" }, { "code": null, "e": 28023, "s": 28018, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" path1tent= \"width=device-width, initial-scale=1.0\"> <script src=\"https://d3js.org/d3.v4.min.js\"> </script> <style> h1 { color: green; } div { width: 300px; color: #ffffff; height: 50px; background-color: green; margin: 10px; } </style> <body> <h1>Geeks for geeks</h1> <h4>D3.js selection.remove() Function</h4> <p>The <span> from div will be removed.</p> <div><span>1. This text will be removed.</span></div> <div><span>2. This div will not be removed.</span></div> <button>Click Here!</button> <script> function func() { // Selecting div and // The text inside the div will be removed. var div = d3.select(\"span\") .remove(); } btn = document.querySelector(\"button\"); btn.addEventListener(\"click\", func); </script></body> </html>", "e": 29076, "s": 28023, "text": null }, { "code": null, "e": 29084, "s": 29076, "text": "Output:" }, { "code": null, "e": 29123, "s": 29084, "text": "Before clicking the click Here button:" }, { "code": null, "e": 29161, "s": 29123, "text": "After clicking the click Here button:" }, { "code": null, "e": 29167, "s": 29161, "text": "D3.js" }, { "code": null, "e": 29178, "s": 29167, "text": "JavaScript" }, { "code": null, "e": 29195, "s": 29178, "text": "Web Technologies" }, { "code": null, "e": 29293, "s": 29195, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29333, "s": 29293, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29394, "s": 29333, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29435, "s": 29394, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 29457, "s": 29435, "text": "JavaScript | Promises" }, { "code": null, "e": 29511, "s": 29457, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 29551, "s": 29511, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29584, "s": 29551, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29627, "s": 29584, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29677, "s": 29627, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Count number of integers less than or equal to N which has exactly 9 divisors - GeeksforGeeks
10 May, 2021 Given a number N(1<=N<=109), the task is to find the total number of integers less than equal to n which have exactly 9 divisors. Examples: Input: N = 100 Output: 2 The two numbers which have exactly 9 divisors are 36 and 100. Input: N = 1000 Output: 8 The numbers are 36 100 196 225 256 441 484 676 A naive approach is to iterate for all numbers till N and count the numbers that have exactly 9 divisors. For counting the number of divisors, one can easily iterate till N and check if N is divisible by i or not and keep a count. Below is the implementation of the above approach: C++ Java Python 3 C# PHP Javascript // C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to count factors in O(N)int numberOfDivisors(int num){ int c = 0; // iterate and check if factor or not for (int i = 1; i <= num; i++) { if (num % i == 0) { c += 1; } } return c;} // Function to count numbers having// exactly 9 divisorsint countNumbers(int n){ int c = 0; // check for all numbers <=N for (int i = 1; i <= n; i++) { // check if exactly 9 factors or not if (numberOfDivisors(i) == 9) c += 1; } return c;} // Driver Codeint main(){ int n = 1000; cout << countNumbers(n); return 0;} // Java implementation of above approach import java.io.*; class GFG { // Function to count factors in O(N)static int numberOfDivisors(int num){ int c = 0; // iterate and check if factor or not for (int i = 1; i <= num; i++) { if (num % i == 0) { c += 1; } } return c;} // Function to count numbers having// exactly 9 divisorsstatic int countNumbers(int n){ int c = 0; // check for all numbers <=N for (int i = 1; i <= n; i++) { // check if exactly 9 factors or not if (numberOfDivisors(i) == 9) c += 1; } return c;} // Driver Code public static void main (String[] args) { int n = 1000; System.out.print(countNumbers(n)); }} // This code is contributed by inder_verma.. # Python 3 implementation of# above approach # Function to count factors in O(N)def numberOfDivisors(num): c = 0 # iterate and check if # factor or not for i in range(1, num + 1) : if (num % i == 0) : c += 1 return c # Function to count numbers having# exactly 9 divisorsdef countNumbers(n): c = 0 # check for all numbers <=N for i in range(1, n + 1) : # check if exactly 9 factors or not if (numberOfDivisors(i) == 9): c += 1 return c # Driver Codeif __name__ == "__main__": n = 1000 print(countNumbers(n)) # This code is contributed# by ChitraNayal // C# implementation of above approachusing System; class GFG{ // Function to count factors in O(N)static int numberOfDivisors(int num){ int c = 0; // iterate and check if factor or not for (int i = 1; i <= num; i++) { if (num % i == 0) { c += 1; } } return c;} // Function to count numbers having// exactly 9 divisorsstatic int countNumbers(int n){ int c = 0; // check for all numbers <=N for (int i = 1; i <= n; i++) { // check if exactly 9 factors or not if (numberOfDivisors(i) == 9) c += 1; } return c;} // Driver Codepublic static void Main (){int n = 1000; Console.Write(countNumbers(n));}} // This code is contributed// by Akanksha Rai(Abby_akku) <?php// PHP implementation of above approach // Function to count factors in O(N)Function numberOfDivisors($num){ $c = 0; // iterate and check // if factor or not for ($i = 1; $i <= $num; $i++) { if ($num % $i == 0) { $c += 1; } } return $c;} // Function to count numbers// having exactly 9 divisorsFunction countNumbers($n){ $c = 0; // check for all numbers <=N for ($i = 1; $i <= $n; $i++) { // check if exactly 9 factors or not if (numberOfDivisors($i) == 9) $c += 1; } return $c;} // Driver Code$n = 1000; echo countNumbers($n); // This code is contributed// by Shivi_Aggarwal?> <script> // Javascript implementation of above approach // Function to count factors in O(N) function numberOfDivisors(num) { let c = 0; // iterate and check if factor or not for (let i = 1; i <= num; i++) { if (num % i == 0) { c += 1; } } return c; } // Function to count numbers having // exactly 9 divisors function countNumbers(n) { let c = 0; // check for all numbers <=N for (let i = 1; i <= n; i++) { // check if exactly 9 factors or not if (numberOfDivisors(i) == 9) c += 1; } return c; } let n = 1000; document.write(countNumbers(n)); </script> 8 An efficient approach is to use the property of the prime factor to count the number of divisors of a number. The method can be found here. If any number(let x) can be expressed in terms of (p^2 * q^2) or (p^8), where p and q are prime factors of X, then X has a total of 9 divisors. The below steps can be followed to solve the above problem. Use Sieve technique to mark the smallest prime factor of a number.We just need to check for all the numbers in the range[1-sqrt(n)] that can be expressed in terms of p*q since (p^2*q^2) has 9 factors, hence (p*q)^2 will also have exactly 9 factors.Iterate from 1 to sqrt(n) and check if i can be expressed as p*q, where p and q are prime numbers.Also, check if i is prime then pow(i, 8)<=n or not, in that case, count that number also.The summation of the count of numbers that can be expressed in the form p*q and p^8 is our answer. Use Sieve technique to mark the smallest prime factor of a number. We just need to check for all the numbers in the range[1-sqrt(n)] that can be expressed in terms of p*q since (p^2*q^2) has 9 factors, hence (p*q)^2 will also have exactly 9 factors. Iterate from 1 to sqrt(n) and check if i can be expressed as p*q, where p and q are prime numbers. Also, check if i is prime then pow(i, 8)<=n or not, in that case, count that number also. The summation of the count of numbers that can be expressed in the form p*q and p^8 is our answer. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to count numbers having// exactly 9 divisorsint countNumbers(int n){ int c = 0; int limit = sqrt(n); // Sieve array int prime[limit + 1]; // initially prime[i] = i for (int i = 1; i <= limit; i++) prime[i] = i; // use sieve concept to store the // first prime factor of every number for (int i = 2; i * i <= limit; i++) { if (prime[i] == i) { // mark all factors of i for (int j = i * i; j <= limit; j += i) if (prime[j] == j) prime[j] = i; } } // check for all numbers if they can be // expressed in form p*q for (int i = 2; i <= limit; i++) { // p prime factor int p = prime[i]; // q prime factor int q = prime[i / prime[i]]; // if both prime factors are different // if p*q<=n and q!= if (p * q == i && q != 1 && p != q) { c += 1; } else if (prime[i] == i) { // Check if it can be expressed as p^8 if (pow(i, 8) <= n) { c += 1; } } } return c;} // Driver Codeint main(){ int n = 1000; cout << countNumbers(n); return 0;} // Java implementation of above approachpublic class GFG { // Function to count numbers having// exactly 9 divisors static int countNumbers(int n) { int c = 0; int limit = (int) Math.sqrt(n); // Sieve array int prime[] = new int[limit + 1]; // initially prime[i] = i for (int i = 1; i <= limit; i++) { prime[i] = i; } // use sieve concept to store the // first prime factor of every number for (int i = 2; i * i <= limit; i++) { if (prime[i] == i) { // mark all factors of i for (int j = i * i; j <= limit; j += i) { if (prime[j] == j) { prime[j] = i; } } } } // check for all numbers if they can be // expressed in form p*q for (int i = 2; i <= limit; i++) { // p prime factor int p = prime[i]; // q prime factor int q = prime[i / prime[i]]; // if both prime factors are different // if p*q<=n and q!= if (p * q == i && q != 1 && p != q) { c += 1; } else if (prime[i] == i) { // Check if it can be expressed as p^8 if (Math.pow(i, 8) <= n) { c += 1; } } } return c; } // Driver Code public static void main(String[] args) { int n = 1000; System.out.println(countNumbers(n)); }}/*This code is contributed by PrinciRaj1992*/ # Python3 implementation of the above approach # Function to count numbers# having exactly 9 divisorsdef countNumbers(n): c = 0 limit = int(n ** (0.5)) # Sieve array, initially prime[i] = i prime = [i for i in range(limit + 1)] # use sieve concept to store the # first prime factor of every number i = 2 while i * i <= limit: if prime[i] == i: # mark all factors of i for j in range(i * i, limit + 1, i): if prime[j] == j: prime[j] = i i += 1 # check for all numbers if they # can be expressed in form p*q for i in range(2, limit + 1): # p prime factor p = prime[i] # q prime factor q = prime[i // prime[i]] # if both prime factors are different # if p*q<=n and q!= if p * q == i and q != 1 and p != q: c += 1 elif prime[i] == i: # Check if it can be # expressed as p^8 if i ** 8 <= n: c += 1 return c # Driver Codeif __name__ == "__main__": n = 1000 print(countNumbers(n)) # This code is contributed# by Rituraj Jain // C# implementation of above approachusing System; public class GFG { // Function to count numbers having// exactly 9 divisors static int countNumbers(int n) { int c = 0; int limit = (int) Math.Sqrt(n); // Sieve array int []prime = new int[limit + 1]; // initially prime[i] = i for (int i = 1; i <= limit; i++) { prime[i] = i; } // use sieve concept to store the // first prime factor of every number for (int i = 2; i * i <= limit; i++) { if (prime[i] == i) { // mark all factors of i for (int j = i * i; j <= limit; j += i) { if (prime[j] == j) { prime[j] = i; } } } } // check for all numbers if they can be // expressed in form p*q for (int i = 2; i <= limit; i++) { // p prime factor int p = prime[i]; // q prime factor int q = prime[i / prime[i]]; // if both prime factors are different // if p*q<=n and q!= if (p * q == i && q != 1 && p != q) { c += 1; } else if (prime[i] == i) { // Check if it can be expressed as p^8 if (Math.Pow(i, 8) <= n) { c += 1; } } } return c; } // Driver Code public static void Main() { int n = 1000; Console.WriteLine(countNumbers(n)); }}/*This code is contributed by PrinciRaj1992*/ <?php// PHP implementation of above approach// Function to count numbers having// exactly 9 divisors function countNumbers($n){ $c = 0; $limit = sqrt($n); // Sieve array $prime[$limit + 1] = array(0); // initially prime[i] = i for ($i = 1; $i <= $limit; $i++) $prime[$i] = $i; // use sieve concept to store the // first prime factor of every number for ($i = 2; $i * $i <= $limit; $i++) { if ($prime[$i] == $i) { // mark all factors of i for ($j = $i * $i; $j <= $limit; $j += $i) if ($prime[$j] == $j) $prime[$j] = $i; } } // check for all numbers if they // can be expressed in form p*q for ($i = 2; $i <= $limit; $i++) { // p prime factor $p = $prime[$i]; // q prime factor $q = $prime[$i / $prime[$i]]; // if both prime factors are different // if p*q<=n and q!= if ($p * $q == $i && $q != 1 && $p != $q) { $c += 1; } else if ($prime[$i] == $i) { // Check if it can be expressed as p^8 if (pow($i, 8) <= $n) { $c += 1; } } } return $c;} // Driver Code$n = 1000;echo countNumbers($n); // This code is contributed by jit_t?> <script> // Javascript implementation of above approach // Function to count numbers having // exactly 9 divisors function countNumbers(n) { let c = 0; let limit = parseInt(Math.sqrt(n), 10); // Sieve array let prime = new Array(limit + 1); prime.fill(0); // initially prime[i] = i for (let i = 1; i <= limit; i++) { prime[i] = i; } // use sieve concept to store the // first prime factor of every number for (let i = 2; i * i <= limit; i++) { if (prime[i] == i) { // mark all factors of i for (let j = i * i; j <= limit; j += i) { if (prime[j] == j) { prime[j] = i; } } } } // check for all numbers if they can be // expressed in form p*q for (let i = 2; i <= limit; i++) { // p prime factor let p = prime[i]; // q prime factor let q = prime[parseInt(i / prime[i], 10)]; // if both prime factors are different // if p*q<=n and q!= if (p * q == i && q != 1 && p != q) { c += 1; } else if (prime[i] == i) { // Check if it can be expressed as p^8 if (Math.pow(i, 8) <= n) { c += 1; } } } return c; } let n = 1000; document.write(countNumbers(n)); </script> 8 Time Complexity: O(sqrt(N)) Auxiliary Space: O(sqrt(N)) inderDuMCA Shivi_Aggarwal ukasp Akanksha_Rai jit_t princiraj1992 rituraj_jain shubham_singh divyesh072019 divyeshrabadiya07 Directi divisors Prime Number prime-factor sieve Technical Scripter 2018 Competitive Programming Mathematical Directi Mathematical Prime Number sieve Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Prefix Sum Array - Implementation and Applications in Competitive Programming Ordered Set and GNU C++ PBDS Modulo 10^9+7 (1000000007) Bits manipulation (Important tactics) What is Competitive Programming and How to Prepare for It? Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 26391, "s": 26363, "text": "\n10 May, 2021" }, { "code": null, "e": 26521, "s": 26391, "text": "Given a number N(1<=N<=109), the task is to find the total number of integers less than equal to n which have exactly 9 divisors." }, { "code": null, "e": 26533, "s": 26521, "text": "Examples: " }, { "code": null, "e": 26694, "s": 26533, "text": "Input: N = 100 Output: 2 The two numbers which have exactly 9 divisors are 36 and 100. Input: N = 1000 Output: 8 The numbers are 36 100 196 225 256 441 484 676 " }, { "code": null, "e": 26926, "s": 26694, "text": "A naive approach is to iterate for all numbers till N and count the numbers that have exactly 9 divisors. For counting the number of divisors, one can easily iterate till N and check if N is divisible by i or not and keep a count. " }, { "code": null, "e": 26979, "s": 26926, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26983, "s": 26979, "text": "C++" }, { "code": null, "e": 26988, "s": 26983, "text": "Java" }, { "code": null, "e": 26997, "s": 26988, "text": "Python 3" }, { "code": null, "e": 27000, "s": 26997, "text": "C#" }, { "code": null, "e": 27004, "s": 27000, "text": "PHP" }, { "code": null, "e": 27015, "s": 27004, "text": "Javascript" }, { "code": "// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to count factors in O(N)int numberOfDivisors(int num){ int c = 0; // iterate and check if factor or not for (int i = 1; i <= num; i++) { if (num % i == 0) { c += 1; } } return c;} // Function to count numbers having// exactly 9 divisorsint countNumbers(int n){ int c = 0; // check for all numbers <=N for (int i = 1; i <= n; i++) { // check if exactly 9 factors or not if (numberOfDivisors(i) == 9) c += 1; } return c;} // Driver Codeint main(){ int n = 1000; cout << countNumbers(n); return 0;}", "e": 27696, "s": 27015, "text": null }, { "code": "// Java implementation of above approach import java.io.*; class GFG { // Function to count factors in O(N)static int numberOfDivisors(int num){ int c = 0; // iterate and check if factor or not for (int i = 1; i <= num; i++) { if (num % i == 0) { c += 1; } } return c;} // Function to count numbers having// exactly 9 divisorsstatic int countNumbers(int n){ int c = 0; // check for all numbers <=N for (int i = 1; i <= n; i++) { // check if exactly 9 factors or not if (numberOfDivisors(i) == 9) c += 1; } return c;} // Driver Code public static void main (String[] args) { int n = 1000; System.out.print(countNumbers(n)); }} // This code is contributed by inder_verma..", "e": 28469, "s": 27696, "text": null }, { "code": "# Python 3 implementation of# above approach # Function to count factors in O(N)def numberOfDivisors(num): c = 0 # iterate and check if # factor or not for i in range(1, num + 1) : if (num % i == 0) : c += 1 return c # Function to count numbers having# exactly 9 divisorsdef countNumbers(n): c = 0 # check for all numbers <=N for i in range(1, n + 1) : # check if exactly 9 factors or not if (numberOfDivisors(i) == 9): c += 1 return c # Driver Codeif __name__ == \"__main__\": n = 1000 print(countNumbers(n)) # This code is contributed# by ChitraNayal", "e": 29118, "s": 28469, "text": null }, { "code": "// C# implementation of above approachusing System; class GFG{ // Function to count factors in O(N)static int numberOfDivisors(int num){ int c = 0; // iterate and check if factor or not for (int i = 1; i <= num; i++) { if (num % i == 0) { c += 1; } } return c;} // Function to count numbers having// exactly 9 divisorsstatic int countNumbers(int n){ int c = 0; // check for all numbers <=N for (int i = 1; i <= n; i++) { // check if exactly 9 factors or not if (numberOfDivisors(i) == 9) c += 1; } return c;} // Driver Codepublic static void Main (){int n = 1000; Console.Write(countNumbers(n));}} // This code is contributed// by Akanksha Rai(Abby_akku)", "e": 29865, "s": 29118, "text": null }, { "code": "<?php// PHP implementation of above approach // Function to count factors in O(N)Function numberOfDivisors($num){ $c = 0; // iterate and check // if factor or not for ($i = 1; $i <= $num; $i++) { if ($num % $i == 0) { $c += 1; } } return $c;} // Function to count numbers// having exactly 9 divisorsFunction countNumbers($n){ $c = 0; // check for all numbers <=N for ($i = 1; $i <= $n; $i++) { // check if exactly 9 factors or not if (numberOfDivisors($i) == 9) $c += 1; } return $c;} // Driver Code$n = 1000; echo countNumbers($n); // This code is contributed// by Shivi_Aggarwal?>", "e": 30551, "s": 29865, "text": null }, { "code": "<script> // Javascript implementation of above approach // Function to count factors in O(N) function numberOfDivisors(num) { let c = 0; // iterate and check if factor or not for (let i = 1; i <= num; i++) { if (num % i == 0) { c += 1; } } return c; } // Function to count numbers having // exactly 9 divisors function countNumbers(n) { let c = 0; // check for all numbers <=N for (let i = 1; i <= n; i++) { // check if exactly 9 factors or not if (numberOfDivisors(i) == 9) c += 1; } return c; } let n = 1000; document.write(countNumbers(n)); </script>", "e": 31353, "s": 30551, "text": null }, { "code": null, "e": 31355, "s": 31353, "text": "8" }, { "code": null, "e": 31703, "s": 31357, "text": "An efficient approach is to use the property of the prime factor to count the number of divisors of a number. The method can be found here. If any number(let x) can be expressed in terms of (p^2 * q^2) or (p^8), where p and q are prime factors of X, then X has a total of 9 divisors. The below steps can be followed to solve the above problem. " }, { "code": null, "e": 32237, "s": 31703, "text": "Use Sieve technique to mark the smallest prime factor of a number.We just need to check for all the numbers in the range[1-sqrt(n)] that can be expressed in terms of p*q since (p^2*q^2) has 9 factors, hence (p*q)^2 will also have exactly 9 factors.Iterate from 1 to sqrt(n) and check if i can be expressed as p*q, where p and q are prime numbers.Also, check if i is prime then pow(i, 8)<=n or not, in that case, count that number also.The summation of the count of numbers that can be expressed in the form p*q and p^8 is our answer." }, { "code": null, "e": 32304, "s": 32237, "text": "Use Sieve technique to mark the smallest prime factor of a number." }, { "code": null, "e": 32487, "s": 32304, "text": "We just need to check for all the numbers in the range[1-sqrt(n)] that can be expressed in terms of p*q since (p^2*q^2) has 9 factors, hence (p*q)^2 will also have exactly 9 factors." }, { "code": null, "e": 32586, "s": 32487, "text": "Iterate from 1 to sqrt(n) and check if i can be expressed as p*q, where p and q are prime numbers." }, { "code": null, "e": 32676, "s": 32586, "text": "Also, check if i is prime then pow(i, 8)<=n or not, in that case, count that number also." }, { "code": null, "e": 32775, "s": 32676, "text": "The summation of the count of numbers that can be expressed in the form p*q and p^8 is our answer." }, { "code": null, "e": 32828, "s": 32775, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 32832, "s": 32828, "text": "C++" }, { "code": null, "e": 32837, "s": 32832, "text": "Java" }, { "code": null, "e": 32845, "s": 32837, "text": "Python3" }, { "code": null, "e": 32848, "s": 32845, "text": "C#" }, { "code": null, "e": 32852, "s": 32848, "text": "PHP" }, { "code": null, "e": 32863, "s": 32852, "text": "Javascript" }, { "code": "// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to count numbers having// exactly 9 divisorsint countNumbers(int n){ int c = 0; int limit = sqrt(n); // Sieve array int prime[limit + 1]; // initially prime[i] = i for (int i = 1; i <= limit; i++) prime[i] = i; // use sieve concept to store the // first prime factor of every number for (int i = 2; i * i <= limit; i++) { if (prime[i] == i) { // mark all factors of i for (int j = i * i; j <= limit; j += i) if (prime[j] == j) prime[j] = i; } } // check for all numbers if they can be // expressed in form p*q for (int i = 2; i <= limit; i++) { // p prime factor int p = prime[i]; // q prime factor int q = prime[i / prime[i]]; // if both prime factors are different // if p*q<=n and q!= if (p * q == i && q != 1 && p != q) { c += 1; } else if (prime[i] == i) { // Check if it can be expressed as p^8 if (pow(i, 8) <= n) { c += 1; } } } return c;} // Driver Codeint main(){ int n = 1000; cout << countNumbers(n); return 0;}", "e": 34151, "s": 32863, "text": null }, { "code": "// Java implementation of above approachpublic class GFG { // Function to count numbers having// exactly 9 divisors static int countNumbers(int n) { int c = 0; int limit = (int) Math.sqrt(n); // Sieve array int prime[] = new int[limit + 1]; // initially prime[i] = i for (int i = 1; i <= limit; i++) { prime[i] = i; } // use sieve concept to store the // first prime factor of every number for (int i = 2; i * i <= limit; i++) { if (prime[i] == i) { // mark all factors of i for (int j = i * i; j <= limit; j += i) { if (prime[j] == j) { prime[j] = i; } } } } // check for all numbers if they can be // expressed in form p*q for (int i = 2; i <= limit; i++) { // p prime factor int p = prime[i]; // q prime factor int q = prime[i / prime[i]]; // if both prime factors are different // if p*q<=n and q!= if (p * q == i && q != 1 && p != q) { c += 1; } else if (prime[i] == i) { // Check if it can be expressed as p^8 if (Math.pow(i, 8) <= n) { c += 1; } } } return c; } // Driver Code public static void main(String[] args) { int n = 1000; System.out.println(countNumbers(n)); }}/*This code is contributed by PrinciRaj1992*/", "e": 35742, "s": 34151, "text": null }, { "code": "# Python3 implementation of the above approach # Function to count numbers# having exactly 9 divisorsdef countNumbers(n): c = 0 limit = int(n ** (0.5)) # Sieve array, initially prime[i] = i prime = [i for i in range(limit + 1)] # use sieve concept to store the # first prime factor of every number i = 2 while i * i <= limit: if prime[i] == i: # mark all factors of i for j in range(i * i, limit + 1, i): if prime[j] == j: prime[j] = i i += 1 # check for all numbers if they # can be expressed in form p*q for i in range(2, limit + 1): # p prime factor p = prime[i] # q prime factor q = prime[i // prime[i]] # if both prime factors are different # if p*q<=n and q!= if p * q == i and q != 1 and p != q: c += 1 elif prime[i] == i: # Check if it can be # expressed as p^8 if i ** 8 <= n: c += 1 return c # Driver Codeif __name__ == \"__main__\": n = 1000 print(countNumbers(n)) # This code is contributed# by Rituraj Jain", "e": 36948, "s": 35742, "text": null }, { "code": "// C# implementation of above approachusing System; public class GFG { // Function to count numbers having// exactly 9 divisors static int countNumbers(int n) { int c = 0; int limit = (int) Math.Sqrt(n); // Sieve array int []prime = new int[limit + 1]; // initially prime[i] = i for (int i = 1; i <= limit; i++) { prime[i] = i; } // use sieve concept to store the // first prime factor of every number for (int i = 2; i * i <= limit; i++) { if (prime[i] == i) { // mark all factors of i for (int j = i * i; j <= limit; j += i) { if (prime[j] == j) { prime[j] = i; } } } } // check for all numbers if they can be // expressed in form p*q for (int i = 2; i <= limit; i++) { // p prime factor int p = prime[i]; // q prime factor int q = prime[i / prime[i]]; // if both prime factors are different // if p*q<=n and q!= if (p * q == i && q != 1 && p != q) { c += 1; } else if (prime[i] == i) { // Check if it can be expressed as p^8 if (Math.Pow(i, 8) <= n) { c += 1; } } } return c; } // Driver Code public static void Main() { int n = 1000; Console.WriteLine(countNumbers(n)); }}/*This code is contributed by PrinciRaj1992*/", "e": 38550, "s": 36948, "text": null }, { "code": "<?php// PHP implementation of above approach// Function to count numbers having// exactly 9 divisors function countNumbers($n){ $c = 0; $limit = sqrt($n); // Sieve array $prime[$limit + 1] = array(0); // initially prime[i] = i for ($i = 1; $i <= $limit; $i++) $prime[$i] = $i; // use sieve concept to store the // first prime factor of every number for ($i = 2; $i * $i <= $limit; $i++) { if ($prime[$i] == $i) { // mark all factors of i for ($j = $i * $i; $j <= $limit; $j += $i) if ($prime[$j] == $j) $prime[$j] = $i; } } // check for all numbers if they // can be expressed in form p*q for ($i = 2; $i <= $limit; $i++) { // p prime factor $p = $prime[$i]; // q prime factor $q = $prime[$i / $prime[$i]]; // if both prime factors are different // if p*q<=n and q!= if ($p * $q == $i && $q != 1 && $p != $q) { $c += 1; } else if ($prime[$i] == $i) { // Check if it can be expressed as p^8 if (pow($i, 8) <= $n) { $c += 1; } } } return $c;} // Driver Code$n = 1000;echo countNumbers($n); // This code is contributed by jit_t?>", "e": 39891, "s": 38550, "text": null }, { "code": "<script> // Javascript implementation of above approach // Function to count numbers having // exactly 9 divisors function countNumbers(n) { let c = 0; let limit = parseInt(Math.sqrt(n), 10); // Sieve array let prime = new Array(limit + 1); prime.fill(0); // initially prime[i] = i for (let i = 1; i <= limit; i++) { prime[i] = i; } // use sieve concept to store the // first prime factor of every number for (let i = 2; i * i <= limit; i++) { if (prime[i] == i) { // mark all factors of i for (let j = i * i; j <= limit; j += i) { if (prime[j] == j) { prime[j] = i; } } } } // check for all numbers if they can be // expressed in form p*q for (let i = 2; i <= limit; i++) { // p prime factor let p = prime[i]; // q prime factor let q = prime[parseInt(i / prime[i], 10)]; // if both prime factors are different // if p*q<=n and q!= if (p * q == i && q != 1 && p != q) { c += 1; } else if (prime[i] == i) { // Check if it can be expressed as p^8 if (Math.pow(i, 8) <= n) { c += 1; } } } return c; } let n = 1000; document.write(countNumbers(n)); </script>", "e": 41450, "s": 39891, "text": null }, { "code": null, "e": 41452, "s": 41450, "text": "8" }, { "code": null, "e": 41511, "s": 41454, "text": "Time Complexity: O(sqrt(N)) Auxiliary Space: O(sqrt(N)) " }, { "code": null, "e": 41522, "s": 41511, "text": "inderDuMCA" }, { "code": null, "e": 41537, "s": 41522, "text": "Shivi_Aggarwal" }, { "code": null, "e": 41543, "s": 41537, "text": "ukasp" }, { "code": null, "e": 41556, "s": 41543, "text": "Akanksha_Rai" }, { "code": null, "e": 41562, "s": 41556, "text": "jit_t" }, { "code": null, "e": 41576, "s": 41562, "text": "princiraj1992" }, { "code": null, "e": 41589, "s": 41576, "text": "rituraj_jain" }, { "code": null, "e": 41603, "s": 41589, "text": "shubham_singh" }, { "code": null, "e": 41617, "s": 41603, "text": "divyesh072019" }, { "code": null, "e": 41635, "s": 41617, "text": "divyeshrabadiya07" }, { "code": null, "e": 41643, "s": 41635, "text": "Directi" }, { "code": null, "e": 41652, "s": 41643, "text": "divisors" }, { "code": null, "e": 41665, "s": 41652, "text": "Prime Number" }, { "code": null, "e": 41678, "s": 41665, "text": "prime-factor" }, { "code": null, "e": 41684, "s": 41678, "text": "sieve" }, { "code": null, "e": 41708, "s": 41684, "text": "Technical Scripter 2018" }, { "code": null, "e": 41732, "s": 41708, "text": "Competitive Programming" }, { "code": null, "e": 41745, "s": 41732, "text": "Mathematical" }, { "code": null, "e": 41753, "s": 41745, "text": "Directi" }, { "code": null, "e": 41766, "s": 41753, "text": "Mathematical" }, { "code": null, "e": 41779, "s": 41766, "text": "Prime Number" }, { "code": null, "e": 41785, "s": 41779, "text": "sieve" }, { "code": null, "e": 41883, "s": 41785, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41961, "s": 41883, "text": "Prefix Sum Array - Implementation and Applications in Competitive Programming" }, { "code": null, "e": 41990, "s": 41961, "text": "Ordered Set and GNU C++ PBDS" }, { "code": null, "e": 42017, "s": 41990, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 42055, "s": 42017, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 42114, "s": 42055, "text": "What is Competitive Programming and How to Prepare for It?" }, { "code": null, "e": 42144, "s": 42114, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 42204, "s": 42144, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 42219, "s": 42204, "text": "C++ Data Types" }, { "code": null, "e": 42262, "s": 42219, "text": "Set in C++ Standard Template Library (STL)" } ]
Perl | Grouping and Alternation in Regex - GeeksforGeeks
03 Feb, 2022 Regex or Regular Expressions are an important part of Perl Programming. It is used for searching the specified text pattern. In this, set of characters together form the search pattern. It is also known as regexp. Working with regex might become complex with more and more addition in functionalities. To reduce the complexity, Perl provides us with more operations such as Alternation and Grouping. The name itself suggests the mechanism it does, first and foremost its like a (&&) operator which appears in ‘C’ programming language. The ‘&&’ operator in C works as until it finds that all the conditional statements are true it won’t return 1 and returns 0 as soon as it finds a false statement. The alternation in Perl works in both ways simultaneously. Alternation can be done using either the metacharacters ‘|’ or ‘[]’. Following examples will make things clear:Example 1: perl #!/usr/bin/perl # Initializing the string and checking it# against few search patternsmy $str = "geeksforgeeks rocks..."; # prints 1 due to no match (=0)print "1\n" if (($str =~ /gek|for/) == 0); # for word searchif($str =~ /geek|for/){ print "I found $&.\n";}else{ print "no match"} 1 I found geek. So, in the above example, it first checks for ‘geek’ and finds a match in the first alternate pattern returns 1 as soon as it finds a match. But it also checks for ‘for’ too and if it is not present in the string it won’t be bothered as it already returned the match status. If ‘for’ is a match, it checks whether ‘for’ is appearing in the least position of the string as ‘g’ in ‘geeks’ appears at position 0 and ‘f’ in ‘for’ appears at position 5, ‘geek’ gets stored in the last match pattern. Check out the following example: $& - Contains the string matched by the last pattern match. Example 2: perl #!/usr/bin/perl # Initializing the string and checking it# against few search patternsmy $str = "geeksforgeeks rocks...";print "1\n" if ($str =~ /for|eeks|rock|ge/); # | for word searchif($str =~ /for|eeks|rock|ge/){ print "I found $&.\n";} # for single character searchif ($str =~ /[gfrkc]/){ print "$&"} 1 I found ge. g Grouping is used to search for a pattern bounded with similar words or patterns, in the beginning, end or in the middle and it also returns the least positioned pattern. Grouping is done using metacharacter ‘()’. Following is an example which will make things clear: Example 1: perl #!/usr/bin/perl# Initializing the string and checking it# against few search patternsmy $str = "Blackbackground Brownbackground";print "1\n" if ($str =~ /(Bron|Back)[a-z]+/);if ($str =~ /(Brown|Black)[a-z]+/){ print "I found $&.\n";} else{ print "no match"} I found Blackbackground. For better understanding check out the following example: perl #!/usr/bin/perluse warnings;use strict; # Initializing the string and checking it# against few searching patterns # array of stringsmy @mail = ('Ab-@gmail.com', 'd.f@yahoo.com', '0b_f@bing.com', 'jet@hotmail.con', 's/s@otmail.com'); for(@mail){ # search pattern to check valid mail # service providers followed with '.com' print "Valid : $_\n" if($_ =~ /[a-zA-Z0-9-._]+@(gmail|yahoo|bing|hotmail)(.com)$/)} Valid : Ab-@gmail.com Valid : d.f@yahoo.com Valid : 0b_f@bing.com sumitgumber28 Perl-regex Picked Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Perl Tutorial - Learn Perl With Examples Perl | Basic Syntax of a Perl Program Perl | Inheritance in OOPs Perl | Opening and Reading a File Perl | Multidimensional Hashes Perl | Scope of Variables Perl | ne operator Perl | Hashes Perl | Data Types Perl | defined() Function
[ { "code": null, "e": 25315, "s": 25287, "text": "\n03 Feb, 2022" }, { "code": null, "e": 25716, "s": 25315, "text": "Regex or Regular Expressions are an important part of Perl Programming. It is used for searching the specified text pattern. In this, set of characters together form the search pattern. It is also known as regexp. Working with regex might become complex with more and more addition in functionalities. To reduce the complexity, Perl provides us with more operations such as Alternation and Grouping. " }, { "code": null, "e": 26197, "s": 25716, "text": "The name itself suggests the mechanism it does, first and foremost its like a (&&) operator which appears in ‘C’ programming language. The ‘&&’ operator in C works as until it finds that all the conditional statements are true it won’t return 1 and returns 0 as soon as it finds a false statement. The alternation in Perl works in both ways simultaneously. Alternation can be done using either the metacharacters ‘|’ or ‘[]’. Following examples will make things clear:Example 1: " }, { "code": null, "e": 26202, "s": 26197, "text": "perl" }, { "code": "#!/usr/bin/perl # Initializing the string and checking it# against few search patternsmy $str = \"geeksforgeeks rocks...\"; # prints 1 due to no match (=0)print \"1\\n\" if (($str =~ /gek|for/) == 0); # for word searchif($str =~ /geek|for/){ print \"I found $&.\\n\";}else{ print \"no match\"}", "e": 26492, "s": 26202, "text": null }, { "code": null, "e": 26508, "s": 26492, "text": "1\nI found geek." }, { "code": null, "e": 27039, "s": 26510, "text": "So, in the above example, it first checks for ‘geek’ and finds a match in the first alternate pattern returns 1 as soon as it finds a match. But it also checks for ‘for’ too and if it is not present in the string it won’t be bothered as it already returned the match status. If ‘for’ is a match, it checks whether ‘for’ is appearing in the least position of the string as ‘g’ in ‘geeks’ appears at position 0 and ‘f’ in ‘for’ appears at position 5, ‘geek’ gets stored in the last match pattern. Check out the following example: " }, { "code": null, "e": 27100, "s": 27039, "text": " $& - Contains the string matched by the last pattern match." }, { "code": null, "e": 27113, "s": 27100, "text": "Example 2: " }, { "code": null, "e": 27118, "s": 27113, "text": "perl" }, { "code": "#!/usr/bin/perl # Initializing the string and checking it# against few search patternsmy $str = \"geeksforgeeks rocks...\";print \"1\\n\" if ($str =~ /for|eeks|rock|ge/); # | for word searchif($str =~ /for|eeks|rock|ge/){ print \"I found $&.\\n\";} # for single character searchif ($str =~ /[gfrkc]/){ print \"$&\"}", "e": 27430, "s": 27118, "text": null }, { "code": null, "e": 27446, "s": 27430, "text": "1\nI found ge.\ng" }, { "code": null, "e": 27727, "s": 27448, "text": "Grouping is used to search for a pattern bounded with similar words or patterns, in the beginning, end or in the middle and it also returns the least positioned pattern. Grouping is done using metacharacter ‘()’. Following is an example which will make things clear: Example 1: " }, { "code": null, "e": 27732, "s": 27727, "text": "perl" }, { "code": "#!/usr/bin/perl# Initializing the string and checking it# against few search patternsmy $str = \"Blackbackground Brownbackground\";print \"1\\n\" if ($str =~ /(Bron|Back)[a-z]+/);if ($str =~ /(Brown|Black)[a-z]+/){ print \"I found $&.\\n\";} else{ print \"no match\"}", "e": 27996, "s": 27732, "text": null }, { "code": null, "e": 28021, "s": 27996, "text": "I found Blackbackground." }, { "code": null, "e": 28083, "s": 28023, "text": "For better understanding check out the following example: " }, { "code": null, "e": 28088, "s": 28083, "text": "perl" }, { "code": "#!/usr/bin/perluse warnings;use strict; # Initializing the string and checking it# against few searching patterns # array of stringsmy @mail = ('Ab-@gmail.com', 'd.f@yahoo.com', '0b_f@bing.com', 'jet@hotmail.con', 's/s@otmail.com'); for(@mail){ # search pattern to check valid mail # service providers followed with '.com' print \"Valid : $_\\n\" if($_ =~ /[a-zA-Z0-9-._]+@(gmail|yahoo|bing|hotmail)(.com)$/)}", "e": 28551, "s": 28088, "text": null }, { "code": null, "e": 28617, "s": 28551, "text": "Valid : Ab-@gmail.com\nValid : d.f@yahoo.com\nValid : 0b_f@bing.com" }, { "code": null, "e": 28633, "s": 28619, "text": "sumitgumber28" }, { "code": null, "e": 28644, "s": 28633, "text": "Perl-regex" }, { "code": null, "e": 28651, "s": 28644, "text": "Picked" }, { "code": null, "e": 28656, "s": 28651, "text": "Perl" }, { "code": null, "e": 28661, "s": 28656, "text": "Perl" }, { "code": null, "e": 28759, "s": 28661, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28800, "s": 28759, "text": "Perl Tutorial - Learn Perl With Examples" }, { "code": null, "e": 28838, "s": 28800, "text": "Perl | Basic Syntax of a Perl Program" }, { "code": null, "e": 28865, "s": 28838, "text": "Perl | Inheritance in OOPs" }, { "code": null, "e": 28899, "s": 28865, "text": "Perl | Opening and Reading a File" }, { "code": null, "e": 28930, "s": 28899, "text": "Perl | Multidimensional Hashes" }, { "code": null, "e": 28956, "s": 28930, "text": "Perl | Scope of Variables" }, { "code": null, "e": 28975, "s": 28956, "text": "Perl | ne operator" }, { "code": null, "e": 28989, "s": 28975, "text": "Perl | Hashes" }, { "code": null, "e": 29007, "s": 28989, "text": "Perl | Data Types" } ]
Python - Maximum column values in mixed length 2D List - GeeksforGeeks
29 Dec, 2019 The usual list of list, unlike conventional C type Matrix, can allow the nested list of lists with variable lengths, and when we require the maximizations of its columns, the uneven length of rows may lead to some elements in that elements to be absent and if not handled correctly, may throw exception. Let’s discuss certain ways in which this problem can be performed in error free manner. Method #1 : Using max() + filter() + map() + list comprehensionThe combination of above three function combined with list comprehension can help us perform this particular task, the max function helps to perform the maximization, filter allows us to check for the present elements and all rows are combined using the map function. Works only with python 2. # Python code to demonstrate # Maximum column values mixed length 2D List# using max() + filter() + map() + list comprehension # initializing list of liststest_list = [[1, 5, 3], [4], [9, 8]] # printing original list print ("The original list is : " + str(test_list)) # using max() + filter() + map() + list comprehension# Maximum column values mixed length 2D Listres = [max(filter(None, j)) for j in map(None, *test_list)] # printing resultprint ("The maximization of columns is : " + str(res)) The original list is : [[1, 5, 3], [4], [9, 8]] The maximization of columns is : [9, 8, 3] Method #2 : Using list comprehension + max() + zip_longest()If one desires not to play with the None values, one can opt for this method to resolve this particular problem. The zip_longest function helps to fill the not present column with 0 so that it does not has to handle the void of elements not present. # Python3 code to demonstrate # Maximum column values mixed length 2D List# using list comprehension + max() + zip_longest()import itertools # initializing list of liststest_list = [[1, 5, 3], [4], [9, 8]] # printing original list print ("The original list is : " + str(test_list)) # using list comprehension + max() + zip_longest()# Maximum column values mixed length 2D Listres = [max(i) for i in itertools.zip_longest(*test_list, fillvalue = 0)] # printing resultprint ("The maximization of columns is : " + str(res)) The original list is : [[1, 5, 3], [4], [9, 8]] The maximization of columns is : [9, 8, 3] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25537, "s": 25509, "text": "\n29 Dec, 2019" }, { "code": null, "e": 25929, "s": 25537, "text": "The usual list of list, unlike conventional C type Matrix, can allow the nested list of lists with variable lengths, and when we require the maximizations of its columns, the uneven length of rows may lead to some elements in that elements to be absent and if not handled correctly, may throw exception. Let’s discuss certain ways in which this problem can be performed in error free manner." }, { "code": null, "e": 26286, "s": 25929, "text": "Method #1 : Using max() + filter() + map() + list comprehensionThe combination of above three function combined with list comprehension can help us perform this particular task, the max function helps to perform the maximization, filter allows us to check for the present elements and all rows are combined using the map function. Works only with python 2." }, { "code": "# Python code to demonstrate # Maximum column values mixed length 2D List# using max() + filter() + map() + list comprehension # initializing list of liststest_list = [[1, 5, 3], [4], [9, 8]] # printing original list print (\"The original list is : \" + str(test_list)) # using max() + filter() + map() + list comprehension# Maximum column values mixed length 2D Listres = [max(filter(None, j)) for j in map(None, *test_list)] # printing resultprint (\"The maximization of columns is : \" + str(res))", "e": 26787, "s": 26286, "text": null }, { "code": null, "e": 26879, "s": 26787, "text": "The original list is : [[1, 5, 3], [4], [9, 8]]\nThe maximization of columns is : [9, 8, 3]\n" }, { "code": null, "e": 27191, "s": 26881, "text": "Method #2 : Using list comprehension + max() + zip_longest()If one desires not to play with the None values, one can opt for this method to resolve this particular problem. The zip_longest function helps to fill the not present column with 0 so that it does not has to handle the void of elements not present." }, { "code": "# Python3 code to demonstrate # Maximum column values mixed length 2D List# using list comprehension + max() + zip_longest()import itertools # initializing list of liststest_list = [[1, 5, 3], [4], [9, 8]] # printing original list print (\"The original list is : \" + str(test_list)) # using list comprehension + max() + zip_longest()# Maximum column values mixed length 2D Listres = [max(i) for i in itertools.zip_longest(*test_list, fillvalue = 0)] # printing resultprint (\"The maximization of columns is : \" + str(res))", "e": 27716, "s": 27191, "text": null }, { "code": null, "e": 27808, "s": 27716, "text": "The original list is : [[1, 5, 3], [4], [9, 8]]\nThe maximization of columns is : [9, 8, 3]\n" }, { "code": null, "e": 27829, "s": 27808, "text": "Python list-programs" }, { "code": null, "e": 27836, "s": 27829, "text": "Python" }, { "code": null, "e": 27852, "s": 27836, "text": "Python Programs" }, { "code": null, "e": 27950, "s": 27852, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27982, "s": 27950, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28024, "s": 27982, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28066, "s": 28024, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28093, "s": 28066, "text": "Python Classes and Objects" }, { "code": null, "e": 28149, "s": 28093, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28171, "s": 28149, "text": "Defaultdict in Python" }, { "code": null, "e": 28210, "s": 28171, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28256, "s": 28210, "text": "Python | Split string into list of characters" }, { "code": null, "e": 28294, "s": 28256, "text": "Python | Convert a list to dictionary" } ]
Python | Pandas Index.insert() - GeeksforGeeks
17 Dec, 2018 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Index.insert() function make new Index inserting new item at location. This function also follows Python list.append() semantics for negative values. If the negative value are passed then it start from the other end. Syntax: Index.insert(loc, item) Parameters :loc : intitem : object Returns : new_index : Index Example #1: Use Index.insert() function to insert a new value in the Index. # importing pandas as pdimport pandas as pd # Creating the Indexidx = pd.Index(['Labrador', 'Beagle', 'Labrador', 'Lhasa', 'Husky', 'Beagle']) # Print the Indexidx Output :Now insert ‘Great_Dane’ at the 1st index. # Inserting a value at the first position in the index.idx.insert(1, 'Great_Dane') Output : As we can see in the output, the Index.insert() function has inserted the passed value at the desired location. Example #2: Use Index.insert() function to insert a value into the Index at the second position from the last in the Index. # importing pandas as pdimport pandas as pd # Creating the Indexidx = pd.Index(['Labrador', 'Beagle', 'Labrador', 'Lhasa', 'Husky', 'Beagle']) # Print the Indexidx Output : Now insert ‘Great_Dane’ at the 1st index from the last. # Inserting a value at the first position in the index.idx.insert(-1, 'Great_Dane') Output :As we can see in the output, the passed value has been inserted into the Index at the desired location. Python pandas-indexing Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Convert integer to string in Python Check if element exists in list in Python How To Convert Python Dictionary To JSON?
[ { "code": null, "e": 26177, "s": 26149, "text": "\n17 Dec, 2018" }, { "code": null, "e": 26391, "s": 26177, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 26615, "s": 26391, "text": "Pandas Index.insert() function make new Index inserting new item at location. This function also follows Python list.append() semantics for negative values. If the negative value are passed then it start from the other end." }, { "code": null, "e": 26647, "s": 26615, "text": "Syntax: Index.insert(loc, item)" }, { "code": null, "e": 26682, "s": 26647, "text": "Parameters :loc : intitem : object" }, { "code": null, "e": 26710, "s": 26682, "text": "Returns : new_index : Index" }, { "code": null, "e": 26786, "s": 26710, "text": "Example #1: Use Index.insert() function to insert a new value in the Index." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Indexidx = pd.Index(['Labrador', 'Beagle', 'Labrador', 'Lhasa', 'Husky', 'Beagle']) # Print the Indexidx", "e": 26972, "s": 26786, "text": null }, { "code": null, "e": 27022, "s": 26972, "text": "Output :Now insert ‘Great_Dane’ at the 1st index." }, { "code": "# Inserting a value at the first position in the index.idx.insert(1, 'Great_Dane')", "e": 27105, "s": 27022, "text": null }, { "code": null, "e": 27114, "s": 27105, "text": "Output :" }, { "code": null, "e": 27350, "s": 27114, "text": "As we can see in the output, the Index.insert() function has inserted the passed value at the desired location. Example #2: Use Index.insert() function to insert a value into the Index at the second position from the last in the Index." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Indexidx = pd.Index(['Labrador', 'Beagle', 'Labrador', 'Lhasa', 'Husky', 'Beagle']) # Print the Indexidx", "e": 27536, "s": 27350, "text": null }, { "code": null, "e": 27545, "s": 27536, "text": "Output :" }, { "code": null, "e": 27601, "s": 27545, "text": "Now insert ‘Great_Dane’ at the 1st index from the last." }, { "code": "# Inserting a value at the first position in the index.idx.insert(-1, 'Great_Dane')", "e": 27685, "s": 27601, "text": null }, { "code": null, "e": 27797, "s": 27685, "text": "Output :As we can see in the output, the passed value has been inserted into the Index at the desired location." }, { "code": null, "e": 27820, "s": 27797, "text": "Python pandas-indexing" }, { "code": null, "e": 27834, "s": 27820, "text": "Python-pandas" }, { "code": null, "e": 27841, "s": 27834, "text": "Python" }, { "code": null, "e": 27939, "s": 27841, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27957, "s": 27939, "text": "Python Dictionary" }, { "code": null, "e": 27989, "s": 27957, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28011, "s": 27989, "text": "Enumerate() in Python" }, { "code": null, "e": 28053, "s": 28011, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28082, "s": 28053, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28126, "s": 28082, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 28163, "s": 28126, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28199, "s": 28163, "text": "Convert integer to string in Python" }, { "code": null, "e": 28241, "s": 28199, "text": "Check if element exists in list in Python" } ]
ClipRect Widget in Flutter - GeeksforGeeks
02 Sep, 2020 The ClipRect widget is used to clips its child using a rectangle. It associates with the Clippers family. The main use of clippers is to clip out any portion of the widget as required. It behaves similar to that of ClipRRect and is used to Clip a Rectangle portion of the child widget but without the rounded corners Syntax: ClipRect( {Key key, CustomClipper<Rect> clipper, Clip clipBehavior: Clip.hardEdge, Widget child}) children: The widgets below this widget in the tree. hashCode: The hash code for this object. key: Controls how one widget replaces another widget in the tree. runtimeType: A representation of the runtime type of the object. clipBehaviour: Controls how to clip clipper: If non-null, determines which clip to use. Example: Here we will clip the below image in our app: Dart import 'package:flutter/material.dart'; void main() { runApp(MyApp());} class MyApp extends StatelessWidget { // This widget is //the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'ClipOval', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePAGE(), debugShowCheckedModeBanner: false, ); }} class MyHomePAGE extends StatefulWidget { @override _MyHomePAGEState createState() => _MyHomePAGEState();} class _MyHomePAGEState extends State<MyHomePAGE> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.green, ), body: Center( child: ClipRect( child: Align( alignment: Alignment.topCenter, heightFactor: 0.5, child: Image.network('https://picsum.photos/250?image=9'), ), ) ), backgroundColor: Colors.lightBlue[50], ); }} class MyClip extends CustomClipper<Rect> { Rect getClip(Size size) { return Rect.fromLTWH(0, 0, 100, 100); } bool shouldReclip(oldClipper) { return false; }} Output: First initialize the main app as a stateless widget.Second design the main widget as you desire.Build the Appbar with the scaffold widget.Now use the ClipRect widget inside the body of the scaffold widget and place it in the middle using the center widget. First initialize the main app as a stateless widget. Second design the main widget as you desire. Build the Appbar with the scaffold widget. Now use the ClipRect widget inside the body of the scaffold widget and place it in the middle using the center widget. android Flutter Flutter-widgets Dart Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - Custom Bottom Navigation Bar ListView Class in Flutter Flutter - Flexible Widget Container class in Flutter Flutter - Stack Widget Operators in Dart Flutter - Dialogs Android Studio Setup for Flutter Development Flutter - Positioned Widget Format Dates in Flutter
[ { "code": null, "e": 25285, "s": 25257, "text": "\n02 Sep, 2020" }, { "code": null, "e": 25602, "s": 25285, "text": "The ClipRect widget is used to clips its child using a rectangle. It associates with the Clippers family. The main use of clippers is to clip out any portion of the widget as required. It behaves similar to that of ClipRRect and is used to Clip a Rectangle portion of the child widget but without the rounded corners" }, { "code": null, "e": 25713, "s": 25602, "text": "Syntax:\nClipRect(\n{Key key, \nCustomClipper<Rect> clipper, \nClip clipBehavior: Clip.hardEdge, \nWidget child}) \n" }, { "code": null, "e": 25766, "s": 25713, "text": "children: The widgets below this widget in the tree." }, { "code": null, "e": 25807, "s": 25766, "text": "hashCode: The hash code for this object." }, { "code": null, "e": 25873, "s": 25807, "text": "key: Controls how one widget replaces another widget in the tree." }, { "code": null, "e": 25938, "s": 25873, "text": "runtimeType: A representation of the runtime type of the object." }, { "code": null, "e": 25974, "s": 25938, "text": "clipBehaviour: Controls how to clip" }, { "code": null, "e": 26026, "s": 25974, "text": "clipper: If non-null, determines which clip to use." }, { "code": null, "e": 26035, "s": 26026, "text": "Example:" }, { "code": null, "e": 26081, "s": 26035, "text": "Here we will clip the below image in our app:" }, { "code": null, "e": 26086, "s": 26081, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; void main() { runApp(MyApp());} class MyApp extends StatelessWidget { // This widget is //the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'ClipOval', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePAGE(), debugShowCheckedModeBanner: false, ); }} class MyHomePAGE extends StatefulWidget { @override _MyHomePAGEState createState() => _MyHomePAGEState();} class _MyHomePAGEState extends State<MyHomePAGE> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.green, ), body: Center( child: ClipRect( child: Align( alignment: Alignment.topCenter, heightFactor: 0.5, child: Image.network('https://picsum.photos/250?image=9'), ), ) ), backgroundColor: Colors.lightBlue[50], ); }} class MyClip extends CustomClipper<Rect> { Rect getClip(Size size) { return Rect.fromLTWH(0, 0, 100, 100); } bool shouldReclip(oldClipper) { return false; }}", "e": 27300, "s": 26086, "text": null }, { "code": null, "e": 27308, "s": 27300, "text": "Output:" }, { "code": null, "e": 27565, "s": 27308, "text": "First initialize the main app as a stateless widget.Second design the main widget as you desire.Build the Appbar with the scaffold widget.Now use the ClipRect widget inside the body of the scaffold widget and place it in the middle using the center widget." }, { "code": null, "e": 27618, "s": 27565, "text": "First initialize the main app as a stateless widget." }, { "code": null, "e": 27663, "s": 27618, "text": "Second design the main widget as you desire." }, { "code": null, "e": 27706, "s": 27663, "text": "Build the Appbar with the scaffold widget." }, { "code": null, "e": 27825, "s": 27706, "text": "Now use the ClipRect widget inside the body of the scaffold widget and place it in the middle using the center widget." }, { "code": null, "e": 27833, "s": 27825, "text": "android" }, { "code": null, "e": 27841, "s": 27833, "text": "Flutter" }, { "code": null, "e": 27857, "s": 27841, "text": "Flutter-widgets" }, { "code": null, "e": 27862, "s": 27857, "text": "Dart" }, { "code": null, "e": 27960, "s": 27862, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27999, "s": 27960, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 28025, "s": 27999, "text": "ListView Class in Flutter" }, { "code": null, "e": 28051, "s": 28025, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 28078, "s": 28051, "text": "Container class in Flutter" }, { "code": null, "e": 28101, "s": 28078, "text": "Flutter - Stack Widget" }, { "code": null, "e": 28119, "s": 28101, "text": "Operators in Dart" }, { "code": null, "e": 28137, "s": 28119, "text": "Flutter - Dialogs" }, { "code": null, "e": 28182, "s": 28137, "text": "Android Studio Setup for Flutter Development" }, { "code": null, "e": 28210, "s": 28182, "text": "Flutter - Positioned Widget" } ]
Login Application and Validating info using Kivy GUI and Pandas in Python - GeeksforGeeks
17 Aug, 2020 Prerequisites : Kivy, Pandas Kivy is a multiplatform GUI library, known for being responsive. It provides management of multiple screens in a single application. In this application we will be using multiple screens to log in user’s info and validate it. We will save the information in a csv file and use pandas to validate the information inside of the csv file by reading it into a DataFrame. To build the GUI we will use .kv file. Approach : There will be three screens, one for letting the user log in, second for signing up and third for telling if the login was successful.The info will be stored in a csv file.Pandas Library will be used to read the csv file into a DataFrame and further check if the user info already exists or not.If the information entered is invalid, popups will inform the user.Finally, the user will be informed if the login was successful or not. There will be three screens, one for letting the user log in, second for signing up and third for telling if the login was successful. The info will be stored in a csv file. Pandas Library will be used to read the csv file into a DataFrame and further check if the user info already exists or not. If the information entered is invalid, popups will inform the user. Finally, the user will be informed if the login was successful or not. Main program : # import all the relevant classesfrom kivy.app import Appfrom kivy.uix.widget import Widgetfrom kivy.uix.screenmanager import ScreenManager, Screenfrom kivy.properties import ObjectPropertyfrom kivy.lang import Builderfrom kivy.uix.popup import Popupfrom kivy.uix.floatlayout import FloatLayoutimport pandas as pd # class to call the popup functionclass PopupWindow(Widget): def btn(self): popFun() # class to build GUI for a popup windowclass P(FloatLayout): pass # function that displays the contentdef popFun(): show = P() window = Popup(title = "popup", content = show, size_hint = (None, None), size = (300, 300)) window.open() # class to accept user info and validate itclass loginWindow(Screen): email = ObjectProperty(None) pwd = ObjectProperty(None) def validate(self): # validating if the email already exists if self.email.text not in users['Email'].unique(): popFun() else: # switching the current screen to display validation result sm.current = 'logdata' # reset TextInput widget self.email.text = "" self.pwd.text = "" # class to accept sign up info class signupWindow(Screen): name2 = ObjectProperty(None) email = ObjectProperty(None) pwd = ObjectProperty(None) def signupbtn(self): # creating a DataFrame of the info user = pd.DataFrame([[self.name2.text, self.email.text, self.pwd.text]], columns = ['Name', 'Email', 'Password']) if self.email.text != "": if self.email.text not in users['Email'].unique(): # if email does not exist already then append to the csv file # change current screen to log in the user now user.to_csv('login.csv', mode = 'a', header = False, index = False) sm.current = 'login' self.name2.text = "" self.email.text = "" self.pwd.text = "" else: # if values are empty or invalid show pop up popFun() # class to display validation resultclass logDataWindow(Screen): pass # class for managing screensclass windowManager(ScreenManager): pass # kv filekv = Builder.load_file('login.kv')sm = windowManager() # reading all the data storedusers=pd.read_csv('login.csv') # adding screenssm.add_widget(loginWindow(name='login'))sm.add_widget(signupWindow(name='signup'))sm.add_widget(logDataWindow(name='logdata')) # class that builds guiclass loginMain(App): def build(self): return sm # driver functionif __name__=="__main__": loginMain().run() .kv file : .kv file contains all the code to design and place the GUI and to define the direction of the transitions of the screens. # there are three screenswindowManager: loginWindow: signupWindow: logDataWindow: # GUI for the login window<loginWindow>: email : email pwd : pwd FloatLayout: size: root.width, root.height Label: text : "EMAIL: " size_hint : 0.2, 0.1 pos_hint : {"x":0.25, "top":0.9} TextInput: id : email multiline :False size_hint : 0.3, 0.1 pos_hint : {"x" : 0.45, "top" : 0.9} Label: text : "PASSWORD: " size_hint : 0.2, 0.1 pos_hint : {"x" : 0.25, "top" : 0.7} TextInput: id : pwd multiline :False size_hint : 0.3, 0.1 pos_hint : {"x" : 0.45, "top" : 0.7} Button: text : "Create an account" size_hint : 0.4, 0.1 pos_hint : {"x" : 0.33, "top" : 0.4} on_release: app.root.current = 'signup' root.manager.transition.direction = "left" Button: text : "LOGIN" size_hint : 0.3, 0.1 pos_hint : {"x" : 0.39, "top" : 0.2} on_release: root.validate() root.manager.transition.direction = "up" # GUI for the signup window<signupWindow>: name2 : name2 email : email pwd : pwd FloatLayout: Label: text : "NAME: " size_hint : 0.2, 0.1 pos_hint : {"x":0.25, "top":0.9} TextInput: id : name2 multiline : False size_hint : 0.3, 0.1 pos_hint : {"x" : 0.45, "top" : 0.9} Label: text : "EMAIL: " size_hint : 0.2, 0.1 pos_hint : {"x" : 0.25, "top" : 0.7} TextInput: id : email multiline : False size_hint : 0.3, 0.1 pos_hint : {"x" : 0.45, "top" : 0.7} Label: text : "PASSWORD: " size_hint : 0.2, 0.1 pos_hint : {"x" : 0.25, "top" : 0.5} TextInput: id : pwd multiline : False size_hint : 0.3, 0.1 pos_hint : {"x" : 0.45, "top" : 0.5} Button: text : "SUBMIT" size_hint : 0.3, 0.1 pos_hint : {"x" : 0.39, "top" : 0.28} on_press : root.signupbtn() root.manager.transition.direction = "right" # GUI to show validation result<logDataWindow>: info : info FloatLayout: Label: id : info size_hint : 0.8, 0.2 pos_hint : {"x" : 0.15, "top" : 0.8} text : "SUCCESSFULLY LOGGED IN" Button: text : "Login" size_hint : 0.4, 0.1 pos_hint : {"x" : 0.33, "top" : 0.55} on_release: app.root.current = 'login' root.manager.transition.direction = "down" Button: text : "Create new account" size_hint : 0.4, 0.1 pos_hint : {"x" : 0.33, "top" : 0.4} on_release: app.root.current = 'signup' root.manager.transition.direction = "down" # GUI for pop up window<P>: Label: text : "Please enter valid information" size_hint : 0.2, 0.1 pos_hint : {"x" : 0.3, "top" : 0.8} Output: Signup Window : Login Window : Popup Window: Validation : Python-gui Python-kivy Python-pandas Python-projects Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25689, "s": 25661, "text": "\n17 Aug, 2020" }, { "code": null, "e": 25718, "s": 25689, "text": "Prerequisites : Kivy, Pandas" }, { "code": null, "e": 25852, "s": 25718, "text": "Kivy is a multiplatform GUI library, known for being responsive. It provides management of multiple screens in a single application. " }, { "code": null, "e": 26127, "s": 25852, "text": "In this application we will be using multiple screens to log in user’s info and validate it. We will save the information in a csv file and use pandas to validate the information inside of the csv file by reading it into a DataFrame. To build the GUI we will use .kv file. " }, { "code": null, "e": 26138, "s": 26127, "text": "Approach :" }, { "code": null, "e": 26572, "s": 26138, "text": "There will be three screens, one for letting the user log in, second for signing up and third for telling if the login was successful.The info will be stored in a csv file.Pandas Library will be used to read the csv file into a DataFrame and further check if the user info already exists or not.If the information entered is invalid, popups will inform the user.Finally, the user will be informed if the login was successful or not. " }, { "code": null, "e": 26707, "s": 26572, "text": "There will be three screens, one for letting the user log in, second for signing up and third for telling if the login was successful." }, { "code": null, "e": 26746, "s": 26707, "text": "The info will be stored in a csv file." }, { "code": null, "e": 26870, "s": 26746, "text": "Pandas Library will be used to read the csv file into a DataFrame and further check if the user info already exists or not." }, { "code": null, "e": 26938, "s": 26870, "text": "If the information entered is invalid, popups will inform the user." }, { "code": null, "e": 27010, "s": 26938, "text": "Finally, the user will be informed if the login was successful or not. " }, { "code": null, "e": 27025, "s": 27010, "text": "Main program :" }, { "code": "# import all the relevant classesfrom kivy.app import Appfrom kivy.uix.widget import Widgetfrom kivy.uix.screenmanager import ScreenManager, Screenfrom kivy.properties import ObjectPropertyfrom kivy.lang import Builderfrom kivy.uix.popup import Popupfrom kivy.uix.floatlayout import FloatLayoutimport pandas as pd # class to call the popup functionclass PopupWindow(Widget): def btn(self): popFun() # class to build GUI for a popup windowclass P(FloatLayout): pass # function that displays the contentdef popFun(): show = P() window = Popup(title = \"popup\", content = show, size_hint = (None, None), size = (300, 300)) window.open() # class to accept user info and validate itclass loginWindow(Screen): email = ObjectProperty(None) pwd = ObjectProperty(None) def validate(self): # validating if the email already exists if self.email.text not in users['Email'].unique(): popFun() else: # switching the current screen to display validation result sm.current = 'logdata' # reset TextInput widget self.email.text = \"\" self.pwd.text = \"\" # class to accept sign up info class signupWindow(Screen): name2 = ObjectProperty(None) email = ObjectProperty(None) pwd = ObjectProperty(None) def signupbtn(self): # creating a DataFrame of the info user = pd.DataFrame([[self.name2.text, self.email.text, self.pwd.text]], columns = ['Name', 'Email', 'Password']) if self.email.text != \"\": if self.email.text not in users['Email'].unique(): # if email does not exist already then append to the csv file # change current screen to log in the user now user.to_csv('login.csv', mode = 'a', header = False, index = False) sm.current = 'login' self.name2.text = \"\" self.email.text = \"\" self.pwd.text = \"\" else: # if values are empty or invalid show pop up popFun() # class to display validation resultclass logDataWindow(Screen): pass # class for managing screensclass windowManager(ScreenManager): pass # kv filekv = Builder.load_file('login.kv')sm = windowManager() # reading all the data storedusers=pd.read_csv('login.csv') # adding screenssm.add_widget(loginWindow(name='login'))sm.add_widget(signupWindow(name='signup'))sm.add_widget(logDataWindow(name='logdata')) # class that builds guiclass loginMain(App): def build(self): return sm # driver functionif __name__==\"__main__\": loginMain().run()", "e": 29698, "s": 27025, "text": null }, { "code": null, "e": 29832, "s": 29698, "text": ".kv file : .kv file contains all the code to design and place the GUI and to define the direction of the transitions of the screens. " }, { "code": "# there are three screenswindowManager: loginWindow: signupWindow: logDataWindow: # GUI for the login window<loginWindow>: email : email pwd : pwd FloatLayout: size: root.width, root.height Label: text : \"EMAIL: \" size_hint : 0.2, 0.1 pos_hint : {\"x\":0.25, \"top\":0.9} TextInput: id : email multiline :False size_hint : 0.3, 0.1 pos_hint : {\"x\" : 0.45, \"top\" : 0.9} Label: text : \"PASSWORD: \" size_hint : 0.2, 0.1 pos_hint : {\"x\" : 0.25, \"top\" : 0.7} TextInput: id : pwd multiline :False size_hint : 0.3, 0.1 pos_hint : {\"x\" : 0.45, \"top\" : 0.7} Button: text : \"Create an account\" size_hint : 0.4, 0.1 pos_hint : {\"x\" : 0.33, \"top\" : 0.4} on_release: app.root.current = 'signup' root.manager.transition.direction = \"left\" Button: text : \"LOGIN\" size_hint : 0.3, 0.1 pos_hint : {\"x\" : 0.39, \"top\" : 0.2} on_release: root.validate() root.manager.transition.direction = \"up\" # GUI for the signup window<signupWindow>: name2 : name2 email : email pwd : pwd FloatLayout: Label: text : \"NAME: \" size_hint : 0.2, 0.1 pos_hint : {\"x\":0.25, \"top\":0.9} TextInput: id : name2 multiline : False size_hint : 0.3, 0.1 pos_hint : {\"x\" : 0.45, \"top\" : 0.9} Label: text : \"EMAIL: \" size_hint : 0.2, 0.1 pos_hint : {\"x\" : 0.25, \"top\" : 0.7} TextInput: id : email multiline : False size_hint : 0.3, 0.1 pos_hint : {\"x\" : 0.45, \"top\" : 0.7} Label: text : \"PASSWORD: \" size_hint : 0.2, 0.1 pos_hint : {\"x\" : 0.25, \"top\" : 0.5} TextInput: id : pwd multiline : False size_hint : 0.3, 0.1 pos_hint : {\"x\" : 0.45, \"top\" : 0.5} Button: text : \"SUBMIT\" size_hint : 0.3, 0.1 pos_hint : {\"x\" : 0.39, \"top\" : 0.28} on_press : root.signupbtn() root.manager.transition.direction = \"right\" # GUI to show validation result<logDataWindow>: info : info FloatLayout: Label: id : info size_hint : 0.8, 0.2 pos_hint : {\"x\" : 0.15, \"top\" : 0.8} text : \"SUCCESSFULLY LOGGED IN\" Button: text : \"Login\" size_hint : 0.4, 0.1 pos_hint : {\"x\" : 0.33, \"top\" : 0.55} on_release: app.root.current = 'login' root.manager.transition.direction = \"down\" Button: text : \"Create new account\" size_hint : 0.4, 0.1 pos_hint : {\"x\" : 0.33, \"top\" : 0.4} on_release: app.root.current = 'signup' root.manager.transition.direction = \"down\" # GUI for pop up window<P>: Label: text : \"Please enter valid information\" size_hint : 0.2, 0.1 pos_hint : {\"x\" : 0.3, \"top\" : 0.8}", "e": 33129, "s": 29832, "text": null }, { "code": null, "e": 33137, "s": 33129, "text": "Output:" }, { "code": null, "e": 33153, "s": 33137, "text": "Signup Window :" }, { "code": null, "e": 33168, "s": 33153, "text": "Login Window :" }, { "code": null, "e": 33182, "s": 33168, "text": "Popup Window:" }, { "code": null, "e": 33195, "s": 33182, "text": "Validation :" }, { "code": null, "e": 33206, "s": 33195, "text": "Python-gui" }, { "code": null, "e": 33218, "s": 33206, "text": "Python-kivy" }, { "code": null, "e": 33232, "s": 33218, "text": "Python-pandas" }, { "code": null, "e": 33248, "s": 33232, "text": "Python-projects" }, { "code": null, "e": 33255, "s": 33248, "text": "Python" }, { "code": null, "e": 33353, "s": 33255, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33371, "s": 33353, "text": "Python Dictionary" }, { "code": null, "e": 33406, "s": 33371, "text": "Read a file line by line in Python" }, { "code": null, "e": 33438, "s": 33406, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 33460, "s": 33438, "text": "Enumerate() in Python" }, { "code": null, "e": 33502, "s": 33460, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 33532, "s": 33502, "text": "Iterate over a list in Python" }, { "code": null, "e": 33558, "s": 33532, "text": "Python String | replace()" }, { "code": null, "e": 33587, "s": 33558, "text": "*args and **kwargs in Python" }, { "code": null, "e": 33631, "s": 33587, "text": "Reading and Writing to text files in Python" } ]
Find the smallest number whose digits multiply to a given number n - GeeksforGeeks
17 Jan, 2022 Given a number ‘n’, find the smallest number ‘p’ such that if we multiply all digits of ‘p’, we get ‘n’. The result ‘p’ should have minimum two digits.Examples: Input: n = 36 Output: p = 49 // Note that 4*9 = 36 and 49 is the smallest such number Input: n = 100 Output: p = 455 // Note that 4*5*5 = 100 and 455 is the smallest such number Input: n = 1 Output:p = 11 // Note that 1*1 = 1 Input: n = 13 Output: Not Possible For a given n, following are the two cases to be considered. Case 1: n < 10 When n is smaller than 10, the output is always n+10. For example for n = 7, the output is 17. For n = 9, output is 19.Case 2: n >= 10 Find all factors of n which are between 2 and 9 (both inclusive). The idea is to start searching from 9 so that the number of digits in the result is minimized. For example, 9 is preferred over 33 and 8 is preferred over 24. Store all found factors in an array. The array would contain digits in non-increasing order, so finally print the array in reverse order.Following is the implementation of above concept. C++ C Java Python3 C# PHP Javascript #include<bits/stdc++.h>using namespace std; // Maximum number of digits in output#define MAX 50 // prints the smallest number// whose digits multiply to nvoid findSmallest(int n){ int i, j = 0; // To store digits of result // in reverse order int res[MAX]; // Case 1: If number is smaller than 10 if (n < 10) { cout << n + 10; return; } // Case 2: Start with 9 and // try every possible digit for (i = 9; i > 1; i--) { // If current digit divides n, then store all // occurrences of current digit in res while (n % i == 0) { n = n / i; res[j] = i; j++; } } // If n could not be broken // in form of digits (prime factors // of n are greater than 9) if (n > 10) { cout << "Not possible"; return; } // Print the result array in reverse order for (i = j - 1; i >= 0; i--) cout << res[i];} // Driver Codeint main(){ findSmallest(7); cout << "\n"; findSmallest(36); cout << "\n"; findSmallest(13); cout << "\n"; findSmallest(100); return 0;} // This code is contributed by Code_Mech #include<stdio.h> // Maximum number of digits in output#define MAX 50 // prints the smallest number whose digits multiply to nvoid findSmallest(int n){ int i, j=0; int res[MAX]; // To store digits of result in reverse order // Case 1: If number is smaller than 10 if (n < 10) { printf("%d", n+10); return; } // Case 2: Start with 9 and try every possible digit for (i=9; i>1; i--) { // If current digit divides n, then store all // occurrences of current digit in res while (n%i == 0) { n = n/i; res[j] = i; j++; } } // If n could not be broken in form of digits (prime factors of n // are greater than 9) if (n > 10) { printf("Not possible"); return; } // Print the result array in reverse order for (i=j-1; i>=0; i--) printf("%d", res[i]);} // Driver program to test above functionint main(){ findSmallest(7); printf("\n"); findSmallest(36); printf("\n"); findSmallest(13); printf("\n"); findSmallest(100); return 0;} // Java program to find the smallest number whose// digits multiply to a given number n import java.io.*; class Smallest{ // Function to prints the smallest number whose // digits multiply to n static void findSmallest(int n) { int i, j=0; int MAX = 50; // To store digits of result in reverse order int[] res = new int[MAX]; // Case 1: If number is smaller than 10 if (n < 10) { System.out.println(n+10); return; } // Case 2: Start with 9 and try every possible digit for (i=9; i>1; i--) { // If current digit divides n, then store all // occurrences of current digit in res while (n%i == 0) { n = n/i; res[j] = i; j++; } } // If n could not be broken in form of digits (prime factors of n // are greater than 9) if (n > 10) { System.out.println("Not possible"); return; } // Print the result array in reverse order for (i=j-1; i>=0; i--) System.out.print(res[i]); System.out.println(); } // Driver program public static void main (String[] args) { findSmallest(7); findSmallest(36); findSmallest(13); findSmallest(100); }} // Contributed by Pramod Kumar # Python code to find the smallest number# whose digits multiply to give n # function to print the smallest number whose# digits multiply to ndef findSmallest(n): # Case 1 - If the number is smaller than 10 if n < 10: print (n+10) return # Case 2 - Start with 9 and try every possible digit res = [] # to sort digits for i in range(9,1,-1): # If current digit divides n, then store all # occurrences of current digit in res while n % i == 0: n = n / i res.append(i) # If n could not be broken in the form of digits # prime factors of n are greater than 9 if n > 10: print ("Not Possible") return # Print the number from result array in reverse order n = res[len(res)-1] for i in range(len(res)-2,-1,-1): n = 10 * n + res[i] print (n) # Driver CodefindSmallest(7) findSmallest(36) findSmallest(13) findSmallest(100) # This code is contributed by Harshit Agrawal // C# program to find the smallest number whose// digits multiply to a given number nusing System; class GFG { // Function to prints the smallest number // whose digits multiply to n static void findSmallest(int n) { int i, j=0; int MAX = 50; // To store digits of result in // reverse order int []res = new int[MAX]; // Case 1: If number is smaller than 10 if (n < 10) { Console.WriteLine(n + 10); return; } // Case 2: Start with 9 and try every // possible digit for (i = 9; i > 1; i--) { // If current digit divides n, then // store all occurrences of current // digit in res while (n % i == 0) { n = n / i; res[j] = i; j++; } } // If n could not be broken in form of // digits (prime factors of n // are greater than 9) if (n > 10) { Console.WriteLine("Not possible"); return; } // Print the result array in reverse order for (i = j-1; i >= 0; i--) Console.Write(res[i]); Console.WriteLine(); } // Driver program public static void Main () { findSmallest(7); findSmallest(36); findSmallest(13); findSmallest(100); }} // This code is contributed by nitin mittal. <?php// PHP program to find the// smallest number whose// digits multiply to a// given number n prints the// smallest number whose digits// multiply to n function findSmallest($n){ // To store digits of // result in reverse order $i; $j = 0; $res; // Case 1: If number is // smaller than 10 if ($n < 10) { echo $n + 10; return; } // Case 2: Start with 9 and // try every possible digit for ($i = 9; $i > 1; $i--) { // If current digit divides // n, then store all // occurrences of current // digit in res while ($n % $i == 0) { $n = $n / $i; $res[$j] = $i; $j++; } } // If n could not be broken // in form of digits // (prime factors of n // are greater than 9) if ($n > 10) { echo "Not possible"; return; } // Print the result // array in reverse order for ($i = $j - 1; $i >= 0; $i--) echo $res[$i];} // Driver Code findSmallest(7); echo "\n"; findSmallest(36); echo "\n"; findSmallest(13); echo "\n"; findSmallest(100); // This code is contributed by ajit?> <script> // Javascript program to find the smallest number whose // digits multiply to a given number n // Maximum number of digits in output // prints the smallest number// whose digits multiply to nfunction findSmallest(n){ let i, j = 0; // To store digits of result // in reverse order let res = new Array(50); // Case 1: If number is smaller than 10 if (n < 10) { document.write(n + 10); return; } // Case 2: Start with 9 and // try every possible digit for (i = 9; i > 1; i--) { // If current digit divides n, then store all // occurrences of current digit in res while (n % i == 0) { n = Math.floor(n / i); res[j] = i; j++; } } // If n could not be broken // in form of digits (prime factors // of n are greater than 9) if (n > 10) { document.write("Not possible"); return; } // Print the result array in reverse order for (i = j - 1; i >= 0; i--) document.write(res[i]);} // Driver Code findSmallest(7); document.write("<br>"); findSmallest(36); document.write("<br>"); findSmallest(13); document.write("<br>"); findSmallest(100); // This code is contributed by Mayank Tyagi </script> Output: 17 49 Not possible 455 Time Complexity: O(log2n * 10) Auxiliary Space: O(MAX) This article is contributed by Ashish Bansal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above nitin mittal jit_t shreyashagrawal nidhi_biet Code_Mech mayanktyagi1709 subhammahato348 amartyaghoshgfg simmytarika5 Amazon FactSet number-digits Numbers Mathematical Amazon FactSet Mathematical Numbers Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Sieve of Eratosthenes Program to find GCD or HCF of two numbers Print all possible combinations of r elements in a given array of size n Program for factorial of a number Program for Decimal to Binary Conversion The Knight's tour problem | Backtracking-1 Operators in C / C++
[ { "code": null, "e": 26179, "s": 26151, "text": "\n17 Jan, 2022" }, { "code": null, "e": 26342, "s": 26179, "text": "Given a number ‘n’, find the smallest number ‘p’ such that if we multiply all digits of ‘p’, we get ‘n’. The result ‘p’ should have minimum two digits.Examples: " }, { "code": null, "e": 26609, "s": 26342, "text": "Input: n = 36\nOutput: p = 49 \n// Note that 4*9 = 36 and 49 is the smallest such number\n\nInput: n = 100\nOutput: p = 455\n// Note that 4*5*5 = 100 and 455 is the smallest such number\n\nInput: n = 1\nOutput:p = 11\n// Note that 1*1 = 1\n\nInput: n = 13\nOutput: Not Possible" }, { "code": null, "e": 27236, "s": 26611, "text": "For a given n, following are the two cases to be considered. Case 1: n < 10 When n is smaller than 10, the output is always n+10. For example for n = 7, the output is 17. For n = 9, output is 19.Case 2: n >= 10 Find all factors of n which are between 2 and 9 (both inclusive). The idea is to start searching from 9 so that the number of digits in the result is minimized. For example, 9 is preferred over 33 and 8 is preferred over 24. Store all found factors in an array. The array would contain digits in non-increasing order, so finally print the array in reverse order.Following is the implementation of above concept. " }, { "code": null, "e": 27240, "s": 27236, "text": "C++" }, { "code": null, "e": 27242, "s": 27240, "text": "C" }, { "code": null, "e": 27247, "s": 27242, "text": "Java" }, { "code": null, "e": 27255, "s": 27247, "text": "Python3" }, { "code": null, "e": 27258, "s": 27255, "text": "C#" }, { "code": null, "e": 27262, "s": 27258, "text": "PHP" }, { "code": null, "e": 27273, "s": 27262, "text": "Javascript" }, { "code": "#include<bits/stdc++.h>using namespace std; // Maximum number of digits in output#define MAX 50 // prints the smallest number// whose digits multiply to nvoid findSmallest(int n){ int i, j = 0; // To store digits of result // in reverse order int res[MAX]; // Case 1: If number is smaller than 10 if (n < 10) { cout << n + 10; return; } // Case 2: Start with 9 and // try every possible digit for (i = 9; i > 1; i--) { // If current digit divides n, then store all // occurrences of current digit in res while (n % i == 0) { n = n / i; res[j] = i; j++; } } // If n could not be broken // in form of digits (prime factors // of n are greater than 9) if (n > 10) { cout << \"Not possible\"; return; } // Print the result array in reverse order for (i = j - 1; i >= 0; i--) cout << res[i];} // Driver Codeint main(){ findSmallest(7); cout << \"\\n\"; findSmallest(36); cout << \"\\n\"; findSmallest(13); cout << \"\\n\"; findSmallest(100); return 0;} // This code is contributed by Code_Mech", "e": 28453, "s": 27273, "text": null }, { "code": "#include<stdio.h> // Maximum number of digits in output#define MAX 50 // prints the smallest number whose digits multiply to nvoid findSmallest(int n){ int i, j=0; int res[MAX]; // To store digits of result in reverse order // Case 1: If number is smaller than 10 if (n < 10) { printf(\"%d\", n+10); return; } // Case 2: Start with 9 and try every possible digit for (i=9; i>1; i--) { // If current digit divides n, then store all // occurrences of current digit in res while (n%i == 0) { n = n/i; res[j] = i; j++; } } // If n could not be broken in form of digits (prime factors of n // are greater than 9) if (n > 10) { printf(\"Not possible\"); return; } // Print the result array in reverse order for (i=j-1; i>=0; i--) printf(\"%d\", res[i]);} // Driver program to test above functionint main(){ findSmallest(7); printf(\"\\n\"); findSmallest(36); printf(\"\\n\"); findSmallest(13); printf(\"\\n\"); findSmallest(100); return 0;}", "e": 29558, "s": 28453, "text": null }, { "code": "// Java program to find the smallest number whose// digits multiply to a given number n import java.io.*; class Smallest{ // Function to prints the smallest number whose // digits multiply to n static void findSmallest(int n) { int i, j=0; int MAX = 50; // To store digits of result in reverse order int[] res = new int[MAX]; // Case 1: If number is smaller than 10 if (n < 10) { System.out.println(n+10); return; } // Case 2: Start with 9 and try every possible digit for (i=9; i>1; i--) { // If current digit divides n, then store all // occurrences of current digit in res while (n%i == 0) { n = n/i; res[j] = i; j++; } } // If n could not be broken in form of digits (prime factors of n // are greater than 9) if (n > 10) { System.out.println(\"Not possible\"); return; } // Print the result array in reverse order for (i=j-1; i>=0; i--) System.out.print(res[i]); System.out.println(); } // Driver program public static void main (String[] args) { findSmallest(7); findSmallest(36); findSmallest(13); findSmallest(100); }} // Contributed by Pramod Kumar", "e": 30977, "s": 29558, "text": null }, { "code": "# Python code to find the smallest number# whose digits multiply to give n # function to print the smallest number whose# digits multiply to ndef findSmallest(n): # Case 1 - If the number is smaller than 10 if n < 10: print (n+10) return # Case 2 - Start with 9 and try every possible digit res = [] # to sort digits for i in range(9,1,-1): # If current digit divides n, then store all # occurrences of current digit in res while n % i == 0: n = n / i res.append(i) # If n could not be broken in the form of digits # prime factors of n are greater than 9 if n > 10: print (\"Not Possible\") return # Print the number from result array in reverse order n = res[len(res)-1] for i in range(len(res)-2,-1,-1): n = 10 * n + res[i] print (n) # Driver CodefindSmallest(7) findSmallest(36) findSmallest(13) findSmallest(100) # This code is contributed by Harshit Agrawal", "e": 31981, "s": 30977, "text": null }, { "code": "// C# program to find the smallest number whose// digits multiply to a given number nusing System; class GFG { // Function to prints the smallest number // whose digits multiply to n static void findSmallest(int n) { int i, j=0; int MAX = 50; // To store digits of result in // reverse order int []res = new int[MAX]; // Case 1: If number is smaller than 10 if (n < 10) { Console.WriteLine(n + 10); return; } // Case 2: Start with 9 and try every // possible digit for (i = 9; i > 1; i--) { // If current digit divides n, then // store all occurrences of current // digit in res while (n % i == 0) { n = n / i; res[j] = i; j++; } } // If n could not be broken in form of // digits (prime factors of n // are greater than 9) if (n > 10) { Console.WriteLine(\"Not possible\"); return; } // Print the result array in reverse order for (i = j-1; i >= 0; i--) Console.Write(res[i]); Console.WriteLine(); } // Driver program public static void Main () { findSmallest(7); findSmallest(36); findSmallest(13); findSmallest(100); }} // This code is contributed by nitin mittal.", "e": 33487, "s": 31981, "text": null }, { "code": "<?php// PHP program to find the// smallest number whose// digits multiply to a// given number n prints the// smallest number whose digits// multiply to n function findSmallest($n){ // To store digits of // result in reverse order $i; $j = 0; $res; // Case 1: If number is // smaller than 10 if ($n < 10) { echo $n + 10; return; } // Case 2: Start with 9 and // try every possible digit for ($i = 9; $i > 1; $i--) { // If current digit divides // n, then store all // occurrences of current // digit in res while ($n % $i == 0) { $n = $n / $i; $res[$j] = $i; $j++; } } // If n could not be broken // in form of digits // (prime factors of n // are greater than 9) if ($n > 10) { echo \"Not possible\"; return; } // Print the result // array in reverse order for ($i = $j - 1; $i >= 0; $i--) echo $res[$i];} // Driver Code findSmallest(7); echo \"\\n\"; findSmallest(36); echo \"\\n\"; findSmallest(13); echo \"\\n\"; findSmallest(100); // This code is contributed by ajit?>", "e": 34692, "s": 33487, "text": null }, { "code": "<script> // Javascript program to find the smallest number whose // digits multiply to a given number n // Maximum number of digits in output // prints the smallest number// whose digits multiply to nfunction findSmallest(n){ let i, j = 0; // To store digits of result // in reverse order let res = new Array(50); // Case 1: If number is smaller than 10 if (n < 10) { document.write(n + 10); return; } // Case 2: Start with 9 and // try every possible digit for (i = 9; i > 1; i--) { // If current digit divides n, then store all // occurrences of current digit in res while (n % i == 0) { n = Math.floor(n / i); res[j] = i; j++; } } // If n could not be broken // in form of digits (prime factors // of n are greater than 9) if (n > 10) { document.write(\"Not possible\"); return; } // Print the result array in reverse order for (i = j - 1; i >= 0; i--) document.write(res[i]);} // Driver Code findSmallest(7); document.write(\"<br>\"); findSmallest(36); document.write(\"<br>\"); findSmallest(13); document.write(\"<br>\"); findSmallest(100); // This code is contributed by Mayank Tyagi </script>", "e": 35993, "s": 34692, "text": null }, { "code": null, "e": 36002, "s": 35993, "text": "Output: " }, { "code": null, "e": 36026, "s": 36002, "text": "17\n49\nNot possible\n455 " }, { "code": null, "e": 36057, "s": 36026, "text": "Time Complexity: O(log2n * 10)" }, { "code": null, "e": 36081, "s": 36057, "text": "Auxiliary Space: O(MAX)" }, { "code": null, "e": 36252, "s": 36081, "text": "This article is contributed by Ashish Bansal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 36265, "s": 36252, "text": "nitin mittal" }, { "code": null, "e": 36271, "s": 36265, "text": "jit_t" }, { "code": null, "e": 36287, "s": 36271, "text": "shreyashagrawal" }, { "code": null, "e": 36298, "s": 36287, "text": "nidhi_biet" }, { "code": null, "e": 36308, "s": 36298, "text": "Code_Mech" }, { "code": null, "e": 36324, "s": 36308, "text": "mayanktyagi1709" }, { "code": null, "e": 36340, "s": 36324, "text": "subhammahato348" }, { "code": null, "e": 36356, "s": 36340, "text": "amartyaghoshgfg" }, { "code": null, "e": 36369, "s": 36356, "text": "simmytarika5" }, { "code": null, "e": 36376, "s": 36369, "text": "Amazon" }, { "code": null, "e": 36384, "s": 36376, "text": "FactSet" }, { "code": null, "e": 36398, "s": 36384, "text": "number-digits" }, { "code": null, "e": 36406, "s": 36398, "text": "Numbers" }, { "code": null, "e": 36419, "s": 36406, "text": "Mathematical" }, { "code": null, "e": 36426, "s": 36419, "text": "Amazon" }, { "code": null, "e": 36434, "s": 36426, "text": "FactSet" }, { "code": null, "e": 36447, "s": 36434, "text": "Mathematical" }, { "code": null, "e": 36455, "s": 36447, "text": "Numbers" }, { "code": null, "e": 36553, "s": 36455, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36577, "s": 36553, "text": "Merge two sorted arrays" }, { "code": null, "e": 36620, "s": 36577, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 36634, "s": 36620, "text": "Prime Numbers" }, { "code": null, "e": 36656, "s": 36634, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 36698, "s": 36656, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 36771, "s": 36698, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 36805, "s": 36771, "text": "Program for factorial of a number" }, { "code": null, "e": 36846, "s": 36805, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 36889, "s": 36846, "text": "The Knight's tour problem | Backtracking-1" } ]
How to execute multiple promises sequentially in JavaScript ?
13 Jan, 2022 In this article, we will try to understand how we could easily execute multiple promises in a sequential manner (one after the another) with several techniques or methods provided by JavaScript. Let us first quickly understand how we may create a promise by using the following syntax provided by JavaScript. Syntax: Following syntax could be used for the creation of promise in JavaScript. let promise = new Promise((resolve, reject) => resolve(10)) By using the above syntax we could create our promise successfully by either resolving it (having the resolved state) or rejecting it (having the rejected state). Example: In this example, we will create a simple promise just to see how it works or how it gets executed. Javascript <script> let promise = new Promise((resolve, reject) => { resolve("GeeksforGeeks"); }); promise.then(result => console.log(result));</script> Output: GeeksforGeeks Now that we have understood how to create a promise let us quickly see and visualize how we could execute multiple promises in a sequential manner. Following are the certain approaches through which we could easily execute multiple promises in a sequential manner. Approach 1: In this approach, we will use Promise.all() method which takes all promises in a single array as its input. As a result, this method executes all the promises in itself and returns a new single promise in which the values of all the other promises are combined together. The values in the newly returned single promise will be in a sequential manner (that it one after the another). The output which will be returned is in the form of an array that will consist of the values which are either resolved or rejected by the other two promises. Example: Let us see the following code which illustrates the above approach: Javascript <script> let promise1 = new Promise((resolve, reject) => { resolve("Hello! "); }); let promise2 = new Promise((resolve, reject) => { setTimeout(() => { resolve("GeeksforGeeks"); }, 1000); }); Promise.all([promise1, promise2]) .then((result) => console.log(result));</script> Output: [ 'Hello! ', 'GeeksforGeeks' ] Approach 2: In this approach, we will use Promise.allSettled() which will be executed in a quite similar manner as Promise.all() method executed by taking promises as input in the single array and executing them sequentially. There is a slight difference which is that this Promise.allSettled() method returns an array of objects in which along with the state of each promise (either fulfilled or rejected), the value of each promise is also there. Example: Let us see the following code which illustrates the above approach: Javascript <script> let promise1 = new Promise((resolve, reject) => { resolve("Hello! "); }); let promise2 = new Promise((resolve, reject) => { setTimeout(() => { resolve("GeeksforGeeks"); }, 1000); }); Promise.allSettled([promise1, promise2]) .then((result) => console.log(result));</script> Output: [ { status: 'fulfilled', value: 'Hello! ' }, { status: 'fulfilled', value: 'GeeksforGeeks' } ] Approach 3: In this approach, we will use for-of loop along with the async-await methods. We will run the loop over the array of promises, further making an async function and thus await the result into the resultant promise along with the try-catch block and thus print the result over the browser’s console. Example: Let us see the following code which illustrates the above approach: Javascript <script> let promise1 = new Promise((resolve, reject) => { resolve("Hello! "); }); let promise2 = new Promise((resolve, reject) => { setTimeout(() => { resolve("GeeksforGeeks"); }, 1000); }); let promiseExecution = async () => { for (let promise of [promise1, promise2]) { try { const message = await promise; console.log(message); } catch (error) { console.log(error.message); } } }; promiseExecution();</script> Output: Hello! GeeksforGeeks JavaScript-Questions Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array Difference Between PUT and PATCH Request Roadmap to Learn JavaScript For Beginners JavaScript | Promises Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 52, "s": 24, "text": "\n13 Jan, 2022" }, { "code": null, "e": 247, "s": 52, "text": "In this article, we will try to understand how we could easily execute multiple promises in a sequential manner (one after the another) with several techniques or methods provided by JavaScript." }, { "code": null, "e": 361, "s": 247, "text": "Let us first quickly understand how we may create a promise by using the following syntax provided by JavaScript." }, { "code": null, "e": 443, "s": 361, "text": "Syntax: Following syntax could be used for the creation of promise in JavaScript." }, { "code": null, "e": 503, "s": 443, "text": "let promise = new Promise((resolve, reject) => resolve(10))" }, { "code": null, "e": 666, "s": 503, "text": "By using the above syntax we could create our promise successfully by either resolving it (having the resolved state) or rejecting it (having the rejected state)." }, { "code": null, "e": 774, "s": 666, "text": "Example: In this example, we will create a simple promise just to see how it works or how it gets executed." }, { "code": null, "e": 785, "s": 774, "text": "Javascript" }, { "code": "<script> let promise = new Promise((resolve, reject) => { resolve(\"GeeksforGeeks\"); }); promise.then(result => console.log(result));</script>", "e": 943, "s": 785, "text": null }, { "code": null, "e": 951, "s": 943, "text": "Output:" }, { "code": null, "e": 965, "s": 951, "text": "GeeksforGeeks" }, { "code": null, "e": 1113, "s": 965, "text": "Now that we have understood how to create a promise let us quickly see and visualize how we could execute multiple promises in a sequential manner." }, { "code": null, "e": 1230, "s": 1113, "text": "Following are the certain approaches through which we could easily execute multiple promises in a sequential manner." }, { "code": null, "e": 1242, "s": 1230, "text": "Approach 1:" }, { "code": null, "e": 1350, "s": 1242, "text": "In this approach, we will use Promise.all() method which takes all promises in a single array as its input." }, { "code": null, "e": 1513, "s": 1350, "text": "As a result, this method executes all the promises in itself and returns a new single promise in which the values of all the other promises are combined together." }, { "code": null, "e": 1625, "s": 1513, "text": "The values in the newly returned single promise will be in a sequential manner (that it one after the another)." }, { "code": null, "e": 1783, "s": 1625, "text": "The output which will be returned is in the form of an array that will consist of the values which are either resolved or rejected by the other two promises." }, { "code": null, "e": 1860, "s": 1783, "text": "Example: Let us see the following code which illustrates the above approach:" }, { "code": null, "e": 1871, "s": 1860, "text": "Javascript" }, { "code": "<script> let promise1 = new Promise((resolve, reject) => { resolve(\"Hello! \"); }); let promise2 = new Promise((resolve, reject) => { setTimeout(() => { resolve(\"GeeksforGeeks\"); }, 1000); }); Promise.all([promise1, promise2]) .then((result) => console.log(result));</script>", "e": 2204, "s": 1871, "text": null }, { "code": null, "e": 2212, "s": 2204, "text": "Output:" }, { "code": null, "e": 2243, "s": 2212, "text": "[ 'Hello! ', 'GeeksforGeeks' ]" }, { "code": null, "e": 2255, "s": 2243, "text": "Approach 2:" }, { "code": null, "e": 2469, "s": 2255, "text": "In this approach, we will use Promise.allSettled() which will be executed in a quite similar manner as Promise.all() method executed by taking promises as input in the single array and executing them sequentially." }, { "code": null, "e": 2692, "s": 2469, "text": "There is a slight difference which is that this Promise.allSettled() method returns an array of objects in which along with the state of each promise (either fulfilled or rejected), the value of each promise is also there." }, { "code": null, "e": 2769, "s": 2692, "text": "Example: Let us see the following code which illustrates the above approach:" }, { "code": null, "e": 2780, "s": 2769, "text": "Javascript" }, { "code": "<script> let promise1 = new Promise((resolve, reject) => { resolve(\"Hello! \"); }); let promise2 = new Promise((resolve, reject) => { setTimeout(() => { resolve(\"GeeksforGeeks\"); }, 1000); }); Promise.allSettled([promise1, promise2]) .then((result) => console.log(result));</script>", "e": 3120, "s": 2780, "text": null }, { "code": null, "e": 3128, "s": 3120, "text": "Output:" }, { "code": null, "e": 3227, "s": 3128, "text": "[\n { status: 'fulfilled', value: 'Hello! ' },\n { status: 'fulfilled', value: 'GeeksforGeeks' }\n]" }, { "code": null, "e": 3239, "s": 3227, "text": "Approach 3:" }, { "code": null, "e": 3317, "s": 3239, "text": "In this approach, we will use for-of loop along with the async-await methods." }, { "code": null, "e": 3537, "s": 3317, "text": "We will run the loop over the array of promises, further making an async function and thus await the result into the resultant promise along with the try-catch block and thus print the result over the browser’s console." }, { "code": null, "e": 3614, "s": 3537, "text": "Example: Let us see the following code which illustrates the above approach:" }, { "code": null, "e": 3625, "s": 3614, "text": "Javascript" }, { "code": "<script> let promise1 = new Promise((resolve, reject) => { resolve(\"Hello! \"); }); let promise2 = new Promise((resolve, reject) => { setTimeout(() => { resolve(\"GeeksforGeeks\"); }, 1000); }); let promiseExecution = async () => { for (let promise of [promise1, promise2]) { try { const message = await promise; console.log(message); } catch (error) { console.log(error.message); } } }; promiseExecution();</script>", "e": 4188, "s": 3625, "text": null }, { "code": null, "e": 4196, "s": 4188, "text": "Output:" }, { "code": null, "e": 4218, "s": 4196, "text": "Hello! \nGeeksforGeeks" }, { "code": null, "e": 4239, "s": 4218, "text": "JavaScript-Questions" }, { "code": null, "e": 4246, "s": 4239, "text": "Picked" }, { "code": null, "e": 4257, "s": 4246, "text": "JavaScript" }, { "code": null, "e": 4274, "s": 4257, "text": "Web Technologies" }, { "code": null, "e": 4372, "s": 4274, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4433, "s": 4372, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4473, "s": 4433, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 4514, "s": 4473, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 4556, "s": 4514, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 4578, "s": 4556, "text": "JavaScript | Promises" }, { "code": null, "e": 4640, "s": 4578, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4673, "s": 4640, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 4734, "s": 4673, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4784, "s": 4734, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to add Custom Spinner in android?
25 Jun, 2020 Spinner is a widget that is used to select an item from a list of items. When the user tap on a spinner a drop-down menu is visible to the user. In this article, we will learn how to add custom spinner in the app. If you want to know more about spinner in detail then click on this link. Approach: Create a new file algorithm_spinner.xml and add the following code. Each item in spinner will have this layout, an image view and a textview.algorithm_spinner.xmlalgorithm_spinner.xml<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:id="@+id/image_view" android:layout_width="100dp" android:layout_height="100dp" android:src="@drawable/gfg" /> <TextView android:id="@+id/text_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/image_view" android:layout_alignParentTop="true" android:layout_margin="20dp" android:layout_toEndOf="@+id/image_view" android:gravity="center" android:text="Quick Sort" android:textColor="@android:color/black" android:textSize="20sp" /> </RelativeLayout>Create a new file AlgorithmItem.java and add the below following code. This is the model class which is used to get the algorithm name when the user clicks on any item. Here we define a constructor and a getAlgorithmName method which returns the algorithm name of the object.AlgorithmItem.javaAlgorithmItem.javapackage org.geeksforgeeks.gfgcustomspinner; public class AlgorithmItem { private String algorithmName; public AlgorithmItem(String countryName) { algorithmName = countryName; } public String getAlgorithmName() { return algorithmName; }}Create a new file AlgorithmAdapter.java and add the following code. Here we define our own Adapter class. It maps the item with its view, providing access to the item`s data in the list of spinner.AlgorithmAdapter.javaAlgorithmAdapter.javapackage org.geeksforgeeks.gfgcustomspinner; import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ArrayAdapter;import android.widget.TextView;import androidx.annotation.NonNull;import androidx.annotation.Nullable;import java.util.ArrayList; public class AlgorithmAdapter extends ArrayAdapter<AlgorithmItem> { public AlgorithmAdapter(Context context, ArrayList<AlgorithmItem> algorithmList) { super(context, 0, algorithmList); } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { return initView(position, convertView, parent); } @Override public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { return initView(position, convertView, parent); } private View initView(int position, View convertView, ViewGroup parent) { // It is used to set our custom view. if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.algorithm_spinner, parent, false); } TextView textViewName = convertView.findViewById(R.id.text_view); AlgorithmItem currentItem = getItem(position); // It is used the name to the TextView when the // current item is not null. if (currentItem != null) { textViewName.setText(currentItem.getAlgorithmName()); } return convertView; }}Add the following code in activity_main.xml file. Here we add our spinner on the layout. This will add a textview and a spinner.activity_main.xmlactivity_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" tools:context=".MainActivity"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Learn Algorithms" android:textStyle="bold" android:textSize="18sp" android:layout_above="@+id/spinner_algorithm" android:layout_marginStart="10dp" android:layout_marginBottom="25dp" /> <Spinner android:layout_margin="5dp" android:id="@+id/spinner_algorithm" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:layout_marginTop="18dp" /> </RelativeLayout>Now add the following code in the MainActivity.java file. Here AlgorithmAdapter class object is made and it acts as an adapter for the spinner and add onItemSelectedListner() to our spinner. When the user tap on any item of the spinner, it gets invoked. It shows a toast with the name of the item that user selected from the list.MainActivity.javaMainActivity.javapackage org.geeksforgeeks.gfgcustomspinner; import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.AdapterView;import android.widget.Spinner;import android.widget.Toast;import java.util.ArrayList; public class MainActivity extends AppCompatActivity { ArrayList<AlgorithmItem> algorithmItems; AlgorithmAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initList(); Spinner spinner = findViewById(R.id.spinner_algorithm); // we pass our item list and context to our Adapter. adapter = new AlgorithmAdapter(this, algorithmItems); spinner.setAdapter(adapter); spinner.setOnItemSelectedListener( new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // It returns the clicked item. AlgorithmItem clickedItem = (AlgorithmItem) parent.getItemAtPosition(position); String name = clickedItem.getAlgorithmName(); Toast.makeText(MainActivity.this, name + " selected", Toast.LENGTH_SHORT).show(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } // It is used to set the algorithm names to our array list. private void initList() { algorithmItems = new ArrayList<>(); algorithmItems.add(new AlgorithmItem("Quick Sort")); algorithmItems.add(new AlgorithmItem("Merge Sort")); algorithmItems.add(new AlgorithmItem("Heap Sort")); algorithmItems.add(new AlgorithmItem("Prims Algorithm")); algorithmItems.add(new AlgorithmItem("Kruskal Algorithm")); algorithmItems.add(new AlgorithmItem("Rabin Karp")); algorithmItems.add(new AlgorithmItem("Binary Search")); }} Create a new file algorithm_spinner.xml and add the following code. Each item in spinner will have this layout, an image view and a textview.algorithm_spinner.xmlalgorithm_spinner.xml<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:id="@+id/image_view" android:layout_width="100dp" android:layout_height="100dp" android:src="@drawable/gfg" /> <TextView android:id="@+id/text_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/image_view" android:layout_alignParentTop="true" android:layout_margin="20dp" android:layout_toEndOf="@+id/image_view" android:gravity="center" android:text="Quick Sort" android:textColor="@android:color/black" android:textSize="20sp" /> </RelativeLayout> algorithm_spinner.xml <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:id="@+id/image_view" android:layout_width="100dp" android:layout_height="100dp" android:src="@drawable/gfg" /> <TextView android:id="@+id/text_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/image_view" android:layout_alignParentTop="true" android:layout_margin="20dp" android:layout_toEndOf="@+id/image_view" android:gravity="center" android:text="Quick Sort" android:textColor="@android:color/black" android:textSize="20sp" /> </RelativeLayout> Create a new file AlgorithmItem.java and add the below following code. This is the model class which is used to get the algorithm name when the user clicks on any item. Here we define a constructor and a getAlgorithmName method which returns the algorithm name of the object.AlgorithmItem.javaAlgorithmItem.javapackage org.geeksforgeeks.gfgcustomspinner; public class AlgorithmItem { private String algorithmName; public AlgorithmItem(String countryName) { algorithmName = countryName; } public String getAlgorithmName() { return algorithmName; }} AlgorithmItem.java package org.geeksforgeeks.gfgcustomspinner; public class AlgorithmItem { private String algorithmName; public AlgorithmItem(String countryName) { algorithmName = countryName; } public String getAlgorithmName() { return algorithmName; }} Create a new file AlgorithmAdapter.java and add the following code. Here we define our own Adapter class. It maps the item with its view, providing access to the item`s data in the list of spinner.AlgorithmAdapter.javaAlgorithmAdapter.javapackage org.geeksforgeeks.gfgcustomspinner; import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ArrayAdapter;import android.widget.TextView;import androidx.annotation.NonNull;import androidx.annotation.Nullable;import java.util.ArrayList; public class AlgorithmAdapter extends ArrayAdapter<AlgorithmItem> { public AlgorithmAdapter(Context context, ArrayList<AlgorithmItem> algorithmList) { super(context, 0, algorithmList); } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { return initView(position, convertView, parent); } @Override public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { return initView(position, convertView, parent); } private View initView(int position, View convertView, ViewGroup parent) { // It is used to set our custom view. if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.algorithm_spinner, parent, false); } TextView textViewName = convertView.findViewById(R.id.text_view); AlgorithmItem currentItem = getItem(position); // It is used the name to the TextView when the // current item is not null. if (currentItem != null) { textViewName.setText(currentItem.getAlgorithmName()); } return convertView; }} AlgorithmAdapter.java package org.geeksforgeeks.gfgcustomspinner; import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ArrayAdapter;import android.widget.TextView;import androidx.annotation.NonNull;import androidx.annotation.Nullable;import java.util.ArrayList; public class AlgorithmAdapter extends ArrayAdapter<AlgorithmItem> { public AlgorithmAdapter(Context context, ArrayList<AlgorithmItem> algorithmList) { super(context, 0, algorithmList); } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { return initView(position, convertView, parent); } @Override public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { return initView(position, convertView, parent); } private View initView(int position, View convertView, ViewGroup parent) { // It is used to set our custom view. if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.algorithm_spinner, parent, false); } TextView textViewName = convertView.findViewById(R.id.text_view); AlgorithmItem currentItem = getItem(position); // It is used the name to the TextView when the // current item is not null. if (currentItem != null) { textViewName.setText(currentItem.getAlgorithmName()); } return convertView; }} Add the following code in activity_main.xml file. Here we add our spinner on the layout. This will add a textview and a spinner.activity_main.xmlactivity_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" tools:context=".MainActivity"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Learn Algorithms" android:textStyle="bold" android:textSize="18sp" android:layout_above="@+id/spinner_algorithm" android:layout_marginStart="10dp" android:layout_marginBottom="25dp" /> <Spinner android:layout_margin="5dp" android:id="@+id/spinner_algorithm" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:layout_marginTop="18dp" /> </RelativeLayout> 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" tools:context=".MainActivity"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Learn Algorithms" android:textStyle="bold" android:textSize="18sp" android:layout_above="@+id/spinner_algorithm" android:layout_marginStart="10dp" android:layout_marginBottom="25dp" /> <Spinner android:layout_margin="5dp" android:id="@+id/spinner_algorithm" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:layout_marginTop="18dp" /> </RelativeLayout> Now add the following code in the MainActivity.java file. Here AlgorithmAdapter class object is made and it acts as an adapter for the spinner and add onItemSelectedListner() to our spinner. When the user tap on any item of the spinner, it gets invoked. It shows a toast with the name of the item that user selected from the list.MainActivity.javaMainActivity.javapackage org.geeksforgeeks.gfgcustomspinner; import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.AdapterView;import android.widget.Spinner;import android.widget.Toast;import java.util.ArrayList; public class MainActivity extends AppCompatActivity { ArrayList<AlgorithmItem> algorithmItems; AlgorithmAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initList(); Spinner spinner = findViewById(R.id.spinner_algorithm); // we pass our item list and context to our Adapter. adapter = new AlgorithmAdapter(this, algorithmItems); spinner.setAdapter(adapter); spinner.setOnItemSelectedListener( new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // It returns the clicked item. AlgorithmItem clickedItem = (AlgorithmItem) parent.getItemAtPosition(position); String name = clickedItem.getAlgorithmName(); Toast.makeText(MainActivity.this, name + " selected", Toast.LENGTH_SHORT).show(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } // It is used to set the algorithm names to our array list. private void initList() { algorithmItems = new ArrayList<>(); algorithmItems.add(new AlgorithmItem("Quick Sort")); algorithmItems.add(new AlgorithmItem("Merge Sort")); algorithmItems.add(new AlgorithmItem("Heap Sort")); algorithmItems.add(new AlgorithmItem("Prims Algorithm")); algorithmItems.add(new AlgorithmItem("Kruskal Algorithm")); algorithmItems.add(new AlgorithmItem("Rabin Karp")); algorithmItems.add(new AlgorithmItem("Binary Search")); }} MainActivity.java package org.geeksforgeeks.gfgcustomspinner; import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.AdapterView;import android.widget.Spinner;import android.widget.Toast;import java.util.ArrayList; public class MainActivity extends AppCompatActivity { ArrayList<AlgorithmItem> algorithmItems; AlgorithmAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initList(); Spinner spinner = findViewById(R.id.spinner_algorithm); // we pass our item list and context to our Adapter. adapter = new AlgorithmAdapter(this, algorithmItems); spinner.setAdapter(adapter); spinner.setOnItemSelectedListener( new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // It returns the clicked item. AlgorithmItem clickedItem = (AlgorithmItem) parent.getItemAtPosition(position); String name = clickedItem.getAlgorithmName(); Toast.makeText(MainActivity.this, name + " selected", Toast.LENGTH_SHORT).show(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } // It is used to set the algorithm names to our array list. private void initList() { algorithmItems = new ArrayList<>(); algorithmItems.add(new AlgorithmItem("Quick Sort")); algorithmItems.add(new AlgorithmItem("Merge Sort")); algorithmItems.add(new AlgorithmItem("Heap Sort")); algorithmItems.add(new AlgorithmItem("Prims Algorithm")); algorithmItems.add(new AlgorithmItem("Kruskal Algorithm")); algorithmItems.add(new AlgorithmItem("Rabin Karp")); algorithmItems.add(new AlgorithmItem("Binary Search")); }} Output: android Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java ArrayList in Java Collections in Java Stream In Java Multidimensional Arrays in Java Stack Class in Java Singleton Class in Java Set in Java Introduction to Java Constructors in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Jun, 2020" }, { "code": null, "e": 316, "s": 28, "text": "Spinner is a widget that is used to select an item from a list of items. When the user tap on a spinner a drop-down menu is visible to the user. In this article, we will learn how to add custom spinner in the app. If you want to know more about spinner in detail then click on this link." }, { "code": null, "e": 326, "s": 316, "text": "Approach:" }, { "code": null, "e": 7492, "s": 326, "text": "Create a new file algorithm_spinner.xml and add the following code. Each item in spinner will have this layout, an image view and a textview.algorithm_spinner.xmlalgorithm_spinner.xml<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"> <ImageView android:id=\"@+id/image_view\" android:layout_width=\"100dp\" android:layout_height=\"100dp\" android:src=\"@drawable/gfg\" /> <TextView android:id=\"@+id/text_view\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignBottom=\"@+id/image_view\" android:layout_alignParentTop=\"true\" android:layout_margin=\"20dp\" android:layout_toEndOf=\"@+id/image_view\" android:gravity=\"center\" android:text=\"Quick Sort\" android:textColor=\"@android:color/black\" android:textSize=\"20sp\" /> </RelativeLayout>Create a new file AlgorithmItem.java and add the below following code. This is the model class which is used to get the algorithm name when the user clicks on any item. Here we define a constructor and a getAlgorithmName method which returns the algorithm name of the object.AlgorithmItem.javaAlgorithmItem.javapackage org.geeksforgeeks.gfgcustomspinner; public class AlgorithmItem { private String algorithmName; public AlgorithmItem(String countryName) { algorithmName = countryName; } public String getAlgorithmName() { return algorithmName; }}Create a new file AlgorithmAdapter.java and add the following code. Here we define our own Adapter class. It maps the item with its view, providing access to the item`s data in the list of spinner.AlgorithmAdapter.javaAlgorithmAdapter.javapackage org.geeksforgeeks.gfgcustomspinner; import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ArrayAdapter;import android.widget.TextView;import androidx.annotation.NonNull;import androidx.annotation.Nullable;import java.util.ArrayList; public class AlgorithmAdapter extends ArrayAdapter<AlgorithmItem> { public AlgorithmAdapter(Context context, ArrayList<AlgorithmItem> algorithmList) { super(context, 0, algorithmList); } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { return initView(position, convertView, parent); } @Override public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { return initView(position, convertView, parent); } private View initView(int position, View convertView, ViewGroup parent) { // It is used to set our custom view. if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.algorithm_spinner, parent, false); } TextView textViewName = convertView.findViewById(R.id.text_view); AlgorithmItem currentItem = getItem(position); // It is used the name to the TextView when the // current item is not null. if (currentItem != null) { textViewName.setText(currentItem.getAlgorithmName()); } return convertView; }}Add the following code in activity_main.xml file. Here we add our spinner on the layout. This will add a textview and a spinner.activity_main.xmlactivity_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\" tools:context=\".MainActivity\"> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"Learn Algorithms\" android:textStyle=\"bold\" android:textSize=\"18sp\" android:layout_above=\"@+id/spinner_algorithm\" android:layout_marginStart=\"10dp\" android:layout_marginBottom=\"25dp\" /> <Spinner android:layout_margin=\"5dp\" android:id=\"@+id/spinner_algorithm\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:layout_marginTop=\"18dp\" /> </RelativeLayout>Now add the following code in the MainActivity.java file. Here AlgorithmAdapter class object is made and it acts as an adapter for the spinner and add onItemSelectedListner() to our spinner. When the user tap on any item of the spinner, it gets invoked. It shows a toast with the name of the item that user selected from the list.MainActivity.javaMainActivity.javapackage org.geeksforgeeks.gfgcustomspinner; import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.AdapterView;import android.widget.Spinner;import android.widget.Toast;import java.util.ArrayList; public class MainActivity extends AppCompatActivity { ArrayList<AlgorithmItem> algorithmItems; AlgorithmAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initList(); Spinner spinner = findViewById(R.id.spinner_algorithm); // we pass our item list and context to our Adapter. adapter = new AlgorithmAdapter(this, algorithmItems); spinner.setAdapter(adapter); spinner.setOnItemSelectedListener( new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // It returns the clicked item. AlgorithmItem clickedItem = (AlgorithmItem) parent.getItemAtPosition(position); String name = clickedItem.getAlgorithmName(); Toast.makeText(MainActivity.this, name + \" selected\", Toast.LENGTH_SHORT).show(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } // It is used to set the algorithm names to our array list. private void initList() { algorithmItems = new ArrayList<>(); algorithmItems.add(new AlgorithmItem(\"Quick Sort\")); algorithmItems.add(new AlgorithmItem(\"Merge Sort\")); algorithmItems.add(new AlgorithmItem(\"Heap Sort\")); algorithmItems.add(new AlgorithmItem(\"Prims Algorithm\")); algorithmItems.add(new AlgorithmItem(\"Kruskal Algorithm\")); algorithmItems.add(new AlgorithmItem(\"Rabin Karp\")); algorithmItems.add(new AlgorithmItem(\"Binary Search\")); }}" }, { "code": null, "e": 8517, "s": 7492, "text": "Create a new file algorithm_spinner.xml and add the following code. Each item in spinner will have this layout, an image view and a textview.algorithm_spinner.xmlalgorithm_spinner.xml<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"> <ImageView android:id=\"@+id/image_view\" android:layout_width=\"100dp\" android:layout_height=\"100dp\" android:src=\"@drawable/gfg\" /> <TextView android:id=\"@+id/text_view\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignBottom=\"@+id/image_view\" android:layout_alignParentTop=\"true\" android:layout_margin=\"20dp\" android:layout_toEndOf=\"@+id/image_view\" android:gravity=\"center\" android:text=\"Quick Sort\" android:textColor=\"@android:color/black\" android:textSize=\"20sp\" /> </RelativeLayout>" }, { "code": null, "e": 8539, "s": 8517, "text": "algorithm_spinner.xml" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"> <ImageView android:id=\"@+id/image_view\" android:layout_width=\"100dp\" android:layout_height=\"100dp\" android:src=\"@drawable/gfg\" /> <TextView android:id=\"@+id/text_view\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignBottom=\"@+id/image_view\" android:layout_alignParentTop=\"true\" android:layout_margin=\"20dp\" android:layout_toEndOf=\"@+id/image_view\" android:gravity=\"center\" android:text=\"Quick Sort\" android:textColor=\"@android:color/black\" android:textSize=\"20sp\" /> </RelativeLayout>", "e": 9381, "s": 8539, "text": null }, { "code": null, "e": 9969, "s": 9381, "text": "Create a new file AlgorithmItem.java and add the below following code. This is the model class which is used to get the algorithm name when the user clicks on any item. Here we define a constructor and a getAlgorithmName method which returns the algorithm name of the object.AlgorithmItem.javaAlgorithmItem.javapackage org.geeksforgeeks.gfgcustomspinner; public class AlgorithmItem { private String algorithmName; public AlgorithmItem(String countryName) { algorithmName = countryName; } public String getAlgorithmName() { return algorithmName; }}" }, { "code": null, "e": 9988, "s": 9969, "text": "AlgorithmItem.java" }, { "code": "package org.geeksforgeeks.gfgcustomspinner; public class AlgorithmItem { private String algorithmName; public AlgorithmItem(String countryName) { algorithmName = countryName; } public String getAlgorithmName() { return algorithmName; }}", "e": 10265, "s": 9988, "text": null }, { "code": null, "e": 12183, "s": 10265, "text": "Create a new file AlgorithmAdapter.java and add the following code. Here we define our own Adapter class. It maps the item with its view, providing access to the item`s data in the list of spinner.AlgorithmAdapter.javaAlgorithmAdapter.javapackage org.geeksforgeeks.gfgcustomspinner; import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ArrayAdapter;import android.widget.TextView;import androidx.annotation.NonNull;import androidx.annotation.Nullable;import java.util.ArrayList; public class AlgorithmAdapter extends ArrayAdapter<AlgorithmItem> { public AlgorithmAdapter(Context context, ArrayList<AlgorithmItem> algorithmList) { super(context, 0, algorithmList); } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { return initView(position, convertView, parent); } @Override public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { return initView(position, convertView, parent); } private View initView(int position, View convertView, ViewGroup parent) { // It is used to set our custom view. if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.algorithm_spinner, parent, false); } TextView textViewName = convertView.findViewById(R.id.text_view); AlgorithmItem currentItem = getItem(position); // It is used the name to the TextView when the // current item is not null. if (currentItem != null) { textViewName.setText(currentItem.getAlgorithmName()); } return convertView; }}" }, { "code": null, "e": 12205, "s": 12183, "text": "AlgorithmAdapter.java" }, { "code": "package org.geeksforgeeks.gfgcustomspinner; import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ArrayAdapter;import android.widget.TextView;import androidx.annotation.NonNull;import androidx.annotation.Nullable;import java.util.ArrayList; public class AlgorithmAdapter extends ArrayAdapter<AlgorithmItem> { public AlgorithmAdapter(Context context, ArrayList<AlgorithmItem> algorithmList) { super(context, 0, algorithmList); } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { return initView(position, convertView, parent); } @Override public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { return initView(position, convertView, parent); } private View initView(int position, View convertView, ViewGroup parent) { // It is used to set our custom view. if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.algorithm_spinner, parent, false); } TextView textViewName = convertView.findViewById(R.id.text_view); AlgorithmItem currentItem = getItem(position); // It is used the name to the TextView when the // current item is not null. if (currentItem != null) { textViewName.setText(currentItem.getAlgorithmName()); } return convertView; }}", "e": 13884, "s": 12205, "text": null }, { "code": null, "e": 14965, "s": 13884, "text": "Add the following code in activity_main.xml file. Here we add our spinner on the layout. This will add a textview and a spinner.activity_main.xmlactivity_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\" tools:context=\".MainActivity\"> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"Learn Algorithms\" android:textStyle=\"bold\" android:textSize=\"18sp\" android:layout_above=\"@+id/spinner_algorithm\" android:layout_marginStart=\"10dp\" android:layout_marginBottom=\"25dp\" /> <Spinner android:layout_margin=\"5dp\" android:id=\"@+id/spinner_algorithm\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:layout_marginTop=\"18dp\" /> </RelativeLayout>" }, { "code": null, "e": 14983, "s": 14965, "text": "activity_main.xml" }, { "code": " <?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\" tools:context=\".MainActivity\"> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"Learn Algorithms\" android:textStyle=\"bold\" android:textSize=\"18sp\" android:layout_above=\"@+id/spinner_algorithm\" android:layout_marginStart=\"10dp\" android:layout_marginBottom=\"25dp\" /> <Spinner android:layout_margin=\"5dp\" android:id=\"@+id/spinner_algorithm\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:layout_marginTop=\"18dp\" /> </RelativeLayout>", "e": 15902, "s": 14983, "text": null }, { "code": null, "e": 18460, "s": 15902, "text": "Now add the following code in the MainActivity.java file. Here AlgorithmAdapter class object is made and it acts as an adapter for the spinner and add onItemSelectedListner() to our spinner. When the user tap on any item of the spinner, it gets invoked. It shows a toast with the name of the item that user selected from the list.MainActivity.javaMainActivity.javapackage org.geeksforgeeks.gfgcustomspinner; import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.AdapterView;import android.widget.Spinner;import android.widget.Toast;import java.util.ArrayList; public class MainActivity extends AppCompatActivity { ArrayList<AlgorithmItem> algorithmItems; AlgorithmAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initList(); Spinner spinner = findViewById(R.id.spinner_algorithm); // we pass our item list and context to our Adapter. adapter = new AlgorithmAdapter(this, algorithmItems); spinner.setAdapter(adapter); spinner.setOnItemSelectedListener( new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // It returns the clicked item. AlgorithmItem clickedItem = (AlgorithmItem) parent.getItemAtPosition(position); String name = clickedItem.getAlgorithmName(); Toast.makeText(MainActivity.this, name + \" selected\", Toast.LENGTH_SHORT).show(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } // It is used to set the algorithm names to our array list. private void initList() { algorithmItems = new ArrayList<>(); algorithmItems.add(new AlgorithmItem(\"Quick Sort\")); algorithmItems.add(new AlgorithmItem(\"Merge Sort\")); algorithmItems.add(new AlgorithmItem(\"Heap Sort\")); algorithmItems.add(new AlgorithmItem(\"Prims Algorithm\")); algorithmItems.add(new AlgorithmItem(\"Kruskal Algorithm\")); algorithmItems.add(new AlgorithmItem(\"Rabin Karp\")); algorithmItems.add(new AlgorithmItem(\"Binary Search\")); }}" }, { "code": null, "e": 18478, "s": 18460, "text": "MainActivity.java" }, { "code": "package org.geeksforgeeks.gfgcustomspinner; import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.AdapterView;import android.widget.Spinner;import android.widget.Toast;import java.util.ArrayList; public class MainActivity extends AppCompatActivity { ArrayList<AlgorithmItem> algorithmItems; AlgorithmAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initList(); Spinner spinner = findViewById(R.id.spinner_algorithm); // we pass our item list and context to our Adapter. adapter = new AlgorithmAdapter(this, algorithmItems); spinner.setAdapter(adapter); spinner.setOnItemSelectedListener( new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // It returns the clicked item. AlgorithmItem clickedItem = (AlgorithmItem) parent.getItemAtPosition(position); String name = clickedItem.getAlgorithmName(); Toast.makeText(MainActivity.this, name + \" selected\", Toast.LENGTH_SHORT).show(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } // It is used to set the algorithm names to our array list. private void initList() { algorithmItems = new ArrayList<>(); algorithmItems.add(new AlgorithmItem(\"Quick Sort\")); algorithmItems.add(new AlgorithmItem(\"Merge Sort\")); algorithmItems.add(new AlgorithmItem(\"Heap Sort\")); algorithmItems.add(new AlgorithmItem(\"Prims Algorithm\")); algorithmItems.add(new AlgorithmItem(\"Kruskal Algorithm\")); algorithmItems.add(new AlgorithmItem(\"Rabin Karp\")); algorithmItems.add(new AlgorithmItem(\"Binary Search\")); }}", "e": 20672, "s": 18478, "text": null }, { "code": null, "e": 20680, "s": 20672, "text": "Output:" }, { "code": null, "e": 20688, "s": 20680, "text": "android" }, { "code": null, "e": 20693, "s": 20688, "text": "Java" }, { "code": null, "e": 20698, "s": 20693, "text": "Java" }, { "code": null, "e": 20796, "s": 20698, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 20815, "s": 20796, "text": "Interfaces in Java" }, { "code": null, "e": 20833, "s": 20815, "text": "ArrayList in Java" }, { "code": null, "e": 20853, "s": 20833, "text": "Collections in Java" }, { "code": null, "e": 20868, "s": 20853, "text": "Stream In Java" }, { "code": null, "e": 20900, "s": 20868, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 20920, "s": 20900, "text": "Stack Class in Java" }, { "code": null, "e": 20944, "s": 20920, "text": "Singleton Class in Java" }, { "code": null, "e": 20956, "s": 20944, "text": "Set in Java" }, { "code": null, "e": 20977, "s": 20956, "text": "Introduction to Java" } ]
How to Create Toggle Switch by using HTML and CSS ?
18 May, 2022 To create a toggle switch, we will use HTML and CSS. If you want to add a more attractive toggle switch then you can add sliding animation, bouncing effect, etc. In this article, we will divide the whole thing into two different sections structure creating and designing the structure. Creating Structure: In this section, we will just create a basic structure for the toggle button. Here all we need to put a checkbox and a label to create in an HTML document like below. We can do that by using the HTML label tag and HTML input type = checkbox. HTML code: The HTML code is used to create a structure of toggle switch. Since it does not contain CSS so it is just a simple structure. We will use some CSS property to make it attractive responsive. HTML <!DOCTYPE html><html> <head> <title>toggle switch</title></head> <body> <center> <h1>GeeksforGeeks</h1> <b>Toggle switch with HTML and CSS</b> <br><br> <input type="checkbox" id="switch" class="checkbox" /> <label for="switch" class="toggle"> <p>OFF ON</p> </label> </center></body> </html> Designing Structure: In the previous section, we have created the structure of the toggle switch. We will design the switch and make that responsive in this section. CSS code: CSS code is used to make an attractive HTML component. This CSS property is used to make the style on the toggle switch. CSS <style> h1 { color: green; } /* toggle in label designing */ .toggle { position : relative ; display : inline-block; width : 100px; height : 52px; background-color: red; border-radius: 30px; border: 2px solid gray; } /* After slide changes */ .toggle:after { content: ''; position: absolute; width: 50px; height: 50px; border-radius: 50%; background-color: gray; top: 1px; left: 1px; transition: all 0.5s; } /* Toggle text */ p { font-family: Arial, Helvetica, sans-serif; font-weight: bold; } /* Checkbox checked effect */ .checkbox:checked + .toggle::after { left : 49px; } /* Checkbox checked toggle label bg color */ .checkbox:checked + .toggle { background-color: green; } /* Checkbox vanished */ .checkbox { display : none; }</style> Combining HTML and CSS Code: This is the final code that is the combination of the above two sections. It will be displaying the toggle switch. HTML <!DOCTYPE html><html> <head> <title>toggle switch</title> <style> h1 { color: green; } /* toggle in label designing */ .toggle { position : relative ; display : inline-block; width : 100px; height : 52px; background-color: red; border-radius: 30px; border: 2px solid gray; } /* After slide changes */ .toggle:after { content: ''; position: absolute; width: 50px; height: 50px; border-radius: 50%; background-color: gray; top: 1px; left: 1px; transition: all 0.5s; } /* Toggle text */ p { font-family: Arial, Helvetica, sans-serif; font-weight: bold; } /* Checkbox checked effect */ .checkbox:checked + .toggle::after { left : 49px; } /* Checkbox checked toggle label bg color */ .checkbox:checked + .toggle { background-color: green; } /* Checkbox vanished */ .checkbox { display : none; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <b>Toggle switch with HTML and CSS</b> <br><br> <input type="checkbox" id="switch" class="checkbox" /> <label for="switch" class="toggle"> <p>OFF ON</p> </label> </center></body> </html> Output: HTML and CSS both are foundation of webpages. HTML is used for webpage development by structuring websites, web apps and CSS used for styling websites and webapps. You can learn more about HTML and CSS from the links given below: HTML Tutorial and HTML Examples. CSS Tutorial and CSS Examples. sweetyty hardikkoriintern CSS-Misc HTML-Misc CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? CSS to put icon inside an input element in a form How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? REST API (Introduction) Hide or show elements in HTML using display property
[ { "code": null, "e": 54, "s": 26, "text": "\n18 May, 2022" }, { "code": null, "e": 340, "s": 54, "text": "To create a toggle switch, we will use HTML and CSS. If you want to add a more attractive toggle switch then you can add sliding animation, bouncing effect, etc. In this article, we will divide the whole thing into two different sections structure creating and designing the structure." }, { "code": null, "e": 602, "s": 340, "text": "Creating Structure: In this section, we will just create a basic structure for the toggle button. Here all we need to put a checkbox and a label to create in an HTML document like below. We can do that by using the HTML label tag and HTML input type = checkbox." }, { "code": null, "e": 803, "s": 602, "text": "HTML code: The HTML code is used to create a structure of toggle switch. Since it does not contain CSS so it is just a simple structure. We will use some CSS property to make it attractive responsive." }, { "code": null, "e": 808, "s": 803, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>toggle switch</title></head> <body> <center> <h1>GeeksforGeeks</h1> <b>Toggle switch with HTML and CSS</b> <br><br> <input type=\"checkbox\" id=\"switch\" class=\"checkbox\" /> <label for=\"switch\" class=\"toggle\"> <p>OFF ON</p> </label> </center></body> </html>", "e": 1189, "s": 808, "text": null }, { "code": null, "e": 1356, "s": 1189, "text": " Designing Structure: In the previous section, we have created the structure of the toggle switch. We will design the switch and make that responsive in this section." }, { "code": null, "e": 1487, "s": 1356, "text": "CSS code: CSS code is used to make an attractive HTML component. This CSS property is used to make the style on the toggle switch." }, { "code": null, "e": 1491, "s": 1487, "text": "CSS" }, { "code": "<style> h1 { color: green; } /* toggle in label designing */ .toggle { position : relative ; display : inline-block; width : 100px; height : 52px; background-color: red; border-radius: 30px; border: 2px solid gray; } /* After slide changes */ .toggle:after { content: ''; position: absolute; width: 50px; height: 50px; border-radius: 50%; background-color: gray; top: 1px; left: 1px; transition: all 0.5s; } /* Toggle text */ p { font-family: Arial, Helvetica, sans-serif; font-weight: bold; } /* Checkbox checked effect */ .checkbox:checked + .toggle::after { left : 49px; } /* Checkbox checked toggle label bg color */ .checkbox:checked + .toggle { background-color: green; } /* Checkbox vanished */ .checkbox { display : none; }</style>", "e": 2512, "s": 1491, "text": null }, { "code": null, "e": 2656, "s": 2512, "text": "Combining HTML and CSS Code: This is the final code that is the combination of the above two sections. It will be displaying the toggle switch." }, { "code": null, "e": 2661, "s": 2656, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>toggle switch</title> <style> h1 { color: green; } /* toggle in label designing */ .toggle { position : relative ; display : inline-block; width : 100px; height : 52px; background-color: red; border-radius: 30px; border: 2px solid gray; } /* After slide changes */ .toggle:after { content: ''; position: absolute; width: 50px; height: 50px; border-radius: 50%; background-color: gray; top: 1px; left: 1px; transition: all 0.5s; } /* Toggle text */ p { font-family: Arial, Helvetica, sans-serif; font-weight: bold; } /* Checkbox checked effect */ .checkbox:checked + .toggle::after { left : 49px; } /* Checkbox checked toggle label bg color */ .checkbox:checked + .toggle { background-color: green; } /* Checkbox vanished */ .checkbox { display : none; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <b>Toggle switch with HTML and CSS</b> <br><br> <input type=\"checkbox\" id=\"switch\" class=\"checkbox\" /> <label for=\"switch\" class=\"toggle\"> <p>OFF ON</p> </label> </center></body> </html>", "e": 4267, "s": 2661, "text": null }, { "code": null, "e": 4276, "s": 4267, "text": "Output: " }, { "code": null, "e": 4506, "s": 4276, "text": "HTML and CSS both are foundation of webpages. HTML is used for webpage development by structuring websites, web apps and CSS used for styling websites and webapps. You can learn more about HTML and CSS from the links given below:" }, { "code": null, "e": 4539, "s": 4506, "text": "HTML Tutorial and HTML Examples." }, { "code": null, "e": 4570, "s": 4539, "text": "CSS Tutorial and CSS Examples." }, { "code": null, "e": 4579, "s": 4570, "text": "sweetyty" }, { "code": null, "e": 4596, "s": 4579, "text": "hardikkoriintern" }, { "code": null, "e": 4605, "s": 4596, "text": "CSS-Misc" }, { "code": null, "e": 4615, "s": 4605, "text": "HTML-Misc" }, { "code": null, "e": 4619, "s": 4615, "text": "CSS" }, { "code": null, "e": 4624, "s": 4619, "text": "HTML" }, { "code": null, "e": 4641, "s": 4624, "text": "Web Technologies" }, { "code": null, "e": 4646, "s": 4641, "text": "HTML" }, { "code": null, "e": 4744, "s": 4646, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4792, "s": 4744, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 4854, "s": 4792, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4904, "s": 4854, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 4962, "s": 4904, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 5012, "s": 4962, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 5060, "s": 5012, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 5122, "s": 5060, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 5172, "s": 5122, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 5196, "s": 5172, "text": "REST API (Introduction)" } ]
Logger info(String) method in Java with Examples
11 Jan, 2022 The info() method of a Logger class is used to Log an INFO message. This method is used to forward logs to all the registered output Handler objects. INFO message: Info is for the use of administrators or advanced users. It denotes mostly the actions that have led to a change in state for the application. There are two types of info() method depending upon no of parameters passed. 1. info(String msg): This method is used to forward the string passed as a parameter to method to all the registered output Handler objects. Syntax: public void info(String msg) Parameters: This method accepts a single parameter String which is the information we want to pass to logs. Return value: This method returns nothing. Below programs illustrate the info(String msg) method: Program 1: Java // Java program to demonstrate// Logger.info(String msg) method import java.util.logging.Logger; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // Call info method logger.info("This is message 1"); logger.info("This is message 2"); logger.info("This is message 3"); logger.info("This is message 4"); }} The output printed on eclipse ide is shown below. Output: Program 2: Java // Java program to demonstrate// Logger.info(String msg) method import java.util.logging.Logger; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger .getLogger("com.api.jar"); // Call info method logger.info("Welcome to gfg"); logger.info("google of codes"); }} The output printed on IDE is shown below. Output: 2. info(Supplier msgSupplier): This method is used Log an INFO message, constructed only if the logging level is such that the message will actually be logged. It means If the logger is enabled for the INFO message level then the message is constructed by invoking the provided supplier function and forwarded to all the registered output Handler objects. Syntax: public void info(Supplier msgSupplier) Parameters: This method accepts a single parameter msgSupplier which is a function, which when called, produces the desired log message. Return value: This method returns nothing. Below programs illustrate info(String msg) method: Program 1: Java // Java program to demonstrate// Logger.info(Supplier) method import java.util.logging.Logger;import java.util.function.Supplier; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // Create a supplier<String> method Supplier<String> StrSupplier = () -> new String("Logger logs"); // Call info(Supplier<String>) logger.info(StrSupplier); }} The output printed on eclipse ide is shown below. Output: References: https://docs.oracle.com/javase/10/docs/api/java/util/logging/Logger.html#info(java.lang.String) https://docs.oracle.com/javase/10/docs/api/java/util/logging/Logger.html#info(java.util.function.Supplier) adnanirshad158 Java - util package Java-Functions Java-Logger Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Jan, 2022" }, { "code": null, "e": 178, "s": 28, "text": "The info() method of a Logger class is used to Log an INFO message. This method is used to forward logs to all the registered output Handler objects." }, { "code": null, "e": 335, "s": 178, "text": "INFO message: Info is for the use of administrators or advanced users. It denotes mostly the actions that have led to a change in state for the application." }, { "code": null, "e": 413, "s": 335, "text": "There are two types of info() method depending upon no of parameters passed. " }, { "code": null, "e": 554, "s": 413, "text": "1. info(String msg): This method is used to forward the string passed as a parameter to method to all the registered output Handler objects." }, { "code": null, "e": 563, "s": 554, "text": "Syntax: " }, { "code": null, "e": 592, "s": 563, "text": "public void info(String msg)" }, { "code": null, "e": 700, "s": 592, "text": "Parameters: This method accepts a single parameter String which is the information we want to pass to logs." }, { "code": null, "e": 743, "s": 700, "text": "Return value: This method returns nothing." }, { "code": null, "e": 798, "s": 743, "text": "Below programs illustrate the info(String msg) method:" }, { "code": null, "e": 810, "s": 798, "text": "Program 1: " }, { "code": null, "e": 815, "s": 810, "text": "Java" }, { "code": "// Java program to demonstrate// Logger.info(String msg) method import java.util.logging.Logger; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // Call info method logger.info(\"This is message 1\"); logger.info(\"This is message 2\"); logger.info(\"This is message 3\"); logger.info(\"This is message 4\"); }}", "e": 1303, "s": 815, "text": null }, { "code": null, "e": 1354, "s": 1303, "text": "The output printed on eclipse ide is shown below. " }, { "code": null, "e": 1363, "s": 1354, "text": "Output: " }, { "code": null, "e": 1375, "s": 1363, "text": "Program 2: " }, { "code": null, "e": 1380, "s": 1375, "text": "Java" }, { "code": "// Java program to demonstrate// Logger.info(String msg) method import java.util.logging.Logger; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger .getLogger(\"com.api.jar\"); // Call info method logger.info(\"Welcome to gfg\"); logger.info(\"google of codes\"); }}", "e": 1777, "s": 1380, "text": null }, { "code": null, "e": 1820, "s": 1777, "text": "The output printed on IDE is shown below. " }, { "code": null, "e": 1829, "s": 1820, "text": "Output: " }, { "code": null, "e": 2185, "s": 1829, "text": "2. info(Supplier msgSupplier): This method is used Log an INFO message, constructed only if the logging level is such that the message will actually be logged. It means If the logger is enabled for the INFO message level then the message is constructed by invoking the provided supplier function and forwarded to all the registered output Handler objects." }, { "code": null, "e": 2194, "s": 2185, "text": "Syntax: " }, { "code": null, "e": 2233, "s": 2194, "text": "public void info(Supplier msgSupplier)" }, { "code": null, "e": 2370, "s": 2233, "text": "Parameters: This method accepts a single parameter msgSupplier which is a function, which when called, produces the desired log message." }, { "code": null, "e": 2413, "s": 2370, "text": "Return value: This method returns nothing." }, { "code": null, "e": 2465, "s": 2413, "text": "Below programs illustrate info(String msg) method: " }, { "code": null, "e": 2477, "s": 2465, "text": "Program 1: " }, { "code": null, "e": 2482, "s": 2477, "text": "Java" }, { "code": "// Java program to demonstrate// Logger.info(Supplier) method import java.util.logging.Logger;import java.util.function.Supplier; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // Create a supplier<String> method Supplier<String> StrSupplier = () -> new String(\"Logger logs\"); // Call info(Supplier<String>) logger.info(StrSupplier); }}", "e": 3011, "s": 2482, "text": null }, { "code": null, "e": 3062, "s": 3011, "text": "The output printed on eclipse ide is shown below. " }, { "code": null, "e": 3071, "s": 3062, "text": "Output: " }, { "code": null, "e": 3084, "s": 3071, "text": "References: " }, { "code": null, "e": 3180, "s": 3084, "text": "https://docs.oracle.com/javase/10/docs/api/java/util/logging/Logger.html#info(java.lang.String)" }, { "code": null, "e": 3287, "s": 3180, "text": "https://docs.oracle.com/javase/10/docs/api/java/util/logging/Logger.html#info(java.util.function.Supplier)" }, { "code": null, "e": 3304, "s": 3289, "text": "adnanirshad158" }, { "code": null, "e": 3324, "s": 3304, "text": "Java - util package" }, { "code": null, "e": 3339, "s": 3324, "text": "Java-Functions" }, { "code": null, "e": 3351, "s": 3339, "text": "Java-Logger" }, { "code": null, "e": 3356, "s": 3351, "text": "Java" }, { "code": null, "e": 3361, "s": 3356, "text": "Java" } ]
Katana Framework – Hacking Framework in Kali Linux
24 Jun, 2021 The Katana Framework is a free and open-source tool available on GitHub. This is a framework similar to Metasploitable 1 and Metasploitable 2, which makes it easy to use. The katana framework is written in python. This means you must have python installed in your Kali Linux operating system. This framework is developed to make penetration testing easy and simple to perform experiments. Using this tool, you can perform experiments of penetration testing. This tool unifies all the tools that are used for penetration testing. The Katana Framework has its own command to enter as an input. This tool provides a command-line interface. Using this tool, you can find Admin Panels, perform Sniffing, establish Backdoors on remote servers. The Katana Framework is written in python. The Katana Framework is similar to Metasploitable 1 and Metasploitable 2, which makes it easy to use. The Katana Framework is developed for performing penetration testing, easy and simple to perform experiments. The Katana Framework has its own command to enter as an input. The Katana Framework tool provides a command-line interface. Using this tool, you can find Admin Panels, perform Sniffing, establish Backdoors on remote servers. Nmap aircrack-ng arpspoof mysql ssh dhcpd hostapd ettercap xterm default-jre Step 1: Open your kali linux and install the tool using the following command. git clone https://github.com/PowerScript/KatanaFramework.git Step 2: The tool has been downloaded and now use the following command to move in the directory of the framework. cd KatanaFramework Step 3: Now you have to install the dependencies of the tool using the following command. sudo sh dependencies Step 4: Now use the following command to install the tool. sudo python install Step 5: The tool is running successfully. Example 1: Use the katana framework to initialize the console of katana. ktf.console Example 2: Use the katana framework to show modules. showm These are the modules present in the katana framework. Example 3: Use the katana framework to show option modules and find the admin panel. use web/ap.finder set target www.geeksforgeeks.com run The tool has started and will give you admin panel information about the target domain. You can also use this module for your own target domain. Kali-Linux Linux-Tools Linux-Unix 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": 768, "s": 28, "text": "The Katana Framework is a free and open-source tool available on GitHub. This is a framework similar to Metasploitable 1 and Metasploitable 2, which makes it easy to use. The katana framework is written in python. This means you must have python installed in your Kali Linux operating system. This framework is developed to make penetration testing easy and simple to perform experiments. Using this tool, you can perform experiments of penetration testing. This tool unifies all the tools that are used for penetration testing. The Katana Framework has its own command to enter as an input. This tool provides a command-line interface. Using this tool, you can find Admin Panels, perform Sniffing, establish Backdoors on remote servers. " }, { "code": null, "e": 811, "s": 768, "text": "The Katana Framework is written in python." }, { "code": null, "e": 913, "s": 811, "text": "The Katana Framework is similar to Metasploitable 1 and Metasploitable 2, which makes it easy to use." }, { "code": null, "e": 1023, "s": 913, "text": "The Katana Framework is developed for performing penetration testing, easy and simple to perform experiments." }, { "code": null, "e": 1086, "s": 1023, "text": "The Katana Framework has its own command to enter as an input." }, { "code": null, "e": 1248, "s": 1086, "text": "The Katana Framework tool provides a command-line interface. Using this tool, you can find Admin Panels, perform Sniffing, establish Backdoors on remote servers." }, { "code": null, "e": 1253, "s": 1248, "text": "Nmap" }, { "code": null, "e": 1265, "s": 1253, "text": "aircrack-ng" }, { "code": null, "e": 1275, "s": 1265, "text": "arpspoof " }, { "code": null, "e": 1282, "s": 1275, "text": "mysql " }, { "code": null, "e": 1287, "s": 1282, "text": "ssh " }, { "code": null, "e": 1293, "s": 1287, "text": "dhcpd" }, { "code": null, "e": 1301, "s": 1293, "text": "hostapd" }, { "code": null, "e": 1310, "s": 1301, "text": "ettercap" }, { "code": null, "e": 1317, "s": 1310, "text": "xterm " }, { "code": null, "e": 1329, "s": 1317, "text": "default-jre" }, { "code": null, "e": 1408, "s": 1329, "text": "Step 1: Open your kali linux and install the tool using the following command." }, { "code": null, "e": 1469, "s": 1408, "text": "git clone https://github.com/PowerScript/KatanaFramework.git" }, { "code": null, "e": 1583, "s": 1469, "text": "Step 2: The tool has been downloaded and now use the following command to move in the directory of the framework." }, { "code": null, "e": 1602, "s": 1583, "text": "cd KatanaFramework" }, { "code": null, "e": 1692, "s": 1602, "text": "Step 3: Now you have to install the dependencies of the tool using the following command." }, { "code": null, "e": 1713, "s": 1692, "text": "sudo sh dependencies" }, { "code": null, "e": 1772, "s": 1713, "text": "Step 4: Now use the following command to install the tool." }, { "code": null, "e": 1792, "s": 1772, "text": "sudo python install" }, { "code": null, "e": 1834, "s": 1792, "text": "Step 5: The tool is running successfully." }, { "code": null, "e": 1907, "s": 1834, "text": "Example 1: Use the katana framework to initialize the console of katana." }, { "code": null, "e": 1919, "s": 1907, "text": "ktf.console" }, { "code": null, "e": 1972, "s": 1919, "text": "Example 2: Use the katana framework to show modules." }, { "code": null, "e": 1978, "s": 1972, "text": "showm" }, { "code": null, "e": 2033, "s": 1978, "text": "These are the modules present in the katana framework." }, { "code": null, "e": 2118, "s": 2033, "text": "Example 3: Use the katana framework to show option modules and find the admin panel." }, { "code": null, "e": 2173, "s": 2118, "text": "use web/ap.finder\nset target www.geeksforgeeks.com\nrun" }, { "code": null, "e": 2318, "s": 2173, "text": "The tool has started and will give you admin panel information about the target domain. You can also use this module for your own target domain." }, { "code": null, "e": 2329, "s": 2318, "text": "Kali-Linux" }, { "code": null, "e": 2341, "s": 2329, "text": "Linux-Tools" }, { "code": null, "e": 2352, "s": 2341, "text": "Linux-Unix" } ]
Given n appointments, find all conflicting appointments
24 Jun, 2022 Given n appointments, find all conflicting appointments. Examples: Input: appointments[] = { {1, 5} {3, 7}, {2, 6}, {10, 15}, {5, 6}, {4, 100}} Output: Following are conflicting intervals [3,7] Conflicts with [1,5] [2,6] Conflicts with [1,5] [5,6] Conflicts with [3,7] [4,100] Conflicts with [1,5] An appointment is conflicting if it conflicts with any of the previous appointments in the array. We strongly recommend to minimize the browser and try this yourself first. A Simple Solution is to one by one process all appointments from the second appointment to last. For every appointment i, check if it conflicts with i-1, i-2, ... 0. The time complexity of this method is O(n2). We can use Interval Tree to solve this problem in O(nLogn) time. Following is a detailed algorithm. Create an Interval Tree, initially with the first appointment.Do following for all other appointments starting from the second one.Check if the current appointment conflicts with any of the existing appointments in Interval Tree. If conflicts, then print the current appointment. This step can be done O(Logn) time.nsert the current appointment in Interval Tree. This step also can be done O(Logn) time. Create an Interval Tree, initially with the first appointment. Do following for all other appointments starting from the second one.Check if the current appointment conflicts with any of the existing appointments in Interval Tree. If conflicts, then print the current appointment. This step can be done O(Logn) time.nsert the current appointment in Interval Tree. This step also can be done O(Logn) time. Check if the current appointment conflicts with any of the existing appointments in Interval Tree. If conflicts, then print the current appointment. This step can be done O(Logn) time.nsert the current appointment in Interval Tree. This step also can be done O(Logn) time. Check if the current appointment conflicts with any of the existing appointments in Interval Tree. If conflicts, then print the current appointment. This step can be done O(Logn) time. nsert the current appointment in Interval Tree. This step also can be done O(Logn) time. Following is the implementation of the above idea. C++ Java Python3 C# Javascript // C++ program to print all conflicting appointments in a// given set of appointments#include <bits/stdc++.h>using namespace std; // Structure to represent an intervalstruct Interval{ int low, high;}; // Structure to represent a node in Interval Search Treestruct ITNode{ Interval *i; // 'i' could also be a normal variable int max; ITNode *left, *right;}; // A utility function to create a new Interval Search Tree NodeITNode * newNode(Interval i){ ITNode *temp = new ITNode; temp->i = new Interval(i); temp->max = i.high; temp->left = temp->right = NULL; return temp;}; // A utility function to insert a new Interval Search Tree// Node. This is similar to BST Insert. Here the low value// of interval is used tomaintain BST propertyITNode *insert(ITNode *root, Interval i){ // Base case: Tree is empty, new node becomes root if (root == NULL) return newNode(i); // Get low value of interval at root int l = root->i->low; // If root's low value is smaller, then new interval // goes to left subtree if (i.low < l) root->left = insert(root->left, i); // Else, new node goes to right subtree. else root->right = insert(root->right, i); // Update the max value of this ancestor if needed if (root->max < i.high) root->max = i.high; return root;} // A utility function to check if given two intervals overlapbool doOVerlap(Interval i1, Interval i2){ if (i1.low < i2.high && i2.low < i1.high) return true; return false;} // The main function that searches a given interval i// in a given Interval Tree.Interval *overlapSearch(ITNode *root, Interval i){ // Base Case, tree is empty if (root == NULL) return NULL; // If given interval overlaps with root if (doOVerlap(*(root->i), i)) return root->i; // If left child of root is present and max of left child // is greater than or equal to given interval, then i may // overlap with an interval is left subtree if (root->left != NULL && root->left->max >= i.low) return overlapSearch(root->left, i); // Else interval can only overlap with right subtree return overlapSearch(root->right, i);} // This function prints all conflicting appointments in a given// array of appointments.void printConflicting(Interval appt[], int n){ // Create an empty Interval Search Tree, add first // appointment ITNode *root = NULL; root = insert(root, appt[0]); // Process rest of the intervals for (int i=1; i<n; i++) { // If current appointment conflicts with any of the // existing intervals, print it Interval *res = overlapSearch(root, appt[i]); if (res != NULL) cout << "[" << appt[i].low << "," << appt[i].high << "] Conflicts with [" << res->low << "," << res->high << "]\n"; // Insert this appointment root = insert(root, appt[i]); }} // Driver program to test above functionsint main(){ // Let us create interval tree shown in above figure Interval appt[] = { {1, 5}, {3, 7}, {2, 6}, {10, 15}, {5, 6}, {4, 100}}; int n = sizeof(appt)/sizeof(appt[0]); cout << "Following are conflicting intervals\n"; printConflicting(appt, n); return 0;} // Java program to print all conflicting// appointments in a given set of appointmentsclass GfG{ // Structure to represent an intervalstatic class Interval{ int low, high;} static class ITNode{ // 'i' could also be a normal variable Interval i; int max; ITNode left, right;} // A utility function to create a new nodestatic Interval newNode(int l, int h){ Interval temp = new Interval(); temp.low = l; temp.high = h; return temp;} // A utility function to create a new nodestatic ITNode newNode(Interval i){ ITNode temp = new ITNode(); temp.i = i; temp.max = i.high; temp.left = temp.right = null; return temp;} // A utility function to insert a new// Interval Search Tree Node. This is// similar to BST Insert. Here the// low value of interval is used to// maintain BST propertystatic ITNode insert(ITNode root, Interval i){ // Base case: Tree is empty, // new node becomes root if (root == null) return newNode(i); // Get low value of interval at root int l = root.i.low; // If root's low value is smaller, // then new interval goes to left subtree if (i.low < l) root.left = insert(root.left, i); // Else, new node goes to right subtree. else root.right = insert(root.right, i); // Update the max value of this // ancestor if needed if (root.max < i.high) root.max = i.high; return root;} // A utility function to check if given// two intervals overlapstatic boolean doOVerlap(Interval i1, Interval i2){ if (i1.low < i2.high && i2.low < i1.high) return true; return false;} // The main function that searches a given// interval i in a given Interval Tree.static Interval overlapSearch(ITNode root, Interval i){ // Base Case, tree is empty if (root == null) return null; // If given interval overlaps with root if (doOVerlap(root.i, i)) return root.i; // If left child of root is present // and max of left child is greater // than or equal to given interval, // then i may overlap with an interval // is left subtree if (root.left != null && root.left.max >= i.low) return overlapSearch(root.left, i); // Else interval can only // overlap with right subtree return overlapSearch(root.right, i);} // This function prints all conflicting// appointments in a given array of appointments.static void printConflicting(Interval appt[], int n){ // Create an empty Interval Search // Tree, add first appointment ITNode root = null; root = insert(root, appt[0]); // Process rest of the intervals for(int i = 1; i < n; i++) { // If current appointment conflicts // with any of the existing intervals, // print it Interval res = overlapSearch(root, appt[i]); if (res != null) System.out.print("[" + appt[i].low + "," + appt[i].high + "] Conflicts with [" + res.low + "," + res.high + "]\n"); // Insert this appointment root = insert(root, appt[i]); }} // Driver codepublic static void main(String[] args){ Interval appt[] = new Interval[6]; appt[0] = newNode(1, 5); appt[1] = newNode(3, 7); appt[2] = newNode(2, 6); appt[3] = newNode(10, 15); appt[4] = newNode(5, 6); appt[5] = newNode(4, 100); int n = appt.length; System.out.print( "Following are conflicting intervals\n"); printConflicting(appt, n);}} // This code is contributed by tushar_bansal # Python3 program to print all conflicting# appointments in a given set of appointments # Structure to represent an intervalclass Interval: def __init__(self): self.low = None self.high = None # Structure to represent a node# in Interval Search Treeclass ITNode: def __init__(self): self.max = None self.i = None self.left = None self.right = None def newNode(j): #print(j) temp = ITNode() temp.i = j temp.max = j[1] return temp # A utility function to check if# given two intervals overlapdef doOVerlap(i1, i2): if (i1[0] < i2[1] and i2[0] < i1[1]): return True return False # Function to create a new nodedef insert(node, data): global succ # If the tree is empty, return a new node root = node if (node == None): return newNode(data) # If key is smaller than root's key, go to left # subtree and set successor as current node # print(node) if (data[0] < node.i[0]): # print(node) root.left = insert(node.left, data) # Go to right subtree else: root.right = insert(node.right, data) if root.max < data[1]: root.max = data[1] return root # The main function that searches a given# interval i in a given Interval Tree.def overlapSearch(root, i): # Base Case, tree is empty if (root == None): return None # If given interval overlaps with root if (doOVerlap(root.i, i)): return root.i # If left child of root is present and # max of left child is greater than or # equal to given interval, then i may # overlap with an interval is left subtree if (root.left != None and root.left.max >= i[0]): return overlapSearch(root.left, i) # Else interval can only overlap # with right subtree return overlapSearch(root.right, i) # This function prints all conflicting# appointments in a given array of# appointments.def printConflicting(appt, n): # Create an empty Interval Search Tree, # add first appointment root = None root = insert(root, appt[0]) # Process rest of the intervals for i in range(1, n): # If current appointment conflicts # with any of the existing intervals, # print it res = overlapSearch(root, appt[i]) if (res != None): print("[", appt[i][0], ",", appt[i][1], "] Conflicts with [", res[0], ",", res[1], "]") # Insert this appointment root = insert(root, appt[i]) # Driver codeif __name__ == '__main__': # Let us create interval tree # shown in above figure appt = [ [ 1, 5 ], [ 3, 7 ], [ 2, 6 ], [ 10, 15 ], [ 5, 6 ], [ 4, 100 ] ] n = len(appt) print("Following are conflicting intervals") printConflicting(appt, n) # This code is contributed by mohit kumar 29 // C# program to print all conflicting// appointments in a given set of appointmentsusing System;public class GfG{ // Structure to represent an intervalpublicclass Interval{ publicint low, high;}publicclass ITNode{ // 'i' could also be a normal variable public Interval i; public int max; publicITNode left, right;} // A utility function to create a new nodestatic Interval newNode(int l, int h){ Interval temp = new Interval(); temp.low = l; temp.high = h; return temp;} // A utility function to create a new nodestatic ITNode newNode(Interval i){ ITNode temp = new ITNode(); temp.i = i; temp.max = i.high; temp.left = temp.right = null; return temp;} // A utility function to insert a new// Interval Search Tree Node. This is// similar to BST Insert. Here the// low value of interval is used to// maintain BST propertystatic ITNode insert(ITNode root, Interval i){ // Base case: Tree is empty, // new node becomes root if (root == null) return newNode(i); // Get low value of interval at root int l = root.i.low; // If root's low value is smaller, // then new interval goes to left subtree if (i.low < l) root.left = insert(root.left, i); // Else, new node goes to right subtree. else root.right = insert(root.right, i); // Update the max value of this // ancestor if needed if (root.max < i.high) root.max = i.high; return root;} // A utility function to check if given// two intervals overlapstatic bool doOVerlap(Interval i1, Interval i2){ if (i1.low < i2.high && i2.low < i1.high) return true; return false;} // The main function that searches a given// interval i in a given Interval Tree.static Interval overlapSearch(ITNode root, Interval i){ // Base Case, tree is empty if (root == null) return null; // If given interval overlaps with root if (doOVerlap(root.i, i)) return root.i; // If left child of root is present // and max of left child is greater // than or equal to given interval, // then i may overlap with an interval // is left subtree if (root.left != null && root.left.max >= i.low) return overlapSearch(root.left, i); // Else interval can only // overlap with right subtree return overlapSearch(root.right, i);} // This function prints all conflicting// appointments in a given array of appointments.static void printConflicting(Interval []appt, int n){ // Create an empty Interval Search // Tree, add first appointment ITNode root = null; root = insert(root, appt[0]); // Process rest of the intervals for(int i = 1; i < n; i++) { // If current appointment conflicts // with any of the existing intervals, // print it Interval res = overlapSearch(root, appt[i]); if (res != null) Console.Write("[" + appt[i].low + "," + appt[i].high + "] Conflicts with [" + res.low + "," + res.high + "]\n"); // Insert this appointment root = insert(root, appt[i]); }} // Driver codepublic static void Main(String[] args){ Interval []appt = new Interval[6]; appt[0] = newNode(1, 5); appt[1] = newNode(3, 7); appt[2] = newNode(2, 6); appt[3] = newNode(10, 15); appt[4] = newNode(5, 6); appt[5] = newNode(4, 100); int n = appt.Length; Console.Write( "Following are conflicting intervals\n"); printConflicting(appt, n);}} // This code is contributed by gauravrajput1 <script> // Javascript program to print all conflicting// appointments in a given set of appointments // Structure to represent an intervalclass Interval{ constructor() { this.low = 0; this.high = 0; }} class ITNode{ // 'i' could also be a normal variable constructor() { this.max = 0; this.left = null; this.right = null; this.i = null; }} // A utility function to create a new nodefunction newNodeDouble(l, h){ var temp = new Interval(); temp.low = l; temp.high = h; return temp;} // A utility function to create a new nodefunction newNodeSingle(i){ var temp = new ITNode(); temp.i = i; temp.max = i.high; temp.left = temp.right = null; return temp;} // A utility function to insert a new// Interval Search Tree Node. This is// similar to BST Insert. Here the// low value of interval is used to// maintain BST propertyfunction insert(root, i){ // Base case: Tree is empty, // new node becomes root if (root == null) return newNodeSingle(i); // Get low value of interval at root var l = root.i.low; // If root's low value is smaller, // then new interval goes to left subtree if (i.low < l) root.left = insert(root.left, i); // Else, new node goes to right subtree. else root.right = insert(root.right, i); // Update the max value of this // ancestor if needed if (root.max < i.high) root.max = i.high; return root;} // A utility function to check if given// two intervals overlapfunction doOVerlap(i1, i2){ if (i1.low < i2.high && i2.low < i1.high) return true; return false;} // The main function that searches a given// interval i in a given Interval Tree.function overlapSearch(root, i){ // Base Case, tree is empty if (root == null) return null; // If given interval overlaps with root if (doOVerlap(root.i, i)) return root.i; // If left child of root is present // and max of left child is greater // than or equal to given interval, // then i may overlap with an interval // is left subtree if (root.left != null && root.left.max >= i.low) return overlapSearch(root.left, i); // Else interval can only // overlap with right subtree return overlapSearch(root.right, i);} // This function prints all conflicting// appointments in a given array of appointments.function printConflicting(appt, n){ // Create an empty Interval Search // Tree, add first appointment var root = null; root = insert(root, appt[0]); // Process rest of the intervals for(var i = 1; i < n; i++) { // If current appointment conflicts // with any of the existing intervals, // print it var res = overlapSearch(root, appt[i]); if (res != null) document.write("[" + appt[i].low + "," + appt[i].high + "] Conflicts with [" + res.low + "," + res.high + "]<br>"); // Insert this appointment root = insert(root, appt[i]); }} // Driver codevar appt = Array(6);appt[0] = newNodeDouble(1, 5);appt[1] = newNodeDouble(3, 7);appt[2] = newNodeDouble(2, 6);appt[3] = newNodeDouble(10, 15);appt[4] = newNodeDouble(5, 6);appt[5] = newNodeDouble(4, 100); var n = appt.length;document.write( "Following are conflicting intervals<br>");printConflicting(appt, n); </script> Following are conflicting intervals [3,7] Conflicts with [1,5] [2,6] Conflicts with [1,5] [5,6] Conflicts with [3,7] [4,100] Conflicts with [1,5] Note that the above implementation uses a simple Binary Search Tree insert operations. Therefore, the time complexity of the above implementation is more than O(nLogn). We can use Red-Black Tree or AVL Tree balancing techniques to make the above implementation O(nLogn). This article is contributed by Anmol. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above mysticpeaks mohit kumar 29 GauravRajput1 rutvik_56 mathuriarajatkumar surindertarika1234 hardikkoriintern Binary Search Tree Binary Search Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. set vs unordered_set in C++ STL Flatten BST to sorted list | Increasing order Count BST nodes that lie in a given range Find median of BST in O(n) time and O(1) space Largest BST in a Binary Tree | Set 2 Replace every element with the least greater element on its right Convert BST to Min Heap Floor and Ceil from a BST Common operations on various Data Structures Find the largest BST subtree in a given Binary Tree | Set 3
[ { "code": null, "e": 52, "s": 24, "text": "\n24 Jun, 2022" }, { "code": null, "e": 110, "s": 52, "text": "Given n appointments, find all conflicting appointments. " }, { "code": null, "e": 120, "s": 110, "text": "Examples:" }, { "code": null, "e": 351, "s": 120, "text": "Input: appointments[] = { {1, 5} {3, 7}, {2, 6}, {10, 15}, {5, 6}, {4, 100}}\nOutput: Following are conflicting intervals\n[3,7] Conflicts with [1,5]\n[2,6] Conflicts with [1,5]\n[5,6] Conflicts with [3,7]\n[4,100] Conflicts with [1,5]" }, { "code": null, "e": 449, "s": 351, "text": "An appointment is conflicting if it conflicts with any of the previous appointments in the array." }, { "code": null, "e": 524, "s": 449, "text": "We strongly recommend to minimize the browser and try this yourself first." }, { "code": null, "e": 836, "s": 524, "text": "A Simple Solution is to one by one process all appointments from the second appointment to last. For every appointment i, check if it conflicts with i-1, i-2, ... 0. The time complexity of this method is O(n2). We can use Interval Tree to solve this problem in O(nLogn) time. Following is a detailed algorithm. " }, { "code": null, "e": 1243, "s": 836, "text": "Create an Interval Tree, initially with the first appointment.Do following for all other appointments starting from the second one.Check if the current appointment conflicts with any of the existing appointments in Interval Tree. If conflicts, then print the current appointment. This step can be done O(Logn) time.nsert the current appointment in Interval Tree. This step also can be done O(Logn) time." }, { "code": null, "e": 1306, "s": 1243, "text": "Create an Interval Tree, initially with the first appointment." }, { "code": null, "e": 1651, "s": 1306, "text": "Do following for all other appointments starting from the second one.Check if the current appointment conflicts with any of the existing appointments in Interval Tree. If conflicts, then print the current appointment. This step can be done O(Logn) time.nsert the current appointment in Interval Tree. This step also can be done O(Logn) time." }, { "code": null, "e": 1927, "s": 1651, "text": "Check if the current appointment conflicts with any of the existing appointments in Interval Tree. If conflicts, then print the current appointment. This step can be done O(Logn) time.nsert the current appointment in Interval Tree. This step also can be done O(Logn) time." }, { "code": null, "e": 2115, "s": 1927, "text": "Check if the current appointment conflicts with any of the existing appointments in Interval Tree. If conflicts, then print the current appointment. This step can be done O(Logn) time." }, { "code": null, "e": 2204, "s": 2115, "text": "nsert the current appointment in Interval Tree. This step also can be done O(Logn) time." }, { "code": null, "e": 2255, "s": 2204, "text": "Following is the implementation of the above idea." }, { "code": null, "e": 2259, "s": 2255, "text": "C++" }, { "code": null, "e": 2264, "s": 2259, "text": "Java" }, { "code": null, "e": 2272, "s": 2264, "text": "Python3" }, { "code": null, "e": 2275, "s": 2272, "text": "C#" }, { "code": null, "e": 2286, "s": 2275, "text": "Javascript" }, { "code": "// C++ program to print all conflicting appointments in a// given set of appointments#include <bits/stdc++.h>using namespace std; // Structure to represent an intervalstruct Interval{ int low, high;}; // Structure to represent a node in Interval Search Treestruct ITNode{ Interval *i; // 'i' could also be a normal variable int max; ITNode *left, *right;}; // A utility function to create a new Interval Search Tree NodeITNode * newNode(Interval i){ ITNode *temp = new ITNode; temp->i = new Interval(i); temp->max = i.high; temp->left = temp->right = NULL; return temp;}; // A utility function to insert a new Interval Search Tree// Node. This is similar to BST Insert. Here the low value// of interval is used tomaintain BST propertyITNode *insert(ITNode *root, Interval i){ // Base case: Tree is empty, new node becomes root if (root == NULL) return newNode(i); // Get low value of interval at root int l = root->i->low; // If root's low value is smaller, then new interval // goes to left subtree if (i.low < l) root->left = insert(root->left, i); // Else, new node goes to right subtree. else root->right = insert(root->right, i); // Update the max value of this ancestor if needed if (root->max < i.high) root->max = i.high; return root;} // A utility function to check if given two intervals overlapbool doOVerlap(Interval i1, Interval i2){ if (i1.low < i2.high && i2.low < i1.high) return true; return false;} // The main function that searches a given interval i// in a given Interval Tree.Interval *overlapSearch(ITNode *root, Interval i){ // Base Case, tree is empty if (root == NULL) return NULL; // If given interval overlaps with root if (doOVerlap(*(root->i), i)) return root->i; // If left child of root is present and max of left child // is greater than or equal to given interval, then i may // overlap with an interval is left subtree if (root->left != NULL && root->left->max >= i.low) return overlapSearch(root->left, i); // Else interval can only overlap with right subtree return overlapSearch(root->right, i);} // This function prints all conflicting appointments in a given// array of appointments.void printConflicting(Interval appt[], int n){ // Create an empty Interval Search Tree, add first // appointment ITNode *root = NULL; root = insert(root, appt[0]); // Process rest of the intervals for (int i=1; i<n; i++) { // If current appointment conflicts with any of the // existing intervals, print it Interval *res = overlapSearch(root, appt[i]); if (res != NULL) cout << \"[\" << appt[i].low << \",\" << appt[i].high << \"] Conflicts with [\" << res->low << \",\" << res->high << \"]\\n\"; // Insert this appointment root = insert(root, appt[i]); }} // Driver program to test above functionsint main(){ // Let us create interval tree shown in above figure Interval appt[] = { {1, 5}, {3, 7}, {2, 6}, {10, 15}, {5, 6}, {4, 100}}; int n = sizeof(appt)/sizeof(appt[0]); cout << \"Following are conflicting intervals\\n\"; printConflicting(appt, n); return 0;}", "e": 5588, "s": 2286, "text": null }, { "code": "// Java program to print all conflicting// appointments in a given set of appointmentsclass GfG{ // Structure to represent an intervalstatic class Interval{ int low, high;} static class ITNode{ // 'i' could also be a normal variable Interval i; int max; ITNode left, right;} // A utility function to create a new nodestatic Interval newNode(int l, int h){ Interval temp = new Interval(); temp.low = l; temp.high = h; return temp;} // A utility function to create a new nodestatic ITNode newNode(Interval i){ ITNode temp = new ITNode(); temp.i = i; temp.max = i.high; temp.left = temp.right = null; return temp;} // A utility function to insert a new// Interval Search Tree Node. This is// similar to BST Insert. Here the// low value of interval is used to// maintain BST propertystatic ITNode insert(ITNode root, Interval i){ // Base case: Tree is empty, // new node becomes root if (root == null) return newNode(i); // Get low value of interval at root int l = root.i.low; // If root's low value is smaller, // then new interval goes to left subtree if (i.low < l) root.left = insert(root.left, i); // Else, new node goes to right subtree. else root.right = insert(root.right, i); // Update the max value of this // ancestor if needed if (root.max < i.high) root.max = i.high; return root;} // A utility function to check if given// two intervals overlapstatic boolean doOVerlap(Interval i1, Interval i2){ if (i1.low < i2.high && i2.low < i1.high) return true; return false;} // The main function that searches a given// interval i in a given Interval Tree.static Interval overlapSearch(ITNode root, Interval i){ // Base Case, tree is empty if (root == null) return null; // If given interval overlaps with root if (doOVerlap(root.i, i)) return root.i; // If left child of root is present // and max of left child is greater // than or equal to given interval, // then i may overlap with an interval // is left subtree if (root.left != null && root.left.max >= i.low) return overlapSearch(root.left, i); // Else interval can only // overlap with right subtree return overlapSearch(root.right, i);} // This function prints all conflicting// appointments in a given array of appointments.static void printConflicting(Interval appt[], int n){ // Create an empty Interval Search // Tree, add first appointment ITNode root = null; root = insert(root, appt[0]); // Process rest of the intervals for(int i = 1; i < n; i++) { // If current appointment conflicts // with any of the existing intervals, // print it Interval res = overlapSearch(root, appt[i]); if (res != null) System.out.print(\"[\" + appt[i].low + \",\" + appt[i].high + \"] Conflicts with [\" + res.low + \",\" + res.high + \"]\\n\"); // Insert this appointment root = insert(root, appt[i]); }} // Driver codepublic static void main(String[] args){ Interval appt[] = new Interval[6]; appt[0] = newNode(1, 5); appt[1] = newNode(3, 7); appt[2] = newNode(2, 6); appt[3] = newNode(10, 15); appt[4] = newNode(5, 6); appt[5] = newNode(4, 100); int n = appt.length; System.out.print( \"Following are conflicting intervals\\n\"); printConflicting(appt, n);}} // This code is contributed by tushar_bansal", "e": 9284, "s": 5588, "text": null }, { "code": "# Python3 program to print all conflicting# appointments in a given set of appointments # Structure to represent an intervalclass Interval: def __init__(self): self.low = None self.high = None # Structure to represent a node# in Interval Search Treeclass ITNode: def __init__(self): self.max = None self.i = None self.left = None self.right = None def newNode(j): #print(j) temp = ITNode() temp.i = j temp.max = j[1] return temp # A utility function to check if# given two intervals overlapdef doOVerlap(i1, i2): if (i1[0] < i2[1] and i2[0] < i1[1]): return True return False # Function to create a new nodedef insert(node, data): global succ # If the tree is empty, return a new node root = node if (node == None): return newNode(data) # If key is smaller than root's key, go to left # subtree and set successor as current node # print(node) if (data[0] < node.i[0]): # print(node) root.left = insert(node.left, data) # Go to right subtree else: root.right = insert(node.right, data) if root.max < data[1]: root.max = data[1] return root # The main function that searches a given# interval i in a given Interval Tree.def overlapSearch(root, i): # Base Case, tree is empty if (root == None): return None # If given interval overlaps with root if (doOVerlap(root.i, i)): return root.i # If left child of root is present and # max of left child is greater than or # equal to given interval, then i may # overlap with an interval is left subtree if (root.left != None and root.left.max >= i[0]): return overlapSearch(root.left, i) # Else interval can only overlap # with right subtree return overlapSearch(root.right, i) # This function prints all conflicting# appointments in a given array of# appointments.def printConflicting(appt, n): # Create an empty Interval Search Tree, # add first appointment root = None root = insert(root, appt[0]) # Process rest of the intervals for i in range(1, n): # If current appointment conflicts # with any of the existing intervals, # print it res = overlapSearch(root, appt[i]) if (res != None): print(\"[\", appt[i][0], \",\", appt[i][1], \"] Conflicts with [\", res[0], \",\", res[1], \"]\") # Insert this appointment root = insert(root, appt[i]) # Driver codeif __name__ == '__main__': # Let us create interval tree # shown in above figure appt = [ [ 1, 5 ], [ 3, 7 ], [ 2, 6 ], [ 10, 15 ], [ 5, 6 ], [ 4, 100 ] ] n = len(appt) print(\"Following are conflicting intervals\") printConflicting(appt, n) # This code is contributed by mohit kumar 29", "e": 12260, "s": 9284, "text": null }, { "code": "// C# program to print all conflicting// appointments in a given set of appointmentsusing System;public class GfG{ // Structure to represent an intervalpublicclass Interval{ publicint low, high;}publicclass ITNode{ // 'i' could also be a normal variable public Interval i; public int max; publicITNode left, right;} // A utility function to create a new nodestatic Interval newNode(int l, int h){ Interval temp = new Interval(); temp.low = l; temp.high = h; return temp;} // A utility function to create a new nodestatic ITNode newNode(Interval i){ ITNode temp = new ITNode(); temp.i = i; temp.max = i.high; temp.left = temp.right = null; return temp;} // A utility function to insert a new// Interval Search Tree Node. This is// similar to BST Insert. Here the// low value of interval is used to// maintain BST propertystatic ITNode insert(ITNode root, Interval i){ // Base case: Tree is empty, // new node becomes root if (root == null) return newNode(i); // Get low value of interval at root int l = root.i.low; // If root's low value is smaller, // then new interval goes to left subtree if (i.low < l) root.left = insert(root.left, i); // Else, new node goes to right subtree. else root.right = insert(root.right, i); // Update the max value of this // ancestor if needed if (root.max < i.high) root.max = i.high; return root;} // A utility function to check if given// two intervals overlapstatic bool doOVerlap(Interval i1, Interval i2){ if (i1.low < i2.high && i2.low < i1.high) return true; return false;} // The main function that searches a given// interval i in a given Interval Tree.static Interval overlapSearch(ITNode root, Interval i){ // Base Case, tree is empty if (root == null) return null; // If given interval overlaps with root if (doOVerlap(root.i, i)) return root.i; // If left child of root is present // and max of left child is greater // than or equal to given interval, // then i may overlap with an interval // is left subtree if (root.left != null && root.left.max >= i.low) return overlapSearch(root.left, i); // Else interval can only // overlap with right subtree return overlapSearch(root.right, i);} // This function prints all conflicting// appointments in a given array of appointments.static void printConflicting(Interval []appt, int n){ // Create an empty Interval Search // Tree, add first appointment ITNode root = null; root = insert(root, appt[0]); // Process rest of the intervals for(int i = 1; i < n; i++) { // If current appointment conflicts // with any of the existing intervals, // print it Interval res = overlapSearch(root, appt[i]); if (res != null) Console.Write(\"[\" + appt[i].low + \",\" + appt[i].high + \"] Conflicts with [\" + res.low + \",\" + res.high + \"]\\n\"); // Insert this appointment root = insert(root, appt[i]); }} // Driver codepublic static void Main(String[] args){ Interval []appt = new Interval[6]; appt[0] = newNode(1, 5); appt[1] = newNode(3, 7); appt[2] = newNode(2, 6); appt[3] = newNode(10, 15); appt[4] = newNode(5, 6); appt[5] = newNode(4, 100); int n = appt.Length; Console.Write( \"Following are conflicting intervals\\n\"); printConflicting(appt, n);}} // This code is contributed by gauravrajput1", "e": 15971, "s": 12260, "text": null }, { "code": "<script> // Javascript program to print all conflicting// appointments in a given set of appointments // Structure to represent an intervalclass Interval{ constructor() { this.low = 0; this.high = 0; }} class ITNode{ // 'i' could also be a normal variable constructor() { this.max = 0; this.left = null; this.right = null; this.i = null; }} // A utility function to create a new nodefunction newNodeDouble(l, h){ var temp = new Interval(); temp.low = l; temp.high = h; return temp;} // A utility function to create a new nodefunction newNodeSingle(i){ var temp = new ITNode(); temp.i = i; temp.max = i.high; temp.left = temp.right = null; return temp;} // A utility function to insert a new// Interval Search Tree Node. This is// similar to BST Insert. Here the// low value of interval is used to// maintain BST propertyfunction insert(root, i){ // Base case: Tree is empty, // new node becomes root if (root == null) return newNodeSingle(i); // Get low value of interval at root var l = root.i.low; // If root's low value is smaller, // then new interval goes to left subtree if (i.low < l) root.left = insert(root.left, i); // Else, new node goes to right subtree. else root.right = insert(root.right, i); // Update the max value of this // ancestor if needed if (root.max < i.high) root.max = i.high; return root;} // A utility function to check if given// two intervals overlapfunction doOVerlap(i1, i2){ if (i1.low < i2.high && i2.low < i1.high) return true; return false;} // The main function that searches a given// interval i in a given Interval Tree.function overlapSearch(root, i){ // Base Case, tree is empty if (root == null) return null; // If given interval overlaps with root if (doOVerlap(root.i, i)) return root.i; // If left child of root is present // and max of left child is greater // than or equal to given interval, // then i may overlap with an interval // is left subtree if (root.left != null && root.left.max >= i.low) return overlapSearch(root.left, i); // Else interval can only // overlap with right subtree return overlapSearch(root.right, i);} // This function prints all conflicting// appointments in a given array of appointments.function printConflicting(appt, n){ // Create an empty Interval Search // Tree, add first appointment var root = null; root = insert(root, appt[0]); // Process rest of the intervals for(var i = 1; i < n; i++) { // If current appointment conflicts // with any of the existing intervals, // print it var res = overlapSearch(root, appt[i]); if (res != null) document.write(\"[\" + appt[i].low + \",\" + appt[i].high + \"] Conflicts with [\" + res.low + \",\" + res.high + \"]<br>\"); // Insert this appointment root = insert(root, appt[i]); }} // Driver codevar appt = Array(6);appt[0] = newNodeDouble(1, 5);appt[1] = newNodeDouble(3, 7);appt[2] = newNodeDouble(2, 6);appt[3] = newNodeDouble(10, 15);appt[4] = newNodeDouble(5, 6);appt[5] = newNodeDouble(4, 100); var n = appt.length;document.write( \"Following are conflicting intervals<br>\");printConflicting(appt, n); </script>", "e": 19521, "s": 15971, "text": null }, { "code": null, "e": 19667, "s": 19521, "text": "Following are conflicting intervals\n[3,7] Conflicts with [1,5]\n[2,6] Conflicts with [1,5]\n[5,6] Conflicts with [3,7]\n[4,100] Conflicts with [1,5]" }, { "code": null, "e": 19938, "s": 19667, "text": "Note that the above implementation uses a simple Binary Search Tree insert operations. Therefore, the time complexity of the above implementation is more than O(nLogn). We can use Red-Black Tree or AVL Tree balancing techniques to make the above implementation O(nLogn)." }, { "code": null, "e": 20100, "s": 19938, "text": "This article is contributed by Anmol. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 20112, "s": 20100, "text": "mysticpeaks" }, { "code": null, "e": 20127, "s": 20112, "text": "mohit kumar 29" }, { "code": null, "e": 20141, "s": 20127, "text": "GauravRajput1" }, { "code": null, "e": 20151, "s": 20141, "text": "rutvik_56" }, { "code": null, "e": 20170, "s": 20151, "text": "mathuriarajatkumar" }, { "code": null, "e": 20189, "s": 20170, "text": "surindertarika1234" }, { "code": null, "e": 20206, "s": 20189, "text": "hardikkoriintern" }, { "code": null, "e": 20225, "s": 20206, "text": "Binary Search Tree" }, { "code": null, "e": 20244, "s": 20225, "text": "Binary Search Tree" }, { "code": null, "e": 20342, "s": 20244, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 20374, "s": 20342, "text": "set vs unordered_set in C++ STL" }, { "code": null, "e": 20420, "s": 20374, "text": "Flatten BST to sorted list | Increasing order" }, { "code": null, "e": 20462, "s": 20420, "text": "Count BST nodes that lie in a given range" }, { "code": null, "e": 20509, "s": 20462, "text": "Find median of BST in O(n) time and O(1) space" }, { "code": null, "e": 20546, "s": 20509, "text": "Largest BST in a Binary Tree | Set 2" }, { "code": null, "e": 20612, "s": 20546, "text": "Replace every element with the least greater element on its right" }, { "code": null, "e": 20636, "s": 20612, "text": "Convert BST to Min Heap" }, { "code": null, "e": 20662, "s": 20636, "text": "Floor and Ceil from a BST" }, { "code": null, "e": 20707, "s": 20662, "text": "Common operations on various Data Structures" } ]
Minimum number of bombs
26 May, 2022 There are aliens in n buildings (minimum of 1 in each) and you have to kill all of them minimum number of bombings. Buildings are numbered as 1 – n. Aliens in a bombed building gets injured at the first bombing and die at the second. When a building is bombed for the first time, aliens in that building try to escape to the nearest building (for first building the nearest one is the second one and for nth building it is n-1). Calculate the minimum number of bombs required to kill all the aliens and the order of bombings. Example: Input: 3 Output: 4 2 1 3 2 Explanation: Minimum number of bombs required are 4. First bomb the 2nd building, aliens will move to 1st or 3rd to save themselves. Then bomb at 1st building, if some aliens have moved from 2nd building to 1st they will be killed and the 1st building aliens will be injured, and they will move to the 2nd building as it is nearest to them. Now, bomb at the 3rd building to kill aliens who moved from the 2nd building to 3rd and injure 3rd building aliens so they move to 2nd building as it is nearest to them. Now, bomb at the 2nd building again and all aliens who moved from 1st or 3rd building will be killed. Input: 2 Output: 3 2 1 2 We can make a constructive way to kill all aliens. Since everyone either moves to the left or to the right, we have to make sure that all the even positions are attacked, once at the start to injure aliens and the other time at the end. When we attack aliens at the even positions first time they move to the odd position buildings, so attack them at odd to kill all the previous even positions and injure the odd position aliens. The odd position aliens get injured and will move to the even position, so attack them at the even at the end to kill them. The number of ways will be n/2 + n/2 + n/2 which is n + n/2. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // CPP program to find number of bombings required// to kill all aliens.#include <bits/stdc++.h>using namespace std; // function to print where to shootvoid print(int n){ // no. of bombs required cout << n + n / 2 << endl; // bomb all the even positions for (int i = 2; i <= n; i += 2) cout << i << " "; // bomb all the odd positions for (int i = 1; i <= n; i += 2) cout << i << " "; // bomb all the even positions again for (int i = 2; i <= n; i += 2) cout << i << " ";} // driver programint main(){ int n = 3; print(n); return 0;} // Java program to find number of bombings// required to kill all aliens.class GFG { // function to print where to shoot static void print(int n) { // no. of bombs required System.out.println(n + n / 2); // bomb all the even positions for (int i = 2; i <= n; i += 2) System.out.print( i + " "); // bomb all the odd positions for (int i = 1; i <= n; i += 2) System.out.print(i + " "); // bomb all the even positions again for (int i = 2; i <= n; i += 2) System.out.print( i + " "); } // Driver code public static void main (String[] args) { int n = 3; print(n); }} // This code is contributed by Anant Agarwal. """Python program to find number ofbombings required to kill all aliens""" # function to print where to shootdef bomb_required(n): # no. of bombs required print(n+n // 2) # bomb all the even positions for i in range(2, n + 1, 2): print(i, end = " ") # bomb all the odd positions for i in range(1, n + 1, 2): print(i, end = " ") # bomb all the even positions again for i in range(2, n, 2): print(i, end = " ") # Driver Code bomb_required(3) # This code is contributed by Abhishek Agrawal. // C# program to find number of bombings// required to kill all aliens.using System; class GFG { // function to print where to shoot static void print(int n) { // no. of bombs required Console.WriteLine(n + n / 2); // bomb all the even positions for (int i = 2; i <= n; i += 2) Console.Write( i + " "); // bomb all the odd positions for (int i = 1; i <= n; i += 2) Console.Write(i + " "); // bomb all the even positions // again for (int i = 2; i <= n; i += 2) Console.Write( i + " "); } // Driver code public static void Main () { int n = 3; print(n); }} // This code is contributed by vt_m. <?php// PHP program to find number// of bombings required to// kill all aliens. // function to print// where to shootfunction p_rint($n){ // no. of bombs required echo floor($n + $n / 2),"\n" ; // bomb all the even positions for ($i = 2; $i <= $n; $i += 2) echo $i ," "; // bomb all the odd positions for ( $i = 1; $i <= $n; $i += 2) echo $i , " "; // bomb all the even positions again for ( $i = 2; $i <= $n; $i += 2) echo $i , " ";} // Driver Code $n = 3; p_rint($n); // This code is contributed by anuj_67.?> <script>// javascript program to find number of bombings// required to kill all aliens. // function to print where to shoot function print(n) { // no. of bombs required document.write(n + parseInt(n / 2) + "<br/>"); // bomb all the even positions for (i = 2; i <= n; i += 2) document.write(i + " "); // bomb all the odd positions for (i = 1; i <= n; i += 2) document.write(i + " "); // bomb all the even positions again for (i = 2; i <= n; i += 2) document.write(i + " "); } // Driver code var n = 3; print(n); // This code is contributed by Rajput-Ji</script> Output: 4 2 1 3 2 Time complexity: O(n) Auxiliary Space: O(1) This article is contributed by Raj. 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. vt_m Rajput-Ji ankita_saini shivamanandrj9 programming-puzzle Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Operators in C / C++ Prime Numbers Sieve of Eratosthenes Program to find GCD or HCF of two numbers Algorithm to solve Rubik's Cube Modulo 10^9+7 (1000000007) The Knight's tour problem | Backtracking-1 Program for Decimal to Binary Conversion Modulo Operator (%) in C/C++ with Examples
[ { "code": null, "e": 54, "s": 26, "text": "\n26 May, 2022" }, { "code": null, "e": 591, "s": 54, "text": "There are aliens in n buildings (minimum of 1 in each) and you have to kill all of them minimum number of bombings. Buildings are numbered as 1 – n. Aliens in a bombed building gets injured at the first bombing and die at the second. When a building is bombed for the first time, aliens in that building try to escape to the nearest building (for first building the nearest one is the second one and for nth building it is n-1). Calculate the minimum number of bombs required to kill all the aliens and the order of bombings. Example: " }, { "code": null, "e": 1478, "s": 591, "text": "Input: 3\nOutput: 4 \n 2 1 3 2 \nExplanation: Minimum number of bombs required are 4.\n First bomb the 2nd building, aliens \n will move to 1st or 3rd to save\n themselves. Then bomb at 1st building, \n if some aliens have moved from 2nd \n building to 1st they will be killed and\n the 1st building aliens will be injured,\n and they will move to the 2nd building\n as it is nearest to them. Now, bomb at\n the 3rd building to kill aliens who \n moved from the 2nd building to 3rd and\n injure 3rd building aliens so they move \n to 2nd building as it is nearest to them.\n Now, bomb at the 2nd building again and\n all aliens who moved from 1st or 3rd\n building will be killed.\n\nInput: 2\nOutput: 3\n 2 1 2 " }, { "code": null, "e": 2149, "s": 1480, "text": "We can make a constructive way to kill all aliens. Since everyone either moves to the left or to the right, we have to make sure that all the even positions are attacked, once at the start to injure aliens and the other time at the end. When we attack aliens at the even positions first time they move to the odd position buildings, so attack them at odd to kill all the previous even positions and injure the odd position aliens. The odd position aliens get injured and will move to the even position, so attack them at the even at the end to kill them. The number of ways will be n/2 + n/2 + n/2 which is n + n/2. Below is the implementation of the above approach: " }, { "code": null, "e": 2153, "s": 2149, "text": "C++" }, { "code": null, "e": 2158, "s": 2153, "text": "Java" }, { "code": null, "e": 2166, "s": 2158, "text": "Python3" }, { "code": null, "e": 2169, "s": 2166, "text": "C#" }, { "code": null, "e": 2173, "s": 2169, "text": "PHP" }, { "code": null, "e": 2184, "s": 2173, "text": "Javascript" }, { "code": "// CPP program to find number of bombings required// to kill all aliens.#include <bits/stdc++.h>using namespace std; // function to print where to shootvoid print(int n){ // no. of bombs required cout << n + n / 2 << endl; // bomb all the even positions for (int i = 2; i <= n; i += 2) cout << i << \" \"; // bomb all the odd positions for (int i = 1; i <= n; i += 2) cout << i << \" \"; // bomb all the even positions again for (int i = 2; i <= n; i += 2) cout << i << \" \";} // driver programint main(){ int n = 3; print(n); return 0;}", "e": 2774, "s": 2184, "text": null }, { "code": "// Java program to find number of bombings// required to kill all aliens.class GFG { // function to print where to shoot static void print(int n) { // no. of bombs required System.out.println(n + n / 2); // bomb all the even positions for (int i = 2; i <= n; i += 2) System.out.print( i + \" \"); // bomb all the odd positions for (int i = 1; i <= n; i += 2) System.out.print(i + \" \"); // bomb all the even positions again for (int i = 2; i <= n; i += 2) System.out.print( i + \" \"); } // Driver code public static void main (String[] args) { int n = 3; print(n); }} // This code is contributed by Anant Agarwal.", "e": 3546, "s": 2774, "text": null }, { "code": "\"\"\"Python program to find number ofbombings required to kill all aliens\"\"\" # function to print where to shootdef bomb_required(n): # no. of bombs required print(n+n // 2) # bomb all the even positions for i in range(2, n + 1, 2): print(i, end = \" \") # bomb all the odd positions for i in range(1, n + 1, 2): print(i, end = \" \") # bomb all the even positions again for i in range(2, n, 2): print(i, end = \" \") # Driver Code bomb_required(3) # This code is contributed by Abhishek Agrawal.", "e": 4106, "s": 3546, "text": null }, { "code": "// C# program to find number of bombings// required to kill all aliens.using System; class GFG { // function to print where to shoot static void print(int n) { // no. of bombs required Console.WriteLine(n + n / 2); // bomb all the even positions for (int i = 2; i <= n; i += 2) Console.Write( i + \" \"); // bomb all the odd positions for (int i = 1; i <= n; i += 2) Console.Write(i + \" \"); // bomb all the even positions // again for (int i = 2; i <= n; i += 2) Console.Write( i + \" \"); } // Driver code public static void Main () { int n = 3; print(n); }} // This code is contributed by vt_m.", "e": 4859, "s": 4106, "text": null }, { "code": "<?php// PHP program to find number// of bombings required to// kill all aliens. // function to print// where to shootfunction p_rint($n){ // no. of bombs required echo floor($n + $n / 2),\"\\n\" ; // bomb all the even positions for ($i = 2; $i <= $n; $i += 2) echo $i ,\" \"; // bomb all the odd positions for ( $i = 1; $i <= $n; $i += 2) echo $i , \" \"; // bomb all the even positions again for ( $i = 2; $i <= $n; $i += 2) echo $i , \" \";} // Driver Code $n = 3; p_rint($n); // This code is contributed by anuj_67.?>", "e": 5435, "s": 4859, "text": null }, { "code": "<script>// javascript program to find number of bombings// required to kill all aliens. // function to print where to shoot function print(n) { // no. of bombs required document.write(n + parseInt(n / 2) + \"<br/>\"); // bomb all the even positions for (i = 2; i <= n; i += 2) document.write(i + \" \"); // bomb all the odd positions for (i = 1; i <= n; i += 2) document.write(i + \" \"); // bomb all the even positions again for (i = 2; i <= n; i += 2) document.write(i + \" \"); } // Driver code var n = 3; print(n); // This code is contributed by Rajput-Ji</script>", "e": 6118, "s": 5435, "text": null }, { "code": null, "e": 6128, "s": 6118, "text": "Output: " }, { "code": null, "e": 6138, "s": 6128, "text": "4\n2 1 3 2" }, { "code": null, "e": 6160, "s": 6138, "text": "Time complexity: O(n)" }, { "code": null, "e": 6182, "s": 6160, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 6594, "s": 6182, "text": "This article is contributed by Raj. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 6599, "s": 6594, "text": "vt_m" }, { "code": null, "e": 6609, "s": 6599, "text": "Rajput-Ji" }, { "code": null, "e": 6622, "s": 6609, "text": "ankita_saini" }, { "code": null, "e": 6637, "s": 6622, "text": "shivamanandrj9" }, { "code": null, "e": 6656, "s": 6637, "text": "programming-puzzle" }, { "code": null, "e": 6669, "s": 6656, "text": "Mathematical" }, { "code": null, "e": 6682, "s": 6669, "text": "Mathematical" }, { "code": null, "e": 6780, "s": 6682, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6804, "s": 6780, "text": "Merge two sorted arrays" }, { "code": null, "e": 6825, "s": 6804, "text": "Operators in C / C++" }, { "code": null, "e": 6839, "s": 6825, "text": "Prime Numbers" }, { "code": null, "e": 6861, "s": 6839, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 6903, "s": 6861, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 6935, "s": 6903, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 6962, "s": 6935, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 7005, "s": 6962, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 7046, "s": 7005, "text": "Program for Decimal to Binary Conversion" } ]
jQuery | slideUp() with Examples
13 Feb, 2019 The slideUp() is an inbuilt method in jQuery which is used to hide the selected elements.Syntax: $(selector).slideUp(speed); Parameter: It accepts an optional parameter “speed” which specifies the speed of the duration of the effect. Return Value: It does not return anything simply it hides the selected element. <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script> <!-- jQuery code to show the working of this method --> $(document).ready(function() { $(".btn1").click(function() { $("p").slideUp(); }); }); </script> <style> div { width: 300px; height: 100px; padding: 20px; border: 2px solid green; } </style></head> <body> <div> <p>This paragraph will get hide.</p> <!-- click on this button --> <button class="btn1">Slide up</button> </div></body> </html> Output :In the below video, working of this method has been shown. Code #2:In the below code, speeding parameter is passed to this method. <!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script> <!-- jQuery code to show the working of this method --> $(document).ready(function() { $(".btn1").click(function() { $("p").slideUp(3000); }); }); </script> <style> div { width: 300px; height: 100px; padding: 20px; border: 2px solid green; } </style></head> <body> <div> <p>This paragraph will get hide.</p> <!-- click on this button --> <button class="btn1">Slide up</button> </div></body> </html> Output :In the below video, the working of this method has been shown. jQuery-Effects JQuery 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": "\n13 Feb, 2019" }, { "code": null, "e": 125, "s": 28, "text": "The slideUp() is an inbuilt method in jQuery which is used to hide the selected elements.Syntax:" }, { "code": null, "e": 154, "s": 125, "text": "$(selector).slideUp(speed);\n" }, { "code": null, "e": 263, "s": 154, "text": "Parameter: It accepts an optional parameter “speed” which specifies the speed of the duration of the effect." }, { "code": null, "e": 343, "s": 263, "text": "Return Value: It does not return anything simply it hides the selected element." }, { "code": "<html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script> <!-- jQuery code to show the working of this method --> $(document).ready(function() { $(\".btn1\").click(function() { $(\"p\").slideUp(); }); }); </script> <style> div { width: 300px; height: 100px; padding: 20px; border: 2px solid green; } </style></head> <body> <div> <p>This paragraph will get hide.</p> <!-- click on this button --> <button class=\"btn1\">Slide up</button> </div></body> </html>", "e": 1019, "s": 343, "text": null }, { "code": null, "e": 1086, "s": 1019, "text": "Output :In the below video, working of this method has been shown." }, { "code": null, "e": 1158, "s": 1086, "text": "Code #2:In the below code, speeding parameter is passed to this method." }, { "code": "<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script> <!-- jQuery code to show the working of this method --> $(document).ready(function() { $(\".btn1\").click(function() { $(\"p\").slideUp(3000); }); }); </script> <style> div { width: 300px; height: 100px; padding: 20px; border: 2px solid green; } </style></head> <body> <div> <p>This paragraph will get hide.</p> <!-- click on this button --> <button class=\"btn1\">Slide up</button> </div></body> </html>", "e": 1853, "s": 1158, "text": null }, { "code": null, "e": 1924, "s": 1853, "text": "Output :In the below video, the working of this method has been shown." }, { "code": null, "e": 1939, "s": 1924, "text": "jQuery-Effects" }, { "code": null, "e": 1946, "s": 1939, "text": "JQuery" }, { "code": null, "e": 1963, "s": 1946, "text": "Web Technologies" } ]
Scala Char toInt() method with example
29 Oct, 2019 The toInt() method is utilized to convert a stated character into an integer or its ASCII value of type Int. Method Definition: def toInt: Int Return Type: It returns Integer or ASCII value of the corresponding character of type Int. Example: 1# // Scala program of toInt()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying toInt method val result = 'A'.toInt // Displays output println(result) }} 65 Example: 2# // Scala program of toInt()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying toInt method val result = '9'.toInt // Displays output println(result) }} 57 Scala Scala-Method Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Oct, 2019" }, { "code": null, "e": 137, "s": 28, "text": "The toInt() method is utilized to convert a stated character into an integer or its ASCII value of type Int." }, { "code": null, "e": 171, "s": 137, "text": "Method Definition: def toInt: Int" }, { "code": null, "e": 262, "s": 171, "text": "Return Type: It returns Integer or ASCII value of the corresponding character of type Int." }, { "code": null, "e": 274, "s": 262, "text": "Example: 1#" }, { "code": "// Scala program of toInt()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying toInt method val result = 'A'.toInt // Displays output println(result) }} ", "e": 540, "s": 274, "text": null }, { "code": null, "e": 544, "s": 540, "text": "65\n" }, { "code": null, "e": 556, "s": 544, "text": "Example: 2#" }, { "code": "// Scala program of toInt()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying toInt method val result = '9'.toInt // Displays output println(result) }} ", "e": 822, "s": 556, "text": null }, { "code": null, "e": 826, "s": 822, "text": "57\n" }, { "code": null, "e": 832, "s": 826, "text": "Scala" }, { "code": null, "e": 845, "s": 832, "text": "Scala-Method" }, { "code": null, "e": 851, "s": 845, "text": "Scala" } ]
Send Text messages to any mobile number using Fast2SMS API in Python
02 Sep, 2020 This article is going to be about how can we send text messages using Python. We will be using Fast2SMS API to send messages. You don’t need to install any Python package for this purpose. First, you need a Fast2SMS account. You can sign up for Fast2SMS from here. Now, go to Dev API option and copy the API Authorization Key. This API key is generated by Fast2SMS, however, you can regenerate the API key if you want to. Now, all you have to do is to make a POST request to Fast2SMS API with your API key, message, recipient, etc. and it will send your SMS. So, to make requests to the API, we need to use the requests module, and to read the data returned by the API, we need json module. So, first Let’s import them. Python3 # import required moduleimport requestsimport json Now, We will create two dictionaries, one for the SMS data and another for the headers. Python # mention urlurl = "https://www.fast2sms.com/dev/bulk" # create a dictionarymy_data = { # Your default Sender ID 'sender_id': 'FSTSMS', # Put your message here! 'message': 'This is a test message', 'language': 'english', 'route': 'p', # You can send sms to multiple numbers # separated by comma. 'numbers': '9999999999, 7777777777, 6666666666' } # create a dictionaryheaders = { 'authorization': 'YOUR API KEY HERE', 'Content-Type': "application/x-www-form-urlencoded", 'Cache-Control': "no-cache"} Now, we are ready to post our data to the API. Python3 # make a post requestresponse = requests.request("POST", url, data = my_data, headers = headers)#load json data from sourcereturned_msg = json.loads(response.text) # print the send messageprint(returned_msg['message']) Output: ['Message sent successfully to NonDND numbers'] If the message is sent successfully, It will print a success message. Your mobile number will be displayed to the recipient with your message. In case of an error, it will print the Error message. For example, if your API key is changed or you have entered the wrong API key, the following error message will be printed. Invalid Authentication, Check Authorization Key python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n02 Sep, 2020" }, { "code": null, "e": 241, "s": 52, "text": "This article is going to be about how can we send text messages using Python. We will be using Fast2SMS API to send messages. You don’t need to install any Python package for this purpose." }, { "code": null, "e": 611, "s": 241, "text": "First, you need a Fast2SMS account. You can sign up for Fast2SMS from here. Now, go to Dev API option and copy the API Authorization Key. This API key is generated by Fast2SMS, however, you can regenerate the API key if you want to. Now, all you have to do is to make a POST request to Fast2SMS API with your API key, message, recipient, etc. and it will send your SMS." }, { "code": null, "e": 772, "s": 611, "text": "So, to make requests to the API, we need to use the requests module, and to read the data returned by the API, we need json module. So, first Let’s import them." }, { "code": null, "e": 780, "s": 772, "text": "Python3" }, { "code": "# import required moduleimport requestsimport json", "e": 831, "s": 780, "text": null }, { "code": null, "e": 919, "s": 831, "text": "Now, We will create two dictionaries, one for the SMS data and another for the headers." }, { "code": null, "e": 926, "s": 919, "text": "Python" }, { "code": "# mention urlurl = \"https://www.fast2sms.com/dev/bulk\" # create a dictionarymy_data = { # Your default Sender ID 'sender_id': 'FSTSMS', # Put your message here! 'message': 'This is a test message', 'language': 'english', 'route': 'p', # You can send sms to multiple numbers # separated by comma. 'numbers': '9999999999, 7777777777, 6666666666' } # create a dictionaryheaders = { 'authorization': 'YOUR API KEY HERE', 'Content-Type': \"application/x-www-form-urlencoded\", 'Cache-Control': \"no-cache\"}", "e": 1484, "s": 926, "text": null }, { "code": null, "e": 1531, "s": 1484, "text": "Now, we are ready to post our data to the API." }, { "code": null, "e": 1539, "s": 1531, "text": "Python3" }, { "code": "# make a post requestresponse = requests.request(\"POST\", url, data = my_data, headers = headers)#load json data from sourcereturned_msg = json.loads(response.text) # print the send messageprint(returned_msg['message'])", "e": 1840, "s": 1539, "text": null }, { "code": null, "e": 1848, "s": 1840, "text": "Output:" }, { "code": null, "e": 1896, "s": 1848, "text": "['Message sent successfully to NonDND numbers']" }, { "code": null, "e": 2039, "s": 1896, "text": "If the message is sent successfully, It will print a success message. Your mobile number will be displayed to the recipient with your message." }, { "code": null, "e": 2093, "s": 2039, "text": "In case of an error, it will print the Error message." }, { "code": null, "e": 2217, "s": 2093, "text": "For example, if your API key is changed or you have entered the wrong API key, the following error message will be printed." }, { "code": null, "e": 2265, "s": 2217, "text": "Invalid Authentication, Check Authorization Key" }, { "code": null, "e": 2280, "s": 2265, "text": "python-utility" }, { "code": null, "e": 2287, "s": 2280, "text": "Python" } ]
numpy.arccos() in Python
29 Nov, 2018 numpy.arccos(x[, out]) = ufunc ‘arccos’) : This mathematical function helps user to calculate inverse cos for all x(being the array elements). Parameters : array : [array_like]elements are in radians. out : [array_like]array of same shape as x. Note : 2pi Radians = 360 degreesThe convention is to return the angle z whose real part lies in [0, pi]. Return : An array with inverse cosine of x for all x i.e. array elements. The values are in the closed interval [-pi/2, pi/2]. Code #1 : Working # Python program explaining# arccos() function import numpy as np in_array = [0, 1, 0.3, -1]print ("Input array : \n", in_array) arccos_Values = np.arccos(in_array)print ("\nInverse Cosine values : \n", arccos_Values) Output : Input array : [0, 1, 0.3, -1] Inverse Cosine values : [ 1.57079633 0. 1.26610367 3.14159265] Code #2 : Graphical representation # Python program showing# Graphical representation # of arccos() function import numpy as npimport matplotlib.pyplot as plt in_array = np.linspace(-np.pi, np.pi, 12)out_array1 = np.cos(in_array)out_array2 = np.arccos(in_array) print("in_array : ", in_array)print("\nout_array with cos : ", out_array1)print("\nout_arraywith arccos : ", out_array1) # red for numpy.arccos()plt.plot(in_array, out_array1, color = 'blue', marker = "*") plt.plot(in_array, out_array2, color = 'red', marker = "o") plt.title("blue : numpy.cos() \nred : numpy.arccos()")plt.xlabel("X")plt.ylabel("Y")plt.show() Output : in_array : [-3.14159265 -2.57039399 -1.99919533 -1.42799666 -0.856798 -0.28559933 0.28559933 0.856798 1.42799666 1.99919533 2.57039399 3.14159265] out_array with cos : [-1. -0.84125353 -0.41541501 0.14231484 0.65486073 0.95949297 0.95949297 0.65486073 0.14231484 -0.41541501 -0.84125353 -1. ] out_arraywith arccos : [-1. -0.84125353 -0.41541501 0.14231484 0.65486073 0.95949297 0.95949297 0.65486073 0.14231484 -0.41541501 -0.84125353 -1. ] RuntimeWarning: invalid value encountered in arccos out_array1 = np.sin(in_array) References :https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.arcsin.html#numpy.arccos. Python numpy-Mathematical Function Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Nov, 2018" }, { "code": null, "e": 171, "s": 28, "text": "numpy.arccos(x[, out]) = ufunc ‘arccos’) : This mathematical function helps user to calculate inverse cos for all x(being the array elements)." }, { "code": null, "e": 184, "s": 171, "text": "Parameters :" }, { "code": null, "e": 282, "s": 184, "text": "array : [array_like]elements are in radians.\nout : [array_like]array of same shape as x.\n" }, { "code": null, "e": 289, "s": 282, "text": "Note :" }, { "code": null, "e": 387, "s": 289, "text": "2pi Radians = 360 degreesThe convention is to return the angle z whose real part lies in [0, pi]." }, { "code": null, "e": 396, "s": 387, "text": "Return :" }, { "code": null, "e": 518, "s": 396, "text": "An array with inverse cosine of x \nfor all x i.e. array elements. \n\nThe values are in the closed interval [-pi/2, pi/2].\n" }, { "code": null, "e": 537, "s": 518, "text": " Code #1 : Working" }, { "code": "# Python program explaining# arccos() function import numpy as np in_array = [0, 1, 0.3, -1]print (\"Input array : \\n\", in_array) arccos_Values = np.arccos(in_array)print (\"\\nInverse Cosine values : \\n\", arccos_Values)", "e": 758, "s": 537, "text": null }, { "code": null, "e": 767, "s": 758, "text": "Output :" }, { "code": null, "e": 876, "s": 767, "text": "Input array : \n [0, 1, 0.3, -1]\n\nInverse Cosine values : \n [ 1.57079633 0. 1.26610367 3.14159265]" }, { "code": null, "e": 912, "s": 876, "text": " Code #2 : Graphical representation" }, { "code": "# Python program showing# Graphical representation # of arccos() function import numpy as npimport matplotlib.pyplot as plt in_array = np.linspace(-np.pi, np.pi, 12)out_array1 = np.cos(in_array)out_array2 = np.arccos(in_array) print(\"in_array : \", in_array)print(\"\\nout_array with cos : \", out_array1)print(\"\\nout_arraywith arccos : \", out_array1) # red for numpy.arccos()plt.plot(in_array, out_array1, color = 'blue', marker = \"*\") plt.plot(in_array, out_array2, color = 'red', marker = \"o\") plt.title(\"blue : numpy.cos() \\nred : numpy.arccos()\")plt.xlabel(\"X\")plt.ylabel(\"Y\")plt.show()", "e": 1553, "s": 912, "text": null }, { "code": null, "e": 1562, "s": 1553, "text": "Output :" }, { "code": null, "e": 2148, "s": 1562, "text": "\nin_array : [-3.14159265 -2.57039399 -1.99919533 -1.42799666 -0.856798 -0.28559933\n 0.28559933 0.856798 1.42799666 1.99919533 2.57039399 3.14159265]\n\nout_array with cos : [-1. -0.84125353 -0.41541501 0.14231484 0.65486073 0.95949297\n 0.95949297 0.65486073 0.14231484 -0.41541501 -0.84125353 -1. ]\n\nout_arraywith arccos : [-1. -0.84125353 -0.41541501 0.14231484 0.65486073 0.95949297\n 0.95949297 0.65486073 0.14231484 -0.41541501 -0.84125353 -1. ]\nRuntimeWarning: invalid value encountered in arccos\n out_array1 = np.sin(in_array)" }, { "code": null, "e": 2249, "s": 2148, "text": "References :https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.arcsin.html#numpy.arccos." }, { "code": null, "e": 2284, "s": 2249, "text": "Python numpy-Mathematical Function" }, { "code": null, "e": 2297, "s": 2284, "text": "Python-numpy" }, { "code": null, "e": 2304, "s": 2297, "text": "Python" }, { "code": null, "e": 2402, "s": 2304, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2420, "s": 2402, "text": "Python Dictionary" }, { "code": null, "e": 2462, "s": 2420, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2484, "s": 2462, "text": "Enumerate() in Python" }, { "code": null, "e": 2519, "s": 2484, "text": "Read a file line by line in Python" }, { "code": null, "e": 2545, "s": 2519, "text": "Python String | replace()" }, { "code": null, "e": 2577, "s": 2545, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2606, "s": 2577, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2633, "s": 2606, "text": "Python Classes and Objects" }, { "code": null, "e": 2663, "s": 2633, "text": "Iterate over a list in Python" } ]
Stack add(Object) method in Java with Example
24 Dec, 2018 The add(Object) method of Stack Class appends the specified element to the end of this Stack. Syntax: boolean add(Object element) Parameters: This function accepts a single parameter element as shown in the above syntax. The element specified by this parameter is appended to end of the Stack. Return Value: This method returns True after successful execution, else False. Below program illustrates the working of java.util.Stack.add(Object element) method: Example 1: // Java code to illustrate boolean add(Object element)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"); // Output the present Stack System.out.println("The Stack is: " + stack); // Adding new elements to the end stack.add("Last"); stack.add("Element"); // Printing the new Stack System.out.println("The new Stack is: " + stack); }} The Stack is: [Geeks, for, Geeks, 10, 20] The new Stack is: [Geeks, for, Geeks, 10, 20, Last, Element] Example 2: // Java code to illustrate// boolean add(Object element) import java.util.*; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<Integer> stack = new Stack<Integer>(); // Use add() method // to add elements in the Stack stack.add(10); stack.add(20); stack.add(30); stack.add(40); stack.add(50); // Output the present Stack System.out.println("The Stack is: " + stack); // Adding new elements to the end stack.add(100); stack.add(200); // Printing the new Stack System.out.println("The new Stack is: " + stack); }} The Stack is: [10, 20, 30, 40, 50] The new Stack is: [10, 20, 30, 40, 50, 100, 200] 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.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Dec, 2018" }, { "code": null, "e": 122, "s": 28, "text": "The add(Object) method of Stack Class appends the specified element to the end of this Stack." }, { "code": null, "e": 130, "s": 122, "text": "Syntax:" }, { "code": null, "e": 158, "s": 130, "text": "boolean add(Object element)" }, { "code": null, "e": 322, "s": 158, "text": "Parameters: This function accepts a single parameter element as shown in the above syntax. The element specified by this parameter is appended to end of the Stack." }, { "code": null, "e": 401, "s": 322, "text": "Return Value: This method returns True after successful execution, else False." }, { "code": null, "e": 486, "s": 401, "text": "Below program illustrates the working of java.util.Stack.add(Object element) method:" }, { "code": null, "e": 497, "s": 486, "text": "Example 1:" }, { "code": "// Java code to illustrate boolean add(Object element)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\"); // Output the present Stack System.out.println(\"The Stack is: \" + stack); // Adding new elements to the end stack.add(\"Last\"); stack.add(\"Element\"); // Printing the new Stack System.out.println(\"The new Stack is: \" + stack); }}", "e": 1274, "s": 497, "text": null }, { "code": null, "e": 1378, "s": 1274, "text": "The Stack is: [Geeks, for, Geeks, 10, 20]\nThe new Stack is: [Geeks, for, Geeks, 10, 20, Last, Element]\n" }, { "code": null, "e": 1389, "s": 1378, "text": "Example 2:" }, { "code": "// Java code to illustrate// boolean add(Object element) import java.util.*; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<Integer> stack = new Stack<Integer>(); // Use add() method // to add elements in the Stack stack.add(10); stack.add(20); stack.add(30); stack.add(40); stack.add(50); // Output the present Stack System.out.println(\"The Stack is: \" + stack); // Adding new elements to the end stack.add(100); stack.add(200); // Printing the new Stack System.out.println(\"The new Stack is: \" + stack); }}", "e": 2146, "s": 1389, "text": null }, { "code": null, "e": 2231, "s": 2146, "text": "The Stack is: [10, 20, 30, 40, 50]\nThe new Stack is: [10, 20, 30, 40, 50, 100, 200]\n" }, { "code": null, "e": 2251, "s": 2231, "text": "Java - util package" }, { "code": null, "e": 2268, "s": 2251, "text": "Java-Collections" }, { "code": null, "e": 2283, "s": 2268, "text": "Java-Functions" }, { "code": null, "e": 2294, "s": 2283, "text": "Java-Stack" }, { "code": null, "e": 2299, "s": 2294, "text": "Java" }, { "code": null, "e": 2304, "s": 2299, "text": "Java" }, { "code": null, "e": 2321, "s": 2304, "text": "Java-Collections" } ]
Why is Java ‘write once and run anywhere’?
26 May, 2019 JVM(Java Virtual Machine) acts as a run-time engine to run Java applications. JVM is the one that actually calls the main method present in Java code. JVM is a part of the JRE(Java Runtime Environment). Java applications are called WORA (Write Once Run Anywhere). This means a programmer can develop Java code on one system and can expect it to run on any other Java-enabled system without any adjustment. This is all possible because of JVM. How Java is WORA: In traditional programming languages like C, C++ when programs were compiled, they used to be converted into the code understood by the particular underlying hardware, so If we try to run the same code at another machine with different hardware, which understands different code will cause an error, so you have to re-compile the code to be understood by the new hardware. In Java, the program is not converted to code directly understood by Hardware, rather it is converted to bytecode(.class file), which is interpreted by JVM, so once compiled it generates bytecode file, which can be run anywhere (any machine) which has JVM( Java Virtual Machine) and hence it gets the nature of Write Once and Run Anywhere. Example: Practical Implementation of WORA using a simple JAVA program to check whether a number is even or odd. import java.util.Scanner; class GFG { public static void main(String args[]) { int num; System.out.println("Enter a number:"); Scanner input = new Scanner(System.in); num = input.nextInt(); if (num % 2 == 0) System.out.println(num + " is even"); else System.out.println(num + " is odd"); }} For Compiling (done on Windows 10):javac GFG.java javac GFG.java After compilation there will be a class file in the corresponding folder named as:GFG.class GFG.class When copied the bytecode (.class) generated on compilation to a macOS 10.14.3 and running it we get the following output.Java program Compiled on WIndows and ran in macOS Java program Compiled on WIndows and ran in macOS Conclusion:To sum it up, Java, when compiled, creates a bytecode (.class file), which can be run in any machine which supports JVM. So once compiled it doesn’t require re-compilation at every machine it runs, JVM converts the bytecode to be understood by the underlying hardware. java-basics Picked Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n26 May, 2019" }, { "code": null, "e": 256, "s": 53, "text": "JVM(Java Virtual Machine) acts as a run-time engine to run Java applications. JVM is the one that actually calls the main method present in Java code. JVM is a part of the JRE(Java Runtime Environment)." }, { "code": null, "e": 496, "s": 256, "text": "Java applications are called WORA (Write Once Run Anywhere). This means a programmer can develop Java code on one system and can expect it to run on any other Java-enabled system without any adjustment. This is all possible because of JVM." }, { "code": null, "e": 514, "s": 496, "text": "How Java is WORA:" }, { "code": null, "e": 887, "s": 514, "text": "In traditional programming languages like C, C++ when programs were compiled, they used to be converted into the code understood by the particular underlying hardware, so If we try to run the same code at another machine with different hardware, which understands different code will cause an error, so you have to re-compile the code to be understood by the new hardware." }, { "code": null, "e": 1227, "s": 887, "text": "In Java, the program is not converted to code directly understood by Hardware, rather it is converted to bytecode(.class file), which is interpreted by JVM, so once compiled it generates bytecode file, which can be run anywhere (any machine) which has JVM( Java Virtual Machine) and hence it gets the nature of Write Once and Run Anywhere." }, { "code": null, "e": 1339, "s": 1227, "text": "Example: Practical Implementation of WORA using a simple JAVA program to check whether a number is even or odd." }, { "code": "import java.util.Scanner; class GFG { public static void main(String args[]) { int num; System.out.println(\"Enter a number:\"); Scanner input = new Scanner(System.in); num = input.nextInt(); if (num % 2 == 0) System.out.println(num + \" is even\"); else System.out.println(num + \" is odd\"); }}", "e": 1704, "s": 1339, "text": null }, { "code": null, "e": 1755, "s": 1704, "text": "For Compiling (done on Windows 10):javac GFG.java\n" }, { "code": null, "e": 1771, "s": 1755, "text": "javac GFG.java\n" }, { "code": null, "e": 1864, "s": 1771, "text": "After compilation there will be a class file in the corresponding folder named as:GFG.class\n" }, { "code": null, "e": 1875, "s": 1864, "text": "GFG.class\n" }, { "code": null, "e": 2046, "s": 1875, "text": "When copied the bytecode (.class) generated on compilation to a macOS 10.14.3 and running it we get the following output.Java program Compiled on WIndows and ran in macOS" }, { "code": null, "e": 2096, "s": 2046, "text": "Java program Compiled on WIndows and ran in macOS" }, { "code": null, "e": 2376, "s": 2096, "text": "Conclusion:To sum it up, Java, when compiled, creates a bytecode (.class file), which can be run in any machine which supports JVM. So once compiled it doesn’t require re-compilation at every machine it runs, JVM converts the bytecode to be understood by the underlying hardware." }, { "code": null, "e": 2388, "s": 2376, "text": "java-basics" }, { "code": null, "e": 2395, "s": 2388, "text": "Picked" }, { "code": null, "e": 2400, "s": 2395, "text": "Java" }, { "code": null, "e": 2405, "s": 2400, "text": "Java" } ]
DateTime.AddYears() Method in C#
21 Jan, 2019 This method is used to returns a new DateTime that adds the specified number of years to the value of this instance. Syntax: public DateTime AddYears (int value); Here, the value is the number of years. The value parameter can be negative or positive. Return Value: This method returns an object whose value is the sum of the date and time represented by this instance and the number of years represented by value. Exception: This method will give ArgumentOutOfRangeException if the resulting DateTime is less than MinValue or greater than MaxValue. Below programs illustrate the use of DateTime.AddYears(Int32) Method: Example 1: // C# program to demonstrate the// DateTime.AddYears(Int32) Methodusing System;using System.Globalization; class GFG { // Main Methodpublic static void Main(){ try { // creating object of DateTime DateTime date1 = new DateTime(2010, 1, 1, 4, 0, 15); // adding the 8 Months // using AddYears() method; DateTime date2 = date1.AddYears(8); // Display the date1 Console.WriteLine("DateTime before operation: " + "{0:y} {0:dd}", date1); // Display the date2 Console.WriteLine("\nDateTime after operation: " + "{0:y} {0:dd}", date2); } catch (ArgumentOutOfRangeException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); }}} DateTime before operation: 2010 January 01 DateTime after operation: 2018 January 01 Example 2: For ArgumentOutOfRangeException // C# program to demonstrate the// DateTime.AddYears(Int32) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // creating object of DateTime // and initialize with MinValue DateTime date1 = DateTime.MaxValue; // Display the date1 Console.WriteLine("DateTime before operation: " + "{0:y} {0:dd}", date1); // adding the TimeSpan of 8 Years // using AddYears() method; DateTime date2 = date1.AddYears(5); // Display the date2 Console.WriteLine("DateTime before operation: " + "{0:y} {0:dd}", date2); } catch (ArgumentOutOfRangeException e) { Console.WriteLine("\nThe resulting DateTime is "+ "greater than the DateTime.MaxValue "); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }} DateTime before operation: 9999 December 31 The resulting DateTime is greater than the DateTime.MaxValue Exception Thrown: System.ArgumentOutOfRangeException Note: This method does not change the value of this DateTime object. Instead, it returns a new DateTime object whose value is the result of this operation. This method calculates the resulting year taking into account leap years. The month and time-of-day part of the resulting DateTime object remains the same as this instance. If the current instance represents the leap day in a leap year, the return value depends on the target date:If value + DateTime.Year is also a leap year, the return value represents the leap day in that year. For example, if four years is added to February 29, 2016, the date returned is February 29, 2020.If value + DateTime.Year is not a leap year, the return value represents the day before the leap day in that year. For example, if one year is added to February 29, 2016, the date returned is February 28, 2017. If value + DateTime.Year is also a leap year, the return value represents the leap day in that year. For example, if four years is added to February 29, 2016, the date returned is February 29, 2020. If value + DateTime.Year is not a leap year, the return value represents the day before the leap day in that year. For example, if one year is added to February 29, 2016, the date returned is February 28, 2017. Reference: https://docs.microsoft.com/en-us/dotnet/api/system.datetime.addyears?view=netframework-4.7.2 CSharp DateTime Struct CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Multiple inheritance using interfaces Differences Between .NET Core and .NET Framework Extension Method in C# C# | List Class HashSet in C# with Examples C# | .NET Framework (Basic Architecture and Component Stack) Switch Statement in C# Partial Classes in C# Lambda Expressions in C# Hello World in C#
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Jan, 2019" }, { "code": null, "e": 145, "s": 28, "text": "This method is used to returns a new DateTime that adds the specified number of years to the value of this instance." }, { "code": null, "e": 153, "s": 145, "text": "Syntax:" }, { "code": null, "e": 191, "s": 153, "text": "public DateTime AddYears (int value);" }, { "code": null, "e": 280, "s": 191, "text": "Here, the value is the number of years. The value parameter can be negative or positive." }, { "code": null, "e": 443, "s": 280, "text": "Return Value: This method returns an object whose value is the sum of the date and time represented by this instance and the number of years represented by value." }, { "code": null, "e": 578, "s": 443, "text": "Exception: This method will give ArgumentOutOfRangeException if the resulting DateTime is less than MinValue or greater than MaxValue." }, { "code": null, "e": 648, "s": 578, "text": "Below programs illustrate the use of DateTime.AddYears(Int32) Method:" }, { "code": null, "e": 659, "s": 648, "text": "Example 1:" }, { "code": "// C# program to demonstrate the// DateTime.AddYears(Int32) Methodusing System;using System.Globalization; class GFG { // Main Methodpublic static void Main(){ try { // creating object of DateTime DateTime date1 = new DateTime(2010, 1, 1, 4, 0, 15); // adding the 8 Months // using AddYears() method; DateTime date2 = date1.AddYears(8); // Display the date1 Console.WriteLine(\"DateTime before operation: \" + \"{0:y} {0:dd}\", date1); // Display the date2 Console.WriteLine(\"\\nDateTime after operation: \" + \"{0:y} {0:dd}\", date2); } catch (ArgumentOutOfRangeException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); }}}", "e": 1679, "s": 659, "text": null }, { "code": null, "e": 1766, "s": 1679, "text": "DateTime before operation: 2010 January 01\n\nDateTime after operation: 2018 January 01\n" }, { "code": null, "e": 1809, "s": 1766, "text": "Example 2: For ArgumentOutOfRangeException" }, { "code": "// C# program to demonstrate the// DateTime.AddYears(Int32) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // creating object of DateTime // and initialize with MinValue DateTime date1 = DateTime.MaxValue; // Display the date1 Console.WriteLine(\"DateTime before operation: \" + \"{0:y} {0:dd}\", date1); // adding the TimeSpan of 8 Years // using AddYears() method; DateTime date2 = date1.AddYears(5); // Display the date2 Console.WriteLine(\"DateTime before operation: \" + \"{0:y} {0:dd}\", date2); } catch (ArgumentOutOfRangeException e) { Console.WriteLine(\"\\nThe resulting DateTime is \"+ \"greater than the DateTime.MaxValue \"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}", "e": 2956, "s": 1809, "text": null }, { "code": null, "e": 3117, "s": 2956, "text": "DateTime before operation: 9999 December 31\n\nThe resulting DateTime is greater than the DateTime.MaxValue \nException Thrown: System.ArgumentOutOfRangeException\n" }, { "code": null, "e": 3123, "s": 3117, "text": "Note:" }, { "code": null, "e": 3273, "s": 3123, "text": "This method does not change the value of this DateTime object. Instead, it returns a new DateTime object whose value is the result of this operation." }, { "code": null, "e": 3446, "s": 3273, "text": "This method calculates the resulting year taking into account leap years. The month and time-of-day part of the resulting DateTime object remains the same as this instance." }, { "code": null, "e": 3963, "s": 3446, "text": "If the current instance represents the leap day in a leap year, the return value depends on the target date:If value + DateTime.Year is also a leap year, the return value represents the leap day in that year. For example, if four years is added to February 29, 2016, the date returned is February 29, 2020.If value + DateTime.Year is not a leap year, the return value represents the day before the leap day in that year. For example, if one year is added to February 29, 2016, the date returned is February 28, 2017." }, { "code": null, "e": 4162, "s": 3963, "text": "If value + DateTime.Year is also a leap year, the return value represents the leap day in that year. For example, if four years is added to February 29, 2016, the date returned is February 29, 2020." }, { "code": null, "e": 4373, "s": 4162, "text": "If value + DateTime.Year is not a leap year, the return value represents the day before the leap day in that year. For example, if one year is added to February 29, 2016, the date returned is February 28, 2017." }, { "code": null, "e": 4384, "s": 4373, "text": "Reference:" }, { "code": null, "e": 4477, "s": 4384, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.datetime.addyears?view=netframework-4.7.2" }, { "code": null, "e": 4500, "s": 4477, "text": "CSharp DateTime Struct" }, { "code": null, "e": 4514, "s": 4500, "text": "CSharp-method" }, { "code": null, "e": 4517, "s": 4514, "text": "C#" }, { "code": null, "e": 4615, "s": 4517, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4658, "s": 4615, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 4707, "s": 4658, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 4730, "s": 4707, "text": "Extension Method in C#" }, { "code": null, "e": 4746, "s": 4730, "text": "C# | List Class" }, { "code": null, "e": 4774, "s": 4746, "text": "HashSet in C# with Examples" }, { "code": null, "e": 4835, "s": 4774, "text": "C# | .NET Framework (Basic Architecture and Component Stack)" }, { "code": null, "e": 4858, "s": 4835, "text": "Switch Statement in C#" }, { "code": null, "e": 4880, "s": 4858, "text": "Partial Classes in C#" }, { "code": null, "e": 4905, "s": 4880, "text": "Lambda Expressions in C#" } ]
Lambda expression in C++
27 Dec, 2021 C++ 11 introduced lambda expression to allow us write an inline function which can be used for short snippets of code that are not going to be reuse and not worth naming. In its simplest form lambda expression can be defined as follows: [ capture clause ] (parameters) -> return-type { definition of method } Generally return-type in lambda expression are evaluated by compiler itself and we don’t need to specify that explicitly and -> return-type part can be ignored but in some complex case as in conditional statement, compiler can’t make out the return type and we need to specify that. Various uses of lambda expression with standard function are given below : CPP // C++ program to demonstrate lambda expression in C++#include <bits/stdc++.h>using namespace std; // Function to print vectorvoid printVector(vector<int> v){ // lambda expression to print vector for_each(v.begin(), v.end(), [](int i) { std::cout << i << " "; }); cout << endl;} int main(){ vector<int> v {4, 1, 3, 5, 2, 3, 1, 7}; printVector(v); // below snippet find first number greater than 4 // find_if searches for an element for which // function(third argument) returns true vector<int>:: iterator p = find_if(v.begin(), v.end(), [](int i) { return i > 4; }); cout << "First number greater than 4 is : " << *p << endl; // function to sort vector, lambda expression is for sorting in // non-increasing order Compiler can make out return type as // bool, but shown here just for explanation sort(v.begin(), v.end(), [](const int& a, const int& b) -> bool { return a > b; }); printVector(v); // function to count numbers greater than or equal to 5 int count_5 = count_if(v.begin(), v.end(), [](int a) { return (a >= 5); }); cout << "The number of elements greater than or equal to 5 is : " << count_5 << endl; // function for removing duplicate element (after sorting all // duplicate comes together) p = unique(v.begin(), v.end(), [](int a, int b) { return a == b; }); // resizing vector to make size equal to total different number v.resize(distance(v.begin(), p)); printVector(v); // accumulate function accumulate the container on the basis of // function provided as third argument int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int f = accumulate(arr, arr + 10, 1, [](int i, int j) { return i * j; }); cout << "Factorial of 10 is : " << f << endl; // We can also access function by storing this into variable auto square = [](int i) { return i * i; }; cout << "Square of 5 is : " << square(5) << endl;} Output: 4 1 3 5 2 3 1 7 First number greater than 4 is : 5 7 5 4 3 3 2 1 1 The number of elements greater than or equal to 5 is : 2 7 5 4 3 2 1 Factorial of 10 is : 3628800 Square of 5 is : 25 A lambda expression can have more power than an ordinary function by having access to variables from the enclosing scope. We can capture external variables from enclosing scope by three ways : Capture by reference Capture by value Capture by both (mixed capture)Syntax used for capturing variables : [&] : capture all external variable by reference [=] : capture all external variable by value [a, &b] : capture a by value and b by referenceA lambda with empty capture clause [ ] can access only those variable which are local to it. Capturing ways are demonstrated below : CPP // C++ program to demonstrate lambda expression in C++#include <bits/stdc++.h>using namespace std; int main(){ vector<int> v1 = {3, 1, 7, 9}; vector<int> v2 = {10, 2, 7, 16, 9}; // access v1 and v2 by reference auto pushinto = [&] (int m) { v1.push_back(m); v2.push_back(m); }; // it pushes 20 in both v1 and v2 pushinto(20); // access v1 by copy [v1]() { for (auto p = v1.begin(); p != v1.end(); p++) { cout << *p << " "; } }; int N = 5; // below snippet find first number greater than N // [N] denotes, can access only N by value vector<int>:: iterator p = find_if(v1.begin(), v1.end(), [N](int i) { return i > N; }); cout << "First number greater than 5 is : " << *p << endl; // function to count numbers greater than or equal to N // [=] denotes, can access all variable int count_N = count_if(v1.begin(), v1.end(), [=](int a) { return (a >= N); }); cout << "The number of elements greater than or equal to 5 is : " << count_N << endl;} Output: First number greater than 5 is : 7 The number of elements greater than or equal to 5 is : 3 Lambda expression can work only on C++ 11 and after versions.This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above sandip_maity11 cpp-advanced C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Function Pointer in C Different Methods to Reverse a String in C++ Left Shift and Right Shift Operators in C/C++ std::string class in C++ Vector in C++ STL Map in C++ Standard Template Library (STL) Initialize a vector in C++ (7 different ways) Set in C++ Standard Template Library (STL) vector erase() and clear() in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n27 Dec, 2021" }, { "code": null, "e": 290, "s": 52, "text": "C++ 11 introduced lambda expression to allow us write an inline function which can be used for short snippets of code that are not going to be reuse and not worth naming. In its simplest form lambda expression can be defined as follows: " }, { "code": null, "e": 374, "s": 290, "text": "[ capture clause ] (parameters) -> return-type \n{ \n definition of method \n} " }, { "code": null, "e": 733, "s": 374, "text": "Generally return-type in lambda expression are evaluated by compiler itself and we don’t need to specify that explicitly and -> return-type part can be ignored but in some complex case as in conditional statement, compiler can’t make out the return type and we need to specify that. Various uses of lambda expression with standard function are given below : " }, { "code": null, "e": 737, "s": 733, "text": "CPP" }, { "code": "// C++ program to demonstrate lambda expression in C++#include <bits/stdc++.h>using namespace std; // Function to print vectorvoid printVector(vector<int> v){ // lambda expression to print vector for_each(v.begin(), v.end(), [](int i) { std::cout << i << \" \"; }); cout << endl;} int main(){ vector<int> v {4, 1, 3, 5, 2, 3, 1, 7}; printVector(v); // below snippet find first number greater than 4 // find_if searches for an element for which // function(third argument) returns true vector<int>:: iterator p = find_if(v.begin(), v.end(), [](int i) { return i > 4; }); cout << \"First number greater than 4 is : \" << *p << endl; // function to sort vector, lambda expression is for sorting in // non-increasing order Compiler can make out return type as // bool, but shown here just for explanation sort(v.begin(), v.end(), [](const int& a, const int& b) -> bool { return a > b; }); printVector(v); // function to count numbers greater than or equal to 5 int count_5 = count_if(v.begin(), v.end(), [](int a) { return (a >= 5); }); cout << \"The number of elements greater than or equal to 5 is : \" << count_5 << endl; // function for removing duplicate element (after sorting all // duplicate comes together) p = unique(v.begin(), v.end(), [](int a, int b) { return a == b; }); // resizing vector to make size equal to total different number v.resize(distance(v.begin(), p)); printVector(v); // accumulate function accumulate the container on the basis of // function provided as third argument int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int f = accumulate(arr, arr + 10, 1, [](int i, int j) { return i * j; }); cout << \"Factorial of 10 is : \" << f << endl; // We can also access function by storing this into variable auto square = [](int i) { return i * i; }; cout << \"Square of 5 is : \" << square(5) << endl;}", "e": 2760, "s": 737, "text": null }, { "code": null, "e": 2769, "s": 2760, "text": "Output: " }, { "code": null, "e": 2957, "s": 2769, "text": "4 1 3 5 2 3 1 7 \nFirst number greater than 4 is : 5\n7 5 4 3 3 2 1 1 \nThe number of elements greater than or equal to 5 is : 2\n7 5 4 3 2 1 \nFactorial of 10 is : 3628800\nSquare of 5 is : 25" }, { "code": null, "e": 3568, "s": 2957, "text": "A lambda expression can have more power than an ordinary function by having access to variables from the enclosing scope. We can capture external variables from enclosing scope by three ways : Capture by reference Capture by value Capture by both (mixed capture)Syntax used for capturing variables : [&] : capture all external variable by reference [=] : capture all external variable by value [a, &b] : capture a by value and b by referenceA lambda with empty capture clause [ ] can access only those variable which are local to it. Capturing ways are demonstrated below : " }, { "code": null, "e": 3572, "s": 3568, "text": "CPP" }, { "code": "// C++ program to demonstrate lambda expression in C++#include <bits/stdc++.h>using namespace std; int main(){ vector<int> v1 = {3, 1, 7, 9}; vector<int> v2 = {10, 2, 7, 16, 9}; // access v1 and v2 by reference auto pushinto = [&] (int m) { v1.push_back(m); v2.push_back(m); }; // it pushes 20 in both v1 and v2 pushinto(20); // access v1 by copy [v1]() { for (auto p = v1.begin(); p != v1.end(); p++) { cout << *p << \" \"; } }; int N = 5; // below snippet find first number greater than N // [N] denotes, can access only N by value vector<int>:: iterator p = find_if(v1.begin(), v1.end(), [N](int i) { return i > N; }); cout << \"First number greater than 5 is : \" << *p << endl; // function to count numbers greater than or equal to N // [=] denotes, can access all variable int count_N = count_if(v1.begin(), v1.end(), [=](int a) { return (a >= N); }); cout << \"The number of elements greater than or equal to 5 is : \" << count_N << endl;}", "e": 4670, "s": 3572, "text": null }, { "code": null, "e": 4679, "s": 4670, "text": "Output: " }, { "code": null, "e": 4771, "s": 4679, "text": "First number greater than 5 is : 7\nThe number of elements greater than or equal to 5 is : 3" }, { "code": null, "e": 5005, "s": 4771, "text": "Lambda expression can work only on C++ 11 and after versions.This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 5020, "s": 5005, "text": "sandip_maity11" }, { "code": null, "e": 5033, "s": 5020, "text": "cpp-advanced" }, { "code": null, "e": 5044, "s": 5033, "text": "C Language" }, { "code": null, "e": 5048, "s": 5044, "text": "C++" }, { "code": null, "e": 5052, "s": 5048, "text": "CPP" }, { "code": null, "e": 5150, "s": 5052, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5167, "s": 5150, "text": "Substring in C++" }, { "code": null, "e": 5189, "s": 5167, "text": "Function Pointer in C" }, { "code": null, "e": 5234, "s": 5189, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 5280, "s": 5234, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 5305, "s": 5280, "text": "std::string class in C++" }, { "code": null, "e": 5323, "s": 5305, "text": "Vector in C++ STL" }, { "code": null, "e": 5366, "s": 5323, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 5412, "s": 5366, "text": "Initialize a vector in C++ (7 different ways)" }, { "code": null, "e": 5455, "s": 5412, "text": "Set in C++ Standard Template Library (STL)" } ]
BabylonJS - Back-Face Culling
Back-face culling determines whether a polygon of a graphical object is visible. Back-face culling determines whether or not a StandardMaterial is visible from its back side (from behind). <!doctype html> <html> <head> <meta charset = "utf-8"> <title>BabylonJs - Basic Element-Creating Scene</title> <script src = "babylon.js"></script> <style> canvas {width: 100%; height: 100%;} </style> </head> <body> <canvas id = "renderCanvas"></canvas> <script type = "text/javascript"> var canvas = document.getElementById("renderCanvas"); var engine = new BABYLON.Engine(canvas, true); var createScene = function() { var scene = new BABYLON.Scene(engine); var camera = new BABYLON.ArcRotateCamera("Camera", 1, 0.8, 10, new BABYLON.Vector3(0, 0, 0), scene); camera.attachControl(canvas, true); var light = new BABYLON.HemisphericLight("light1", new BABYLON.Vector3(0, 1, 0), scene); light.intensity = 0.7; var materialforsphere = new BABYLON.StandardMaterial("texture1", scene); var sphere = BABYLON.Mesh.CreateSphere("Sphere1",20, 3.0, scene); sphere.material = materialforsphere; materialforsphere.diffuseTexture = new BABYLON.Texture("images/rainbow.png", scene); materialforsphere.diffuseTexture.hasAlpha = true materialforsphere.backFaceCulling = false; return scene; }; var scene = createScene(); engine.runRenderLoop(function() { scene.render(); }); </script> </body> </html> The above line of code generates the following output − In this demo, we have used an image called rainbow.png. The images are stored in images/ folder locally. You can download any image of your choice and use in the demo link.
[ { "code": null, "e": 2506, "s": 2317, "text": "Back-face culling determines whether a polygon of a graphical object is visible. Back-face culling determines whether or not a StandardMaterial is visible from its back side (from behind)." }, { "code": null, "e": 4058, "s": 2506, "text": "<!doctype html>\n<html>\n <head>\n <meta charset = \"utf-8\">\n <title>BabylonJs - Basic Element-Creating Scene</title>\n <script src = \"babylon.js\"></script>\n <style>\n canvas {width: 100%; height: 100%;}\n </style>\n </head>\n\n <body>\n <canvas id = \"renderCanvas\"></canvas>\n <script type = \"text/javascript\">\n var canvas = document.getElementById(\"renderCanvas\");\n var engine = new BABYLON.Engine(canvas, true);\n \n var createScene = function() {\n var scene = new BABYLON.Scene(engine);\n \n var camera = new BABYLON.ArcRotateCamera(\"Camera\", 1, 0.8, 10, new BABYLON.Vector3(0, 0, 0), scene);\n camera.attachControl(canvas, true);\n \n var light = new BABYLON.HemisphericLight(\"light1\", new BABYLON.Vector3(0, 1, 0), scene);\n light.intensity = 0.7;\t\n \n var materialforsphere = new BABYLON.StandardMaterial(\"texture1\", scene);\n \n var sphere = BABYLON.Mesh.CreateSphere(\"Sphere1\",20, 3.0, scene);\n sphere.material = materialforsphere;\n materialforsphere.diffuseTexture = new BABYLON.Texture(\"images/rainbow.png\", scene);\n \n materialforsphere.diffuseTexture.hasAlpha = true\n materialforsphere.backFaceCulling = false;\n return scene;\n };\n var scene = createScene();\n engine.runRenderLoop(function() {\n scene.render();\n });\n </script>\n </body>\n</html>" }, { "code": null, "e": 4114, "s": 4058, "text": "The above line of code generates the following output −" } ]
Python program to find the largest number in a list
In this article, we will learn about the solution to the problem statement given below. Problem statement − We are given a list, we need to calculate the largest element of the list. Here we will take the help of built-in functions to reach the solution of the problem statement # list list1 = [23,1,32,67,2,34,12] # sorting list1.sort() # printing the last element print("Largest element is:", list1[-1]) Largest in given array is 67 Live Demo # list list1 = [23,1,32,67,2,34,12] # printing the maximum element print("Largest element is:", max(list1)) Largest in given array is 67 We can also take input from the user by the code given below # empty list list1 = [] # asking number of elements to put in list num = int(input("Enter number of elements in list: ")) # appending elements in the list for i in range(1, num + 1): ele = int(input("Enter elements: ")) list1.append(ele) # print maximum element print("Largest element is:", max(list1)) In this article, we have learned how to get the largest element from the list.
[ { "code": null, "e": 1150, "s": 1062, "text": "In this article, we will learn about the solution to the problem statement given below." }, { "code": null, "e": 1245, "s": 1150, "text": "Problem statement − We are given a list, we need to calculate the largest element of the list." }, { "code": null, "e": 1341, "s": 1245, "text": "Here we will take the help of built-in functions to reach the solution of the problem statement" }, { "code": null, "e": 1468, "s": 1341, "text": "# list\nlist1 = [23,1,32,67,2,34,12]\n# sorting\nlist1.sort()\n# printing the last element\nprint(\"Largest element is:\", list1[-1])" }, { "code": null, "e": 1497, "s": 1468, "text": "Largest in given array is 67" }, { "code": null, "e": 1508, "s": 1497, "text": " Live Demo" }, { "code": null, "e": 1616, "s": 1508, "text": "# list\nlist1 = [23,1,32,67,2,34,12]\n# printing the maximum element\nprint(\"Largest element is:\", max(list1))" }, { "code": null, "e": 1645, "s": 1616, "text": "Largest in given array is 67" }, { "code": null, "e": 1706, "s": 1645, "text": "We can also take input from the user by the code given below" }, { "code": null, "e": 2015, "s": 1706, "text": "# empty list\nlist1 = []\n# asking number of elements to put in list\nnum = int(input(\"Enter number of elements in list: \"))\n# appending elements in the list\nfor i in range(1, num + 1):\n ele = int(input(\"Enter elements: \"))\n list1.append(ele)\n# print maximum element\nprint(\"Largest element is:\", max(list1))" }, { "code": null, "e": 2094, "s": 2015, "text": "In this article, we have learned how to get the largest element from the list." } ]
How to Explain Data using Gaussian Distribution and Summary Statistics with Python | by Harshit Tyagi | Towards Data Science
This is the second blog in the Stats series after explaining the taxonomy of data in the first blog. Here, we’ll learn to apply a few essential foundational concepts that help us describe the data using a set of statistical methods. A sample is a snapshot of data from a larger dataset; this larger dataset which is all of the data that could be possibly collected is called population. In statistics, the population is a broad, defined, and often theoretical set of all possible observations that are generated from an experiment or from a domain. These observations in the sample dataset often fit a certain kind of distribution which is commonly called the normal distribution and formally called Gaussian distribution. It is the most studied distribution because of which there is a subfield of statistics simply dedicated to Gaussian data. In this post, we’ll focus on understanding: how normal distribution can be used to describe the data and observations from a machine learning model. estimates of location — the central tendency of a distribution. estimates of variability — the dispersion of data from the mean in the distribution. the code snippets for generating normally distributed data and calculating estimates using various python packages like numpy, scipy, matplotlib, etc. Let’s get started... When we plot a dataset such as a histogram, the shape of that charted plot is what we call its distribution. The most commonly observed shape of continuous values is the bell curve which is also called the Gaussian distribution a.k.a. normal distribution. It is named after the German mathematician, Carl Friedrich Gauss. Some common example datasets that follow Gaussian distribution are: Body temperature People’s Heights Car mileage IQ scores Let’s try to generate the ideal normal distribution and plot it using python. We have libraries like Numpy, scipy, and matplotlib to help us plot an ideal normal curve. import numpy as npimport scipy as spfrom scipy import statsimport matplotlib.pyplot as plt## generate the data and plot it for an ideal normal curve## x-axis for the plotx_data = np.arange(-5, 5, 0.001)## y-axis as the gaussiany_data = stats.norm.pdf(x_axis, 0, 1)## plot dataplt.plot(x_data, y_data)plt.show() Output: The points on the x-axis are the observations and the y-axis is the likelihood of each observation. We generated regularly spaced observations in the range (-5, 5) using np.arange() and then ran it by the norm.pdf() function with a mean of 0.0 and a standard deviation of 1 which returned the likelihood of that observation. Observations around 0 are the most common and the ones around -5.0 and 5.0 are rare. The technical term for the pdf() function is the probability density function. It is important to note that not all data fits the Gaussian distribution, and we have to discover the distribution either by reviewing histogram plots of the data or by implementing some statistical tests. Some examples of observations that do not fit a Gaussian distribution and instead may fit an exponential (hockey-stick shape) include: People’s incomes Population of countries Sales of cars. Until now, we have just talked about the ideal bell-shaped curve of the distribution but if we had to work with random data and figure out its distribution, this is how we would proceed: Let’s create some random data for this example using numpy’s randn() function. Plot the data using a histogram and analyze the returned graph for the expected shape. In reality, the data is rarely perfectly Gaussian, but it will have a Gaussian-like distribution and if the sample size is large enough, we treat it as Gaussian. You may have to change the plotting configuration(scale, number of bins, etc.) to look for the desired pattern. Let’s check the code: Python code: ##setting the seed for the random generationnp.random.seed(1)##generating univariate datadata = 10 * np.random.randn(1000) + 100##plotting the dataplt.hist(data)plt.show() Output: Here’s the output of the code above with the histogram plot of the data. The plot looks more like a simple set of blocks but if we change the scale which in this case is the arbitrary number of bins in the histogram. Let’s specify the number of bins and plot: plt.hist(data, bins=100)plt.show() We can see that the curve looks closer to a Gaussian bell-shaped curve. Although, we should notice that we have a few observations that are going out of bounds and can be seen as noise. It points to another important conclusion that we should always expect some noise or outliers in our sample of data. A fundamental step in exploring a dataset is getting a summarised value for each feature (variable): this is commonly an estimate of where most of the data is located (i.e., the central tendency). At first, summarising the data might sound like a piece of cake i.e. just take the mean of the data. In reality, although the mean is very easy to compute and use, it may not always be the best measure for the central value. To solve this problem, statisticians have developed alternative estimates to mean. We are going to use the Boston dataset from the sklearn package. I’ve dropped a few columns and this is what the dataframe looks like now: Let’s look over the commonly used estimates of location with the help of a sample dataset rather than greek symbols: Mean The sum of all values divided by the number of values. A.k.a average Python code: Calculating the mean of the Age variable in the data. ## we have a pandas dataframe that offer the mean() functiondf['Age'].mean()##output: 68.57490118577076 Weighted mean The sum of all values times a weight divided by the sum of the weights. Two main motivations for using a weighted mean: Some observations are intrinsically more variable(high standard deviation) than others, and highly variable observations are given a lower weight. The collected data does not equally represent the different groups that we are interested in measuring. A.k.a weighted average Median The value that separates one-half of the data from the other and thus dividing it into the higher and lower half. A.k.a. 50th percentile Python code: ## we have a pandas dataframe that offer the median() functiondf['Age'].median()##output: 77.5 Percentile The value such that P percent of the data lies below. A.k.a. quantile Python code: we can use the describe method to learn about the percentile ## we have a pandas dataframe that offer the describe() functiondf.describe() This gives summary statistics of all the numerical(metrics are different for categorical variables) variables. Weighted median The value such that one-half of the sum of the weights lies above and below the sorted data. Trimmed mean The average of all values after dropping a fixed number of extreme values. A trimmed mean eliminates the influence of extreme values. For example, while judging an event, we can calculate the final score using the trimmed mean of all the scores so that no judge can manipulate the result. A.k.a. truncated mean Python code: for this, we are going to use the stats module from the scipy library. ## trim = 0.1 drops 10% from each endstats.trim_mean(df['Age'], 0.1)##output: 71.19605911330049 Outlier A data value that is very different from most of the data. The median is referred to as a robust estimate of location since it is not influenced by outliers i.e. extreme cases whereas the mean is sensitive to outliers. A.k.a. extreme value Besides location, we have another method of summarizing a feature. Variability, also referred to as dispersion, tells us how spread-out or clustered the data is. Calculating the variability measures for the same dataframe using libraries like pandas, numpy, and scipy. Deviations The difference between the observed values and the estimate of location. A.k.a. : errors, residuals Variance The sum of squared deviations from the mean divided by n — 1 where n is the number of data values. A.k.a. : mean-squared-error Python code: ## calculating variaince over Age variabledf['Age'].var() Standard deviation The square root of the variance. Python code: ## calculating standard deviation over Age variabledf['Age'].std()##output: 28.148861406903617 Mean absolute deviation The mean of the absolute values of the deviations from the mean. I’ve covered this in more detail along with a mathematical explanation here: towardsdatascience.com A.k.a. : l1-norm, Manhattan norm Median absolute deviation from the median The median of the absolute values of the deviations from the median. Python code: ## calculating mean absolute deviation over Age variabledf['Age'].mad()##output: 24.610885188020433 Range The difference between the largest and the smallest value in a data set. We can calculate the range of a variable using the min and max from the summary statistics of the dataframe. Python code: ##range of Age columndf['Age'].iloc[df['Age'].idxmax] - df['Age'].iloc[df['Age'].idxmin()]##output: 97.1 Order statistics Metrics based on the data values sorted from smallest to biggest. A.k.a. : ranks Percentile The value such that P percent of the values take on this value or less and (100–P) percent take on this value or more. A.k.a. : quantile Interquartile range The difference between the 75th percentile and the 25th percentile. A.k.a. : IQR Python code: # Computing IQRQ1 = df['Age'].quantile(0.25)Q3 = df['Age'].quantile(0.75)IQR = Q3 - Q1##Output: 49.04999999999999 We’ll cover this in detail in the next blog along with the box plot visualization methods. Now that we have a clear understanding of Gaussian distribution and common estimates of location and variability, we can summarise and interpret the data easily using these statistical methods. In the next blog, we’ll cover all the basic data visualization charts and methods. We’ll learn how to chart time series data, summarize data distributions, and relationships. With this channel, I am planning to roll out a couple of series covering the entire data science space. Here is why you should be subscribing to the channel: This series would cover all the required/demanded quality tutorials on each of the topics and subtopics like Python fundamentals for Data Science. Explained Mathematics and derivations of why we do what we do in ML and Deep Learning. Podcasts with Data Scientists and Engineers at Google, Microsoft, Amazon, etc, and CEOs of big data-driven companies. Projects and instructions to implement the topics learned so far. Learn about new certifications, Bootcamp, and resources to crack those certifications like this TensorFlow Developer Certificate Exam by Google. Feel free to connect with me on Twitter or LinkedIn.
[ { "code": null, "e": 405, "s": 172, "text": "This is the second blog in the Stats series after explaining the taxonomy of data in the first blog. Here, we’ll learn to apply a few essential foundational concepts that help us describe the data using a set of statistical methods." }, { "code": null, "e": 721, "s": 405, "text": "A sample is a snapshot of data from a larger dataset; this larger dataset which is all of the data that could be possibly collected is called population. In statistics, the population is a broad, defined, and often theoretical set of all possible observations that are generated from an experiment or from a domain." }, { "code": null, "e": 1017, "s": 721, "text": "These observations in the sample dataset often fit a certain kind of distribution which is commonly called the normal distribution and formally called Gaussian distribution. It is the most studied distribution because of which there is a subfield of statistics simply dedicated to Gaussian data." }, { "code": null, "e": 1061, "s": 1017, "text": "In this post, we’ll focus on understanding:" }, { "code": null, "e": 1166, "s": 1061, "text": "how normal distribution can be used to describe the data and observations from a machine learning model." }, { "code": null, "e": 1230, "s": 1166, "text": "estimates of location — the central tendency of a distribution." }, { "code": null, "e": 1315, "s": 1230, "text": "estimates of variability — the dispersion of data from the mean in the distribution." }, { "code": null, "e": 1466, "s": 1315, "text": "the code snippets for generating normally distributed data and calculating estimates using various python packages like numpy, scipy, matplotlib, etc." }, { "code": null, "e": 1487, "s": 1466, "text": "Let’s get started..." }, { "code": null, "e": 1743, "s": 1487, "text": "When we plot a dataset such as a histogram, the shape of that charted plot is what we call its distribution. The most commonly observed shape of continuous values is the bell curve which is also called the Gaussian distribution a.k.a. normal distribution." }, { "code": null, "e": 1877, "s": 1743, "text": "It is named after the German mathematician, Carl Friedrich Gauss. Some common example datasets that follow Gaussian distribution are:" }, { "code": null, "e": 1894, "s": 1877, "text": "Body temperature" }, { "code": null, "e": 1911, "s": 1894, "text": "People’s Heights" }, { "code": null, "e": 1923, "s": 1911, "text": "Car mileage" }, { "code": null, "e": 1933, "s": 1923, "text": "IQ scores" }, { "code": null, "e": 2011, "s": 1933, "text": "Let’s try to generate the ideal normal distribution and plot it using python." }, { "code": null, "e": 2102, "s": 2011, "text": "We have libraries like Numpy, scipy, and matplotlib to help us plot an ideal normal curve." }, { "code": null, "e": 2413, "s": 2102, "text": "import numpy as npimport scipy as spfrom scipy import statsimport matplotlib.pyplot as plt## generate the data and plot it for an ideal normal curve## x-axis for the plotx_data = np.arange(-5, 5, 0.001)## y-axis as the gaussiany_data = stats.norm.pdf(x_axis, 0, 1)## plot dataplt.plot(x_data, y_data)plt.show()" }, { "code": null, "e": 2421, "s": 2413, "text": "Output:" }, { "code": null, "e": 2746, "s": 2421, "text": "The points on the x-axis are the observations and the y-axis is the likelihood of each observation. We generated regularly spaced observations in the range (-5, 5) using np.arange() and then ran it by the norm.pdf() function with a mean of 0.0 and a standard deviation of 1 which returned the likelihood of that observation." }, { "code": null, "e": 2910, "s": 2746, "text": "Observations around 0 are the most common and the ones around -5.0 and 5.0 are rare. The technical term for the pdf() function is the probability density function." }, { "code": null, "e": 3116, "s": 2910, "text": "It is important to note that not all data fits the Gaussian distribution, and we have to discover the distribution either by reviewing histogram plots of the data or by implementing some statistical tests." }, { "code": null, "e": 3251, "s": 3116, "text": "Some examples of observations that do not fit a Gaussian distribution and instead may fit an exponential (hockey-stick shape) include:" }, { "code": null, "e": 3268, "s": 3251, "text": "People’s incomes" }, { "code": null, "e": 3292, "s": 3268, "text": "Population of countries" }, { "code": null, "e": 3307, "s": 3292, "text": "Sales of cars." }, { "code": null, "e": 3494, "s": 3307, "text": "Until now, we have just talked about the ideal bell-shaped curve of the distribution but if we had to work with random data and figure out its distribution, this is how we would proceed:" }, { "code": null, "e": 3573, "s": 3494, "text": "Let’s create some random data for this example using numpy’s randn() function." }, { "code": null, "e": 3660, "s": 3573, "text": "Plot the data using a histogram and analyze the returned graph for the expected shape." }, { "code": null, "e": 3822, "s": 3660, "text": "In reality, the data is rarely perfectly Gaussian, but it will have a Gaussian-like distribution and if the sample size is large enough, we treat it as Gaussian." }, { "code": null, "e": 3934, "s": 3822, "text": "You may have to change the plotting configuration(scale, number of bins, etc.) to look for the desired pattern." }, { "code": null, "e": 3956, "s": 3934, "text": "Let’s check the code:" }, { "code": null, "e": 3969, "s": 3956, "text": "Python code:" }, { "code": null, "e": 4141, "s": 3969, "text": "##setting the seed for the random generationnp.random.seed(1)##generating univariate datadata = 10 * np.random.randn(1000) + 100##plotting the dataplt.hist(data)plt.show()" }, { "code": null, "e": 4149, "s": 4141, "text": "Output:" }, { "code": null, "e": 4222, "s": 4149, "text": "Here’s the output of the code above with the histogram plot of the data." }, { "code": null, "e": 4409, "s": 4222, "text": "The plot looks more like a simple set of blocks but if we change the scale which in this case is the arbitrary number of bins in the histogram. Let’s specify the number of bins and plot:" }, { "code": null, "e": 4444, "s": 4409, "text": "plt.hist(data, bins=100)plt.show()" }, { "code": null, "e": 4747, "s": 4444, "text": "We can see that the curve looks closer to a Gaussian bell-shaped curve. Although, we should notice that we have a few observations that are going out of bounds and can be seen as noise. It points to another important conclusion that we should always expect some noise or outliers in our sample of data." }, { "code": null, "e": 4944, "s": 4747, "text": "A fundamental step in exploring a dataset is getting a summarised value for each feature (variable): this is commonly an estimate of where most of the data is located (i.e., the central tendency)." }, { "code": null, "e": 5252, "s": 4944, "text": "At first, summarising the data might sound like a piece of cake i.e. just take the mean of the data. In reality, although the mean is very easy to compute and use, it may not always be the best measure for the central value. To solve this problem, statisticians have developed alternative estimates to mean." }, { "code": null, "e": 5391, "s": 5252, "text": "We are going to use the Boston dataset from the sklearn package. I’ve dropped a few columns and this is what the dataframe looks like now:" }, { "code": null, "e": 5508, "s": 5391, "text": "Let’s look over the commonly used estimates of location with the help of a sample dataset rather than greek symbols:" }, { "code": null, "e": 5513, "s": 5508, "text": "Mean" }, { "code": null, "e": 5568, "s": 5513, "text": "The sum of all values divided by the number of values." }, { "code": null, "e": 5582, "s": 5568, "text": "A.k.a average" }, { "code": null, "e": 5649, "s": 5582, "text": "Python code: Calculating the mean of the Age variable in the data." }, { "code": null, "e": 5753, "s": 5649, "text": "## we have a pandas dataframe that offer the mean() functiondf['Age'].mean()##output: 68.57490118577076" }, { "code": null, "e": 5767, "s": 5753, "text": "Weighted mean" }, { "code": null, "e": 5839, "s": 5767, "text": "The sum of all values times a weight divided by the sum of the weights." }, { "code": null, "e": 5887, "s": 5839, "text": "Two main motivations for using a weighted mean:" }, { "code": null, "e": 6034, "s": 5887, "text": "Some observations are intrinsically more variable(high standard deviation) than others, and highly variable observations are given a lower weight." }, { "code": null, "e": 6138, "s": 6034, "text": "The collected data does not equally represent the different groups that we are interested in measuring." }, { "code": null, "e": 6161, "s": 6138, "text": "A.k.a weighted average" }, { "code": null, "e": 6168, "s": 6161, "text": "Median" }, { "code": null, "e": 6282, "s": 6168, "text": "The value that separates one-half of the data from the other and thus dividing it into the higher and lower half." }, { "code": null, "e": 6305, "s": 6282, "text": "A.k.a. 50th percentile" }, { "code": null, "e": 6318, "s": 6305, "text": "Python code:" }, { "code": null, "e": 6413, "s": 6318, "text": "## we have a pandas dataframe that offer the median() functiondf['Age'].median()##output: 77.5" }, { "code": null, "e": 6424, "s": 6413, "text": "Percentile" }, { "code": null, "e": 6478, "s": 6424, "text": "The value such that P percent of the data lies below." }, { "code": null, "e": 6494, "s": 6478, "text": "A.k.a. quantile" }, { "code": null, "e": 6568, "s": 6494, "text": "Python code: we can use the describe method to learn about the percentile" }, { "code": null, "e": 6646, "s": 6568, "text": "## we have a pandas dataframe that offer the describe() functiondf.describe()" }, { "code": null, "e": 6757, "s": 6646, "text": "This gives summary statistics of all the numerical(metrics are different for categorical variables) variables." }, { "code": null, "e": 6773, "s": 6757, "text": "Weighted median" }, { "code": null, "e": 6866, "s": 6773, "text": "The value such that one-half of the sum of the weights lies above and below the sorted data." }, { "code": null, "e": 6879, "s": 6866, "text": "Trimmed mean" }, { "code": null, "e": 7168, "s": 6879, "text": "The average of all values after dropping a fixed number of extreme values. A trimmed mean eliminates the influence of extreme values. For example, while judging an event, we can calculate the final score using the trimmed mean of all the scores so that no judge can manipulate the result." }, { "code": null, "e": 7190, "s": 7168, "text": "A.k.a. truncated mean" }, { "code": null, "e": 7274, "s": 7190, "text": "Python code: for this, we are going to use the stats module from the scipy library." }, { "code": null, "e": 7370, "s": 7274, "text": "## trim = 0.1 drops 10% from each endstats.trim_mean(df['Age'], 0.1)##output: 71.19605911330049" }, { "code": null, "e": 7378, "s": 7370, "text": "Outlier" }, { "code": null, "e": 7597, "s": 7378, "text": "A data value that is very different from most of the data. The median is referred to as a robust estimate of location since it is not influenced by outliers i.e. extreme cases whereas the mean is sensitive to outliers." }, { "code": null, "e": 7618, "s": 7597, "text": "A.k.a. extreme value" }, { "code": null, "e": 7780, "s": 7618, "text": "Besides location, we have another method of summarizing a feature. Variability, also referred to as dispersion, tells us how spread-out or clustered the data is." }, { "code": null, "e": 7887, "s": 7780, "text": "Calculating the variability measures for the same dataframe using libraries like pandas, numpy, and scipy." }, { "code": null, "e": 7898, "s": 7887, "text": "Deviations" }, { "code": null, "e": 7971, "s": 7898, "text": "The difference between the observed values and the estimate of location." }, { "code": null, "e": 7998, "s": 7971, "text": "A.k.a. : errors, residuals" }, { "code": null, "e": 8007, "s": 7998, "text": "Variance" }, { "code": null, "e": 8106, "s": 8007, "text": "The sum of squared deviations from the mean divided by n — 1 where n is the number of data values." }, { "code": null, "e": 8134, "s": 8106, "text": "A.k.a. : mean-squared-error" }, { "code": null, "e": 8147, "s": 8134, "text": "Python code:" }, { "code": null, "e": 8205, "s": 8147, "text": "## calculating variaince over Age variabledf['Age'].var()" }, { "code": null, "e": 8224, "s": 8205, "text": "Standard deviation" }, { "code": null, "e": 8257, "s": 8224, "text": "The square root of the variance." }, { "code": null, "e": 8270, "s": 8257, "text": "Python code:" }, { "code": null, "e": 8365, "s": 8270, "text": "## calculating standard deviation over Age variabledf['Age'].std()##output: 28.148861406903617" }, { "code": null, "e": 8389, "s": 8365, "text": "Mean absolute deviation" }, { "code": null, "e": 8531, "s": 8389, "text": "The mean of the absolute values of the deviations from the mean. I’ve covered this in more detail along with a mathematical explanation here:" }, { "code": null, "e": 8554, "s": 8531, "text": "towardsdatascience.com" }, { "code": null, "e": 8587, "s": 8554, "text": "A.k.a. : l1-norm, Manhattan norm" }, { "code": null, "e": 8629, "s": 8587, "text": "Median absolute deviation from the median" }, { "code": null, "e": 8698, "s": 8629, "text": "The median of the absolute values of the deviations from the median." }, { "code": null, "e": 8711, "s": 8698, "text": "Python code:" }, { "code": null, "e": 8811, "s": 8711, "text": "## calculating mean absolute deviation over Age variabledf['Age'].mad()##output: 24.610885188020433" }, { "code": null, "e": 8817, "s": 8811, "text": "Range" }, { "code": null, "e": 8890, "s": 8817, "text": "The difference between the largest and the smallest value in a data set." }, { "code": null, "e": 8999, "s": 8890, "text": "We can calculate the range of a variable using the min and max from the summary statistics of the dataframe." }, { "code": null, "e": 9012, "s": 8999, "text": "Python code:" }, { "code": null, "e": 9117, "s": 9012, "text": "##range of Age columndf['Age'].iloc[df['Age'].idxmax] - df['Age'].iloc[df['Age'].idxmin()]##output: 97.1" }, { "code": null, "e": 9134, "s": 9117, "text": "Order statistics" }, { "code": null, "e": 9200, "s": 9134, "text": "Metrics based on the data values sorted from smallest to biggest." }, { "code": null, "e": 9215, "s": 9200, "text": "A.k.a. : ranks" }, { "code": null, "e": 9226, "s": 9215, "text": "Percentile" }, { "code": null, "e": 9345, "s": 9226, "text": "The value such that P percent of the values take on this value or less and (100–P) percent take on this value or more." }, { "code": null, "e": 9363, "s": 9345, "text": "A.k.a. : quantile" }, { "code": null, "e": 9383, "s": 9363, "text": "Interquartile range" }, { "code": null, "e": 9451, "s": 9383, "text": "The difference between the 75th percentile and the 25th percentile." }, { "code": null, "e": 9464, "s": 9451, "text": "A.k.a. : IQR" }, { "code": null, "e": 9477, "s": 9464, "text": "Python code:" }, { "code": null, "e": 9591, "s": 9477, "text": "# Computing IQRQ1 = df['Age'].quantile(0.25)Q3 = df['Age'].quantile(0.75)IQR = Q3 - Q1##Output: 49.04999999999999" }, { "code": null, "e": 9682, "s": 9591, "text": "We’ll cover this in detail in the next blog along with the box plot visualization methods." }, { "code": null, "e": 9876, "s": 9682, "text": "Now that we have a clear understanding of Gaussian distribution and common estimates of location and variability, we can summarise and interpret the data easily using these statistical methods." }, { "code": null, "e": 10051, "s": 9876, "text": "In the next blog, we’ll cover all the basic data visualization charts and methods. We’ll learn how to chart time series data, summarize data distributions, and relationships." }, { "code": null, "e": 10209, "s": 10051, "text": "With this channel, I am planning to roll out a couple of series covering the entire data science space. Here is why you should be subscribing to the channel:" }, { "code": null, "e": 10356, "s": 10209, "text": "This series would cover all the required/demanded quality tutorials on each of the topics and subtopics like Python fundamentals for Data Science." }, { "code": null, "e": 10443, "s": 10356, "text": "Explained Mathematics and derivations of why we do what we do in ML and Deep Learning." }, { "code": null, "e": 10561, "s": 10443, "text": "Podcasts with Data Scientists and Engineers at Google, Microsoft, Amazon, etc, and CEOs of big data-driven companies." }, { "code": null, "e": 10772, "s": 10561, "text": "Projects and instructions to implement the topics learned so far. Learn about new certifications, Bootcamp, and resources to crack those certifications like this TensorFlow Developer Certificate Exam by Google." } ]
C Program for Basic Euclidean algorithms - GeeksforGeeks
05 Nov, 2021 GCD of two numbers is the largest number that divides both of them. A simple way to find GCD is to factorize both numbers and multiply common factors. C // C program to demonstrate Basic Euclidean Algorithm#include <stdio.h> // Function to return gcd of a and bint gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // Driver program to test above functionint main(){ int a = 10, b = 15; printf("GCD(%d, %d) = %d\n", a, b, gcd(a, b)); a = 35, b = 10; printf("GCD(%d, %d) = %d\n", a, b, gcd(a, b)); a = 31, b = 2; printf("GCD(%d, %d) = %d\n", a, b, gcd(a, b)); return 0;} GCD(10, 15) = 5 GCD(35, 10) = 5 GCD(31, 2) = 1 Time Complexity: O(Log min(a, b)) Auxiliary Space: O(1)Please refer complete article on Basic and Extended Euclidean algorithms for more details! subham348 GCD-LCM C Programs Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C Program to read contents of Whole File How to Append a Character to a String in C time() function in C Flex (Fast Lexical Analyzer Generator ) C Program to Swap two Numbers 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": 24417, "s": 24389, "text": "\n05 Nov, 2021" }, { "code": null, "e": 24569, "s": 24417, "text": "GCD of two numbers is the largest number that divides both of them. A simple way to find GCD is to factorize both numbers and multiply common factors. " }, { "code": null, "e": 24571, "s": 24569, "text": "C" }, { "code": "// C program to demonstrate Basic Euclidean Algorithm#include <stdio.h> // Function to return gcd of a and bint gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // Driver program to test above functionint main(){ int a = 10, b = 15; printf(\"GCD(%d, %d) = %d\\n\", a, b, gcd(a, b)); a = 35, b = 10; printf(\"GCD(%d, %d) = %d\\n\", a, b, gcd(a, b)); a = 31, b = 2; printf(\"GCD(%d, %d) = %d\\n\", a, b, gcd(a, b)); return 0;}", "e": 25036, "s": 24571, "text": null }, { "code": null, "e": 25083, "s": 25036, "text": "GCD(10, 15) = 5\nGCD(35, 10) = 5\nGCD(31, 2) = 1" }, { "code": null, "e": 25120, "s": 25085, "text": "Time Complexity: O(Log min(a, b)) " }, { "code": null, "e": 25233, "s": 25120, "text": "Auxiliary Space: O(1)Please refer complete article on Basic and Extended Euclidean algorithms for more details! " }, { "code": null, "e": 25243, "s": 25233, "text": "subham348" }, { "code": null, "e": 25251, "s": 25243, "text": "GCD-LCM" }, { "code": null, "e": 25262, "s": 25251, "text": "C Programs" }, { "code": null, "e": 25275, "s": 25262, "text": "Mathematical" }, { "code": null, "e": 25288, "s": 25275, "text": "Mathematical" }, { "code": null, "e": 25386, "s": 25288, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25395, "s": 25386, "text": "Comments" }, { "code": null, "e": 25408, "s": 25395, "text": "Old Comments" }, { "code": null, "e": 25449, "s": 25408, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 25492, "s": 25449, "text": "How to Append a Character to a String in C" }, { "code": null, "e": 25513, "s": 25492, "text": "time() function in C" }, { "code": null, "e": 25553, "s": 25513, "text": "Flex (Fast Lexical Analyzer Generator )" }, { "code": null, "e": 25583, "s": 25553, "text": "C Program to Swap two Numbers" }, { "code": null, "e": 25613, "s": 25583, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 25628, "s": 25613, "text": "C++ Data Types" }, { "code": null, "e": 25688, "s": 25628, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 25731, "s": 25688, "text": "Set in C++ Standard Template Library (STL)" } ]
ExpressJS - Authentication
Authentication is a process in which the credentials provided are compared to those on file in a database of authorized users' information on a local operating system or within an authentication server. If the credentials match, the process is completed and the user is granted authorization for access. For us to create an authentication system, we will need to create a sign up page and a user-password store. The following code creates an account for us and stores it in memory. This is just for the purpose of demo; it is recommended that a persistent storage (database or files) is always used to store user information. var express = require('express'); var app = express(); var bodyParser = require('body-parser'); var multer = require('multer'); var upload = multer(); var session = require('express-session'); var cookieParser = require('cookie-parser'); app.set('view engine', 'pug'); app.set('views','./views'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(upload.array()); app.use(cookieParser()); app.use(session({secret: "Your secret key"})); var Users = []; app.get('/signup', function(req, res){ res.render('signup'); }); app.post('/signup', function(req, res){ if(!req.body.id || !req.body.password){ res.status("400"); res.send("Invalid details!"); } else { Users.filter(function(user){ if(user.id === req.body.id){ res.render('signup', { message: "User Already Exists! Login or choose another user id"}); } }); var newUser = {id: req.body.id, password: req.body.password}; Users.push(newUser); req.session.user = newUser; res.redirect('/protected_page'); } }); app.listen(3000); Now for the signup form, create a new view called signup.jade. html head title Signup body if(message) h4 #{message} form(action = "/signup" method = "POST") input(name = "id" type = "text" required placeholder = "User ID") input(name = "password" type = "password" required placeholder = "Password") button(type = "Submit") Sign me up! Check if this page loads by visiting localhost:3000/signup. We have set the required attribute for both fields, so HTML5 enabled browsers will not let us submit this form until we provide both id and password. If someone tries to register using a curl request without a User ID or Password, an error will be displayed. Create a new file called protected_page.pug in views with the following content − html head title Protected page body div Hey #{id}, How are you doing today? div Want to log out? div Logout This page should only be visible if the user has just signed up or logged in. Let us now define its route and also routes to log in and log out − var express = require('express'); var app = express(); var bodyParser = require('body-parser'); var multer = require('multer'); var upload = multer(); var session = require('express-session'); var cookieParser = require('cookie-parser'); app.set('view engine', 'pug'); app.set('views','./views'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(upload.array()); app.use(cookieParser()); app.use(session({secret: "Your secret key"})); var Users = []; app.get('/signup', function(req, res){ res.render('signup'); }); app.post('/signup', function(req, res){ if(!req.body.id || !req.body.password){ res.status("400"); res.send("Invalid details!"); } else { Users.filter(function(user){ if(user.id === req.body.id){ res.render('signup', { message: "User Already Exists! Login or choose another user id"}); } }); var newUser = {id: req.body.id, password: req.body.password}; Users.push(newUser); req.session.user = newUser; res.redirect('/protected_page'); } }); function checkSignIn(req, res){ if(req.session.user){ next(); //If session exists, proceed to page } else { var err = new Error("Not logged in!"); console.log(req.session.user); next(err); //Error, trying to access unauthorized page! } } app.get('/protected_page', checkSignIn, function(req, res){ res.render('protected_page', {id: req.session.user.id}) }); app.get('/login', function(req, res){ res.render('login'); }); app.post('/login', function(req, res){ console.log(Users); if(!req.body.id || !req.body.password){ res.render('login', {message: "Please enter both id and password"}); } else { Users.filter(function(user){ if(user.id === req.body.id && user.password === req.body.password){ req.session.user = user; res.redirect('/protected_page'); } }); res.render('login', {message: "Invalid credentials!"}); } }); app.get('/logout', function(req, res){ req.session.destroy(function(){ console.log("user logged out.") }); res.redirect('/login'); }); app.use('/protected_page', function(err, req, res, next){ console.log(err); //User should be authenticated! Redirect him to log in. res.redirect('/login'); }); app.listen(3000); We have created a middleware function checkSignIn to check if the user is signed in. The protected_page uses this function. To log the user out, we destroy the session. Let us now create the login page. Name the view as login.pug and enter the contents − html head title Signup body if(message) h4 #{message} form(action = "/login" method = "POST") input(name = "id" type = "text" required placeholder = "User ID") input(name = "password" type = "password" required placeholder = "Password") button(type = "Submit") Log in Our simple authentication application is now complete; let us now test the application. Run the app using nodemon index.js, and proceed to localhost:3000/signup. Enter a Username and a password and click sign up. You will be redirected to the protected_page if details are valid/unique − Now log out of the app. This will redirect us to the login page − This route is protected such that if an unauthenticated person tries to visit it, he will be edirected to our login page. This was all about basic user authentication. It is always recommended that we use a persistent session system and use hashes for password transport. There are much better ways to authenticate users now, leveraging JSON tokens. 16 Lectures 1 hours Anadi Sharma Print Add Notes Bookmark this page
[ { "code": null, "e": 2365, "s": 2061, "text": "Authentication is a process in which the credentials provided are compared to those on file in a database of authorized users' information on a local operating system or within an authentication server. If the credentials match, the process is completed and the user is granted authorization for access." }, { "code": null, "e": 2687, "s": 2365, "text": "For us to create an authentication system, we will need to create a sign up page and a user-password store. The following code creates an account for us and stores it in memory. This is just for the purpose of demo; it is recommended that a persistent storage (database or files) is always used to store user information." }, { "code": null, "e": 3815, "s": 2687, "text": "var express = require('express');\nvar app = express();\nvar bodyParser = require('body-parser');\nvar multer = require('multer');\nvar upload = multer(); \nvar session = require('express-session');\nvar cookieParser = require('cookie-parser');\n\napp.set('view engine', 'pug');\napp.set('views','./views');\n\napp.use(bodyParser.json());\napp.use(bodyParser.urlencoded({ extended: true })); \napp.use(upload.array());\napp.use(cookieParser());\napp.use(session({secret: \"Your secret key\"}));\n\nvar Users = [];\n\napp.get('/signup', function(req, res){\n res.render('signup');\n});\n\napp.post('/signup', function(req, res){\n if(!req.body.id || !req.body.password){\n res.status(\"400\");\n res.send(\"Invalid details!\");\n } else {\n Users.filter(function(user){\n if(user.id === req.body.id){\n res.render('signup', {\n message: \"User Already Exists! Login or choose another user id\"});\n }\n });\n var newUser = {id: req.body.id, password: req.body.password};\n Users.push(newUser);\n req.session.user = newUser;\n res.redirect('/protected_page');\n }\n});\n\napp.listen(3000);" }, { "code": null, "e": 3878, "s": 3815, "text": "Now for the signup form, create a new view called signup.jade." }, { "code": null, "e": 4215, "s": 3878, "text": "html\n head\n title Signup\n body\n if(message)\n h4 #{message}\n form(action = \"/signup\" method = \"POST\")\n input(name = \"id\" type = \"text\" required placeholder = \"User ID\")\n input(name = \"password\" type = \"password\" required placeholder = \"Password\")\n button(type = \"Submit\") Sign me up!" }, { "code": null, "e": 4275, "s": 4215, "text": "Check if this page loads by visiting localhost:3000/signup." }, { "code": null, "e": 4616, "s": 4275, "text": "We have set the required attribute for both fields, so HTML5 enabled browsers will not let us submit this form until we provide both id and password. If someone tries to register using a curl request without a User ID or Password, an error will be displayed. Create a new file called protected_page.pug in views with the following content −" }, { "code": null, "e": 4754, "s": 4616, "text": "html\n head\n title Protected page\n body\n div Hey #{id}, How are you doing today?\n div Want to log out?\n div Logout" }, { "code": null, "e": 4900, "s": 4754, "text": "This page should only be visible if the user has just signed up or logged in. Let us now define its route and also routes to log in and log out −" }, { "code": null, "e": 7291, "s": 4900, "text": "var express = require('express');\nvar app = express();\nvar bodyParser = require('body-parser');\nvar multer = require('multer');\nvar upload = multer(); \nvar session = require('express-session');\nvar cookieParser = require('cookie-parser');\n\napp.set('view engine', 'pug');\napp.set('views','./views');\n\napp.use(bodyParser.json());\napp.use(bodyParser.urlencoded({ extended: true })); \napp.use(upload.array());\napp.use(cookieParser());\napp.use(session({secret: \"Your secret key\"}));\n\nvar Users = [];\n\napp.get('/signup', function(req, res){\n res.render('signup');\n});\n\napp.post('/signup', function(req, res){\n if(!req.body.id || !req.body.password){\n res.status(\"400\");\n res.send(\"Invalid details!\");\n } else {\n Users.filter(function(user){\n if(user.id === req.body.id){\n res.render('signup', {\n message: \"User Already Exists! Login or choose another user id\"});\n }\n });\n var newUser = {id: req.body.id, password: req.body.password};\n Users.push(newUser);\n req.session.user = newUser;\n res.redirect('/protected_page');\n }\n});\nfunction checkSignIn(req, res){\n if(req.session.user){\n next(); //If session exists, proceed to page\n } else {\n var err = new Error(\"Not logged in!\");\n console.log(req.session.user);\n next(err); //Error, trying to access unauthorized page!\n }\n}\napp.get('/protected_page', checkSignIn, function(req, res){\n res.render('protected_page', {id: req.session.user.id})\n});\n\napp.get('/login', function(req, res){\n res.render('login');\n});\n\napp.post('/login', function(req, res){\n console.log(Users);\n if(!req.body.id || !req.body.password){\n res.render('login', {message: \"Please enter both id and password\"});\n } else {\n Users.filter(function(user){\n if(user.id === req.body.id && user.password === req.body.password){\n req.session.user = user;\n res.redirect('/protected_page');\n }\n });\n res.render('login', {message: \"Invalid credentials!\"});\n }\n});\n\napp.get('/logout', function(req, res){\n req.session.destroy(function(){\n console.log(\"user logged out.\")\n });\n res.redirect('/login');\n});\n\napp.use('/protected_page', function(err, req, res, next){\nconsole.log(err);\n //User should be authenticated! Redirect him to log in.\n res.redirect('/login');\n});\n\napp.listen(3000);" }, { "code": null, "e": 7460, "s": 7291, "text": "We have created a middleware function checkSignIn to check if the user is signed in. The protected_page uses this function. To log the user out, we destroy the session." }, { "code": null, "e": 7546, "s": 7460, "text": "Let us now create the login page. Name the view as login.pug and enter the contents −" }, { "code": null, "e": 7877, "s": 7546, "text": "html\n head\n title Signup\n body\n if(message)\n h4 #{message}\n form(action = \"/login\" method = \"POST\")\n input(name = \"id\" type = \"text\" required placeholder = \"User ID\")\n input(name = \"password\" type = \"password\" required placeholder = \"Password\")\n button(type = \"Submit\") Log in" }, { "code": null, "e": 8039, "s": 7877, "text": "Our simple authentication application is now complete; let us now test the application. Run the app using nodemon index.js, and proceed to localhost:3000/signup." }, { "code": null, "e": 8165, "s": 8039, "text": "Enter a Username and a password and click sign up. You will be redirected to the protected_page if details are valid/unique −" }, { "code": null, "e": 8231, "s": 8165, "text": "Now log out of the app. This will redirect us to the login page −" }, { "code": null, "e": 8581, "s": 8231, "text": "This route is protected such that if an unauthenticated person tries to visit it, he will be edirected to our login page. This was all about basic user authentication. It is always recommended that we use a persistent session system and use hashes for password transport. There are much better ways to authenticate users now, leveraging JSON tokens." }, { "code": null, "e": 8614, "s": 8581, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 8628, "s": 8614, "text": " Anadi Sharma" }, { "code": null, "e": 8635, "s": 8628, "text": " Print" }, { "code": null, "e": 8646, "s": 8635, "text": " Add Notes" } ]
Anubis - Subdomain enumeration and information gathering tool in Kali Linux - GeeksforGeeks
21 Jul, 2021 Anubis is a tool for information gathering. This tool is very useful in the initial phases of penetration testing. The main technique used to find subdomain using many modules is to target bruteforce with an improved wordlist Anubis is a free and open-source tool available on GitHub. This tool is free means you can download and use this tool free of cost. Anubis is used for reconnaissance of subdomains. Anubis is used for Anubis of the target. This tool is used to find subdomains from a website/web-applications. Usually, what happens that it becomes very difficult for a security researcher to find subdomains from an HTTPS website or web application. This tool helps to get subdomains of all HTTPS as well as HTTP websites. Anubis tool is written in python language you must have python language installed into your Kali Linux in order to use this tool. This tool comes with an awesome user interface. The user interface of the tool is very similar to Metasploitable 1 and metasploitable 2 which makes it very easy to run and use. Step 1: Use the following command to install the tool in your operating system and use the second command to move into the directory of the tool. git clone https://github.com/jonluca/Anubis.git cd Anubis Step 2: The tool has been downloaded and installed in your system. Now you have to install the requirements of the tool using the following command. pip3 install -r requirements.txt The requirements have been installed. Now we will see an example to use the tool. Example 1: Use the Anubis tool to find subdomains of a domain. anubis -t reddit.com Example 2: Find the subdomain of domain geeksforgeeks.com and IP address. anubis -t geeksforgeeks.org -ip Kali-Linux Linux-Tools Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments scp command in Linux with Examples nohup Command in Linux with Examples mv command in Linux with examples Thread functions in C/C++ Docker - COPY Instruction chown command in Linux with Examples nslookup command in Linux with Examples SED command in Linux | Set 2 Named Pipe or FIFO with example C program uniq Command in LINUX with examples
[ { "code": null, "e": 24015, "s": 23987, "text": "\n21 Jul, 2021" }, { "code": null, "e": 25053, "s": 24015, "text": "Anubis is a tool for information gathering. This tool is very useful in the initial phases of penetration testing. The main technique used to find subdomain using many modules is to target bruteforce with an improved wordlist Anubis is a free and open-source tool available on GitHub. This tool is free means you can download and use this tool free of cost. Anubis is used for reconnaissance of subdomains. Anubis is used for Anubis of the target. This tool is used to find subdomains from a website/web-applications. Usually, what happens that it becomes very difficult for a security researcher to find subdomains from an HTTPS website or web application. This tool helps to get subdomains of all HTTPS as well as HTTP websites. Anubis tool is written in python language you must have python language installed into your Kali Linux in order to use this tool. This tool comes with an awesome user interface. The user interface of the tool is very similar to Metasploitable 1 and metasploitable 2 which makes it very easy to run and use." }, { "code": null, "e": 25199, "s": 25053, "text": "Step 1: Use the following command to install the tool in your operating system and use the second command to move into the directory of the tool." }, { "code": null, "e": 25257, "s": 25199, "text": "git clone https://github.com/jonluca/Anubis.git\ncd Anubis" }, { "code": null, "e": 25406, "s": 25257, "text": "Step 2: The tool has been downloaded and installed in your system. Now you have to install the requirements of the tool using the following command." }, { "code": null, "e": 25439, "s": 25406, "text": "pip3 install -r requirements.txt" }, { "code": null, "e": 25521, "s": 25439, "text": "The requirements have been installed. Now we will see an example to use the tool." }, { "code": null, "e": 25584, "s": 25521, "text": "Example 1: Use the Anubis tool to find subdomains of a domain." }, { "code": null, "e": 25605, "s": 25584, "text": "anubis -t reddit.com" }, { "code": null, "e": 25679, "s": 25605, "text": "Example 2: Find the subdomain of domain geeksforgeeks.com and IP address." }, { "code": null, "e": 25711, "s": 25679, "text": "anubis -t geeksforgeeks.org -ip" }, { "code": null, "e": 25722, "s": 25711, "text": "Kali-Linux" }, { "code": null, "e": 25734, "s": 25722, "text": "Linux-Tools" }, { "code": null, "e": 25745, "s": 25734, "text": "Linux-Unix" }, { "code": null, "e": 25843, "s": 25745, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25852, "s": 25843, "text": "Comments" }, { "code": null, "e": 25865, "s": 25852, "text": "Old Comments" }, { "code": null, "e": 25900, "s": 25865, "text": "scp command in Linux with Examples" }, { "code": null, "e": 25937, "s": 25900, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 25971, "s": 25937, "text": "mv command in Linux with examples" }, { "code": null, "e": 25997, "s": 25971, "text": "Thread functions in C/C++" }, { "code": null, "e": 26023, "s": 25997, "text": "Docker - COPY Instruction" }, { "code": null, "e": 26060, "s": 26023, "text": "chown command in Linux with Examples" }, { "code": null, "e": 26100, "s": 26060, "text": "nslookup command in Linux with Examples" }, { "code": null, "e": 26129, "s": 26100, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 26171, "s": 26129, "text": "Named Pipe or FIFO with example C program" } ]
The Complete Guide to Cron and Launchd on macOS/Linux | by Shinichi Okada | Towards Data Science
Table of contentsIntroduction1. Papermill and terminal-notifier2. cron for Linux/macOS3. launchd for macOSConclusion [Update.1 : 2021–05–28] Do you have a Data Science project that requires your time every day? Do you use data feeds that update daily? For example, the 2019 Novel Coronavirus COVID-19 (2019-nCoV) Data Repository by Johns Hopkins CSSE updates daily and I use it in my personal project. Manually, I start Jupyter, open a project, restart the Kernel and run all the cells, then git add/commit/push. It is a bit of work. In this article, I am going to share a step-by-step process to set up launchd and cron jobs for your data science project so that it will automatically update your project behind the scene and even notify you. cron for Linux/macOS and launched for macOS Although launchd is the preferred method in macOS, the cron method still works in macOS as well. cron is a Linux utility that schedules a command or script on your server/computer to run automatically at a specified time and date. A cron job is the scheduled task and it is very useful to automate repetitive tasks. launchd is created by Apple and is a replacement for a lot of Unix tools, like cron, inetd, init, etc. You can start scheduling tasks and save a lot of your precious time after reading this article. towardsdatascience.com towardsdatascience.com Papermill is a tool for parameterizing and executing Jupyter Notebooks. I can use this to run a Jupyter Notebook file in a cron and launchd job file. $ pip install papermill or $ pip3 install papermill$ papermill --help You can find command-line interface help here. Papermill’s usage: papermill [OPTIONS] NOTEBOOK_PATH OUTPUT_PATH I will show you an example soon. terminal-notifier is a command-line tool to send macOS User Notifications. I will use this to notify me when the scheduled job is done. Install terminal-notifier. $ brew install terminal-notifier$ terminal-notifier -help towardsdatascience.com In macOS, you can run a background job on a timed schedule in two ways: launchd jobs and cron jobs. Note that it is still supported in macOS v10.15 even though cronis not a recommended solution and launchd has superseded. You can set up your cron job using your user name: $ whoamiyour-name$ sudo crontab -u your-name -ePassword:sh-3.2# You can enable the root user by using sudo su in macOS so that you are not required your password. $ sudo su$ crontab -u your-name -e -u specifies the name of the user. -e edits the current crontab. Add five numbers as described above and a path to a file you want to execute. Example: 0 10 * * * ~/DataScience/covid-19-stats/covid19-cron The above will run the file ~/DataScience/covid-19-stats/covid19-cron every day at 10:00. If the system is turned off or asleep, cron jobs do not execute. If you miss the designated time, it will exectute at the next designated time when your system is turned on. You can output stdout and stderr: # log stdout and stderr42 6 * * * ~/DataScience/covid-19-stats/covid19-cron > /tmp/stdout.log 2> /tmp/stderr.log > redirect the standard output to /tmp/stdout.log and >2 redirect the standard error to /tmp/stderr.log. Once you set up a cron job, you can list it: $ crontab -l0 20 * * * ~/DataScience/covid-19-stats/covid19-cron If you want to remove all the cron job: $ crontab -r You can add multiple cron jobs in the crontab. 0 20 * * * ~/DataScience/covid-19-stats/covid19-cron0 7 * * * Path/to/file/to/execute0 7 * * 0 Path/to/another/file/to/execute crontab guru is a quick and simple tool for the cron schedule. You can place all cron job files in a directory, but I place it in the project root. Change the current working directory to your project, create a cron job file, and open it in an editor. Executables should have no .sh extension according to the Google style guides. $ cd path/to/project$ touch covid19-cron$ vim covid19-cron The shebang used in the first line in scripts is to indicate the UNIX/Linux operating system for execution. Even though Papermill and terminal-notifier work in a terminal, we need to add their paths. Let’s find them. $ which papermill/usr/local/bin/papermill$ which terminal-notifier/usr/local/bin/terminal-notifier In my covid19-cron file: #!/usr/bin/env bash# run covid-19 files # git add, comit and pushdir=/Users/shinokada/DataScience/covid-19-statspapermill=/usr/local/bin/papermillnotifier=/usr/local/bin/terminal-notifiercd $dir$papermill covid-19-matplotlib.ipynb ./latest/covid-19-matplotlib.ipynb# more files ...$papermill covid-19-plotly.ipynb ./latest/covid-19-plotly.ipynb git add . git commit -m "update" git push$notifier -title Covid19 -subtitle "Daily Updated" -message "Completed" -open "https://mybinder.org/v2/gh/shinokada/covid-19-stats/master"now=$(date)echo "Cron job update completed at $now" I create “latest” directory in the root directory. The Papermill outputs files to this “latest” directory. Since we are going to use git, you need to make sure that you have .git in the project root. If you are using %run somefile, I suggest you add them to the cron-file. I use title, substitle, message and open for the terminal-notifier options. terminal-notifier quick guide This bash file needs permission to execute. $ chmod u+x covid19-cron chmod sets permissions to files. chmod u+x covid19-cron allows the user to execute covid19-cron. The above command is the same as: $ chmod 744 covid19-cron Your terminal sends its output and error messages by mail after running a cron job. Let’s check if the cron job worked. $ mail You need to press enter to read messages, and then q and enter to quit. Use j to see the next lines. You need to check if the mail has no errors. In case of errors, you need to attend the problem. You need to reset the crontab time to test your cron job. launchd allows us to test a job but for cron this is the only way you can test. $ sudo crontab -u your-name -e# change time 5 20 * * * ~/DataScience/covid-19-stats/covid19-cron$ crontab -l5 20 * * * ~/DataScience/covid-19-stats/covid19-cron When the test is done, it will display the notification. launchd is a unified, open-source service management framework for starting, stopping and managing daemons, applications, processes, and scripts. If you schedule a launchd job by setting the StartCalendarInterval key and the computer is asleep when the job should have run, your job will run when the computer wakes up. However, if the machine is off when the job should have run, the job does not execute until the next designated time occurs. A PLIST file is a system-wide and per-user daemon/agent configuration file. A daemon/agent is a program running in the background without user input. You define the name of the program, when you run it, what you want to run, etc. You store all your plist files in the ~/Library/LaunchAgents directory. [Update.1] If you don’t have ~/Library/LaunchAgents you need to create it. # check ~/Library if it has LaunchAgents$ ls ~/Library# if not create the directory$ mkdir ~/Library/LaunchAgents Create a plist file: $ cd ~/Library/LaunchAgents$ touch com.shinokada.covid19.plist In the com.shinokada.covid19.plist: <?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"> <dict> <key>Label</key> <string>com.shinokada.covid19</string> <key>Program</key> <string>/Users/shinokada/DataScience/covid-19-stats/covid19-launchd</string> <key>EnvironmentVariables</key> <dict> <key>PATH</key> <string>/bin:/usr/bin:/usr/local/bin</string> </dict> <key>StandardInPath</key> <string>/tmp/covid.stdin</string> <key>StandardOutPath</key> <string>/tmp/covid.stdout</string> <key>StandardErrorPath</key> <string>/tmp/covid.stderr</string> <key>WorkingDirectory</key> <string>/Users/shinokada/DataScience/covid-19-stats</string> <key>StartCalendarInterval</key> <dict> <key>Hour</key> <integer>8</integer> <key>Minute</key> <integer>0</integer> </dict> </dict></plist> Here I run /Users/shinokada/DataScience/covid-19-stats/covid19-launchd at 8:00 AM every day. Configuration in plist file quick guide Create a file called covid19-launchd in the project root directory. This is very similar to the above covid19-cron. #!/usr/bin/env bash# run covid-19 files # git add, comit and pushpapermill covid-19-data.ipynb ./latest/covid-19-data.ipynbpapermill multiplot.ipynb ./latest/multiplot.ipynb # more files ...papermill uk-japan.ipynb ./latest/uk-japan.ipynb papermill Dropdown-interactive.ipynb ./latest/Dropdown-interactive.ipynbgit add . git commit -m "update" git pushterminal-notifier -title Covid19 -subtitle "Daily Updated" -message "Completed" -open "https://mybinder.org/v2/gh/shinokada/covid-19-stats/master"now=$(date)echo "launchd update completed at $now" Since we are setting PATH EnvironmentVariables in the plist file, we don't need to worry about Papermill and terminal-notifier absolute paths. You can test if it works by bash covid19-launchd. This bash file needs permission to execute. $ chmod u+x covid19-cron lauchctl controls the macOS launchd process. It has subcommand such as list, start, stop, load, unload, etc. For my case; $ launchctl list | grep covid- 0 com.shinokada.covid19# test/debug $ launchctl start com.shinokada.covid19# if you need to stop$ launchctl stop com.shinokada.covid19# load the job$ launchctl load ~/Library/LaunchAgents/com.shinokada.covid19.plist# unload the job$ launchctl unload ~/Library/LaunchAgents/com.shinokada.covid19.plist# get help$ launchctl help launchctl does not have a reload command for reading changes to the config.plist file. Instead, you must unload and then load the plist file anew, e.g.: $ launchctl unload ~/Library/LaunchAgents/com.shinokada.covid19.plist$ launchctl load $_ $_, like !$, refers to the last argument of the previous command. If you make any changes to the script or plist, make sure you unload and load the plist. launchctl quick guide launchctl has many subcommands and the following diagram shows important ones. Scheduled tasks save your time and easy to set up. You can set it up not only for your Data Science projects but also for your day-to-day work, such as updating node packages, homebrew formulae, etc. If you save 3 minutes a day, it will save more than 18 hours a year! If you are interested, you can see my sample project here. Get full access to every story on Medium by becoming a member.
[ { "code": null, "e": 289, "s": 172, "text": "Table of contentsIntroduction1. Papermill and terminal-notifier2. cron for Linux/macOS3. launchd for macOSConclusion" }, { "code": null, "e": 313, "s": 289, "text": "[Update.1 : 2021–05–28]" }, { "code": null, "e": 574, "s": 313, "text": "Do you have a Data Science project that requires your time every day? Do you use data feeds that update daily? For example, the 2019 Novel Coronavirus COVID-19 (2019-nCoV) Data Repository by Johns Hopkins CSSE updates daily and I use it in my personal project." }, { "code": null, "e": 916, "s": 574, "text": "Manually, I start Jupyter, open a project, restart the Kernel and run all the cells, then git add/commit/push. It is a bit of work. In this article, I am going to share a step-by-step process to set up launchd and cron jobs for your data science project so that it will automatically update your project behind the scene and even notify you." }, { "code": null, "e": 960, "s": 916, "text": "cron for Linux/macOS and launched for macOS" }, { "code": null, "e": 1057, "s": 960, "text": "Although launchd is the preferred method in macOS, the cron method still works in macOS as well." }, { "code": null, "e": 1276, "s": 1057, "text": "cron is a Linux utility that schedules a command or script on your server/computer to run automatically at a specified time and date. A cron job is the scheduled task and it is very useful to automate repetitive tasks." }, { "code": null, "e": 1379, "s": 1276, "text": "launchd is created by Apple and is a replacement for a lot of Unix tools, like cron, inetd, init, etc." }, { "code": null, "e": 1475, "s": 1379, "text": "You can start scheduling tasks and save a lot of your precious time after reading this article." }, { "code": null, "e": 1498, "s": 1475, "text": "towardsdatascience.com" }, { "code": null, "e": 1521, "s": 1498, "text": "towardsdatascience.com" }, { "code": null, "e": 1671, "s": 1521, "text": "Papermill is a tool for parameterizing and executing Jupyter Notebooks. I can use this to run a Jupyter Notebook file in a cron and launchd job file." }, { "code": null, "e": 1695, "s": 1671, "text": "$ pip install papermill" }, { "code": null, "e": 1698, "s": 1695, "text": "or" }, { "code": null, "e": 1741, "s": 1698, "text": "$ pip3 install papermill$ papermill --help" }, { "code": null, "e": 1788, "s": 1741, "text": "You can find command-line interface help here." }, { "code": null, "e": 1807, "s": 1788, "text": "Papermill’s usage:" }, { "code": null, "e": 1853, "s": 1807, "text": "papermill [OPTIONS] NOTEBOOK_PATH OUTPUT_PATH" }, { "code": null, "e": 1886, "s": 1853, "text": "I will show you an example soon." }, { "code": null, "e": 2022, "s": 1886, "text": "terminal-notifier is a command-line tool to send macOS User Notifications. I will use this to notify me when the scheduled job is done." }, { "code": null, "e": 2049, "s": 2022, "text": "Install terminal-notifier." }, { "code": null, "e": 2107, "s": 2049, "text": "$ brew install terminal-notifier$ terminal-notifier -help" }, { "code": null, "e": 2130, "s": 2107, "text": "towardsdatascience.com" }, { "code": null, "e": 2352, "s": 2130, "text": "In macOS, you can run a background job on a timed schedule in two ways: launchd jobs and cron jobs. Note that it is still supported in macOS v10.15 even though cronis not a recommended solution and launchd has superseded." }, { "code": null, "e": 2403, "s": 2352, "text": "You can set up your cron job using your user name:" }, { "code": null, "e": 2467, "s": 2403, "text": "$ whoamiyour-name$ sudo crontab -u your-name -ePassword:sh-3.2#" }, { "code": null, "e": 2566, "s": 2467, "text": "You can enable the root user by using sudo su in macOS so that you are not required your password." }, { "code": null, "e": 2601, "s": 2566, "text": "$ sudo su$ crontab -u your-name -e" }, { "code": null, "e": 2666, "s": 2601, "text": "-u specifies the name of the user. -e edits the current crontab." }, { "code": null, "e": 2744, "s": 2666, "text": "Add five numbers as described above and a path to a file you want to execute." }, { "code": null, "e": 2753, "s": 2744, "text": "Example:" }, { "code": null, "e": 2806, "s": 2753, "text": "0 10 * * * ~/DataScience/covid-19-stats/covid19-cron" }, { "code": null, "e": 2896, "s": 2806, "text": "The above will run the file ~/DataScience/covid-19-stats/covid19-cron every day at 10:00." }, { "code": null, "e": 3070, "s": 2896, "text": "If the system is turned off or asleep, cron jobs do not execute. If you miss the designated time, it will exectute at the next designated time when your system is turned on." }, { "code": null, "e": 3104, "s": 3070, "text": "You can output stdout and stderr:" }, { "code": null, "e": 3217, "s": 3104, "text": "# log stdout and stderr42 6 * * * ~/DataScience/covid-19-stats/covid19-cron > /tmp/stdout.log 2> /tmp/stderr.log" }, { "code": null, "e": 3322, "s": 3217, "text": "> redirect the standard output to /tmp/stdout.log and >2 redirect the standard error to /tmp/stderr.log." }, { "code": null, "e": 3367, "s": 3322, "text": "Once you set up a cron job, you can list it:" }, { "code": null, "e": 3432, "s": 3367, "text": "$ crontab -l0 20 * * * ~/DataScience/covid-19-stats/covid19-cron" }, { "code": null, "e": 3472, "s": 3432, "text": "If you want to remove all the cron job:" }, { "code": null, "e": 3485, "s": 3472, "text": "$ crontab -r" }, { "code": null, "e": 3532, "s": 3485, "text": "You can add multiple cron jobs in the crontab." }, { "code": null, "e": 3659, "s": 3532, "text": "0 20 * * * ~/DataScience/covid-19-stats/covid19-cron0 7 * * * Path/to/file/to/execute0 7 * * 0 Path/to/another/file/to/execute" }, { "code": null, "e": 3722, "s": 3659, "text": "crontab guru is a quick and simple tool for the cron schedule." }, { "code": null, "e": 3990, "s": 3722, "text": "You can place all cron job files in a directory, but I place it in the project root. Change the current working directory to your project, create a cron job file, and open it in an editor. Executables should have no .sh extension according to the Google style guides." }, { "code": null, "e": 4049, "s": 3990, "text": "$ cd path/to/project$ touch covid19-cron$ vim covid19-cron" }, { "code": null, "e": 4157, "s": 4049, "text": "The shebang used in the first line in scripts is to indicate the UNIX/Linux operating system for execution." }, { "code": null, "e": 4249, "s": 4157, "text": "Even though Papermill and terminal-notifier work in a terminal, we need to add their paths." }, { "code": null, "e": 4266, "s": 4249, "text": "Let’s find them." }, { "code": null, "e": 4365, "s": 4266, "text": "$ which papermill/usr/local/bin/papermill$ which terminal-notifier/usr/local/bin/terminal-notifier" }, { "code": null, "e": 4390, "s": 4365, "text": "In my covid19-cron file:" }, { "code": null, "e": 4966, "s": 4390, "text": "#!/usr/bin/env bash# run covid-19 files # git add, comit and pushdir=/Users/shinokada/DataScience/covid-19-statspapermill=/usr/local/bin/papermillnotifier=/usr/local/bin/terminal-notifiercd $dir$papermill covid-19-matplotlib.ipynb ./latest/covid-19-matplotlib.ipynb# more files ...$papermill covid-19-plotly.ipynb ./latest/covid-19-plotly.ipynb git add . git commit -m \"update\" git push$notifier -title Covid19 -subtitle \"Daily Updated\" -message \"Completed\" -open \"https://mybinder.org/v2/gh/shinokada/covid-19-stats/master\"now=$(date)echo \"Cron job update completed at $now\"" }, { "code": null, "e": 5166, "s": 4966, "text": "I create “latest” directory in the root directory. The Papermill outputs files to this “latest” directory. Since we are going to use git, you need to make sure that you have .git in the project root." }, { "code": null, "e": 5239, "s": 5166, "text": "If you are using %run somefile, I suggest you add them to the cron-file." }, { "code": null, "e": 5315, "s": 5239, "text": "I use title, substitle, message and open for the terminal-notifier options." }, { "code": null, "e": 5345, "s": 5315, "text": "terminal-notifier quick guide" }, { "code": null, "e": 5389, "s": 5345, "text": "This bash file needs permission to execute." }, { "code": null, "e": 5414, "s": 5389, "text": "$ chmod u+x covid19-cron" }, { "code": null, "e": 5447, "s": 5414, "text": "chmod sets permissions to files." }, { "code": null, "e": 5511, "s": 5447, "text": "chmod u+x covid19-cron allows the user to execute covid19-cron." }, { "code": null, "e": 5545, "s": 5511, "text": "The above command is the same as:" }, { "code": null, "e": 5570, "s": 5545, "text": "$ chmod 744 covid19-cron" }, { "code": null, "e": 5690, "s": 5570, "text": "Your terminal sends its output and error messages by mail after running a cron job. Let’s check if the cron job worked." }, { "code": null, "e": 5697, "s": 5690, "text": "$ mail" }, { "code": null, "e": 5894, "s": 5697, "text": "You need to press enter to read messages, and then q and enter to quit. Use j to see the next lines. You need to check if the mail has no errors. In case of errors, you need to attend the problem." }, { "code": null, "e": 6032, "s": 5894, "text": "You need to reset the crontab time to test your cron job. launchd allows us to test a job but for cron this is the only way you can test." }, { "code": null, "e": 6193, "s": 6032, "text": "$ sudo crontab -u your-name -e# change time 5 20 * * * ~/DataScience/covid-19-stats/covid19-cron$ crontab -l5 20 * * * ~/DataScience/covid-19-stats/covid19-cron" }, { "code": null, "e": 6250, "s": 6193, "text": "When the test is done, it will display the notification." }, { "code": null, "e": 6396, "s": 6250, "text": "launchd is a unified, open-source service management framework for starting, stopping and managing daemons, applications, processes, and scripts." }, { "code": null, "e": 6570, "s": 6396, "text": "If you schedule a launchd job by setting the StartCalendarInterval key and the computer is asleep when the job should have run, your job will run when the computer wakes up." }, { "code": null, "e": 6695, "s": 6570, "text": "However, if the machine is off when the job should have run, the job does not execute until the next designated time occurs." }, { "code": null, "e": 6997, "s": 6695, "text": "A PLIST file is a system-wide and per-user daemon/agent configuration file. A daemon/agent is a program running in the background without user input. You define the name of the program, when you run it, what you want to run, etc. You store all your plist files in the ~/Library/LaunchAgents directory." }, { "code": null, "e": 7072, "s": 6997, "text": "[Update.1] If you don’t have ~/Library/LaunchAgents you need to create it." }, { "code": null, "e": 7186, "s": 7072, "text": "# check ~/Library if it has LaunchAgents$ ls ~/Library# if not create the directory$ mkdir ~/Library/LaunchAgents" }, { "code": null, "e": 7207, "s": 7186, "text": "Create a plist file:" }, { "code": null, "e": 7270, "s": 7207, "text": "$ cd ~/Library/LaunchAgents$ touch com.shinokada.covid19.plist" }, { "code": null, "e": 7306, "s": 7270, "text": "In the com.shinokada.covid19.plist:" }, { "code": null, "e": 8349, "s": 7306, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?><!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\"><plist version=\"1.0\"> <dict> <key>Label</key> <string>com.shinokada.covid19</string> <key>Program</key> <string>/Users/shinokada/DataScience/covid-19-stats/covid19-launchd</string> <key>EnvironmentVariables</key> <dict> <key>PATH</key> <string>/bin:/usr/bin:/usr/local/bin</string> </dict> <key>StandardInPath</key> <string>/tmp/covid.stdin</string> <key>StandardOutPath</key> <string>/tmp/covid.stdout</string> <key>StandardErrorPath</key> <string>/tmp/covid.stderr</string> <key>WorkingDirectory</key> <string>/Users/shinokada/DataScience/covid-19-stats</string> <key>StartCalendarInterval</key> <dict> <key>Hour</key> <integer>8</integer> <key>Minute</key> <integer>0</integer> </dict> </dict></plist>" }, { "code": null, "e": 8442, "s": 8349, "text": "Here I run /Users/shinokada/DataScience/covid-19-stats/covid19-launchd at 8:00 AM every day." }, { "code": null, "e": 8482, "s": 8442, "text": "Configuration in plist file quick guide" }, { "code": null, "e": 8598, "s": 8482, "text": "Create a file called covid19-launchd in the project root directory. This is very similar to the above covid19-cron." }, { "code": null, "e": 9147, "s": 8598, "text": "#!/usr/bin/env bash# run covid-19 files # git add, comit and pushpapermill covid-19-data.ipynb ./latest/covid-19-data.ipynbpapermill multiplot.ipynb ./latest/multiplot.ipynb # more files ...papermill uk-japan.ipynb ./latest/uk-japan.ipynb papermill Dropdown-interactive.ipynb ./latest/Dropdown-interactive.ipynbgit add . git commit -m \"update\" git pushterminal-notifier -title Covid19 -subtitle \"Daily Updated\" -message \"Completed\" -open \"https://mybinder.org/v2/gh/shinokada/covid-19-stats/master\"now=$(date)echo \"launchd update completed at $now\"" }, { "code": null, "e": 9290, "s": 9147, "text": "Since we are setting PATH EnvironmentVariables in the plist file, we don't need to worry about Papermill and terminal-notifier absolute paths." }, { "code": null, "e": 9340, "s": 9290, "text": "You can test if it works by bash covid19-launchd." }, { "code": null, "e": 9384, "s": 9340, "text": "This bash file needs permission to execute." }, { "code": null, "e": 9409, "s": 9384, "text": "$ chmod u+x covid19-cron" }, { "code": null, "e": 9518, "s": 9409, "text": "lauchctl controls the macOS launchd process. It has subcommand such as list, start, stop, load, unload, etc." }, { "code": null, "e": 9531, "s": 9518, "text": "For my case;" }, { "code": null, "e": 9891, "s": 9531, "text": "$ launchctl list | grep covid- 0 com.shinokada.covid19# test/debug $ launchctl start com.shinokada.covid19# if you need to stop$ launchctl stop com.shinokada.covid19# load the job$ launchctl load ~/Library/LaunchAgents/com.shinokada.covid19.plist# unload the job$ launchctl unload ~/Library/LaunchAgents/com.shinokada.covid19.plist# get help$ launchctl help" }, { "code": null, "e": 10044, "s": 9891, "text": "launchctl does not have a reload command for reading changes to the config.plist file. Instead, you must unload and then load the plist file anew, e.g.:" }, { "code": null, "e": 10133, "s": 10044, "text": "$ launchctl unload ~/Library/LaunchAgents/com.shinokada.covid19.plist$ launchctl load $_" }, { "code": null, "e": 10199, "s": 10133, "text": "$_, like !$, refers to the last argument of the previous command." }, { "code": null, "e": 10288, "s": 10199, "text": "If you make any changes to the script or plist, make sure you unload and load the plist." }, { "code": null, "e": 10310, "s": 10288, "text": "launchctl quick guide" }, { "code": null, "e": 10389, "s": 10310, "text": "launchctl has many subcommands and the following diagram shows important ones." }, { "code": null, "e": 10717, "s": 10389, "text": "Scheduled tasks save your time and easy to set up. You can set it up not only for your Data Science projects but also for your day-to-day work, such as updating node packages, homebrew formulae, etc. If you save 3 minutes a day, it will save more than 18 hours a year! If you are interested, you can see my sample project here." } ]
Feed Forward Neural Networks — How To Successfully Build Them in Python | by Saul Dobilas | Towards Data Science
Neural Networks have been the central talking point over the last few years. While they may initially seem intimidating, I assure you that you do not need a Ph.D. to understand how they work. In this article, I will take you through the main ideas behind basic Neural Networks, also known as Feed Forward NNs or Multilayer Perceptrons (MLPs), and show you how to build them in Python using Tensorflow and Keras libraries. Feed Forward Neural Network’s place within the universe of Machine Learning A visual explanation of how Feed Forward NNs work- Network structure and terminology- Parameters and activation functions- Loss functions, optimizers, and training Python examples of how to build and train your own Feed Forward Neural Networks Machine Learning is a vast and ever-expanding space with new algorithms developed daily. I have attempted to bring structure to this world by categorizing some of the most commonly used algorithms in the interactive chart below. Click on different categories to enlarge and reveal more.👇 While this categorization is not perfect, it brings a general understanding of how different pieces fit together, and hopefully, it can also facilitate your data science learning journey. I have placed Neural Networks in a distinct category recognizing their unique approach to Machine Learning. However, it is essential to remember that Neural Networks are most frequently employed to solve classification and regression problems using labeled training data. Hence, an alternative approach could be to put them under the Supervised branch of Machine Learning. If you enjoy Data Science and Machine Learning, please subscribe to get an email whenever I publish a new story. First, let’s familiarize ourselves with the basic structure of a Neural Network. Input Layer — contains one or more input nodes. For example, suppose you want to predict whether it will rain tomorrow and base your decision on two variables, humidity and wind speed. In that case, your first input would be the value for humidity, and the second input would be the value for wind speed. Hidden Layer — this layer houses hidden nodes, each containing an activation function (more on these later). Note that a Neural Network with multiple hidden layers is known as Deep Neural Network. Output Layer — contains one or more output nodes. Following the same weather prediction example above, you could choose to have only one output node generating a rain probability (where >0.5 means rain tomorrow, and ≤0.5 no rain tomorrow). Alternatively, you could have two output nodes, one for rain and another for no rain. Note, you can use a different activation function for output nodes vs. hidden nodes. Connections — lines joining different nodes are known as connections. These contain kernels (weights) and biases, the parameters that get optimized during the training of a neural network. Let’s take a closer look at kernels (weights) and biases to understand what they do. For simplicity, we create a basic neural network with one input node, two hidden nodes, and one output node (1–2–1). Kernels (weights) — used to scale input and hidden node values. Each connection typically holds a different weight. Biases — used to adjust scaled values before passing them through an activation function. Activation functions — think of activation functions as standard curves (building blocks) used by the Neural Network to create a custom curve to fit the training data. Passing different input values through the network selects different sections of the standard curve, which are then assembled into a final custom-fit curve. There are many activation functions to choose from, with Softplus, ReLU, and Sigmoid being the most commonly used. Here are the shapes and equations of six frequently used activation functions in Neural Networks: As we are now familiar with kernels (weights), biases, and activation functions, let’s use the same Neural Network to calculate the probability of rain tomorrow based on today’s humidity. Note, I have already trained this Neural Network (see Python section below). Hence, we already know the values for kernels (weights) and biases. The below illustration shows you a step-by-step process of how FF Neural Network takes an input value and produces the answer (output value). As you can see, the above Neural Network tells us that a 50% humidity today implies a 33% probability of rain tomorrow. Training Neural Networks involves a complicated process known as backpropagation. I will not go through a step-by-step explanation of how backpropagation works since it is a big enough topic deserving a separate article. Instead, let me briefly introduce you to loss functions and optimizers and summarize what happens when we “train” a Neural Network. Loss — represents the “size” of error between the true values/labels and the predicted values/labels. The goal of training a Neural Network is to minimize this loss. The smaller the loss, the closer the match between the true and the predicted data. There are many loss functions to choose from, with BinaryCrossentropy, CategoricalCrossentropy, and MeanSquaredError being the most common. Optimizers — are the algorithms used in backpropagation. The goal of an optimizer is to find the optimum set of kernels (weights) and biases to minimize the loss. Optimizers typically use a gradient descent approach, which allows them to iteratively find the “best” possible configuration of weights and biases. The most commonly used ones are SGD, ADAM, and RMSProp. Training a Neural Network is basically fitting a custom curve through the training data until it can approximate it as well as possible. The graph below illustrates what a custom-fitted curve could look like in a specific scenario. This example contains a set of data that seem to flip between 0 and 1 as the value for input increases. In general, the wide selection of activation functions combined with the ability to add as many hidden nodes as we wish (provided we have sufficient computational power) means that Neural Networks can create a curve of any shape to fit the data. However, having this extreme flexibility may sometimes lead to overfitting the data. Hence, we must always ensure that we validate the model on the test/validation set before using it to make predictions. Feed Forward Neural Networks take one or multiple input values and apply transformations using kernels (weights) and biases before passing results through activation functions. In the end, we get an output (prediction), which is a result of this complex set of transformations optimized through training. We train Neural Networks by fitting a custom curve through the training data, guided by loss minimization and achieved through parameter (kernels and biases) optimization. Let’s now have some fun and build our own Neural Network. We will use historic Australian weather data to train a Neural Network that predicts whether it will rain tomorrow or not. We’ll need the following data and libraries: Australian weather data from Kaggle (license: Creative Commons, original source of the data: Commonwealth of Australia, Bureau of Meteorology). Pandas and Numpy for data manipulation Plotly for data visualizations Tensorflow/Keras for Neural Networks Scikit-learn library for splitting the data into train-test samples, and for some basic model evaluation Let’s import all the libraries: The above code prints package versions used in this example: Tensorflow/Keras: 2.7.0pandas: 1.3.4numpy: 1.21.4sklearn: 1.0.1plotly: 5.4.0 Next, we download and ingest Australian weather data (source: Kaggle). We also do some simple data manipulations and derive new variables for our models. And this is what the data looks like: Now we train and evaluate our Feed Forward (FF) Neural Network. I have extensively commented the code below to provide you with a clear understanding of what each part does. Hence, I will not repeat the same in the body of the article. Using one input (Humidity3pm) In short, we are using humidity at 3 pm today to predict whether it will rain tomorrow or not. Our Neural Network has a simple structure (1–2–1) analyzed earlier in this article: one input node, two hidden nodes, and one output node. A couple of things to note: The below code performs validation twice, once on a portion of X_train data (see validation_split in step 5) and another time on a test sample created in step 2. Of course, there is no need to do it twice, so feel free to use either method to validate your model. The data was imbalanced (more sunny days than rainy days), so I’ve adjusted classes_weight in step 5. The above code prints the following summary and evaluation metrics for our 1–2–1 Neural Network: Note that weights and biases for this model are different from the ones in the calculated example earlier in this article. It is because Neural Network training uses a stochastic (random) approach within the optimizer algorithms. Hence, your model will be different every time you re-train it. Let’s now plot the prediction curve on a chart. Using two inputs (WindGustSpeed and Humidity3pm) Let’s see how the network and predictions change when we use two inputs (WindGustSpeed and Humidity3pm) to train a Neural Network that has a 2–2–1 structure. Feel free to experiment at your own time by training a model with 17 inputs and a different number of hidden nodes. And the results are: Since we used two inputs, we can still visualize the predictions. However, this time we need a 3D chart to do it: Neural Networks are not as scary as they seem at first. I sincerely hope you enjoyed reading this article and obtained some new knowledge. Feel feel to use the code provided in this article to build your own Neural Networks. Also, you can find the complete Jupyter Notebook in my GitHub repository. As I try to make my articles more useful for readers, I would appreciate it if you could let me know what has driven you to read this piece and whether it has given you the answers you were looking for. If not, what was missing? Cheers! 👏Saul Dobilas If you have already spent your learning budget for this month, please remember me next time. My personalized link to join Medium is: solclover.com Other articles you may find interesting:
[ { "code": null, "e": 364, "s": 172, "text": "Neural Networks have been the central talking point over the last few years. While they may initially seem intimidating, I assure you that you do not need a Ph.D. to understand how they work." }, { "code": null, "e": 594, "s": 364, "text": "In this article, I will take you through the main ideas behind basic Neural Networks, also known as Feed Forward NNs or Multilayer Perceptrons (MLPs), and show you how to build them in Python using Tensorflow and Keras libraries." }, { "code": null, "e": 670, "s": 594, "text": "Feed Forward Neural Network’s place within the universe of Machine Learning" }, { "code": null, "e": 834, "s": 670, "text": "A visual explanation of how Feed Forward NNs work- Network structure and terminology- Parameters and activation functions- Loss functions, optimizers, and training" }, { "code": null, "e": 914, "s": 834, "text": "Python examples of how to build and train your own Feed Forward Neural Networks" }, { "code": null, "e": 1202, "s": 914, "text": "Machine Learning is a vast and ever-expanding space with new algorithms developed daily. I have attempted to bring structure to this world by categorizing some of the most commonly used algorithms in the interactive chart below. Click on different categories to enlarge and reveal more.👇" }, { "code": null, "e": 1390, "s": 1202, "text": "While this categorization is not perfect, it brings a general understanding of how different pieces fit together, and hopefully, it can also facilitate your data science learning journey." }, { "code": null, "e": 1763, "s": 1390, "text": "I have placed Neural Networks in a distinct category recognizing their unique approach to Machine Learning. However, it is essential to remember that Neural Networks are most frequently employed to solve classification and regression problems using labeled training data. Hence, an alternative approach could be to put them under the Supervised branch of Machine Learning." }, { "code": null, "e": 1876, "s": 1763, "text": "If you enjoy Data Science and Machine Learning, please subscribe to get an email whenever I publish a new story." }, { "code": null, "e": 1957, "s": 1876, "text": "First, let’s familiarize ourselves with the basic structure of a Neural Network." }, { "code": null, "e": 2262, "s": 1957, "text": "Input Layer — contains one or more input nodes. For example, suppose you want to predict whether it will rain tomorrow and base your decision on two variables, humidity and wind speed. In that case, your first input would be the value for humidity, and the second input would be the value for wind speed." }, { "code": null, "e": 2459, "s": 2262, "text": "Hidden Layer — this layer houses hidden nodes, each containing an activation function (more on these later). Note that a Neural Network with multiple hidden layers is known as Deep Neural Network." }, { "code": null, "e": 2870, "s": 2459, "text": "Output Layer — contains one or more output nodes. Following the same weather prediction example above, you could choose to have only one output node generating a rain probability (where >0.5 means rain tomorrow, and ≤0.5 no rain tomorrow). Alternatively, you could have two output nodes, one for rain and another for no rain. Note, you can use a different activation function for output nodes vs. hidden nodes." }, { "code": null, "e": 3059, "s": 2870, "text": "Connections — lines joining different nodes are known as connections. These contain kernels (weights) and biases, the parameters that get optimized during the training of a neural network." }, { "code": null, "e": 3261, "s": 3059, "text": "Let’s take a closer look at kernels (weights) and biases to understand what they do. For simplicity, we create a basic neural network with one input node, two hidden nodes, and one output node (1–2–1)." }, { "code": null, "e": 3377, "s": 3261, "text": "Kernels (weights) — used to scale input and hidden node values. Each connection typically holds a different weight." }, { "code": null, "e": 3467, "s": 3377, "text": "Biases — used to adjust scaled values before passing them through an activation function." }, { "code": null, "e": 3792, "s": 3467, "text": "Activation functions — think of activation functions as standard curves (building blocks) used by the Neural Network to create a custom curve to fit the training data. Passing different input values through the network selects different sections of the standard curve, which are then assembled into a final custom-fit curve." }, { "code": null, "e": 4005, "s": 3792, "text": "There are many activation functions to choose from, with Softplus, ReLU, and Sigmoid being the most commonly used. Here are the shapes and equations of six frequently used activation functions in Neural Networks:" }, { "code": null, "e": 4193, "s": 4005, "text": "As we are now familiar with kernels (weights), biases, and activation functions, let’s use the same Neural Network to calculate the probability of rain tomorrow based on today’s humidity." }, { "code": null, "e": 4480, "s": 4193, "text": "Note, I have already trained this Neural Network (see Python section below). Hence, we already know the values for kernels (weights) and biases. The below illustration shows you a step-by-step process of how FF Neural Network takes an input value and produces the answer (output value)." }, { "code": null, "e": 4600, "s": 4480, "text": "As you can see, the above Neural Network tells us that a 50% humidity today implies a 33% probability of rain tomorrow." }, { "code": null, "e": 4821, "s": 4600, "text": "Training Neural Networks involves a complicated process known as backpropagation. I will not go through a step-by-step explanation of how backpropagation works since it is a big enough topic deserving a separate article." }, { "code": null, "e": 4953, "s": 4821, "text": "Instead, let me briefly introduce you to loss functions and optimizers and summarize what happens when we “train” a Neural Network." }, { "code": null, "e": 5343, "s": 4953, "text": "Loss — represents the “size” of error between the true values/labels and the predicted values/labels. The goal of training a Neural Network is to minimize this loss. The smaller the loss, the closer the match between the true and the predicted data. There are many loss functions to choose from, with BinaryCrossentropy, CategoricalCrossentropy, and MeanSquaredError being the most common." }, { "code": null, "e": 5711, "s": 5343, "text": "Optimizers — are the algorithms used in backpropagation. The goal of an optimizer is to find the optimum set of kernels (weights) and biases to minimize the loss. Optimizers typically use a gradient descent approach, which allows them to iteratively find the “best” possible configuration of weights and biases. The most commonly used ones are SGD, ADAM, and RMSProp." }, { "code": null, "e": 6047, "s": 5711, "text": "Training a Neural Network is basically fitting a custom curve through the training data until it can approximate it as well as possible. The graph below illustrates what a custom-fitted curve could look like in a specific scenario. This example contains a set of data that seem to flip between 0 and 1 as the value for input increases." }, { "code": null, "e": 6293, "s": 6047, "text": "In general, the wide selection of activation functions combined with the ability to add as many hidden nodes as we wish (provided we have sufficient computational power) means that Neural Networks can create a curve of any shape to fit the data." }, { "code": null, "e": 6498, "s": 6293, "text": "However, having this extreme flexibility may sometimes lead to overfitting the data. Hence, we must always ensure that we validate the model on the test/validation set before using it to make predictions." }, { "code": null, "e": 6803, "s": 6498, "text": "Feed Forward Neural Networks take one or multiple input values and apply transformations using kernels (weights) and biases before passing results through activation functions. In the end, we get an output (prediction), which is a result of this complex set of transformations optimized through training." }, { "code": null, "e": 6975, "s": 6803, "text": "We train Neural Networks by fitting a custom curve through the training data, guided by loss minimization and achieved through parameter (kernels and biases) optimization." }, { "code": null, "e": 7156, "s": 6975, "text": "Let’s now have some fun and build our own Neural Network. We will use historic Australian weather data to train a Neural Network that predicts whether it will rain tomorrow or not." }, { "code": null, "e": 7201, "s": 7156, "text": "We’ll need the following data and libraries:" }, { "code": null, "e": 7345, "s": 7201, "text": "Australian weather data from Kaggle (license: Creative Commons, original source of the data: Commonwealth of Australia, Bureau of Meteorology)." }, { "code": null, "e": 7384, "s": 7345, "text": "Pandas and Numpy for data manipulation" }, { "code": null, "e": 7415, "s": 7384, "text": "Plotly for data visualizations" }, { "code": null, "e": 7452, "s": 7415, "text": "Tensorflow/Keras for Neural Networks" }, { "code": null, "e": 7557, "s": 7452, "text": "Scikit-learn library for splitting the data into train-test samples, and for some basic model evaluation" }, { "code": null, "e": 7589, "s": 7557, "text": "Let’s import all the libraries:" }, { "code": null, "e": 7650, "s": 7589, "text": "The above code prints package versions used in this example:" }, { "code": null, "e": 7727, "s": 7650, "text": "Tensorflow/Keras: 2.7.0pandas: 1.3.4numpy: 1.21.4sklearn: 1.0.1plotly: 5.4.0" }, { "code": null, "e": 7881, "s": 7727, "text": "Next, we download and ingest Australian weather data (source: Kaggle). We also do some simple data manipulations and derive new variables for our models." }, { "code": null, "e": 7919, "s": 7881, "text": "And this is what the data looks like:" }, { "code": null, "e": 8155, "s": 7919, "text": "Now we train and evaluate our Feed Forward (FF) Neural Network. I have extensively commented the code below to provide you with a clear understanding of what each part does. Hence, I will not repeat the same in the body of the article." }, { "code": null, "e": 8185, "s": 8155, "text": "Using one input (Humidity3pm)" }, { "code": null, "e": 8419, "s": 8185, "text": "In short, we are using humidity at 3 pm today to predict whether it will rain tomorrow or not. Our Neural Network has a simple structure (1–2–1) analyzed earlier in this article: one input node, two hidden nodes, and one output node." }, { "code": null, "e": 8447, "s": 8419, "text": "A couple of things to note:" }, { "code": null, "e": 8711, "s": 8447, "text": "The below code performs validation twice, once on a portion of X_train data (see validation_split in step 5) and another time on a test sample created in step 2. Of course, there is no need to do it twice, so feel free to use either method to validate your model." }, { "code": null, "e": 8813, "s": 8711, "text": "The data was imbalanced (more sunny days than rainy days), so I’ve adjusted classes_weight in step 5." }, { "code": null, "e": 8910, "s": 8813, "text": "The above code prints the following summary and evaluation metrics for our 1–2–1 Neural Network:" }, { "code": null, "e": 9204, "s": 8910, "text": "Note that weights and biases for this model are different from the ones in the calculated example earlier in this article. It is because Neural Network training uses a stochastic (random) approach within the optimizer algorithms. Hence, your model will be different every time you re-train it." }, { "code": null, "e": 9252, "s": 9204, "text": "Let’s now plot the prediction curve on a chart." }, { "code": null, "e": 9301, "s": 9252, "text": "Using two inputs (WindGustSpeed and Humidity3pm)" }, { "code": null, "e": 9459, "s": 9301, "text": "Let’s see how the network and predictions change when we use two inputs (WindGustSpeed and Humidity3pm) to train a Neural Network that has a 2–2–1 structure." }, { "code": null, "e": 9575, "s": 9459, "text": "Feel free to experiment at your own time by training a model with 17 inputs and a different number of hidden nodes." }, { "code": null, "e": 9596, "s": 9575, "text": "And the results are:" }, { "code": null, "e": 9710, "s": 9596, "text": "Since we used two inputs, we can still visualize the predictions. However, this time we need a 3D chart to do it:" }, { "code": null, "e": 9849, "s": 9710, "text": "Neural Networks are not as scary as they seem at first. I sincerely hope you enjoyed reading this article and obtained some new knowledge." }, { "code": null, "e": 10009, "s": 9849, "text": "Feel feel to use the code provided in this article to build your own Neural Networks. Also, you can find the complete Jupyter Notebook in my GitHub repository." }, { "code": null, "e": 10238, "s": 10009, "text": "As I try to make my articles more useful for readers, I would appreciate it if you could let me know what has driven you to read this piece and whether it has given you the answers you were looking for. If not, what was missing?" }, { "code": null, "e": 10260, "s": 10238, "text": "Cheers! 👏Saul Dobilas" }, { "code": null, "e": 10393, "s": 10260, "text": "If you have already spent your learning budget for this month, please remember me next time. My personalized link to join Medium is:" }, { "code": null, "e": 10407, "s": 10393, "text": "solclover.com" } ]
C Program to print contents of file - GeeksforGeeks
20 May, 2017 fopen() is used to open and fclose() is used to close a file in C #include <stdio.h>#include <stdlib.h> // For exit() int main(){ FILE *fptr; char filename[100], c; printf("Enter the filename to open \n"); scanf("%s", filename); // Open file fptr = fopen(filename, "r"); if (fptr == NULL) { printf("Cannot open file \n"); exit(0); } // Read contents from file c = fgetc(fptr); while (c != EOF) { printf ("%c", c); c = fgetc(fptr); } fclose(fptr); return 0;} Output: Enter the filename to open a.txt /*Contents of a.txt*/ cpp-file-handling C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. rand() and srand() in C/C++ Left Shift and Right Shift Operators in C/C++ Command line arguments in C/C++ Function Pointer in C Different methods to reverse a string in C/C++ Substring in C++ TCP Server-Client implementation in C Enumeration (or enum) in C Structures in C std::string class in C++
[ { "code": null, "e": 24454, "s": 24426, "text": "\n20 May, 2017" }, { "code": null, "e": 24520, "s": 24454, "text": "fopen() is used to open and fclose() is used to close a file in C" }, { "code": "#include <stdio.h>#include <stdlib.h> // For exit() int main(){ FILE *fptr; char filename[100], c; printf(\"Enter the filename to open \\n\"); scanf(\"%s\", filename); // Open file fptr = fopen(filename, \"r\"); if (fptr == NULL) { printf(\"Cannot open file \\n\"); exit(0); } // Read contents from file c = fgetc(fptr); while (c != EOF) { printf (\"%c\", c); c = fgetc(fptr); } fclose(fptr); return 0;}", "e": 24999, "s": 24520, "text": null }, { "code": null, "e": 25007, "s": 24999, "text": "Output:" }, { "code": null, "e": 25062, "s": 25007, "text": "Enter the filename to open\na.txt\n/*Contents of a.txt*/" }, { "code": null, "e": 25080, "s": 25062, "text": "cpp-file-handling" }, { "code": null, "e": 25091, "s": 25080, "text": "C Language" }, { "code": null, "e": 25189, "s": 25091, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25217, "s": 25189, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 25263, "s": 25217, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 25295, "s": 25263, "text": "Command line arguments in C/C++" }, { "code": null, "e": 25317, "s": 25295, "text": "Function Pointer in C" }, { "code": null, "e": 25364, "s": 25317, "text": "Different methods to reverse a string in C/C++" }, { "code": null, "e": 25381, "s": 25364, "text": "Substring in C++" }, { "code": null, "e": 25419, "s": 25381, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 25446, "s": 25419, "text": "Enumeration (or enum) in C" }, { "code": null, "e": 25462, "s": 25446, "text": "Structures in C" } ]
Entity Framework - Stored Procedures
The Entity Framework allows you to use stored procedures in the Entity Data Model instead of, or in combination with, its automatic command generation. You can use stored procedures to perform predefined logic on database tables, and many organizations have policies in place that require the use of these stored procedures. You can use stored procedures to perform predefined logic on database tables, and many organizations have policies in place that require the use of these stored procedures. It can also specify that EF should use your stored procedures for inserting, updating, or deleting entities. It can also specify that EF should use your stored procedures for inserting, updating, or deleting entities. Although the dynamically built commands are secure, efficient, and generally as good as or better than those you may write yourself, there are many cases where stored procedures already exist and your company practices may restrict direct use of the tables. Although the dynamically built commands are secure, efficient, and generally as good as or better than those you may write yourself, there are many cases where stored procedures already exist and your company practices may restrict direct use of the tables. Alternatively, you may just want to have explicit control over what is executed on the store and prefer to create stored procedures. Alternatively, you may just want to have explicit control over what is executed on the store and prefer to create stored procedures. The following example creates a new project from File → New → Project. Step 1 − Select the Console Application from the middle pane and enter StoredProceduresDemo in the name field. Step 2 − In Server explorer right-click on your database. Step 3 − Select New Query and enter the following code in T-SQL editor to add a new table in your database. IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[StudentGrade]') AND type in (N'U')) BEGIN CREATE TABLE [dbo].[StudentGrade]( [EnrollmentID] [int] IDENTITY(1,1) NOT NULL, [CourseID] [int] NOT NULL, [StudentID] [int] NOT NULL, [Grade] [decimal](3, 2) NULL, CONSTRAINT [PK_StudentGrade] PRIMARY KEY CLUSTERED ( [EnrollmentID] ASC ) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY] ) ON [PRIMARY] END GO Step 4 − Right-click on the editor and select Execute. Step 5 − Right-click on your database and click refresh. You will see the newly added table in your database. Step 6 − In Server explorer, right-click on your database again. Step 7 − Select New Query and enter the following code in T-SQL editor to add a stored procedure in your database, which will return the Student grades. IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetStudentGrades]') AND type in (N'P', N'PC')) BEGIN EXEC dbo.sp_executesql @statement = N' CREATE PROCEDURE [dbo].[GetStudentGrades] @StudentID int AS SELECT EnrollmentID, Grade, CourseID, StudentID FROM dbo.StudentGrade WHERE StudentID = @StudentID ' END GO Step 8 − Right-click on the editor and select Execute. Step 9 − Right-click on your database and click refresh. You will see that a stored procedure is created in your database. Step 10 − Right-click on the project name in Solution Explorer and select Add → New Item. Step 11 − Then select ADO.NET Entity Data Model in the Templates pane. Step 12 − Enter SPModel as name, and then click Add. Step 13 − In the Choose Model Contents dialog box, select EF designer from database, and then click Next. Step 14 − Select your database and click Next. Step 15 − In the Choose Your Database Objects dialog box click on tables, views. Step 16 − Select the GetStudentGradesForCourse function located under the Stored Procedures and Functions node and click Finish. Step 17 − Select View → Other Windows → Entity Data Model Browser and right-click GetStudentGrades under Function Imports and select Edit. It will produce the following dialog. Step 18 − Click on Entities radio button and select StudentGrade from the combobox as return type of this stored procedure and click Ok. Let’s take a look at the following C# code in which all the grades will be retrieved by passing the student ID as parameter in GetStudentGrades stored procedure. class Program { static void Main(string[] args) { using (var context = new UniContextEntities()) { int studentID = 22; var studentGrades = context.GetStudentGrades(studentID); foreach (var student in studentGrades) { Console.WriteLine("Course ID: {0}, Title: {1}, Grade: {2} ", student.CourseID, student.Course.Title, student.Grade); } Console.ReadKey(); } } } When the above code is compiled and executed you will receive the following output − Course ID: 4022, Title: Microeconomics, Grade: 3.00 Course ID: 4041, Title: Macroeconomics, Grade: 3.50 We recommend that you execute the above example in a step-by-step manner for better understanding. 19 Lectures 5 hours Trevoir Williams 33 Lectures 3.5 hours Nilay Mehta 21 Lectures 2.5 hours TELCOMA Global 89 Lectures 7.5 hours Mustafa Radaideh Print Add Notes Bookmark this page
[ { "code": null, "e": 3184, "s": 3032, "text": "The Entity Framework allows you to use stored procedures in the Entity Data Model instead of, or in combination with, its automatic command generation." }, { "code": null, "e": 3357, "s": 3184, "text": "You can use stored procedures to perform predefined logic on database tables, and many organizations have policies in place that require the use of these stored procedures." }, { "code": null, "e": 3530, "s": 3357, "text": "You can use stored procedures to perform predefined logic on database tables, and many organizations have policies in place that require the use of these stored procedures." }, { "code": null, "e": 3639, "s": 3530, "text": "It can also specify that EF should use your stored procedures for inserting, updating, or deleting entities." }, { "code": null, "e": 3748, "s": 3639, "text": "It can also specify that EF should use your stored procedures for inserting, updating, or deleting entities." }, { "code": null, "e": 4006, "s": 3748, "text": "Although the dynamically built commands are secure, efficient, and generally as good as or better than those you may write yourself, there are many cases where stored procedures already exist and your company practices may restrict direct use of the tables." }, { "code": null, "e": 4264, "s": 4006, "text": "Although the dynamically built commands are secure, efficient, and generally as good as or better than those you may write yourself, there are many cases where stored procedures already exist and your company practices may restrict direct use of the tables." }, { "code": null, "e": 4397, "s": 4264, "text": "Alternatively, you may just want to have explicit control over what is executed on the store and prefer to create stored procedures." }, { "code": null, "e": 4530, "s": 4397, "text": "Alternatively, you may just want to have explicit control over what is executed on the store and prefer to create stored procedures." }, { "code": null, "e": 4601, "s": 4530, "text": "The following example creates a new project from File → New → Project." }, { "code": null, "e": 4712, "s": 4601, "text": "Step 1 − Select the Console Application from the middle pane and enter StoredProceduresDemo in the name field." }, { "code": null, "e": 4770, "s": 4712, "text": "Step 2 − In Server explorer right-click on your database." }, { "code": null, "e": 4878, "s": 4770, "text": "Step 3 − Select New Query and enter the following code in T-SQL editor to add a new table in your database." }, { "code": null, "e": 5368, "s": 4878, "text": "IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = \n OBJECT_ID(N'[dbo].[StudentGrade]') AND type in (N'U'))\n\nBEGIN\n\n CREATE TABLE [dbo].[StudentGrade](\n\n [EnrollmentID] [int] IDENTITY(1,1) NOT NULL,\n [CourseID] [int] NOT NULL,\n [StudentID] [int] NOT NULL,\n [Grade] [decimal](3, 2) NULL,\n\n CONSTRAINT [PK_StudentGrade] PRIMARY KEY CLUSTERED (\n [EnrollmentID] ASC\n )\n\n WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]\n\n ) ON [PRIMARY]\n\nEND\nGO" }, { "code": null, "e": 5423, "s": 5368, "text": "Step 4 − Right-click on the editor and select Execute." }, { "code": null, "e": 5533, "s": 5423, "text": "Step 5 − Right-click on your database and click refresh. You will see the newly added table in your database." }, { "code": null, "e": 5598, "s": 5533, "text": "Step 6 − In Server explorer, right-click on your database again." }, { "code": null, "e": 5751, "s": 5598, "text": "Step 7 − Select New Query and enter the following code in T-SQL editor to add a stored procedure in your database, which will return the Student grades." }, { "code": null, "e": 6117, "s": 5751, "text": "IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = \n OBJECT_ID(N'[dbo].[GetStudentGrades]') AND type in (N'P', N'PC'))\n\nBEGIN\n\n EXEC dbo.sp_executesql @statement = N'\n CREATE PROCEDURE [dbo].[GetStudentGrades]\n @StudentID int\n AS\n SELECT EnrollmentID, Grade, CourseID, StudentID FROM dbo.StudentGrade \n WHERE StudentID = @StudentID\n '\nEND\nGO" }, { "code": null, "e": 6172, "s": 6117, "text": "Step 8 − Right-click on the editor and select Execute." }, { "code": null, "e": 6295, "s": 6172, "text": "Step 9 − Right-click on your database and click refresh. You will see that a stored procedure is created in your database." }, { "code": null, "e": 6385, "s": 6295, "text": "Step 10 − Right-click on the project name in Solution Explorer and select Add → New Item." }, { "code": null, "e": 6456, "s": 6385, "text": "Step 11 − Then select ADO.NET Entity Data Model in the Templates pane." }, { "code": null, "e": 6509, "s": 6456, "text": "Step 12 − Enter SPModel as name, and then click Add." }, { "code": null, "e": 6615, "s": 6509, "text": "Step 13 − In the Choose Model Contents dialog box, select EF designer from database, and then click Next." }, { "code": null, "e": 6662, "s": 6615, "text": "Step 14 − Select your database and click Next." }, { "code": null, "e": 6743, "s": 6662, "text": "Step 15 − In the Choose Your Database Objects dialog box click on tables, views." }, { "code": null, "e": 6872, "s": 6743, "text": "Step 16 − Select the GetStudentGradesForCourse function located under the Stored Procedures and Functions node and click Finish." }, { "code": null, "e": 7011, "s": 6872, "text": "Step 17 − Select View → Other Windows → Entity Data Model Browser and right-click GetStudentGrades under Function Imports and select Edit." }, { "code": null, "e": 7049, "s": 7011, "text": "It will produce the following dialog." }, { "code": null, "e": 7186, "s": 7049, "text": "Step 18 − Click on Entities radio button and select StudentGrade from the combobox as return type of this stored procedure and click Ok." }, { "code": null, "e": 7348, "s": 7186, "text": "Let’s take a look at the following C# code in which all the grades will be retrieved by passing the student ID as parameter in GetStudentGrades stored procedure." }, { "code": null, "e": 7806, "s": 7348, "text": "class Program {\n\n static void Main(string[] args) {\n\n using (var context = new UniContextEntities()) {\n\n int studentID = 22;\n var studentGrades = context.GetStudentGrades(studentID);\n\n foreach (var student in studentGrades) {\n Console.WriteLine(\"Course ID: {0}, Title: {1}, Grade: {2} \", \n student.CourseID, student.Course.Title, student.Grade);\n }\n\n Console.ReadKey();\n\n }\n }\n}" }, { "code": null, "e": 7891, "s": 7806, "text": "When the above code is compiled and executed you will receive the following output −" }, { "code": null, "e": 7996, "s": 7891, "text": "Course ID: 4022, Title: Microeconomics, Grade: 3.00\nCourse ID: 4041, Title: Macroeconomics, Grade: 3.50\n" }, { "code": null, "e": 8095, "s": 7996, "text": "We recommend that you execute the above example in a step-by-step manner for better understanding." }, { "code": null, "e": 8128, "s": 8095, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 8146, "s": 8128, "text": " Trevoir Williams" }, { "code": null, "e": 8181, "s": 8146, "text": "\n 33 Lectures \n 3.5 hours \n" }, { "code": null, "e": 8194, "s": 8181, "text": " Nilay Mehta" }, { "code": null, "e": 8229, "s": 8194, "text": "\n 21 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8245, "s": 8229, "text": " TELCOMA Global" }, { "code": null, "e": 8280, "s": 8245, "text": "\n 89 Lectures \n 7.5 hours \n" }, { "code": null, "e": 8298, "s": 8280, "text": " Mustafa Radaideh" }, { "code": null, "e": 8305, "s": 8298, "text": " Print" }, { "code": null, "e": 8316, "s": 8305, "text": " Add Notes" } ]
Auto Import Python Libraries. Using Pyforest to import important... | by Himanshu Sharma | Towards Data Science
Do you also get stuck in importing libraries while coding in python? It happens with most of us that while coding we forget to import libraries that we will use and we got stuck in importing different libraries which is frustrating, also I must say being a lazy programmer I want a way to solve this importing problem once and for all. PyForest is an open-source python library that is really helpful for a lazy programmer like me because it imports all the major libraries that are required for python programming including machine learning and deep learning. In this article, we will explore PyForest and see how we can use it. Let’s get started... We will start by installing PyForest using pip. The command given below will do that. !pip install pyforest In this step, we will import only PyForest which is the only required library. from pyforest import * Now the magic begins, let’s see how many python libraries we have imported in just a single line of code. lazy_imports() You see how easily we imported all the major python libraries including libraries for deep learning, machine learning, image processing, etc. These libraries are really helpful if you are a lazy programmer like me. In this article, we saw how PyForest is useful for importing important libraries. Go ahead try importing the library in a single line and let me know your comments 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": 508, "s": 172, "text": "Do you also get stuck in importing libraries while coding in python? It happens with most of us that while coding we forget to import libraries that we will use and we got stuck in importing different libraries which is frustrating, also I must say being a lazy programmer I want a way to solve this importing problem once and for all." }, { "code": null, "e": 733, "s": 508, "text": "PyForest is an open-source python library that is really helpful for a lazy programmer like me because it imports all the major libraries that are required for python programming including machine learning and deep learning." }, { "code": null, "e": 802, "s": 733, "text": "In this article, we will explore PyForest and see how we can use it." }, { "code": null, "e": 823, "s": 802, "text": "Let’s get started..." }, { "code": null, "e": 909, "s": 823, "text": "We will start by installing PyForest using pip. The command given below will do that." }, { "code": null, "e": 931, "s": 909, "text": "!pip install pyforest" }, { "code": null, "e": 1010, "s": 931, "text": "In this step, we will import only PyForest which is the only required library." }, { "code": null, "e": 1033, "s": 1010, "text": "from pyforest import *" }, { "code": null, "e": 1139, "s": 1033, "text": "Now the magic begins, let’s see how many python libraries we have imported in just a single line of code." }, { "code": null, "e": 1154, "s": 1139, "text": "lazy_imports()" }, { "code": null, "e": 1369, "s": 1154, "text": "You see how easily we imported all the major python libraries including libraries for deep learning, machine learning, image processing, etc. These libraries are really helpful if you are a lazy programmer like me." }, { "code": null, "e": 1558, "s": 1369, "text": "In this article, we saw how PyForest is useful for importing important libraries. Go ahead try importing the library in a single line and let me know your comments in the response section." }, { "code": null, "e": 1611, "s": 1558, "text": "This article is in collaboration with Piyush Ingale." } ]
Building a Sentiment Analysis Model using Yelp Reviews and ML Ensemble Methods | by Ben Chamblee | Towards Data Science
If you’ve ever read through Yelp reviews you might have noticed that there is a lot of inconsistency from reviewer to reviewer. Some reviews say the food is “life-changing” while only leaving three stars, while others say the food is “just okay” and leave five stars. The five-star review system is flawed because there’s no definitive way to define a five-star establishment versus a four-star one. However, if we ignore the number of stars and instead read through the actual reviews we should get a much better idea of what Yelp reviewers are actually saying. This sounds like much more work, but by using Python’s Natural Language Toolkit we can make our code do all the hard work. Part 1: Getting Yelp Reviews You can go about this in a few different ways. There are few Kaggle datasets like this one that have plenty of content but might not have the most up-to-date reviews. There are also some other independent datasets like this one from Hugging Face. People have been using Yelp reviews for analysis for years now and there are tons of resources like this to get your started. The best option, in my opinion, is to get reviews straight from the source. Yelp has a public dataset containing over 8 Million reviews all stored in a JSON file. You should be able to find a great variety of reviews, old and new all in a simple format. Part 2: Cleaning and Prepping for Sentiment Analysis When working with text-based data, it’s beneficial to reduce the amount of words and characters so that your code doesn’t take hours to run. We want to do this while still retaining the important words though, words with meaning like ‘good’ or ‘bad’ that give us an idea of the reviewer’s feelings. Words like ‘the’, ‘or’, and ‘is’, also known as stop words, aren’t very important. There’s no reason to waste time and processing power going through these stops words, so it’s best to just remove them. Python’s Natural Language Toolkit makes this process simple: from nltk.corpus import stopwordsfrom nltk.tokenize import word_tokenizeexample_sent = """This is a sample sentence, showing off the stop words filtration."""stop_words = set(stopwords.words('english')) word_tokens = word_tokenize(example_sent) filtered_sentence = [w for w in word_tokens if not w.lower() in stop_words] filtered_sentence = [] for w in word_tokens: if w not in stop_words: filtered_sentence.append(w)print(word_tokens)print(filtered_sentence) You’ll also notice I’m using the word ‘token’ in some of my variables. That just means I’m taking a sentence and breaking it down into a list of words, that process is known as tokenization. You can see here that Yelp reviews have are about 40–45% stop words on average. Getting rid of them will save us a lot of time! Now that we’ve filtered out the stop words, let’s try and simplify the dataset using a process called stemming. Stemming is the process of reducing all forms of words to their base form. If you have words like ‘greatly’, ‘greatest’, and ‘greater’, those will all be reduced down to ‘great’ for easier grouping and processing. Once again, Python’s Natural Language Toolkit makes this process very easy: import nltkfrom nltk.stem.snowball import SnowballStemmersnowBallStemmer = SnowballStemmer("english")sentence = yelp_data_unpacked[40]wordList = nltk.word_tokenize(sentence)stemWords = [snowBallStemmer.stem(word) for word in wordList]stemmed = ' '.join(stemWords)print(sentence)print('')print(stemmed) It doesn’t look like that much of a change, but if we tokenize these sentences and group them together there will be fewer unique key-value pairs. At this point in the project, we’ve got our data cleaned and ready for processing. Before we get to building our classification model we have to decide how we’re going to classify it. Part 3: Categorization and Hyperparameters At the start of this article, I said that I wanted to improve Yelp’s five-star rating system by analyzing the actual content in each review. So, instead of sorting the reviews into five groups based on the number of stars, I’m sorting them into four groups based on sentiment. These groups are ‘Negative’, ‘Slightly Negative’, ‘Slightly Positive’, and ‘Positive’. To sort out my reviews for a training dataset, I used Textblob’s Polarity score as a baseline. from textblob import TextBlobyelp_data_s['Polarity'] =yelp_data_s['Stemmed'].apply(lambda x: TextBlob(x).sentiment[0])sentiment = []for i in range(len(yelp_data_s)): if yelp_data_s['Polarity'][i] >= 0.4: sentiment.append('Positive') if yelp_data_s['Polarity'][i] > 0.2 and yelp_data_s['Polarity'][i] < 0.4: sentiment.append('Slightly Positive') if yelp_data_s['Polarity'][i] <= 0.2 and yelp_data_s['Polarity'][i] > 0: sentiment.append('Slightly Negative') if yelp_data_s['Polarity'][i] < 0: sentiment.append('Negative')yelp_data_s['sentiment'] = sentiment I wanted to use more than just this score to build our model though, so I decided to look at some other features. For the second graph, I used this list of positive sentiment words to determine what a ‘positive word’ is. Now I had a good idea of what features to look for while building a model. The last step before actually selecting a model was to look at the content in each review by using a Term Frequency Inverse Document Frequency Matrix (TFIDF) Simply put, this is a way to find the most unique and impactful words in a review. Term Frequency just tells you how often the word appears, but once you add the inverse document frequency parameter you can also analyze how infrequently that word appears throughout the whole dataset. It’s important to analyze these unique words because they can tell you much more than the common words that every reviewer is using. To create the training dataset, I used these as my columns: Name: just the name of the restaurant Review: the full review written on Yelp Polarity: The TextBlob Polarity Score Positive_Words_P: The percentage of positive words Sentiment: The Assigned Sentiment score TFIDF: Each unique word is a column with the frequency listed as it’s value, there will be a lot of columns in this dataset (which is why we removed stop words and stemmed our reviews at first) from sklearn.feature_extraction.text import TfidfVectorizertext = yelp_data_s['Stemmed:Sentence']Tvectorizer = TfidfVectorizer()Tvectorizer.fit(text)Tvector = Tvectorizer.transform(text)voc = Tvectorizer.vocabulary_df = pd.DataFrame(Tvector.toarray(),columns=voc)col_name1 ='Name'col_name2 = 'Review'col_name3 = 'Polarity'col_name4 = 'Sentiment'col_name5 = 'Positive_Words_P'col1 = yelp_data_s['Name']col2 = yelp_data_s['Review']col3 = yelp_data_s['Polarity']col4 = yelp_data_s['sentiment']col5 = yelp_data_s['Positive_Words_P']df.insert(0,col_name1,col1)df.insert(1,col_name2,col2)df.insert(2,col_name3,col3)df.insert(3,col_name4,col4)df.insert(4,col_name5,col5) Using this training dataset and a simple logistic regression model to test it, I got a baseline score of 67% accuracy. I knew I could improve this by tuning some hyperparameters though, so I looked at the TFIDF matrix again. Minumum Word Frequency: While it is important to look at the really unique words, it might help with overfitting to raise the threshold of words that we’re processing. I tested this same model but added the hyperparameter of minimum word frequency to see how it impacted accuracy. Total Number of ngrams: This basically tells us how the data is processed word by word. If you have ngrams set to 1, the words will process one by one like ‘this’, ‘is’, ‘not’, ‘lame’ for example. If you have ngrams set to 2, you can process word pairs like ’this is’, ‘is not’, ‘not lame’ for example. You can probably see how this would impact accuracy, with ngrams set to 1 the model will only see ‘lame’ and process it as negative while the model with ngrams set to 2 will see ‘not lame’ and process it as positive. This is reflected on this accuracy graph: And with these two hyperparameters, we’ve improved our baseline accuracy to 71%! This might not seem like much, but when we start working with other models it’s important to know that we have the most optimal hyperparameters. Part 4: Model Selection Finally, it’s model selection time. For this project I wanted to try many different classification models, the whole process looked like this: Choose a model type Define a pipeline and use Gridsearch to find the best parameters Save the model so we don’t have to run it multiple times Load the model and run accuracy and f1 scores Repeat the process with other models I also wanted to split up my model selection into two parts, the first four will analyze the numerical component (% of positive words, polarity score, etc.) and the last two will analyze the TFIDF matrices. Here’s how each model performed: Logistic Regression: F1 score of 71%, lr__C: 0.1 from sklearn.linear_model import LogisticRegressionfrom sklearn.model_selection import GridSearchCVfrom sklearn.metrics import make_scorer, accuracy_score, f1_scorefrom sklearn.model_selection import train_test_splitfrom sklearn.pipeline import Pipelinefrom sklearn.preprocessing import StandardScalersteps = [('scaler', StandardScaler()), ('lr', LogisticRegression(solver = 'lbfgs'))] pipeline = Pipeline(steps)parameters = {'lr__C':[0.01, 0.1, 1, 10, 100]}clf = GridSearchCV(pipeline, parameters, cv = 10, scoring="accuracy") clf.fit(X_train, y_train)clf.best_params_ Random Forest: F1 score of 66%, max_features: ‘sqrt’, n_estimators: 50 from sklearn.ensemble import RandomForestClassifiersteps = [('scaler', StandardScaler()), ('rf', RandomForestClassifier())] pipeline = Pipeline(steps)parameters = {'rf__n_estimators':[10 , 20, 30, 40, 50], 'rf__max_features':['auto','sqrt']}clf = GridSearchCV(pipeline, parameters, cv = 10, scoring="accuracy") clf.fit(X_train, y_train)clf.best_params_ Support Vector Classification (SVC): F1 score of 70%, svc__C: 0.01 from sklearn.svm import SVCsteps = [('scaler', StandardScaler()), ('svc', SVC(probability=False,kernel='linear',gamma='auto'))] pipeline = Pipeline(steps) parameters = {'svc__C':[0.01, 0.1, 1]}clf = GridSearchCV(pipeline, parameters, cv = 3, scoring="accuracy") clf.fit(X_train, y_train)clf.best_params_ Gradient Boosted Classifier: F1 score of 72%, learning_rate: 0.15, n_estimators: 500 from sklearn.ensemble import GradientBoostingClassifiersteps = [('scaler', StandardScaler()), ('gbc', GradientBoostingClassifier(max_features='sqrt'))] pipeline = Pipeline(steps) parameters = {'gbc__n_estimators':[10, 50, 100, 200, 500], 'gbc__learning_rate': [0.05, 0.1, 0.15, 0.2, 0.25]}clf = GridSearchCV(pipeline, parameters, cv = 10, scoring="accuracy") clf.fit(X_train, y_train)steps = [('scaler', StandardScaler()), ('gbc', GradientBoostingClassifier(learning_rate = 0.15, max_features = 'sqrt', n_estimators = 500))] clf = Pipeline(steps) clf.fit(X_train, y_train) Naive Bayes with TFIDF: F1 Score of 64%, alpha: 1, min_df: 10 from sklearn.feature_extraction.text import TfidfVectorizerfrom sklearn.naive_bayes import MultinomialNBsteps = [('vec', TfidfVectorizer(stop_words = 'english', ngram_range = (1, 2))), ('nb', MultinomialNB())] pipeline = Pipeline(steps) parameters = {'vec__min_df':[0.01, 0.1, 1, 10, 100], 'nb__alpha':[0.01, 0.1, 1, 10, 100]}clf = GridSearchCV(pipeline, parameters, cv = 10, scoring="accuracy") clf.fit(X_train, y_train)clf.best_params_ Gradient Boosted Classifier with TFIDF: F1 score of 57%, learning_rate: 0.25 steps = [('vec', TfidfVectorizer(stop_words = 'english', ngram_range = (1, 2))), ('gbc', GradientBoostingClassifier(max_features='sqrt',n_estimators=500))] pipeline = Pipeline(steps) parameters = {'gbc__learning_rate': [0.05, 0.1, 0.15, 0.2, 0.25]}clf = GridSearchCV(pipeline, parameters, cv = 3, scoring="accuracy") clf.fit(X_train, y_train)clf.best_params_ Unfortunately, these models’ scores are all around the 60–70% range which isn’t the best. There is a way to take the performances from the best models and combine them to improve results, it’s known as Ensemble Methods. For this project, I took the best performing text-based model (Naive Bayes with TFIDF) and its performance as a feature in the best performing numerical model (Gradient Boosted Classifier). This part has a lot of steps but the code looks something like this: # define train/test split X = yelp_data.Review # word tokensy = yelp_data.Sentiment # assigned sentimentindices = yelp_data.indexX_train, X_test, y_train, y_test, i_train, i_test = train_test_split(X, y, indices, train_size = 0.8, random_state = 7)# define Naive Bayes TFIDF modelsteps = [('vec', TfidfVectorizer(ngram_range = (1, 2))), ('nb', MultinomialNB())] pipeline = Pipeline(steps)parameters = {'vec__min_df':10, 'nb__alpha':0.1}clf = GridSearchCV(pipeline, parameters, cv = 10, scoring="accuracy") clf.fit(X_train, y_train)# turn model scores into feature in dataframe (prediction probability)Xtrain_proba = pd.DataFrame(clf.predict_proba(X_train), index = i_train) Xtest_proba = pd.DataFrame(clf.predict_proba(X_test), index = i_test)# define new train/test splitX = yelp_data.iloc[0:,4:] # first four columns are text, review, positive word percentage, and polarityy = yelp_data.Sentiment # assigned sentimentindices = yelp_data.indexX_train, X_test, y_train, y_test, itrain, itest = train_test_split(X,y,indices,train_size=0.8,random_state=7)# Adding prediction probabilityXtrain_combined = pd.merge(X_train, Xtrain_proba, left_index=True, right_index=True) Xtest_combined = pd.merge(X_test, Xtest_proba, left_index=True, right_index=True)# define Gradient Boosted Classifiersteps = [('scaler', StandardScaler()), ('gbc', GradientBoostingClassifier(max_features='sqrt'))] pipeline = Pipeline(steps) parameters = {'gbc__n_estimators':[10, 50, 100, 200, 500], 'gbc__learning_rate': [0.05, 0.1, 0.15, 0.2, 0.25]}clf = GridSearchCV(pipeline, parameters, cv = 10, scoring="accuracy") clf.fit(X_train, y_train)# with best featuressteps = [('scaler', StandardScaler()), ('gbc', GradientBoostingClassifier(learning_rate = 0.2, max_features = 'sqrt', n_estimators = 500))] clf = Pipeline(steps) clf.fit(X_train, y_train) And finally, with this stacked model we have a very improved F1 score of 92%! To show you how much more accurate this is, let’s take a look at the confusion matrix of the original logistic regression (accuracy of 71%): Versus the confusion matrix of our stacked model (accuracy of 92%): As you can see, Ensemble Methods has a huge impact on our accuracy. It may have taken some extra time to define all those models and combine the two together, but for a 21% accuracy boost, I think it was well worth it. I would highly recommend reading more about Ensemble Methods, it will be very helpful for almost any machine learning project you work on! Part 5: Results Now let’s put our model to the test. I went to Yelp and found a random three-star review for an Italian restaurant. A three-star review doesn’t really tell you how the reviewer felt and I didn’t feel like reading the entire review, so I let the model do all the work. From this simple output, I can get a much better idea of how the reviewer felt about this Italian restaurant. The words and numbers below the sentiment show the 15 words that had the largest impact on the score, these words are usually unique and close to sentiment words like ‘good’ or ‘bad’. From this result, I know that this reviewer had a slightly positive experience and that the scallops are probably really good. I also know that this place is probably a little humid and that this reviewer was horrified by something in the restaurant. If I were the owner of this restaurant, I would really benefit from this because I can see which words are contributing to positive reviews and which ones are contributing to negative reviews. Natural Language Processing has a wide variety of uses, Yelp Reviews are just one of the many forms of text-based data we can use to build Sentiment Analysis Models. I learned so much from building this model, something like this would be a great introduction to NLP with Python. If you’re interested in learning more I would highly suggest reading through the book Natural Language Processing in Action by Cole Howard, Hannes Hapke, and Hobson Lane. I hope that this project walkthrough inspires you to create your own sentiment analysis model or to look into Ensemble Methods! Thank you for reading! Full project: https://github.com/Bench-amblee/yelp_sentiment_analysis
[ { "code": null, "e": 857, "s": 171, "text": "If you’ve ever read through Yelp reviews you might have noticed that there is a lot of inconsistency from reviewer to reviewer. Some reviews say the food is “life-changing” while only leaving three stars, while others say the food is “just okay” and leave five stars. The five-star review system is flawed because there’s no definitive way to define a five-star establishment versus a four-star one. However, if we ignore the number of stars and instead read through the actual reviews we should get a much better idea of what Yelp reviewers are actually saying. This sounds like much more work, but by using Python’s Natural Language Toolkit we can make our code do all the hard work." }, { "code": null, "e": 886, "s": 857, "text": "Part 1: Getting Yelp Reviews" }, { "code": null, "e": 933, "s": 886, "text": "You can go about this in a few different ways." }, { "code": null, "e": 1053, "s": 933, "text": "There are few Kaggle datasets like this one that have plenty of content but might not have the most up-to-date reviews." }, { "code": null, "e": 1259, "s": 1053, "text": "There are also some other independent datasets like this one from Hugging Face. People have been using Yelp reviews for analysis for years now and there are tons of resources like this to get your started." }, { "code": null, "e": 1513, "s": 1259, "text": "The best option, in my opinion, is to get reviews straight from the source. Yelp has a public dataset containing over 8 Million reviews all stored in a JSON file. You should be able to find a great variety of reviews, old and new all in a simple format." }, { "code": null, "e": 1566, "s": 1513, "text": "Part 2: Cleaning and Prepping for Sentiment Analysis" }, { "code": null, "e": 2129, "s": 1566, "text": "When working with text-based data, it’s beneficial to reduce the amount of words and characters so that your code doesn’t take hours to run. We want to do this while still retaining the important words though, words with meaning like ‘good’ or ‘bad’ that give us an idea of the reviewer’s feelings. Words like ‘the’, ‘or’, and ‘is’, also known as stop words, aren’t very important. There’s no reason to waste time and processing power going through these stops words, so it’s best to just remove them. Python’s Natural Language Toolkit makes this process simple:" }, { "code": null, "e": 2616, "s": 2129, "text": "from nltk.corpus import stopwordsfrom nltk.tokenize import word_tokenizeexample_sent = \"\"\"This is a sample sentence, showing off the stop words filtration.\"\"\"stop_words = set(stopwords.words('english')) word_tokens = word_tokenize(example_sent) filtered_sentence = [w for w in word_tokens if not w.lower() in stop_words] filtered_sentence = [] for w in word_tokens: if w not in stop_words: filtered_sentence.append(w)print(word_tokens)print(filtered_sentence)" }, { "code": null, "e": 2807, "s": 2616, "text": "You’ll also notice I’m using the word ‘token’ in some of my variables. That just means I’m taking a sentence and breaking it down into a list of words, that process is known as tokenization." }, { "code": null, "e": 2935, "s": 2807, "text": "You can see here that Yelp reviews have are about 40–45% stop words on average. Getting rid of them will save us a lot of time!" }, { "code": null, "e": 3337, "s": 2935, "text": "Now that we’ve filtered out the stop words, let’s try and simplify the dataset using a process called stemming. Stemming is the process of reducing all forms of words to their base form. If you have words like ‘greatly’, ‘greatest’, and ‘greater’, those will all be reduced down to ‘great’ for easier grouping and processing. Once again, Python’s Natural Language Toolkit makes this process very easy:" }, { "code": null, "e": 3639, "s": 3337, "text": "import nltkfrom nltk.stem.snowball import SnowballStemmersnowBallStemmer = SnowballStemmer(\"english\")sentence = yelp_data_unpacked[40]wordList = nltk.word_tokenize(sentence)stemWords = [snowBallStemmer.stem(word) for word in wordList]stemmed = ' '.join(stemWords)print(sentence)print('')print(stemmed)" }, { "code": null, "e": 3786, "s": 3639, "text": "It doesn’t look like that much of a change, but if we tokenize these sentences and group them together there will be fewer unique key-value pairs." }, { "code": null, "e": 3970, "s": 3786, "text": "At this point in the project, we’ve got our data cleaned and ready for processing. Before we get to building our classification model we have to decide how we’re going to classify it." }, { "code": null, "e": 4013, "s": 3970, "text": "Part 3: Categorization and Hyperparameters" }, { "code": null, "e": 4472, "s": 4013, "text": "At the start of this article, I said that I wanted to improve Yelp’s five-star rating system by analyzing the actual content in each review. So, instead of sorting the reviews into five groups based on the number of stars, I’m sorting them into four groups based on sentiment. These groups are ‘Negative’, ‘Slightly Negative’, ‘Slightly Positive’, and ‘Positive’. To sort out my reviews for a training dataset, I used Textblob’s Polarity score as a baseline." }, { "code": null, "e": 5068, "s": 4472, "text": "from textblob import TextBlobyelp_data_s['Polarity'] =yelp_data_s['Stemmed'].apply(lambda x: TextBlob(x).sentiment[0])sentiment = []for i in range(len(yelp_data_s)): if yelp_data_s['Polarity'][i] >= 0.4: sentiment.append('Positive') if yelp_data_s['Polarity'][i] > 0.2 and yelp_data_s['Polarity'][i] < 0.4: sentiment.append('Slightly Positive') if yelp_data_s['Polarity'][i] <= 0.2 and yelp_data_s['Polarity'][i] > 0: sentiment.append('Slightly Negative') if yelp_data_s['Polarity'][i] < 0: sentiment.append('Negative')yelp_data_s['sentiment'] = sentiment" }, { "code": null, "e": 5182, "s": 5068, "text": "I wanted to use more than just this score to build our model though, so I decided to look at some other features." }, { "code": null, "e": 5289, "s": 5182, "text": "For the second graph, I used this list of positive sentiment words to determine what a ‘positive word’ is." }, { "code": null, "e": 5522, "s": 5289, "text": "Now I had a good idea of what features to look for while building a model. The last step before actually selecting a model was to look at the content in each review by using a Term Frequency Inverse Document Frequency Matrix (TFIDF)" }, { "code": null, "e": 5940, "s": 5522, "text": "Simply put, this is a way to find the most unique and impactful words in a review. Term Frequency just tells you how often the word appears, but once you add the inverse document frequency parameter you can also analyze how infrequently that word appears throughout the whole dataset. It’s important to analyze these unique words because they can tell you much more than the common words that every reviewer is using." }, { "code": null, "e": 6000, "s": 5940, "text": "To create the training dataset, I used these as my columns:" }, { "code": null, "e": 6038, "s": 6000, "text": "Name: just the name of the restaurant" }, { "code": null, "e": 6078, "s": 6038, "text": "Review: the full review written on Yelp" }, { "code": null, "e": 6116, "s": 6078, "text": "Polarity: The TextBlob Polarity Score" }, { "code": null, "e": 6167, "s": 6116, "text": "Positive_Words_P: The percentage of positive words" }, { "code": null, "e": 6207, "s": 6167, "text": "Sentiment: The Assigned Sentiment score" }, { "code": null, "e": 6401, "s": 6207, "text": "TFIDF: Each unique word is a column with the frequency listed as it’s value, there will be a lot of columns in this dataset (which is why we removed stop words and stemmed our reviews at first)" }, { "code": null, "e": 7065, "s": 6401, "text": "from sklearn.feature_extraction.text import TfidfVectorizertext = yelp_data_s['Stemmed:Sentence']Tvectorizer = TfidfVectorizer()Tvectorizer.fit(text)Tvector = Tvectorizer.transform(text)voc = Tvectorizer.vocabulary_df = pd.DataFrame(Tvector.toarray(),columns=voc)col_name1 ='Name'col_name2 = 'Review'col_name3 = 'Polarity'col_name4 = 'Sentiment'col_name5 = 'Positive_Words_P'col1 = yelp_data_s['Name']col2 = yelp_data_s['Review']col3 = yelp_data_s['Polarity']col4 = yelp_data_s['sentiment']col5 = yelp_data_s['Positive_Words_P']df.insert(0,col_name1,col1)df.insert(1,col_name2,col2)df.insert(2,col_name3,col3)df.insert(3,col_name4,col4)df.insert(4,col_name5,col5)" }, { "code": null, "e": 7290, "s": 7065, "text": "Using this training dataset and a simple logistic regression model to test it, I got a baseline score of 67% accuracy. I knew I could improve this by tuning some hyperparameters though, so I looked at the TFIDF matrix again." }, { "code": null, "e": 7571, "s": 7290, "text": "Minumum Word Frequency: While it is important to look at the really unique words, it might help with overfitting to raise the threshold of words that we’re processing. I tested this same model but added the hyperparameter of minimum word frequency to see how it impacted accuracy." }, { "code": null, "e": 8133, "s": 7571, "text": "Total Number of ngrams: This basically tells us how the data is processed word by word. If you have ngrams set to 1, the words will process one by one like ‘this’, ‘is’, ‘not’, ‘lame’ for example. If you have ngrams set to 2, you can process word pairs like ’this is’, ‘is not’, ‘not lame’ for example. You can probably see how this would impact accuracy, with ngrams set to 1 the model will only see ‘lame’ and process it as negative while the model with ngrams set to 2 will see ‘not lame’ and process it as positive. This is reflected on this accuracy graph:" }, { "code": null, "e": 8359, "s": 8133, "text": "And with these two hyperparameters, we’ve improved our baseline accuracy to 71%! This might not seem like much, but when we start working with other models it’s important to know that we have the most optimal hyperparameters." }, { "code": null, "e": 8383, "s": 8359, "text": "Part 4: Model Selection" }, { "code": null, "e": 8526, "s": 8383, "text": "Finally, it’s model selection time. For this project I wanted to try many different classification models, the whole process looked like this:" }, { "code": null, "e": 8546, "s": 8526, "text": "Choose a model type" }, { "code": null, "e": 8611, "s": 8546, "text": "Define a pipeline and use Gridsearch to find the best parameters" }, { "code": null, "e": 8668, "s": 8611, "text": "Save the model so we don’t have to run it multiple times" }, { "code": null, "e": 8714, "s": 8668, "text": "Load the model and run accuracy and f1 scores" }, { "code": null, "e": 8751, "s": 8714, "text": "Repeat the process with other models" }, { "code": null, "e": 8991, "s": 8751, "text": "I also wanted to split up my model selection into two parts, the first four will analyze the numerical component (% of positive words, polarity score, etc.) and the last two will analyze the TFIDF matrices. Here’s how each model performed:" }, { "code": null, "e": 9040, "s": 8991, "text": "Logistic Regression: F1 score of 71%, lr__C: 0.1" }, { "code": null, "e": 9610, "s": 9040, "text": "from sklearn.linear_model import LogisticRegressionfrom sklearn.model_selection import GridSearchCVfrom sklearn.metrics import make_scorer, accuracy_score, f1_scorefrom sklearn.model_selection import train_test_splitfrom sklearn.pipeline import Pipelinefrom sklearn.preprocessing import StandardScalersteps = [('scaler', StandardScaler()), ('lr', LogisticRegression(solver = 'lbfgs'))] pipeline = Pipeline(steps)parameters = {'lr__C':[0.01, 0.1, 1, 10, 100]}clf = GridSearchCV(pipeline, parameters, cv = 10, scoring=\"accuracy\") clf.fit(X_train, y_train)clf.best_params_" }, { "code": null, "e": 9681, "s": 9610, "text": "Random Forest: F1 score of 66%, max_features: ‘sqrt’, n_estimators: 50" }, { "code": null, "e": 10034, "s": 9681, "text": "from sklearn.ensemble import RandomForestClassifiersteps = [('scaler', StandardScaler()), ('rf', RandomForestClassifier())] pipeline = Pipeline(steps)parameters = {'rf__n_estimators':[10 , 20, 30, 40, 50], 'rf__max_features':['auto','sqrt']}clf = GridSearchCV(pipeline, parameters, cv = 10, scoring=\"accuracy\") clf.fit(X_train, y_train)clf.best_params_" }, { "code": null, "e": 10101, "s": 10034, "text": "Support Vector Classification (SVC): F1 score of 70%, svc__C: 0.01" }, { "code": null, "e": 10405, "s": 10101, "text": "from sklearn.svm import SVCsteps = [('scaler', StandardScaler()), ('svc', SVC(probability=False,kernel='linear',gamma='auto'))] pipeline = Pipeline(steps) parameters = {'svc__C':[0.01, 0.1, 1]}clf = GridSearchCV(pipeline, parameters, cv = 3, scoring=\"accuracy\") clf.fit(X_train, y_train)clf.best_params_" }, { "code": null, "e": 10490, "s": 10405, "text": "Gradient Boosted Classifier: F1 score of 72%, learning_rate: 0.15, n_estimators: 500" }, { "code": null, "e": 11065, "s": 10490, "text": "from sklearn.ensemble import GradientBoostingClassifiersteps = [('scaler', StandardScaler()), ('gbc', GradientBoostingClassifier(max_features='sqrt'))] pipeline = Pipeline(steps) parameters = {'gbc__n_estimators':[10, 50, 100, 200, 500], 'gbc__learning_rate': [0.05, 0.1, 0.15, 0.2, 0.25]}clf = GridSearchCV(pipeline, parameters, cv = 10, scoring=\"accuracy\") clf.fit(X_train, y_train)steps = [('scaler', StandardScaler()), ('gbc', GradientBoostingClassifier(learning_rate = 0.15, max_features = 'sqrt', n_estimators = 500))] clf = Pipeline(steps) clf.fit(X_train, y_train)" }, { "code": null, "e": 11127, "s": 11065, "text": "Naive Bayes with TFIDF: F1 Score of 64%, alpha: 1, min_df: 10" }, { "code": null, "e": 11565, "s": 11127, "text": "from sklearn.feature_extraction.text import TfidfVectorizerfrom sklearn.naive_bayes import MultinomialNBsteps = [('vec', TfidfVectorizer(stop_words = 'english', ngram_range = (1, 2))), ('nb', MultinomialNB())] pipeline = Pipeline(steps) parameters = {'vec__min_df':[0.01, 0.1, 1, 10, 100], 'nb__alpha':[0.01, 0.1, 1, 10, 100]}clf = GridSearchCV(pipeline, parameters, cv = 10, scoring=\"accuracy\") clf.fit(X_train, y_train)clf.best_params_" }, { "code": null, "e": 11642, "s": 11565, "text": "Gradient Boosted Classifier with TFIDF: F1 score of 57%, learning_rate: 0.25" }, { "code": null, "e": 12010, "s": 11642, "text": "steps = [('vec', TfidfVectorizer(stop_words = 'english', ngram_range = (1, 2))), ('gbc', GradientBoostingClassifier(max_features='sqrt',n_estimators=500))] pipeline = Pipeline(steps) parameters = {'gbc__learning_rate': [0.05, 0.1, 0.15, 0.2, 0.25]}clf = GridSearchCV(pipeline, parameters, cv = 3, scoring=\"accuracy\") clf.fit(X_train, y_train)clf.best_params_" }, { "code": null, "e": 12489, "s": 12010, "text": "Unfortunately, these models’ scores are all around the 60–70% range which isn’t the best. There is a way to take the performances from the best models and combine them to improve results, it’s known as Ensemble Methods. For this project, I took the best performing text-based model (Naive Bayes with TFIDF) and its performance as a feature in the best performing numerical model (Gradient Boosted Classifier). This part has a lot of steps but the code looks something like this:" }, { "code": null, "e": 14312, "s": 12489, "text": "# define train/test split X = yelp_data.Review # word tokensy = yelp_data.Sentiment # assigned sentimentindices = yelp_data.indexX_train, X_test, y_train, y_test, i_train, i_test = train_test_split(X, y, indices, train_size = 0.8, random_state = 7)# define Naive Bayes TFIDF modelsteps = [('vec', TfidfVectorizer(ngram_range = (1, 2))), ('nb', MultinomialNB())] pipeline = Pipeline(steps)parameters = {'vec__min_df':10, 'nb__alpha':0.1}clf = GridSearchCV(pipeline, parameters, cv = 10, scoring=\"accuracy\") clf.fit(X_train, y_train)# turn model scores into feature in dataframe (prediction probability)Xtrain_proba = pd.DataFrame(clf.predict_proba(X_train), index = i_train) Xtest_proba = pd.DataFrame(clf.predict_proba(X_test), index = i_test)# define new train/test splitX = yelp_data.iloc[0:,4:] # first four columns are text, review, positive word percentage, and polarityy = yelp_data.Sentiment # assigned sentimentindices = yelp_data.indexX_train, X_test, y_train, y_test, itrain, itest = train_test_split(X,y,indices,train_size=0.8,random_state=7)# Adding prediction probabilityXtrain_combined = pd.merge(X_train, Xtrain_proba, left_index=True, right_index=True) Xtest_combined = pd.merge(X_test, Xtest_proba, left_index=True, right_index=True)# define Gradient Boosted Classifiersteps = [('scaler', StandardScaler()), ('gbc', GradientBoostingClassifier(max_features='sqrt'))] pipeline = Pipeline(steps) parameters = {'gbc__n_estimators':[10, 50, 100, 200, 500], 'gbc__learning_rate': [0.05, 0.1, 0.15, 0.2, 0.25]}clf = GridSearchCV(pipeline, parameters, cv = 10, scoring=\"accuracy\") clf.fit(X_train, y_train)# with best featuressteps = [('scaler', StandardScaler()), ('gbc', GradientBoostingClassifier(learning_rate = 0.2, max_features = 'sqrt', n_estimators = 500))] clf = Pipeline(steps) clf.fit(X_train, y_train)" }, { "code": null, "e": 14531, "s": 14312, "text": "And finally, with this stacked model we have a very improved F1 score of 92%! To show you how much more accurate this is, let’s take a look at the confusion matrix of the original logistic regression (accuracy of 71%):" }, { "code": null, "e": 14599, "s": 14531, "text": "Versus the confusion matrix of our stacked model (accuracy of 92%):" }, { "code": null, "e": 14957, "s": 14599, "text": "As you can see, Ensemble Methods has a huge impact on our accuracy. It may have taken some extra time to define all those models and combine the two together, but for a 21% accuracy boost, I think it was well worth it. I would highly recommend reading more about Ensemble Methods, it will be very helpful for almost any machine learning project you work on!" }, { "code": null, "e": 14973, "s": 14957, "text": "Part 5: Results" }, { "code": null, "e": 15241, "s": 14973, "text": "Now let’s put our model to the test. I went to Yelp and found a random three-star review for an Italian restaurant. A three-star review doesn’t really tell you how the reviewer felt and I didn’t feel like reading the entire review, so I let the model do all the work." }, { "code": null, "e": 15979, "s": 15241, "text": "From this simple output, I can get a much better idea of how the reviewer felt about this Italian restaurant. The words and numbers below the sentiment show the 15 words that had the largest impact on the score, these words are usually unique and close to sentiment words like ‘good’ or ‘bad’. From this result, I know that this reviewer had a slightly positive experience and that the scallops are probably really good. I also know that this place is probably a little humid and that this reviewer was horrified by something in the restaurant. If I were the owner of this restaurant, I would really benefit from this because I can see which words are contributing to positive reviews and which ones are contributing to negative reviews." }, { "code": null, "e": 16430, "s": 15979, "text": "Natural Language Processing has a wide variety of uses, Yelp Reviews are just one of the many forms of text-based data we can use to build Sentiment Analysis Models. I learned so much from building this model, something like this would be a great introduction to NLP with Python. If you’re interested in learning more I would highly suggest reading through the book Natural Language Processing in Action by Cole Howard, Hannes Hapke, and Hobson Lane." }, { "code": null, "e": 16581, "s": 16430, "text": "I hope that this project walkthrough inspires you to create your own sentiment analysis model or to look into Ensemble Methods! Thank you for reading!" } ]
Digital Number System
A digital system can understand positional number system only where there are a few symbols called digits and these symbols represent different values depending on the position they occupy in the number. A value of each digit in a number can be determined using The digit The digit The position of the digit in the number The position of the digit in the number The base of the number system (where base is defined as the total number of digits available in the number system). The base of the number system (where base is defined as the total number of digits available in the number system). The number system that we use in our day-to-day life is the decimal number system. Decimal number system has base 10 as it uses 10 digits from 0 to 9. In decimal number system, the successive positions to the left of the decimal point represents units, tens, hundreds, thousands and so on. Each position represents a specific power of the base (10). For example, the decimal number 1234 consists of the digit 4 in the units position, 3 in the tens position, 2 in the hundreds position, and 1 in the thousands position, and its value can be written as (1×1000) + (2×100) + (3×10) + (4×l) (1×103) + (2×102) + (3×101) + (4×l00) 1000 + 200 + 30 + 1 1234 As a computer programmer or an IT professional, you should understand the following number systems which are frequently used in computers. Base 2. Digits used: 0, 1 Base 8. Digits used: 0 to 7 Base 16. Digits used: 0 to 9, Letters used: A- F Characteristics Uses two digits, 0 and 1. Uses two digits, 0 and 1. Also called base 2 number system Also called base 2 number system Each position in a binary number represents a 0 power of the base (2). Example: 20 Each position in a binary number represents a 0 power of the base (2). Example: 20 Last position in a binary number represents an x power of the base (2). Example: 2x where x represents the last position - 1. Last position in a binary number represents an x power of the base (2). Example: 2x where x represents the last position - 1. Binary Number: 101012 Calculating Decimal Equivalent − Note: 101012 is normally written as 10101. Characteristics Uses eight digits, 0,1,2,3,4,5,6,7. Uses eight digits, 0,1,2,3,4,5,6,7. Also called base 8 number system Also called base 8 number system Each position in an octal number represents a 0 power of the base (8). Example: 80 Each position in an octal number represents a 0 power of the base (8). Example: 80 Last position in an octal number represents an x power of the base (8). Example: 8x where x represents the last position - 1. Last position in an octal number represents an x power of the base (8). Example: 8x where x represents the last position - 1. Octal Number − 125708 Calculating Decimal Equivalent − Note: 125708 is normally written as 12570. Characteristics Uses 10 digits and 6 letters, 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F. Uses 10 digits and 6 letters, 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F. Letters represents numbers starting from 10. A = 10, B = 11, C = 12, D = 13, E = 14, F = 15. Letters represents numbers starting from 10. A = 10, B = 11, C = 12, D = 13, E = 14, F = 15. Also called base 16 number system. Also called base 16 number system. Each position in a hexadecimal number represents a 0 power of the base (16). Example 160. Each position in a hexadecimal number represents a 0 power of the base (16). Example 160. Last position in a hexadecimal number represents an x power of the base (16). Example 16x where x represents the last position - 1. Last position in a hexadecimal number represents an x power of the base (16). Example 16x where x represents the last position - 1. Hexadecimal Number: 19FDE16 Calculating Decimal Equivalent − Note − 19FDE16 is normally written as 19FDE. 107 Lectures 13.5 hours Arnab Chakraborty 106 Lectures 8 hours Arnab Chakraborty 99 Lectures 6 hours Arnab Chakraborty 46 Lectures 2.5 hours Shweta 70 Lectures 9 hours Abhilash Nelson 52 Lectures 7 hours Abhishek And Pukhraj Print Add Notes Bookmark this page
[ { "code": null, "e": 2175, "s": 1971, "text": "A digital system can understand positional number system only where there are a few symbols called digits and these symbols represent different values depending on the position they occupy in the number." }, { "code": null, "e": 2233, "s": 2175, "text": "A value of each digit in a number can be determined using" }, { "code": null, "e": 2243, "s": 2233, "text": "The digit" }, { "code": null, "e": 2253, "s": 2243, "text": "The digit" }, { "code": null, "e": 2293, "s": 2253, "text": "The position of the digit in the number" }, { "code": null, "e": 2333, "s": 2293, "text": "The position of the digit in the number" }, { "code": null, "e": 2449, "s": 2333, "text": "The base of the number system (where base is defined as the total number of digits available in the number system)." }, { "code": null, "e": 2565, "s": 2449, "text": "The base of the number system (where base is defined as the total number of digits available in the number system)." }, { "code": null, "e": 2855, "s": 2565, "text": "The number system that we use in our day-to-day life is the decimal number system. Decimal number system has base 10 as it uses 10 digits from 0 to 9. In decimal number system, the successive positions to the left of the decimal point represents units, tens, hundreds, thousands and so on." }, { "code": null, "e": 3116, "s": 2855, "text": "Each position represents a specific power of the base (10). For example, the decimal number 1234 consists of the digit 4 in the units position, 3 in the tens position, 2 in the hundreds position, and 1 in the thousands position, and its value can be written as" }, { "code": null, "e": 3217, "s": 3116, "text": "(1×1000) + (2×100) + (3×10) + (4×l)\n(1×103) + (2×102) + (3×101) + (4×l00)\n1000 + 200 + 30 + 1\n1234\n" }, { "code": null, "e": 3356, "s": 3217, "text": "As a computer programmer or an IT professional, you should understand the following number systems which are frequently used in computers." }, { "code": null, "e": 3382, "s": 3356, "text": "Base 2. Digits used: 0, 1" }, { "code": null, "e": 3410, "s": 3382, "text": "Base 8. Digits used: 0 to 7" }, { "code": null, "e": 3459, "s": 3410, "text": "Base 16. Digits used: 0 to 9, Letters used: A- F" }, { "code": null, "e": 3475, "s": 3459, "text": "Characteristics" }, { "code": null, "e": 3501, "s": 3475, "text": "Uses two digits, 0 and 1." }, { "code": null, "e": 3527, "s": 3501, "text": "Uses two digits, 0 and 1." }, { "code": null, "e": 3560, "s": 3527, "text": "Also called base 2 number system" }, { "code": null, "e": 3593, "s": 3560, "text": "Also called base 2 number system" }, { "code": null, "e": 3676, "s": 3593, "text": "Each position in a binary number represents a 0 power of the base (2). Example: 20" }, { "code": null, "e": 3759, "s": 3676, "text": "Each position in a binary number represents a 0 power of the base (2). Example: 20" }, { "code": null, "e": 3885, "s": 3759, "text": "Last position in a binary number represents an x power of the base (2). Example: 2x where x represents the last position - 1." }, { "code": null, "e": 4011, "s": 3885, "text": "Last position in a binary number represents an x power of the base (2). Example: 2x where x represents the last position - 1." }, { "code": null, "e": 4033, "s": 4011, "text": "Binary Number: 101012" }, { "code": null, "e": 4066, "s": 4033, "text": "Calculating Decimal Equivalent −" }, { "code": null, "e": 4109, "s": 4066, "text": "Note: 101012 is normally written as 10101." }, { "code": null, "e": 4125, "s": 4109, "text": "Characteristics" }, { "code": null, "e": 4161, "s": 4125, "text": "Uses eight digits, 0,1,2,3,4,5,6,7." }, { "code": null, "e": 4197, "s": 4161, "text": "Uses eight digits, 0,1,2,3,4,5,6,7." }, { "code": null, "e": 4230, "s": 4197, "text": "Also called base 8 number system" }, { "code": null, "e": 4263, "s": 4230, "text": "Also called base 8 number system" }, { "code": null, "e": 4346, "s": 4263, "text": "Each position in an octal number represents a 0 power of the base (8). Example: 80" }, { "code": null, "e": 4429, "s": 4346, "text": "Each position in an octal number represents a 0 power of the base (8). Example: 80" }, { "code": null, "e": 4555, "s": 4429, "text": "Last position in an octal number represents an x power of the base (8). Example: 8x where x represents the last position - 1." }, { "code": null, "e": 4681, "s": 4555, "text": "Last position in an octal number represents an x power of the base (8). Example: 8x where x represents the last position - 1." }, { "code": null, "e": 4703, "s": 4681, "text": "Octal Number − 125708" }, { "code": null, "e": 4736, "s": 4703, "text": "Calculating Decimal Equivalent −" }, { "code": null, "e": 4779, "s": 4736, "text": "Note: 125708 is normally written as 12570." }, { "code": null, "e": 4795, "s": 4779, "text": "Characteristics" }, { "code": null, "e": 4858, "s": 4795, "text": "Uses 10 digits and 6 letters, 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F." }, { "code": null, "e": 4921, "s": 4858, "text": "Uses 10 digits and 6 letters, 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F." }, { "code": null, "e": 5014, "s": 4921, "text": "Letters represents numbers starting from 10. A = 10, B = 11, C = 12, D = 13, E = 14, F = 15." }, { "code": null, "e": 5107, "s": 5014, "text": "Letters represents numbers starting from 10. A = 10, B = 11, C = 12, D = 13, E = 14, F = 15." }, { "code": null, "e": 5142, "s": 5107, "text": "Also called base 16 number system." }, { "code": null, "e": 5177, "s": 5142, "text": "Also called base 16 number system." }, { "code": null, "e": 5267, "s": 5177, "text": "Each position in a hexadecimal number represents a 0 power of the base (16). Example 160." }, { "code": null, "e": 5357, "s": 5267, "text": "Each position in a hexadecimal number represents a 0 power of the base (16). Example 160." }, { "code": null, "e": 5489, "s": 5357, "text": "Last position in a hexadecimal number represents an x power of the base (16). Example 16x where x represents the last position - 1." }, { "code": null, "e": 5621, "s": 5489, "text": "Last position in a hexadecimal number represents an x power of the base (16). Example 16x where x represents the last position - 1." }, { "code": null, "e": 5649, "s": 5621, "text": "Hexadecimal Number: 19FDE16" }, { "code": null, "e": 5682, "s": 5649, "text": "Calculating Decimal Equivalent −" }, { "code": null, "e": 5727, "s": 5682, "text": "Note − 19FDE16 is normally written as 19FDE." }, { "code": null, "e": 5764, "s": 5727, "text": "\n 107 Lectures \n 13.5 hours \n" }, { "code": null, "e": 5783, "s": 5764, "text": " Arnab Chakraborty" }, { "code": null, "e": 5817, "s": 5783, "text": "\n 106 Lectures \n 8 hours \n" }, { "code": null, "e": 5836, "s": 5817, "text": " Arnab Chakraborty" }, { "code": null, "e": 5869, "s": 5836, "text": "\n 99 Lectures \n 6 hours \n" }, { "code": null, "e": 5888, "s": 5869, "text": " Arnab Chakraborty" }, { "code": null, "e": 5923, "s": 5888, "text": "\n 46 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5931, "s": 5923, "text": " Shweta" }, { "code": null, "e": 5964, "s": 5931, "text": "\n 70 Lectures \n 9 hours \n" }, { "code": null, "e": 5981, "s": 5964, "text": " Abhilash Nelson" }, { "code": null, "e": 6014, "s": 5981, "text": "\n 52 Lectures \n 7 hours \n" }, { "code": null, "e": 6036, "s": 6014, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 6043, "s": 6036, "text": " Print" }, { "code": null, "e": 6054, "s": 6043, "text": " Add Notes" } ]
Donut Chart using Matplotlib in Python - GeeksforGeeks
02 Feb, 2022 Prequsities: Pie Chart in matplotlib Donut charts are the modified version of Pie Charts with the area of center cut out. A donut is more concerned about the use of area of arcs to represent the information in the most effective manner instead of Pie chart which is more focused on comparing the proportion area between the slices. Donut charts are more efficient in terms of space because the blank space inside the donut charts can be used to display some additional information about the donut chart. For being a Donut chart it must be necessarily a Pie chart. If we look at the pie chart, we will focus on the center of the chart. Donut charts, on the other hand, eliminates the need to compare the size or area of the slice and shifts the focus on the length of the arc, which in turn is easy to measure. Creating a Donut Chart involves three simple steps which are as follows : Create a Pie Chart Draw a circle of suitable dimensions. Add circle at the Center of Pie chart Python3 import matplotlib.pyplot as plt # Setting labels for items in ChartEmployee = ['Roshni', 'Shyam', 'Priyanshi', 'Harshit', 'Anmol'] # Setting size in Chart based on # given valuesSalary = [40000, 50000, 70000, 54000, 44000] # colorscolors = ['#FF0000', '#0000FF', '#FFFF00', '#ADFF2F', '#FFA500']# explosionexplode = (0.05, 0.05, 0.05, 0.05, 0.05) # Pie Chartplt.pie(Salary, colors=colors, labels=Employee, autopct='%1.1f%%', pctdistance=0.85, explode=explode) # draw circlecentre_circle = plt.Circle((0, 0), 0.70, fc='white')fig = plt.gcf() # Adding Circle in Pie chartfig.gca().add_artist(centre_circle) # Adding Title of chartplt.title('Employee Salary Details') # Displaying Chartplt.show() Output: A graph legend generally appears in form of a box to the right or left in the graph. It contains small samples of each color on the graph as well as a short description of what each color means in the graph. To add legends we will simply write the following code. plt.legend(labels, loc = "upper right") Here plt.legend() takes two parameters the first is labels and loc is used to set the location of legend box. Example: Python3 import matplotlib.pyplot as plt # Setting size in Chart based on # given valuessizes = [100, 500, 70, 54, 440] # Setting labels for items in Chartlabels = ['Apple', 'Banana', 'Mango', 'Grapes', 'Orange'] # colorscolors = ['#FF0000', '#0000FF', '#FFFF00', '#ADFF2F', '#FFA500'] # explosionexplode = (0.05, 0.05, 0.05, 0.05, 0.05) # Pie Chartplt.pie(sizes, colors=colors, labels=labels, autopct='%1.1f%%', pctdistance=0.85, explode=explode) # draw circlecentre_circle = plt.Circle((0, 0), 0.70, fc='white')fig = plt.gcf() # Adding Circle in Pie chartfig.gca().add_artist(centre_circle) # Adding Title of chartplt.title('Favourite Fruit Survey') # Add Legendsplt.legend(labels, loc="upper right") # Displaying Chartplt.show() Output: We can add a title to the Legend Box in Donut Chart by writing the following code: plt.legend(labels, loc = "upper right",title="Fruits Color") Example: Python3 import matplotlib.pyplot as plt # Setting size in Chart based on # given valuessizes = [100, 500, 70, 54, 440] # Setting labels for items in Chartlabels = ['Apple', 'Banana', 'Mango', 'Grapes', 'Orange'] # colorscolors = ['#FF0000', '#0000FF', '#FFFF00', '#ADFF2F', '#FFA500'] # explosionexplode = (0.05, 0.05, 0.05, 0.05, 0.05) # Pie Chartplt.pie(sizes, colors=colors, labels=labels, autopct='%1.1f%%', pctdistance=0.85, explode=explode) # draw circlecentre_circle = plt.Circle((0, 0), 0.70, fc='white')fig = plt.gcf() # Adding Circle in Pie chartfig.gca().add_artist(centre_circle) # Adding Title of chartplt.title('Favourite Fruit Survey') # Add Legendsplt.legend(labels, loc="upper right", title="Fruits Color") # Displaying Chartplt.show() Output: Example 2: Consider another situation that you have to prepare a report of marks obtained by different students in a test and visualize their performance by using a donut chart. To solve this problem we will use matplotlib library of python. The idea is that we will make a list of names of different students and another list of their respective marks and use this list to make a donut chart. Python3 # libraryimport matplotlib.pyplot as plt # list of name of studentsnames = ['Manish', 'Atul', 'Priya', 'Harshit'] # list of their respective marksmarks = [45, 66, 55, 77] # Create a circle at the center of# the plotmy_circle = plt.Circle((0, 0), 0.7, color='white') # Give color namesplt.pie(marks, labels=names, autopct='%1.1f%%', colors=['red', 'green', 'blue', 'yellow']) p = plt.gcf()p.gca().add_artist(my_circle) # Show the graphplt.show() Output: varshagumber28 Python-matplotlib 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() Defaultdict in Python Python | Get unique values from a list Python Classes and Objects Python | os.path.join() method Create a directory in Python
[ { "code": null, "e": 23927, "s": 23899, "text": "\n02 Feb, 2022" }, { "code": null, "e": 23964, "s": 23927, "text": "Prequsities: Pie Chart in matplotlib" }, { "code": null, "e": 24431, "s": 23964, "text": "Donut charts are the modified version of Pie Charts with the area of center cut out. A donut is more concerned about the use of area of arcs to represent the information in the most effective manner instead of Pie chart which is more focused on comparing the proportion area between the slices. Donut charts are more efficient in terms of space because the blank space inside the donut charts can be used to display some additional information about the donut chart." }, { "code": null, "e": 24737, "s": 24431, "text": "For being a Donut chart it must be necessarily a Pie chart. If we look at the pie chart, we will focus on the center of the chart. Donut charts, on the other hand, eliminates the need to compare the size or area of the slice and shifts the focus on the length of the arc, which in turn is easy to measure." }, { "code": null, "e": 24811, "s": 24737, "text": "Creating a Donut Chart involves three simple steps which are as follows :" }, { "code": null, "e": 24830, "s": 24811, "text": "Create a Pie Chart" }, { "code": null, "e": 24868, "s": 24830, "text": "Draw a circle of suitable dimensions." }, { "code": null, "e": 24906, "s": 24868, "text": "Add circle at the Center of Pie chart" }, { "code": null, "e": 24914, "s": 24906, "text": "Python3" }, { "code": "import matplotlib.pyplot as plt # Setting labels for items in ChartEmployee = ['Roshni', 'Shyam', 'Priyanshi', 'Harshit', 'Anmol'] # Setting size in Chart based on # given valuesSalary = [40000, 50000, 70000, 54000, 44000] # colorscolors = ['#FF0000', '#0000FF', '#FFFF00', '#ADFF2F', '#FFA500']# explosionexplode = (0.05, 0.05, 0.05, 0.05, 0.05) # Pie Chartplt.pie(Salary, colors=colors, labels=Employee, autopct='%1.1f%%', pctdistance=0.85, explode=explode) # draw circlecentre_circle = plt.Circle((0, 0), 0.70, fc='white')fig = plt.gcf() # Adding Circle in Pie chartfig.gca().add_artist(centre_circle) # Adding Title of chartplt.title('Employee Salary Details') # Displaying Chartplt.show()", "e": 25651, "s": 24914, "text": null }, { "code": null, "e": 25659, "s": 25651, "text": "Output:" }, { "code": null, "e": 25867, "s": 25659, "text": "A graph legend generally appears in form of a box to the right or left in the graph. It contains small samples of each color on the graph as well as a short description of what each color means in the graph." }, { "code": null, "e": 25923, "s": 25867, "text": "To add legends we will simply write the following code." }, { "code": null, "e": 25964, "s": 25923, "text": "plt.legend(labels, loc = \"upper right\") " }, { "code": null, "e": 26074, "s": 25964, "text": "Here plt.legend() takes two parameters the first is labels and loc is used to set the location of legend box." }, { "code": null, "e": 26084, "s": 26074, "text": "Example: " }, { "code": null, "e": 26092, "s": 26084, "text": "Python3" }, { "code": "import matplotlib.pyplot as plt # Setting size in Chart based on # given valuessizes = [100, 500, 70, 54, 440] # Setting labels for items in Chartlabels = ['Apple', 'Banana', 'Mango', 'Grapes', 'Orange'] # colorscolors = ['#FF0000', '#0000FF', '#FFFF00', '#ADFF2F', '#FFA500'] # explosionexplode = (0.05, 0.05, 0.05, 0.05, 0.05) # Pie Chartplt.pie(sizes, colors=colors, labels=labels, autopct='%1.1f%%', pctdistance=0.85, explode=explode) # draw circlecentre_circle = plt.Circle((0, 0), 0.70, fc='white')fig = plt.gcf() # Adding Circle in Pie chartfig.gca().add_artist(centre_circle) # Adding Title of chartplt.title('Favourite Fruit Survey') # Add Legendsplt.legend(labels, loc=\"upper right\") # Displaying Chartplt.show()", "e": 26842, "s": 26092, "text": null }, { "code": null, "e": 26850, "s": 26842, "text": "Output:" }, { "code": null, "e": 26933, "s": 26850, "text": "We can add a title to the Legend Box in Donut Chart by writing the following code:" }, { "code": null, "e": 26994, "s": 26933, "text": "plt.legend(labels, loc = \"upper right\",title=\"Fruits Color\")" }, { "code": null, "e": 27003, "s": 26994, "text": "Example:" }, { "code": null, "e": 27011, "s": 27003, "text": "Python3" }, { "code": "import matplotlib.pyplot as plt # Setting size in Chart based on # given valuessizes = [100, 500, 70, 54, 440] # Setting labels for items in Chartlabels = ['Apple', 'Banana', 'Mango', 'Grapes', 'Orange'] # colorscolors = ['#FF0000', '#0000FF', '#FFFF00', '#ADFF2F', '#FFA500'] # explosionexplode = (0.05, 0.05, 0.05, 0.05, 0.05) # Pie Chartplt.pie(sizes, colors=colors, labels=labels, autopct='%1.1f%%', pctdistance=0.85, explode=explode) # draw circlecentre_circle = plt.Circle((0, 0), 0.70, fc='white')fig = plt.gcf() # Adding Circle in Pie chartfig.gca().add_artist(centre_circle) # Adding Title of chartplt.title('Favourite Fruit Survey') # Add Legendsplt.legend(labels, loc=\"upper right\", title=\"Fruits Color\") # Displaying Chartplt.show()", "e": 27800, "s": 27011, "text": null }, { "code": null, "e": 27808, "s": 27800, "text": "Output:" }, { "code": null, "e": 28202, "s": 27808, "text": "Example 2: Consider another situation that you have to prepare a report of marks obtained by different students in a test and visualize their performance by using a donut chart. To solve this problem we will use matplotlib library of python. The idea is that we will make a list of names of different students and another list of their respective marks and use this list to make a donut chart." }, { "code": null, "e": 28210, "s": 28202, "text": "Python3" }, { "code": "# libraryimport matplotlib.pyplot as plt # list of name of studentsnames = ['Manish', 'Atul', 'Priya', 'Harshit'] # list of their respective marksmarks = [45, 66, 55, 77] # Create a circle at the center of# the plotmy_circle = plt.Circle((0, 0), 0.7, color='white') # Give color namesplt.pie(marks, labels=names, autopct='%1.1f%%', colors=['red', 'green', 'blue', 'yellow']) p = plt.gcf()p.gca().add_artist(my_circle) # Show the graphplt.show()", "e": 28668, "s": 28210, "text": null }, { "code": null, "e": 28676, "s": 28668, "text": "Output:" }, { "code": null, "e": 28691, "s": 28676, "text": "varshagumber28" }, { "code": null, "e": 28709, "s": 28691, "text": "Python-matplotlib" }, { "code": null, "e": 28716, "s": 28709, "text": "Python" }, { "code": null, "e": 28814, "s": 28716, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28823, "s": 28814, "text": "Comments" }, { "code": null, "e": 28836, "s": 28823, "text": "Old Comments" }, { "code": null, "e": 28868, "s": 28836, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28924, "s": 28868, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28966, "s": 28924, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29008, "s": 28966, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29044, "s": 29008, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 29066, "s": 29044, "text": "Defaultdict in Python" }, { "code": null, "e": 29105, "s": 29066, "text": "Python | Get unique values from a list" }, { "code": null, "e": 29132, "s": 29105, "text": "Python Classes and Objects" }, { "code": null, "e": 29163, "s": 29132, "text": "Python | os.path.join() method" } ]
What is strcpy() Function in C language?
The C library function char *strcpy(char *dest, const char *src) copies the string pointed to, by src to dest. An array of characters is called a string. Following is the declaration for an array char stringname [size]; For example − char string[50]; string of length 50 characters Using single character constant − char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’} Using string constants − char string[10] = "Hello":; Accessing − There is a control string "%s" used for accessing the string till it encounters ‘\0’ This function is used for copying source string into destination string. This function is used for copying source string into destination string. The length of the destination string is greater than or equal to the source string. The length of the destination string is greater than or equal to the source string. The syntax is as follows − strcpy (Destination string, Source String); The following example shows the usage of strcpy() function. char a[50]; char a[50]; strcpy ("Hello",a); strcpy ( a,"hello"); output: error output: a= "Hello" The following program shows the usage of strcpy() function. Live Demo #include <string.h> main ( ){ char a[50], b[50]; printf ("enter a source string"); scanf("%s", a); strcpy ( b,a); printf ("copied string = %s",b); getch ( ); } When the above program is executed, it produces the following result − Enter a source string : Hello Copied string = Hello Let’s see another example on strcpy. Given below is a C program demonstrating strcpy library function − Live Demo #include<stdio.h> #include<string.h> void main(){ //Declaring source and destination strings// char source[25],destination[50]; //Reading Input from user// printf("Enter the string to be copied : "); gets(source); printf("Enter the existing destination string : "); gets(destination); //Using strcpy library function// strcpy(destination,source); //Printing destination string// printf("Destination string is : "); puts(destination); } When the above program is executed, it produces the following result − Enter the string to be copied : C programming Enter the existing destination string : bhanu Destination string is : C programming
[ { "code": null, "e": 1173, "s": 1062, "text": "The C library function char *strcpy(char *dest, const char *src) copies the string pointed to, by src to dest." }, { "code": null, "e": 1216, "s": 1173, "text": "An array of characters is called a string." }, { "code": null, "e": 1258, "s": 1216, "text": "Following is the declaration for an array" }, { "code": null, "e": 1282, "s": 1258, "text": "char stringname [size];" }, { "code": null, "e": 1344, "s": 1282, "text": "For example − char string[50]; string of length 50 characters" }, { "code": null, "e": 1378, "s": 1344, "text": "Using single character constant −" }, { "code": null, "e": 1429, "s": 1378, "text": "char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\\0’}" }, { "code": null, "e": 1454, "s": 1429, "text": "Using string constants −" }, { "code": null, "e": 1482, "s": 1454, "text": "char string[10] = \"Hello\":;" }, { "code": null, "e": 1579, "s": 1482, "text": "Accessing − There is a control string \"%s\" used for accessing the string till it encounters ‘\\0’" }, { "code": null, "e": 1652, "s": 1579, "text": "This function is used for copying source string into destination string." }, { "code": null, "e": 1725, "s": 1652, "text": "This function is used for copying source string into destination string." }, { "code": null, "e": 1809, "s": 1725, "text": "The length of the destination string is greater than or equal to the source string." }, { "code": null, "e": 1893, "s": 1809, "text": "The length of the destination string is greater than or equal to the source string." }, { "code": null, "e": 1920, "s": 1893, "text": "The syntax is as follows −" }, { "code": null, "e": 1964, "s": 1920, "text": "strcpy (Destination string, Source String);" }, { "code": null, "e": 2024, "s": 1964, "text": "The following example shows the usage of strcpy() function." }, { "code": null, "e": 2122, "s": 2024, "text": "char a[50]; char a[50];\nstrcpy (\"Hello\",a); strcpy ( a,\"hello\");\noutput: error output: a= \"Hello\"" }, { "code": null, "e": 2182, "s": 2122, "text": "The following program shows the usage of strcpy() function." }, { "code": null, "e": 2193, "s": 2182, "text": " Live Demo" }, { "code": null, "e": 2371, "s": 2193, "text": "#include <string.h>\nmain ( ){\n char a[50], b[50];\n printf (\"enter a source string\");\n scanf(\"%s\", a);\n strcpy ( b,a);\n printf (\"copied string = %s\",b);\n getch ( );\n}" }, { "code": null, "e": 2442, "s": 2371, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 2494, "s": 2442, "text": "Enter a source string : Hello\nCopied string = Hello" }, { "code": null, "e": 2531, "s": 2494, "text": "Let’s see another example on strcpy." }, { "code": null, "e": 2598, "s": 2531, "text": "Given below is a C program demonstrating strcpy library function −" }, { "code": null, "e": 2609, "s": 2598, "text": " Live Demo" }, { "code": null, "e": 3081, "s": 2609, "text": "#include<stdio.h>\n#include<string.h>\nvoid main(){\n //Declaring source and destination strings//\n char source[25],destination[50];\n //Reading Input from user//\n printf(\"Enter the string to be copied : \");\n gets(source);\n printf(\"Enter the existing destination string : \");\n gets(destination);\n //Using strcpy library function//\n strcpy(destination,source);\n //Printing destination string//\n printf(\"Destination string is : \");\n puts(destination);\n}" }, { "code": null, "e": 3152, "s": 3081, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 3282, "s": 3152, "text": "Enter the string to be copied : C programming\nEnter the existing destination string : bhanu\nDestination string is : C programming" } ]
D3.js | d3.selectAll() Function
18 Jul, 2019 The d3.selectAll() function in D3.js is used to select all the element that matches the specified selector string. Syntax: d3.selectAll("element") Parameters: This function accepts single parameter HTML tag as a parameter. Return Value: This function returns the selected elements. Below programs illustrate the d3.selectAll() function in D3.js: Example 1: <!DOCTYPE html><html> <head> <title> D3.js | d3.selectAll() Function </title> <script src = "https://d3js.org/d3.v4.min.js"></script></head> <body> <div>Geeks</div> <div>GeeksforGeeks</div> <script> // Calling the selectAll() function d3.selectAll("div").text(); </script></body> </html> Output: Geeks GeeksforGeeks Example 2: <!DOCTYPE html><html> <head> <title> D3.js | d3.selectAll() Function </title> <script src = "https://d3js.org/d3.v4.min.js"></script></head> <body> <p>GeeksforGeeks</p> <p>A computer science portal for geeks</p> <p>d3.selectAll() function</p> <script> // Calling the selectAll() function d3.selectAll("p").text(); </script></body> </html> Output: GeeksforGeeks A computer science portal for geeks d3.selectAll() function Reference: https://devdocs.io/d3~5/d3-selection#selectAll D3.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Jul, 2019" }, { "code": null, "e": 143, "s": 28, "text": "The d3.selectAll() function in D3.js is used to select all the element that matches the specified selector string." }, { "code": null, "e": 151, "s": 143, "text": "Syntax:" }, { "code": null, "e": 175, "s": 151, "text": "d3.selectAll(\"element\")" }, { "code": null, "e": 251, "s": 175, "text": "Parameters: This function accepts single parameter HTML tag as a parameter." }, { "code": null, "e": 310, "s": 251, "text": "Return Value: This function returns the selected elements." }, { "code": null, "e": 374, "s": 310, "text": "Below programs illustrate the d3.selectAll() function in D3.js:" }, { "code": null, "e": 385, "s": 374, "text": "Example 1:" }, { "code": "<!DOCTYPE html><html> <head> <title> D3.js | d3.selectAll() Function </title> <script src = \"https://d3js.org/d3.v4.min.js\"></script></head> <body> <div>Geeks</div> <div>GeeksforGeeks</div> <script> // Calling the selectAll() function d3.selectAll(\"div\").text(); </script></body> </html> ", "e": 774, "s": 385, "text": null }, { "code": null, "e": 782, "s": 774, "text": "Output:" }, { "code": null, "e": 803, "s": 782, "text": "Geeks\nGeeksforGeeks\n" }, { "code": null, "e": 814, "s": 803, "text": "Example 2:" }, { "code": "<!DOCTYPE html><html> <head> <title> D3.js | d3.selectAll() Function </title> <script src = \"https://d3js.org/d3.v4.min.js\"></script></head> <body> <p>GeeksforGeeks</p> <p>A computer science portal for geeks</p> <p>d3.selectAll() function</p> <script> // Calling the selectAll() function d3.selectAll(\"p\").text(); </script></body> </html> ", "e": 1263, "s": 814, "text": null }, { "code": null, "e": 1271, "s": 1263, "text": "Output:" }, { "code": null, "e": 1346, "s": 1271, "text": "GeeksforGeeks\nA computer science portal for geeks\nd3.selectAll() function\n" }, { "code": null, "e": 1404, "s": 1346, "text": "Reference: https://devdocs.io/d3~5/d3-selection#selectAll" }, { "code": null, "e": 1410, "s": 1404, "text": "D3.js" }, { "code": null, "e": 1421, "s": 1410, "text": "JavaScript" }, { "code": null, "e": 1438, "s": 1421, "text": "Web Technologies" }, { "code": null, "e": 1536, "s": 1438, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1597, "s": 1536, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1669, "s": 1597, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 1709, "s": 1669, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 1751, "s": 1709, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 1792, "s": 1751, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 1825, "s": 1792, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1887, "s": 1825, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 1948, "s": 1887, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1998, "s": 1948, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to create components in ReactJS ?
06 Aug, 2021 As we all know, React uses this JSX format so that we can put HTML and JavaScript together. These React components can be defined anywhere in your ReactJS project and can be used anywhere in your ReactJS project. There are two ways to define components in ReactJS, both are used by a wide range of programmers, but with the APIS/HOOKs like useState, use context the functional components are becoming more and more popular. React functional componentsReact class-based component React functional components React class-based component 1. React Functional Components: React functional components can be any JavaScript function that returns the HTML. These functional components can also accept “props”, meaning properties or data. As these are JavaScript functions or extensions of JavaScript functions, they can also be created from the ES6 convention of the arrow function. These functional components can also accept the props that we can use using JSX syntax and you can also put your normal JavaScript code before the return statement. One thing to notice is that there should only be one return per component. Syntax: Javascript const Greet = (props) => { const person = props.name; return ( <div> <h1>Hello {person}!!</h1> </div> )} 2. React Class-based Components: The class-based components also have almost the same features as React function components. but before we define our class-based component, we need to import the “React. Component” or extract the Component like “{Component}” from React. import React, {Components} from 'react'; Syntax: Javascript import React, { Component } from 'react' class App extends Component { render() { return ( <div> <h1>Hello {this.props.name}</h1> </div> ) }} Rendering the Component: We have successfully made the components, but in order to use them we need to render them. one can first export their components and can use them anywhere in the ReactDOM.render method after importing them. Somewhere in your project in ReactDOM.render() ReactDOM.render( <React.StrictMode> <Greet name="gfg " /> </React.StrictMode>, document.getElementById('root') ); Now we are going to see the full-fledged working App created using React components. Creating React Application And Installing Module: Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Project Structure: It will look like the following. file directory Approach: Now have a component named “Card” in your App.js. we are going to use this component later. This Then component accepts two arguments/data of “writer” and “receiver”. Then we have one return which just uses this data of writer and receiver and displays it on a card. After that, we have made another component named App which will be used to hold all the components for our Application. This App has an export default so that we can use it anywhere in our React App. Hence, we do not have to render it manually. This App is automatically rendered in your index.js while creating a react app using npx. App.js import React from "react"; function Card({ receiver, writer }) { return ( <div> <h1 style={{ backgroundColor: "lightblue", width: "fit-content" }}> GeeksforGeeks </h1> <h2 style={{ backgroundColor: "lightgrey", width: "fit-content" }}> A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles </h2> <h3>Your truly, {writer}</h3> </div> );} export default function App() { return ( <div> <Card writer="GFG" receiver="gfg jr" /> </div> );} 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: Output Picked React-Questions JavaScript ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request JavaScript | Promises How to fetch data from an API in ReactJS ? Axios in React: A Guide for Beginners How to redirect to another page in ReactJS ? ReactJS Functional Components
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Aug, 2021" }, { "code": null, "e": 452, "s": 28, "text": "As we all know, React uses this JSX format so that we can put HTML and JavaScript together. These React components can be defined anywhere in your ReactJS project and can be used anywhere in your ReactJS project. There are two ways to define components in ReactJS, both are used by a wide range of programmers, but with the APIS/HOOKs like useState, use context the functional components are becoming more and more popular." }, { "code": null, "e": 507, "s": 452, "text": "React functional componentsReact class-based component" }, { "code": null, "e": 535, "s": 507, "text": "React functional components" }, { "code": null, "e": 563, "s": 535, "text": "React class-based component" }, { "code": null, "e": 1143, "s": 563, "text": "1. React Functional Components: React functional components can be any JavaScript function that returns the HTML. These functional components can also accept “props”, meaning properties or data. As these are JavaScript functions or extensions of JavaScript functions, they can also be created from the ES6 convention of the arrow function. These functional components can also accept the props that we can use using JSX syntax and you can also put your normal JavaScript code before the return statement. One thing to notice is that there should only be one return per component." }, { "code": null, "e": 1151, "s": 1143, "text": "Syntax:" }, { "code": null, "e": 1162, "s": 1151, "text": "Javascript" }, { "code": "const Greet = (props) => { const person = props.name; return ( <div> <h1>Hello {person}!!</h1> </div> )}", "e": 1283, "s": 1162, "text": null }, { "code": null, "e": 1555, "s": 1285, "text": "2. React Class-based Components: The class-based components also have almost the same features as React function components. but before we define our class-based component, we need to import the “React. Component” or extract the Component like “{Component}” from React." }, { "code": null, "e": 1596, "s": 1555, "text": "import React, {Components} from 'react';" }, { "code": null, "e": 1604, "s": 1596, "text": "Syntax:" }, { "code": null, "e": 1615, "s": 1604, "text": "Javascript" }, { "code": "import React, { Component } from 'react' class App extends Component { render() { return ( <div> <h1>Hello {this.props.name}</h1> </div> ) }}", "e": 1783, "s": 1615, "text": null }, { "code": null, "e": 2015, "s": 1783, "text": "Rendering the Component: We have successfully made the components, but in order to use them we need to render them. one can first export their components and can use them anywhere in the ReactDOM.render method after importing them." }, { "code": null, "e": 2062, "s": 2015, "text": "Somewhere in your project in ReactDOM.render()" }, { "code": null, "e": 2186, "s": 2062, "text": "ReactDOM.render(\n <React.StrictMode>\n <Greet name=\"gfg \" />\n </React.StrictMode>,\n document.getElementById('root')\n);" }, { "code": null, "e": 2271, "s": 2186, "text": "Now we are going to see the full-fledged working App created using React components." }, { "code": null, "e": 2323, "s": 2273, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 2387, "s": 2323, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 2419, "s": 2387, "text": "npx create-react-app foldername" }, { "code": null, "e": 2519, "s": 2419, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 2533, "s": 2519, "text": "cd foldername" }, { "code": null, "e": 2585, "s": 2533, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 2600, "s": 2585, "text": "file directory" }, { "code": null, "e": 3213, "s": 2600, "text": "Approach: Now have a component named “Card” in your App.js. we are going to use this component later. This Then component accepts two arguments/data of “writer” and “receiver”. Then we have one return which just uses this data of writer and receiver and displays it on a card. After that, we have made another component named App which will be used to hold all the components for our Application. This App has an export default so that we can use it anywhere in our React App. Hence, we do not have to render it manually. This App is automatically rendered in your index.js while creating a react app using npx. " }, { "code": null, "e": 3220, "s": 3213, "text": "App.js" }, { "code": "import React from \"react\"; function Card({ receiver, writer }) { return ( <div> <h1 style={{ backgroundColor: \"lightblue\", width: \"fit-content\" }}> GeeksforGeeks </h1> <h2 style={{ backgroundColor: \"lightgrey\", width: \"fit-content\" }}> A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles </h2> <h3>Your truly, {writer}</h3> </div> );} export default function App() { return ( <div> <Card writer=\"GFG\" receiver=\"gfg jr\" /> </div> );}", "e": 3895, "s": 3220, "text": null }, { "code": null, "e": 4008, "s": 3895, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 4018, "s": 4008, "text": "npm start" }, { "code": null, "e": 4117, "s": 4018, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 4125, "s": 4117, "text": "Output " }, { "code": null, "e": 4132, "s": 4125, "text": "Picked" }, { "code": null, "e": 4148, "s": 4132, "text": "React-Questions" }, { "code": null, "e": 4159, "s": 4148, "text": "JavaScript" }, { "code": null, "e": 4167, "s": 4159, "text": "ReactJS" }, { "code": null, "e": 4184, "s": 4167, "text": "Web Technologies" }, { "code": null, "e": 4282, "s": 4184, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4343, "s": 4282, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4383, "s": 4343, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 4425, "s": 4383, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 4466, "s": 4425, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 4488, "s": 4466, "text": "JavaScript | Promises" }, { "code": null, "e": 4531, "s": 4488, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 4569, "s": 4531, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 4614, "s": 4569, "text": "How to redirect to another page in ReactJS ?" } ]
Remove array elements in Ruby
20 Jul, 2021 In this article, we will learn how to remove elements from an array in Ruby. Method #1: Using Index Ruby # Ruby program to remove elements # in array # creating string using []str = ["GFG", "G4G", "Sudo", "Geeks"] str.delete_at(0)print str Output: ["G4G", "Sudo", "Geeks" Method #2: Using delete() method – Ruby # Ruby program to remove elements # in array # creating string using []str = ["GFG", "G4G", "Sudo", "Geeks"] str.delete("Sudo")print str Output: ["GFG", "G4G", "Geeks" Method #3: Using pop() method – Ruby # Ruby program to remove elements # in array # creating string using []str = ["GFG", "G4G", "Sudo", "Geeks"] str.popprint str Output: ["GFG", "G4G", "Sudo"] surinderdawra388 Ruby Array Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Make a Custom Array of Hashes in Ruby? Ruby | Enumerator each_with_index function Ruby | unless Statement and unless Modifier Ruby | Array class find_index() operation Ruby For Beginners Ruby | String concat Method Ruby on Rails Introduction Ruby | Array shift() function Ruby | Types of Variables
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Jul, 2021" }, { "code": null, "e": 105, "s": 28, "text": "In this article, we will learn how to remove elements from an array in Ruby." }, { "code": null, "e": 128, "s": 105, "text": "Method #1: Using Index" }, { "code": null, "e": 133, "s": 128, "text": "Ruby" }, { "code": "# Ruby program to remove elements # in array # creating string using []str = [\"GFG\", \"G4G\", \"Sudo\", \"Geeks\"] str.delete_at(0)print str", "e": 272, "s": 133, "text": null }, { "code": null, "e": 280, "s": 272, "text": "Output:" }, { "code": null, "e": 304, "s": 280, "text": "[\"G4G\", \"Sudo\", \"Geeks\"" }, { "code": null, "e": 339, "s": 304, "text": "Method #2: Using delete() method –" }, { "code": null, "e": 344, "s": 339, "text": "Ruby" }, { "code": "# Ruby program to remove elements # in array # creating string using []str = [\"GFG\", \"G4G\", \"Sudo\", \"Geeks\"] str.delete(\"Sudo\")print str", "e": 485, "s": 344, "text": null }, { "code": null, "e": 493, "s": 485, "text": "Output:" }, { "code": null, "e": 517, "s": 493, "text": " [\"GFG\", \"G4G\", \"Geeks\"" }, { "code": null, "e": 549, "s": 517, "text": "Method #3: Using pop() method –" }, { "code": null, "e": 554, "s": 549, "text": "Ruby" }, { "code": "# Ruby program to remove elements # in array # creating string using []str = [\"GFG\", \"G4G\", \"Sudo\", \"Geeks\"] str.popprint str", "e": 684, "s": 554, "text": null }, { "code": null, "e": 692, "s": 684, "text": "Output:" }, { "code": null, "e": 717, "s": 692, "text": " [\"GFG\", \"G4G\", \"Sudo\"] " }, { "code": null, "e": 736, "s": 719, "text": "surinderdawra388" }, { "code": null, "e": 747, "s": 736, "text": "Ruby Array" }, { "code": null, "e": 752, "s": 747, "text": "Ruby" }, { "code": null, "e": 850, "s": 752, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 896, "s": 850, "text": "How to Make a Custom Array of Hashes in Ruby?" }, { "code": null, "e": 939, "s": 896, "text": "Ruby | Enumerator each_with_index function" }, { "code": null, "e": 983, "s": 939, "text": "Ruby | unless Statement and unless Modifier" }, { "code": null, "e": 1025, "s": 983, "text": "Ruby | Array class find_index() operation" }, { "code": null, "e": 1044, "s": 1025, "text": "Ruby For Beginners" }, { "code": null, "e": 1072, "s": 1044, "text": "Ruby | String concat Method" }, { "code": null, "e": 1099, "s": 1072, "text": "Ruby on Rails Introduction" }, { "code": null, "e": 1129, "s": 1099, "text": "Ruby | Array shift() function" } ]
Least Frequently Used (LFU) Cache Implementation
05 Dec, 2019 Least Frequently Used (LFU) is a caching algorithm in which the least frequently used cache block is removed whenever the cache is overflowed. In LFU we check the old page as well as the frequency of that page and if the frequency of the page is larger than the old page we cannot remove it and if all the old pages are having same frequency then take last i.e FIFO method for that and remove that page. Min-heap data structure is a good option to implement this algorithm, as it handles insertion, deletion, and update in logarithmic time complexity. A tie can be resolved by removing the least recently used cache block. The following two containers have been used to solve the problem: A vector of integer pairs has been used to represent the cache, where each pair consists of the block number and the number of times it has been used. The vector is ordered in the form of a min-heap, which allows us to access the least frequently used block in constant time. A hashmap has been used to store the indices of the cache blocks which allows searching in constant time. Below is the implementation of the above approach: // C++ program for LFU cache implementation#include <bits/stdc++.h>using namespace std; // Generic function to swap two pairsvoid swap(pair<int, int>& a, pair<int, int>& b){ pair<int, int> temp = a; a = b; b = temp;} // Returns the index of the parent nodeinline int parent(int i){ return (i - 1) / 2;} // Returns the index of the left child nodeinline int left(int i){ return 2 * i + 1;} // Returns the index of the right child nodeinline int right(int i){ return 2 * i + 2;} // Self made heap tp Rearranges// the nodes in order to maintain the heap propertyvoid heapify(vector<pair<int, int> >& v, unordered_map<int, int>& m, int i, int n){ int l = left(i), r = right(i), minim; if (l < n) minim = ((v[i].second < v[l].second) ? i : l); else minim = i; if (r < n) minim = ((v[minim].second < v[r].second) ? minim : r); if (minim != i) { m[v[minim].first] = i; m[v[i].first] = minim; swap(v[minim], v[i]); heapify(v, m, minim, n); }} // Function to Increment the frequency // of a node and rearranges the heapvoid increment(vector<pair<int, int> >& v, unordered_map<int, int>& m, int i, int n){ ++v[i].second; heapify(v, m, i, n);} // Function to Insert a new node in the heapvoid insert(vector<pair<int, int> >& v, unordered_map<int, int>& m, int value, int& n){ if (n == v.size()) { m.erase(v[0].first); cout << "Cache block " << v[0].first << " removed.\n"; v[0] = v[--n]; heapify(v, m, 0, n); } v[n++] = make_pair(value, 1); m.insert(make_pair(value, n - 1)); int i = n - 1; // Insert a node in the heap by swapping elements while (i && v[parent(i)].second > v[i].second) { m[v[i].first] = parent(i); m[v[parent(i)].first] = i; swap(v[i], v[parent(i)]); i = parent(i); } cout << "Cache block " << value << " inserted.\n";} // Function to refer to the block value in the cachevoid refer(vector<pair<int, int> >& cache, unordered_map<int, int>& indices, int value, int& cache_size){ if (indices.find(value) == indices.end()) insert(cache, indices, value, cache_size); else increment(cache, indices, indices[value], cache_size);} // Driver Codeint main(){ int cache_max_size = 4, cache_size = 0; vector<pair<int, int> > cache(cache_max_size); unordered_map<int, int> indices; refer(cache, indices, 1, cache_size); refer(cache, indices, 2, cache_size); refer(cache, indices, 1, cache_size); refer(cache, indices, 3, cache_size); refer(cache, indices, 2, cache_size); refer(cache, indices, 4, cache_size); refer(cache, indices, 5, cache_size); return 0;} Cache block 1 inserted. Cache block 2 inserted. Cache block 3 inserted. Cache block 4 inserted. Cache block 3 removed. Cache block 5 inserted. vaibhav29498 Amazon cpp-map cpp-pair cpp-vector Data Structures-Heap Google Hash Heap Operating Systems Amazon Google Operating Systems Hash Heap Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Hash Functions and list/types of Hash functions Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash) Sorting a Map by value in C++ STL File Organization in DBMS | Set 2 Applications of Hashing HeapSort Binary Heap Huffman Coding | Greedy Algo-3 Introduction to Data Structures Time Complexity of building a heap
[ { "code": null, "e": 54, "s": 26, "text": "\n05 Dec, 2019" }, { "code": null, "e": 458, "s": 54, "text": "Least Frequently Used (LFU) is a caching algorithm in which the least frequently used cache block is removed whenever the cache is overflowed. In LFU we check the old page as well as the frequency of that page and if the frequency of the page is larger than the old page we cannot remove it and if all the old pages are having same frequency then take last i.e FIFO method for that and remove that page." }, { "code": null, "e": 743, "s": 458, "text": "Min-heap data structure is a good option to implement this algorithm, as it handles insertion, deletion, and update in logarithmic time complexity. A tie can be resolved by removing the least recently used cache block. The following two containers have been used to solve the problem:" }, { "code": null, "e": 1019, "s": 743, "text": "A vector of integer pairs has been used to represent the cache, where each pair consists of the block number and the number of times it has been used. The vector is ordered in the form of a min-heap, which allows us to access the least frequently used block in constant time." }, { "code": null, "e": 1125, "s": 1019, "text": "A hashmap has been used to store the indices of the cache blocks which allows searching in constant time." }, { "code": null, "e": 1176, "s": 1125, "text": "Below is the implementation of the above approach:" }, { "code": "// C++ program for LFU cache implementation#include <bits/stdc++.h>using namespace std; // Generic function to swap two pairsvoid swap(pair<int, int>& a, pair<int, int>& b){ pair<int, int> temp = a; a = b; b = temp;} // Returns the index of the parent nodeinline int parent(int i){ return (i - 1) / 2;} // Returns the index of the left child nodeinline int left(int i){ return 2 * i + 1;} // Returns the index of the right child nodeinline int right(int i){ return 2 * i + 2;} // Self made heap tp Rearranges// the nodes in order to maintain the heap propertyvoid heapify(vector<pair<int, int> >& v, unordered_map<int, int>& m, int i, int n){ int l = left(i), r = right(i), minim; if (l < n) minim = ((v[i].second < v[l].second) ? i : l); else minim = i; if (r < n) minim = ((v[minim].second < v[r].second) ? minim : r); if (minim != i) { m[v[minim].first] = i; m[v[i].first] = minim; swap(v[minim], v[i]); heapify(v, m, minim, n); }} // Function to Increment the frequency // of a node and rearranges the heapvoid increment(vector<pair<int, int> >& v, unordered_map<int, int>& m, int i, int n){ ++v[i].second; heapify(v, m, i, n);} // Function to Insert a new node in the heapvoid insert(vector<pair<int, int> >& v, unordered_map<int, int>& m, int value, int& n){ if (n == v.size()) { m.erase(v[0].first); cout << \"Cache block \" << v[0].first << \" removed.\\n\"; v[0] = v[--n]; heapify(v, m, 0, n); } v[n++] = make_pair(value, 1); m.insert(make_pair(value, n - 1)); int i = n - 1; // Insert a node in the heap by swapping elements while (i && v[parent(i)].second > v[i].second) { m[v[i].first] = parent(i); m[v[parent(i)].first] = i; swap(v[i], v[parent(i)]); i = parent(i); } cout << \"Cache block \" << value << \" inserted.\\n\";} // Function to refer to the block value in the cachevoid refer(vector<pair<int, int> >& cache, unordered_map<int, int>& indices, int value, int& cache_size){ if (indices.find(value) == indices.end()) insert(cache, indices, value, cache_size); else increment(cache, indices, indices[value], cache_size);} // Driver Codeint main(){ int cache_max_size = 4, cache_size = 0; vector<pair<int, int> > cache(cache_max_size); unordered_map<int, int> indices; refer(cache, indices, 1, cache_size); refer(cache, indices, 2, cache_size); refer(cache, indices, 1, cache_size); refer(cache, indices, 3, cache_size); refer(cache, indices, 2, cache_size); refer(cache, indices, 4, cache_size); refer(cache, indices, 5, cache_size); return 0;}", "e": 3964, "s": 1176, "text": null }, { "code": null, "e": 4108, "s": 3964, "text": "Cache block 1 inserted.\nCache block 2 inserted.\nCache block 3 inserted.\nCache block 4 inserted.\nCache block 3 removed.\nCache block 5 inserted.\n" }, { "code": null, "e": 4121, "s": 4108, "text": "vaibhav29498" }, { "code": null, "e": 4128, "s": 4121, "text": "Amazon" }, { "code": null, "e": 4136, "s": 4128, "text": "cpp-map" }, { "code": null, "e": 4145, "s": 4136, "text": "cpp-pair" }, { "code": null, "e": 4156, "s": 4145, "text": "cpp-vector" }, { "code": null, "e": 4177, "s": 4156, "text": "Data Structures-Heap" }, { "code": null, "e": 4184, "s": 4177, "text": "Google" }, { "code": null, "e": 4189, "s": 4184, "text": "Hash" }, { "code": null, "e": 4194, "s": 4189, "text": "Heap" }, { "code": null, "e": 4212, "s": 4194, "text": "Operating Systems" }, { "code": null, "e": 4219, "s": 4212, "text": "Amazon" }, { "code": null, "e": 4226, "s": 4219, "text": "Google" }, { "code": null, "e": 4244, "s": 4226, "text": "Operating Systems" }, { "code": null, "e": 4249, "s": 4244, "text": "Hash" }, { "code": null, "e": 4254, "s": 4249, "text": "Heap" }, { "code": null, "e": 4352, "s": 4254, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4400, "s": 4352, "text": "Hash Functions and list/types of Hash functions" }, { "code": null, "e": 4470, "s": 4400, "text": "Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)" }, { "code": null, "e": 4504, "s": 4470, "text": "Sorting a Map by value in C++ STL" }, { "code": null, "e": 4538, "s": 4504, "text": "File Organization in DBMS | Set 2" }, { "code": null, "e": 4562, "s": 4538, "text": "Applications of Hashing" }, { "code": null, "e": 4571, "s": 4562, "text": "HeapSort" }, { "code": null, "e": 4583, "s": 4571, "text": "Binary Heap" }, { "code": null, "e": 4614, "s": 4583, "text": "Huffman Coding | Greedy Algo-3" }, { "code": null, "e": 4646, "s": 4614, "text": "Introduction to Data Structures" } ]
Shortest Superstring Problem
28 Jun, 2022 Given a set of n strings arr[], find the smallest string that contains each string in the given set as substring. We may assume that no string in arr[] is substring of another string.Examples: Input: arr[] = {"geeks", "quiz", "for"} Output: geeksquizfor Input: arr[] = {"catg", "ctaagt", "gcta", "ttca", "atgcatc"} Output: gctaagttcatgcatc Shortest Superstring Greedy Approximate Algorithm Shortest Superstring Problem is a NP Hard problem. A solution that always finds shortest superstring takes exponential time. Below is an Approximate Greedy algorithm. Let arr[] be given set of strings. 1) Create an auxiliary array of strings, temp[]. Copy contents of arr[] to temp[] 2) While temp[] contains more than one strings a) Find the most overlapping string pair in temp[]. Let this pair be 'a' and 'b'. b) Replace 'a' and 'b' with the string obtained after combining them. 3) The only string left in temp[] is the result, return it. Two strings are overlapping if prefix of one string is same suffix of other string or vice versa. The maximum overlap mean length of the matching prefix and suffix is maximum. Working of above Algorithm: arr[] = {"catgc", "ctaagt", "gcta", "ttca", "atgcatc"} Initialize: temp[] = {"catgc", "ctaagt", "gcta", "ttca", "atgcatc"} The most overlapping strings are "catgc" and "atgcatc" (Suffix of length 4 of "catgc" is same as prefix of "atgcatc") Replace two strings with "catgcatc", we get temp[] = {"catgcatc", "ctaagt", "gcta", "ttca"} The most overlapping strings are "ctaagt" and "gcta" (Prefix of length 3 of "ctaagt" is same as suffix of "gcta") Replace two strings with "gctaagt", we get temp[] = {"catgcatc", "gctaagt", "ttca"} The most overlapping strings are "catgcatc" and "ttca" (Prefix of length 2 of "catgcatc" as suffix of "ttca") Replace two strings with "ttcatgcatc", we get temp[] = {"ttcatgcatc", "gctaagt"} Now there are only two strings in temp[], after combing the two in optimal way, we get tem[] = {"gctaagttcatgcatc"} Since temp[] has only one string now, return it. Below is the implementation of the above algorithm. C++ Java C# // C++ program to find shortest// superstring using Greedy// Approximate Algorithm#include <bits/stdc++.h>using namespace std; // Utility function to calculate// minimum of two numbersint min(int a, int b){ return (a < b) ? a : b;} // Function to calculate maximum// overlap in two given stringsint findOverlappingPair(string str1, string str2, string &str){ // Max will store maximum // overlap i.e maximum // length of the matching // prefix and suffix int max = INT_MIN; int len1 = str1.length(); int len2 = str2.length(); // Check suffix of str1 matches // with prefix of str2 for (int i = 1; i <= min(len1, len2); i++) { // Compare last i characters // in str1 with first i // characters in str2 if (str1.compare(len1-i, i, str2, 0, i) == 0) { if (max < i) { // Update max and str max = i; str = str1 + str2.substr(i); } } } // Check prefix of str1 matches // with suffix of str2 for (int i = 1; i <= min(len1, len2); i++) { // compare first i characters // in str1 with last i // characters in str2 if (str1.compare(0, i, str2, len2-i, i) == 0) { if (max < i) { // Update max and str max = i; str = str2 + str1.substr(i); } } } return max;} // Function to calculate// smallest string that contains// each string in the given// set as substring.string findShortestSuperstring(string arr[], int len){ // Run len-1 times to // consider every pair while(len != 1) { // To store maximum overlap int max = INT_MIN; // To store array index of strings int l, r; // Involved in maximum overlap string resStr; // Maximum overlap for (int i = 0; i < len; i++) { for (int j = i + 1; j < len; j++) { string str; // res will store maximum // length of the matching // prefix and suffix str is // passed by reference and // will store the resultant // string after maximum // overlap of arr[i] and arr[j], // if any. int res = findOverlappingPair(arr[i], arr[j], str); // check for maximum overlap if (max < res) { max = res; resStr.assign(str); l = i, r = j; } } } // Ignore last element in next cycle len--; // If no overlap, append arr[len] to arr[0] if (max == INT_MIN) arr[0] += arr[len]; else { // Copy resultant string to index l arr[l] = resStr; // Copy string at last index to index r arr[r] = arr[len]; } } return arr[0];} // Driver programint main(){ string arr[] = {"catgc", "ctaagt", "gcta", "ttca", "atgcatc"}; int len = sizeof(arr)/sizeof(arr[0]); // Function Call cout << "The Shortest Superstring is " << findShortestSuperstring(arr, len); return 0;}// This code is contributed by Aditya Goel // Java program to find shortest// superstring using Greedy// Approximate Algorithmimport java.io.*;import java.util.*; class GFG{ static String str; // Utility function to calculate // minimum of two numbers static int min(int a, int b) { return (a < b) ? a : b; } // Function to calculate maximum // overlap in two given strings static int findOverlappingPair(String str1, String str2) { // max will store maximum // overlap i.e maximum // length of the matching // prefix and suffix int max = Integer.MIN_VALUE; int len1 = str1.length(); int len2 = str2.length(); // check suffix of str1 matches // with prefix of str2 for (int i = 1; i <= min(len1, len2); i++) { // compare last i characters // in str1 with first i // characters in str2 if (str1.substring(len1 - i).compareTo( str2.substring(0, i)) == 0) { if (max < i) { // Update max and str max = i; str = str1 + str2.substring(i); } } } // check prefix of str1 matches // with suffix of str2 for (int i = 1; i <= min(len1, len2); i++) { // compare first i characters // in str1 with last i // characters in str2 if (str1.substring(0, i).compareTo( str2.substring(len2 - i)) == 0) { if (max < i) { // update max and str max = i; str = str2 + str1.substring(i); } } } return max; } // Function to calculate smallest // string that contains // each string in the given set as substring. static String findShortestSuperstring( String arr[], int len) { // run len-1 times to consider every pair while (len != 1) { // To store maximum overlap int max = Integer.MIN_VALUE; // To store array index of strings // involved in maximum overlap int l = 0, r = 0; // to store resultant string after // maximum overlap String resStr = ""; for (int i = 0; i < len; i++) { for (int j = i + 1; j < len; j++) { // res will store maximum // length of the matching // prefix and suffix str is // passed by reference and // will store the resultant // string after maximum // overlap of arr[i] and arr[j], // if any. int res = findOverlappingPair (arr[i], arr[j]); // Check for maximum overlap if (max < res) { max = res; resStr = str; l = i; r = j; } } } // Ignore last element in next cycle len--; // If no overlap, // append arr[len] to arr[0] if (max == Integer.MIN_VALUE) arr[0] += arr[len]; else { // Copy resultant string // to index l arr[l] = resStr; // Copy string at last index // to index r arr[r] = arr[len]; } } return arr[0]; } // Driver Code public static void main(String[] args) { String[] arr = { "catgc", "ctaagt", "gcta", "ttca", "atgcatc" }; int len = arr.length; System.out.println("The Shortest Superstring is " + findShortestSuperstring(arr, len)); }} // This code is contributed by// sanjeev2552 // C# program to find shortest// superstring using Greedy// Approximate Algorithmusing System; class GFG{ static String str; // Utility function to calculate // minimum of two numbers static int min(int a, int b) { return (a < b) ? a : b; } // Function to calculate maximum // overlap in two given strings static int findOverlappingPair(String str1, String str2) { // max will store maximum // overlap i.e maximum // length of the matching // prefix and suffix int max = Int32.MinValue; int len1 = str1.Length; int len2 = str2.Length; // check suffix of str1 matches // with prefix of str2 for (int i = 1; i <= min(len1, len2); i++) { // compare last i characters // in str1 with first i // characters in str2 if (str1.Substring(len1 - i).CompareTo( str2.Substring(0, i)) == 0) { if (max < i) { // Update max and str max = i; str = str1 + str2.Substring(i); } } } // check prefix of str1 matches // with suffix of str2 for (int i = 1; i <= min(len1, len2); i++) { // compare first i characters // in str1 with last i // characters in str2 if (str1.Substring(0, i).CompareTo( str2.Substring(len2 - i)) == 0) { if (max < i) { // update max and str max = i; str = str2 + str1.Substring(i); } } } return max; } // Function to calculate smallest // string that contains // each string in the given set as substring. static String findShortestSuperstring(String []arr, int len) { // run len-1 times to consider every pair while (len != 1) { // To store maximum overlap int max = Int32.MinValue; // To store array index of strings // involved in maximum overlap int l = 0, r = 0; // to store resultant string after // maximum overlap String resStr = ""; for (int i = 0; i < len; i++) { for (int j = i + 1; j < len; j++) { // res will store maximum // length of the matching // prefix and suffix str is // passed by reference and // will store the resultant // string after maximum // overlap of arr[i] and arr[j], // if any. int res = findOverlappingPair (arr[i], arr[j]); // Check for maximum overlap if (max < res) { max = res; resStr = str; l = i; r = j; } } } // Ignore last element in next cycle len--; // If no overlap, // append arr[len] to arr[0] if (max == Int32.MinValue) arr[0] += arr[len]; else { // Copy resultant string // to index l arr[l] = resStr; // Copy string at last index // to index r arr[r] = arr[len]; } } return arr[0]; } // Driver Code public static void Main(String[] args) { String[] arr = { "catgc", "ctaagt", "gcta", "ttca", "atgcatc" }; int len = arr.Length; Console.Write("The Shortest Superstring is " + findShortestSuperstring(arr, len)); }} // This code is contributed by shivanisinghss2110 The Shortest Superstring is gctaagttcatgcatc Performance of above algorithm: The above Greedy Algorithm is proved to be 4 approximate (i.e., length of the superstring generated by this algorithm is never beyond 4 times the shortest possible superstring). This algorithm is conjectured to 2 approximate (nobody has found case where it generates more than twice the worst). Conjectured worst case example is {abk, bkc, bk+1}. For example {“abb”, “bbc”, “bbb”}, the above algorithm may generate “abbcbbb” (if “abb” and “bbc” are picked as first pair), but the actual shortest superstring is “abbbc”. Here ratio is 7/5, but for large k, ration approaches 2. Another Approach: By “greedy approach” I mean: each time we merge the two strings with a maximum length of overlap, remove them from the string array, and put the merged string into the string array. Then the problem becomes to: find the shortest path in this graph which visits every node exactly once. This is a Travelling Salesman Problem. Apply Travelling Salesman Problem DP solution. Remember to record the path. Below is the implementation of the above approach: Java // Java program for above approachimport java.io.*;import java.util.*; class Solution{ // Function to calculate shortest // super string public static String shortestSuperstring( String[] A) { int n = A.length; int[][] graph = new int[n][n]; // Build the graph for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { graph[i][j] = calc(A[i], A[j]); graph[j][i] = calc(A[j], A[i]); } } // Creating dp array int[][] dp = new int[1 << n][n]; // Creating path array int[][] path = new int[1 << n][n]; int last = -1, min = Integer.MAX_VALUE; // start TSP DP for (int i = 1; i < (1 << n); i++) { Arrays.fill(dp[i], Integer.MAX_VALUE); // Iterate j from 0 to n - 1 for (int j = 0; j < n; j++) { if ((i & (1 << j)) > 0) { int prev = i - (1 << j); // Check if prev is zero if (prev == 0) { dp[i][j] = A[j].length(); } else { // Iterate k from 0 to n - 1 for (int k = 0; k < n; k++) { if (dp[prev][k] < Integer.MAX_VALUE && dp[prev][k] + graph[k][j] < dp[i][j]) { dp[i][j] = dp[prev][k] + graph[k][j]; path[i][j] = k; } } } } if (i == (1 << n) - 1 && dp[i][j] < min) { min = dp[i][j]; last = j; } } } // Build the path StringBuilder sb = new StringBuilder(); int cur = (1 << n) - 1; // Creating a stack Stack<Integer> stack = new Stack<>(); // Until cur is zero // push last while (cur > 0) { stack.push(last); int temp = cur; cur -= (1 << last); last = path[temp][last]; } // Build the result int i = stack.pop(); sb.append(A[i]); // Until stack is empty while (!stack.isEmpty()) { int j = stack.pop(); sb.append(A[j].substring(A[j].length() - graph[i][j])); i = j; } return sb.toString(); } // Function to check public static int calc(String a, String b) { for (int i = 1; i < a.length(); i++) { if (b.startsWith(a.substring(i))) { return b.length() - a.length() + i; } } // Return size of b return b.length(); } // Driver Code public static void main(String[] args) { String[] arr = { "catgc", "ctaagt", "gcta", "ttca", "atgcatc" }; // Function Call System.out.println("The Shortest Superstring is " + shortestSuperstring(arr)); }} The Shortest Superstring is gctaagttcatgcatc Time complexity: O(n^2 * 2^n) There exist better approximate algorithms for this problem. Please refer to below link. Shortest Superstring Problem | Set 2 (Using Set Cover) Applications: Useful in the genome project since it will allow researchers to determine entire coding regions from a collection of fragmented sections. sanjeev2552 spongebobqq sagar0719kumar adnanirshad158 shivanisinghss2110 sweetyty simmytarika5 hardikkoriintern NPHard Greedy Strings Strings Greedy Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program for array rotation Write a program to print all permutations of a given string Coin Change | DP-7 Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive) Minimum Number of Platforms Required for a Railway/Bus Station Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Different Methods to Reverse a String in C++
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Jun, 2022" }, { "code": null, "e": 248, "s": 54, "text": "Given a set of n strings arr[], find the smallest string that contains each string in the given set as substring. We may assume that no string in arr[] is substring of another string.Examples: " }, { "code": null, "e": 398, "s": 248, "text": "Input: arr[] = {\"geeks\", \"quiz\", \"for\"}\nOutput: geeksquizfor\n\nInput: arr[] = {\"catg\", \"ctaagt\", \"gcta\", \"ttca\", \"atgcatc\"}\nOutput: gctaagttcatgcatc" }, { "code": null, "e": 449, "s": 398, "text": "Shortest Superstring Greedy Approximate Algorithm " }, { "code": null, "e": 617, "s": 449, "text": "Shortest Superstring Problem is a NP Hard problem. A solution that always finds shortest superstring takes exponential time. Below is an Approximate Greedy algorithm. " }, { "code": null, "e": 1027, "s": 617, "text": "Let arr[] be given set of strings.\n\n1) Create an auxiliary array of strings, temp[]. Copy contents\n of arr[] to temp[]\n\n2) While temp[] contains more than one strings\n a) Find the most overlapping string pair in temp[]. Let this\n pair be 'a' and 'b'. \n b) Replace 'a' and 'b' with the string obtained after combining\n them.\n\n3) The only string left in temp[] is the result, return it." }, { "code": null, "e": 1203, "s": 1027, "text": "Two strings are overlapping if prefix of one string is same suffix of other string or vice versa. The maximum overlap mean length of the matching prefix and suffix is maximum." }, { "code": null, "e": 1232, "s": 1203, "text": "Working of above Algorithm: " }, { "code": null, "e": 2124, "s": 1232, "text": "arr[] = {\"catgc\", \"ctaagt\", \"gcta\", \"ttca\", \"atgcatc\"}\nInitialize:\ntemp[] = {\"catgc\", \"ctaagt\", \"gcta\", \"ttca\", \"atgcatc\"}\n\nThe most overlapping strings are \"catgc\" and \"atgcatc\"\n(Suffix of length 4 of \"catgc\" is same as prefix of \"atgcatc\")\nReplace two strings with \"catgcatc\", we get\ntemp[] = {\"catgcatc\", \"ctaagt\", \"gcta\", \"ttca\"}\n\nThe most overlapping strings are \"ctaagt\" and \"gcta\"\n(Prefix of length 3 of \"ctaagt\" is same as suffix of \"gcta\")\nReplace two strings with \"gctaagt\", we get\ntemp[] = {\"catgcatc\", \"gctaagt\", \"ttca\"}\n\nThe most overlapping strings are \"catgcatc\" and \"ttca\"\n(Prefix of length 2 of \"catgcatc\" as suffix of \"ttca\")\nReplace two strings with \"ttcatgcatc\", we get\ntemp[] = {\"ttcatgcatc\", \"gctaagt\"}\n\nNow there are only two strings in temp[], after combing\nthe two in optimal way, we get tem[] = {\"gctaagttcatgcatc\"}\n\nSince temp[] has only one string now, return it." }, { "code": null, "e": 2178, "s": 2124, "text": "Below is the implementation of the above algorithm. " }, { "code": null, "e": 2182, "s": 2178, "text": "C++" }, { "code": null, "e": 2187, "s": 2182, "text": "Java" }, { "code": null, "e": 2190, "s": 2187, "text": "C#" }, { "code": "// C++ program to find shortest// superstring using Greedy// Approximate Algorithm#include <bits/stdc++.h>using namespace std; // Utility function to calculate// minimum of two numbersint min(int a, int b){ return (a < b) ? a : b;} // Function to calculate maximum// overlap in two given stringsint findOverlappingPair(string str1, string str2, string &str){ // Max will store maximum // overlap i.e maximum // length of the matching // prefix and suffix int max = INT_MIN; int len1 = str1.length(); int len2 = str2.length(); // Check suffix of str1 matches // with prefix of str2 for (int i = 1; i <= min(len1, len2); i++) { // Compare last i characters // in str1 with first i // characters in str2 if (str1.compare(len1-i, i, str2, 0, i) == 0) { if (max < i) { // Update max and str max = i; str = str1 + str2.substr(i); } } } // Check prefix of str1 matches // with suffix of str2 for (int i = 1; i <= min(len1, len2); i++) { // compare first i characters // in str1 with last i // characters in str2 if (str1.compare(0, i, str2, len2-i, i) == 0) { if (max < i) { // Update max and str max = i; str = str2 + str1.substr(i); } } } return max;} // Function to calculate// smallest string that contains// each string in the given// set as substring.string findShortestSuperstring(string arr[], int len){ // Run len-1 times to // consider every pair while(len != 1) { // To store maximum overlap int max = INT_MIN; // To store array index of strings int l, r; // Involved in maximum overlap string resStr; // Maximum overlap for (int i = 0; i < len; i++) { for (int j = i + 1; j < len; j++) { string str; // res will store maximum // length of the matching // prefix and suffix str is // passed by reference and // will store the resultant // string after maximum // overlap of arr[i] and arr[j], // if any. int res = findOverlappingPair(arr[i], arr[j], str); // check for maximum overlap if (max < res) { max = res; resStr.assign(str); l = i, r = j; } } } // Ignore last element in next cycle len--; // If no overlap, append arr[len] to arr[0] if (max == INT_MIN) arr[0] += arr[len]; else { // Copy resultant string to index l arr[l] = resStr; // Copy string at last index to index r arr[r] = arr[len]; } } return arr[0];} // Driver programint main(){ string arr[] = {\"catgc\", \"ctaagt\", \"gcta\", \"ttca\", \"atgcatc\"}; int len = sizeof(arr)/sizeof(arr[0]); // Function Call cout << \"The Shortest Superstring is \" << findShortestSuperstring(arr, len); return 0;}// This code is contributed by Aditya Goel", "e": 5841, "s": 2190, "text": null }, { "code": "// Java program to find shortest// superstring using Greedy// Approximate Algorithmimport java.io.*;import java.util.*; class GFG{ static String str; // Utility function to calculate // minimum of two numbers static int min(int a, int b) { return (a < b) ? a : b; } // Function to calculate maximum // overlap in two given strings static int findOverlappingPair(String str1, String str2) { // max will store maximum // overlap i.e maximum // length of the matching // prefix and suffix int max = Integer.MIN_VALUE; int len1 = str1.length(); int len2 = str2.length(); // check suffix of str1 matches // with prefix of str2 for (int i = 1; i <= min(len1, len2); i++) { // compare last i characters // in str1 with first i // characters in str2 if (str1.substring(len1 - i).compareTo( str2.substring(0, i)) == 0) { if (max < i) { // Update max and str max = i; str = str1 + str2.substring(i); } } } // check prefix of str1 matches // with suffix of str2 for (int i = 1; i <= min(len1, len2); i++) { // compare first i characters // in str1 with last i // characters in str2 if (str1.substring(0, i).compareTo( str2.substring(len2 - i)) == 0) { if (max < i) { // update max and str max = i; str = str2 + str1.substring(i); } } } return max; } // Function to calculate smallest // string that contains // each string in the given set as substring. static String findShortestSuperstring( String arr[], int len) { // run len-1 times to consider every pair while (len != 1) { // To store maximum overlap int max = Integer.MIN_VALUE; // To store array index of strings // involved in maximum overlap int l = 0, r = 0; // to store resultant string after // maximum overlap String resStr = \"\"; for (int i = 0; i < len; i++) { for (int j = i + 1; j < len; j++) { // res will store maximum // length of the matching // prefix and suffix str is // passed by reference and // will store the resultant // string after maximum // overlap of arr[i] and arr[j], // if any. int res = findOverlappingPair (arr[i], arr[j]); // Check for maximum overlap if (max < res) { max = res; resStr = str; l = i; r = j; } } } // Ignore last element in next cycle len--; // If no overlap, // append arr[len] to arr[0] if (max == Integer.MIN_VALUE) arr[0] += arr[len]; else { // Copy resultant string // to index l arr[l] = resStr; // Copy string at last index // to index r arr[r] = arr[len]; } } return arr[0]; } // Driver Code public static void main(String[] args) { String[] arr = { \"catgc\", \"ctaagt\", \"gcta\", \"ttca\", \"atgcatc\" }; int len = arr.length; System.out.println(\"The Shortest Superstring is \" + findShortestSuperstring(arr, len)); }} // This code is contributed by// sanjeev2552", "e": 10127, "s": 5841, "text": null }, { "code": "// C# program to find shortest// superstring using Greedy// Approximate Algorithmusing System; class GFG{ static String str; // Utility function to calculate // minimum of two numbers static int min(int a, int b) { return (a < b) ? a : b; } // Function to calculate maximum // overlap in two given strings static int findOverlappingPair(String str1, String str2) { // max will store maximum // overlap i.e maximum // length of the matching // prefix and suffix int max = Int32.MinValue; int len1 = str1.Length; int len2 = str2.Length; // check suffix of str1 matches // with prefix of str2 for (int i = 1; i <= min(len1, len2); i++) { // compare last i characters // in str1 with first i // characters in str2 if (str1.Substring(len1 - i).CompareTo( str2.Substring(0, i)) == 0) { if (max < i) { // Update max and str max = i; str = str1 + str2.Substring(i); } } } // check prefix of str1 matches // with suffix of str2 for (int i = 1; i <= min(len1, len2); i++) { // compare first i characters // in str1 with last i // characters in str2 if (str1.Substring(0, i).CompareTo( str2.Substring(len2 - i)) == 0) { if (max < i) { // update max and str max = i; str = str2 + str1.Substring(i); } } } return max; } // Function to calculate smallest // string that contains // each string in the given set as substring. static String findShortestSuperstring(String []arr, int len) { // run len-1 times to consider every pair while (len != 1) { // To store maximum overlap int max = Int32.MinValue; // To store array index of strings // involved in maximum overlap int l = 0, r = 0; // to store resultant string after // maximum overlap String resStr = \"\"; for (int i = 0; i < len; i++) { for (int j = i + 1; j < len; j++) { // res will store maximum // length of the matching // prefix and suffix str is // passed by reference and // will store the resultant // string after maximum // overlap of arr[i] and arr[j], // if any. int res = findOverlappingPair (arr[i], arr[j]); // Check for maximum overlap if (max < res) { max = res; resStr = str; l = i; r = j; } } } // Ignore last element in next cycle len--; // If no overlap, // append arr[len] to arr[0] if (max == Int32.MinValue) arr[0] += arr[len]; else { // Copy resultant string // to index l arr[l] = resStr; // Copy string at last index // to index r arr[r] = arr[len]; } } return arr[0]; } // Driver Code public static void Main(String[] args) { String[] arr = { \"catgc\", \"ctaagt\", \"gcta\", \"ttca\", \"atgcatc\" }; int len = arr.Length; Console.Write(\"The Shortest Superstring is \" + findShortestSuperstring(arr, len)); }} // This code is contributed by shivanisinghss2110", "e": 14349, "s": 10127, "text": null }, { "code": null, "e": 14394, "s": 14349, "text": "The Shortest Superstring is gctaagttcatgcatc" }, { "code": null, "e": 14427, "s": 14394, "text": "Performance of above algorithm: " }, { "code": null, "e": 15004, "s": 14427, "text": "The above Greedy Algorithm is proved to be 4 approximate (i.e., length of the superstring generated by this algorithm is never beyond 4 times the shortest possible superstring). This algorithm is conjectured to 2 approximate (nobody has found case where it generates more than twice the worst). Conjectured worst case example is {abk, bkc, bk+1}. For example {“abb”, “bbc”, “bbb”}, the above algorithm may generate “abbcbbb” (if “abb” and “bbc” are picked as first pair), but the actual shortest superstring is “abbbc”. Here ratio is 7/5, but for large k, ration approaches 2." }, { "code": null, "e": 15022, "s": 15004, "text": "Another Approach:" }, { "code": null, "e": 15204, "s": 15022, "text": "By “greedy approach” I mean: each time we merge the two strings with a maximum length of overlap, remove them from the string array, and put the merged string into the string array." }, { "code": null, "e": 15347, "s": 15204, "text": "Then the problem becomes to: find the shortest path in this graph which visits every node exactly once. This is a Travelling Salesman Problem." }, { "code": null, "e": 15423, "s": 15347, "text": "Apply Travelling Salesman Problem DP solution. Remember to record the path." }, { "code": null, "e": 15474, "s": 15423, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 15479, "s": 15474, "text": "Java" }, { "code": "// Java program for above approachimport java.io.*;import java.util.*; class Solution{ // Function to calculate shortest // super string public static String shortestSuperstring( String[] A) { int n = A.length; int[][] graph = new int[n][n]; // Build the graph for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { graph[i][j] = calc(A[i], A[j]); graph[j][i] = calc(A[j], A[i]); } } // Creating dp array int[][] dp = new int[1 << n][n]; // Creating path array int[][] path = new int[1 << n][n]; int last = -1, min = Integer.MAX_VALUE; // start TSP DP for (int i = 1; i < (1 << n); i++) { Arrays.fill(dp[i], Integer.MAX_VALUE); // Iterate j from 0 to n - 1 for (int j = 0; j < n; j++) { if ((i & (1 << j)) > 0) { int prev = i - (1 << j); // Check if prev is zero if (prev == 0) { dp[i][j] = A[j].length(); } else { // Iterate k from 0 to n - 1 for (int k = 0; k < n; k++) { if (dp[prev][k] < Integer.MAX_VALUE && dp[prev][k] + graph[k][j] < dp[i][j]) { dp[i][j] = dp[prev][k] + graph[k][j]; path[i][j] = k; } } } } if (i == (1 << n) - 1 && dp[i][j] < min) { min = dp[i][j]; last = j; } } } // Build the path StringBuilder sb = new StringBuilder(); int cur = (1 << n) - 1; // Creating a stack Stack<Integer> stack = new Stack<>(); // Until cur is zero // push last while (cur > 0) { stack.push(last); int temp = cur; cur -= (1 << last); last = path[temp][last]; } // Build the result int i = stack.pop(); sb.append(A[i]); // Until stack is empty while (!stack.isEmpty()) { int j = stack.pop(); sb.append(A[j].substring(A[j].length() - graph[i][j])); i = j; } return sb.toString(); } // Function to check public static int calc(String a, String b) { for (int i = 1; i < a.length(); i++) { if (b.startsWith(a.substring(i))) { return b.length() - a.length() + i; } } // Return size of b return b.length(); } // Driver Code public static void main(String[] args) { String[] arr = { \"catgc\", \"ctaagt\", \"gcta\", \"ttca\", \"atgcatc\" }; // Function Call System.out.println(\"The Shortest Superstring is \" + shortestSuperstring(arr)); }}", "e": 18203, "s": 15479, "text": null }, { "code": null, "e": 18248, "s": 18203, "text": "The Shortest Superstring is gctaagttcatgcatc" }, { "code": null, "e": 18278, "s": 18248, "text": "Time complexity: O(n^2 * 2^n)" }, { "code": null, "e": 18421, "s": 18278, "text": "There exist better approximate algorithms for this problem. Please refer to below link. Shortest Superstring Problem | Set 2 (Using Set Cover)" }, { "code": null, "e": 18573, "s": 18421, "text": "Applications: Useful in the genome project since it will allow researchers to determine entire coding regions from a collection of fragmented sections." }, { "code": null, "e": 18585, "s": 18573, "text": "sanjeev2552" }, { "code": null, "e": 18597, "s": 18585, "text": "spongebobqq" }, { "code": null, "e": 18612, "s": 18597, "text": "sagar0719kumar" }, { "code": null, "e": 18627, "s": 18612, "text": "adnanirshad158" }, { "code": null, "e": 18646, "s": 18627, "text": "shivanisinghss2110" }, { "code": null, "e": 18655, "s": 18646, "text": "sweetyty" }, { "code": null, "e": 18668, "s": 18655, "text": "simmytarika5" }, { "code": null, "e": 18685, "s": 18668, "text": "hardikkoriintern" }, { "code": null, "e": 18692, "s": 18685, "text": "NPHard" }, { "code": null, "e": 18699, "s": 18692, "text": "Greedy" }, { "code": null, "e": 18707, "s": 18699, "text": "Strings" }, { "code": null, "e": 18715, "s": 18707, "text": "Strings" }, { "code": null, "e": 18722, "s": 18715, "text": "Greedy" }, { "code": null, "e": 18820, "s": 18722, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 18847, "s": 18820, "text": "Program for array rotation" }, { "code": null, "e": 18907, "s": 18847, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 18926, "s": 18907, "text": "Coin Change | DP-7" }, { "code": null, "e": 19007, "s": 18926, "text": "Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)" }, { "code": null, "e": 19070, "s": 19007, "text": "Minimum Number of Platforms Required for a Railway/Bus Station" }, { "code": null, "e": 19116, "s": 19070, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 19141, "s": 19116, "text": "Reverse a string in Java" }, { "code": null, "e": 19201, "s": 19141, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 19216, "s": 19201, "text": "C++ Data Types" } ]
Different Forms of Assignment Statements in Python
10 May, 2020 We use Python assignment statements to assign objects to names. The target of an assignment statement is written on the left side of the equal sign (=), and the object on the right can be an arbitrary expression that computes an object. There are some important properties of assignment in Python :- Assignment creates object references instead of copying the objects. Python creates a variable name the first time when they are assigned a value. Names must be assigned before being referenced. There are some operations that perform assignments implicitly. Assignment statement forms :- 1. Basic form: This form is the most common form. student = 'Geeks'print(student) OUTPUT Geeks 2. Tuple assignment: # equivalent to: (x, y) = (50, 100)x, y = 50, 100 print('x = ', x)print('y = ', y) OUTPUT x = 50 y = 100 When we code a tuple on the left side of the =, Python pairs objects on the right side with targets on the left by position and assigns them from left to right. Therefore, the values of x and y are 50 and 100 respectively. 3. List assignment: This works in the same way as the tuple assignment. [x, y] = [2, 4] print('x = ', x)print('y = ', y) OUTPUT x = 2 y = 4 4. Sequence assignment: In recent version of Python, tuple and list assignment have been generalized into instances of what we now call sequence assignment – any sequence of names can be assigned to any sequence of values, and Python assigns the items one at a time by position. a, b, c = 'HEY' print('a = ', a)print('b = ', b)print('c = ', c) OUTPUT a = H b = E c = Y 5. Extended Sequence unpacking: It allows us to be more flexible in how we select portions of a sequence to assign. p, *q = 'Hello' print('p = ', p)print('q = ', q) Here, p is matched with the first character in the string on the right and q with the rest. The starred name (*q) is assigned a list, which collects all items in the sequence not assigned to other names. OUTPUT p = H q = ['e', 'l', 'l', 'o'] This is especially handy for a common coding pattern such as splitting a sequence and accessing its front and rest part. ranks = ['A', 'B', 'C', 'D']first, *rest = ranks print("Winner: ", first)print("Runner ups: ", ', '.join(rest)) OUTPUT Winner: A Runner ups: B, C, D 6. Multiple- target assignment: x = y = 75 print(x, y) In this form, Python assigns a reference to the same object (the object which is rightmost) to all the target on the left. OUTPUT 75 75 7. Augmented assignment : The augmented assignment is a shorthand assignment that combines an expression and an assignment. x = 2 # equivalent to: x = x + 1x += 1 print(x) OUTPUT 3 There are several other augmented assignment forms: -=, **=, &=, etc. python-basics 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 Iterate over a list in Python Python Classes and Objects Convert integer to string in Python Python | os.path.join() method
[ { "code": null, "e": 53, "s": 25, "text": "\n10 May, 2020" }, { "code": null, "e": 290, "s": 53, "text": "We use Python assignment statements to assign objects to names. The target of an assignment statement is written on the left side of the equal sign (=), and the object on the right can be an arbitrary expression that computes an object." }, { "code": null, "e": 353, "s": 290, "text": "There are some important properties of assignment in Python :-" }, { "code": null, "e": 422, "s": 353, "text": "Assignment creates object references instead of copying the objects." }, { "code": null, "e": 500, "s": 422, "text": "Python creates a variable name the first time when they are assigned a value." }, { "code": null, "e": 548, "s": 500, "text": "Names must be assigned before being referenced." }, { "code": null, "e": 611, "s": 548, "text": "There are some operations that perform assignments implicitly." }, { "code": null, "e": 641, "s": 611, "text": "Assignment statement forms :-" }, { "code": null, "e": 656, "s": 641, "text": "1. Basic form:" }, { "code": null, "e": 691, "s": 656, "text": "This form is the most common form." }, { "code": "student = 'Geeks'print(student)", "e": 723, "s": 691, "text": null }, { "code": null, "e": 730, "s": 723, "text": "OUTPUT" }, { "code": null, "e": 736, "s": 730, "text": "Geeks" }, { "code": null, "e": 757, "s": 736, "text": "2. Tuple assignment:" }, { "code": "# equivalent to: (x, y) = (50, 100)x, y = 50, 100 print('x = ', x)print('y = ', y)", "e": 843, "s": 757, "text": null }, { "code": null, "e": 850, "s": 843, "text": "OUTPUT" }, { "code": null, "e": 867, "s": 850, "text": "x = 50 \ny = 100\n" }, { "code": null, "e": 1090, "s": 867, "text": "When we code a tuple on the left side of the =, Python pairs objects on the right side with targets on the left by position and assigns them from left to right. Therefore, the values of x and y are 50 and 100 respectively." }, { "code": null, "e": 1110, "s": 1090, "text": "3. List assignment:" }, { "code": null, "e": 1162, "s": 1110, "text": "This works in the same way as the tuple assignment." }, { "code": "[x, y] = [2, 4] print('x = ', x)print('y = ', y)", "e": 1212, "s": 1162, "text": null }, { "code": null, "e": 1219, "s": 1212, "text": "OUTPUT" }, { "code": null, "e": 1232, "s": 1219, "text": "x = 2\ny = 4\n" }, { "code": null, "e": 1256, "s": 1232, "text": "4. Sequence assignment:" }, { "code": null, "e": 1511, "s": 1256, "text": "In recent version of Python, tuple and list assignment have been generalized into instances of what we now call sequence assignment – any sequence of names can be assigned to any sequence of values, and Python assigns the items one at a time by position." }, { "code": "a, b, c = 'HEY' print('a = ', a)print('b = ', b)print('c = ', c)", "e": 1577, "s": 1511, "text": null }, { "code": null, "e": 1584, "s": 1577, "text": "OUTPUT" }, { "code": null, "e": 1603, "s": 1584, "text": "a = H\nb = E\nc = Y\n" }, { "code": null, "e": 1635, "s": 1603, "text": "5. Extended Sequence unpacking:" }, { "code": null, "e": 1719, "s": 1635, "text": "It allows us to be more flexible in how we select portions of a sequence to assign." }, { "code": "p, *q = 'Hello' print('p = ', p)print('q = ', q)", "e": 1769, "s": 1719, "text": null }, { "code": null, "e": 1973, "s": 1769, "text": "Here, p is matched with the first character in the string on the right and q with the rest. The starred name (*q) is assigned a list, which collects all items in the sequence not assigned to other names." }, { "code": null, "e": 1980, "s": 1973, "text": "OUTPUT" }, { "code": null, "e": 2012, "s": 1980, "text": "p = H\nq = ['e', 'l', 'l', 'o']\n" }, { "code": null, "e": 2133, "s": 2012, "text": "This is especially handy for a common coding pattern such as splitting a sequence and accessing its front and rest part." }, { "code": "ranks = ['A', 'B', 'C', 'D']first, *rest = ranks print(\"Winner: \", first)print(\"Runner ups: \", ', '.join(rest))", "e": 2246, "s": 2133, "text": null }, { "code": null, "e": 2253, "s": 2246, "text": "OUTPUT" }, { "code": null, "e": 2284, "s": 2253, "text": "Winner: A\nRunner ups: B, C, D\n" }, { "code": null, "e": 2316, "s": 2284, "text": "6. Multiple- target assignment:" }, { "code": "x = y = 75 print(x, y)", "e": 2340, "s": 2316, "text": null }, { "code": null, "e": 2463, "s": 2340, "text": "In this form, Python assigns a reference to the same object (the object which is rightmost) to all the target on the left." }, { "code": null, "e": 2470, "s": 2463, "text": "OUTPUT" }, { "code": null, "e": 2477, "s": 2470, "text": "75 75\n" }, { "code": null, "e": 2503, "s": 2477, "text": "7. Augmented assignment :" }, { "code": null, "e": 2601, "s": 2503, "text": "The augmented assignment is a shorthand assignment that combines an expression and an assignment." }, { "code": "x = 2 # equivalent to: x = x + 1x += 1 print(x)", "e": 2653, "s": 2601, "text": null }, { "code": null, "e": 2660, "s": 2653, "text": "OUTPUT" }, { "code": null, "e": 2663, "s": 2660, "text": "3\n" }, { "code": null, "e": 2715, "s": 2663, "text": "There are several other augmented assignment forms:" }, { "code": null, "e": 2733, "s": 2715, "text": "-=, **=, &=, etc." }, { "code": null, "e": 2747, "s": 2733, "text": "python-basics" }, { "code": null, "e": 2754, "s": 2747, "text": "Python" }, { "code": null, "e": 2852, "s": 2754, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2894, "s": 2852, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2916, "s": 2894, "text": "Enumerate() in Python" }, { "code": null, "e": 2951, "s": 2916, "text": "Read a file line by line in Python" }, { "code": null, "e": 2977, "s": 2951, "text": "Python String | replace()" }, { "code": null, "e": 3009, "s": 2977, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3038, "s": 3009, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3068, "s": 3038, "text": "Iterate over a list in Python" }, { "code": null, "e": 3095, "s": 3068, "text": "Python Classes and Objects" }, { "code": null, "e": 3131, "s": 3095, "text": "Convert integer to string in Python" } ]
Efficiency of Stop and Wait Protocol
22 Jun, 2022 Stop and Wait is a flow control protocol. In which the sender sends one packet and waits for the receiver to acknowledge and then it will send the next packet. In case if the acknowledgement is not received, the sender will retransmit the packet. This is the simplest one and easy to implement. but the main disadvantage is the efficiency is very low. Total time taken to send one packet, = Tt(data) + Tp(data) + Tq + Tpro + Tt(ack) + Tp(ack) Since, Tp(ack) = Tp(data) And, Tt(ack) << Tt(data). So we can neglect Tt(ack) Tq = 0 and Tpro = 0 Hence, Total time = Tt(data) + 2 * Tp Where, Tt(data) : Transmission delay for Data packet Tp(data) : propagation delay for Data packet Tq: Queuing delay Tpro: Processing delay Tt(ack): Transmission delay for acknowledgment Tp(ack) : Propagation delay for acknowledgment We know that the Efficiency (η), = Useful time / Total cycle time. = Tt / (Tt + 2*Tp) = 1 / (1+2*(Tp/Tt)) = 1 / (1+2*a) where, a = Tp / Tt Throughput: Number of bits send per second, which is also known as Effective Bandwidth or Bandwidth utilization. Throughput, = L/(Tt + 2*Tp) = ((L/BW)*BW)/(Tt + 2*Tp) = Tt/(Tt + 2*Tp) * BW = 1/(1 + 2a) * BW Hence, Throughput = η * BW where, BW : BandWidth L : Size of Data packet Factors affecting Efficiency: n = 1/(1 + 2*(Tp/Tt) = 1/(1 + 2*(d/v)*(BW/L)) where, d = distance between source and receiver v = velocity Lets see an example. Example: Given, Tt = 1ms Tp = 2ms Bandwidth = 6 Mbps Efficiency(η) = 1/(1 + 2*a) = 1/(1 + 2*(2/1)) = 1/5 = 20 % Throughput = η * BW = (1/5) * 6 = 1.2 Mbps Note: As we can observe from the above given formula of Efficiency that: On increasing the distance between source and receiver the Efficiency will decrease. Hence, Stop and Wait is only suitable for small area network like LAN. It is not suitable for MAN or WAN, as the efficiency will be very low.If we increase the size of the Data packet, the efficiency is going to increase. Hence, it is suitable not for small packets. Big data packets can be send by Stop and Wait efficiently. On increasing the distance between source and receiver the Efficiency will decrease. Hence, Stop and Wait is only suitable for small area network like LAN. It is not suitable for MAN or WAN, as the efficiency will be very low. If we increase the size of the Data packet, the efficiency is going to increase. Hence, it is suitable not for small packets. Big data packets can be send by Stop and Wait efficiently. arifhbd120 pall58183 Computer Networks GATE CS Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Differences between TCP and UDP Types of Network Topology RSA Algorithm in Cryptography TCP Server-Client implementation in C GSM in Wireless Communication ACID Properties in DBMS Types of Operating Systems Normal Forms in DBMS Page Replacement Algorithms in Operating Systems Inter Process Communication (IPC)
[ { "code": null, "e": 54, "s": 26, "text": "\n22 Jun, 2022" }, { "code": null, "e": 444, "s": 54, "text": "Stop and Wait is a flow control protocol. In which the sender sends one packet and waits for the receiver to acknowledge and then it will send the next packet. In case if the acknowledgement is not received, the sender will retransmit the packet. This is the simplest one and easy to implement. but the main disadvantage is the efficiency is very low. Total time taken to send one packet," }, { "code": null, "e": 640, "s": 444, "text": "= Tt(data) + Tp(data) + Tq + Tpro + Tt(ack) + Tp(ack)\n\nSince,\nTp(ack) = Tp(data)\n\nAnd,\nTt(ack) << Tt(data).\n\nSo we can neglect Tt(ack)\nTq = 0 and Tpro = 0\n\nHence, \nTotal time = Tt(data) + 2 * Tp " }, { "code": null, "e": 647, "s": 640, "text": "Where," }, { "code": null, "e": 874, "s": 647, "text": "Tt(data) : Transmission delay for Data packet\nTp(data) : propagation delay for Data packet\nTq: Queuing delay\nTpro: Processing delay\nTt(ack): Transmission delay for acknowledgment\nTp(ack) : Propagation delay for acknowledgment " }, { "code": null, "e": 907, "s": 874, "text": "We know that the Efficiency (η)," }, { "code": null, "e": 1017, "s": 907, "text": "= Useful time / Total cycle time.\n= Tt / (Tt + 2*Tp)\n= 1 / (1+2*(Tp/Tt))\n= 1 / (1+2*a) \n\nwhere, \na = Tp / Tt " }, { "code": null, "e": 1130, "s": 1017, "text": "Throughput: Number of bits send per second, which is also known as Effective Bandwidth or Bandwidth utilization." }, { "code": null, "e": 1302, "s": 1130, "text": "Throughput, \n= L/(Tt + 2*Tp)\n= ((L/BW)*BW)/(Tt + 2*Tp)\n= Tt/(Tt + 2*Tp) * BW\n= 1/(1 + 2a) * BW\n\nHence, Throughput \n= η * BW\n\nwhere,\nBW : BandWidth\nL : Size of Data packet " }, { "code": null, "e": 1332, "s": 1302, "text": "Factors affecting Efficiency:" }, { "code": null, "e": 1442, "s": 1332, "text": "n = 1/(1 + 2*(Tp/Tt)\n= 1/(1 + 2*(d/v)*(BW/L))\n\nwhere,\nd = distance between source and receiver \nv = velocity " }, { "code": null, "e": 1479, "s": 1442, "text": "Lets see an example. Example: Given," }, { "code": null, "e": 1633, "s": 1479, "text": "Tt = 1ms \nTp = 2ms \nBandwidth = 6 Mbps\n\nEfficiency(η) \n= 1/(1 + 2*a)\n= 1/(1 + 2*(2/1))\n= 1/5 \n= 20 %\n\nThroughput \n= η * BW\n= (1/5) * 6 \n= 1.2 Mbps " }, { "code": null, "e": 1706, "s": 1633, "text": "Note: As we can observe from the above given formula of Efficiency that:" }, { "code": null, "e": 2117, "s": 1706, "text": "On increasing the distance between source and receiver the Efficiency will decrease. Hence, Stop and Wait is only suitable for small area network like LAN. It is not suitable for MAN or WAN, as the efficiency will be very low.If we increase the size of the Data packet, the efficiency is going to increase. Hence, it is suitable not for small packets. Big data packets can be send by Stop and Wait efficiently." }, { "code": null, "e": 2344, "s": 2117, "text": "On increasing the distance between source and receiver the Efficiency will decrease. Hence, Stop and Wait is only suitable for small area network like LAN. It is not suitable for MAN or WAN, as the efficiency will be very low." }, { "code": null, "e": 2529, "s": 2344, "text": "If we increase the size of the Data packet, the efficiency is going to increase. Hence, it is suitable not for small packets. Big data packets can be send by Stop and Wait efficiently." }, { "code": null, "e": 2540, "s": 2529, "text": "arifhbd120" }, { "code": null, "e": 2550, "s": 2540, "text": "pall58183" }, { "code": null, "e": 2568, "s": 2550, "text": "Computer Networks" }, { "code": null, "e": 2576, "s": 2568, "text": "GATE CS" }, { "code": null, "e": 2594, "s": 2576, "text": "Computer Networks" }, { "code": null, "e": 2692, "s": 2594, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2724, "s": 2692, "text": "Differences between TCP and UDP" }, { "code": null, "e": 2750, "s": 2724, "text": "Types of Network Topology" }, { "code": null, "e": 2780, "s": 2750, "text": "RSA Algorithm in Cryptography" }, { "code": null, "e": 2818, "s": 2780, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 2848, "s": 2818, "text": "GSM in Wireless Communication" }, { "code": null, "e": 2872, "s": 2848, "text": "ACID Properties in DBMS" }, { "code": null, "e": 2899, "s": 2872, "text": "Types of Operating Systems" }, { "code": null, "e": 2920, "s": 2899, "text": "Normal Forms in DBMS" }, { "code": null, "e": 2969, "s": 2920, "text": "Page Replacement Algorithms in Operating Systems" } ]
Python – Stock Data Visualisation
17 May, 2020 Python is a great language for making data-based analysis and visualizations. It also helps that there is a wide range of open-source libraries that can be used off the shelf for some great functionalities.Python Dash is a library that allows you to build web dashboards and data visualizations without the hassle of complex front end HTML, CSS or JavaScript.In this article, we will be learning to build a Stock data dashboard using Python Dash, Pandas and Yahoo’s Finance API. Installation:Install the latest version of Pandas Datareader pip install pandas_datareader Install the latest version of Dash pip install dash Implementation:Import all the required libraries # importing required librariesimport datetimeimport pandas_datareader.data as webimport dashimport dash_core_components as dcc import dash_html_components as htmlfrom dash.dependencies import Input, Output Now let’s make a user interface using dash. We are going to make a simple yet functional user interface, one will be a simple Heading title and a input textbox for the user to type in the stock names. # UIapp = dash.Dash()app.title = "Stock Visualisation"app.layout = html.Div(children =[ html.H1("Stock Visualisation Dashboard"), html.H4("Please enter the stock name"), dcc.Input(id ='input', value ='', type ='text'), html.Div(id ='output-graph')]) The input text box is now just a static text box. To get the input data, which in this case is the stock name of a company, from the user interface, we should add app callbacks. The read stock name(input_data) is passed as a parameter to the method update_value. The function then gets all the stock data from the Yahoo Finance API since 1st January 2010 till now, the current day and is store in a Pandas data frame. A graph is plotted, with the X-axis being the index of the data frame, which is time in years, Y-axis with the closing stock price of each day and the name of the graph being the stock name(input_data). This graph is returned to the callback wrapper which then displays it on the user interface.Code: def update_value(input_data): # Reads stock prices from 1st January 2010 start = datetime.datetime(2010, 1, 1) end = datetime.datetime.now() # Read stock data from yahoo's finance API from start to end df = web.DataReader(input_data, 'yahoo', start, end) return dcc.Graph(id ="example", figure ={ 'data':[{'x':df.index, 'y':df.Close, 'type':'line', 'name':input_data}, ], 'layout':{ 'title':input_data } } ) Code: Finally, run the server. if __name__ == '__main__': app.run_server() Execution:The web application will now run on the local host at 8050 by default. 127.0.0.1:8050 Example:Let’s consider an example. The stock name of Google is GOOGL. Let’s enter this data into the input text box.Below is the result. Screenshot of Google’s Stock Data data-science Machine Learning Python Python Programs Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Linear Regression Search Algorithms in AI Getting started with Machine Learning Introduction to Recurrent Neural Network Support Vector Machine Algorithm Read JSON file using Python Python map() function Adding new column to existing DataFrame in Pandas Python Dictionary How to get column names in Pandas dataframe
[ { "code": null, "e": 54, "s": 26, "text": "\n17 May, 2020" }, { "code": null, "e": 533, "s": 54, "text": "Python is a great language for making data-based analysis and visualizations. It also helps that there is a wide range of open-source libraries that can be used off the shelf for some great functionalities.Python Dash is a library that allows you to build web dashboards and data visualizations without the hassle of complex front end HTML, CSS or JavaScript.In this article, we will be learning to build a Stock data dashboard using Python Dash, Pandas and Yahoo’s Finance API." }, { "code": null, "e": 594, "s": 533, "text": "Installation:Install the latest version of Pandas Datareader" }, { "code": null, "e": 625, "s": 594, "text": "pip install pandas_datareader\n" }, { "code": null, "e": 660, "s": 625, "text": "Install the latest version of Dash" }, { "code": null, "e": 678, "s": 660, "text": "pip install dash\n" }, { "code": null, "e": 727, "s": 678, "text": "Implementation:Import all the required libraries" }, { "code": "# importing required librariesimport datetimeimport pandas_datareader.data as webimport dashimport dash_core_components as dcc import dash_html_components as htmlfrom dash.dependencies import Input, Output ", "e": 937, "s": 727, "text": null }, { "code": null, "e": 1138, "s": 937, "text": "Now let’s make a user interface using dash. We are going to make a simple yet functional user interface, one will be a simple Heading title and a input textbox for the user to type in the stock names." }, { "code": "# UIapp = dash.Dash()app.title = \"Stock Visualisation\"app.layout = html.Div(children =[ html.H1(\"Stock Visualisation Dashboard\"), html.H4(\"Please enter the stock name\"), dcc.Input(id ='input', value ='', type ='text'), html.Div(id ='output-graph')])", "e": 1410, "s": 1138, "text": null }, { "code": null, "e": 2129, "s": 1410, "text": "The input text box is now just a static text box. To get the input data, which in this case is the stock name of a company, from the user interface, we should add app callbacks. The read stock name(input_data) is passed as a parameter to the method update_value. The function then gets all the stock data from the Yahoo Finance API since 1st January 2010 till now, the current day and is store in a Pandas data frame. A graph is plotted, with the X-axis being the index of the data frame, which is time in years, Y-axis with the closing stock price of each day and the name of the graph being the stock name(input_data). This graph is returned to the callback wrapper which then displays it on the user interface.Code:" }, { "code": "def update_value(input_data): # Reads stock prices from 1st January 2010 start = datetime.datetime(2010, 1, 1) end = datetime.datetime.now() # Read stock data from yahoo's finance API from start to end df = web.DataReader(input_data, 'yahoo', start, end) return dcc.Graph(id =\"example\", figure ={ 'data':[{'x':df.index, 'y':df.Close, 'type':'line', 'name':input_data}, ], 'layout':{ 'title':input_data } } )", "e": 2643, "s": 2129, "text": null }, { "code": null, "e": 2674, "s": 2643, "text": "Code: Finally, run the server." }, { "code": "if __name__ == '__main__': app.run_server()", "e": 2721, "s": 2674, "text": null }, { "code": null, "e": 2802, "s": 2721, "text": "Execution:The web application will now run on the local host at 8050 by default." }, { "code": null, "e": 2818, "s": 2802, "text": "127.0.0.1:8050\n" }, { "code": null, "e": 2955, "s": 2818, "text": "Example:Let’s consider an example. The stock name of Google is GOOGL. Let’s enter this data into the input text box.Below is the result." }, { "code": null, "e": 2989, "s": 2955, "text": "Screenshot of Google’s Stock Data" }, { "code": null, "e": 3002, "s": 2989, "text": "data-science" }, { "code": null, "e": 3019, "s": 3002, "text": "Machine Learning" }, { "code": null, "e": 3026, "s": 3019, "text": "Python" }, { "code": null, "e": 3042, "s": 3026, "text": "Python Programs" }, { "code": null, "e": 3059, "s": 3042, "text": "Machine Learning" }, { "code": null, "e": 3157, "s": 3059, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3180, "s": 3157, "text": "ML | Linear Regression" }, { "code": null, "e": 3204, "s": 3180, "text": "Search Algorithms in AI" }, { "code": null, "e": 3242, "s": 3204, "text": "Getting started with Machine Learning" }, { "code": null, "e": 3283, "s": 3242, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 3316, "s": 3283, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 3344, "s": 3316, "text": "Read JSON file using Python" }, { "code": null, "e": 3366, "s": 3344, "text": "Python map() function" }, { "code": null, "e": 3416, "s": 3366, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 3434, "s": 3416, "text": "Python Dictionary" } ]
Runtime Polymorphism in various types of Inheritance in C++
16 Apr, 2020 C++ allows users to use the concept of Run-Time Polymorphism using Virtual Functions for any type of Inheritance . Below is how to implement Run-Time Polymorphism in all types of inheritance: Single Inheritance:// C++ program to demonstrate Run Time// Polymorphism in Single Inheritance #include <iostream>using namespace std; // Base Classclass Base { public: // Virtual function virtual void funct1() { cout << "Base::funct1() is called\n"; } // Virtual function virtual void funct2(int x) { cout << "Base's Val of x:" << x << endl; } // Non-Virtual Function void funct3() { cout << "Base is the Parent class!" << endl; }}; // Derived Class or Sub Classclass Derived : public Base {private: // Virtual Functions // can also be Private! void funct1() { cout << "Derived::funct1() is called\n"; } void funct2(int x) { cout << "Derived Class's Val of x:" << x << endl; } void funct3() { cout << "It's the Derived class's" << " funct3() called!" << endl; }}; int main(){ // Run-Time Polymorphism // in Single Inheritance Base* bptr = new Derived(); // virtual function bptr->funct1(); // virtual function bptr->funct2(12); // Non-virtual function bptr->funct3(); return 0;}Output:Derived::funct1() is called Derived Class's Val of x:12 Base is the Parent class! Multiple Inheritance:#include <iostream>using namespace std; // Parent to Derived classclass Base1 {public: // Non-Virtual function void funct1() { cout << "Base1::funct1() is called\n"; } // Virtual function virtual void funct2(int x) { cout << "Base1's Val of x:" << x << endl; } // Non-Virtual Function void funct3() { cout << "Base1 is the Parent class!" << endl; }}; // Second Parent to Derived classclass Base2 {public: void funct1() { cout << "Base2::funct1() is called\n"; } void funct2(int x) { cout << "Base2's Val of x:" << x << endl; } // Only Virtual Function // in Base2 Parent class virtual void funct3() { cout << "Base2 is Also a Parent class!" << endl; }}; // Derived Class of Base1 and Base2class Derived : public Base1, public Base2 {private: void funct1() { cout << "Derived::funct1() is called\n"; } void funct2(int x) { cout << "Derived Class's Val of x:" << x << endl; } void funct3() { cout << "Derived::funct3() is called " << "and not Base2::funct3() due" << " to RTP" << endl; }}; int main(){ Derived d; // Run-Time Polymorphism // in Multiple Inheritance Base1* b1ptr = &d; // Compile-Time Binding, // Hence Base1::funct1() will be called! b1ptr->funct1(); // virtual function of Base1 // RunTime PolyMorphism b1ptr->funct2(10); // Now Parent Class Base2 // is also pointed to object 'd' // of Derived (to demonstrate RTP) Base2* b2ptr = &d; // virtual function of Base2 // RunTime PolyMorphism b2ptr->funct3(); return 0;}Output:Base1::funct1() is called Derived Class's Val of x:10 Derived::funct3() is called and not Base2::funct3() due to RTP Note: Here Both Base1 pointer and Base2 pointer may be pointing to the same Derived Class object ‘d’ but actually the Compiler selects difference Virtual Functions during Run-Time due to the use of different Base Class pointers.Multi-level inheritance:// C++ Program to illustrate Run-Time// Polymorphism in multi-level inheritance #include <iostream>using namespace std; // Parent Classclass Base1 {public: // Virtual function virtual void funct1() { cout << "Base1::funct1() is called\n"; } // Virtual function virtual void funct2(int x) { cout << "Base1's Val of x:" << x << endl; } // Non-Virtual Function void funct3() { cout << "Base1 is the Parent class!" << endl; }}; // Derived Class of Base1// but Parent to Base3class Base2 : public Base1 { // Virtual Functions can be Private!private: void funct1() { cout << "Base2::funct1() is called\n"; } void funct2(int x) { cout << "Base2's Val of x:" << x << endl; } void funct3() { cout << "Base2 is the first " << "Derived class!" << endl; }}; // Derived Class of Base2// but Parent to Derivedclass Base3 : public Base2 {private: void funct1() { cout << "Base3::funct1() is called\n"; } void funct2(int x) { cout << "Base3's Val of x:" << x << endl; } void funct3() { cout << "Class Base3 is second " << "Derived class!" << endl; }}; // 3 Levels of Multi-Level Inheritance// and final Child Classclass Derived : public Base3 {private: void funct1() { cout << "Derived::funct1() is called\n"; } void funct2(int x) { cout << "Derived Class's Val of x:" << x << endl; } void funct3() { cout << "Class Derived is Final" << " Child class!" << endl; }}; int main(){ // Run-Time Polymorphism // in multi-level Inheritance Base1* b1ptr = new Derived; b1ptr->funct1(); b1ptr->funct2(30); // Compile-Time Binding b1ptr->funct3(); return 0;}Output:Derived::funct1() is called Derived Class's Val of x:30 Base1 is the Parent class! Explanation : In the above Example, the Derived class is the final Child class which inherits from Base3 which inherits from Base2 which again finally inherits from the Base1 (Parent Class to Base2). But if you see the Run-Time Polymorphism works even when you are trying to use Virtual Functions in Base1 Class and point its pointer to Derived Class (Which is the great grand-Child of Base1). Hence, even here Run-Time Polymorphism works according to the standard Rules.Hierarchical inheritance:// C++ Program to illustrate Run-Time// Polymorphism in Hierarchical inheritance #include <iostream>using namespace std; class Base1 {public: // Virtual function of Parent Class virtual void funct1() { cout << "Base1::funct1() is called\n"; } virtual void funct2(int x) { cout << "Base1's Val of x:" << x << endl; } // Non-Virtual Function void funct3() { cout << "Base1 is the Parent class!" << endl; }}; class Base2 : public Base1 {private: void funct1() { cout << "Base2::funct1() is called\n"; } void funct2(int x) { cout << "Base2's Val of x:" << x << endl; } void funct3() { cout << "Base2 is the first" << " Derived class!" << endl; }}; class Base3 : public Base1 {private: void funct1() { cout << "Base3::funct1() is called\n"; } void funct2(int x) { cout << "Base3's Val of x:" << x << endl; } void funct3() { cout << "Class Base3 is second" << " Derived class!" << endl; }}; // Grand-Child_1 of Base1 classclass Derived1 : public Base3 {private: void funct1() { cout << "Derived1::funct1() is called\n"; } void funct2(int x) { cout << "Derived1 Class's Val of x:" << x << endl; } void funct3() { cout << "Class Derived1 is Good!!" << endl; }}; // Grand-Child_2 of Base1 classclass Derived2 : public Base3 {private: void funct1() { cout << "Derived2::funct1()" << " is called\n"; } void funct2(int x) { cout << "Derived2 Class's Val " << "of x:" << x << endl; } void funct3() { cout << "Class Derived2 is Good!!" << endl; }}; // Run-Time Polymorphism// in Hierarchical Inheritanceint main(){ // Base1 class's(Parent class's) // pointer points to Derived1 class Base1* b1ptr = new Derived1(); // Run-Time Polymorphism b1ptr->funct1(); Derived2 d2; // Now the Base1 class pointer // points to d2 object(Derived2 class) b1ptr = &d2; // Run-Time Polymorphism b1ptr->funct2(30); // Compile-Time Binding b1ptr->funct3(); return 0;}Output:Derived1::funct1() is called Derived2 Class's Val of x:30 Base1 is the Parent class! Explanation: Here, the Parent is Base1 and its Grand-children are Derived1 Class and Derived2 class. Even in this case, When the Base1 Class pointer is pointed to Derived1 object or Derived2 object, due to the Virtual Functions (‘VPTR’ and ‘VTABLE’), we can apply Run-Time Polymorphism here. Single Inheritance:// C++ program to demonstrate Run Time// Polymorphism in Single Inheritance #include <iostream>using namespace std; // Base Classclass Base { public: // Virtual function virtual void funct1() { cout << "Base::funct1() is called\n"; } // Virtual function virtual void funct2(int x) { cout << "Base's Val of x:" << x << endl; } // Non-Virtual Function void funct3() { cout << "Base is the Parent class!" << endl; }}; // Derived Class or Sub Classclass Derived : public Base {private: // Virtual Functions // can also be Private! void funct1() { cout << "Derived::funct1() is called\n"; } void funct2(int x) { cout << "Derived Class's Val of x:" << x << endl; } void funct3() { cout << "It's the Derived class's" << " funct3() called!" << endl; }}; int main(){ // Run-Time Polymorphism // in Single Inheritance Base* bptr = new Derived(); // virtual function bptr->funct1(); // virtual function bptr->funct2(12); // Non-virtual function bptr->funct3(); return 0;}Output:Derived::funct1() is called Derived Class's Val of x:12 Base is the Parent class! // C++ program to demonstrate Run Time// Polymorphism in Single Inheritance #include <iostream>using namespace std; // Base Classclass Base { public: // Virtual function virtual void funct1() { cout << "Base::funct1() is called\n"; } // Virtual function virtual void funct2(int x) { cout << "Base's Val of x:" << x << endl; } // Non-Virtual Function void funct3() { cout << "Base is the Parent class!" << endl; }}; // Derived Class or Sub Classclass Derived : public Base {private: // Virtual Functions // can also be Private! void funct1() { cout << "Derived::funct1() is called\n"; } void funct2(int x) { cout << "Derived Class's Val of x:" << x << endl; } void funct3() { cout << "It's the Derived class's" << " funct3() called!" << endl; }}; int main(){ // Run-Time Polymorphism // in Single Inheritance Base* bptr = new Derived(); // virtual function bptr->funct1(); // virtual function bptr->funct2(12); // Non-virtual function bptr->funct3(); return 0;} Derived::funct1() is called Derived Class's Val of x:12 Base is the Parent class! Multiple Inheritance:#include <iostream>using namespace std; // Parent to Derived classclass Base1 {public: // Non-Virtual function void funct1() { cout << "Base1::funct1() is called\n"; } // Virtual function virtual void funct2(int x) { cout << "Base1's Val of x:" << x << endl; } // Non-Virtual Function void funct3() { cout << "Base1 is the Parent class!" << endl; }}; // Second Parent to Derived classclass Base2 {public: void funct1() { cout << "Base2::funct1() is called\n"; } void funct2(int x) { cout << "Base2's Val of x:" << x << endl; } // Only Virtual Function // in Base2 Parent class virtual void funct3() { cout << "Base2 is Also a Parent class!" << endl; }}; // Derived Class of Base1 and Base2class Derived : public Base1, public Base2 {private: void funct1() { cout << "Derived::funct1() is called\n"; } void funct2(int x) { cout << "Derived Class's Val of x:" << x << endl; } void funct3() { cout << "Derived::funct3() is called " << "and not Base2::funct3() due" << " to RTP" << endl; }}; int main(){ Derived d; // Run-Time Polymorphism // in Multiple Inheritance Base1* b1ptr = &d; // Compile-Time Binding, // Hence Base1::funct1() will be called! b1ptr->funct1(); // virtual function of Base1 // RunTime PolyMorphism b1ptr->funct2(10); // Now Parent Class Base2 // is also pointed to object 'd' // of Derived (to demonstrate RTP) Base2* b2ptr = &d; // virtual function of Base2 // RunTime PolyMorphism b2ptr->funct3(); return 0;}Output:Base1::funct1() is called Derived Class's Val of x:10 Derived::funct3() is called and not Base2::funct3() due to RTP Note: Here Both Base1 pointer and Base2 pointer may be pointing to the same Derived Class object ‘d’ but actually the Compiler selects difference Virtual Functions during Run-Time due to the use of different Base Class pointers. #include <iostream>using namespace std; // Parent to Derived classclass Base1 {public: // Non-Virtual function void funct1() { cout << "Base1::funct1() is called\n"; } // Virtual function virtual void funct2(int x) { cout << "Base1's Val of x:" << x << endl; } // Non-Virtual Function void funct3() { cout << "Base1 is the Parent class!" << endl; }}; // Second Parent to Derived classclass Base2 {public: void funct1() { cout << "Base2::funct1() is called\n"; } void funct2(int x) { cout << "Base2's Val of x:" << x << endl; } // Only Virtual Function // in Base2 Parent class virtual void funct3() { cout << "Base2 is Also a Parent class!" << endl; }}; // Derived Class of Base1 and Base2class Derived : public Base1, public Base2 {private: void funct1() { cout << "Derived::funct1() is called\n"; } void funct2(int x) { cout << "Derived Class's Val of x:" << x << endl; } void funct3() { cout << "Derived::funct3() is called " << "and not Base2::funct3() due" << " to RTP" << endl; }}; int main(){ Derived d; // Run-Time Polymorphism // in Multiple Inheritance Base1* b1ptr = &d; // Compile-Time Binding, // Hence Base1::funct1() will be called! b1ptr->funct1(); // virtual function of Base1 // RunTime PolyMorphism b1ptr->funct2(10); // Now Parent Class Base2 // is also pointed to object 'd' // of Derived (to demonstrate RTP) Base2* b2ptr = &d; // virtual function of Base2 // RunTime PolyMorphism b2ptr->funct3(); return 0;} Base1::funct1() is called Derived Class's Val of x:10 Derived::funct3() is called and not Base2::funct3() due to RTP Note: Here Both Base1 pointer and Base2 pointer may be pointing to the same Derived Class object ‘d’ but actually the Compiler selects difference Virtual Functions during Run-Time due to the use of different Base Class pointers. Multi-level inheritance:// C++ Program to illustrate Run-Time// Polymorphism in multi-level inheritance #include <iostream>using namespace std; // Parent Classclass Base1 {public: // Virtual function virtual void funct1() { cout << "Base1::funct1() is called\n"; } // Virtual function virtual void funct2(int x) { cout << "Base1's Val of x:" << x << endl; } // Non-Virtual Function void funct3() { cout << "Base1 is the Parent class!" << endl; }}; // Derived Class of Base1// but Parent to Base3class Base2 : public Base1 { // Virtual Functions can be Private!private: void funct1() { cout << "Base2::funct1() is called\n"; } void funct2(int x) { cout << "Base2's Val of x:" << x << endl; } void funct3() { cout << "Base2 is the first " << "Derived class!" << endl; }}; // Derived Class of Base2// but Parent to Derivedclass Base3 : public Base2 {private: void funct1() { cout << "Base3::funct1() is called\n"; } void funct2(int x) { cout << "Base3's Val of x:" << x << endl; } void funct3() { cout << "Class Base3 is second " << "Derived class!" << endl; }}; // 3 Levels of Multi-Level Inheritance// and final Child Classclass Derived : public Base3 {private: void funct1() { cout << "Derived::funct1() is called\n"; } void funct2(int x) { cout << "Derived Class's Val of x:" << x << endl; } void funct3() { cout << "Class Derived is Final" << " Child class!" << endl; }}; int main(){ // Run-Time Polymorphism // in multi-level Inheritance Base1* b1ptr = new Derived; b1ptr->funct1(); b1ptr->funct2(30); // Compile-Time Binding b1ptr->funct3(); return 0;}Output:Derived::funct1() is called Derived Class's Val of x:30 Base1 is the Parent class! Explanation : In the above Example, the Derived class is the final Child class which inherits from Base3 which inherits from Base2 which again finally inherits from the Base1 (Parent Class to Base2). But if you see the Run-Time Polymorphism works even when you are trying to use Virtual Functions in Base1 Class and point its pointer to Derived Class (Which is the great grand-Child of Base1). Hence, even here Run-Time Polymorphism works according to the standard Rules. // C++ Program to illustrate Run-Time// Polymorphism in multi-level inheritance #include <iostream>using namespace std; // Parent Classclass Base1 {public: // Virtual function virtual void funct1() { cout << "Base1::funct1() is called\n"; } // Virtual function virtual void funct2(int x) { cout << "Base1's Val of x:" << x << endl; } // Non-Virtual Function void funct3() { cout << "Base1 is the Parent class!" << endl; }}; // Derived Class of Base1// but Parent to Base3class Base2 : public Base1 { // Virtual Functions can be Private!private: void funct1() { cout << "Base2::funct1() is called\n"; } void funct2(int x) { cout << "Base2's Val of x:" << x << endl; } void funct3() { cout << "Base2 is the first " << "Derived class!" << endl; }}; // Derived Class of Base2// but Parent to Derivedclass Base3 : public Base2 {private: void funct1() { cout << "Base3::funct1() is called\n"; } void funct2(int x) { cout << "Base3's Val of x:" << x << endl; } void funct3() { cout << "Class Base3 is second " << "Derived class!" << endl; }}; // 3 Levels of Multi-Level Inheritance// and final Child Classclass Derived : public Base3 {private: void funct1() { cout << "Derived::funct1() is called\n"; } void funct2(int x) { cout << "Derived Class's Val of x:" << x << endl; } void funct3() { cout << "Class Derived is Final" << " Child class!" << endl; }}; int main(){ // Run-Time Polymorphism // in multi-level Inheritance Base1* b1ptr = new Derived; b1ptr->funct1(); b1ptr->funct2(30); // Compile-Time Binding b1ptr->funct3(); return 0;} Derived::funct1() is called Derived Class's Val of x:30 Base1 is the Parent class! Explanation : In the above Example, the Derived class is the final Child class which inherits from Base3 which inherits from Base2 which again finally inherits from the Base1 (Parent Class to Base2). But if you see the Run-Time Polymorphism works even when you are trying to use Virtual Functions in Base1 Class and point its pointer to Derived Class (Which is the great grand-Child of Base1). Hence, even here Run-Time Polymorphism works according to the standard Rules. Hierarchical inheritance:// C++ Program to illustrate Run-Time// Polymorphism in Hierarchical inheritance #include <iostream>using namespace std; class Base1 {public: // Virtual function of Parent Class virtual void funct1() { cout << "Base1::funct1() is called\n"; } virtual void funct2(int x) { cout << "Base1's Val of x:" << x << endl; } // Non-Virtual Function void funct3() { cout << "Base1 is the Parent class!" << endl; }}; class Base2 : public Base1 {private: void funct1() { cout << "Base2::funct1() is called\n"; } void funct2(int x) { cout << "Base2's Val of x:" << x << endl; } void funct3() { cout << "Base2 is the first" << " Derived class!" << endl; }}; class Base3 : public Base1 {private: void funct1() { cout << "Base3::funct1() is called\n"; } void funct2(int x) { cout << "Base3's Val of x:" << x << endl; } void funct3() { cout << "Class Base3 is second" << " Derived class!" << endl; }}; // Grand-Child_1 of Base1 classclass Derived1 : public Base3 {private: void funct1() { cout << "Derived1::funct1() is called\n"; } void funct2(int x) { cout << "Derived1 Class's Val of x:" << x << endl; } void funct3() { cout << "Class Derived1 is Good!!" << endl; }}; // Grand-Child_2 of Base1 classclass Derived2 : public Base3 {private: void funct1() { cout << "Derived2::funct1()" << " is called\n"; } void funct2(int x) { cout << "Derived2 Class's Val " << "of x:" << x << endl; } void funct3() { cout << "Class Derived2 is Good!!" << endl; }}; // Run-Time Polymorphism// in Hierarchical Inheritanceint main(){ // Base1 class's(Parent class's) // pointer points to Derived1 class Base1* b1ptr = new Derived1(); // Run-Time Polymorphism b1ptr->funct1(); Derived2 d2; // Now the Base1 class pointer // points to d2 object(Derived2 class) b1ptr = &d2; // Run-Time Polymorphism b1ptr->funct2(30); // Compile-Time Binding b1ptr->funct3(); return 0;}Output:Derived1::funct1() is called Derived2 Class's Val of x:30 Base1 is the Parent class! Explanation: Here, the Parent is Base1 and its Grand-children are Derived1 Class and Derived2 class. Even in this case, When the Base1 Class pointer is pointed to Derived1 object or Derived2 object, due to the Virtual Functions (‘VPTR’ and ‘VTABLE’), we can apply Run-Time Polymorphism here. // C++ Program to illustrate Run-Time// Polymorphism in Hierarchical inheritance #include <iostream>using namespace std; class Base1 {public: // Virtual function of Parent Class virtual void funct1() { cout << "Base1::funct1() is called\n"; } virtual void funct2(int x) { cout << "Base1's Val of x:" << x << endl; } // Non-Virtual Function void funct3() { cout << "Base1 is the Parent class!" << endl; }}; class Base2 : public Base1 {private: void funct1() { cout << "Base2::funct1() is called\n"; } void funct2(int x) { cout << "Base2's Val of x:" << x << endl; } void funct3() { cout << "Base2 is the first" << " Derived class!" << endl; }}; class Base3 : public Base1 {private: void funct1() { cout << "Base3::funct1() is called\n"; } void funct2(int x) { cout << "Base3's Val of x:" << x << endl; } void funct3() { cout << "Class Base3 is second" << " Derived class!" << endl; }}; // Grand-Child_1 of Base1 classclass Derived1 : public Base3 {private: void funct1() { cout << "Derived1::funct1() is called\n"; } void funct2(int x) { cout << "Derived1 Class's Val of x:" << x << endl; } void funct3() { cout << "Class Derived1 is Good!!" << endl; }}; // Grand-Child_2 of Base1 classclass Derived2 : public Base3 {private: void funct1() { cout << "Derived2::funct1()" << " is called\n"; } void funct2(int x) { cout << "Derived2 Class's Val " << "of x:" << x << endl; } void funct3() { cout << "Class Derived2 is Good!!" << endl; }}; // Run-Time Polymorphism// in Hierarchical Inheritanceint main(){ // Base1 class's(Parent class's) // pointer points to Derived1 class Base1* b1ptr = new Derived1(); // Run-Time Polymorphism b1ptr->funct1(); Derived2 d2; // Now the Base1 class pointer // points to d2 object(Derived2 class) b1ptr = &d2; // Run-Time Polymorphism b1ptr->funct2(30); // Compile-Time Binding b1ptr->funct3(); return 0;} Derived1::funct1() is called Derived2 Class's Val of x:30 Base1 is the Parent class! Explanation: Here, the Parent is Base1 and its Grand-children are Derived1 Class and Derived2 class. Even in this case, When the Base1 Class pointer is pointed to Derived1 object or Derived2 object, due to the Virtual Functions (‘VPTR’ and ‘VTABLE’), we can apply Run-Time Polymorphism here. C++-Inheritance C++-Virtual Functions C++ C++ Programs CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sorting a vector in C++ Polymorphism in C++ Friend class and function in C++ std::string class in C++ Pair in C++ Standard Template Library (STL) Header files in C/C++ and its uses Sorting a Map by value in C++ STL Program to print ASCII Value of a character How to return multiple values from a function in C or C++? Shallow Copy and Deep Copy in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n16 Apr, 2020" }, { "code": null, "e": 167, "s": 52, "text": "C++ allows users to use the concept of Run-Time Polymorphism using Virtual Functions for any type of Inheritance ." }, { "code": null, "e": 244, "s": 167, "text": "Below is how to implement Run-Time Polymorphism in all types of inheritance:" }, { "code": null, "e": 8763, "s": 244, "text": "Single Inheritance:// C++ program to demonstrate Run Time// Polymorphism in Single Inheritance #include <iostream>using namespace std; // Base Classclass Base { public: // Virtual function virtual void funct1() { cout << \"Base::funct1() is called\\n\"; } // Virtual function virtual void funct2(int x) { cout << \"Base's Val of x:\" << x << endl; } // Non-Virtual Function void funct3() { cout << \"Base is the Parent class!\" << endl; }}; // Derived Class or Sub Classclass Derived : public Base {private: // Virtual Functions // can also be Private! void funct1() { cout << \"Derived::funct1() is called\\n\"; } void funct2(int x) { cout << \"Derived Class's Val of x:\" << x << endl; } void funct3() { cout << \"It's the Derived class's\" << \" funct3() called!\" << endl; }}; int main(){ // Run-Time Polymorphism // in Single Inheritance Base* bptr = new Derived(); // virtual function bptr->funct1(); // virtual function bptr->funct2(12); // Non-virtual function bptr->funct3(); return 0;}Output:Derived::funct1() is called\nDerived Class's Val of x:12\nBase is the Parent class!\nMultiple Inheritance:#include <iostream>using namespace std; // Parent to Derived classclass Base1 {public: // Non-Virtual function void funct1() { cout << \"Base1::funct1() is called\\n\"; } // Virtual function virtual void funct2(int x) { cout << \"Base1's Val of x:\" << x << endl; } // Non-Virtual Function void funct3() { cout << \"Base1 is the Parent class!\" << endl; }}; // Second Parent to Derived classclass Base2 {public: void funct1() { cout << \"Base2::funct1() is called\\n\"; } void funct2(int x) { cout << \"Base2's Val of x:\" << x << endl; } // Only Virtual Function // in Base2 Parent class virtual void funct3() { cout << \"Base2 is Also a Parent class!\" << endl; }}; // Derived Class of Base1 and Base2class Derived : public Base1, public Base2 {private: void funct1() { cout << \"Derived::funct1() is called\\n\"; } void funct2(int x) { cout << \"Derived Class's Val of x:\" << x << endl; } void funct3() { cout << \"Derived::funct3() is called \" << \"and not Base2::funct3() due\" << \" to RTP\" << endl; }}; int main(){ Derived d; // Run-Time Polymorphism // in Multiple Inheritance Base1* b1ptr = &d; // Compile-Time Binding, // Hence Base1::funct1() will be called! b1ptr->funct1(); // virtual function of Base1 // RunTime PolyMorphism b1ptr->funct2(10); // Now Parent Class Base2 // is also pointed to object 'd' // of Derived (to demonstrate RTP) Base2* b2ptr = &d; // virtual function of Base2 // RunTime PolyMorphism b2ptr->funct3(); return 0;}Output:Base1::funct1() is called\nDerived Class's Val of x:10\nDerived::funct3() is called and not Base2::funct3() due to RTP\nNote: Here Both Base1 pointer and Base2 pointer may be pointing to the same Derived Class object ‘d’ but actually the Compiler selects difference Virtual Functions during Run-Time due to the use of different Base Class pointers.Multi-level inheritance:// C++ Program to illustrate Run-Time// Polymorphism in multi-level inheritance #include <iostream>using namespace std; // Parent Classclass Base1 {public: // Virtual function virtual void funct1() { cout << \"Base1::funct1() is called\\n\"; } // Virtual function virtual void funct2(int x) { cout << \"Base1's Val of x:\" << x << endl; } // Non-Virtual Function void funct3() { cout << \"Base1 is the Parent class!\" << endl; }}; // Derived Class of Base1// but Parent to Base3class Base2 : public Base1 { // Virtual Functions can be Private!private: void funct1() { cout << \"Base2::funct1() is called\\n\"; } void funct2(int x) { cout << \"Base2's Val of x:\" << x << endl; } void funct3() { cout << \"Base2 is the first \" << \"Derived class!\" << endl; }}; // Derived Class of Base2// but Parent to Derivedclass Base3 : public Base2 {private: void funct1() { cout << \"Base3::funct1() is called\\n\"; } void funct2(int x) { cout << \"Base3's Val of x:\" << x << endl; } void funct3() { cout << \"Class Base3 is second \" << \"Derived class!\" << endl; }}; // 3 Levels of Multi-Level Inheritance// and final Child Classclass Derived : public Base3 {private: void funct1() { cout << \"Derived::funct1() is called\\n\"; } void funct2(int x) { cout << \"Derived Class's Val of x:\" << x << endl; } void funct3() { cout << \"Class Derived is Final\" << \" Child class!\" << endl; }}; int main(){ // Run-Time Polymorphism // in multi-level Inheritance Base1* b1ptr = new Derived; b1ptr->funct1(); b1ptr->funct2(30); // Compile-Time Binding b1ptr->funct3(); return 0;}Output:Derived::funct1() is called\nDerived Class's Val of x:30\nBase1 is the Parent class!\nExplanation : In the above Example, the Derived class is the final Child class which inherits from Base3 which inherits from Base2 which again finally inherits from the Base1 (Parent Class to Base2). But if you see the Run-Time Polymorphism works even when you are trying to use Virtual Functions in Base1 Class and point its pointer to Derived Class (Which is the great grand-Child of Base1). Hence, even here Run-Time Polymorphism works according to the standard Rules.Hierarchical inheritance:// C++ Program to illustrate Run-Time// Polymorphism in Hierarchical inheritance #include <iostream>using namespace std; class Base1 {public: // Virtual function of Parent Class virtual void funct1() { cout << \"Base1::funct1() is called\\n\"; } virtual void funct2(int x) { cout << \"Base1's Val of x:\" << x << endl; } // Non-Virtual Function void funct3() { cout << \"Base1 is the Parent class!\" << endl; }}; class Base2 : public Base1 {private: void funct1() { cout << \"Base2::funct1() is called\\n\"; } void funct2(int x) { cout << \"Base2's Val of x:\" << x << endl; } void funct3() { cout << \"Base2 is the first\" << \" Derived class!\" << endl; }}; class Base3 : public Base1 {private: void funct1() { cout << \"Base3::funct1() is called\\n\"; } void funct2(int x) { cout << \"Base3's Val of x:\" << x << endl; } void funct3() { cout << \"Class Base3 is second\" << \" Derived class!\" << endl; }}; // Grand-Child_1 of Base1 classclass Derived1 : public Base3 {private: void funct1() { cout << \"Derived1::funct1() is called\\n\"; } void funct2(int x) { cout << \"Derived1 Class's Val of x:\" << x << endl; } void funct3() { cout << \"Class Derived1 is Good!!\" << endl; }}; // Grand-Child_2 of Base1 classclass Derived2 : public Base3 {private: void funct1() { cout << \"Derived2::funct1()\" << \" is called\\n\"; } void funct2(int x) { cout << \"Derived2 Class's Val \" << \"of x:\" << x << endl; } void funct3() { cout << \"Class Derived2 is Good!!\" << endl; }}; // Run-Time Polymorphism// in Hierarchical Inheritanceint main(){ // Base1 class's(Parent class's) // pointer points to Derived1 class Base1* b1ptr = new Derived1(); // Run-Time Polymorphism b1ptr->funct1(); Derived2 d2; // Now the Base1 class pointer // points to d2 object(Derived2 class) b1ptr = &d2; // Run-Time Polymorphism b1ptr->funct2(30); // Compile-Time Binding b1ptr->funct3(); return 0;}Output:Derived1::funct1() is called\nDerived2 Class's Val of x:30\nBase1 is the Parent class!\nExplanation: Here, the Parent is Base1 and its Grand-children are Derived1 Class and Derived2 class. Even in this case, When the Base1 Class pointer is pointed to Derived1 object or Derived2 object, due to the Virtual Functions (‘VPTR’ and ‘VTABLE’), we can apply Run-Time Polymorphism here." }, { "code": null, "e": 10040, "s": 8763, "text": "Single Inheritance:// C++ program to demonstrate Run Time// Polymorphism in Single Inheritance #include <iostream>using namespace std; // Base Classclass Base { public: // Virtual function virtual void funct1() { cout << \"Base::funct1() is called\\n\"; } // Virtual function virtual void funct2(int x) { cout << \"Base's Val of x:\" << x << endl; } // Non-Virtual Function void funct3() { cout << \"Base is the Parent class!\" << endl; }}; // Derived Class or Sub Classclass Derived : public Base {private: // Virtual Functions // can also be Private! void funct1() { cout << \"Derived::funct1() is called\\n\"; } void funct2(int x) { cout << \"Derived Class's Val of x:\" << x << endl; } void funct3() { cout << \"It's the Derived class's\" << \" funct3() called!\" << endl; }}; int main(){ // Run-Time Polymorphism // in Single Inheritance Base* bptr = new Derived(); // virtual function bptr->funct1(); // virtual function bptr->funct2(12); // Non-virtual function bptr->funct3(); return 0;}Output:Derived::funct1() is called\nDerived Class's Val of x:12\nBase is the Parent class!\n" }, { "code": "// C++ program to demonstrate Run Time// Polymorphism in Single Inheritance #include <iostream>using namespace std; // Base Classclass Base { public: // Virtual function virtual void funct1() { cout << \"Base::funct1() is called\\n\"; } // Virtual function virtual void funct2(int x) { cout << \"Base's Val of x:\" << x << endl; } // Non-Virtual Function void funct3() { cout << \"Base is the Parent class!\" << endl; }}; // Derived Class or Sub Classclass Derived : public Base {private: // Virtual Functions // can also be Private! void funct1() { cout << \"Derived::funct1() is called\\n\"; } void funct2(int x) { cout << \"Derived Class's Val of x:\" << x << endl; } void funct3() { cout << \"It's the Derived class's\" << \" funct3() called!\" << endl; }}; int main(){ // Run-Time Polymorphism // in Single Inheritance Base* bptr = new Derived(); // virtual function bptr->funct1(); // virtual function bptr->funct2(12); // Non-virtual function bptr->funct3(); return 0;}", "e": 11209, "s": 10040, "text": null }, { "code": null, "e": 11292, "s": 11209, "text": "Derived::funct1() is called\nDerived Class's Val of x:12\nBase is the Parent class!\n" }, { "code": null, "e": 13403, "s": 11292, "text": "Multiple Inheritance:#include <iostream>using namespace std; // Parent to Derived classclass Base1 {public: // Non-Virtual function void funct1() { cout << \"Base1::funct1() is called\\n\"; } // Virtual function virtual void funct2(int x) { cout << \"Base1's Val of x:\" << x << endl; } // Non-Virtual Function void funct3() { cout << \"Base1 is the Parent class!\" << endl; }}; // Second Parent to Derived classclass Base2 {public: void funct1() { cout << \"Base2::funct1() is called\\n\"; } void funct2(int x) { cout << \"Base2's Val of x:\" << x << endl; } // Only Virtual Function // in Base2 Parent class virtual void funct3() { cout << \"Base2 is Also a Parent class!\" << endl; }}; // Derived Class of Base1 and Base2class Derived : public Base1, public Base2 {private: void funct1() { cout << \"Derived::funct1() is called\\n\"; } void funct2(int x) { cout << \"Derived Class's Val of x:\" << x << endl; } void funct3() { cout << \"Derived::funct3() is called \" << \"and not Base2::funct3() due\" << \" to RTP\" << endl; }}; int main(){ Derived d; // Run-Time Polymorphism // in Multiple Inheritance Base1* b1ptr = &d; // Compile-Time Binding, // Hence Base1::funct1() will be called! b1ptr->funct1(); // virtual function of Base1 // RunTime PolyMorphism b1ptr->funct2(10); // Now Parent Class Base2 // is also pointed to object 'd' // of Derived (to demonstrate RTP) Base2* b2ptr = &d; // virtual function of Base2 // RunTime PolyMorphism b2ptr->funct3(); return 0;}Output:Base1::funct1() is called\nDerived Class's Val of x:10\nDerived::funct3() is called and not Base2::funct3() due to RTP\nNote: Here Both Base1 pointer and Base2 pointer may be pointing to the same Derived Class object ‘d’ but actually the Compiler selects difference Virtual Functions during Run-Time due to the use of different Base Class pointers." }, { "code": "#include <iostream>using namespace std; // Parent to Derived classclass Base1 {public: // Non-Virtual function void funct1() { cout << \"Base1::funct1() is called\\n\"; } // Virtual function virtual void funct2(int x) { cout << \"Base1's Val of x:\" << x << endl; } // Non-Virtual Function void funct3() { cout << \"Base1 is the Parent class!\" << endl; }}; // Second Parent to Derived classclass Base2 {public: void funct1() { cout << \"Base2::funct1() is called\\n\"; } void funct2(int x) { cout << \"Base2's Val of x:\" << x << endl; } // Only Virtual Function // in Base2 Parent class virtual void funct3() { cout << \"Base2 is Also a Parent class!\" << endl; }}; // Derived Class of Base1 and Base2class Derived : public Base1, public Base2 {private: void funct1() { cout << \"Derived::funct1() is called\\n\"; } void funct2(int x) { cout << \"Derived Class's Val of x:\" << x << endl; } void funct3() { cout << \"Derived::funct3() is called \" << \"and not Base2::funct3() due\" << \" to RTP\" << endl; }}; int main(){ Derived d; // Run-Time Polymorphism // in Multiple Inheritance Base1* b1ptr = &d; // Compile-Time Binding, // Hence Base1::funct1() will be called! b1ptr->funct1(); // virtual function of Base1 // RunTime PolyMorphism b1ptr->funct2(10); // Now Parent Class Base2 // is also pointed to object 'd' // of Derived (to demonstrate RTP) Base2* b2ptr = &d; // virtual function of Base2 // RunTime PolyMorphism b2ptr->funct3(); return 0;}", "e": 15141, "s": 13403, "text": null }, { "code": null, "e": 15259, "s": 15141, "text": "Base1::funct1() is called\nDerived Class's Val of x:10\nDerived::funct3() is called and not Base2::funct3() due to RTP\n" }, { "code": null, "e": 15488, "s": 15259, "text": "Note: Here Both Base1 pointer and Base2 pointer may be pointing to the same Derived Class object ‘d’ but actually the Compiler selects difference Virtual Functions during Run-Time due to the use of different Base Class pointers." }, { "code": null, "e": 17950, "s": 15488, "text": "Multi-level inheritance:// C++ Program to illustrate Run-Time// Polymorphism in multi-level inheritance #include <iostream>using namespace std; // Parent Classclass Base1 {public: // Virtual function virtual void funct1() { cout << \"Base1::funct1() is called\\n\"; } // Virtual function virtual void funct2(int x) { cout << \"Base1's Val of x:\" << x << endl; } // Non-Virtual Function void funct3() { cout << \"Base1 is the Parent class!\" << endl; }}; // Derived Class of Base1// but Parent to Base3class Base2 : public Base1 { // Virtual Functions can be Private!private: void funct1() { cout << \"Base2::funct1() is called\\n\"; } void funct2(int x) { cout << \"Base2's Val of x:\" << x << endl; } void funct3() { cout << \"Base2 is the first \" << \"Derived class!\" << endl; }}; // Derived Class of Base2// but Parent to Derivedclass Base3 : public Base2 {private: void funct1() { cout << \"Base3::funct1() is called\\n\"; } void funct2(int x) { cout << \"Base3's Val of x:\" << x << endl; } void funct3() { cout << \"Class Base3 is second \" << \"Derived class!\" << endl; }}; // 3 Levels of Multi-Level Inheritance// and final Child Classclass Derived : public Base3 {private: void funct1() { cout << \"Derived::funct1() is called\\n\"; } void funct2(int x) { cout << \"Derived Class's Val of x:\" << x << endl; } void funct3() { cout << \"Class Derived is Final\" << \" Child class!\" << endl; }}; int main(){ // Run-Time Polymorphism // in multi-level Inheritance Base1* b1ptr = new Derived; b1ptr->funct1(); b1ptr->funct2(30); // Compile-Time Binding b1ptr->funct3(); return 0;}Output:Derived::funct1() is called\nDerived Class's Val of x:30\nBase1 is the Parent class!\nExplanation : In the above Example, the Derived class is the final Child class which inherits from Base3 which inherits from Base2 which again finally inherits from the Base1 (Parent Class to Base2). But if you see the Run-Time Polymorphism works even when you are trying to use Virtual Functions in Base1 Class and point its pointer to Derived Class (Which is the great grand-Child of Base1). Hence, even here Run-Time Polymorphism works according to the standard Rules." }, { "code": "// C++ Program to illustrate Run-Time// Polymorphism in multi-level inheritance #include <iostream>using namespace std; // Parent Classclass Base1 {public: // Virtual function virtual void funct1() { cout << \"Base1::funct1() is called\\n\"; } // Virtual function virtual void funct2(int x) { cout << \"Base1's Val of x:\" << x << endl; } // Non-Virtual Function void funct3() { cout << \"Base1 is the Parent class!\" << endl; }}; // Derived Class of Base1// but Parent to Base3class Base2 : public Base1 { // Virtual Functions can be Private!private: void funct1() { cout << \"Base2::funct1() is called\\n\"; } void funct2(int x) { cout << \"Base2's Val of x:\" << x << endl; } void funct3() { cout << \"Base2 is the first \" << \"Derived class!\" << endl; }}; // Derived Class of Base2// but Parent to Derivedclass Base3 : public Base2 {private: void funct1() { cout << \"Base3::funct1() is called\\n\"; } void funct2(int x) { cout << \"Base3's Val of x:\" << x << endl; } void funct3() { cout << \"Class Base3 is second \" << \"Derived class!\" << endl; }}; // 3 Levels of Multi-Level Inheritance// and final Child Classclass Derived : public Base3 {private: void funct1() { cout << \"Derived::funct1() is called\\n\"; } void funct2(int x) { cout << \"Derived Class's Val of x:\" << x << endl; } void funct3() { cout << \"Class Derived is Final\" << \" Child class!\" << endl; }}; int main(){ // Run-Time Polymorphism // in multi-level Inheritance Base1* b1ptr = new Derived; b1ptr->funct1(); b1ptr->funct2(30); // Compile-Time Binding b1ptr->funct3(); return 0;}", "e": 19827, "s": 17950, "text": null }, { "code": null, "e": 19911, "s": 19827, "text": "Derived::funct1() is called\nDerived Class's Val of x:30\nBase1 is the Parent class!\n" }, { "code": null, "e": 20383, "s": 19911, "text": "Explanation : In the above Example, the Derived class is the final Child class which inherits from Base3 which inherits from Base2 which again finally inherits from the Base1 (Parent Class to Base2). But if you see the Run-Time Polymorphism works even when you are trying to use Virtual Functions in Base1 Class and point its pointer to Derived Class (Which is the great grand-Child of Base1). Hence, even here Run-Time Polymorphism works according to the standard Rules." }, { "code": null, "e": 23055, "s": 20383, "text": "Hierarchical inheritance:// C++ Program to illustrate Run-Time// Polymorphism in Hierarchical inheritance #include <iostream>using namespace std; class Base1 {public: // Virtual function of Parent Class virtual void funct1() { cout << \"Base1::funct1() is called\\n\"; } virtual void funct2(int x) { cout << \"Base1's Val of x:\" << x << endl; } // Non-Virtual Function void funct3() { cout << \"Base1 is the Parent class!\" << endl; }}; class Base2 : public Base1 {private: void funct1() { cout << \"Base2::funct1() is called\\n\"; } void funct2(int x) { cout << \"Base2's Val of x:\" << x << endl; } void funct3() { cout << \"Base2 is the first\" << \" Derived class!\" << endl; }}; class Base3 : public Base1 {private: void funct1() { cout << \"Base3::funct1() is called\\n\"; } void funct2(int x) { cout << \"Base3's Val of x:\" << x << endl; } void funct3() { cout << \"Class Base3 is second\" << \" Derived class!\" << endl; }}; // Grand-Child_1 of Base1 classclass Derived1 : public Base3 {private: void funct1() { cout << \"Derived1::funct1() is called\\n\"; } void funct2(int x) { cout << \"Derived1 Class's Val of x:\" << x << endl; } void funct3() { cout << \"Class Derived1 is Good!!\" << endl; }}; // Grand-Child_2 of Base1 classclass Derived2 : public Base3 {private: void funct1() { cout << \"Derived2::funct1()\" << \" is called\\n\"; } void funct2(int x) { cout << \"Derived2 Class's Val \" << \"of x:\" << x << endl; } void funct3() { cout << \"Class Derived2 is Good!!\" << endl; }}; // Run-Time Polymorphism// in Hierarchical Inheritanceint main(){ // Base1 class's(Parent class's) // pointer points to Derived1 class Base1* b1ptr = new Derived1(); // Run-Time Polymorphism b1ptr->funct1(); Derived2 d2; // Now the Base1 class pointer // points to d2 object(Derived2 class) b1ptr = &d2; // Run-Time Polymorphism b1ptr->funct2(30); // Compile-Time Binding b1ptr->funct3(); return 0;}Output:Derived1::funct1() is called\nDerived2 Class's Val of x:30\nBase1 is the Parent class!\nExplanation: Here, the Parent is Base1 and its Grand-children are Derived1 Class and Derived2 class. Even in this case, When the Base1 Class pointer is pointed to Derived1 object or Derived2 object, due to the Virtual Functions (‘VPTR’ and ‘VTABLE’), we can apply Run-Time Polymorphism here." }, { "code": "// C++ Program to illustrate Run-Time// Polymorphism in Hierarchical inheritance #include <iostream>using namespace std; class Base1 {public: // Virtual function of Parent Class virtual void funct1() { cout << \"Base1::funct1() is called\\n\"; } virtual void funct2(int x) { cout << \"Base1's Val of x:\" << x << endl; } // Non-Virtual Function void funct3() { cout << \"Base1 is the Parent class!\" << endl; }}; class Base2 : public Base1 {private: void funct1() { cout << \"Base2::funct1() is called\\n\"; } void funct2(int x) { cout << \"Base2's Val of x:\" << x << endl; } void funct3() { cout << \"Base2 is the first\" << \" Derived class!\" << endl; }}; class Base3 : public Base1 {private: void funct1() { cout << \"Base3::funct1() is called\\n\"; } void funct2(int x) { cout << \"Base3's Val of x:\" << x << endl; } void funct3() { cout << \"Class Base3 is second\" << \" Derived class!\" << endl; }}; // Grand-Child_1 of Base1 classclass Derived1 : public Base3 {private: void funct1() { cout << \"Derived1::funct1() is called\\n\"; } void funct2(int x) { cout << \"Derived1 Class's Val of x:\" << x << endl; } void funct3() { cout << \"Class Derived1 is Good!!\" << endl; }}; // Grand-Child_2 of Base1 classclass Derived2 : public Base3 {private: void funct1() { cout << \"Derived2::funct1()\" << \" is called\\n\"; } void funct2(int x) { cout << \"Derived2 Class's Val \" << \"of x:\" << x << endl; } void funct3() { cout << \"Class Derived2 is Good!!\" << endl; }}; // Run-Time Polymorphism// in Hierarchical Inheritanceint main(){ // Base1 class's(Parent class's) // pointer points to Derived1 class Base1* b1ptr = new Derived1(); // Run-Time Polymorphism b1ptr->funct1(); Derived2 d2; // Now the Base1 class pointer // points to d2 object(Derived2 class) b1ptr = &d2; // Run-Time Polymorphism b1ptr->funct2(30); // Compile-Time Binding b1ptr->funct3(); return 0;}", "e": 25319, "s": 23055, "text": null }, { "code": null, "e": 25405, "s": 25319, "text": "Derived1::funct1() is called\nDerived2 Class's Val of x:30\nBase1 is the Parent class!\n" }, { "code": null, "e": 25697, "s": 25405, "text": "Explanation: Here, the Parent is Base1 and its Grand-children are Derived1 Class and Derived2 class. Even in this case, When the Base1 Class pointer is pointed to Derived1 object or Derived2 object, due to the Virtual Functions (‘VPTR’ and ‘VTABLE’), we can apply Run-Time Polymorphism here." }, { "code": null, "e": 25713, "s": 25697, "text": "C++-Inheritance" }, { "code": null, "e": 25735, "s": 25713, "text": "C++-Virtual Functions" }, { "code": null, "e": 25739, "s": 25735, "text": "C++" }, { "code": null, "e": 25752, "s": 25739, "text": "C++ Programs" }, { "code": null, "e": 25756, "s": 25752, "text": "CPP" }, { "code": null, "e": 25854, "s": 25756, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25878, "s": 25854, "text": "Sorting a vector in C++" }, { "code": null, "e": 25898, "s": 25878, "text": "Polymorphism in C++" }, { "code": null, "e": 25931, "s": 25898, "text": "Friend class and function in C++" }, { "code": null, "e": 25956, "s": 25931, "text": "std::string class in C++" }, { "code": null, "e": 26000, "s": 25956, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 26035, "s": 26000, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 26069, "s": 26035, "text": "Sorting a Map by value in C++ STL" }, { "code": null, "e": 26113, "s": 26069, "text": "Program to print ASCII Value of a character" }, { "code": null, "e": 26172, "s": 26113, "text": "How to return multiple values from a function in C or C++?" } ]
Matplotlib.figure.Figure.dpi() in Python
30 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements. The dpi method of figure module of matplotlib library is the resolution in dots per inch. Syntax: fig.dpi Parameters: This method does not accept any parameters. Returns: This method returns resolution in dots per inch. Below examples illustrate the matplotlib.figure.Figure.dpi function in matplotlib.figure: Example 1: # Implementation of matplotlib function import matplotlib.pyplot as pltimport numpy as np fig = plt.figure() nx = int(fig.get_figwidth() * fig.dpi)ny = int(fig.get_figheight() * fig.dpi) data = np.random.random((ny, nx))plt.plot(data) fig.suptitle('matplotlib.figure.Figure.dpi \function Example', fontweight ="bold") plt.show() Output: Example 2: # Implementation of matplotlib function import matplotlib.pyplot as pltfrom matplotlib import collections, colors, transformsimport numpy as np nverts = 50npts = 100 r = np.arange(nverts)theta = np.linspace(0, 2 * np.pi, nverts) xx = r * np.sin(theta)yy = r * np.cos(theta) spiral = np.column_stack([xx, yy]) rs = np.random.RandomState(19680801) xyo = rs.randn(npts, 2) colors = [colors.to_rgba(c) for c in plt.rcParams['axes.prop_cycle'].by_key()['color']] fig, ax1 = plt.subplots() col = collections.RegularPolyCollection( 7, sizes = np.abs(xx) * 10.0, offsets = xyo, transOffset = ax1.transData) trans = transforms.Affine2D().scale(fig.dpi / 72.0) col.set_transform(trans) ax1.add_collection(col, autolim = True)col.set_color(colors) fig.suptitle('matplotlib.figure.Figure.dpi() function\ Example', fontweight ="bold") plt.show() Output: Matplotlib figure-class Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Apr, 2020" }, { "code": null, "e": 339, "s": 28, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements." }, { "code": null, "e": 429, "s": 339, "text": "The dpi method of figure module of matplotlib library is the resolution in dots per inch." }, { "code": null, "e": 445, "s": 429, "text": "Syntax: fig.dpi" }, { "code": null, "e": 501, "s": 445, "text": "Parameters: This method does not accept any parameters." }, { "code": null, "e": 559, "s": 501, "text": "Returns: This method returns resolution in dots per inch." }, { "code": null, "e": 649, "s": 559, "text": "Below examples illustrate the matplotlib.figure.Figure.dpi function in matplotlib.figure:" }, { "code": null, "e": 660, "s": 649, "text": "Example 1:" }, { "code": "# Implementation of matplotlib function import matplotlib.pyplot as pltimport numpy as np fig = plt.figure() nx = int(fig.get_figwidth() * fig.dpi)ny = int(fig.get_figheight() * fig.dpi) data = np.random.random((ny, nx))plt.plot(data) fig.suptitle('matplotlib.figure.Figure.dpi \\function Example', fontweight =\"bold\") plt.show()", "e": 999, "s": 660, "text": null }, { "code": null, "e": 1007, "s": 999, "text": "Output:" }, { "code": null, "e": 1018, "s": 1007, "text": "Example 2:" }, { "code": "# Implementation of matplotlib function import matplotlib.pyplot as pltfrom matplotlib import collections, colors, transformsimport numpy as np nverts = 50npts = 100 r = np.arange(nverts)theta = np.linspace(0, 2 * np.pi, nverts) xx = r * np.sin(theta)yy = r * np.cos(theta) spiral = np.column_stack([xx, yy]) rs = np.random.RandomState(19680801) xyo = rs.randn(npts, 2) colors = [colors.to_rgba(c) for c in plt.rcParams['axes.prop_cycle'].by_key()['color']] fig, ax1 = plt.subplots() col = collections.RegularPolyCollection( 7, sizes = np.abs(xx) * 10.0, offsets = xyo, transOffset = ax1.transData) trans = transforms.Affine2D().scale(fig.dpi / 72.0) col.set_transform(trans) ax1.add_collection(col, autolim = True)col.set_color(colors) fig.suptitle('matplotlib.figure.Figure.dpi() function\\ Example', fontweight =\"bold\") plt.show()", "e": 1889, "s": 1018, "text": null }, { "code": null, "e": 1897, "s": 1889, "text": "Output:" }, { "code": null, "e": 1921, "s": 1897, "text": "Matplotlib figure-class" }, { "code": null, "e": 1939, "s": 1921, "text": "Python-matplotlib" }, { "code": null, "e": 1946, "s": 1939, "text": "Python" }, { "code": null, "e": 2044, "s": 1946, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2062, "s": 2044, "text": "Python Dictionary" }, { "code": null, "e": 2104, "s": 2062, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2126, "s": 2104, "text": "Enumerate() in Python" }, { "code": null, "e": 2161, "s": 2126, "text": "Read a file line by line in Python" }, { "code": null, "e": 2187, "s": 2161, "text": "Python String | replace()" }, { "code": null, "e": 2219, "s": 2187, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2248, "s": 2219, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2275, "s": 2248, "text": "Python Classes and Objects" }, { "code": null, "e": 2305, "s": 2275, "text": "Iterate over a list in Python" } ]
Python - Print Heart Pattern - GeeksforGeeks
24 Feb, 2021 Given an even integer input, the task is to write a Python program to print a heart using loops and mathematical formulations. For n = 8 * * * * * * * * * * G F G * * * * * * * * For n = 14 * * * * * * * * * * * * * * * * * * G F G * * * * * * * * * * * * * * The following steps are used : Form the worksheet of n X n+1 using two loops. Apply the if-else conditions for printing stars. Apply the if-else conditions for printing text “GFG”. Apply else condition for rest spaces. Note: The value of n must be greater than 8 Below is the implementation of the above approach : Python3 # define size n = even only n = 8 # so this heart can be made n//2 part left, # n//2 part right, and one middle line # i.e; columns m = n + 1 m = n+1 # loops for upper part for i in range(n//2-1): for j in range(m): # condition for printing stars to GFG upper line if i == n//2-2 and (j == 0 or j == m-1): print("*", end=" ") # condition for printing stars to left upper elif j <= m//2 and ((i+j == n//2-3 and j <= m//4) \ or (j-i == m//2-n//2+3 and j > m//4)): print("*", end=" ") # condition for printing stars to right upper elif j > m//2 and ((i+j == n//2-3+m//2 and j < 3*m//4) \ or (j-i == m//2-n//2+3+m//2 and j >= 3*m//4)): print("*", end=" ") # condition for printing spaces else: print(" ", end=" ") print() # loops for lower part for i in range(n//2-1, n): for j in range(m): # condition for printing stars if (i-j == n//2-1) or (i+j == n-1+m//2): print('*', end=" ") # condition for printing GFG elif i == n//2-1: if j == m//2-1 or j == m//2+1: print('G', end=" ") elif j == m//2: print('F', end=" ") else: print(' ', end=" ") # condition for printing spaces else: print(' ', end=" ") print() Output: * * * * * * * * * * * * * * * * * * G F G * * * * * * * * * * * * * * Python Pattern-printing 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 ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python program to check whether a number is Prime or not Python | Convert a list to dictionary
[ { "code": null, "e": 24001, "s": 23970, "text": " \n24 Feb, 2021\n" }, { "code": null, "e": 24128, "s": 24001, "text": "Given an even integer input, the task is to write a Python program to print a heart using loops and mathematical formulations." }, { "code": null, "e": 24690, "s": 24128, "text": "For n = 8\n\n * * * * \n* * * \n* * \n* G F G * \n * * \n * * \n * * \n *\n\nFor n = 14\n\n * * * * \n * * * * \n * * * * \n* * * \n* * \n* G F G * \n * * \n * * \n * * \n * * \n * * \n * * \n * " }, { "code": null, "e": 24721, "s": 24690, "text": "The following steps are used :" }, { "code": null, "e": 24768, "s": 24721, "text": "Form the worksheet of n X n+1 using two loops." }, { "code": null, "e": 24817, "s": 24768, "text": "Apply the if-else conditions for printing stars." }, { "code": null, "e": 24871, "s": 24817, "text": "Apply the if-else conditions for printing text “GFG”." }, { "code": null, "e": 24909, "s": 24871, "text": "Apply else condition for rest spaces." }, { "code": null, "e": 24953, "s": 24909, "text": "Note: The value of n must be greater than 8" }, { "code": null, "e": 25005, "s": 24953, "text": "Below is the implementation of the above approach :" }, { "code": null, "e": 25013, "s": 25005, "text": "Python3" }, { "code": "\n\n\n\n\n\n\n# define size n = even only \nn = 8\n \n# so this heart can be made n//2 part left, \n# n//2 part right, and one middle line \n# i.e; columns m = n + 1 \nm = n+1\n \n# loops for upper part \nfor i in range(n//2-1): \n for j in range(m): \n \n # condition for printing stars to GFG upper line \n if i == n//2-2 and (j == 0 or j == m-1): \n print(\"*\", end=\" \") \n \n # condition for printing stars to left upper \n elif j <= m//2 and ((i+j == n//2-3 and j <= m//4) \\ \n or (j-i == m//2-n//2+3 and j > m//4)): \n print(\"*\", end=\" \") \n \n # condition for printing stars to right upper \n elif j > m//2 and ((i+j == n//2-3+m//2 and j < 3*m//4) \\ \n or (j-i == m//2-n//2+3+m//2 and j >= 3*m//4)): \n print(\"*\", end=\" \") \n \n # condition for printing spaces \n else: \n print(\" \", end=\" \") \n print() \n \n# loops for lower part \nfor i in range(n//2-1, n): \n for j in range(m): \n \n # condition for printing stars \n if (i-j == n//2-1) or (i+j == n-1+m//2): \n print('*', end=\" \") \n \n # condition for printing GFG \n elif i == n//2-1: \n \n if j == m//2-1 or j == m//2+1: \n print('G', end=\" \") \n elif j == m//2: \n print('F', end=\" \") \n else: \n print(' ', end=\" \") \n \n # condition for printing spaces \n else: \n print(' ', end=\" \") \n \n print()\n\n\n\n\n\n", "e": 26659, "s": 25023, "text": null }, { "code": null, "e": 26667, "s": 26659, "text": "Output:" }, { "code": null, "e": 27101, "s": 26667, "text": " \n * * * * \n * * * * \n * * * * \n* * * \n* * \n* G F G * \n * * \n * * \n * * \n * * \n * * \n * * \n * " }, { "code": null, "e": 27127, "s": 27101, "text": "\nPython Pattern-printing\n" }, { "code": null, "e": 27136, "s": 27127, "text": "\nPython\n" }, { "code": null, "e": 27154, "s": 27136, "text": "\nPython Programs\n" }, { "code": null, "e": 27359, "s": 27154, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 27391, "s": 27359, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27447, "s": 27391, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27489, "s": 27447, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27531, "s": 27489, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27567, "s": 27531, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 27589, "s": 27567, "text": "Defaultdict in Python" }, { "code": null, "e": 27628, "s": 27589, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27674, "s": 27628, "text": "Python | Split string into list of characters" }, { "code": null, "e": 27731, "s": 27674, "text": "Python program to check whether a number is Prime or not" } ]
Using Conditional Expressions
General functions are used to handle NULL values in database. The objective of the general NULL handling functions is to replace the NULL values with an alternate value. We shall briefly see through these functions below. The NVL function substitutes an alternate value for a NULL value. NVL( Arg1, replace_with ) In the syntax, both the parameters are mandatory. Note that NVL function works with all types of data types. And also that the data type of original string and the replacement must be in compatible state i.e. either same or implicitly convertible by Oracle. If arg1 is a character value, then oracle converts replacement string to the data type compatible with arg1 before comparing them and returns VARCHAR2 in the character set of expr1. If arg1 is numeric, then Oracle determines the argument with highest numeric precedence, implicitly converts the other argument to that data type, and returns that data type. The SELECT statement below will display 'n/a' if an employee has been not assigned to any job yet i.e. JOB_ID is NULL. Otherwise, it would display the actual JOB_ID value. SELECT first_name, NVL(JOB_ID, 'n/a') FROM employees; As an enhancement over NVL, Oracle introduced a function to substitute value not only for NULL columns values but also for NOT NULL columns. NVL2 function can be used to substitute an alternate value for NULL as well as non NULL value. NVL2( string1, value_if_NOT_null, value_if_null ) The SELECT statement below would display 'Bench' if the JOB_CODE for an employee is NULL. For a definite not null value of JOB CODE, it would show constant value 'Job Assigned'. SQL> SELECT NVL2(JOB_CODE, 'Job Assigned', 'Bench') FROM employees; The NULLIF function compares two arguments expr1 and expr2. If expr1 and expr2 are equal, it returns NULL; else, it returns expr1. Unlike the other null handling function, first argument can't be NULL. NULLIF (expr1, expr2) Note that first argument can be an expression that evaluates to NULL, but it can't be the literal NULL. Both the parameters are mandatory for the function to execute. The below query returns NULL since both the input values, 12 are equal. SELECT NULLIF (12, 12) FROM DUAL; Similarly, below query return 'SUN' since both the strings are not equal. SELECT NULLIF ('SUN', 'MOON') FROM DUAL; COALESCE function, a more generic form of NVL, returns the first non-null expression in the argument list. It takes minimum two mandatory parameters but maximum arguments has no limit. COALESCE (expr1, expr2, ... expr_n ) Consider the below SELECT query. It selects the first not null value fed into address fields for an employee. SELECT COALESCE (address1, address2, address3) Address FROM employees; Interestingly, the working of COALESCE function is similar to IF..ELSIF..ENDIF construct. The query above can be re-written as - IF address1 is not null THEN result := address1; ELSIF address2 is not null THEN result := address2; ELSIF address3 is not null THEN result := address3; ELSE result := null; END IF; Oracle provides conditional functions DECODE and CASE to impose conditions even in SQL statement. The function is the SQL equivalence of IF..THEN..ELSE conditional procedural statement. DECODE works with values/columns/expressions of all data types. DECODE (expression, search, result [, search, result]... [, default]) DECODE function compares expression against each search value in order. If equality exists between expression and search argument, then it returns the corresponding result. In case of no match, default value is returned, if defined, else NULL. In case of any type compatibility mismatch, oracle internally does possible implicit conversion to return the results. As a matter of fact, Oracle considers two nulls to be equivalent while working with DECODE function. SELECT DECODE(NULL,NULL,'EQUAL','NOT EQUAL') FROM DUAL; DECOD ----- EQUAL If expression is null, then Oracle returns the result of the first search that is also null. The maximum number of components in the DECODE function is 255. SELECT first_name, salary, DECODE (hire_date, sysdate,'NEW JOINEE','EMPLOYEE') FROM employees; CASE expressions works on the same concept as DECODE but differs in syntax and usage. CASE [ expression ] WHEN condition_1 THEN result_1 WHEN condition_2 THEN result_2 ... WHEN condition_n THEN result_n ELSE result END Oracle search starts from left and moves rightwards until it finds a true condition, and then returns result expression associated with it. If no condition is found to be true, and an ELSE clause exists, then Oracle returns result defined with else. Otherwise, Oracle returns null. The maximum number of arguments in a CASE expression is 255. All expressions count toward this limit, including the initial expression of a simple CASE expression and the optional ELSE expression. Each WHEN ... THEN pair counts as two arguments. To avoid exceeding this limit, you can nest CASE expressions so that the return_expr itself is a CASE expression. SELECT first_name, CASE WHEN salary < 200 THEN 'GRADE 1' WHEN salary > 200 AND salary < 5000 THEN 'GRADE 2' ELSE 'GRADE 3' END CASE FROM employees; ENAM CASE ---- ------- JOHN GRADE 2 EDWIN GRADE 3 KING GRADE 1 42 Lectures 5 hours Anadi Sharma 14 Lectures 2 hours Anadi Sharma 44 Lectures 4.5 hours Anadi Sharma 94 Lectures 7 hours Abhishek And Pukhraj 80 Lectures 6.5 hours Oracle Master Training | 150,000+ Students Worldwide 31 Lectures 6 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2685, "s": 2463, "text": "General functions are used to handle NULL values in database. The objective of the general NULL handling functions is to replace the NULL values with an alternate value. We shall briefly see through these functions below." }, { "code": null, "e": 2752, "s": 2685, "text": "The NVL function substitutes an alternate value for a NULL value. " }, { "code": null, "e": 2778, "s": 2752, "text": "NVL( Arg1, replace_with )" }, { "code": null, "e": 3036, "s": 2778, "text": "In the syntax, both the parameters are mandatory. Note that NVL function works with all types of data types. And also that the data type of original string and the replacement must be in compatible state i.e. either same or implicitly convertible by Oracle." }, { "code": null, "e": 3394, "s": 3036, "text": "If arg1 is a character value, then oracle converts replacement string to the data type compatible with arg1 before comparing them and returns VARCHAR2 in the character set of expr1. If arg1 is numeric, then Oracle determines the argument with highest numeric precedence, implicitly converts the other argument to that data type, and returns that data type. " }, { "code": null, "e": 3566, "s": 3394, "text": "The SELECT statement below will display 'n/a' if an employee has been not assigned to any job yet i.e. JOB_ID is NULL. Otherwise, it would display the actual JOB_ID value." }, { "code": null, "e": 3621, "s": 3566, "text": "SELECT first_name, NVL(JOB_ID, 'n/a')\nFROM employees;" }, { "code": null, "e": 3858, "s": 3621, "text": "As an enhancement over NVL, Oracle introduced a function to substitute value not only for NULL columns values but also for NOT NULL columns. NVL2 function can be used to substitute an alternate value for NULL as well as non NULL value. " }, { "code": null, "e": 3908, "s": 3858, "text": "NVL2( string1, value_if_NOT_null, value_if_null )" }, { "code": null, "e": 4086, "s": 3908, "text": "The SELECT statement below would display 'Bench' if the JOB_CODE for an employee is NULL. For a definite not null value of JOB CODE, it would show constant value 'Job Assigned'." }, { "code": null, "e": 4154, "s": 4086, "text": "SQL> SELECT NVL2(JOB_CODE, 'Job Assigned', 'Bench')\nFROM employees;" }, { "code": null, "e": 4356, "s": 4154, "text": "The NULLIF function compares two arguments expr1 and expr2. If expr1 and expr2 are equal, it returns NULL; else, it returns expr1. Unlike the other null handling function, first argument can't be NULL." }, { "code": null, "e": 4378, "s": 4356, "text": "NULLIF (expr1, expr2)" }, { "code": null, "e": 4545, "s": 4378, "text": "Note that first argument can be an expression that evaluates to NULL, but it can't be the literal NULL. Both the parameters are mandatory for the function to execute." }, { "code": null, "e": 4617, "s": 4545, "text": "The below query returns NULL since both the input values, 12 are equal." }, { "code": null, "e": 4651, "s": 4617, "text": "SELECT\tNULLIF (12, 12)\nFROM DUAL;" }, { "code": null, "e": 4725, "s": 4651, "text": "Similarly, below query return 'SUN' since both the strings are not equal." }, { "code": null, "e": 4766, "s": 4725, "text": "SELECT NULLIF ('SUN', 'MOON')\nFROM DUAL;" }, { "code": null, "e": 4951, "s": 4766, "text": "COALESCE function, a more generic form of NVL, returns the first non-null expression in the argument list. It takes minimum two mandatory parameters but maximum arguments has no limit." }, { "code": null, "e": 4988, "s": 4951, "text": "COALESCE (expr1, expr2, ... expr_n )" }, { "code": null, "e": 5098, "s": 4988, "text": "Consider the below SELECT query. It selects the first not null value fed into address fields for an employee." }, { "code": null, "e": 5170, "s": 5098, "text": "SELECT COALESCE (address1, address2, address3) Address\nFROM employees;" }, { "code": null, "e": 5300, "s": 5170, "text": "Interestingly, the working of COALESCE function is similar to IF..ELSIF..ENDIF construct. The query above can be re-written as - " }, { "code": null, "e": 5494, "s": 5300, "text": "IF address1 is not null THEN\n result := address1;\nELSIF address2 is not null THEN\n result := address2;\nELSIF address3 is not null THEN\n result := address3;\nELSE\n result := null;\nEND IF;" }, { "code": null, "e": 5592, "s": 5494, "text": "Oracle provides conditional functions DECODE and CASE to impose conditions even in SQL statement." }, { "code": null, "e": 5744, "s": 5592, "text": "The function is the SQL equivalence of IF..THEN..ELSE conditional procedural statement. DECODE works with values/columns/expressions of all data types." }, { "code": null, "e": 5814, "s": 5744, "text": "DECODE (expression, search, result [, search, result]... [, default])" }, { "code": null, "e": 6177, "s": 5814, "text": "DECODE function compares expression against each search value in order. If equality exists between expression and search argument, then it returns the corresponding result. In case of no match, default value is returned, if defined, else NULL. In case of any type compatibility mismatch, oracle internally does possible implicit conversion to return the results." }, { "code": null, "e": 6278, "s": 6177, "text": "As a matter of fact, Oracle considers two nulls to be equivalent while working with DECODE function." }, { "code": null, "e": 6354, "s": 6278, "text": "SELECT DECODE(NULL,NULL,'EQUAL','NOT EQUAL') \nFROM DUAL;\n\nDECOD\n-----\nEQUAL" }, { "code": null, "e": 6511, "s": 6354, "text": "If expression is null, then Oracle returns the result of the first search that is also null. The maximum number of components in the DECODE function is 255." }, { "code": null, "e": 6607, "s": 6511, "text": "SELECT\tfirst_name, salary, DECODE (hire_date, sysdate,'NEW JOINEE','EMPLOYEE')\n\tFROM employees;" }, { "code": null, "e": 6693, "s": 6607, "text": "CASE expressions works on the same concept as DECODE but differs in syntax and usage." }, { "code": null, "e": 6842, "s": 6693, "text": "CASE [ expression ]\n WHEN condition_1 THEN result_1\n WHEN condition_2 THEN result_2\n ...\n WHEN condition_n THEN result_n\n ELSE result\nEND" }, { "code": null, "e": 7124, "s": 6842, "text": "Oracle search starts from left and moves rightwards until it finds a true condition, and then returns result expression associated with it. If no condition is found to be true, and an ELSE clause exists, then Oracle returns result defined with else. Otherwise, Oracle returns null." }, { "code": null, "e": 7484, "s": 7124, "text": "The maximum number of arguments in a CASE expression is 255. All expressions count toward this limit, including the initial expression of a simple CASE expression and the optional ELSE expression. Each WHEN ... THEN pair counts as two arguments. To avoid exceeding this limit, you can nest CASE expressions so that the return_expr itself is a CASE expression." }, { "code": null, "e": 7722, "s": 7484, "text": "SELECT first_name, CASE\tWHEN salary < 200 THEN 'GRADE 1'\n\t\t\tWHEN salary > 200 AND salary < 5000 THEN 'GRADE 2'\n\t\t\tELSE 'GRADE 3'\n\t\t END CASE\nFROM employees;\t\n\nENAM CASE\n---- -------\nJOHN GRADE 2\nEDWIN GRADE 3\nKING GRADE 1" }, { "code": null, "e": 7755, "s": 7722, "text": "\n 42 Lectures \n 5 hours \n" }, { "code": null, "e": 7769, "s": 7755, "text": " Anadi Sharma" }, { "code": null, "e": 7802, "s": 7769, "text": "\n 14 Lectures \n 2 hours \n" }, { "code": null, "e": 7816, "s": 7802, "text": " Anadi Sharma" }, { "code": null, "e": 7851, "s": 7816, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 7865, "s": 7851, "text": " Anadi Sharma" }, { "code": null, "e": 7898, "s": 7865, "text": "\n 94 Lectures \n 7 hours \n" }, { "code": null, "e": 7920, "s": 7898, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 7955, "s": 7920, "text": "\n 80 Lectures \n 6.5 hours \n" }, { "code": null, "e": 8009, "s": 7955, "text": " Oracle Master Training | 150,000+ Students Worldwide" }, { "code": null, "e": 8042, "s": 8009, "text": "\n 31 Lectures \n 6 hours \n" }, { "code": null, "e": 8070, "s": 8042, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 8077, "s": 8070, "text": " Print" }, { "code": null, "e": 8088, "s": 8077, "text": " Add Notes" } ]
How to handle a back button in an android activity?
This example demonstrates how do I handle back button in an android activity. 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:gravity = "center" android:layout_height = "match_parent" tools:context = ".MainActivity"> <TextView android:text= "My Activity" android:textSize = "30sp" android:layout_width = "match_parent" android:layout_height = "match_parent" android:layout_marginVertical="25sp" android:layout_margin="23dp"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Back to close the activity" android:id="@+id/button" android:layout_centerVertical="true" android:layout_margin="23dp"/> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.java import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="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 − Click here to download the project code.
[ { "code": null, "e": 1140, "s": 1062, "text": "This example demonstrates how do I handle back button in an android activity." }, { "code": null, "e": 1269, "s": 1140, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1334, "s": 1269, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2176, "s": 1334, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<RelativeLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:gravity = \"center\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\">\n <TextView\n android:text= \"My Activity\"\n android:textSize = \"30sp\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n android:layout_marginVertical=\"25sp\"\n android:layout_margin=\"23dp\"/>\n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Back to close the activity\"\n android:id=\"@+id/button\"\n android:layout_centerVertical=\"true\"\n android:layout_margin=\"23dp\"/>\n</RelativeLayout>" }, { "code": null, "e": 2233, "s": 2176, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 2804, "s": 2233, "text": "import android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.Button;\npublic class MainActivity extends AppCompatActivity {\n Button button;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n button = findViewById(R.id.button);\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n finish();\n }\n });\n }\n}" }, { "code": null, "e": 2859, "s": 2804, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 3529, "s": 2859, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 3875, "s": 3529, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 3916, "s": 3875, "text": "Click here to download the project code." } ]
Parametric and Non-Parametric Confidence Interval Estimation for Machine Learning in 3 Lines of Code | by Giovanni Ciampi | Jan, 2021 | Medium | Towards Data Science
[Edit 11/01/2021] Added better definition and adjusted the example in section 1 according to helpful suggestion by AlexMurphy. Confidence intervals are a great tool to provide useful information when reporting results of Machine Learning models. They are an easy and straightforward way of assessing, among other things, the reliability of a model. In this post, I am going to give a brief introduction to confidence intervals and to present confidence_interval_estimator_ML, a tool that will allow you to estimate confidence intervals both parametrically and non-parametrically for your machine learning models in few lines of code. Here is how this post is structured: Introduction to Confidence Intervals with Examples.Hidden Assumptions About Confidence Intervals.What are Parametric Confidence Intervals.What are Non-Parametric Confidence Intervals.How to Use the confidence_interval_estimator_ML to Compute Parametric and Non-Parametric Confidence Intervals. Introduction to Confidence Intervals with Examples. Hidden Assumptions About Confidence Intervals. What are Parametric Confidence Intervals. What are Non-Parametric Confidence Intervals. How to Use the confidence_interval_estimator_ML to Compute Parametric and Non-Parametric Confidence Intervals. Paraphrasing Wikipedia, confidence intervals indicate a range of plausible values for an unknown parameter p, with an associated degree of confidence indicating the degree of belief that the true p is contained that range. In the context of machine learning, confidence intervals are often estimated with respect to the performances of a model, and in particular with respect to the accuracy of a classification model. Given an experiment that aims at measuring a parameter p (in our case the accuracy of a model) a confidence interval I with an associated degree of confidence C% can be interpreted as follows: if the experiment is repeated N times, in C% of the outcomes p will be in the interval I. Although it might be tempting to do so, the degree of confidence cannot be technically interpreted as a probability, as discussed in the next section. Taking as an example the KERMIT paper presented at EMNLP2020, the authors state that their model has an accuracy of 85.91(±0.03) % on the Yelp Polarity dataset with a 95% degree of confidence. From this result, by re-running the model training and evaluation from scratch on the Yelp Polarity dataset 100 times (and changing the random seeds every time), we can expect that 95 times the accuracy will be in the range [85.88, 85.94]. The fact that the degree of confidence is high (95%) and the interval is relatively narrow indicates that in the given conditions, the KERMIT model is pretty robust! When computing statistics there always are some assumptions that tend to be hidden but can have a great deal of importance on the outcome. In the case of confidence intervals, in particular, in the context of machine learning, there are two main assumptions that, in my opinion, can be of crucial importance: the normality of data and the interpretation of the confidence degree. As regards the normality of data, it is assumed that the data sample was drawn from a normal distribution, and that the variance is therefore independent of the mean. This assumption can be problematic as the distribution of the data is often unknown. Now suppose that you want to estimate the confidence interval for the accuracy of model M on dataset D, you not only have to know the distribution of D, but it also has to be that this distribution is a Gaussian. Luckily, the Central Limit Theorem comes in handy, establishing that if the sample size is large enough, the data distribution tends to a normal distribution. Here the definition of large is dependent on several factors, but 30 is generally considered a good threshold for the size of the sample of data to be used for the evaluation of the model. In general though, as often in data science, the more data, the better. As regards the interpretation of the confidence degree, it is often implicitly assumed that the confidence degree represents the probability that a the true value p will fall in the confidence interval I. This is actually wrong, as the confidence degree refers to the reliability of the estimation procedure, as extensively discussed in this Wikipedia section. Anyway, from a practical standpoint, the confidence interval may be understood as an estimate of plausible values for the population parameter. Parametric estimation is a way to estimate the confidence intervals in closed form, from even a single result of your model. The formula to compute confidence intervals through parametric estimation is the following: where A is the accuracy of your model, N indicates the size of the sample on which A was computed and factor is a constant determined by the confidence degree and sample size. The aim of factor is to determine how wide the interval is. Generally speaking, a higher degree of confidence will lead to wider intervals. The source of this constant depends upon the sample size, and will be specified shortly. The value R represents the range of the interval, the interval will be therefore represented by I = [A-R, B+R]. As mentioned in point 2, parametric estimation assumes that the data sample was drawn from a normal distribution. Even though you don’t know the distribution of your data, if the sample size is bigger than 30 this is not a problem thanks to the central limit theorem. In this case, the factor parameter will be the z-score associated with the desired confidence degree. If your sample size is smaller than 30, then it is common practice to assume that the data was drawn from a t-student distribution with sample_size-1 degrees of freedom. Without going into too much detail, this assumption leads to wider confidence intervals, as the small sample size provides additional uncertainty. In this case, the factor parameter will be the t-score associated with the t-student distribution having N-1 degrees of freedom and the specified confidence degree. Non-Parametric confidence interval estimation is a way of estimating the confidence interval empirically. This method goes under several other names: Bootstrap Confidence Interval Estimation, Monte Carlo Confidence Interval Estimation, or simply Empirical Confidence Interval Estimation, but they all indicate the same thing. To estimate non-parametric confidence intervals for the accuracy of model M on dataset D, the model is trained and tested multiple times on samples of D. This is the algorithm to perform the estimation: The dataset D is sampled N times to obtain N datasets Di. This sampling is usually performed with replacement.Each sample Di is split in two separate sets Di_train and Di_test.For each Di, an instance Mi of the model is generated. Every instance Mi is evaluated on the corresponding data sample by performing training on Di_train and testing on Di_test. Let’s denote the list of test accuracies by A.The list of test accuracies A is sorted.Let’s denote the desired confidence-level by C; if we want the c.i. for 95% degree of confidence, C will be set to 95. Let’s denote by alpha the value 100-C. If the desired confidence level is C=95, alpha=100–95=5.The lower bound of the confidence interval is given by the alpha/2-th percentile of A, while the upper bound of the confidence interval is given by the C+(alpha/2)-th percentile.We can say that the confidence interval of model M on dataset D is [lower_bound, upper_bound] with a confidence degree of C%. The dataset D is sampled N times to obtain N datasets Di. This sampling is usually performed with replacement. Each sample Di is split in two separate sets Di_train and Di_test. For each Di, an instance Mi of the model is generated. Every instance Mi is evaluated on the corresponding data sample by performing training on Di_train and testing on Di_test. Let’s denote the list of test accuracies by A. The list of test accuracies A is sorted. Let’s denote the desired confidence-level by C; if we want the c.i. for 95% degree of confidence, C will be set to 95. Let’s denote by alpha the value 100-C. If the desired confidence level is C=95, alpha=100–95=5. The lower bound of the confidence interval is given by the alpha/2-th percentile of A, while the upper bound of the confidence interval is given by the C+(alpha/2)-th percentile. We can say that the confidence interval of model M on dataset D is [lower_bound, upper_bound] with a confidence degree of C%. Intuitively, we want to take lower_bound and upper_bound so that they cover C% of the elements of A, as it is shown in the following illustration. This way of computing confidence intervals challenges both of the assumptions we discussed in point 2 of this post. That is why, when computing confidence intervals non parametrically, it is of crucial importance to have both a large dataset and to use a large number of iterations to perform the estimate. At this point you should have a clear idea of how parametric and non-parametric estimation of confidence intervals work, so I will introduce confidence_interval_estimator_ML, a Python tool that will make the estimation process very simple and straightforward. It is easy to install this tool through pip in your command line: > pip install confidence_interval_estimator_ML Now it is pretty straightforward to perform the estimation: for the parametric case, you just need to import the library and run one line of code, as shown in the following example: In the presented example, the sample size used is bigger than 30, that is why the function specifies that it is assumed that the data is sampled from a normal distribution. The non-parametric case is slightly more complex, as you may need to specify a number of parameters for the estimation you intend to perform. Anyway, this is accomplished within two lines of code: The first line performs the first three steps of the algorithm presented at point 4 (it trains and validates instances of the model for a specified number of iterations), while the second line performs the remaining four points (computes the bounds of the confidence interval). The first function, get_accuracy_samples takes several input parameters: get_classifier_instance is a function that returns a new instance of the model by calling it. The returned model must provide fit and predict methods. A new instance of the model will be created at each iteration. model_params_dict is an optional parameter that allows you to specify parameters to be passed to the model constructor. X and y represent respectively the input and target of the model. sample_ratio indicates the size of the sample to be drawn at each iteration from (X, y). As an example, if (X, y) has 1000 data-points and sample_ratio is set to 0.70, at each iteration a dataset of 700 data-points will be sampled from (X, y). train_ratio specifies what ratio of the sampled dataset will be used for the training and testing of the model at each iteration. Following the example of the previous point, if (X, y) has 1000 data-points and sample_ratio=0.70, then at each iteration a dataset of 700 data-points will be sampled. If train_ratio=0.80, 560 data-points will be used to train the model while the remaining 140 will be used for the evaluation (to compute the test accuracy). The following code provides a more detailed example of the usage of the module. These methods provide other parameters and use cases that are not discussed here for the sake of brevity. If you want to explore all the possibilities offered by the confidence_interval_estimator_ML module, or you simply need more details to perform your estimates, you can check this Google Colab notebook, or simply the GitHub repo providing the code and the documentation. https://ocw.mit.edu/courses/mathematics/18-05-introduction-to-probability-and-statistics-spring-2014/readings/MIT18_05S14_Reading24.pdfhttps://sphweb.bumc.bu.edu/otlt/MPH-Modules/PH717-QuantCore/PH717-Module6-RandomError/PH717-Module6-RandomError11.htmlhttps://machinelearningmastery.com/report-classifier-performance-confidence-intervals/https://machinelearningmastery.com/confidence-intervals-for-machine-learning/#:~:text=Much%20of%20machine%20learning%20involves,the%20uncertainty%20of%20an%20estimate.&text=That%20a%20confidence%20interval%20is,estimate%20of%20a%20population%20parameter.http://www2.stat.duke.edu/~ar182/rr/examples-gallery/BootstrapConfidenceIntervals.html https://ocw.mit.edu/courses/mathematics/18-05-introduction-to-probability-and-statistics-spring-2014/readings/MIT18_05S14_Reading24.pdf https://sphweb.bumc.bu.edu/otlt/MPH-Modules/PH717-QuantCore/PH717-Module6-RandomError/PH717-Module6-RandomError11.html https://machinelearningmastery.com/report-classifier-performance-confidence-intervals/ https://machinelearningmastery.com/confidence-intervals-for-machine-learning/#:~:text=Much%20of%20machine%20learning%20involves,the%20uncertainty%20of%20an%20estimate.&text=That%20a%20confidence%20interval%20is,estimate%20of%20a%20population%20parameter. http://www2.stat.duke.edu/~ar182/rr/examples-gallery/BootstrapConfidenceIntervals.html If you liked this article, please don’t hesitate to connect on Linkedin!
[ { "code": null, "e": 298, "s": 171, "text": "[Edit 11/01/2021] Added better definition and adjusted the example in section 1 according to helpful suggestion by AlexMurphy." }, { "code": null, "e": 520, "s": 298, "text": "Confidence intervals are a great tool to provide useful information when reporting results of Machine Learning models. They are an easy and straightforward way of assessing, among other things, the reliability of a model." }, { "code": null, "e": 805, "s": 520, "text": "In this post, I am going to give a brief introduction to confidence intervals and to present confidence_interval_estimator_ML, a tool that will allow you to estimate confidence intervals both parametrically and non-parametrically for your machine learning models in few lines of code." }, { "code": null, "e": 842, "s": 805, "text": "Here is how this post is structured:" }, { "code": null, "e": 1136, "s": 842, "text": "Introduction to Confidence Intervals with Examples.Hidden Assumptions About Confidence Intervals.What are Parametric Confidence Intervals.What are Non-Parametric Confidence Intervals.How to Use the confidence_interval_estimator_ML to Compute Parametric and Non-Parametric Confidence Intervals." }, { "code": null, "e": 1188, "s": 1136, "text": "Introduction to Confidence Intervals with Examples." }, { "code": null, "e": 1235, "s": 1188, "text": "Hidden Assumptions About Confidence Intervals." }, { "code": null, "e": 1277, "s": 1235, "text": "What are Parametric Confidence Intervals." }, { "code": null, "e": 1323, "s": 1277, "text": "What are Non-Parametric Confidence Intervals." }, { "code": null, "e": 1434, "s": 1323, "text": "How to Use the confidence_interval_estimator_ML to Compute Parametric and Non-Parametric Confidence Intervals." }, { "code": null, "e": 1657, "s": 1434, "text": "Paraphrasing Wikipedia, confidence intervals indicate a range of plausible values for an unknown parameter p, with an associated degree of confidence indicating the degree of belief that the true p is contained that range." }, { "code": null, "e": 1853, "s": 1657, "text": "In the context of machine learning, confidence intervals are often estimated with respect to the performances of a model, and in particular with respect to the accuracy of a classification model." }, { "code": null, "e": 2136, "s": 1853, "text": "Given an experiment that aims at measuring a parameter p (in our case the accuracy of a model) a confidence interval I with an associated degree of confidence C% can be interpreted as follows: if the experiment is repeated N times, in C% of the outcomes p will be in the interval I." }, { "code": null, "e": 2287, "s": 2136, "text": "Although it might be tempting to do so, the degree of confidence cannot be technically interpreted as a probability, as discussed in the next section." }, { "code": null, "e": 2480, "s": 2287, "text": "Taking as an example the KERMIT paper presented at EMNLP2020, the authors state that their model has an accuracy of 85.91(±0.03) % on the Yelp Polarity dataset with a 95% degree of confidence." }, { "code": null, "e": 2886, "s": 2480, "text": "From this result, by re-running the model training and evaluation from scratch on the Yelp Polarity dataset 100 times (and changing the random seeds every time), we can expect that 95 times the accuracy will be in the range [85.88, 85.94]. The fact that the degree of confidence is high (95%) and the interval is relatively narrow indicates that in the given conditions, the KERMIT model is pretty robust!" }, { "code": null, "e": 3266, "s": 2886, "text": "When computing statistics there always are some assumptions that tend to be hidden but can have a great deal of importance on the outcome. In the case of confidence intervals, in particular, in the context of machine learning, there are two main assumptions that, in my opinion, can be of crucial importance: the normality of data and the interpretation of the confidence degree." }, { "code": null, "e": 3518, "s": 3266, "text": "As regards the normality of data, it is assumed that the data sample was drawn from a normal distribution, and that the variance is therefore independent of the mean. This assumption can be problematic as the distribution of the data is often unknown." }, { "code": null, "e": 4151, "s": 3518, "text": "Now suppose that you want to estimate the confidence interval for the accuracy of model M on dataset D, you not only have to know the distribution of D, but it also has to be that this distribution is a Gaussian. Luckily, the Central Limit Theorem comes in handy, establishing that if the sample size is large enough, the data distribution tends to a normal distribution. Here the definition of large is dependent on several factors, but 30 is generally considered a good threshold for the size of the sample of data to be used for the evaluation of the model. In general though, as often in data science, the more data, the better." }, { "code": null, "e": 4656, "s": 4151, "text": "As regards the interpretation of the confidence degree, it is often implicitly assumed that the confidence degree represents the probability that a the true value p will fall in the confidence interval I. This is actually wrong, as the confidence degree refers to the reliability of the estimation procedure, as extensively discussed in this Wikipedia section. Anyway, from a practical standpoint, the confidence interval may be understood as an estimate of plausible values for the population parameter." }, { "code": null, "e": 4873, "s": 4656, "text": "Parametric estimation is a way to estimate the confidence intervals in closed form, from even a single result of your model. The formula to compute confidence intervals through parametric estimation is the following:" }, { "code": null, "e": 5278, "s": 4873, "text": "where A is the accuracy of your model, N indicates the size of the sample on which A was computed and factor is a constant determined by the confidence degree and sample size. The aim of factor is to determine how wide the interval is. Generally speaking, a higher degree of confidence will lead to wider intervals. The source of this constant depends upon the sample size, and will be specified shortly." }, { "code": null, "e": 5390, "s": 5278, "text": "The value R represents the range of the interval, the interval will be therefore represented by I = [A-R, B+R]." }, { "code": null, "e": 5760, "s": 5390, "text": "As mentioned in point 2, parametric estimation assumes that the data sample was drawn from a normal distribution. Even though you don’t know the distribution of your data, if the sample size is bigger than 30 this is not a problem thanks to the central limit theorem. In this case, the factor parameter will be the z-score associated with the desired confidence degree." }, { "code": null, "e": 6242, "s": 5760, "text": "If your sample size is smaller than 30, then it is common practice to assume that the data was drawn from a t-student distribution with sample_size-1 degrees of freedom. Without going into too much detail, this assumption leads to wider confidence intervals, as the small sample size provides additional uncertainty. In this case, the factor parameter will be the t-score associated with the t-student distribution having N-1 degrees of freedom and the specified confidence degree." }, { "code": null, "e": 6568, "s": 6242, "text": "Non-Parametric confidence interval estimation is a way of estimating the confidence interval empirically. This method goes under several other names: Bootstrap Confidence Interval Estimation, Monte Carlo Confidence Interval Estimation, or simply Empirical Confidence Interval Estimation, but they all indicate the same thing." }, { "code": null, "e": 6771, "s": 6568, "text": "To estimate non-parametric confidence intervals for the accuracy of model M on dataset D, the model is trained and tested multiple times on samples of D. This is the algorithm to perform the estimation:" }, { "code": null, "e": 7729, "s": 6771, "text": "The dataset D is sampled N times to obtain N datasets Di. This sampling is usually performed with replacement.Each sample Di is split in two separate sets Di_train and Di_test.For each Di, an instance Mi of the model is generated. Every instance Mi is evaluated on the corresponding data sample by performing training on Di_train and testing on Di_test. Let’s denote the list of test accuracies by A.The list of test accuracies A is sorted.Let’s denote the desired confidence-level by C; if we want the c.i. for 95% degree of confidence, C will be set to 95. Let’s denote by alpha the value 100-C. If the desired confidence level is C=95, alpha=100–95=5.The lower bound of the confidence interval is given by the alpha/2-th percentile of A, while the upper bound of the confidence interval is given by the C+(alpha/2)-th percentile.We can say that the confidence interval of model M on dataset D is [lower_bound, upper_bound] with a confidence degree of C%." }, { "code": null, "e": 7840, "s": 7729, "text": "The dataset D is sampled N times to obtain N datasets Di. This sampling is usually performed with replacement." }, { "code": null, "e": 7907, "s": 7840, "text": "Each sample Di is split in two separate sets Di_train and Di_test." }, { "code": null, "e": 8132, "s": 7907, "text": "For each Di, an instance Mi of the model is generated. Every instance Mi is evaluated on the corresponding data sample by performing training on Di_train and testing on Di_test. Let’s denote the list of test accuracies by A." }, { "code": null, "e": 8173, "s": 8132, "text": "The list of test accuracies A is sorted." }, { "code": null, "e": 8388, "s": 8173, "text": "Let’s denote the desired confidence-level by C; if we want the c.i. for 95% degree of confidence, C will be set to 95. Let’s denote by alpha the value 100-C. If the desired confidence level is C=95, alpha=100–95=5." }, { "code": null, "e": 8567, "s": 8388, "text": "The lower bound of the confidence interval is given by the alpha/2-th percentile of A, while the upper bound of the confidence interval is given by the C+(alpha/2)-th percentile." }, { "code": null, "e": 8693, "s": 8567, "text": "We can say that the confidence interval of model M on dataset D is [lower_bound, upper_bound] with a confidence degree of C%." }, { "code": null, "e": 8840, "s": 8693, "text": "Intuitively, we want to take lower_bound and upper_bound so that they cover C% of the elements of A, as it is shown in the following illustration." }, { "code": null, "e": 9147, "s": 8840, "text": "This way of computing confidence intervals challenges both of the assumptions we discussed in point 2 of this post. That is why, when computing confidence intervals non parametrically, it is of crucial importance to have both a large dataset and to use a large number of iterations to perform the estimate." }, { "code": null, "e": 9407, "s": 9147, "text": "At this point you should have a clear idea of how parametric and non-parametric estimation of confidence intervals work, so I will introduce confidence_interval_estimator_ML, a Python tool that will make the estimation process very simple and straightforward." }, { "code": null, "e": 9473, "s": 9407, "text": "It is easy to install this tool through pip in your command line:" }, { "code": null, "e": 9520, "s": 9473, "text": "> pip install confidence_interval_estimator_ML" }, { "code": null, "e": 9702, "s": 9520, "text": "Now it is pretty straightforward to perform the estimation: for the parametric case, you just need to import the library and run one line of code, as shown in the following example:" }, { "code": null, "e": 9875, "s": 9702, "text": "In the presented example, the sample size used is bigger than 30, that is why the function specifies that it is assumed that the data is sampled from a normal distribution." }, { "code": null, "e": 10072, "s": 9875, "text": "The non-parametric case is slightly more complex, as you may need to specify a number of parameters for the estimation you intend to perform. Anyway, this is accomplished within two lines of code:" }, { "code": null, "e": 10350, "s": 10072, "text": "The first line performs the first three steps of the algorithm presented at point 4 (it trains and validates instances of the model for a specified number of iterations), while the second line performs the remaining four points (computes the bounds of the confidence interval)." }, { "code": null, "e": 10423, "s": 10350, "text": "The first function, get_accuracy_samples takes several input parameters:" }, { "code": null, "e": 10637, "s": 10423, "text": "get_classifier_instance is a function that returns a new instance of the model by calling it. The returned model must provide fit and predict methods. A new instance of the model will be created at each iteration." }, { "code": null, "e": 10757, "s": 10637, "text": "model_params_dict is an optional parameter that allows you to specify parameters to be passed to the model constructor." }, { "code": null, "e": 10823, "s": 10757, "text": "X and y represent respectively the input and target of the model." }, { "code": null, "e": 11067, "s": 10823, "text": "sample_ratio indicates the size of the sample to be drawn at each iteration from (X, y). As an example, if (X, y) has 1000 data-points and sample_ratio is set to 0.70, at each iteration a dataset of 700 data-points will be sampled from (X, y)." }, { "code": null, "e": 11522, "s": 11067, "text": "train_ratio specifies what ratio of the sampled dataset will be used for the training and testing of the model at each iteration. Following the example of the previous point, if (X, y) has 1000 data-points and sample_ratio=0.70, then at each iteration a dataset of 700 data-points will be sampled. If train_ratio=0.80, 560 data-points will be used to train the model while the remaining 140 will be used for the evaluation (to compute the test accuracy)." }, { "code": null, "e": 11602, "s": 11522, "text": "The following code provides a more detailed example of the usage of the module." }, { "code": null, "e": 11978, "s": 11602, "text": "These methods provide other parameters and use cases that are not discussed here for the sake of brevity. If you want to explore all the possibilities offered by the confidence_interval_estimator_ML module, or you simply need more details to perform your estimates, you can check this Google Colab notebook, or simply the GitHub repo providing the code and the documentation." }, { "code": null, "e": 12658, "s": 11978, "text": "https://ocw.mit.edu/courses/mathematics/18-05-introduction-to-probability-and-statistics-spring-2014/readings/MIT18_05S14_Reading24.pdfhttps://sphweb.bumc.bu.edu/otlt/MPH-Modules/PH717-QuantCore/PH717-Module6-RandomError/PH717-Module6-RandomError11.htmlhttps://machinelearningmastery.com/report-classifier-performance-confidence-intervals/https://machinelearningmastery.com/confidence-intervals-for-machine-learning/#:~:text=Much%20of%20machine%20learning%20involves,the%20uncertainty%20of%20an%20estimate.&text=That%20a%20confidence%20interval%20is,estimate%20of%20a%20population%20parameter.http://www2.stat.duke.edu/~ar182/rr/examples-gallery/BootstrapConfidenceIntervals.html" }, { "code": null, "e": 12794, "s": 12658, "text": "https://ocw.mit.edu/courses/mathematics/18-05-introduction-to-probability-and-statistics-spring-2014/readings/MIT18_05S14_Reading24.pdf" }, { "code": null, "e": 12913, "s": 12794, "text": "https://sphweb.bumc.bu.edu/otlt/MPH-Modules/PH717-QuantCore/PH717-Module6-RandomError/PH717-Module6-RandomError11.html" }, { "code": null, "e": 13000, "s": 12913, "text": "https://machinelearningmastery.com/report-classifier-performance-confidence-intervals/" }, { "code": null, "e": 13255, "s": 13000, "text": "https://machinelearningmastery.com/confidence-intervals-for-machine-learning/#:~:text=Much%20of%20machine%20learning%20involves,the%20uncertainty%20of%20an%20estimate.&text=That%20a%20confidence%20interval%20is,estimate%20of%20a%20population%20parameter." }, { "code": null, "e": 13342, "s": 13255, "text": "http://www2.stat.duke.edu/~ar182/rr/examples-gallery/BootstrapConfidenceIntervals.html" } ]
Count of cells in a matrix whose adjacent cells's sum is prime Number - GeeksforGeeks
30 Mar, 2022 Given a M x N matrix mat[][], the task is to count the number of cells which have the sum of its adjacent cells equal to a prime number. For a cell x[i][j], only x[i+1][j], x[i-1][j], x[i][j+1] and x[i][j-1] are the adjacent cells.Examples: Input : mat[][] = {{1, 3}, {2, 5}} Output :2 Explanation: Only the cells mat[0][0] and mat[1][1] satisfying the condition. i.e for mat[0][0]:(3+2) = 5, for mat[1][1]: (3+2) = 5Input : mat[][] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}} Output : 6 Explanation: Cells mat[0][0], mat[0][2], mat[0][3], mat[1][3], mat[2][2] and mat[2][3] are satisfying the condition. Prerequisites: Sieve of Eratosthenes Approach: Precompute and store the prime numbers using Sieve. Iterate the entire matrix and for each cell find the sum of all adjacent cells. If the sum of adjacent cells equal to a prime number then increments the count. Return the value of the count. Below is the implementation of the above approach. C++ Java Python3 C# Javascript // CPP program to find the cells whose// adjacent cells's sum is prime Number#include <bits/stdc++.h>using namespace std;#define MAX 100005 bool prime[MAX]; void SieveOfEratosthenes(){ // Create a boolean array "prime[0..MAX-1]" // and initialize all entries it as true. // A value in prime[i] will finally // be false if i is Not a prime, else true. memset(prime, true, sizeof(prime)); prime[0] = prime[1] = false; for (int p = 2; p * p < MAX; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p // greater than or // equal to the square of it // numbers which are multiple of p and are // less than p^2 are already been marked. for (int i = p * p; i < MAX; i += p) prime[i] = false; } }} // Function to count the cells having// adjacent cell's sum// is equal to primeint PrimeSumCells(vector<vector<int> >& mat){ int count = 0; int N = mat.size(); int M = mat[0].size(); // Traverse for all the cells for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { int sum = 0; // i-1, j if (i - 1 >= 0) sum += mat[i - 1][j]; // i+1, j if (i + 1 < N) sum += mat[i + 1][j]; // i, j-1 if (j - 1 >= 0) sum += mat[i][j - 1]; // i, j+1 if (j + 1 < M) sum += mat[i][j + 1]; // If the sum is a prime number if (prime[sum]) count++; } } // Return the count return count;} // Driver Programint main(){ SieveOfEratosthenes(); vector<vector<int> > mat = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; // Function call cout << PrimeSumCells(mat) << endl;} // Java program to find the cells whose// adjacent cells's sum is prime Numberclass GFG{static final int MAX = 100005; static boolean []prime = new boolean[MAX]; static void SieveOfEratosthenes(){ // Create a boolean array "prime[0..MAX-1]" // and initialize all entries it as true. // A value in prime[i] will finally // be false if i is Not a prime, else true. for (int i = 0; i < prime.length; i++) prime[i] = true; prime[0] = prime[1] = false; for (int p = 2; p * p < MAX; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p // greater than or // equal to the square of it // numbers which are multiple of p and are // less than p^2 are already been marked. for (int i = p * p; i < MAX; i += p) prime[i] = false; } }} // Function to count the cells having// adjacent cell's sum// is equal to primestatic int PrimeSumCells(int [][]mat){ int count = 0; int N = mat.length; int M = mat[0].length; // Traverse for all the cells for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { int sum = 0; // i-1, j if (i - 1 >= 0) sum += mat[i - 1][j]; // i+1, j if (i + 1 < N) sum += mat[i + 1][j]; // i, j-1 if (j - 1 >= 0) sum += mat[i][j - 1]; // i, j+1 if (j + 1 < M) sum += mat[i][j + 1]; // If the sum is a prime number if (prime[sum]) count++; } } // Return the count return count;} // Driver Codepublic static void main(String[] args){ SieveOfEratosthenes(); int [][]mat = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; // Function call System.out.print(PrimeSumCells(mat) + "\n");}} // This code is contributed by sapnasingh4991 # Python 3 program to# find the cells whose# adjacent cells's# sum is prime NumberMAX = 100005prime = [True] * MAX def SieveOfEratosthenes(): # Create a boolean array "prime[0..MAX-1]" # and initialize all entries it as true. # A value in prime[i] will finally # be false if i is Not a prime, else true. global prime prime[0] = prime[1] = False p = 2 while p * p < MAX: # If prime[p] is not changed, # then it is a prime if (prime[p] == True): # Update all multiples of p # greater than or # equal to the square of it # numbers which are multiple of # p and are less than p^2 are # already been marked. for i in range (p * p, MAX, p): prime[i] = False p += 1 # Function to count the# cells having adjacent# cell's sum is equal to primedef PrimeSumCells(mat): count = 0 N = len(mat) M = len(mat[0]) # Traverse for all the cells for i in range (N): for j in range (M): sum = 0 # i - 1, j if (i - 1 >= 0): sum += mat[i - 1][j] # i + 1, j if (i + 1 < N): sum += mat[i + 1][j] # i, j - 1 if (j - 1 >= 0): sum += mat[i][j - 1] # i, j + 1 if (j + 1 < M): sum += mat[i][j + 1] # If the sum is a prime number if (prime[sum]): count += 1 # Return the count return count # Driver codeif __name__ =="__main__": SieveOfEratosthenes() mat = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] # Function call print (PrimeSumCells(mat)) # This code is contributed by Chitranayal // C# program to find the cells whose// adjacent cells's sum is prime Numberusing System;class GFG{ static readonly int MAX = 100005;static bool []prime = new bool[MAX]; static void SieveOfEratosthenes(){ // Create a bool array "prime[0..MAX-1]" // and initialize all entries it as true. // A value in prime[i] will finally // be false if i is Not a prime, else true. for (int i = 0; i < prime.Length; i++) prime[i] = true; prime[0] = prime[1] = false; for (int p = 2; p * p < MAX; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p // greater than or // equal to the square of it // numbers which are multiple of p and are // less than p^2 are already been marked. for (int i = p * p; i < MAX; i += p) prime[i] = false; } }} // Function to count the cells having// adjacent cell's sum// is equal to primestatic int PrimeSumCells(int [,]mat){ int count = 0; int N = mat.GetLength(0); int M = mat.GetLength(1); // Traverse for all the cells for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { int sum = 0; // i-1, j if (i - 1 >= 0) sum += mat[i - 1, j]; // i+1, j if (i + 1 < N) sum += mat[i + 1, j]; // i, j-1 if (j - 1 >= 0) sum += mat[i, j - 1]; // i, j+1 if (j + 1 < M) sum += mat[i, j + 1]; // If the sum is a prime number if (prime[sum]) count++; } } // Return the count return count;} // Driver Codepublic static void Main(String[] args){ SieveOfEratosthenes(); int [,]mat = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; // Function call Console.Write(PrimeSumCells(mat) + "\n");}} // This code is contributed by sapnasingh4991 <script>// Javascript program to find the cells whose// adjacent cells's sum is prime Number let MAX = 100005 let prime = new Array(MAX); function SieveOfEratosthenes(){ // Create a boolean array "prime[0..MAX-1]" // and initialize all entries it as true. // A value in prime[i] will finally // be false if i is Not a prime, else true. prime.fill(true) prime[0] = prime[1] = false; for (let p = 2; p * p < MAX; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p // greater than or // equal to the square of it // numbers which are multiple of p and are // less than p^2 are already been marked. for (let i = p * p; i < MAX; i += p) prime[i] = false; } }} // Function to count the cells having// adjacent cell's sum// is equal to primefunction PrimeSumCells(mat){ let count = 0; let N = mat.length; let M = mat[0].length; // Traverse for all the cells for (let i = 0; i < N; i++) { for (let j = 0; j < M; j++) { let sum = 0; // i-1, j if (i - 1 >= 0) sum += mat[i - 1][j]; // i+1, j if (i + 1 < N) sum += mat[i + 1][j]; // i, j-1 if (j - 1 >= 0) sum += mat[i][j - 1]; // i, j+1 if (j + 1 < M) sum += mat[i][j + 1]; // If the sum is a prime number if (prime[sum]) count++; } } // Return the count return count;} // Driver Program SieveOfEratosthenes(); let mat = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ] ]; // Function call document.write(PrimeSumCells(mat) + "<br>"); // This code is contributed by gfgking </script> 6 Time Complexity: O(N*M) Auxiliary Space: O(MAX) sapnasingh4991 ukasp gfgking rohan07 Prime Number sieve Competitive Programming Matrix Prime Number Matrix sieve Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Breadth First Traversal ( BFS ) on a 2D array Runtime Errors Most important type of Algorithms Multistage Graph (Shortest Path) Shortest path in a directed graph by Dijkstra’s algorithm Matrix Chain Multiplication | DP-8 Program to find largest element in an array Print a given matrix in spiral form Sudoku | Backtracking-7 Rat in a Maze | Backtracking-2
[ { "code": null, "e": 24711, "s": 24683, "text": "\n30 Mar, 2022" }, { "code": null, "e": 24953, "s": 24711, "text": "Given a M x N matrix mat[][], the task is to count the number of cells which have the sum of its adjacent cells equal to a prime number. For a cell x[i][j], only x[i+1][j], x[i-1][j], x[i][j+1] and x[i][j-1] are the adjacent cells.Examples: " }, { "code": null, "e": 25323, "s": 24953, "text": "Input : mat[][] = {{1, 3}, {2, 5}} Output :2 Explanation: Only the cells mat[0][0] and mat[1][1] satisfying the condition. i.e for mat[0][0]:(3+2) = 5, for mat[1][1]: (3+2) = 5Input : mat[][] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}} Output : 6 Explanation: Cells mat[0][0], mat[0][2], mat[0][3], mat[1][3], mat[2][2] and mat[2][3] are satisfying the condition. " }, { "code": null, "e": 25372, "s": 25323, "text": "Prerequisites: Sieve of Eratosthenes Approach: " }, { "code": null, "e": 25424, "s": 25372, "text": "Precompute and store the prime numbers using Sieve." }, { "code": null, "e": 25504, "s": 25424, "text": "Iterate the entire matrix and for each cell find the sum of all adjacent cells." }, { "code": null, "e": 25584, "s": 25504, "text": "If the sum of adjacent cells equal to a prime number then increments the count." }, { "code": null, "e": 25615, "s": 25584, "text": "Return the value of the count." }, { "code": null, "e": 25667, "s": 25615, "text": "Below is the implementation of the above approach. " }, { "code": null, "e": 25671, "s": 25667, "text": "C++" }, { "code": null, "e": 25676, "s": 25671, "text": "Java" }, { "code": null, "e": 25684, "s": 25676, "text": "Python3" }, { "code": null, "e": 25687, "s": 25684, "text": "C#" }, { "code": null, "e": 25698, "s": 25687, "text": "Javascript" }, { "code": "// CPP program to find the cells whose// adjacent cells's sum is prime Number#include <bits/stdc++.h>using namespace std;#define MAX 100005 bool prime[MAX]; void SieveOfEratosthenes(){ // Create a boolean array \"prime[0..MAX-1]\" // and initialize all entries it as true. // A value in prime[i] will finally // be false if i is Not a prime, else true. memset(prime, true, sizeof(prime)); prime[0] = prime[1] = false; for (int p = 2; p * p < MAX; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p // greater than or // equal to the square of it // numbers which are multiple of p and are // less than p^2 are already been marked. for (int i = p * p; i < MAX; i += p) prime[i] = false; } }} // Function to count the cells having// adjacent cell's sum// is equal to primeint PrimeSumCells(vector<vector<int> >& mat){ int count = 0; int N = mat.size(); int M = mat[0].size(); // Traverse for all the cells for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { int sum = 0; // i-1, j if (i - 1 >= 0) sum += mat[i - 1][j]; // i+1, j if (i + 1 < N) sum += mat[i + 1][j]; // i, j-1 if (j - 1 >= 0) sum += mat[i][j - 1]; // i, j+1 if (j + 1 < M) sum += mat[i][j + 1]; // If the sum is a prime number if (prime[sum]) count++; } } // Return the count return count;} // Driver Programint main(){ SieveOfEratosthenes(); vector<vector<int> > mat = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; // Function call cout << PrimeSumCells(mat) << endl;}", "e": 27665, "s": 25698, "text": null }, { "code": "// Java program to find the cells whose// adjacent cells's sum is prime Numberclass GFG{static final int MAX = 100005; static boolean []prime = new boolean[MAX]; static void SieveOfEratosthenes(){ // Create a boolean array \"prime[0..MAX-1]\" // and initialize all entries it as true. // A value in prime[i] will finally // be false if i is Not a prime, else true. for (int i = 0; i < prime.length; i++) prime[i] = true; prime[0] = prime[1] = false; for (int p = 2; p * p < MAX; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p // greater than or // equal to the square of it // numbers which are multiple of p and are // less than p^2 are already been marked. for (int i = p * p; i < MAX; i += p) prime[i] = false; } }} // Function to count the cells having// adjacent cell's sum// is equal to primestatic int PrimeSumCells(int [][]mat){ int count = 0; int N = mat.length; int M = mat[0].length; // Traverse for all the cells for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { int sum = 0; // i-1, j if (i - 1 >= 0) sum += mat[i - 1][j]; // i+1, j if (i + 1 < N) sum += mat[i + 1][j]; // i, j-1 if (j - 1 >= 0) sum += mat[i][j - 1]; // i, j+1 if (j + 1 < M) sum += mat[i][j + 1]; // If the sum is a prime number if (prime[sum]) count++; } } // Return the count return count;} // Driver Codepublic static void main(String[] args){ SieveOfEratosthenes(); int [][]mat = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; // Function call System.out.print(PrimeSumCells(mat) + \"\\n\");}} // This code is contributed by sapnasingh4991", "e": 29721, "s": 27665, "text": null }, { "code": "# Python 3 program to# find the cells whose# adjacent cells's# sum is prime NumberMAX = 100005prime = [True] * MAX def SieveOfEratosthenes(): # Create a boolean array \"prime[0..MAX-1]\" # and initialize all entries it as true. # A value in prime[i] will finally # be false if i is Not a prime, else true. global prime prime[0] = prime[1] = False p = 2 while p * p < MAX: # If prime[p] is not changed, # then it is a prime if (prime[p] == True): # Update all multiples of p # greater than or # equal to the square of it # numbers which are multiple of # p and are less than p^2 are # already been marked. for i in range (p * p, MAX, p): prime[i] = False p += 1 # Function to count the# cells having adjacent# cell's sum is equal to primedef PrimeSumCells(mat): count = 0 N = len(mat) M = len(mat[0]) # Traverse for all the cells for i in range (N): for j in range (M): sum = 0 # i - 1, j if (i - 1 >= 0): sum += mat[i - 1][j] # i + 1, j if (i + 1 < N): sum += mat[i + 1][j] # i, j - 1 if (j - 1 >= 0): sum += mat[i][j - 1] # i, j + 1 if (j + 1 < M): sum += mat[i][j + 1] # If the sum is a prime number if (prime[sum]): count += 1 # Return the count return count # Driver codeif __name__ ==\"__main__\": SieveOfEratosthenes() mat = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] # Function call print (PrimeSumCells(mat)) # This code is contributed by Chitranayal", "e": 31549, "s": 29721, "text": null }, { "code": "// C# program to find the cells whose// adjacent cells's sum is prime Numberusing System;class GFG{ static readonly int MAX = 100005;static bool []prime = new bool[MAX]; static void SieveOfEratosthenes(){ // Create a bool array \"prime[0..MAX-1]\" // and initialize all entries it as true. // A value in prime[i] will finally // be false if i is Not a prime, else true. for (int i = 0; i < prime.Length; i++) prime[i] = true; prime[0] = prime[1] = false; for (int p = 2; p * p < MAX; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p // greater than or // equal to the square of it // numbers which are multiple of p and are // less than p^2 are already been marked. for (int i = p * p; i < MAX; i += p) prime[i] = false; } }} // Function to count the cells having// adjacent cell's sum// is equal to primestatic int PrimeSumCells(int [,]mat){ int count = 0; int N = mat.GetLength(0); int M = mat.GetLength(1); // Traverse for all the cells for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { int sum = 0; // i-1, j if (i - 1 >= 0) sum += mat[i - 1, j]; // i+1, j if (i + 1 < N) sum += mat[i + 1, j]; // i, j-1 if (j - 1 >= 0) sum += mat[i, j - 1]; // i, j+1 if (j + 1 < M) sum += mat[i, j + 1]; // If the sum is a prime number if (prime[sum]) count++; } } // Return the count return count;} // Driver Codepublic static void Main(String[] args){ SieveOfEratosthenes(); int [,]mat = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; // Function call Console.Write(PrimeSumCells(mat) + \"\\n\");}} // This code is contributed by sapnasingh4991", "e": 33616, "s": 31549, "text": null }, { "code": "<script>// Javascript program to find the cells whose// adjacent cells's sum is prime Number let MAX = 100005 let prime = new Array(MAX); function SieveOfEratosthenes(){ // Create a boolean array \"prime[0..MAX-1]\" // and initialize all entries it as true. // A value in prime[i] will finally // be false if i is Not a prime, else true. prime.fill(true) prime[0] = prime[1] = false; for (let p = 2; p * p < MAX; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p // greater than or // equal to the square of it // numbers which are multiple of p and are // less than p^2 are already been marked. for (let i = p * p; i < MAX; i += p) prime[i] = false; } }} // Function to count the cells having// adjacent cell's sum// is equal to primefunction PrimeSumCells(mat){ let count = 0; let N = mat.length; let M = mat[0].length; // Traverse for all the cells for (let i = 0; i < N; i++) { for (let j = 0; j < M; j++) { let sum = 0; // i-1, j if (i - 1 >= 0) sum += mat[i - 1][j]; // i+1, j if (i + 1 < N) sum += mat[i + 1][j]; // i, j-1 if (j - 1 >= 0) sum += mat[i][j - 1]; // i, j+1 if (j + 1 < M) sum += mat[i][j + 1]; // If the sum is a prime number if (prime[sum]) count++; } } // Return the count return count;} // Driver Program SieveOfEratosthenes(); let mat = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ] ]; // Function call document.write(PrimeSumCells(mat) + \"<br>\"); // This code is contributed by gfgking </script>", "e": 35559, "s": 33616, "text": null }, { "code": null, "e": 35561, "s": 35559, "text": "6" }, { "code": null, "e": 35587, "s": 35563, "text": "Time Complexity: O(N*M)" }, { "code": null, "e": 35611, "s": 35587, "text": "Auxiliary Space: O(MAX)" }, { "code": null, "e": 35626, "s": 35611, "text": "sapnasingh4991" }, { "code": null, "e": 35632, "s": 35626, "text": "ukasp" }, { "code": null, "e": 35640, "s": 35632, "text": "gfgking" }, { "code": null, "e": 35648, "s": 35640, "text": "rohan07" }, { "code": null, "e": 35661, "s": 35648, "text": "Prime Number" }, { "code": null, "e": 35667, "s": 35661, "text": "sieve" }, { "code": null, "e": 35691, "s": 35667, "text": "Competitive Programming" }, { "code": null, "e": 35698, "s": 35691, "text": "Matrix" }, { "code": null, "e": 35711, "s": 35698, "text": "Prime Number" }, { "code": null, "e": 35718, "s": 35711, "text": "Matrix" }, { "code": null, "e": 35724, "s": 35718, "text": "sieve" }, { "code": null, "e": 35822, "s": 35724, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35831, "s": 35822, "text": "Comments" }, { "code": null, "e": 35844, "s": 35831, "text": "Old Comments" }, { "code": null, "e": 35890, "s": 35844, "text": "Breadth First Traversal ( BFS ) on a 2D array" }, { "code": null, "e": 35905, "s": 35890, "text": "Runtime Errors" }, { "code": null, "e": 35939, "s": 35905, "text": "Most important type of Algorithms" }, { "code": null, "e": 35972, "s": 35939, "text": "Multistage Graph (Shortest Path)" }, { "code": null, "e": 36030, "s": 35972, "text": "Shortest path in a directed graph by Dijkstra’s algorithm" }, { "code": null, "e": 36065, "s": 36030, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 36109, "s": 36065, "text": "Program to find largest element in an array" }, { "code": null, "e": 36145, "s": 36109, "text": "Print a given matrix in spiral form" }, { "code": null, "e": 36169, "s": 36145, "text": "Sudoku | Backtracking-7" } ]
Store unicode in a char variable in Java
To store Unicode in a char variable, simply create a char variable. char c; Now assign unicode. char c = '\u00AB'; The following is the complete example that shows what will get displayed: when Unicode is stored in a char variable and displayed. Live Demo public class Demo { public static void main(String []args) { int a = 79; System.out.println(a); char b = (char) a; System.out.println(b); char c = '\u00AB'; System.out.println(c); } } 79 O «
[ { "code": null, "e": 1130, "s": 1062, "text": "To store Unicode in a char variable, simply create a char variable." }, { "code": null, "e": 1138, "s": 1130, "text": "char c;" }, { "code": null, "e": 1158, "s": 1138, "text": "Now assign unicode." }, { "code": null, "e": 1177, "s": 1158, "text": "char c = '\\u00AB';" }, { "code": null, "e": 1308, "s": 1177, "text": "The following is the complete example that shows what will get displayed: when Unicode is stored in a char variable and displayed." }, { "code": null, "e": 1319, "s": 1308, "text": " Live Demo" }, { "code": null, "e": 1545, "s": 1319, "text": "public class Demo {\n public static void main(String []args) {\n int a = 79;\n System.out.println(a);\n char b = (char) a;\n System.out.println(b);\n char c = '\\u00AB';\n System.out.println(c);\n }\n}" }, { "code": null, "e": 1552, "s": 1545, "text": "79\nO\n«" } ]
How to Change Tkinter Frame Title?
Tkinter window is the native component of tkinter application that contains some frames, a group of widgets, and some other elements. A Tkinter frame has a group of too many widgets. Let us suppose that we have created a frame with some widgets and now we want to rename the title of the application. Frame titles are a necessary part of any application. We can change the title of the frame using the title("title") method. In this example, we will create an application that will contain an entry widget and a button. The button is used to rename the title of the window. Initially, we will create an instance of StringVar() and this can be used to capture the user input in the Entry widget. Then, by using the set() method, we will pass the captured variable to set the title of the frame. #Import tkinter library from tkinter import * #Create an instance of tkinter frame win= Tk() #Set the Geometry win.geometry("750x250") #Define a Variable to accept the input var= StringVar() #Define a function to change the title def change_title(): win.title(var.get()) #Create an Entry widget text=Entry(win,textvariable=var) text.focus_set() text.pack(pady=20) #Pass the title in the function var.set(win.title()) #Create a Button Button(win, text= "Change", command= change_title).pack(pady=20) win.mainloop() By running the above code, we can display a window that contains a button and the frame object. Now, whenever we write some title in the entry widget and click the “Change” button, it will change the title of the frame. Now, change the title of the frame by writing some text in the Entry widget and click the “Change” to display the reflected output.
[ { "code": null, "e": 1245, "s": 1062, "text": "Tkinter window is the native component of tkinter application that contains some frames, a group of widgets, and some other elements. A Tkinter frame has a group of too many widgets." }, { "code": null, "e": 1487, "s": 1245, "text": "Let us suppose that we have created a frame with some widgets and now we want to rename the title of the application. Frame titles are a necessary part of any application. We can change the title of the frame using the title(\"title\") method." }, { "code": null, "e": 1856, "s": 1487, "text": "In this example, we will create an application that will contain an entry widget and a button. The button is used to rename the title of the window. Initially, we will create an instance of StringVar() and this can be used to capture the user input in the Entry widget. Then, by using the set() method, we will pass the captured variable to set the title of the frame." }, { "code": null, "e": 2370, "s": 1856, "text": "#Import tkinter library\nfrom tkinter import *\n#Create an instance of tkinter frame\nwin= Tk()\n#Set the Geometry\nwin.geometry(\"750x250\")\n#Define a Variable to accept the input\nvar= StringVar()\n#Define a function to change the title\ndef change_title():\nwin.title(var.get())\n#Create an Entry widget\ntext=Entry(win,textvariable=var)\ntext.focus_set()\ntext.pack(pady=20)\n#Pass the title in the function\nvar.set(win.title())\n#Create a Button\nButton(win, text= \"Change\", command= change_title).pack(pady=20)\nwin.mainloop()" }, { "code": null, "e": 2590, "s": 2370, "text": "By running the above code, we can display a window that contains a button and the frame object. Now, whenever we write some title in the entry widget and click the “Change” button, it will change the title of the frame." }, { "code": null, "e": 2722, "s": 2590, "text": "Now, change the title of the frame by writing some text in the Entry widget and click the “Change” to display the reflected output." } ]
Less is More: Labeled data just isn’t as important anymore | by Abhinav Raghunathan | Towards Data Science
I used to always think of data as being inherently calm and ordered — a neatly packaged array of information ready to process. I think most people who haven’t had a taste of the chaos of the real world would believe the same. Professionals (or, really, anyone who has worked with data) know that data is far more fluid and amorphous. Very rarely is data ordered and structured with a nice label to go with it. In fact, most of the time, data is unlabeled, unstructured, and chaotic. Unfortunately, most of the machine learning algorithms that are widely used today depend heavily on labeled data and fully supervised algorithms. Data scientists and data engineers spend a lot of time and effort fighting entropy and producing these clean datasets that we’re so used to seeing on websites like Kaggle. It turns out, however, that a semi-supervised approach with deliberate noise injection might just be better than any supervised learning approach, even while using significantly less labeled data. Supervised learning requires a lot of labeled data that most of us just don’t have. Semi-supervised learning (SSL) is a different method that combines unsupervised and supervised learning to take advantage of the strengths of each. Here’s one possible procedure (called SSL with “domain-relevance data filtering”): 1. Train a model (M) on labeled data (X) and the true labels (Y).2. Calculate the error.3. Apply M on unlabeled data (X’) to “predict” the labels (Y’).4. Take any high-confidence guesses from (2) and move them from X’ to X.5. Repeat. Over time, the labeled dataset grows in size and affords the model a fair bit of data to work with. This is already impressive because unlabeled data is far cheaper and more abundant than labeled data, but SSL isn’t guaranteed to be a good solution (Singh, Nowak, & Zhu). There is, however, a new study that suggests that there are a couple things we can change to boost performance of SSL. What if I told you this new version of SSL almost outperforms supervised learning with only a fraction of the necessary labeled data? If your kids learned exclusively from what you tell them, chances are that there would be a lot of situations they would be completely lost in. Machine learning algorithms are the same way. It turns out, giving algorithms tough pieces of data to work with make them significantly more robust later on. These “tough pieces of data” can also be called “noise.” A really useful technique for strengthening machine learning algorithms is intentionally adding noise (called “noise injection” or “data augmentation” in this paper) to data. In a new paper by CMU and the Google Brain Team, a new SSL framework that cares about “quality of noise” injected as well. Here’s the overarching model as a flowchart: Here’s the same flowchart in a step-by-step format: 1. Train a model (M) on labeled data (X) and true labels (Y).2. Calculate the supervised error.3. Apply M on unlabeled data (X’) to “predict” the labels (Y’).4. Introduce noise to X’ in a smart way to produce X’’.5. Apply M on unlabeled, perturbed data (X’’) to “predict” the labels (Y’’).6. Calculate the unsupervised error by comparing Y’ and Y’’.7. Calculate the total error using (2) and (6).8. Take any high-confidence guesses from (3) and move them from X’ to X.9. Repeat. There are lots of ways to do (4) in the above step-process. One interesting method is called back-translation. Consider the sentence: “Labeled data is not as cheap as unlabeled data and therefore is a relic of the past.” I can convert this sentence into another language and then back into English again. Here’s the result when I use Norwegian as my intermediate. “Marked data is not as cheap as unmarked data and is therefore a thing of the past.” Now we’ve added noise. Subtle changes, but a world of difference to an algorithm. The paper mentioned earlier does a stress-test of the approach outlined in the last section. Using Google’s BERT (Large) algorithm on text classification datasets, they’ve generated the following results, where n is the number of labeled samples used): + — — — — + — — — — — — — — + — — — — — — — — — — — + | Dataset | Supervised Error | Semi-Supervised Error | + — — — — + — — — — — — — — + — — — — — — — — — — — + | IMDb | 4.51 (n = 20k) | 4.78 (n = 20) | | Yelp-2 | 1.89 (n = 560k) | 2.50 (n = 20) | | Yelp-5 | 29.32 (n = 650k) | 33.54(n = 2.5k) | | Amazon-2| 2.63 (n = 3.6m) | 3.93 (n = 20) | | Amazon-5| 34.17 (n = 3.0m) | 37.80(n = 2.5k) | | DBpedia | 0.64 (n = 560k) | 1.09 (n = 140) | + — — — — + — — — — — — — — + — — — — — — — — — — — + These results imply that this particular SSL method works almost as well with just a small fraction of the labeled data as supervised methods do with ALL of the labeled data! As for the usefulness of labeled data — naturally, if labeled data is available, you take it. But with results like these, any rationale for creating neat sets of order, structured, labeled data is rapidly vanishing, especially because unlabeled data is widely available and extremely cheap (computation-, time-, and effort-wise). The future is unpredictable (and unlabeled), but we’re slowly gaining the tools necessary to capture it! The original version of this post can be found here.
[ { "code": null, "e": 585, "s": 166, "text": "I used to always think of data as being inherently calm and ordered — a neatly packaged array of information ready to process. I think most people who haven’t had a taste of the chaos of the real world would believe the same. Professionals (or, really, anyone who has worked with data) know that data is far more fluid and amorphous. Very rarely is data ordered and structured with a nice label to go with it. In fact," }, { "code": null, "e": 649, "s": 585, "text": "most of the time, data is unlabeled, unstructured, and chaotic." }, { "code": null, "e": 967, "s": 649, "text": "Unfortunately, most of the machine learning algorithms that are widely used today depend heavily on labeled data and fully supervised algorithms. Data scientists and data engineers spend a lot of time and effort fighting entropy and producing these clean datasets that we’re so used to seeing on websites like Kaggle." }, { "code": null, "e": 1164, "s": 967, "text": "It turns out, however, that a semi-supervised approach with deliberate noise injection might just be better than any supervised learning approach, even while using significantly less labeled data." }, { "code": null, "e": 1479, "s": 1164, "text": "Supervised learning requires a lot of labeled data that most of us just don’t have. Semi-supervised learning (SSL) is a different method that combines unsupervised and supervised learning to take advantage of the strengths of each. Here’s one possible procedure (called SSL with “domain-relevance data filtering”):" }, { "code": null, "e": 1713, "s": 1479, "text": "1. Train a model (M) on labeled data (X) and the true labels (Y).2. Calculate the error.3. Apply M on unlabeled data (X’) to “predict” the labels (Y’).4. Take any high-confidence guesses from (2) and move them from X’ to X.5. Repeat." }, { "code": null, "e": 2104, "s": 1713, "text": "Over time, the labeled dataset grows in size and affords the model a fair bit of data to work with. This is already impressive because unlabeled data is far cheaper and more abundant than labeled data, but SSL isn’t guaranteed to be a good solution (Singh, Nowak, & Zhu). There is, however, a new study that suggests that there are a couple things we can change to boost performance of SSL." }, { "code": null, "e": 2238, "s": 2104, "text": "What if I told you this new version of SSL almost outperforms supervised learning with only a fraction of the necessary labeled data?" }, { "code": null, "e": 2940, "s": 2238, "text": "If your kids learned exclusively from what you tell them, chances are that there would be a lot of situations they would be completely lost in. Machine learning algorithms are the same way. It turns out, giving algorithms tough pieces of data to work with make them significantly more robust later on. These “tough pieces of data” can also be called “noise.” A really useful technique for strengthening machine learning algorithms is intentionally adding noise (called “noise injection” or “data augmentation” in this paper) to data. In a new paper by CMU and the Google Brain Team, a new SSL framework that cares about “quality of noise” injected as well. Here’s the overarching model as a flowchart:" }, { "code": null, "e": 2992, "s": 2940, "text": "Here’s the same flowchart in a step-by-step format:" }, { "code": null, "e": 3471, "s": 2992, "text": "1. Train a model (M) on labeled data (X) and true labels (Y).2. Calculate the supervised error.3. Apply M on unlabeled data (X’) to “predict” the labels (Y’).4. Introduce noise to X’ in a smart way to produce X’’.5. Apply M on unlabeled, perturbed data (X’’) to “predict” the labels (Y’’).6. Calculate the unsupervised error by comparing Y’ and Y’’.7. Calculate the total error using (2) and (6).8. Take any high-confidence guesses from (3) and move them from X’ to X.9. Repeat." }, { "code": null, "e": 3605, "s": 3471, "text": "There are lots of ways to do (4) in the above step-process. One interesting method is called back-translation. Consider the sentence:" }, { "code": null, "e": 3692, "s": 3605, "text": "“Labeled data is not as cheap as unlabeled data and therefore is a relic of the past.”" }, { "code": null, "e": 3835, "s": 3692, "text": "I can convert this sentence into another language and then back into English again. Here’s the result when I use Norwegian as my intermediate." }, { "code": null, "e": 3920, "s": 3835, "text": "“Marked data is not as cheap as unmarked data and is therefore a thing of the past.”" }, { "code": null, "e": 4002, "s": 3920, "text": "Now we’ve added noise. Subtle changes, but a world of difference to an algorithm." }, { "code": null, "e": 4255, "s": 4002, "text": "The paper mentioned earlier does a stress-test of the approach outlined in the last section. Using Google’s BERT (Large) algorithm on text classification datasets, they’ve generated the following results, where n is the number of labeled samples used):" }, { "code": null, "e": 4866, "s": 4255, "text": " + — — — — + — — — — — — — — + — — — — — — — — — — — + | Dataset | Supervised Error | Semi-Supervised Error | + — — — — + — — — — — — — — + — — — — — — — — — — — + | IMDb | 4.51 (n = 20k) | 4.78 (n = 20) | | Yelp-2 | 1.89 (n = 560k) | 2.50 (n = 20) | | Yelp-5 | 29.32 (n = 650k) | 33.54(n = 2.5k) | | Amazon-2| 2.63 (n = 3.6m) | 3.93 (n = 20) | | Amazon-5| 34.17 (n = 3.0m) | 37.80(n = 2.5k) | | DBpedia | 0.64 (n = 560k) | 1.09 (n = 140) | + — — — — + — — — — — — — — + — — — — — — — — — — — +" }, { "code": null, "e": 5041, "s": 4866, "text": "These results imply that this particular SSL method works almost as well with just a small fraction of the labeled data as supervised methods do with ALL of the labeled data!" }, { "code": null, "e": 5477, "s": 5041, "text": "As for the usefulness of labeled data — naturally, if labeled data is available, you take it. But with results like these, any rationale for creating neat sets of order, structured, labeled data is rapidly vanishing, especially because unlabeled data is widely available and extremely cheap (computation-, time-, and effort-wise). The future is unpredictable (and unlabeled), but we’re slowly gaining the tools necessary to capture it!" } ]
How to print current date and time using Python?
You can get the current date and time using multiple ways. The easiest way is to use the datetime module. It has a function, now, that gives the current date and time. import datetime now = datetime.datetime.now() print("Current date and time: ") print(str(now)) This will give the output − 2017-12-29 11:24:48.042720 You can also get the formatted date and time using strftime function. It accepts a format string that you can use to get your desired output. Following are the directives supported by it. You can use these directives in the strftime function as follows − import datetime now = datetime.datetime.now() print("Current date and time: ") print(now.strftime('%Y-%m-%d %H:%M:%S')) print(now.strftime('%H:%M:%S on %A, %B the %dth, %Y')) This will give the output − 2017-12-29 12:19:13 12:19:13 on Friday, December the 29th, 2017
[ { "code": null, "e": 1231, "s": 1062, "text": "You can get the current date and time using multiple ways. The easiest way is to use the datetime module. It has a function, now, that gives the current date and time. " }, { "code": null, "e": 1326, "s": 1231, "text": "import datetime\nnow = datetime.datetime.now()\nprint(\"Current date and time: \")\nprint(str(now))" }, { "code": null, "e": 1354, "s": 1326, "text": "This will give the output −" }, { "code": null, "e": 1381, "s": 1354, "text": "2017-12-29 11:24:48.042720" }, { "code": null, "e": 1569, "s": 1381, "text": "You can also get the formatted date and time using strftime function. It accepts a format string that you can use to get your desired output. Following are the directives supported by it." }, { "code": null, "e": 1636, "s": 1569, "text": "You can use these directives in the strftime function as follows −" }, { "code": null, "e": 1812, "s": 1636, "text": "import datetime\nnow = datetime.datetime.now()\n\nprint(\"Current date and time: \")\nprint(now.strftime('%Y-%m-%d %H:%M:%S'))\nprint(now.strftime('%H:%M:%S on %A, %B the %dth, %Y'))" }, { "code": null, "e": 1840, "s": 1812, "text": "This will give the output −" }, { "code": null, "e": 1904, "s": 1840, "text": "2017-12-29 12:19:13\n12:19:13 on Friday, December the 29th, 2017" } ]
How does repetition operator work on list in Python?
We are accustomed to using the * symbol to represent multiplication, but when the operand on the left side of the * is a list, it becomes the repetition operator. The repetition operator makes multiple copies of a list and joins them all together. Lists can be created using the repetition operator, *. For example, numbers = [0] * 5 print numbers This will give the output − [0, 0, 0, 0, 0] [0] is a list with one element, 0. The repetition operator makes 5 copies of this list and joins them all together into a single list. Another example using multiple elements in the list. numbers = [0, 1, 2] * 3 print numbers This will give the output − [0, 1, 2, 0, 1, 2, 0, 1, 2] Note that Python creates shallow copies of the lists in this. So changing objects at one place will change them at all places they are repeated. If you don't want this behaviour, don't use repetition operator to create lists.
[ { "code": null, "e": 1378, "s": 1062, "text": "We are accustomed to using the * symbol to represent multiplication, but when the operand on the left side of the * is a list, it becomes the repetition operator. The repetition operator makes multiple copies of a list and joins them all together. Lists can be created using the repetition operator, *. For example," }, { "code": null, "e": 1410, "s": 1378, "text": "numbers = [0] * 5\nprint numbers" }, { "code": null, "e": 1438, "s": 1410, "text": "This will give the output −" }, { "code": null, "e": 1454, "s": 1438, "text": "[0, 0, 0, 0, 0]" }, { "code": null, "e": 1643, "s": 1454, "text": "[0] is a list with one element, 0. The repetition operator makes 5 copies of this list and joins them all together into a single list. Another example using multiple elements in the list." }, { "code": null, "e": 1681, "s": 1643, "text": "numbers = [0, 1, 2] * 3\nprint numbers" }, { "code": null, "e": 1709, "s": 1681, "text": "This will give the output −" }, { "code": null, "e": 1737, "s": 1709, "text": "[0, 1, 2, 0, 1, 2, 0, 1, 2]" }, { "code": null, "e": 1963, "s": 1737, "text": "Note that Python creates shallow copies of the lists in this. So changing objects at one place will change them at all places they are repeated. If you don't want this behaviour, don't use repetition operator to create lists." } ]
Range-based for loop in C++ - GeeksforGeeks
11 May, 2022 Range-based for loop in C++ is added since C++ 11. It executes a for loop over a range. Used as a more readable equivalent to the traditional for loop operating over a range of values, such as all elements in a container. Syntax : for ( range_declaration : range_expression ) loop_statement Parameters : range_declaration : a declaration of a named variable, whose type is the type of the element of the sequence represented by range_expression, or a reference to that type. Often uses the auto specifier for automatic type deduction. range_expression : any expression that represents a suitable sequence or a braced-init-list. loop_statement : any statement, typically a compound statement, which is the body of the loop. C++ implementation : // Illustration of range-for loop// using CPP code#include <iostream>#include <vector>#include <map> //Driverint main() { // Iterating over whole array std::vector<int> v = {0, 1, 2, 3, 4, 5}; for (auto i : v) std::cout << i << ' '; std::cout << '\n'; // the initializer may be a braced-init-list for (int n : {0, 1, 2, 3, 4, 5}) std::cout << n << ' '; std::cout << '\n'; // Iterating over array int a[] = {0, 1, 2, 3, 4, 5}; for (int n : a) std::cout << n << ' '; std::cout << '\n'; // Just running a loop for every array // element for (int n : a) std::cout << "In loop" << ' '; std::cout << '\n'; // Printing string characters std::string str = "Geeks"; for (char c : str) std::cout << c << ' '; std::cout << '\n'; // Printing keys and values of a map std::map <int, int> MAP({{1, 1}, {2, 2}, {3, 3}}); for (auto i : MAP) std::cout << '{' << i.first << ", " << i.second << "}\n";} Output: 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 In loop In loop In loop In loop In loop In loop G e e k s {1, 1} {2, 2} {3, 3} This article is contributed by Rohit Thapliyal. 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. ChrisFedun STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inheritance in C++ Map in C++ Standard Template Library (STL) Virtual Function in C++ C++ Classes and Objects Bitwise Operators in C/C++ Templates in C++ with Examples Constructors in C++ Operator Overloading in C++ Socket Programming in C/C++ Polymorphism in C++
[ { "code": null, "e": 25591, "s": 25563, "text": "\n11 May, 2022" }, { "code": null, "e": 25813, "s": 25591, "text": "Range-based for loop in C++ is added since C++ 11. It executes a for loop over a range. Used as a more readable equivalent to the traditional for loop operating over a range of values, such as all elements in a container." }, { "code": null, "e": 25822, "s": 25813, "text": "Syntax :" }, { "code": null, "e": 26330, "s": 25822, "text": "for ( range_declaration : range_expression ) \n loop_statement\n\nParameters :\nrange_declaration : \na declaration of a named variable, whose type is the \ntype of the element of the sequence represented by \nrange_expression, or a reference to that type.\nOften uses the auto specifier for automatic type \ndeduction.\n\nrange_expression : \nany expression that represents a suitable sequence \nor a braced-init-list.\n\nloop_statement : \nany statement, typically a compound statement, which\nis the body of the loop.\n" }, { "code": null, "e": 26351, "s": 26330, "text": "C++ implementation :" }, { "code": "// Illustration of range-for loop// using CPP code#include <iostream>#include <vector>#include <map> //Driverint main() { // Iterating over whole array std::vector<int> v = {0, 1, 2, 3, 4, 5}; for (auto i : v) std::cout << i << ' '; std::cout << '\\n'; // the initializer may be a braced-init-list for (int n : {0, 1, 2, 3, 4, 5}) std::cout << n << ' '; std::cout << '\\n'; // Iterating over array int a[] = {0, 1, 2, 3, 4, 5}; for (int n : a) std::cout << n << ' '; std::cout << '\\n'; // Just running a loop for every array // element for (int n : a) std::cout << \"In loop\" << ' '; std::cout << '\\n'; // Printing string characters std::string str = \"Geeks\"; for (char c : str) std::cout << c << ' '; std::cout << '\\n'; // Printing keys and values of a map std::map <int, int> MAP({{1, 1}, {2, 2}, {3, 3}}); for (auto i : MAP) std::cout << '{' << i.first << \", \" << i.second << \"}\\n\";}", "e": 27427, "s": 26351, "text": null }, { "code": null, "e": 27435, "s": 27427, "text": "Output:" }, { "code": null, "e": 27556, "s": 27435, "text": "0 1 2 3 4 5 \n0 1 2 3 4 5 \n0 1 2 3 4 5 \nIn loop In loop In loop In loop In loop In loop \nG e e k s \n{1, 1}\n{2, 2}\n{3, 3}\n" }, { "code": null, "e": 27855, "s": 27556, "text": "This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 27980, "s": 27855, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 27991, "s": 27980, "text": "ChrisFedun" }, { "code": null, "e": 27995, "s": 27991, "text": "STL" }, { "code": null, "e": 27999, "s": 27995, "text": "C++" }, { "code": null, "e": 28003, "s": 27999, "text": "STL" }, { "code": null, "e": 28007, "s": 28003, "text": "CPP" }, { "code": null, "e": 28105, "s": 28007, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28124, "s": 28105, "text": "Inheritance in C++" }, { "code": null, "e": 28167, "s": 28124, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 28191, "s": 28167, "text": "Virtual Function in C++" }, { "code": null, "e": 28215, "s": 28191, "text": "C++ Classes and Objects" }, { "code": null, "e": 28242, "s": 28215, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 28273, "s": 28242, "text": "Templates in C++ with Examples" }, { "code": null, "e": 28293, "s": 28273, "text": "Constructors in C++" }, { "code": null, "e": 28321, "s": 28293, "text": "Operator Overloading in C++" }, { "code": null, "e": 28349, "s": 28321, "text": "Socket Programming in C/C++" } ]
Check if two PDF documents are identical with Python - GeeksforGeeks
08 Mar, 2021 Python is an interpreted and general purpose programming language. It is a Object-Oriented and Procedural paradigms programming language. There are various types of modules imported in python such as difflib, hashlib. difflib : It is a module that contains function that allows to compare set of data. SequenceMatcher : It is used to compare pair of input sequences. hash_file ( string $algo , string $filename , bool $binary = false ): It is a function which has the hash of a file. object.hexdigest(): It is a function which returns string. fileObject.read(size): It is a function that returns the specified number of bytes of a file. Import module Declare a function with 2 arguments which is for file. Declare two objects for hashlib.sha1() Open files Read the file by breaking the line into smaller chunks Now return both file such as h1.hexdigest() which is of 160 bits. Use hash_file() function to store the hash of a file. Compare and generate appropriate message File 1 File 2 Program: Python3 import hashlibfrom difflib import SequenceMatcher def hash_file(fileName1, fileName2): # Use hashlib to store the hash of a file h1 = hashlib.sha1() h2 = hashlib.sha1() with open(fileName1, "rb") as file: # Use file.read() to read the size of file # and read the file in small chunks # because we cannot read the large files. chunk = 0 while chunk != b'': chunk = file.read(1024) h1.update(chunk) with open(fileName2, "rb") as file: # Use file.read() to read the size of file a # and read the file in small chunks # because we cannot read the large files. chunk = 0 while chunk != b'': chunk = file.read(1024) h2.update(chunk) # hexdigest() is of 160 bits return h1.hexdigest(), h2.hexdigest() msg1, msg2 = hash_file("pd1.pdf ", "pd1.pdf") if(msg1 != msg2): print("These files are not identical")else: print("These files are identical") Output These files are not identical Picked 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 ? How To Convert Python Dictionary To JSON? Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby() Python | Get unique values from a list
[ { "code": null, "e": 25647, "s": 25619, "text": "\n08 Mar, 2021" }, { "code": null, "e": 25865, "s": 25647, "text": "Python is an interpreted and general purpose programming language. It is a Object-Oriented and Procedural paradigms programming language. There are various types of modules imported in python such as difflib, hashlib." }, { "code": null, "e": 25949, "s": 25865, "text": "difflib : It is a module that contains function that allows to compare set of data." }, { "code": null, "e": 26014, "s": 25949, "text": "SequenceMatcher : It is used to compare pair of input sequences." }, { "code": null, "e": 26131, "s": 26014, "text": "hash_file ( string $algo , string $filename , bool $binary = false ): It is a function which has the hash of a file." }, { "code": null, "e": 26190, "s": 26131, "text": "object.hexdigest(): It is a function which returns string." }, { "code": null, "e": 26284, "s": 26190, "text": "fileObject.read(size): It is a function that returns the specified number of bytes of a file." }, { "code": null, "e": 26298, "s": 26284, "text": "Import module" }, { "code": null, "e": 26353, "s": 26298, "text": "Declare a function with 2 arguments which is for file." }, { "code": null, "e": 26392, "s": 26353, "text": "Declare two objects for hashlib.sha1()" }, { "code": null, "e": 26403, "s": 26392, "text": "Open files" }, { "code": null, "e": 26458, "s": 26403, "text": "Read the file by breaking the line into smaller chunks" }, { "code": null, "e": 26524, "s": 26458, "text": "Now return both file such as h1.hexdigest() which is of 160 bits." }, { "code": null, "e": 26578, "s": 26524, "text": "Use hash_file() function to store the hash of a file." }, { "code": null, "e": 26619, "s": 26578, "text": "Compare and generate appropriate message" }, { "code": null, "e": 26626, "s": 26619, "text": "File 1" }, { "code": null, "e": 26633, "s": 26626, "text": "File 2" }, { "code": null, "e": 26642, "s": 26633, "text": "Program:" }, { "code": null, "e": 26650, "s": 26642, "text": "Python3" }, { "code": "import hashlibfrom difflib import SequenceMatcher def hash_file(fileName1, fileName2): # Use hashlib to store the hash of a file h1 = hashlib.sha1() h2 = hashlib.sha1() with open(fileName1, \"rb\") as file: # Use file.read() to read the size of file # and read the file in small chunks # because we cannot read the large files. chunk = 0 while chunk != b'': chunk = file.read(1024) h1.update(chunk) with open(fileName2, \"rb\") as file: # Use file.read() to read the size of file a # and read the file in small chunks # because we cannot read the large files. chunk = 0 while chunk != b'': chunk = file.read(1024) h2.update(chunk) # hexdigest() is of 160 bits return h1.hexdigest(), h2.hexdigest() msg1, msg2 = hash_file(\"pd1.pdf \", \"pd1.pdf\") if(msg1 != msg2): print(\"These files are not identical\")else: print(\"These files are identical\")", "e": 27667, "s": 26650, "text": null }, { "code": null, "e": 27674, "s": 27667, "text": "Output" }, { "code": null, "e": 27704, "s": 27674, "text": "These files are not identical" }, { "code": null, "e": 27711, "s": 27704, "text": "Picked" }, { "code": null, "e": 27726, "s": 27711, "text": "python-utility" }, { "code": null, "e": 27750, "s": 27726, "text": "Technical Scripter 2020" }, { "code": null, "e": 27757, "s": 27750, "text": "Python" }, { "code": null, "e": 27776, "s": 27757, "text": "Technical Scripter" }, { "code": null, "e": 27874, "s": 27776, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27906, "s": 27874, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27948, "s": 27906, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27990, "s": 27948, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28046, "s": 27990, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28073, "s": 28046, "text": "Python Classes and Objects" }, { "code": null, "e": 28104, "s": 28073, "text": "Python | os.path.join() method" }, { "code": null, "e": 28133, "s": 28104, "text": "Create a directory in Python" }, { "code": null, "e": 28155, "s": 28133, "text": "Defaultdict in Python" }, { "code": null, "e": 28191, "s": 28155, "text": "Python | Pandas dataframe.groupby()" } ]