title stringlengths 3 221 | text stringlengths 17 477k | parsed listlengths 0 3.17k |
|---|---|---|
Patching Array in C++ | Suppose we have an array nums and one number. We can add elements in the array, such that any number in range [1, n] (both are inclusive) can be formed by the sum of some elements in the array. We have to find the minimum number of required patches. So when the array is like [1,4] and given number is n = 7, then output will be 1, as initially the nums are [1], [4] and [1,4] = 5, now if we add 2 into array, then the nums will be [1], [2], [4], [1,2], [1,4],[2,4], [1,2,4], so the sum values will be 1, 2, 4, 3, 5, 6, 7 respectively.
To solve this, we will follow these steps −
req := 1, i := 0, ret := 0
req := 1, i := 0, ret := 0
while req <= n, do −if i < size of nums and nums[i] <= req, then,req = req + nums[i]increase i by 1Otherwisereq = req + reqincrease ret by 1
while req <= n, do −
if i < size of nums and nums[i] <= req, then,req = req + nums[i]increase i by 1
if i < size of nums and nums[i] <= req, then,
req = req + nums[i]
req = req + nums[i]
increase i by 1
increase i by 1
Otherwisereq = req + reqincrease ret by 1
Otherwise
req = req + req
req = req + req
increase ret by 1
increase ret by 1
return ret
return ret
Let us see the following implementation to get better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int minPatches(vector<int>& nums, int n) {
long long int req = 1;
int i = 0;
int ret = 0;
while(req <= n){
if(i < nums.size() && nums[i] <= req){
req += nums[i];
i++;
} else {
req += req;
ret++;
}
}
return ret;
}
};
main(){
Solution ob;
vector<int> v = {1,4};
cout << (ob.minPatches(v, 7));
}
{1,4}
1 | [
{
"code": null,
"e": 1598,
"s": 1062,
"text": "Suppose we have an array nums and one number. We can add elements in the array, such that any number in range [1, n] (both are inclusive) can be formed by the sum of some elements in the array. We have to find the minimum number of required patches. So ... |
How does the Java “foreach” loop work? | JDK 1.5 introduced a new for loop known as foreach loop or enhanced for loop, which enables you to traverse the complete array sequentially without using an index variable.
public class ArrayUsingForEach {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (double element: myList) {
System.out.println(element);
}
}
}
Output
1.9
2.9
3.4
3.5 | [
{
"code": null,
"e": 1236,
"s": 1062,
"text": "JDK 1.5 introduced a new for loop known as foreach loop or enhanced for loop, which enables you to traverse the complete array sequentially without using an index variable. "
},
{
"code": null,
"e": 1487,
"s": 1236,
"text": "public c... |
Yii - Widgets | A widget is a reusable client-side code, which contains HTML, CSS, and JS. This code includes minimal logic and is wrapped in a yii\base\Widget object. We can easily insert and apply this object in any view.
Step 1 − To see widgets in action, create an actionTestWidget function in the SiteController with the following code.
public function actionTestWidget() {
return $this->render('testwidget');
}
In the above example, we just returned a View called “testwidget”.
Step 2 − Now, inside the views/site folder, create a View file called testwidget.php.
<?php
use yii\bootstrap\Progress;
?>
<?= Progress::widget(['percent' => 60, 'label' => 'Progress 60%']) ?>
Step 3 − If you go to http://localhost:8080/index.php?r=site/test-widget, you will see the progress bar widget.
To use a widget in a View, you should call the yii\base\Widget::widget() function. This function takes a configuration array for initializing the widget. In the previous example, we inserted a progress bar with percent and labelled parameters of the configuration object.
Some widgets take a block of content. It should be enclosed between yii\base\Widget::begin() and yii\base\Widget::end() functions. For example, the following widget displays a contact form −
<?php $form = ActiveForm::begin(['id' => 'contact-form']); ?>
<?= $form->field($model, 'name') ?>
<?= $form->field($model, 'email') ?>
<?= $form->field($model, 'subject') ?>
<?= $form->field($model, 'body')->textArea(['rows' => 6]) ?>
<?= $form->field($model, 'verifyCode')->widget(Captcha::className(), [
'template' =>
'<div class="row">
<div class = "col-lg-3">{image}</div>
<div class = "col-lg-6">{input}</div>
</div>',
]) ?>
<div class = "form-group">
<?= Html::submitButton('Submit', ['class' => 'btn btn-primary',
'name' => 'contact-button']) ?>
</div>
<?php ActiveForm::end(); ?>
To create a widget, you should extend from yii\base\Widget. Then you should override the yii\base\Widget::init() and yii\base\Widget::run() functions. The run() function should return the rendering result. The init() function should normalize the widget properties.
Step 1 − Create a components folder in the project root. Inside that folder, create a file called FirstWidget.php with the following code.
<?php
namespace app\components;
use yii\base\Widget;
class FirstWidget extends Widget {
public $mes;
public function init() {
parent::init();
if ($this->mes === null) {
$this->mes = 'First Widget';
}
}
public function run() {
return "<h1>$this->mes</h1>";
}
}
?>
Step 2 − Modify the testwidget view in the following way.
<?php
use app\components\FirstWidget;
?>
<?= FirstWidget∷widget() ?>
Step 3 − Go to http://localhost:8080/index.php?r=site/test-widget. You will see the following.
Step 4 − To enclose the content between the begin() and end() calls, you should modify the FirstWidget.php file.
<?php
namespace app\components;
use yii\base\Widget;
class FirstWidget extends Widget {
public function init() {
parent::init();
ob_start();
}
public function run() {
$content = ob_get_clean();
return "<h1>$content</h1>";
}
}
?>
Step 5 − Now h1 tags will surround all the content. Notice that we use the ob_start() function to buffer the output. Modify the testwidget view as given in the following code.
<?php
use app\components\FirstWidget;
?>
<?php FirstWidget::begin(); ?>
First Widget in H1
<?php FirstWidget::end(); ?>
You will see the following output −
Widgets should −
Be created following the MVC pattern. You should keep presentation layers in views and logic in widget classes.
Be created following the MVC pattern. You should keep presentation layers in views and logic in widget classes.
Be designed to be self-contained. The end developer should be able to design it into a View.
Be designed to be self-contained. The end developer should be able to design it into a View.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3041,
"s": 2833,
"text": "A widget is a reusable client-side code, which contains HTML, CSS, and JS. This code includes minimal logic and is wrapped in a yii\\base\\Widget object. We can easily insert and apply this object in any view."
},
{
"code": null,
"e": 3159,
... |
Build Your own Data Dashboard. Building dashboard web app quickly with... | by Vincent Tatan | Towards Data Science | For data scientists, it is very important to communicate our data and results to the non technical users. Especially in the format which could be understood and reacted quickly. This is why data visualization is very important especially in BI products such as Power BI, Tableau and Qlikview.
Although they have an easy to use interface to produce stunning visualization, the technical licenses for these could be very costly. For Tableau, it could reach up to $50 per month. Furthermore for data professionals like me, I think that most BI Tools are not versatile enough to keep up with the dynamic growth of Python use cases. It still remains very clunky to embed this rather than seamlessly integrating with our web application.
Therefore, we need a better solution to this question.
Can we build an dashboard Web Application with Python for free?
The surprising answer is YES! I am going to exactly show you just that with the open source library — Dash Python.
Simply put, Dash is an open source Python Library to build web applications which are optimized for data visualization. The best thing about Dash is that it is built on top of Data visualization library such as Plotly and Matplotlib, Web Application Library (Flask), and finally data portable through Pandas! As the Javascript layer is handled via Plotly and Flask, you do not even need to touch other programming language to create a stunning web application.
The end result is the beautiful marriage of familiarity, conventions, and practicality. You could pick it up, develop, and deploy the application quickly. All of these are strictly writing only in Python and no other languages are necessary (although options are still available).
“Dash app code is declarative and reactive, which makes it easy to build complex apps that contain many interactive elements.” — Plotly Dash
One of the best features is that Dash supports declarative programming. This allows you to build Dash applications based on the input data and output properties. You will only state what you need and not the details on how to achieve your goal.
Let us say you want to buy eggs.
Declarative Programming will say “ Find and buy eggs for me. Here are the cash”
However, Traditional Programming will say “ Go to the Courts Supermarket, go to the aisle 6 to find the eggs at your right hand corner, go to the cashier and pay with $5 cash”.
Obviously from this example declarative programming will offload the “how”. Similarly with money and eggs, you only need to hand over the input data and output properties then the visualization results will render automatically.
You do not even need to understand how Dash process your visualization. You will just instruct and receive the results. That is the beauty of Dash to support declarative programming.
In fact, this is not foreign at all. Many languages are also built with the same concepts. One example of the declarative language is SQL (Structured Query Language) and Kubernetes yaml. Both are important tools for Data Scientists to optimize their data retrieval and devops process.
Hope I make you excited!! Let’s get started
In this tutorial, you will learn how to build Dashboard Application with Dash Python.
We will visit our previous projects on task scheduler to web scrape data from Lazada (eCommerce) website and dump it into SQLite RDBMS Database. Then we will generate data visualizations to learn about price changes in Lazada Products over date and time.
Feel free to just enjoy this article or visit my Github Repo for the complete codes.
In this scenario let us visualize the change of price over the period of 3 days.
Importing and Activating DashPreparing the dataVisualizing ChartsDropdowns and Input Filter SelectionsStyling and Finishing
Importing and Activating Dash
Preparing the data
Visualizing Charts
Dropdowns and Input Filter Selections
Styling and Finishing
As usual, let us import Dash Libraries on Python.
import dashfrom dash.dependencies import Input, Outputimport dash_core_components as dccimport dash_html_components as html
you can download these libraries with a simple pip install command.
pip install <library name e.g: dash>
We will also activate the Dash Server with this code.
app = dash.Dash(__name__)server = app.serverif __name__ == '__main__': app.run_server(debug=True)
Once you run this Python script, it will run a server which you can open with http://127.0.0.1:8050/. This will open a flask web application which you could deploy anywhere such as Heroku. Notice that we put the run_server parameterdebug =True. This will allow you to automatically update your local deployment once you save any changes in the scripts. Very neat time saving tricks to relaunch your application.
In this sector, we are going to read our product information from our database and dump them into a Pandas Dataframe. The dbm is a module that we created in SQLite RDBMS project before. This will dump a SQLite table into Pandas Dataframe which is called product_df. Feel free to extract the module from my Github.
global product_dfproduct_df = dbm.read()
The keyword global will globalize the product_df so that it is accessible to all call-back functions to generate data visualizations.
We will create an app layout which will encapsulate html objects in the html module. This will be our main access to layout the graphs and and adjust the relative sizes to your view screen sizes.
app.layout = html.Div([ html.Div([ html.H1('Price Optimization Dashboard'), html.H2('Choose a product name'), dcc.Dropdown( id='product-dropdown', options=dict_products, multi=True, value = ["Ben & Jerry's Wake and No Bake Cookie Dough Core Ice Cream","Brewdog Punk IPA"] ), dcc.Graph( id='product-like-bar' ) ], style={'width': '40%', 'display': 'inline-block'}), html.Div([ html.H2('All product info'), html.Table(id='my-table'), html.P(''), ], style={'width': '55%', 'float': 'right', 'display': 'inline-block'}), html.Div([ html.H2('price graph'), dcc.Graph(id='product-trend-graph'), html.P('') ], style={'width': '100%', 'display': 'inline-block'})])
Notice the dcc module. This is the dash core components which will store basic visualizations for web application such as barchart, dropdown, and line chart.
The rest is straightforward and specific to html module. You can create H1 or H2 headers, div (boxes to contain your web component), and even table. Think about it as the html codes abstracted so you do not need to even look at it.
Now let us talk about id. What does the id my-table in dcc.Graph(id=’my-table’) exactly mean? This shows the which function to call for a certain graph output. By inserting the code, we will call the function below.
@app.callback(Output('my-table', 'children'), [Input('product-dropdown', 'value')])def generate_table(selected_dropdown_value, max_rows=20): product_df_filter = product_df[(product_df['product_title'].isin(selected_dropdown_value))]product_df_filter = product_df_filter.sort_values(['index','datetime'], ascending=True)return [html.Tr([html.Th(col) for col in product_df_filter .columns])] + [html.Tr([ html.Td(product_df_filter.iloc[i][col]) for col in product_df_filter .columns ]) for i in range(min(len(product_df_filter ), max_rows))]
On the top of the function code, you will see @app.callback which will run the magic. This means that you are exporting the return function exactly into the my-table component. You can also specify the input which is the selection from the drop down. This will be used to filter the product_df.
Noted the filtered product_df will be used to populate the return statement where we design the table using html module.
The beauty of this is that if you change the dropdown input in the dashboard, the function will render the filtered product_df.
Exactly how you use Tableau, but free and more versatile (plug and play)!!
Notice the @app.callback input? This is the time where you can specify your own filter to render your visualization component.
dcc.Dropdown( id='product-dropdown', options=dict_products, multi=True, value = ["Ben & Jerry's Wake and No Bake Cookie Dough Core Ice Cream","Brewdog Punk IPA"]),
The id is the same with the input annotation in the callback functions. This designates the function to call.
The options will insert the key value pairs of all the available options. This could be stocks ticker such as {‘GOOG’:google,’MSFT’: microsoft} or anything. For our case we will insert the same key value pairs which are the product name.
The multi attribute will allow you to select more than 1 option, which is perfect for this case to do a side by side price comparison in one chart.
Finally the value attribute will store your dropdown values at the start of server run.
Styling in Dash is easy. By default, Dash already has a preconfigured setting to access assets folder. This is where you could overwrite the css for styling and js for web behavior. You can insert the stylesheet.css to beautify your Dash Web Application. Specific room for improvements would be the margin among components and table borders.
Congratulations!! You have created your first interactive dashboard. If you did it properly, you would be able to receive this result. If not, feel free to refer back to my Github Codes or post your questions here.
Now set free and create your own Dash Dashboard!
If you need more examples and better insights of what Dash can do. Feel free to visit the following links. I assure you these will boost your Dashboard Design Skills to solve real life business problems.
Value Investing Dashboard with Python Beautiful Soup and Dash PythonAuto Generated FAQ with Python Dash, Topic Analysis and Reddit Praw APIDash Gallery
Value Investing Dashboard with Python Beautiful Soup and Dash Python
Auto Generated FAQ with Python Dash, Topic Analysis and Reddit Praw API
Dash Gallery
I really hope this has been a great read and a source of inspiration for you to develop and innovate.
Please Comment out below to suggest and feedback. Just like you, I am still learning how to become a better Data Scientist and Engineer. Please help me improve so that I could help you better in my subsequent article releases.
Thank you and Happy coding :)
Vincent Tatan is a Data and Technology enthusiast with relevant working experiences from Visa Inc. and Lazada to implement microservice architectures, business intelligence, and analytics pipeline projects.
Vincent is a native Indonesian with a record of accomplishments in problem solving with strengths in Full Stack Development, Data Analytics, and Strategic Planning.
He has been actively consulting SMU BI & Analytics Club, guiding aspiring data scientists and engineers from various backgrounds, and opening up his expertise for businesses to develop their products .
Please reach out to Vincent via LinkedIn , Medium or Youtube Channel | [
{
"code": null,
"e": 465,
"s": 172,
"text": "For data scientists, it is very important to communicate our data and results to the non technical users. Especially in the format which could be understood and reacted quickly. This is why data visualization is very important especially in BI products su... |
Get the first element from a Sorted Set in Java | To create a Sorted Set, firstly create a Set.
Set<Integer> s = new HashSet<Integer>();
Add elements to the above set.
int a[] = {77, 23, 4, 66, 99, 112, 45, 56, 39, 89};
Set<Integer> s = new HashSet<Integer>();
try {
for(int i = 0; i < 5; i++) {
s.add(a[i]);
}
After that, use TreeSet class to sort.
TreeSet sorted = new TreeSet<Integer>(s);
Get the first element, using the first() method −
System.out.println("\nFirst element of the sorted set = "+ (Integer)sorted.first());
The following is the code to get the first element from a Sorted Set in Java.
Live Demo
import java.util.*;
public class Demo {
public static void main(String args[]) {
int a[] = {77, 23, 4, 66, 99, 112, 45, 56, 39, 89};
Set<Integer> s = new HashSet<Integer>();
try {
for(int i = 0; i < 5; i++) {
s.add(a[i]);
}
System.out.println(s);
TreeSet sorted = new TreeSet<Integer>(s);
System.out.println("Sorted list = ");
System.out.println(sorted);
System.out.println("\nFirst element of the sorted set = "+ (Integer)sorted.first());
} catch(Exception e) {}
}
}
[66, 99, 4, 23, 77]
Sorted list =
[4, 23, 66, 77, 99]
First element of the sorted set = 4 | [
{
"code": null,
"e": 1108,
"s": 1062,
"text": "To create a Sorted Set, firstly create a Set."
},
{
"code": null,
"e": 1149,
"s": 1108,
"text": "Set<Integer> s = new HashSet<Integer>();"
},
{
"code": null,
"e": 1180,
"s": 1149,
"text": "Add elements to the abov... |
What is the difference between super and this, keywords in Java? | The this is a keyword in Java which is used as a reference to the object of the current class. Using it you can −
Differentiate the instance variables from local variables if they have same names, within a constructor or a method.
Call one type of constructor (parametrized constructor or default) from other in a class. It is known as explicit constructor invocation.
class Superclass {
int age;
Superclass(int age) {
this.age = age;
}
public void getAge() {
System.out.println("The value of the variable named age in super class is: " +age);
}
}
The super is a keyword in Java which is used as a reference to the object of the super class. Like the this keyword −
It is used to differentiate the members of superclass from the members of subclass, if they have same names.
It is used to invoke the superclass constructor from subclass.
Live Demo
class Superclass {
int age;
Superclass(int age) {
this.age = age;
}
public void getAge() {
System.out.println("The value of the variable named age in super class is: " +age);
}
}
public class Subclass extends Superclass {
Subclass(int age) {
super(age);
}
public static void main(String argd[]) {
Subclass s = new Subclass(24);
s.getAge();
}
}
The value of the variable named age in super class is: 24 | [
{
"code": null,
"e": 1176,
"s": 1062,
"text": "The this is a keyword in Java which is used as a reference to the object of the current class. Using it you can −"
},
{
"code": null,
"e": 1293,
"s": 1176,
"text": "Differentiate the instance variables from local variables if they ha... |
MySQL query to find sum of fields with same column value? | Use GROUP BY clause for this. Let us first create a table −
mysql> create table sumOfFieldsDemo
-> (
-> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> ClientSerialNumber varchar(100),
-> ClientCost int
-> );
Query OK, 0 rows affected (0.50 sec)
Following is the query to insert some records in the table using insert command −
mysql> insert into sumOfFieldsDemo(ClientSerialNumber,ClientCost) values('1111',450);
Query OK, 1 row affected (0.16 sec)
mysql> insert into sumOfFieldsDemo(ClientSerialNumber,ClientCost) values('2222',550);
Query OK, 1 row affected (0.15 sec)
mysql> insert into sumOfFieldsDemo(ClientSerialNumber,ClientCost) values('3333',150);
Query OK, 1 row affected (0.64 sec)
mysql> insert into sumOfFieldsDemo(ClientSerialNumber,ClientCost) values('3333',250);
Query OK, 1 row affected (0.12 sec)
mysql> insert into sumOfFieldsDemo(ClientSerialNumber,ClientCost) values('2222',1000);
Query OK, 1 row affected (0.10 sec)
mysql> insert into sumOfFieldsDemo(ClientSerialNumber,ClientCost) values('1111',1000);
Query OK, 1 row affected (0.16 sec)
mysql> insert into sumOfFieldsDemo(ClientSerialNumber,ClientCost) values('1111',500);
Query OK, 1 row affected (0.17 sec)
mysql> insert into sumOfFieldsDemo(ClientSerialNumber,ClientCost) values('4444',100);
Query OK, 1 row affected (0.17 sec)
Following is the query to display all records from the table using select statement −
mysql> select * from sumOfFieldsDemo;
This will produce the following output −
+----+--------------------+------------+
| Id | ClientSerialNumber | ClientCost |
+----+--------------------+------------+
| 1 | 1111 | 450 |
| 2 | 2222 | 550 |
| 3 | 3333 | 150 |
| 4 | 3333 | 250 |
| 5 | 2222 | 1000 |
| 6 | 1111 | 1000 |
| 7 | 1111 | 500 |
| 8 | 4444 | 100 |
+----+--------------------+------------+
8 rows in set (0.00 sec)
Here is the query to find sum of fields with same column value −
mysql> select Id,ClientSerialNumber,SUM(ClientCost) AS TotalSum
-> from sumOfFieldsDemo
-> group by ClientSerialNumber;
This will produce the following output −
+----+--------------------+----------+
| Id | ClientSerialNumber | TotalSum |
+----+--------------------+----------+
| 1 | 1111 | 1950 |
| 2 | 2222 | 1550 |
| 3 | 3333 | 400 |
| 8 | 4444 | 100 |
+----+--------------------+----------+
4 rows in set (0.00 sec) | [
{
"code": null,
"e": 1122,
"s": 1062,
"text": "Use GROUP BY clause for this. Let us first create a table −"
},
{
"code": null,
"e": 1322,
"s": 1122,
"text": "mysql> create table sumOfFieldsDemo\n -> (\n -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> ClientSerialNumber ... |
How to plot values with log scales on x and y axis or on a single axis in R? | We can plot numerical values in R with many scales and that includes log scale as well. Also, it is possible to plot the values with log scales on both the axes. In base R, the best way to do this is defining the axes values with decimal representation as shown in the below examples with well-defined log.
Consider the below vector −
Live Demo
set.seed(555)
x<-sample(1:9,10,replace=TRUE)
x
[1] 4 8 7 5 6 1 9 2 1 8
Creating plot of x with log scale on both, x and y axis −
plot(x,xlim=c(0.000001,10),ylim=c(0.000001,10),log="xy")
Creating plot of x with log scale on y axis only −
plot(x,xlim=c(0.000001,10),ylim=c(0.000001,10),log="y")
Creating plot of x with log scale on x axis only −
plot(x,xlim=c(0.000001,10),ylim=c(0.000001,10),log="x") | [
{
"code": null,
"e": 1369,
"s": 1062,
"text": "We can plot numerical values in R with many scales and that includes log scale as well. Also, it is possible to plot the values with log scales on both the axes. In base R, the best way to do this is defining the axes values with decimal representation ... |
Climbing Stairs in C++ | There are n stairs. One person will go to 1st to nth stairs. Maximum how many stairs he/she can cross in one step is also given. With this information, we have to find possible ways to go to the nth stairs. Let us consider one can cross a maximum two stairs in each step. So we can find recursive relations to solve this problem. One can move to nth stair, either from (n-1)th stair or from (n-2)th stair. So ways(n) = ways(n-1) + ways(n-2).
Suppose the number of stairs, say 10, the maximum number of stairs that can be jumped in one step, say 2, then the output will be 89 possible ways.
To solve this, follow these steps −
define array count of size same as stair number
count[0] := 1
for i := 2 to stair -1, docount[i] := 0for j = 1 to i and j <= max; docount[i] := count[i] + count[i - j]
count[i] := 0
for j = 1 to i and j <= max; docount[i] := count[i] + count[i - j]
count[i] := count[i] + count[i - j]
return count[stair - 1]
Let us see the implementation to get better understanding
Live Demo
#include<iostream>
using namespace std;
int stairClimbWays(int stair, int max){
int count[stair]; //fill the result stair using bottom up manner
count[0] = 1; //when there are 0 or 1 stair, 1 way to climb
count[1] = 1;
for (int i=2; i<stair; i++){ //for stair 2 to higher
count[i] = 0;
for(int j=1; j<=max && j<=i; j++)
count[i] += count[i-j];
}
return count[stair-1];
}
int countWays(int stair, int max){ //person can climb 1,2,...max stairs at a time
return stairClimbWays(stair+1, max);
}
int main (){
int stair, max;
cout << "Enter number of stairs: "; cin >> stair;
cout << "Enter max stair a person can climb: "; cin >> max;
cout << "Number of ways to reach: " << countWays(stair, max);
}
Stairs = 10
Max stairs a person can climb: 2
Enter number of stairs: 10
Enter max stair a person can climb: 2
Number of ways to reach: 89 | [
{
"code": null,
"e": 1504,
"s": 1062,
"text": "There are n stairs. One person will go to 1st to nth stairs. Maximum how many stairs he/she can cross in one step is also given. With this information, we have to find possible ways to go to the nth stairs. Let us consider one can cross a maximum two st... |
Web Scraping News Articles to Build an NLP Data Pipeline | by Erdem Isbilen | Towards Data Science | Although it is ok to experiment with the ready-to-use datasets, generating your NLP data pipeline further improves your skills and gives you more freedom in your project choices.
In this article, I will try to explain my NLP data workflow from start to finish. I listed below, the three open-source Python frameworks that I used in my workflow;
Scrapy for extracting the raw text data from the web
spaCy for cleaning and normalizing the text
Tensorflow 2.0 for constructing the data pipeline
The complete workflow will be explained in 3 easy to follow steps. Full source code is provided in my GitHub repository.
Let’s start with the first step.
I decided to scrape news articles from the TRT World website to experiment with several NLP algorithms and data pipeline concepts using the text data scraped.
I aimed to scrape about 2000–3000 articles and store them in a JSON file.
To do this, I created a Scrapy project and generated 2 spiders; one for extracting the article links, another one for extracting the article headlines, and bodies using the links captured in the previous step.
Let’s install the Scrapy and start our Scrapy project.
# Install the scrapy$ pip install scrapy# Start web scraping project with scrapys$ scrapy startproject TRTWorld$ cd TRTWorldTRTWorld $ scrapy genspider Articles trtworld.comTRTWorld $ scrapy genspider ArticleScraper trtworld.com
Our first spider which is “Articles.py” will get the article links by visiting 500 TRTWorld web pages. It will be extracting the href information of the article links available at each page and storing them in a JSON file.
# Spider 1 # Articles.py which scrape article links# importsimport scrapyfrom scrapy.http import Requestfrom TRTWorld.items import TrtworldItemclass ArticlesSpider(scrapy.Spider): name = 'Articles' allowed_domains = ['trtworld.com'] start_urls = ['http://trtworld.com/']def start_requests(self):# Hardcoded URL that contains TURKEY related subjects url="https://www.trtworld.com/turkey?page={}"link_urls = [url.format(i) for i in range(0,500)]# Loops through 500 pages to get the article links for link_url in link_urls:print(link_url)# Request to get the HTML content request=Request(link_url, cookies={'store_language':'en'}, callback=self.parse_main_pages)yield requestdef parse_main_pages(self,response):item=TrtworldItem()# Gets HTML content where the article links are stored content=response.xpath('//div[@id="items"]//div[@class="article- meta"]')# Loops through the each and every article link in HTML 'content' for article_link in content.xpath('.//a'):# Extracts the href info of the link to store in scrapy item item['article_url'] = article_link.xpath('.//@href').extract_first()item['article_url'] = "https://www.trtworld.com"+item['article_url']yield(item)def parse(self, response): pass
After we finalized our first spider, we can now run it with the below command to generate “article_links” JSON file.
TRTWorld $ scrapy crawl -o article_links.json -t json Articles
The next step is to scrape the news articles using the links stored in the JSON file. To do this, let’s create our second spider which is “ArticleScraper”.
# Spider 2# ArticleScraper.py which scrape article headlies and bodies# importsimport scrapyfrom scrapy.http import Requestfrom TRTWorld.items import TrtworldItemimport jsonclass ArticlescraperSpider(scrapy.Spider): name = 'ArticleScraper' allowed_domains = ['trtworld.com'] start_urls = ['http://trtworld.com/']def start_requests(self): # Open the JSON file which contains article links with open('/Users/erdemisbilen/Angular/TRTWorld /article_links.json') as json_file: data = json.load(json_file) for p in data: print('URL: ' + p['article_url'])# Request to get the HTML content request=Request(p['article_url'], cookies={'store_language':'en'}, callback=self.parse_article_page) yield requestdef parse_article_page(self,response):item=TrtworldItem() a_body=""# Extracts the article_title and stores in scrapy item item['article_title']=response.xpath('//h1[@class="article- title"]/text()').extract();# Extracts the article_description and stores in scrapy item item['article_description']=response.xpath('//h3[@class="article- description "]/text()').extract();# Extracts the article_body in <p> elements for p in response.xpath('//div[@class="contentBox bg-w noMedia"]//p/text()').extract(): a_body=a_body+p item['article_body']= a_body yield(item)def parse(self, response): pass
Below command runs the ArticleScraper spider and generates a JSON file containing the 3000 news articles. You can see below the content of the JSON file that the spider produced.
TRTWorld $ scrapy crawl -o article_body.json -t json ArticleScraper
Now that you have around 3000 articles stored in our JSON file, we can start to consider using them in our experimental NLP studies.
To use any text data in NLP applications, we have to convert the text into the numbers as computers have difficulty to understand the words.
Before doing this, we should clean and normalize our text. This step transforms our text into a more simple and structured form so that machine learning algorithms can perform efficiently and better.
In our case, we have news articles containing well-structured sentences so we may not need to apply all of the pre-processes listed below. See an example article below.
Let’s start with installing the ‘spaCy’ and required dependencies of it.
# Install the spaCypip install -U spacy# Install the spaCy Lemmatizationpip install -U spacy-lookups-data# Install the spaCy English Modelpython -m spacy download en_core_web_sm
To clean and normalize the text, we will be applying below processes into our text:
Sentence Segmentation
At first, we will be splitting each article into the sentences. Then we will be cleaning and normalizing each sentence with the help of the spaCy library.
# Splitting text into sentences using spaCydef split_sentences(document): sentences = [sent.string.strip() for sent in doc.sents] return sentences
Removing Stopwords
Stopwords are the most commonly used words in a language and do not help in NLP tasks such as sentiment analysis or text classification. So, you may consider to remove them from the text to increase the speed and accuracy of the model.
In our case, I used spaCy’s built-in stopwords. You can customize the default stopwords according to your domain-specific requirements.
# Removes stopwords from a sentence using spaCy (token.is_stop)def remove_stopwords(sentence): sentence = nlp(sentence) processed_sentence = ' '.join([token.text for token in sentence if token.is_stop != True ]) return processed_sentence# Removes stopwords from spaCy default stopword listnlp.Defaults.stop_words -= {"my_stopword_1", "my_stopword_2"}# Adds custom stopwords into spaCy default stopword listnlp.Defaults.stop_words |= {"my_stopword_1", "my_stopword_2"}# Prints spaCy default stopwordsprint(nlp.Defaults.stop_words)
Removing Punctuations, Quotes, Brackets, Currency Chars and Digits
Oftentimes, we just want words in our NLP pipeline, which means that we have to remove the punctuation and other special characters from the sentence including the digits.
# Removes punctuation and special chars from a sentence using spaCy def remove_punctuation_special_chars(sentence): sentence = nlp(sentence) processed_sentence = ' '.join([token.text for token in sentence if token.is_punct != True and token.is_quote != True and token.is_bracket != True and token.is_currency != True and token.is_digit != True]) return processed_sentence# spaCy - List of special charecters to be removed_currency = r"\$ £ € ¥ ฿ US\$ C\$ A\$ ₽ ریال ₴"_punct = ( r"... ...... , : ; \! \? ¿ ؟ ¡ \( \) \[ \] \{ \} < > _ # \* & 。 ? ! , 、 ; : ~ · । ، ۔ ؛ ٪" )_quotes = r'\' " ” “ ` ‘ ́ ’ ‚ , „ » « 「 」 『 』 ( ) 〔 〕 【 】 《 》 〈 〉'
Lemmatization
Lemmatization is reverting the word to its base form. This is achieved by reducing the inflectional and derivationally related forms of a word to its base form.
Lemmatization aims to reduce the vocabulary count and to normalize the words.
# Lemmatization process with spaCydef lemmatize_text(sentence): sentence = nlp(sentence) processed_sentence = ' '.join([word.lemma_ for word in sentence]) return processed_sentence
You can see above how the sentences are modified after the Lemmatization and stop word removal.
Depending on the NLP task in hand, you may consider not to apply some of the cleaning and normalization processes, as there will be some level of information loss in each of the processes described above.
In some cases, we may want to see the word frequencies to understand the content of a text. ‘spaCy’ provides easy to apply tools to achieve this. Below, you can see the complete Python script containing the text pre-processing and word frequency calculation functions.
# JSONtoTXT.py# Reads news articles from a JSON file# Splits the content into sentences# Cleans and normalizes the content# Write each processed sentence into a text fileimport jsonimport spacyfrom spacy.lang.en import English # updatedfrom spacy.lang.en.stop_words import STOP_WORDSfrom collections import Counterimport re# Loads the spaCy small English language modelnlp = spacy.load('en_core_web_sm')# Removes stopwords from spaCy default stopword listnlp.Defaults.stop_words -= {"my_stopword_1", "my_stopword_2"}# Adds custom stopword into spaCy default stopword listnlp.Defaults.stop_words |= {"my_stopword_1", "my_stopword_2"}print(nlp.Defaults)# Calculates the frequency of words in a documentdef word_frequency(my_doc):# all tokens that arent stop words or punctuations words = [token.text for token in my_doc if token.is_stop != True and token.is_punct != True]# noun tokens that arent stop words or punctuations nouns = [token.text for token in my_doc if token.is_stop != True and token.is_punct != True and token.pos_ == "NOUN"]# verb tokens that arent stop words or punctuations verbs = [token.text for token in my_doc if token.is_stop != True and token.is_punct != True and token.pos_ == "VERB"]# five most common words word_freq = Counter(words) common_words = word_freq.most_common(5) print("---------------------------------------") print("5 MOST COMMON TOKEN") print(common_words) print("---------------------------------------") print("---------------------------------------")# five most common nouns noun_freq = Counter(nouns) common_nouns = noun_freq.most_common(5) print("5 MOST COMMON NOUN") print(common_nouns) print("---------------------------------------") print("---------------------------------------")# five most common verbs verb_freq = Counter(verbs) common_verbs = verb_freq.most_common(5) print("5 MOST COMMON VERB") print(common_verbs) print("---------------------------------------") print("---------------------------------------")# Removes stopwords from a sentence using spaCy (token.is_stop)def remove_stopwords(sentence): sentence = nlp(sentence) processed_sentence = ' '.join([token.text for token in sentence if token.is_stop != True ]) return processed_sentence# Removes punctuation and special chars from a sentence using spaCydef remove_punctuation_special_chars(sentence): sentence = nlp(sentence) processed_sentence = ' '.join([token.text for token in sentence if token.is_punct != True and token.is_quote != True and token.is_bracket != True and token.is_currency != True and token.is_digit != True]) return processed_sentence# Lemmatization process with spaCydef lemmatize_text(sentence): sentence = nlp(sentence) processed_sentence = ' '.join([word.lemma_ for word in sentence]) return processed_sentencedef remove_special_chars(text): bad_chars = ["%", "#", '"', "*"] for i in bad_chars: text = text.replace(i, '') return text# Splitting text into sentences using spaCydef split_sentences(document): sentences = [sent.string.strip() for sent in doc.sents] return sentencessentence_index = 0with open('/Users/erdemisbilen/TFvenv/articles_less.json') as json_file: data = json.load(json_file) with open("article_all.txt", "w") as text_file: for p in data: article_body = p['article_body'] article_body = remove_special_chars(article_body)doc = nlp(article_body)sentences = split_sentences(doc) word_frequency(doc)for sentence in sentences: sentence_index +=1 print("Sentence #" + str(sentence_index) + "-----------------") print("Original Sentence : " + sentence) sentence = remove_stopwords(sentence) sentence = remove_punctuation_special_chars(sentence) print("Stopwors and Punctuation Removal: " + sentence) sentence = lemmatize_text(sentence) print("Lemmitization Applied : " + sentence) text_file.write(sentence + '\n') text_file.close()
You can see below, what the script produces after processing the news articles.
Now that we cleaned and normalized our text as well as splitting it into sentences, it is time to construct a data pipeline with Tensorflow 2.0.
In many cases, feeding the text content directly into the NLP model is not an efficient way of managing the data input process.
Tensorflow ‘tf.data API’ provides better performance with considering flexibility and efficiency. I encourage you to watch this video if you would like to understand why ‘tf.data’ is better than the conventional data pipelines.
I will be using Tensorflow “tf.data.TextLineDataset API” to construct my NLP data pipeline.
Let’s start with installing the “TensorFlow” and “tensorflow-datasets”.
# Install the tensorflow with pip$ pip install tensorflow# Install the tensorflow-datasets with pip$ pip install tensorflow-datasets
I will mainly follow the “Load text” tutorial provided by the TensorFlow to develop my data pipeline.
First, we will use “tf.data.TextLineDataset” with the “articlesTXT.txt” file we generated in previous steps to construct our dataset.
Although we have only one txt file in our data pipeline, the code below provides the ability to load and label several txt files.
parent_dir = "/Users/erdemisbilen/Angular/TRTWorld/articlesTXT"FILE_NAMES = ['article_all.txt']BUFFER_SIZE = 2000BATCH_SIZE = 128TAKE_SIZE = 200def labeler(example, index): return example, tf.cast(index, tf.int64)labeled_data_sets = []for i, file_name in enumerate(FILE_NAMES): lines_dataset = tf.data.TextLineDataset(os.path.join(parent_dir, file_name)) labeled_dataset = lines_dataset.map(lambda ex: labeler(ex, i)) labeled_data_sets.append(labeled_dataset)all_labeled_data = labeled_data_sets[0]for labeled_dataset in labeled_data_sets[1:]: all_labeled_data = all_labeled_data.concatenate(labeled_dataset) all_labeled_data = all_labeled_data.shuffle( BUFFER_SIZE, reshuffle_each_iteration=False)
Then we will use “tfds.features.text.Tokenizer” to split the sentences into the tokens and construct our vocabulary set.
tokenizer = tfds.features.text.Tokenizer()vocabulary_set = set()for text_tensor, _ in all_labeled_data: some_tokens = tokenizer.tokenize(text_tensor.numpy()) vocabulary_set.update(some_tokens)vocab_size = len(vocabulary_set)print("Vocabulary size. :" + str(vocab_size))print("-------------------------------")print(vocabulary_set)print("-------------------------------")
Once we created our vocabulary set, the next step is to encode each word in our vocabulary by assigning a unique integer value for each of the words in our vocabulary set. This is an index-based encoding process which maps each word with a unique index number.
encoder = tfds.features.text.TokenTextEncoder(vocabulary_set)example_text = next(iter(all_labeled_data))[0].numpy()print(example_text)encoded_example = encoder.encode(example_text)print(encoded_example)
Then, we can encode the whole dataset using a map function.
def encode(text_tensor, label): encoded_text = encoder.encode(text_tensor.numpy()) return encoded_text, labeldef encode_map_fn(text, label): encoded_text, label = tf.py_function(encode, inp=[text, label], Tout=(tf.int64, tf.int64)) return encoded_text, labelall_encoded_data = all_labeled_data.map(encode_map_fn)
Our dataset contains sentences with varying length. Now, the final step is to pad each dataset item to a certain size vector as many NLP models use fixed-length vector dimensions.
Meantime, we will be batching the content of the dataset with a batch size of 128. This will be the number of dataset items we will input to the model for each iteration of the training process.
train_data = all_encoded_data.skip(TAKE_SIZE).shuffle(BUFFER_SIZE)train_data = train_data.padded_batch(BATCH_SIZE, padded_shapes=([200],()))test_data = all_encoded_data.take(TAKE_SIZE)test_data = test_data.padded_batch(BATCH_SIZE, padded_shapes=([200],()))sample_text, sample_labels = next(iter(test_data))sample_text[0], sample_labels[0]
After padding, all sentences in our dataset represented as a vector (with size 200) as shown below.
Now that our data pipeline is ready, we can start building an LSTM model to test our data pipeline.
#Training a LSTM model to test the data pipelinevocab_size += 1model = tf.keras.Sequential()model.add(tf.keras.layers.Embedding(vocab_size, 64))model.add(tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64)))for units in [64, 64]: model.add(tf.keras.layers.Dense(units, activation='relu'))# Output layer. The first argument is the number of labels.model.add(tf.keras.layers.Dense(3, activation='softmax'))optimizer = tf.keras.optimizers.Adam(learning_rate=0.005, amsgrad=True)model.compile(optimizer= optimizer, loss='sparse_categorical_crossentropy', metrics=['accuracy'])log_dir="logs/fit/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=1)model.fit(train_data, epochs=10, steps_per_epoch=4, validation_data=test_data, callbacks=[tensorboard_callback])eval_loss, eval_acc = model.evaluate(test_data)print('\nEval loss: {:.3f}, Eval accuracy: {:.3f}'.format(eval_loss, eval_acc))
You can see above the data is fed into the model successfully with the data pipeline we constructed.
In this post, I tried to explain my way of building an NLP data pipeline from scratch. I hope my article helps you to build your NLP application. | [
{
"code": null,
"e": 351,
"s": 172,
"text": "Although it is ok to experiment with the ready-to-use datasets, generating your NLP data pipeline further improves your skills and gives you more freedom in your project choices."
},
{
"code": null,
"e": 517,
"s": 351,
"text": "In this... |
java.lang.reflect.Method.invoke() Method Example | The java.lang.reflect.Method.invoke(Object obj, Object... args) method invokes the underlying method represented by this Method object, on the specified object with the specified parameters. Individual parameters are automatically unwrapped to match primitive formal parameters, and both primitive and reference parameters are subject to method invocation conversions as necessary.
Following is the declaration for java.lang.reflect.Method.invoke(Object obj, Object... args) method.
public Object invoke(Object obj, Object... args)
throws IllegalAccessException, IllegalArgumentException,
InvocationTargetException
obj − the object the underlying method is invoked from.
obj − the object the underlying method is invoked from.
args − the arguments used for the method call.
args − the arguments used for the method call.
the result of dispatching the method represented by this object on obj with parameters args.
IllegalAccessException − if this Method object is enforcing Java language access control and the underlying method is inaccessible.
IllegalAccessException − if this Method object is enforcing Java language access control and the underlying method is inaccessible.
IllegalArgumentException − if the method is an instance method and the specified object argument is not an instance of the class or interface declaring the underlying method (or of a subclass or implementor thereof); if the number of actual and formal parameters differ; if an unwrapping conversion for primitive arguments fails; or if, after possible unwrapping, a parameter value cannot be converted to the corresponding formal parameter type by a method invocation conversion.
IllegalArgumentException − if the method is an instance method and the specified object argument is not an instance of the class or interface declaring the underlying method (or of a subclass or implementor thereof); if the number of actual and formal parameters differ; if an unwrapping conversion for primitive arguments fails; or if, after possible unwrapping, a parameter value cannot be converted to the corresponding formal parameter type by a method invocation conversion.
InvocationTargetException − if the underlying method throws an exception.
InvocationTargetException − if the underlying method throws an exception.
NullPointerException − if the specified object is null and the method is an instance method.
NullPointerException − if the specified object is null and the method is an instance method.
ExceptionInInitializerError − if the initialization provoked by this method fails.
ExceptionInInitializerError − if the initialization provoked by this method fails.
The following example shows the usage of java.lang.reflect.Method.invoke(Object obj, Object... args) method.
package com.tutorialspoint;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class MethodDemo {
public static void main(String[] args)
throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Method[] methods = SampleClass.class.getMethods();
SampleClass sampleObject = new SampleClass();
methods[1].invoke(sampleObject, "data");
System.out.println(methods[0].invoke(sampleObject));
}
}
class SampleClass {
private String sampleField;
public String getSampleField() {
return sampleField;
}
public void setSampleField(String sampleField) {
this.sampleField = sampleField;
}
}
Let us compile and run the above program, this will produce the following result −
data
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1836,
"s": 1454,
"text": "The java.lang.reflect.Method.invoke(Object obj, Object... args) method invokes the underlying method represented by this Method object, on the specified object with the specified parameters. Individual parameters are automatically unwrapped to match pri... |
Search an element of Vector in Java | An element of a Vector can be searched using the method java.util.ArrayList.indexOf(). This method returns the index of the first occurrence of the element that is specified. If the element is not available in the Vector, then this method returns -1.
A program that demonstrates this is given as follows:
Live Demo
import java.util.Vector;
public class Demo {
public static void main(String args[]) {
Vector vec = new Vector(5);
vec.add(4);
vec.add(1);
vec.add(7);
vec.add(9);
vec.add(2);
vec.add(8);
System.out.println("The Vector elements are: " + vec);
System.out.println("The index of element 9 in Vector is: " + vec.indexOf(9));
System.out.println("The index of element 5 in Vector is: " + vec.indexOf(5));
}
}
The output of the above program is as follows:
The Vector elements are: [4, 1, 7, 9, 2, 8]
The index of element 9 in Vector is: 3
The index of element 5 in Vector is: -1
Now let us understand the above program.
The Vector is created. Then Vector.add() is used to add the elements to the Vector. Vector.indexOf() returns the index of the first occurrence of elements 9 and 5 and that is displayed. A code snippet which demonstrates this is as follows:
Vector vec = new Vector(5);
vec.add(4);
vec.add(1);
vec.add(7);
vec.add(9);
vec.add(2);
vec.add(8);
System.out.println("The Vector elements are: " + vec);
System.out.println("The index of element 9 in Vector is: " + vec.indexOf(9));
System.out.println("The index of element 5 in Vector is: " + vec.indexOf(5)); | [
{
"code": null,
"e": 1313,
"s": 1062,
"text": "An element of a Vector can be searched using the method java.util.ArrayList.indexOf(). This method returns the index of the first occurrence of the element that is specified. If the element is not available in the Vector, then this method returns -1."
... |
Set Countdown timer to Capture Image using Python-OpenCV - GeeksforGeeks | 03 Jun, 2021
Prerequisites: Introduction to OpenCV
Most of us have already captured image using countdown timer with our phones. We can do the same thing on our computer with the help of OpenCV.
But here we can specify the countdown timer instead of choosing one of the specified countdown and whenever the particular key will be pressed (let’s say q) the countdown timer will be started and we will be displaying the countdown on our camera with the help of cv2.putText() function and when it reaches zero we will capture the image, display the captured image for fixed number of seconds (according to our need ) and write/save the image on disk. Now let’s see how to perform this task:
Approach:
First, we will be setting the initial value of Countdown timer in second. (We can also take this as input from user).
Open the camera and create a video Capture object using cv2.VideoCapture().
While camera is openWe will read each frame and display it using cv2.imshow().Now we will set a key (we use q ) for the countdown to begin.As soon as this key will be pressed, we will start the Countdown.We will be keeping track of countdown with the help of time.time() function and display the countdown on the video using cv2.putText() function.When it reaches zero, we will copy the current frame and write the current frame at desired location on disk by using cv2.imwrite() function.On pressing ‘Esc’ we will close the camera.
We will read each frame and display it using cv2.imshow().
Now we will set a key (we use q ) for the countdown to begin.
As soon as this key will be pressed, we will start the Countdown.
We will be keeping track of countdown with the help of time.time() function and display the countdown on the video using cv2.putText() function.
When it reaches zero, we will copy the current frame and write the current frame at desired location on disk by using cv2.imwrite() function.
On pressing ‘Esc’ we will close the camera.
Below is the implementation.
Python3
import cv2import time # SET THE COUNTDOWN TIMER# for simplicity we set it to 3# We can also take this as inputTIMER = int(20) # Open the cameracap = cv2.VideoCapture(0) while True: # Read and display each frame ret, img = cap.read() cv2.imshow('a', img) # check for the key pressed k = cv2.waitKey(125) # set the key for the countdown # to begin. Here we set q # if key pressed is q if k == ord('q'): prev = time.time() while TIMER >= 0: ret, img = cap.read() # Display countdown on each frame # specify the font and draw the # countdown using puttext font = cv2.FONT_HERSHEY_SIMPLEX cv2.putText(img, str(TIMER), (200, 250), font, 7, (0, 255, 255), 4, cv2.LINE_AA) cv2.imshow('a', img) cv2.waitKey(125) # current time cur = time.time() # Update and keep track of Countdown # if time elapsed is one second # than decrease the counter if cur-prev >= 1: prev = cur TIMER = TIMER-1 else: ret, img = cap.read() # Display the clicked frame for 2 # sec.You can increase time in # waitKey also cv2.imshow('a', img) # time for which image displayed cv2.waitKey(2000) # Save the frame cv2.imwrite('camera.jpg', img) # HERE we can reset the Countdown timer # if we want more Capture without closing # the camera # Press Esc to exit elif k == 27: break # close the cameracap.release() # close all the opened windowscv2.destroyAllWindows()
Output:
Akanksha_Rai
sumitgumber28
Python-OpenCV
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
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Python | Get unique values from a list
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n03 Jun, 2021"
},
{
"code": null,
"e": 24330,
"s": 24292,
"text": "Prerequisites: Introduction to OpenCV"
},
{
"code": null,
"e": 24474,
"s": 24330,
"text": "Most of us have already captured image using countdo... |
Selenium WebDriver StaleElementReferenceException. | We have StaleElementReferenceException in Selenium webdriver. As the name suggests, the word stale refers to something which is not new and perished. There may be a scenario in which an element which was present in DOM previously is now no longer available due to modification in DOM.
In such a condition, if we try to access that element then StaleElementReferenceException is thrown. This type of exception is encountered due to the below reasons −
The element is not present in the DOM any more.
The element is not present in the DOM any more.
The element has been removed totally.
The element has been removed totally.
There are certain ways we can prevent a StaleElementReferenceException as described below −
We can reload the webpage and try to interact with the same element.
driver.navigate().refresh();
driver.findElement(By.id("txt")).sendKeys("Selenium");
We can add a try catch block and interact with the same element. Here with for loop, there shall be five attempts. If the element is identified before the five attempts, there shall be exit from the loop.
for(int k=0; k<=5;k++){
try{
driver.findElement(By.id("txt")).sendKeys("Selenium");
break;
}
catch(Exception exp){
System.out.println(exp.message());
}
}
To prevent a StaleElementReferenceException we can add the explicit wait [synchronization] to wait for the element till the element is rendered in DOM with the help of the expected condition presenceOfElementLocated.
w.until(ExpectedConditions.presenceOfElementLocated(By.name("presence"))); | [
{
"code": null,
"e": 1347,
"s": 1062,
"text": "We have StaleElementReferenceException in Selenium webdriver. As the name suggests, the word stale refers to something which is not new and perished. There may be a scenario in which an element which was present in DOM previously is now no longer availa... |
JavaScript - Array indexOf() Method | JavaScript array indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
Its syntax is as follows −
array.indexOf(searchElement[, fromIndex]);
searchElement − Element to locate in the array.
searchElement − Element to locate in the array.
fromIndex − The index at which to begin the search. Defaults to 0, i.e. the whole array will be searched. If the index is greater than or equal to the length of the array, -1 is returned.
fromIndex − The index at which to begin the search. Defaults to 0, i.e. the whole array will be searched. If the index is greater than or equal to the length of the array, -1 is returned.
Returns the index of the found element.
This method is a JavaScript extension to the ECMA-262 standard; as such it may not be present in other implementations of the standard. To make it work, you need to add the following code at the top of your script.
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(elt /*, from*/) {
var len = this.length;
var from = Number(arguments[1]) || 0;
from = (from < 0)
? Math.ceil(from)
: Math.floor(from);
if (from < 0)
from += len;
for (; from < len; from++) {
if (from in this &&
this[from] === elt)
return from;
}
return -1;
};
}
Try the following example.
<html>
<head>
<title>JavaScript Array indexOf Method</title>
</head>
<body>
<script type = "text/javascript">
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(elt /*, from*/) {
var len = this.length;
var from = Number(arguments[1]) || 0;
from = (from < 0)
? Math.ceil(from)
: Math.floor(from);
if (from < 0)
from += len;
for (; from < len; from++) {
if (from in this &&
this[from] === elt)
return from;
}
return -1;
};
}
var index = [12, 5, 8, 130, 44].indexOf(8);
document.write("index is : " + index );
var index = [12, 5, 8, 130, 44].indexOf(13);
document.write("<br />index is : " + index );
</script>
</body>
</html>
index is : 2
index is : -1
25 Lectures
2.5 hours
Anadi Sharma
74 Lectures
10 hours
Lets Kode It
72 Lectures
4.5 hours
Frahaan Hussain
70 Lectures
4.5 hours
Frahaan Hussain
46 Lectures
6 hours
Eduonix Learning Solutions
88 Lectures
14 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2604,
"s": 2466,
"text": "JavaScript array indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present."
},
{
"code": null,
"e": 2631,
"s": 2604,
"text": "Its syntax is as follows −"
},
{
"co... |
Shell Script To Check That Input Only Contains Alphanumeric Characters | 09 Apr, 2021
If you want an input which contains only alphanumeric characters i.e. 1-9 or a-z lower case as well as upper case characters, We can make use of regular expression or Regex in short in a Shell Script to verify the input.
Example:
Input: Geeksforgeeks
Output: True
Explanation: Here all the inputted data are alphanumeric
Input: Geeks@for@geeks
Output: False
Explanation: @ is not alphanumeric
Here our task is to write a script to take inputs a variable, and it checks that the input string from start to end has only numbers or alphabets(lower or upper case). If there are any other special characters the condition in the while loop will evaluate to false and hence the while loop will get executed, and it inputs the variable again, and then it again checks for the while loop condition of alphanumeric characters. The loop will continue until the user inputs only alphanumeric and non-empty string or number. \
#!/bin/bash
# Input from user
read -p "Input : " inp
# While loop for alphanumeric characters and a non-zero length input
while [[ "$inp" =~ [^a-zA-Z0-9] || -z "$inp" ]]
do
echo "The input contains special characters."
echo "Input only alphanumeric characters."
# Input from user
read -p "Input : " inp
#loop until the user enters only alphanumeric characters.
done
echo "Successful Input"
Output:
Bash Script Output
The following screenshot of the test case of the code is executed, and it only accepts non-empty alphanumeric input. It even rejects an empty input and other characters excluding alphabets and numbers. The following code is a regular expression to check for numbers or alphabets from start(^) till the end($) and a condition of empty input ( -z stands for the length of zero). So, the shell script will prompt the user again and again until he/she inputs an alphanumeric character.
Picked
Shell Script
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n09 Apr, 2021"
},
{
"code": null,
"e": 275,
"s": 54,
"text": "If you want an input which contains only alphanumeric characters i.e. 1-9 or a-z lower case as well as upper case characters, We can make use of regular expression or Regex i... |
numpy.flipud() in Python | 28 Mar, 2022
The numpy.flipud() function flips the array(entries in each column) in up-down direction, shape preserved. Syntax:
numpy.flipud(array)
Parameters :
array : [array_like]Input array, we want to flip
Return :
Flipped array in up-down direction.
Python
# Python Program illustrating# numpy.flipud() method import numpy as geek array = geek.arange(8).reshape((2,2,2))print("Original array : \n", array) # flipud : means flip up-downprint("\nFlipped array : \n", geek.flipud(array))
Output :
Original array :
[[[0 1]
[2 3]]
[[4 5]
[6 7]]]
Flipped array :
[[[4 5]
[6 7]]
[[0 1]
[2 3]]]
References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.flipud.html#numpy.flipud
Note : These codes won’t run on online IDE’s. So please, run them on your systems to explore the working.
This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
vinayedula
Python numpy-arrayManipulation
Python-numpy
Misc
Python
Misc
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Mar, 2022"
},
{
"code": null,
"e": 144,
"s": 28,
"text": "The numpy.flipud() function flips the array(entries in each column) in up-down direction, shape preserved. Syntax: "
},
{
"code": null,
"e": 164,
"s": 144,
... |
SVG pointer-events Attribute | 31 Mar, 2022
The pointer-events attribute allows us to define whether or when an element may be the target of a mouse event. It is applied on the following elements: <a>, <circle>, <clipPath>, <defs>, <ellipse>, <foreignObject>, <g>, <image>, <line>, <marker>, <mask>, <path>, <pattern>, <polygon>, <polyline>, <rect>, <svg>, <switch>, <symbol>, <text>, <textPath>, <tspan>, <use>.
Syntax:
pointer-events = bounding-box | visiblePainted | visibleFill |
visibleStroke | visible | painted | fill |
stroke | all | none
Attribute Values: The pointer-events attribute accepts the values mentioned above and described below:
auto: It is used to describe that an element must react to pointer events.
none: It is used to describe that an element does not react to pointer-events.
visiblePainted: This value can only be the target of a pointer event when the mouse cursor is over the interior or the perimeter of the element and the fill or stroke property is set to a value other than none.
visibleFill: This value can only be the target of a pointer event when a mouse cursor is over the interior of the element.
visibleStroke: This value can only be the target of a pointer event when the mouse cursor is over the perimeter of the element.
visible: This value can only be the target of a pointer event when the mouse cursor is over either the interior or the perimeter of the element.
painted: This value can only be the target of a pointer event when the mouse cursor is over the interior or the perimeter of the element and the fill or stroke property is set to a value other than none.
fill: This value can only be the target of a pointer event when the pointer is over the interior of the element.
stroke: This value can only be the target of a pointer event when the pointer is over the perimeter of the element.
all: This value can only be the target of a pointer event when the pointer is over the interior or the perimeter of the element.
Below examples illustrate the use of pointer-events attribute.
Example 1:
HTML
<!DOCTYPE html><html> <body> <div style="color: green;"> <h2> GeeksforGeeks </h2> <svg viewBox="0 0 100 10" xmlns="http://www.w3.org/2000/svg"> <rect x="3" y="0" height="10" width="10" fill="green" /> <ellipse cx="8" cy="5" rx="5" ry="4" fill="black" pointer-events="visiblePainted" /> </svg> </div> <script> window.addEventListener( 'mouseup', (e) => { let geekColor = Math.round(Math.random() * 0xFFFFFF) let fill = '#' + geekColor.toString(16). padStart(5, '0') e.target.style.fill = fill }); </script></body> </html>
Output:
Example 2:
HTML
<!DOCTYPE html><html> <body> <div style="color: green;"> <h2> GeeksforGeeks </h2> <svg viewBox="0 0 100 10" xmlns="http://www.w3.org/2000/svg"> <rect x="3" y="0" height="10" width="10" fill="green" /> <ellipse cx="8" cy="5" rx="5" ry="4" fill="black" pointer-events="none" /> </svg> </div> <script> window.addEventListener( 'mouseup', (e) => { let geekColor = Math.round(Math.random() * 0xFFFFFF) let fill = '#' + geekColor.toString(16). padStart(6, '0') e.target.style.fill = fill }); </script></body> </html>
Output:
HTML-SVG
SVG-Attribute
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 Mar, 2022"
},
{
"code": null,
"e": 397,
"s": 28,
"text": "The pointer-events attribute allows us to define whether or when an element may be the target of a mouse event. It is applied on the following elements: <a>, <circle>, <clipPa... |
time.NewTimer() Function in Golang With Examples | 21 Apr, 2020
In Go language, time packages supplies functionality for determining as well as viewing time. The NewTimer() function in Go language is used to create a new Timer that will transmit the actual time on its channel at least after duration “d”. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions.
Syntax:
func NewTimer(d Duration) *Timer
Here, *Timer is a pointer to the Timer.
Return Value: It returns a channel that notifies how long a timer will have to wait.
Example 1:
// Golang program to illustrate the usage of// NewTimer() function // Including main packagepackage main // Importing fmt and timeimport ( "fmt" "time") // Main functionfunc main() { // Calling NewTimer method newtimer := time.NewTimer(5 * time.Second) // Notifying the channel <-newtimer.C // Printed after 5 seconds fmt.Println("Timer is inactivated")}
Output:
Timer is inactivated
Here, the above output is printed after 5 seconds of running the code, as after that stated time the channel is being notified that the timer is inactivated.
Example 2:
// Golang program to illustrate the usage of// NewTimer() function // Including main packagepackage main // Importing fmt and timeimport ( "fmt" "time") // Main functionfunc main() { // Calling NewTimer method newtimer := time.NewTimer(time.Second) // Notifying channel under go function go func() { <-newtimer.C // Printed when timer is fired fmt.Println("timer inactivated") }() // Calling stop method to stop the // timer before inactivation stoptimer := newtimer.Stop() // If the timer is stopped then the // below string is printed if stoptimer { fmt.Println("The timer is stopped!") } // Calling sleep method to stop the // execution at last time.Sleep(4 * time.Second)}
Output:
The timer is stopped!
In the above method, the timer is being stopped before inactivating as here the stop method is being called to stop the timer. And at last, the program is exited using sleep method.
GoLang-time
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Apr, 2020"
},
{
"code": null,
"e": 406,
"s": 28,
"text": "In Go language, time packages supplies functionality for determining as well as viewing time. The NewTimer() function in Go language is used to create a new Timer that will tr... |
PyQt5 – Setting different toolTip to different item of ComboBox | 04 May, 2020
In this article we will see how we can set different tooltip to the different items of the combo box. We can set tooltip to the combo box with the help of setToolTip method and for setting tooltip to the view part we have to use view object with this method. Below is the representation of how individual item tool tip look like.
In order to do we have to use the following method
combo_box.setItemData(index, tool_tip_text, QtCore.Qt.ToolTipRole)
Here index is the index of the item
tool_tip_text is the string which show as tool tip
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a combo box object self.combo_box = QComboBox(self) # setting geometry of combo box self.combo_box.setGeometry(200, 150, 150, 30) # geek list geek_list = ["Sayian", "Super Sayian", "Super Sayian 2", "Super Sayian B"] # adding list of items to combo box self.combo_box.addItems(geek_list) # setting tool tip to each item self.combo_box.setItemData(0, "This is a tooltip for item[0]", QtCore.Qt.ToolTipRole) self.combo_box.setItemData(1, "This is a tooltip for item[1]", QtCore.Qt.ToolTipRole) self.combo_box.setItemData(2, "This is a tooltip for item[2]", QtCore.Qt.ToolTipRole) self.combo_box.setItemData(3, "This is a tooltip for item[3]", QtCore.Qt.ToolTipRole) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() window.show() # start the appsys.exit(App.exec())
Output :
Python PyQt5-ComboBox
Python PyQt5-ComboBox-stylesheet
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 May, 2020"
},
{
"code": null,
"e": 358,
"s": 28,
"text": "In this article we will see how we can set different tooltip to the different items of the combo box. We can set tooltip to the combo box with the help of setToolTip method an... |
Manipulating DataFrames with Pandas – Python | 31 May, 2021
Before manipulating the dataframe with pandas we have to understand what is data manipulation. The data in the real world is very unpleasant & unordered so by performing certain operations we can make data understandable based on one’s requirements, this process of converting unordered data into meaningful information can be done by data manipulation.
Here, we will learn how to manipulate dataframes with pandas. Pandas is an open-source library that is used from data manipulation to data analysis & is very powerful, flexible & easy to use tool which can be imported using import pandas as pd. Pandas deal essentially with data in 1-D and 2-D arrays; Although, pandas handles these two differently. In pandas, 1-D arrays are stated as a series & a dataframe is simply a 2-D array. The dataset used here is country_code.csv.
Below are various operations used to manipulate the dataframe:
First, import the library which is used in data manipulation i.e. pandas then assign and read the dataframe:
Python3
# import moduleimport pandas as pd # assign datasetdf = pd.read_csv("country_code.csv") # displayprint("Type-", type(df))df
Output:
We can read the dataframe by using head() function also which is having an argument (n) i.e. number of rows to be displayed.
Python3
df.head(10)
Output:
Counting the rows and columns in DataFrame using shape(). It returns the no. of rows and columns enclosed in a tuple.
Python3
df.shape
Output:
Summary of Statistics of DataFrame using describe() method.
Python3
df.describe()
Output:
Dropping the missing values in DataFrame, it can be done using the dropna() method, it removes all the NaN values in the dataframe.
Python3
df.dropna()
Output:
Another example is:
Python3
df.dropna(axis=1)
This will drop all the columns with any missing values.
Output:
Merging DataFrames using merge(), arguments passed are the dataframes to be merged along with the column name.
Python3
df1 = pd.read_csv("country_code.csv")merged_col = pd.merge(df, df1, on='Name')merged_col
Output:
An additional argument ‘on’ is the name of the common column, here ‘Name’ is the common column given to the merge() function. df is the first dataframe & df1 is the second dataframe that is to be merged.
Renaming the columns of dataframe using rename(), arguments passed are the columns to be renamed & inplace.
Python3
country_code = df.rename(columns={'Name': 'CountryName', 'Code': 'CountryCode'}, inplace=False)country_code
Output:
The code ‘inplace = False’ means the result would be stored in a new DataFrame instead of the original one.
Creating a dataframe manually:
Python3
student = pd.DataFrame({'Name': ['Rohan', 'Rahul', 'Gaurav', 'Ananya', 'Vinay', 'Rohan', 'Vivek', 'Vinay'], 'Score': [76, 69, 70, 88, 79, 64, 62, 57]}) # Reading Dataframestudent
Output:
Sorting the DataFrame using sort_values() method.
Python3
student.sort_values(by=['Score'], ascending=True)
Output:
Sorting the DataFrame using multiple columns:
Python3
student.sort_values(by=['Name', 'Score'], ascending=[True, False])
Output:
Creating another column in DataFrame, Here we will create column name percentage which will calculate the percentage of student score by using aggregate function sum().
Python3
student['Percentage'] = (student['Score'] / student['Score'].sum()) * 100student
Output:
Selecting DataFrame rows using logical operators:
Python3
# Selecting rows where score is# greater than 70print(student[student.Score>70]) # Selecting rows where score is greater than 60# OR less than 70print(student[(student.Score>60) | (student.Score<70)])
Output:
Indexing & Slicing :
Here .loc is label base & .iloc is integer position based methods used for slicing & indexing of data.
Python3
# Printing five rows with name column only# i.e. printing first 5 student names.print(student.loc[0:4, 'Name']) # Printing all the rows with score column# only i.e. printing score of all the# studentsprint(student.loc[:, 'Score']) # Printing only first rows having name,# score columns i.e. print first student# name & their score.print(student.iloc[0, 0:2]) # Printing first 3 rows having name,score &# percentage columns i.e. printing first three# student name,score & percentage.print(student.iloc[0:3, 0:3]) # Printing all rows having name & score# columns i.e. printing all student# name & their score.print(student.iloc[:, 0:2])
Output:
.loc:
.iloc:
Apply Functions, this function is used to apply a function along an axis of dataframe whether it can be row (axis=0) or column (axis=1).
Python3
# explicit functiondef double(a): return 2*a student['Score'] = student['Score'].apply(double) # Reading Dataframestudent
Output:
prachisharma1320
Picked
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 May, 2021"
},
{
"code": null,
"e": 382,
"s": 28,
"text": "Before manipulating the dataframe with pandas we have to understand what is data manipulation. The data in the real world is very unpleasant & unordered so by performing certa... |
How to find common elements from multiple vectors in R ? | 21 Apr, 2021
In this article, we will discuss how to find the common elements from multiple vectors in R Programming Language.
To do this intersect() method is used. It is used to return the common elements from two objects.
Syntax: intersect(vector1,vector2)
where, vector is the input data.
If there are more than two vectors then we can combine all these vectors into one except one vector. Those combined vectors are passed as one argument and that remaining vector is passed as second argument.
Syntax: intersect(c(vector1,vector2,...,vector n),vector_m)
Example 1: R program to create two vectors and find the common elements.
So we are going to create a vector with elements.
R
# create vector bb = c(2, 3, 4, 5, 6, 7) # create vector aa = c(1, 2, 3, 4) # combine both the vectorsprint(intersect(b, a))
Output:
[1] 2 3 4
Example 2: R program to find common elements in two-character data.
We are taking two vectors which contain names and find the common elements.
R
# create vector bb = c("sravan", "gajji", "gnanesh") # create vector aa = c("sravan", "ojaswi", "gnanesh") # combine both the vectorsprint(intersect(b, a))
Output:
[1] "sravan" "gnanesh"
Example 3: Find common elements from multiple vectors in R.
So we are combining b and a first, and they are passed as the first argument in intersect function and then pass the d vector as the second argument.
R
# create vector bb = c(1, 2, 3, 4, 5) # create vector aa = c(3, 4, 5, 6, 7) # create vector dd = c(5, 6, 7, 8, 9) # combine both the vectors b and a as 1 # then combine with dprint(intersect(c(b, a), d))
Output:
[1] 5 6 7
Picked
R Vector-Programs
R-Vectors
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Apr, 2021"
},
{
"code": null,
"e": 142,
"s": 28,
"text": "In this article, we will discuss how to find the common elements from multiple vectors in R Programming Language."
},
{
"code": null,
"e": 240,
"s": 142,
"... |
Minimum adjacent swaps to group similar characters together | 16 Jul, 2021
Given a string S of length N, consisting of only lowercase English characters, the task is to find the minimum number of adjacent swaps required to group the same characters together.
Examples:
Input: S = “cbabc”Output: 4Explanation:Swap characters S[0] to S[1]. Therefore, S = “bcabc”.Swap characters S[1] to S[2]. Therefore, S = “bacbc”.Swap characters S[2] to S[3]. Therefore, S = “babcc”.Swap characters S[1] to S[2]. Therefore, S = “bbacc”.Hence, the total swaps required is 4.
Input: S = “abcd”Output: 0Explanation:All characters are distinct. Hence, no swapping is required.
Approach: The idea is to store the indices of each character. Then, for each character, find the adjacent absolute differences and add them to the answer. Follow the steps below to solve the problem:
Initialize a 2D vector arr[], where vector arr[i] will store the indices of character (i + ‘a’) and a variable answer initialized to 0.Iterate the given string over the range [0, N – 1].Add index i to arr[S[i] – ‘a’].After traversing the string, traverse the 2D vector arr[] from i = ‘a’ to ‘z’.For each character i, find the absolute adjacent differences of the indices of character i present in that vector and add them to the answer.After traversing the 2D vector, print the answer as the minimum number of swaps.
Initialize a 2D vector arr[], where vector arr[i] will store the indices of character (i + ‘a’) and a variable answer initialized to 0.
Iterate the given string over the range [0, N – 1].
Add index i to arr[S[i] – ‘a’].
After traversing the string, traverse the 2D vector arr[] from i = ‘a’ to ‘z’.
For each character i, find the absolute adjacent differences of the indices of character i present in that vector and add them to the answer.
After traversing the 2D vector, print the answer as the minimum number of swaps.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find minimum adjacent// swaps required to make all the// same character adjacentint minSwaps(string S, int n){ // Initialize answer int swaps = 0; // Create a 2D array of size 26 vector<vector<int> > arr(26); // Traverse the string for (int i = 0; i < n; i++) { // Get character int pos = S[i] - 'a'; // Append the current index in // the corresponding vector arr[pos].push_back(i); } // Traverse each character from a to z for (char ch = 'a'; ch <= 'z'; ++ch) { int pos = ch - 'a'; // Add difference of adjacent index for (int i = 1; i < arr[pos].size(); ++i) { swaps += abs(arr[pos][i] - arr[pos][i - 1] - 1); } } // Return answer return swaps;} // Driver Codeint main(){ // Given string string S = "abbccabbcc"; // Size of string int N = S.length(); // Function Call cout << minSwaps(S, N); return 0;}
// Java program for the above approachimport java.util.*; class GFG{ // Function to find minimum adjacent// swaps required to make all the// same character adjacentstatic int minSwaps(String S, int n){ // Initialize answer int swaps = 0; // Create a 2D array of size 26 @SuppressWarnings("unchecked") Vector<Integer> []arr = new Vector[26]; for(int i = 0; i < arr.length; i++) arr[i] = new Vector<Integer>(); // Traverse the String for(int i = 0; i < n; i++) { // Get character int pos = S.charAt(i) - 'a'; // Append the current index in // the corresponding vector arr[pos].add(i); } // Traverse each character from a to z for(char ch = 'a'; ch <= 'z'; ++ch) { int pos = ch - 'a'; // Add difference of adjacent index for(int i = 1; i < arr[pos].size(); ++i) { swaps += Math.abs(arr[pos].get(i) - arr[pos].get(i - 1) - 1); } } // Return answer return swaps;} // Driver Codepublic static void main(String[] args){ // Given String String S = "abbccabbcc"; // Size of String int N = S.length(); // Function Call System.out.print(minSwaps(S, N));}} // This code is contributed by Amit Katiyar
# Python3 program for the above approach # Function to find minimum adjacent# swaps required to make all the# same character adjacentdef minSwaps(S, n): # Initialize answer swaps = 0 # Create a 2D array of size 26 arr = [[] for i in range(26)] # Traverse the string for i in range(n): # Get character pos = ord(S[i]) - ord('a') # Append the current index in # the corresponding vector arr[pos].append(i) # Traverse each character from a to z for ch in range(ord('a'), ord('z') + 1): pos = ch - ord('a') # Add difference of adjacent index for i in range(1, len(arr[pos])): swaps += abs(arr[pos][i] - arr[pos][i - 1] - 1) # Return answer return swaps # Driver Codeif __name__ == '__main__': # Given string S = "abbccabbcc" # Size of string N = len(S) # Function Call print(minSwaps(S, N)) # This code is contributed by mohit kumar 29
// C# program for the// above approachusing System;using System.Collections.Generic;class GFG{ // Function to find minimum// adjacent swaps required// to make all the same// character adjacentstatic int minSwaps(String S, int n){ // Initialize answer int swaps = 0; // Create a 2D array // of size 26 List<int> []arr = new List<int>[26]; for(int i = 0; i < arr.Length; i++) arr[i] = new List<int>(); // Traverse the String for(int i = 0; i < n; i++) { // Get character int pos = S[i] - 'a'; // Append the current index in // the corresponding vector arr[pos].Add(i); } // Traverse each character // from a to z for(char ch = 'a'; ch <= 'z'; ++ch) { int pos = ch - 'a'; // Add difference of // adjacent index for(int i = 1; i < arr[pos].Count; ++i) { swaps += Math.Abs(arr[pos][i] - arr[pos][i - 1] - 1); } } // Return answer return swaps;} // Driver Codepublic static void Main(String[] args){ // Given String String S = "abbccabbcc"; // Size of String int N = S.Length; // Function Call Console.Write(minSwaps(S, N));}} // This code is contributed by gauravrajput1
<script>// Javascript program for the above approach // Function to find minimum adjacent// swaps required to make all the// same character adjacentfunction minSwaps(S,n){ // Initialize answer let swaps = 0; // Create a 2D array of size 26 let arr = new Array(26); for(let i = 0; i < arr.length; i++) arr[i] = []; // Traverse the String for(let i = 0; i < n; i++) { // Get character let pos = S[i].charCodeAt(0) - 'a'.charCodeAt(0); // Append the current index in // the corresponding vector arr[pos].push(i); } // Traverse each character from a to z for(let ch = 'a'.charCodeAt(0); ch <= 'z'.charCodeAt(0); ++ch) { let pos = ch - 'a'.charCodeAt(0); // Add difference of adjacent index for(let i = 1; i < arr[pos].length; ++i) { swaps += Math.abs(arr[pos][i] - arr[pos][i-1] - 1); } } // Return answer return swaps;} // Driver Code // Given Stringlet S = "abbccabbcc"; // Size of Stringlet N = S.length; // Function Calldocument.write(minSwaps(S, N)); // This code is contributed by patel2127</script>
10
Time Complexity: O(26*N)Auxiliary Space: O(N)
mohit kumar 29
amit143katiyar
GauravRajput1
patel2127
Greedy
Searching
Strings
Searching
Strings
Greedy
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Jul, 2021"
},
{
"code": null,
"e": 212,
"s": 28,
"text": "Given a string S of length N, consisting of only lowercase English characters, the task is to find the minimum number of adjacent swaps required to group the same characters t... |
Matplotlib.pyplot.quiver() in Python - GeeksforGeeks | 12 Apr, 2020
Matplotlib is a library of Python bindings which provides the user with a MATLAB-like plotting framework. Matplotlib can be used in Python scripts, the Python and IPython shell, web application servers, and various graphical user interface toolkits like Tkinter, awxPython, etc.
matplotlib.pyplot.quiver method is used to plot a 2D field of arrows.
Syntax: matplotlib.pyplot.quiver(x_coordinate, y_coordinate, x_direction, y_direction)
Parameters:x_coordinate : x-coordinate of the arrow locationy_coordinate : y-coordinate of the arrow locationx_direction : x-component of the direction of the arrowy_direction : y-component of the direction of the arrow
Optional Parameters:scale: used to set the scale of the graphscale_units: used to set the units of the plane with respect to x and yangle: used to determine the angle of the arrow vectors plotted
Return Value : Returns a 2D graph with arrows plotted
Example #1
#Python program to explain# matplotlib.pyplot.quiver method import matplotlib.pyplot as pltimport numpy as np #defining necessary arraysx = np.linspace(0,2,8)y = np.linspace(2,0,8)x_dir = y_dir = np.zeros((8,8))y_dir[5,5] = 0.2 #plotting the 2D graphplt.quiver(x, y, x_dir, y_dir, scale=1)
Output:
Example #2Plotting multiple arrows on a graph using quiver method
# Python program to explain # matplotlib.pyplot.quiver method # importing necessary librariesimport matplotlib.pyplot as plt # defining necessary arraysx_coordinate = [0, 1.5]y_coordinate = [0.5, 1.5]x_direction = [1, -0.5]y_direction = [1, -1] # plotting the graphplt.quiver(x_coordinate, y_coordinate, x_direction, y_direction, scale_units ='xy', scale = 1.)
Output:
Python-matplotlib
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()
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
*args and **kwargs in Python | [
{
"code": null,
"e": 24278,
"s": 24250,
"text": "\n12 Apr, 2020"
},
{
"code": null,
"e": 24557,
"s": 24278,
"text": "Matplotlib is a library of Python bindings which provides the user with a MATLAB-like plotting framework. Matplotlib can be used in Python scripts, the Python and ... |
Getting value after button click with BeautifulSoup - GeeksforGeeks | 26 Mar, 2021
The library, BeautifulSoup in Python apart from extracting data out of HTML or XML files, helps in searching, modifying, and navigating the parse tree. Are you not able to obtain the value from a widget after the button click? Don’t worry. Just read the article thoroughly to know the procedure of obtaining the value after button click with BeautifulSoup.
First, import the libraries BeautifulSoup, os, and Tkinter.
from bs4 import BeautifulSoup as bs
from tkinter import *
import os
Now, remove the last segment of the path by entering the name of the Python file in which you are currently working.
base=os.path.dirname(os.path.abspath(‘#Name of Python file in which you are currently working))
Then, open the HTML file from which you want to read the value.
html=open(os.path.join(base, ‘#Name of HTML file from which you wish to read value’))
Moreover, parse the HTML file in Beautiful Soup
soup=bs(html, ‘html.parser’)
Next, obtain the text after finding the widget from which you wish to obtain value.
value=soup.find(“#Name of widget”, {“id”:”#Id name of the widget”}).text
Further, create an app in which you have an option to click on the button
app=Tk()
Give the title and geometry to your app.
app.title(“#Title of the app”)
app.geometry(‘#Geometry you wish to give to app’)
Later on, create a function of any name which gets executed when the button is clicked. You can give any function name. In this case, we are supposing the function name to be func. Inside the function, obtain the file in which you want to obtain the value after the button click. Next, write the value in the file you wish to get after the button click
def func():
with open(‘#Name of text file in which you wish to write value’, “w”, encoding=’utf-8′) as f_output:
f_output.write(value)
Construct the button in the app which when clicked gives result
b1=Button(app, text=’#Text you want to give to button’, command=func)
Moreover, display the button created in the previous step.
b1.grid(padx=#Padding from x-axis, pady=#Padding from y-axis)
Finally, make the loop for displaying the GUI app on the screen.
app.mainloop( )
Consider the following HTML source code.
HTML
<!DOCTYPE html><html> <head> My First Heading </head> <body> <ul id="list"> Fruits <li>Apple</li> <li>Banana</li> <li id="here">Mango</li> </ul> </body></html>
Let us consider you want to obtain the value ‘Mango’ in the txt file ‘text_file’ after the button click ‘Click here!’, then you can write the following code.
Python
# Python program to obtain value after button click # Import the libraries BeautifulSoup, tkinter and osfrom bs4 import BeautifulSoup as bsimport osfrom tkinter import * # Remove the last segment of the pathbase = os.path.dirname(os.path.abspath('gfg3.py')) # Open the HTML in which you want to make changeshtml = open(os.path.join(base, 'gfg.html')) # Parse HTML file in Beautiful Soupsoup = bs(html, 'html.parser') # Find the value which you want to obtain after button clickvalue = soup.find("li", {"id": "here"}).text # Construct the app for clicking of buttonapp = Tk() # Give title to your GUI appapp.title("Vinayak App") # Set dimensions for the appapp.geometry('600x400') def apple(): # Open the file in which you want to obtain the value with open('text_file.txt', "w", encoding='utf-8') as f_output: # Writing the value in the file f_output.write(value) # Construct the button in your appb1 = Button(app, text='Click Here!', command=apple) # Display the button created in previous stepb1.grid(padx=250, pady=150) # Make the loop for displaying appapp.mainloop()
Output:
Picked
Python BeautifulSoup
Python bs4-Exercises
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Python Classes and Objects
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Pandas dataframe.groupby()
Create a directory in Python | [
{
"code": null,
"e": 24212,
"s": 24184,
"text": "\n26 Mar, 2021"
},
{
"code": null,
"e": 24569,
"s": 24212,
"text": "The library, BeautifulSoup in Python apart from extracting data out of HTML or XML files, helps in searching, modifying, and navigating the parse tree. Are you not... |
How to split a Dataset into Train and Test Sets using Python - GeeksforGeeks | 09 Feb, 2022
In this article, we will discuss how to split a dataset into Train and Test sets in Python.
The train-test split is used to estimate the performance of machine learning algorithms that are applicable for prediction-based Algorithms/Applications. This method is a fast and easy procedure to perform such that we can compare our own machine learning model results to machine results. By default Test set is split into 30 % of actual data and the Training set is split into 70% of the actual data
We need to split a dataset into train and test sets to evaluate how well our machine learning model performs. The train set is used to fit the model, the statistics of the train set are known. The second set is called the test data set, this set is solely used for predictions.
Scikit-learn alias sklearn is the most useful and robust library for machine learning in Python.
The scikit-learn library provides us with the model_selection module in which we have the splitter function train_test_split().
Syntax:
train_test_split(*arrays, test_size=None, train_size=None, random_state=None, shuffle=True, stratify=None)
parameters:
*arrays : inputs such as lists, arrays, dataframes or matricestest_size : this is a float value whose value ranges between 0.0 and 1.0. it represents the proportion of our test size. it’s default value is none.train_size : this is a float value whose value ranges between 0.0 and 1.0. it represents the proportion of our train size. it’s default value is none.random_state: this parameter is used to control the shuffling applied to the data before applying the split. it acts like a seed.shuffle: This parameter is used to shuffle the data before splitting. it’s default value is true.stratify: This parameter is used to split the data in stratified fashion.
*arrays : inputs such as lists, arrays, dataframes or matrices
test_size : this is a float value whose value ranges between 0.0 and 1.0. it represents the proportion of our test size. it’s default value is none.
train_size : this is a float value whose value ranges between 0.0 and 1.0. it represents the proportion of our train size. it’s default value is none.
random_state: this parameter is used to control the shuffling applied to the data before applying the split. it acts like a seed.
shuffle: This parameter is used to shuffle the data before splitting. it’s default value is true.
stratify: This parameter is used to split the data in stratified fashion.
To view or download the CSV file used in the example click here.
Code:
Python3
# import modulesimport pandas as pdfrom sklearn.linear_model import LinearRegression # read the datasetdf = pd.read_csv('Real estate.csv') # get the locationsX = df.iloc[:, :-1]y = df.iloc[:, -1] # split the datasetX_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.05, random_state=0)
In the above example, We import the pandas package and sklearn package. after that to import the CSV file we use read_csv() method. The variable df now contains the data frame. in the example “house price” is the column we’ve to predict so we take that column as y and the rest of the columns as our X variable. test_size = 0.05 specifies only 5% of the whole data is taken as our test set, and 95% as our train set. The random state helps us get the same random split each time.
Output:
varshagumber28
Picked
Python-pandas
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between Informed and Uninformed Search in AI
Deploy Machine Learning Model using Flask
Support Vector Machine Algorithm
k-nearest neighbor algorithm in Python
Types of Environments in AI
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe | [
{
"code": null,
"e": 23953,
"s": 23925,
"text": "\n09 Feb, 2022"
},
{
"code": null,
"e": 24045,
"s": 23953,
"text": "In this article, we will discuss how to split a dataset into Train and Test sets in Python."
},
{
"code": null,
"e": 24447,
"s": 24045,
"text":... |
Write a C program to display the size and offset of structure members | Write a C program to define the structure and display the size and offsets of member variables
Structure − It is a collection of different datatype variables, grouped together under a single name.
datatype member1;
struct tagname{
datatype member2;
datatype member n;
};
Here, struct - keyword
tagname - specifies name of structure
member1, member2 - specifies the data items that make up structure.
struct book{
int pages;
char author [30];
float price;
};
There are three ways of declaring structure variables −
struct book{
int pages;
char author[30];
float price;
}b;
struct{
int pages;
char author[30];
float price;
}b;
struct book{
int pages;
char author[30];
float price;
};
struct book b;
The link between a member and a structure variable is established using the member operator (or) dot operator.
Initialization can be done in the following ways −
struct book{
int pages;
char author[30];
float price;
} b = {100, "balu", 325.75};
struct book{
int pages;
char author[30];
float price;
};
struct book b = {100, "balu", 325.75};
struct book{
int pages;
char author[30];
float price;
} ;
struct book b;
b. pages = 100;
strcpy (b.author, "balu");
b.price = 325.75;
struct book{
int pages;
char author[30];
float price;
} ;
struct book b;
scanf ("%d", &b.pages);
scanf ("%s", b.author);
scanf ("%f", &b. price);
Declare the structure with data members and try to print their offset values as well as size of the structure.
Live Demo
#include<stdio.h>
#include<stddef.h>
struct tutorial{
int a;
int b;
char c[4];
float d;
double e;
};
int main(){
struct tutorial t1;
printf("the size 'a' is :%d\n",sizeof(t1.a));
printf("the size 'b' is :%d\n",sizeof(t1.b));
printf("the size 'c' is :%d\n",sizeof(t1.c));
printf("the size 'd' is :%d\n",sizeof(t1.d));
printf("the size 'e' is :%d\n",sizeof(t1.e));
printf("the offset 'a' is :%d\n",offsetof(struct tutorial,a));
printf("the offset 'b' is :%d\n",offsetof(struct tutorial,b));
printf("the offset 'c' is :%d\n",offsetof(struct tutorial,c));
printf("the offset 'd' is :%d\n",offsetof(struct tutorial,d));
printf("the offset 'e' is :%d\n\n",offsetof(struct tutorial,e));
printf("size of the structure tutorial is :%d",sizeof(t1));
return 0;
}
the size 'a' is :4
the size 'b' is :4
the size 'c' is :4
the size 'd' is :4
the size 'e' is :8
the offset 'a' is :0
the offset 'b' is :4
the offset 'c' is :8
the offset 'd' is :12
the offset 'e' is :16
size of the structure tutorial is :24 | [
{
"code": null,
"e": 1157,
"s": 1062,
"text": "Write a C program to define the structure and display the size and offsets of member variables"
},
{
"code": null,
"e": 1259,
"s": 1157,
"text": "Structure − It is a collection of different datatype variables, grouped together under ... |
Java - String length() Method | This method returns the length of this string. The length is equal to the number of 16-bit Unicode characters in the string.
Here is the syntax of this method −
public int length()
Here is the detail of parameters −
NA
NA
This method returns the the length of the sequence of characters represented by this object.
This method returns the the length of the sequence of characters represented by this object.
import java.io.*;
public class Test {
public static void main(String args[]) {
String Str1 = new String("Welcome to Tutorialspoint.com");
String Str2 = new String("Tutorials" );
System.out.print("String Length :" );
System.out.println(Str1.length());
System.out.print("String Length :" );
System.out.println(Str2.length());
}
}
This will produce the following result −
String Length :29
String Length :9
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2502,
"s": 2377,
"text": "This method returns the length of this string. The length is equal to the number of 16-bit Unicode characters in the string."
},
{
"code": null,
"e": 2539,
"s": 2502,
"text": "Here is the syntax of this method −"
},
{
"code"... |
How to use JavaScript variables in jQuery selectors? | It’s quite easy to use JavaScript variables in jQuery selectors.
Let’s seen an example to use JavaScript variables in jQuery to hide an element:
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("input").click(function(){
var name = this.name;
$("input[name=" + name + "]").hide();
} );
});
</script>
</head>
<body>
<h1>Heading 1</h1>
<input type="text" id="bx"/>
<input type="button" name="bx" value="one"/><br>
<input type="text" id="by"/>
<input type="button" name="by" value="two"/>
<p>To hide the buttons, click on it.</p>
</body>
</html> | [
{
"code": null,
"e": 1127,
"s": 1062,
"text": "It’s quite easy to use JavaScript variables in jQuery selectors."
},
{
"code": null,
"e": 1207,
"s": 1127,
"text": "Let’s seen an example to use JavaScript variables in jQuery to hide an element:"
},
{
"code": null,
"e": ... |
How I Improved Performance Retrieving Big Data With S3-Select | by Anna Geller | Towards Data Science | I’ve recently come across a feature in S3 that is particularly useful when working with Big Data. You can write a simple SQL query to select specific columns and filter for specific rows to retrieve only the data you need for your application. In this article, I will demonstrate how you can accomplish that using Python’s boto3 library.
Imagine the following scenario:
You are regularly getting a single large CSV file that is stored in an S3 bucket. This file includes marketing data about all countries you’re online shop is active in.
However, you have an application running inside of AWS Lambda that only needs marketing data from one particular country.
Normally, you would have to download this entire large file and filter out data inside of your application. The problem is that your Lambda function may not have enough RAM to read this entire large file into memory. There are some ways to tackle this, such as reading and filtering data in chunks or moving the function to a Docker container, but the simplest and most cost-effective solution in this scenario would be to use the S3-Select feature. Here is how it works.
First, since I actually don’t have any marketing data, we will use data about taxi trips from New York [1], and we will filter for suspicious records with unknown payment type, encoded as payment_type==5according to the data dictionary.
Let’s explore how many rows the entire file has as compared to only those with payment_type==5.
This means that we are only interested in 12 out of half a million records. It would be a massive waste of resources to download and read the entire dataset into memory just to get those 12 rows!
To demonstrate S3-Select in action, we first upload our large CSV file [1] to an S3 bucket:
Now we can use S3-Select to get only data with payment type equal to 5, i.e., we retrieve from S3 only the data we are interested in — data with unknown payment type. And the best part is that it’s all defined in a simple SQL query:
in our query, we select only columns we need for our use case
we filter only for payment_type='5' — note that in S3, all columns in the flat file are considered text, so make sure to enclose your value with quotation marks '5'.
In the code snippet above, we had to define the InputSerialization='CSV' to specify that this is the format of our S3 object. Also, we set FileHeaderInfo to 'Use', which ensures that we can use column names in our S3-select query.
By using the OutputSerialization parameter, we define that we want our output to be comma-separated, which allows us to store the result in a separate CSV file. If you want to use S3-Select in an API, you might prefer the JSON format.
Some extra caveats:
The S3-select only returns the records, not the column names (header), so on line 27, I ensured that the same columns that I defined in the query are also included as the first row in our TARGET_FILE.
S3 select returns a stream of encoded bytes [2], so we have to loop over the returned stream and decode the output: .decode('utf-8').
Let’s cross-check the TARGET_FILE — it should only have 12 rows.
The result:
Nr of rows: 12 ID distance tip total0 1 9.7 0 31.801 1 10.0 0 30.802 1 0.4 0 7.803 1 13.6 0 40.804 1 0.5 0 7.805 1 1.7 0 11.806 1 6.4 0 22.807 1 4.0 0 16.808 1 1.7 0 11.309 1 5.6 0 22.8010 1 7.3 0 30.4211 1 6.7 0 24.80
You may ask: if S3 is so easy to use, why do we need Athena to query a data lake? Here are the main differences between those two:
Athena can query multiple objects at once, while with S3 select, we can only query a single object (ex. a single flat file)
With Athena, we can encapsulate complex business logic using ANSI-compliant SQL queries, while S3-select lets you perform only basic queries to filter out data before loading it from S3.
Athena supports more file formats and more forms of file compression than S3-Select. For instance, S3-select supports only CSV, JSON, and Parquet, while Athena additionally allows TSV, ORC files, and more.
S3-select works only with the S3 API (ex. by using Python boto3 SDK), while Athena can be queried directly from the management console or SQL clients via JDBC.
Athena allows many optimization techniques for better performance and cost-optimization, such as partitioning, columnar storage, while S3-select is a very rudimentary query that just nothing but filtering data.
S3-select can be queried directly, while Athena requires the definition of a schema.
In short, the benefits of this API are:
reduce IO — thus better performance
reduce costs due to smaller data transfer fees.
In this article, we discussed S3-select, which allows filtering data stored in S3. S3-select should only be used when dealing with a single file and when you only need to select specific columns and filter for only specific rows from a flat-file.
If this article was helpful, follow me to see my next articles.
In the article linked below, I discuss various options to transfer large amounts of data between S3 buckets.
medium.com
Resources:
[1] TLC Trip Record Data: https://www1.nyc.gov/site/tlc/about/tlc-trip-record-data.page
[2] Boto3 Docs: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.Client.select_object_content
[3] AWS Docs: https://docs.aws.amazon.com/AmazonS3/latest/API/API_InputSerialization.html and https://docs.aws.amazon.com/AmazonS3/latest/API/API_SelectObjectContent.html | [
{
"code": null,
"e": 509,
"s": 171,
"text": "I’ve recently come across a feature in S3 that is particularly useful when working with Big Data. You can write a simple SQL query to select specific columns and filter for specific rows to retrieve only the data you need for your application. In this art... |
Time Series Decomposition In Python | by Billy Bonaros | Towards Data Science | Time series decomposition is a technique that splits a time series into several components, each representing an underlying pattern category, trend, seasonality, and noise. In this tutorial, we will show you how to automatically decompose a time series with Python.
To begin with, let's talk a bit about the components of a time series:
Seasonality: describes the periodic signal in your time series.Trend: describes whether the time series is decreasing, constant, or increasing over time.Noise: describes what remains behind the separation of seasonality and trend from the time series. In other words, it’s the variability in the data that cannot be explained by the model.
For this example, we will use the Air Passengers Data from Kaggle.
import pandas as pdimport numpy as npfrom statsmodels.tsa.seasonal import seasonal_decompose #https://www.kaggle.com/rakannimer/air-passengersdf=pd.read_csv(‘AirPassengers.csv’) df.head()
Firstly, we need to set as index the Month column and convert it into Datetime Object.
df.set_index('Month',inplace=True)df.index=pd.to_datetime(df.index)#drop null valuesdf.dropna(inplace=True)df.plot()
We will use Pythons statsmodels function seasonal_decompose.
result=seasonal_decompose(df['#Passengers'], model='multiplicable', period=12)
In seasonal_decompose we have to set the model. We can either set the model to be Additive or Multiplicative. A rule of thumb for selecting the right model is to see in our plot if the trend and seasonal variation are relatively constant over time, in other words, linear. If yes, then we will select the Additive model. Otherwise, if the trend and seasonal variation increase or decrease over time then we use the Multiplicative model.
Our data here are aggregated by month. The period we want to analyze is by year so that's why we set the period to 12.
We can get each component as follows:
result.seasonal.plot()
result.trend.plot()
Also, we can plot every component at once
result.plot()
Frequently, when looking at time series data it’s difficult to manually extract the trend or identify the seasonality. Fortunately, we can automatically decompose a time series and helps us have a clearer view of the components as It’s easier to analyze the trend if we remove the seasonality from our data and vise versa.
Originally published at https://predictivehacks.com. | [
{
"code": null,
"e": 438,
"s": 172,
"text": "Time series decomposition is a technique that splits a time series into several components, each representing an underlying pattern category, trend, seasonality, and noise. In this tutorial, we will show you how to automatically decompose a time series wi... |
Average of remaining elements after removing K largest and K smallest elements from array - GeeksforGeeks | 08 Apr, 2021
Given an array of N integers. The task is to find the average of the numbers after removing k largest elements and k smallest element from the array i.e. calculate the average value of the remaining N – 2K elements.
Examples:
Input: arr = [1, 2, 4, 4, 5, 6], K = 2
Output: 4
Remove 2 smallest elements i.e. 1 and 2
Remove 2 largest elements i.e. 5 and 6
Remaining elements are 4, 4. So average of 4, 4 is 4.
Input: arr = [1, 2, 3], K = 3
Output: 0
Approach:
If no. of elements to be removed is greater than no. of elements present in the array, then ans = 0.
Else, Sort all the elements of the array. Then, calculate average of elements from Kth index to n-k-1th index.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to find averagedouble average(int arr[], int n, int k){ double total = 0; // base case if 2*k>=n // means all element get removed if (2 * k >= n) return 0; // first sort all elements sort(arr, arr + n); int start = k, end = n - k - 1; // sum of req number for (int i = start; i <= end; i++) total += arr[i]; // find average return (total / (n - 2 * k));} // Driver codeint main(){ int arr[] = { 1, 2, 4, 4, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 2; cout << average(arr, n, k) << endl; return 0;}
// Java implementation of the above approach import java.io.*;import java.util.*;class GFG { // Function to find averagestatic double average(int arr[], int n, int k){ double total = 0; // base case if 2*k>=n // means all element get removed if (2 * k >= n) return 0; // first sort all elements Arrays.sort(arr); int start = k, end = n - k - 1; // sum of req number for (int i = start; i <= end; i++) total += arr[i]; // find average return (total / (n - 2 * k));} // Driver code public static void main (String[] args) { int arr[] = { 1, 2, 4, 4, 5, 6 }; int n = arr.length; int k = 2; System.out.println( average(arr, n, k)); }}// This code is contributed by anuj_67..
# Python3 implementation of the# above approach # Function to find averagedef average(arr, n, k) : total = 0 # base case if 2*k>=n # means all element get removed if (2 * k >= n) : return 0 # first sort all elements arr.sort() start , end = k , n - k - 1 # sum of req number for i in range(start, end + 1) : total += arr[i] # find average return (total / (n - 2 * k)) # Driver codeif __name__ == "__main__" : arr = [ 1, 2, 4, 4, 5, 6 ] n = len(arr) k = 2 print(average(arr, n, k)) # This code is contributed by Ryuga
// C# implementation of the above approach using System;public class GFG { // Function to find average static double average(int []arr, int n, int k) { double total = 0; // base case if 2*k>=n // means all element get removed if (2 * k >= n) return 0; // first sort all elements Array.Sort(arr); int start = k, end = n - k - 1; // sum of req number for (int i = start; i <= end; i++) total += arr[i]; // find average return (total / (n - 2 * k)); } // Driver code public static void Main() { int []arr = { 1, 2, 4, 4, 5, 6 }; int n = arr.Length; int k = 2; Console.WriteLine( average(arr, n, k)); }}//This code is contributed by 29AjayKumar
<?php// Php implementation of the// above approach // Function to find averagefunction average($arr, $n, $k){ $total = 0; // base case if 2*k>=n // means all element get removed if (2 * $k >= $n) return 0; // first sort all elements sort($arr) ; $start = $k ; $end = $n - $k - 1; // sum of req number for ($i = $start; $i <= $end; $i++) $total += $arr[$i]; // find average return ($total / ($n - 2 * $k));} // Driver code$arr = array(1, 2, 4, 4, 5, 6);$n = sizeof($arr);$k = 2; echo average($arr, $n, $k); // This code is contributed by Ryuga?>
<script> // Javascript implementation of the above approach // Function to find averagefunction average(arr, n, k){ var total = 0; // Base case if 2*k>=n // means all element get removed if (2 * k >= n) return 0; // First sort all elements arr.sort(); var start = k, end = n - k - 1; // Sum of req number for(i = start; i <= end; i++) total += arr[i]; // Find average return (total / (n - 2 * k));} // Driver codevar arr = [ 1, 2, 4, 4, 5, 6 ];var n = arr.length;var k = 2; document.write(average(arr, n, k)); // This code is contributed by aashish1995 </script>
4
vt_m
29AjayKumar
ankthon
Akanksha_Rai
aashish1995
Order-Statistics
Technical Scripter 2018
Arrays
Sorting
Arrays
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Introduction to Arrays
Multidimensional Arrays in Java
Python | Using 2D arrays/lists the right way
Linked List vs Array
Maximum and minimum of an array using minimum number of comparisons | [
{
"code": null,
"e": 24512,
"s": 24484,
"text": "\n08 Apr, 2021"
},
{
"code": null,
"e": 24728,
"s": 24512,
"text": "Given an array of N integers. The task is to find the average of the numbers after removing k largest elements and k smallest element from the array i.e. calculate... |
Python | Pandas Panel.shape | 30 Jun, 2021
In Pandas, Panel is a very important container for three-dimensional data. The names for the 3 axes are intended to give some semantic meaning to describing operations involving panel data and, in particular, econometric analysis of panel data.In Pandas Panel.shape can be used to get a tuple of axis dimensions.
Syntax: Panel.shapeParameters: NoneReturns: Return a tuple of axis dimensions
Code #1:
Python3
# importing pandas module import pandas as pd import numpy as np df1 = pd.DataFrame({'a': ['Geeks', 'For', 'geeks', 'for', 'real'], 'b': [11, 1.025, 333, 114.48, 1333]}) data = {'item1':df1, 'item2':df1} # creating Panel panel = pd.Panel.from_dict(data, orient ='minor') print("panel['b'] is - \n\n", panel['b'], '\n') print("\nSize of panel['b'] is - ", panel['b'].shape)
Output:
Code #2:
Python3
# importing pandas module import pandas as pd import numpy as np df1 = pd.DataFrame({'a': ['Geeks', 'For', 'geeks', 'for', 'real'], 'b': [11, 1.025, 333, 114.48, 1333]}) # Create a 5 * 5 dataframedf2 = pd.DataFrame(np.random.rand(10, 2), columns =['a', 'b']) data = {'item1':df1, 'item2':df2} # creating Panel panel = pd.Panel.from_dict(data, orient ='minor')print("panel['b'] is - \n\n", panel['b'], '\n') print("\nShape of Panel is - ", panel['b'].shape)
Output:
Code #3:
Python3
# importing pandas moduleimport pandas as pdimport numpy as np df1 = pd.DataFrame({'a': ['Geeks', 'For', 'geeks', 'real'], 'b': [-11, +1.025, -114.48, 1333]}) df2 = pd.DataFrame({'a': ['I', 'am', 'dataframe', 'two'], 'b': [100, 100, 100, 100]}) data = {'item1':df1, 'item2':df2} # creating Panelpanel = pd.Panel.from_dict(data, orient ='minor')print("panel['b'] is - \n\n", panel['b']) print("\nShape of panel['b'] is - ", panel['b'].shape)
Output:
Note: The panel has been removed from Pandas module 0.25.0 onwards.
Python3
#To check the version of pandas libraryimport pandasprint(pandas.__version__)
naveenkumarkharwal
Python pandas-panel
Python pandas-panel-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
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": "\n30 Jun, 2021"
},
{
"code": null,
"e": 342,
"s": 28,
"text": "In Pandas, Panel is a very important container for three-dimensional data. The names for the 3 axes are intended to give some semantic meaning to describing operations involvi... |
Steps by Knight | Practice | GeeksforGeeks | Given a square chessboard, the initial position of Knight and position of a target. Find out the minimum steps a Knight will take to reach the target position.
Note:
The initial and the target position coordinates of Knight have been given according to 1-base indexing.
Example 1:
Input:
N=6
knightPos[ ] = {4, 5}
targetPos[ ] = {1, 1}
Output:
3
Explanation:
Knight takes 3 step to reach from
(4, 5) to (1, 1):
(4, 5) -> (5, 3) -> (3, 2) -> (1, 1).
Your Task:
You don't need to read input or print anything. Your task is to complete the function minStepToReachTarget() which takes the initial position of Knight (KnightPos), the target position of Knight (TargetPos), and the size of the chessboard (N) as input parameters and returns the minimum number of steps required by the knight to reach from its current position to the given target position or return -1 if its not possible.
Expected Time Complexity: O(N2).
Expected Auxiliary Space: O(N2).
Constraints:
1 <= N <= 1000
1 <= Knight_pos(X, Y), Targer_pos(X, Y) <= N
0
abs_bharat_sai3 days ago
>> Shortest number of steps BFS is the go to solution
int minStepToReachTarget(vector<int> &ini,vector<int> &tar,int n){
// Code here
queue<pair<int, int>> q;
int cnt = 0;
int r[8] = {2, 1, -1, -2, -2, -1, 1, 2};
int c[8] = {1, 2, 2, 1, -1, -2, -2, -1};
vector<vector<int>> vis(n, vector<int>(n, 0));
q.push({ini[0]-1, ini[1]-1});
vis[ini[0]-1][ini[1]-1] = 1;
while(!q.empty()){
int size = q.size();
while(size--){
int x = q.front().first;
int y = q.front().second;
q.pop();
if(x == tar[0]-1 && y == tar[1]-1){
return cnt;
}
for(int i = 0 ; i < 8; i++){
int cx = x + r[i];
int cy = y + c[i];
if(cx >= 0 && cx < n && cy >= 0 && cy < n && !vis[cx][cy]){
q.push({cx, cy});
vis[cx][cy] = 1;
}
}
}
cnt++;
}
return -1;
}
0
rhythmanand6Premium4 days ago
class Pair{
int x;
int y;
Pair(int x, int y){
this.x = x;
this.y = y;
}
}
public int minStepToReachTarget(int KnightPos[], int TargetPos[], int N)
{
// Code here
int x = KnightPos[0]-1;
int y = KnightPos[1]-1;
int di[]={-1,1,1,-1,-2,-2,2,2};
int dj[]={-2,-2,2,2,-1,1,-1,1};
boolean[][] visited = new boolean[N][N];
Queue<Pair> q = new LinkedList<>();
q.add(new Pair(x, y));
visited[x][y] = true;
int count = 0;
while(!q.isEmpty()){
int size = q.size();
count++;
while(size-->0){
Pair cur = q.poll();
if(cur.x==TargetPos[0]-1 && cur.y==TargetPos[1]-1) return count-1;
for(int i=0; i<8; i++){
int nextX = cur.x + di[i];
int nextY = cur.y + dj[i];
if(nextX>=0 && nextX<N && nextY>=0 && nextY<N && !visited[nextX][nextY]){
q.add(new Pair(nextX, nextY));
visited[nextX][nextY] = true;
}
}
}
}
return -1;
}
0
k_jain5 days ago
// } Driver Code Ends
class Pair{
int x;
int y;
Pair(int x, int y){
this.x = x;
this.y = y;
}
}
class Solution
{
//Function to find out minimum steps Knight needs to reach target position.
public int minStepToReachTarget(int KnightPos[], int TargetPos[], int n)
{
// Code here
//like rotten oranges proble
// we will perform bfs becuase from every position we want to check it's adjacnet position
//queue is needed for bfs
Queue<Pair> q = new LinkedList<>();
//starting cordinates
int start_x = KnightPos[0] - 1; //converting into 0-based index
int start_y = KnightPos[1] - 1;
int target_x = TargetPos[0] - 1 ;
int target_y = TargetPos[1] - 1 ;
if(start_x == target_x && start_y == target_y)
return 0;
//for checking the visited positon;
boolean[][] visited = new boolean[n][n];
for(boolean[] temp : visited){
Arrays.fill(temp, false);
}
//for counting steps
int steps = 0;
visited[start_x][start_y] = true;
q.offer(new Pair(start_x, start_y));
int[] ax = new int[]{-1, 1, 2, -2, -1, 1, 2, -2};
int[] ay = new int[]{2, 2, 1, 1, -2, -2, -1, -1};
while(!q.isEmpty()){
int size = q.size();
steps++;
//for every step we are finding 8 possible moves of the knight
while(size != 0){
//pop out the possible step
Pair p = q.poll();
int x = p.x;
int y = p.y;
//may be this x, y are our required cordinate
if(x == target_x && y == target_y)
return steps-1;
//now choose only the valid position out of these 8
for(int i = 0; i<8; i++){
if(isValid(x+ax[i], y+ay[i],n, visited) == true)
{
//mark this as visited;
visited[x+ax[i]][y+ay[i]] = true;
q.offer(new Pair(x+ax[i], y + ay[i]));
}
}
size--;
}
}
return -1;
}
private boolean isValid(int x, int y, int n, boolean[][] visited){
if(x>=0 && x<n && y>=0 && y<n && visited[x][y] == false)
return true;
return false;
}
}
+1
knightgod1 week ago
class Solution
{
bool isValid(int x,int y,int N){
if(x>=0 && x<N && y>=0 && y<N) return true;
return false;
}
int minStepToReachTarget(vector<int>&KnightPos,
vector<int>&TargetPos,int N)
{
int dx[] = {2,2,-2,-2,1,1,-1,-1};
int dy[] = {1,-1,1,-1,2,-2,2,-2};
vector<vector<bool>> visited(N,vector<bool>(N,false));
queue<pair<int,int>> q;
vector<vector<int>> dist(N,vector<int>(N,0));
q.push(make_pair(KnightPos[0]-1,KnightPos[1]-1));
visited[KnightPos[0]-1][KnightPos[1]-1] = true;
while(!q.empty()){
pair<int,int> currCell=q.front();
q.pop();
for(int i=0;i<8;i++){
int x = currCell.first + dx[i];
int y = currCell.second + dy[i];
if(currCell.first == TargetPos[0]-1 &&
currCell.second == TargetPos[1]-1)
return dist[currCell.first][currCell.second];
if(isValid(x,y,N) && !visited[x][y]){
q.push(make_pair(x,y));
visited[x][y]=true;
dist[x][y] = dist[currCell.first][currCell.second] + 1;
}
}
}
return -1;
// Code here
}
+1
69rw2mwqg20lg2xtig73okg0jp76p59ixg8orzbs1 week ago
int dx[8] = {2,2,-2,-2,1,-1,1,-1};
int dy[8] = {1,-1,1,-1,2,2,-2,-2};
vector<vector<int>> dist;
bool check(int x,int y,int N){
return (x >= 0 && y >= 0 && x <= N && y <= N);
}
int minStepToReachTarget(vector<int> &KnightPos,vector<int> &TargetPos,int N){
dist = vector<vector<int>>(N+1,vector<int>(N+1,0));
if(KnightPos[0] == TargetPos[0] && KnightPos[1] == TargetPos[1]) return 0;
queue<pair<int,int>> q;
q.push(make_pair(KnightPos[0],KnightPos[1]));
while(!q.empty()){
pair<int,int> xx = q.front();
q.pop();
for(int i=0;i<8;i++){
if(check(xx.first + dx[i],xx.second + dy[i],N) && (dist[xx.first + dx[i]][xx.second + dy[i]]) == 0){
dist[xx.first + dx[i]][xx.second + dy[i]] = dist[xx.first][xx.second] + 1;
q.push(make_pair(xx.first + dx[i],xx.second + dy[i]));
}
}
}
if(dist[TargetPos[0]][TargetPos[1]] == 0) return -1;
return dist[TargetPos[0]][TargetPos[1]];
}
0
rajubugude1 week ago
PYTHON CODE (USING BFS)
from queue import Queue
direc = [[1,2],[1,-2],[-1,2],[-1,-2],[2,1],[2,-1],[-2,1],[-2,-1]]
class Solution:
def check(self,i,j,n,vis):
return i >= 0 and j >= 0 and i < n and j < n and vis[i][j] == 0
def minStepToReachTarget(self, KPos, TargetPos, n):
KPos[0] = KPos[0]-1; KPos[1] = KPos[1]-1
TargetPos[0] = TargetPos[0]-1; TargetPos[1] = TargetPos[1]-1
if KPos == TargetPos:
return 0
q = Queue()
q.put([KPos[0],KPos[1],0])
vis = [[0 for _ in range(n)] for _ in range(n)]
vis[KPos[0]][KPos[1]] = 1
while not q.empty():
x,y,d = q.get()
if x == TargetPos[0] and y == TargetPos[1]:
return d
for u,v in direc:
p = x + u
r = y + v
if self.check(p,r,n,vis):
q.put([p,r,d+1])
vis[p][r] = 1
return -1
+1
20192851 week ago
this solution is giving TLE (10/20 case)
pls tell what am in doing wrong ?
public: //Function to find out minimum steps Knight needs to reach target position.int dx[8]={-2,-1,1,2,2,1,-1,-2};int dy[8]={1,2,2,1,-1,-2,-2,-1};bool isvalid(int x,int y, int n,vector<vector<bool>> vis){ if(x<1||y<1||x>n||y>n) return false; if(vis[x][y]) return false; return true;}int minStepToReachTarget(vector<int>&KnightPos,vector<int>&TargetPos,int N){ vector<vector<bool>> vis(N+1,vector<bool>(N+1,false)); vector<vector<int>> d(N+1,vector<int>(N+1,-1)); queue<pair<int,int>> q; q.push({KnightPos[0],KnightPos[1]}); vis[KnightPos[0]][KnightPos[1]] =true; d[KnightPos[0]][KnightPos[1]] =0; while(!q.empty()){ pair<int , int> p = q.front(); q.pop(); for(int i=0;i<8;i++){ int cx=p.first +dx[i]; int cy=p.second +dy[i]; if( isvalid(cx,cy,N,vis) ){ vis[cx][cy]=true; q.push({cx,cy}); d[cx][cy]=d[p.first][p.second]+1; } } } return d[TargetPos[0] ][TargetPos[1] ];}
+1
007msr0071 week ago
C++ Code:
int minStepToReachTarget(vector<int>&KnightPos,vector<int>&TargetPos,int N)
{
// Code here
if(KnightPos[0]==TargetPos[0] && KnightPos[1]==TargetPos[1]) return 0;
int dx[8]={1,2,-2,-1,-1,-2,2,1};
int dy[8]={-2,-1,1,2,-2,-1,1,2};
vector<vector<int>>dis(N,vector<int>(N,0));
queue<vector<int>>q;
q.push({KnightPos[0]-1,KnightPos[1]-1});
while(!q.empty())
{
auto v = q.front();
q.pop();
int x = v[0];
int y=v[1];
for(int i=0;i<8;i++)
{
if(x+dx[i]>=0 && x+dx[i]<N && y+dy[i]>=0 && y+dy[i]<N && dis[x+dx[i]][y+dy[i]]==0)
{
dis[x+dx[i]][y+dy[i]] = dis[x][y]+1;
q.push({x+dx[i],y+dy[i]});
}
}
}
return dis[TargetPos[0]-1][TargetPos[1]-1];
}
0
priyanshu543212 weeks ago
class Solution
{
private:
vector<pair<int,int>> getChild(pair<int,int> pos,int n)
{
vector<pair<int,int>> ans;
int i=pos.first;
int j=pos.second;
if(i-2>=0)
{
if(j-1>=0)
ans.push_back({i-2,j-1});
if(j+1<n)
ans.push_back({i-2,j+1});
}
if(i+2<n)
{
if(j-1>=0)
ans.push_back({i+2,j-1});
if(j+1<n)
ans.push_back({i+2,j+1});
}
if(j-2>=0)
{
if(i-1>=0)
ans.push_back({i-1,j-2});
if(i+1<n)
ans.push_back({i+1,j-2});
}
if(j+2<n)
{
if(i-1>=0)
ans.push_back({i-1,j+2});
if(i+1<n)
ans.push_back({i+1,j+2});
}
return ans;
}
public:
int minStepToReachTarget(vector<int>&KnightPos,vector<int>&TargetPos,int n)
{
queue<pair<int,int>> q;
vector<vector<int>> vis(n,vector<int>(n,0));
vector<vector<pair<int,int>>> parent(n,vector<pair<int,int>>(n));
q.push({KnightPos[0]-1,KnightPos[1]-1});
vis[KnightPos[0]-1][KnightPos[1]-1]=1;
parent[KnightPos[0]-1][KnightPos[1]-1]={-1,-1};
int ans=0;
while(!q.empty())
{
pair<int,int> front=q.front();
q.pop();
for(auto child:getChild(front,n))
{
if(vis[child.first][child.second]!=1)
{
vis[child.first][child.second]=1;
parent[child.first][child.second]=front;
q.push(child);
}
}
if(vis[TargetPos[0]-1][TargetPos[1]-1]==1)
break;
}
int i=TargetPos[0]-1;
int j=TargetPos[1]-1;
while(i!=-1)
{
int x=parent[i][j].first;
int y=parent[i][j].second;
i=x;
j=y;
ans++;
}
return ans-1;
}
};
0
rajkeshari7462 weeks ago
vector<vector<int>> level;
vector<vector<bool>> vis;
vector<pair<int,int>> moves={{-2,-1},{-2,1},{2,-1},{2,1},{1,2},{-1,-2},{-1,2},{1,-2}};
bool isvalid(pair<int,int> i , int x , int y , int N)
{
return (((x+i.first)>=0 && (x+i.first)<N) && ((y+i.second)>=0 && (y+i.second)<N)) && !vis[x+i.first][y+i.second];
}
int minStepToReachTarget(vector<int>&KP,vector<int>&TP,int N)
{
level.resize(N,vector<int>(N,0));
vis.resize(N,vector<bool>(N,false));
queue<pair<int,int>> q;
q.push({KP[0]-1,KP[1]-1});
vis[KP[0]-1][KP[1]-1]=true;
level[KP[0]-1][KP[1]-1]=0;
while(!q.empty())
{
pair<int,int> temp=q.front();
q.pop();
int x=temp.first;
int y=temp.second;
for(auto i:moves)
{
if(isvalid(i,x,y,N))
{
q.push({x+i.first,y+i.second});
vis[x+i.first][y+i.second]=true;
level[x+i.first][y+i.second]=level[x][y]+1;
}
}
}
return level[TP[0]-1][TP[1]-1];
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code.
On submission, your code is tested against multiple test cases consisting of all
possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as
the final solution code.
You can view the solutions submitted by other users from the submission tab.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems does not guarantee the
correctness of code. On submission, your code is tested against multiple test cases
consisting of all possible corner cases and stress constraints. | [
{
"code": null,
"e": 398,
"s": 238,
"text": "Given a square chessboard, the initial position of Knight and position of a target. Find out the minimum steps a Knight will take to reach the target position."
},
{
"code": null,
"e": 508,
"s": 398,
"text": "Note:\nThe initial and the... |
How to create a new object from the specified object, where all the keys are in lowercase in JavaScript? | 21 May, 2021
In this article, we will learn how to make a new object from the specified object where all the keys are in lowercase using JavaScript.
Example:
Input: {RollNo : 1, Mark : 78}
Output: {rollno : 1, mark : 78}
Explanation: here, we have converted upper case to lower case keys values.
Approach 1:
A simple approach is to Extract keys from Object and LowerCase to all keys and make Object with them. For this purpose we use Object.keys( ) to extract keys from object. And use String.toLowerCase() method to lower case keys and Array.reduce() method to make an object with lower-case strings.
Example 1:
HTML
<script> // Test Object const Student = { RollNo : 1, Mark: 78 }; // Function to lowercase keys function Conv( obj , key ) { obj[key.toLowerCase()] = Student[key]; return Student; } // Function to create object from lowercase keys function ObjKeys( obj) { let arr1 = Object.keys(obj); let ans = {}; for(let i of arr1) { Conv(ans,i); } return ans; } a = ObjKeys(Student); console.log(a); </script>
Output:
{ rollno : 1, mark : 78}
Approach 2:
The simplest approach is to convert Object to array and make keys to lower-case and make objects from a new array. For this purpose, we use Object.entries() to make an array from Object. And we use Array.map() to apply String.toLowerCase() method to all keys. To convert a new array to an Object we use Object.fromEntries().
Example:
HTML
<script> // Test Object const employ = { EmpId: 101, Batch: 56 }; // Converting Object to array let k = Object.entries(employ); // Apply toLowerCase function to all keys let l = k.map(function(t){ t[0] = t[0].toLowerCase() return t; } ); // Converting back array to Object const a = Object.fromEntries(l) console.log(a)</script>
Output:
{ empid : 101, batch : 56 }
javascript-functions
JavaScript-Questions
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 May, 2021"
},
{
"code": null,
"e": 164,
"s": 28,
"text": "In this article, we will learn how to make a new object from the specified object where all the keys are in lowercase using JavaScript."
},
{
"code": null,
"e": 17... |
Python | Pandas Series.combine_first() | 17 Oct, 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 combine_first() method is used to combine two series into one. The result is union of the two series that is in case of Null value in caller series, the value from passed series is taken. In case of both null values at the same index, null is returned at that index.
Note: This method is different from Series.combine() which takes a function as parameter to decide output value.
Syntax: Series.combine_first(other)
Parameters:other: Other series to be combined with caller series.
Return type: Pandas series
Example:In this example, two series are created from list using Pandas Series() method. Some Null values are also passed to each list using Numpy np.nan. Both series are then combined using .combine_first() method. At first, the method is called by series1 and result is stored in result1 and then similarly it is called by series2 and stored in result2. Both of the returned series are then printed to compare outputs.
# importing pandas module import pandas as pd # importing numpy module import numpy as np # creating series 1 series1 = pd.Series([70, 5, 0, 225, 1, 16, np.nan, 10, np.nan]) # creating series 2 series2 = pd.Series([27, np.nan, 2, 23, 1, 95, 53, 10, 5]) # combining and returning results to variable# calling on series1result1 = series1.combine_first(series2) # calling on series2result2 = series2.combine_first(series1) # printing resultprint('Result 1:\n', result1, '\n\nResult 2:\n', result2)
Output:As shown in the output, even though the same series were combined, but the outputs are different. This is because of combine_first() method prioritize first series ( Caller series ) before. If there is null value at that position, it takes value at same index from second series.
Result 1:
0 70.0
1 5.0
2 0.0
3 225.0
4 1.0
5 16.0
6 53.0
7 10.0
8 5.0
dtype: float64
Result 2:
0 27.0
1 5.0
2 2.0
3 23.0
4 1.0
5 95.0
6 53.0
7 10.0
8 5.0
dtype: float64
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Oct, 2018"
},
{
"code": null,
"e": 242,
"s": 28,
"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 imp... |
Spring Boot - Tracing Micro Service Logs | Most developers face difficulty of tracing logs if any issue occurred. This can be solved by Spring Cloud Sleuth and ZipKin server for Spring Boot application.
Spring cloud Sleuth logs are printed in the following format −
[application-name,traceid,spanid,zipkin-export]
Where,
Application-name = Name of the application
Application-name = Name of the application
Traceid = each request and response traceid is same when calling same service or one service to another service.
Traceid = each request and response traceid is same when calling same service or one service to another service.
Spanid = Span Id is printed along with Trace Id. Span Id is different every request and response calling one service to another service.
Spanid = Span Id is printed along with Trace Id. Span Id is different every request and response calling one service to another service.
Zipkin-export = By default it is false. If it is true, logs will be exported to the Zipkin server.
Zipkin-export = By default it is false. If it is true, logs will be exported to the Zipkin server.
Now, add the Spring Cloud Starter Sleuth dependency in your build configuration file as follows −
Maven users can add the following dependency in your pom.xml file −
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>
Gradle users can add the following dependency in your build.gradle file −
compile('org.springframework.cloud:spring-cloud-starter-sleuth')
Now, add the Logs into your Spring Boot application Rest Controller class file as shown here −
package com.tutorialspoint.sleuthapp;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class SleuthappApplication {
private static final Logger LOG = Logger.getLogger(SleuthappApplication.class.getName());
public static void main(String[] args) {
SpringApplication.run(SleuthappApplication.class, args);
}
@RequestMapping("/")
public String index() {
LOG.log(Level.INFO, "Index API is calling");
return "Welcome Sleuth!";
}
}
Now, add the application name in application.properties file as shown −
spring.application.name = tracinglogs
The complete code for build configuration file is given below −
Maven – pom.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<project xmlns = "http://maven.apache.org/POM/4.0.0"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tutorialspoint</groupId>
<artifactId>sleuthapp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>sleuthapp</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<spring-cloud.version>Edgware.RELEASE</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Gradle – build.gradle
buildscript {
ext {
springBootVersion = '1.5.9.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
group = 'com.tutorialspoint'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
ext {
springCloudVersion = 'Edgware.RELEASE'
}
dependencies {
compile('org.springframework.cloud:spring-cloud-starter-sleuth')
compile('org.springframework.boot:spring-boot-starter-web')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
}
}
You can create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle commands.
For Maven, you can use the following command −
mvn clean install
After “BUILD SUCCESS”, you can find the JAR file under the target directory.
For Gradle, you can use the following command −
gradle clean build
After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory.
Now, run the JAR file by using the command shown here −
java –jar <JARFILE>
Now, the application has started on the Tomcat port 8080.
Now, hit the URL in your web browser and see the output in console log.
http://localhost:8080/
You can see the following logs in the console window. Observe that log is printed in the following format [application-name, traceid, spanid, zipkin-export]
Zipkin is an application that monitors and manages the Spring Cloud Sleuth logs of your Spring Boot application. To build a Zipkin server, we need to add the Zipkin UI and Zipkin Server dependencies in our build configuration file.
Maven users can add the following dependency in your pom.xml file −
<dependency>
<groupId>io.zipkin.java</groupId>
<artifactId>zipkin-server</artifactId>
</dependency>
<dependency>
<groupId>io.zipkin.java</groupId>
<artifactId>zipkin-autoconfigure-ui</artifactId>
</dependency>
Gradle users can add the below dependency in your build.gradle file −
compile('io.zipkin.java:zipkin-autoconfigure-ui')
compile('io.zipkin.java:zipkin-server')
Now, configure the server.port = 9411 in application properties file.
For properties file users, add the below property in application.properties file.
server.port = 9411
For YAML users, add the below property in application.yml file.
server:
port: 9411
Add the @EnableZipkinServer annotation in your main Spring Boot application class fie. The @EnableZipkinServer annotation is used to enable your application act as a Zipkin server.
package com.tutorialspoint.zipkinapp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import zipkin.server.EnableZipkinServer;
@SpringBootApplication
@EnableZipkinServer
public class ZipkinappApplication {
public static void main(String[] args) {
SpringApplication.run(ZipkinappApplication.class, args);
}
}
The code for complete build configuration file is given below.
Maven – pom.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<project xmlns = "http://maven.apache.org/POM/4.0.0"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tutorialspoint</groupId>
<artifactId>zipkinapp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>zipkinapp</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<spring-cloud.version>Edgware.RELEASE</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>io.zipkin.java</groupId>
<artifactId>zipkin-server</artifactId>
</dependency>
<dependency>
<groupId>io.zipkin.java</groupId>
<artifactId>zipkin-autoconfigure-ui</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Gradle – build.gradle
buildscript {
ext {
springBootVersion = '1.5.9.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
group = 'com.tutorialspoint'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
ext {
springCloudVersion = 'Edgware.RELEASE'
}
dependencies {
compile('io.zipkin.java:zipkin-autoconfigure-ui')
compile('io.zipkin.java:zipkin-server')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
}
}
You can create an executable JAR file, and run the Spring Boot application by using the below Maven or Gradle commands −
For Maven, use the command given below −
mvn clean install
After “BUILD SUCCESS”, you can find the JAR file under the target directory.
For Gradle, use the command given below −
gradle clean build
After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory.
Run the JAR file by using the command shown −
java –jar <JARFILE>
Now, the application has started on the Tomcat port 9411 as shown below −
Now, hit the below URL and see the Zipkin server UI.
http://localhost:9411/zipkin/
Then, add the following dependency in your client service application and point out the Zipkin Server URL to trace the microservice logs via Zipkin UI.
Now, add the Spring Cloud Starter Zipkin dependency in your build configuration file as shown −
Maven users can add the following dependency in pom.xml file −
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-sleuth-zipkin</artifactId>
</dependency>
Gradle users can add the below dependency in build.gradle file −
compile('org.springframework.cloud:spring-cloud-sleuth-zipkin')
Now, add the Always Sampler Bean in your Spring Boot application to export the logs into Zipkin server.
@Bean
public AlwaysSampler defaultSampler() {
return new AlwaysSampler();
}
If you add the AlwaysSampler Bean, then automatically Spring Sleuth Zipkin Export option will change from false to true.
Next, configure your Zipkin Server base URL in client service application.properties file.
spring.zipkin.baseUrl = http://localhost:9411/zipkin/
Then, provide the trace id and find the traces in Zipkin UI. | [
{
"code": null,
"e": 3319,
"s": 3159,
"text": "Most developers face difficulty of tracing logs if any issue occurred. This can be solved by Spring Cloud Sleuth and ZipKin server for Spring Boot application."
},
{
"code": null,
"e": 3382,
"s": 3319,
"text": "Spring cloud Sleuth lo... |
Sum of all divisors from 1 to N | Set 2 | 02 Jun, 2022
Given a positive integer N, the task is to find the sum of divisors of first N natural numbers.
Examples:
Input: N = 4 Output: 15 Explanation: Sum of divisors of 1 = (1) Sum of divisors of 2 = (1+2) Sum of divisors of 3 = (1+3) Sum of divisors of 4 = (1+2+4) Hence, total sum = 1 + (1+2) + (1+3) + (1+2+4) = 15
Input: N = 5 Output: 21 Explanation: Sum of divisors of 1 = (1) Sum of divisors of 2 = (1+2) Sum of divisors of 3 = (1+3) Sum of divisors of 4 = (1+2+4) Sum of divisors of 5 = (1+5) Hence, total sum = (1) + (1+2) + (1+3) + (1+2+4) + (1+5) = 21
For linear time approach, refer to Sum of all divisors from 1 to N
Approach: To optimize the approach in the post mentioned above, we need to look for a solution with logarithmic complexity. A number D is added multiple times in the final answer. Let us try to observe a pattern of repetitive addition. Considering N = 12:
From the above pattern, observe that every number D is added (N / D) times. Also, there are multiple D that have same (N / D). Hence, we can conclude that for a given N, and a particular i, numbers from (N / (i + 1)) + 1 to (N / i) will be added i times.
Illustration:
N = 12, i = 1 (N/(i+1))+1 = 6+1 = 7 and (N/i) = 12 All numbers will be 7, 8, 9, 10, 11, 12 and will be added 1 time only.N = 12, i = 2 (N/(i+1))+1 = 4+1 = 5 and (N/i) = 6 All numbers will be 5, 6 and will be added 2 times.
N = 12, i = 1 (N/(i+1))+1 = 6+1 = 7 and (N/i) = 12 All numbers will be 7, 8, 9, 10, 11, 12 and will be added 1 time only.
N = 12, i = 2 (N/(i+1))+1 = 4+1 = 5 and (N/i) = 6 All numbers will be 5, 6 and will be added 2 times.
Now, assume A = (N / (i + 1)), B = (N / i) Sum of numbers from A + 1 to B = Sum of numbers from 1 to B – Sum of numbers from 1 to A Also, instead of just incrementing i each time by 1, find next i like this, i = N/(N/(i+1))
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for// the above approach#include<bits/stdc++.h>using namespace std; int mod = 1000000007; // Functions returns sum// of numbers from 1 to nint linearSum(int n){ return (n * (n + 1) / 2) % mod;} // Functions returns sum// of numbers from a+1 to bint rangeSum(int b, int a){ return (linearSum(b) - linearSum(a)) % mod;} // Function returns total// sum of divisorsint totalSum(int n){ // Stores total sum int result = 0; int i = 1; // Finding numbers and //its occurrence while(true) { // Sum of product of each // number and its occurrence result += rangeSum(n / i, n / (i + 1)) * (i % mod) % mod; result %= mod; if (i == n) break; i = n / (n / (i + 1)); } return result;} // Driver codeint main(){ int N = 4; cout << totalSum(N) << endl; N = 12; cout << totalSum(N) << endl; return 0;} // This code is contributed by rutvik_56
// Java program for// the above approachclass GFG{ static final int mod = 1000000007; // Functions returns sum// of numbers from 1 to npublic static int linearSum(int n){ return (n * (n + 1) / 2) % mod;} // Functions returns sum// of numbers from a+1 to bpublic static int rangeSum(int b, int a){ return (linearSum(b) - linearSum(a)) % mod;} // Function returns total// sum of divisorspublic static int totalSum(int n){ // Stores total sum int result = 0; int i = 1; // Finding numbers and //its occurrence while(true) { // Sum of product of each // number and its occurrence result += rangeSum(n / i, n / (i + 1)) * (i % mod) % mod; result %= mod; if (i == n) break; i = n / (n / (i + 1)); } return result;} // Driver codepublic static void main(String[] args){ int N = 4; System.out.println(totalSum(N)); N = 12; System.out.println(totalSum(N));}} // This code is contributed by divyeshrabadiya07
# Python3 program for# the above approach mod = 1000000007 # Functions returns sum# of numbers from 1 to ndef linearSum(n): return n*(n + 1)//2 % mod # Functions returns sum# of numbers from a+1 to bdef rangeSum(b, a): return (linearSum(b) - ( linearSum(a))) % mod # Function returns total# sum of divisorsdef totalSum(n): # Stores total sum result = 0 i = 1 # Finding numbers and # its occurrence while True: # Sum of product of each # number and its occurrence result += rangeSum( n//i, n//(i + 1)) * ( i % mod) % mod; result %= mod; if i == n: break i = n//(n//(i + 1)) return result # Driver code N= 4print(totalSum(N)) N= 12print(totalSum(N))
// C# program for// the above approachusing System; class GFG{ static readonly int mod = 1000000007; // Functions returns sum// of numbers from 1 to npublic static int linearSum(int n){ return (n * (n + 1) / 2) % mod;} // Functions returns sum// of numbers from a+1 to bpublic static int rangeSum(int b, int a){ return (linearSum(b) - linearSum(a)) % mod;} // Function returns total// sum of divisorspublic static int totalSum(int n){ // Stores total sum int result = 0; int i = 1; // Finding numbers and //its occurrence while(true) { // Sum of product of each // number and its occurrence result += rangeSum(n / i, n / (i + 1)) * (i % mod) % mod; result %= mod; if (i == n) break; i = n / (n / (i + 1)); } return result;} // Driver codepublic static void Main(String[] args){ int N = 4; Console.WriteLine(totalSum(N)); N = 12; Console.WriteLine(totalSum(N));}} // This code is contributed by Amit Katiyar
<script> // JavaScript program for// the above approachlet mod = 1000000007; // Functions returns sum// of numbers from 1 to nfunction linearSum(n){ return (n * (n + 1) / 2) % mod;} // Functions returns sum// of numbers from a+1 to bfunction rangeSum(b, a){ return (linearSum(b) - linearSum(a)) % mod;} // Function returns total// sum of divisorsfunction totalSum(n){ // Stores total sum let result = 0; let i = 1; // Finding numbers and //its occurrence while(true) { // Sum of product of each // number and its occurrence result += rangeSum(Math.floor(n / i), Math.floor(n / (i + 1))) * (i % mod) % mod; result %= mod; if (i == n) break; i = Math.floor(n / (n / (i + 1))); } return result;} // Driver Codelet N = 4;document.write(totalSum(N) + "<br/>"); N = 12;document.write(totalSum(N)); // This code is contributed by susmitakundugoaldanga </script>
15
127
Time complexity: O(√n)
rohitpal210
rutvik_56
divyeshrabadiya07
amit143katiyar
susmitakundugoaldanga
pranabsingh421306
nikhatkhan11
divisors
number-theory
Algorithms
Articles
Competitive Programming
Mathematical
number-theory
Mathematical
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n02 Jun, 2022"
},
{
"code": null,
"e": 148,
"s": 52,
"text": "Given a positive integer N, the task is to find the sum of divisors of first N natural numbers."
},
{
"code": null,
"e": 158,
"s": 148,
"text": "Examples:... |
Inverted Index | 07 Jul, 2021
An inverted index is an index data structure storing a mapping from content, such as words or numbers, to its locations in a document or a set of documents. In simple words, it is a hashmap like data structure that directs you from a word to a document or a web page.
There are two types of inverted indexes: A record-level inverted index contains a list of references to documents for each word. A word-level inverted index additionally contains the positions of each word within a document. The latter form offers more functionality, but needs more processing power and space to be created.
Suppose we want to search the texts “hello everyone, ” “this article is based on inverted index, ” “which is hashmap like data structure”. If we index by (text, word within the text), the index with location in text is:
hello (1, 1)
everyone (1, 2)
this (2, 1)
article (2, 2)
is (2, 3); (3, 2)
based (2, 4)
on (2, 5)
inverted (2, 6)
index (2, 7)
which (3, 1)
hashmap (3, 3)
like (3, 4)
data (3, 5)
structure (3, 6)
The word “hello” is in document 1 (“hello everyone”) starting at word 1, so has an entry (1, 1) and word “is” is in document 2 and 3 at ‘3rd’ and ‘2nd’ positions respectively (here position is based on word). The index may have weights, frequencies, or other indicators.
Steps to build an inverted index:
Fetch the Document Removing of Stop Words: Stop words are most occurring and useless words in document like “I”, “the”, “we”, “is”, “an”.
Stemming of Root Word Whenever I want to search for “cat”, I want to see a document that has information about it. But the word present in the document is called “cats” or “catty” instead of “cat”. To relate the both words, I’ll chop some part of each and every word I read so that I could get the “root word”. There are standard tools for performing this like “Porter’s Stemmer”.
Record Document IDs If word is already present add reference of document to index else create new entry. Add additional information like frequency of word, location of word etc.
Example:
Words Document
ant doc1
demo doc2
world doc1, doc2
Advantage of Inverted Index are:
Inverted index is to allow fast full text searches, at a cost of increased processing when a document is added to the database.
It is easy to develop.
It is the most popular data structure used in document retrieval systems, used on a large scale for example in search engines.
Inverted Index also has disadvantage:
Large storage overhead and high maintenance costs on update, delete and insert.
smruti94srp
volumezero9786
DBMS
Hash
Hash
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
SQL Interview Questions
SQL | Views
Data Preprocessing in Data Mining
Difference between DELETE, DROP and TRUNCATE
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
What is Hashing | A Complete Tutorial
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Count pairs with given sum | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n07 Jul, 2021"
},
{
"code": null,
"e": 323,
"s": 54,
"text": "An inverted index is an index data structure storing a mapping from content, such as words or numbers, to its locations in a document or a set of documents. In simple words, ... |
Python Program to Print a given matrix in reverse spiral form | 10 Jan, 2022
Given a 2D array, print it in reverse spiral form. We have already discussed Print a given matrix in spiral form. This article discusses how to do the reverse printing. See the following examples.
Input:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Output:
10 11 7 6 5 9 13 14 15 16 12 8 4 3 2 1
Input:
1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
Output:
11 10 9 8 7 13 14 15 16 17 18 12 6 5 4 3 2 1
Python3
# Python3 Code to Print a given # matrix in reverse spiral form # This is a modified code of# https:#www.geeksforgeeks.org/print-a-given-matrix-in-spiral-form/R, C = 3, 6 def ReversespiralPrint(m, n, a): # Large array to initialize it # with elements of matrix b = [0 for i in range(100)] #/* k - starting row index #l - starting column index*/ i, k, l = 0, 0, 0 # Counter for single dimension array # in which elements will be stored z = 0 # Total elements in matrix size = m * n while (k < m and l < n): # Variable to store value of matrix. val = 0 # Print the first row # from the remaining rows for i in range(l, n): # printf("%d ", a[k][i]) val = a[k][i] b[z] = val z += 1 k += 1 # Print the last column # from the remaining columns for i in range(k, m): # printf("%d ", a[i][n-1]) val = a[i][n - 1] b[z] = val z += 1 n -= 1 # Print the last row # from the remaining rows if (k < m): for i in range(n - 1, l - 1, -1): # printf("%d ", a[m-1][i]) val = a[m - 1][i] b[z] = val z += 1 m -= 1 # Print the first column # from the remaining columns if (l < n): for i in range(m - 1, k - 1, -1): # printf("%d ", a[i][l]) val = a[i][l] b[z] = val z += 1 l += 1 for i in range(size - 1, -1, -1): print(b[i], end = " ") # Driver Codea = [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12], [13, 14, 15, 16, 17, 18]] ReversespiralPrint(R, C, a) # This code is contributed by mohit kumar
Output:
11 10 9 8 7 13 14 15 16 17 18 12 6 5 4 3 2 1
Please refer complete article on Print a given matrix in reverse spiral form for more details!
pattern-printing
spiral
Matrix
Python
Python Programs
School Programming
pattern-printing
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unique paths in a Grid with Obstacles
Find the longest path in a matrix with given constraints
Find median in row wise sorted matrix
Zigzag (or diagonal) traversal of Matrix
Traverse a given Matrix using Recursion
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
Python Dictionary
How to get column names in Pandas dataframe | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Jan, 2022"
},
{
"code": null,
"e": 227,
"s": 28,
"text": "Given a 2D array, print it in reverse spiral form. We have already discussed Print a given matrix in spiral form. This article discusses how to do the reverse printing. See th... |
How to splice an array without mutating the original Array? | 02 Feb, 2022
In this article, we will be extracting the range of elements from an array without mutating it. Here, mutation means the changing of the original array. There is a built-in function that is made for the extraction of elements from the array but it mutates the array.
How the .splice( ) method works: The splice method is used to extract the range of elements from an array. It takes three arguments index, number of items to delete, an array of items to be appended. The index (first parameter) is required and the rest of the parameters are optional. This method returns a new array after removing the items but it also mutates the original array. The example below explains how it mutates the original.
Javascript
<script>// Creating an array let originalArr = ["c", "cpp", "java", "python", "javascript", "kotlin"]; // Extracting three items from the index 0let extractedArr = originalArr.splice(0, 3); // Printing the Extracted arrayconsole.log("Extracted Array")console.log(extractedArr) // Printing the original Arrayconsole.log("Original Array")console.log(originalArr)</script>
Output:
Extracted Array
["c", "cpp", "java"]
Original Array
["python", "javascript", "kotlin"]
Here you can see the original array is mutated by the splice method. We will implement the same functionality as the splice method provides but without mutating the original array. Here we will discuss two approaches to achieve this functionality the first one is using the copy of the array and the second approach is using the filter method.
Approach 1: Using the copy of the array. In this approach, we will create a copy of the original array and then use the splice method to extract the items. To create the copy or clone of the array we can use the spread operator or splice method.
Steps :
Create the clone of the array using the spread operator or slice method.
apply the splice method on the cloned array and return the extracted array
Example:
Javascript
<script>// Creating an array let originalArr = ["c", "cpp", "java", "python", "javascript", "kotlin"]; // Creating the clone of the arraylet cloneArr = originalArr.slice(0); // Or you can use spread Operator// let cloneArr = [...originalArr] // Extract the array using splice methodlet extractedArr = cloneArr.splice(0, 4); // Printing the Extracted arrayconsole.log("Extracted Array")console.log(extractedArr) // Printing the original Arrayconsole.log("Original Array")console.log(originalArr)</script>
Output: Here the original array is not mutated. But it is not a good practice to apply this approach in larger arrays because its space consumption increases when we create the clone of the array.
Extracted Array
["c", "cpp", "java", "python"]
Original Array
["c", "cpp", "java", "python", "javascript", "kotlin"]
Approach 2: Using the filter method. In this approach, we use the filter method. the filter method is used to filter out the element of an array after applying some condition to it. This method does not mutate the array.
Syntax :
Array.filter((item, index)=>{ return index >= start
&& index < howMany + start })
Example 1:
Javascript
<script>// Creating an array let originalArr = ["c", "cpp", "java", "python", "javascript", "kotlin"]; let start = 1;let howMany = 3; let extractedArr = originalArr.filter((item, index)=>{ return index >= start && index < howMany + start ;}) // Printing the Extracted arrayconsole.log("Extracted Array")console.log(extractedArr) // Printing the original Arrayconsole.log("Original Array")console.log(originalArr) </script>
Example 2: In Prototype form.
Javascript
<script>// Creating an array let originalArr = ["c", "cpp", "java", "python", "javascript", "kotlin"]; Array.prototype.mySplice = function(start, howMany){ return this.filter((item, index)=>{ return index >= start && index < howMany + start ; })} // Printing the Extracted arrayconsole.log("Extracted Array")console.log(originalArr.mySplice(1, 3)) // Printing the original Arrayconsole.log("Original Array")console.log(originalArr)</script>
Output:
Extracted Array
["cpp", "java", "python"]
Original Array
["c", "cpp", "java", "python", "javascript", "kotlin"]
avtarkumar719
javascript-array
JavaScript-Methods
JavaScript-Questions
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
Hide or show elements in HTML using display property
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": "\n02 Feb, 2022"
},
{
"code": null,
"e": 296,
"s": 28,
"text": "In this article, we will be extracting the range of elements from an array without mutating it. Here, mutation means the changing of the original array. There is a built-in fu... |
How to check if an application is open in Python? | 24 Feb, 2021
This article is about How to check if an application is open in a system using Python. You can also refer to the article Python – Get list of running processes for further information.
In the below approaches, we will be checking if chrome.exe is open in our system or not.
The psutil is a system monitoring and system utilization module of python. It is useful mainly for system monitoring, profiling and limiting process resources, and management of running processes. Usage of resources like CPU, memory, disks, network, sensors can be monitored. It is supported in Python versions 2.6, 2.7, and 3.4+. You can install psutil module by using the following command
pip install psutil
We will use the psutil.process_iter() method, it returns an iterator yielding a process class instance for all running processes on the local machine.
Python3
# import moduleimport psutil # check if chrome is open"chrome.exe" in (i.name() for i in psutil.process_iter())
Output:
True
We import the psutil module. Then we search for chrome.exe in all running processes on the local machine using psutil.process_iter(). If found it will return output as TRUE, else FALSE.
The wmi module can be used to gain system information of a Windows machine and can be installed using the below command:
pip install wmi
Its working is similar to psutil. Here, we check if a particular process name is present in the list of running processes.
Python3
# Import moduleimport wmi # Initializing the wmi constructorf = wmi.WMI() flag = 0 # Iterating through all the running processesfor process in f.Win32_Process(): if "chrome.exe" == process.Name: print("Application is Running") flag = 1 break if flag == 0: print("Application is not Running")
Output:
Application is Running
We import the wmi module. Then we search for chrome.exe in all running processes on the local machine by iterating through the process names. If it matches with the process. Name, it will print Application is Running, else Application is not Running.
Picked
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Create a directory in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Feb, 2021"
},
{
"code": null,
"e": 213,
"s": 28,
"text": "This article is about How to check if an application is open in a system using Python. You can also refer to the article Python – Get list of running processes for further inf... |
Java - Non Access Modifiers | Java provides a number of non-access modifiers to achieve many other functionalities.
The static modifier for creating class methods and variables.
The static modifier for creating class methods and variables.
The final modifier for finalizing the implementations of classes, methods, and variables.
The final modifier for finalizing the implementations of classes, methods, and variables.
The abstract modifier for creating abstract classes and methods.
The abstract modifier for creating abstract classes and methods.
The synchronized and volatile modifiers, which are used for threads.
The synchronized and volatile modifiers, which are used for threads.
The static keyword is used to create variables that will exist independently of any instances created for the class. Only one copy of the static variable exists regardless of the number of instances of the class.
Static variables are also known as class variables. Local variables cannot be declared static.
The static keyword is used to create methods that will exist independently of any instances created for the class.
Static methods do not use any instance variables of any object of the class they are defined in. Static methods take all the data from parameters and compute something from those parameters, with no reference to variables.
Class variables and methods can be accessed using the class name followed by a dot and the name of the variable or method.
Example
The static modifier is used to create class methods and variables, as in the following example −
public class InstanceCounter {
private static int numInstances = 0;
protected static int getCount() {
return numInstances;
}
private static void addInstance() {
numInstances++;
}
InstanceCounter() {
InstanceCounter.addInstance();
}
public static void main(String[] arguments) {
System.out.println("Starting with " + InstanceCounter.getCount() + " instances");
for (int i = 0; i < 500; ++i) {
new InstanceCounter();
}
System.out.println("Created " + InstanceCounter.getCount() + " instances");
}
}
This will produce the following result −
Output
Started with 0 instances
Created 500 instances
A final variable can be explicitly initialized only once. A reference variable declared final can never be reassigned to refer to an different object.
However, the data within the object can be changed. So, the state of the object can be changed but not the reference.
With variables, the final modifier often is used with static to make the constant a class variable.
Example
public class Test {
final int value = 10;
// The following are examples of declaring constants:
public static final int BOXWIDTH = 6;
static final String TITLE = "Manager";
public void changeValue() {
value = 12; // will give an error
}
}
A final method cannot be overridden by any subclasses. As mentioned previously, the final modifier prevents a method from being modified in a subclass.
The main intention of making a method final would be that the content of the method should not be changed by any outsider.
Example
You declare methods using the final modifier in the class declaration, as in the following example −
public class Test {
public final void changeName() {
// body of method
}
}
The main purpose of using a class being declared as final is to prevent the class from being subclassed. If a class is marked as final then no class can inherit any feature from the final class.
Example
public final class Test {
// body of class
}
An abstract class can never be instantiated. If a class is declared as abstract then the sole purpose is for the class to be extended.
A class cannot be both abstract and final (since a final class cannot be extended). If a class contains abstract methods then the class should be declared abstract. Otherwise, a compile error will be thrown.
An abstract class may contain both abstract methods as well normal methods.
Example
abstract class Caravan {
private double price;
private String model;
private String year;
public abstract void goFast(); // an abstract method
public abstract void changeColor();
}
An abstract method is a method declared without any implementation. The methods body (implementation) is provided by the subclass. Abstract methods can never be final or strict.
Any class that extends an abstract class must implement all the abstract methods of the super class, unless the subclass is also an abstract class.
If a class contains one or more abstract methods, then the class must be declared abstract. An abstract class does not need to contain abstract methods.
The abstract method ends with a semicolon. Example: public abstract sample();
Example
public abstract class SuperClass {
abstract void m(); // abstract method
}
class SubClass extends SuperClass {
// implements the abstract method
void m() {
.........
}
}
The synchronized keyword used to indicate that a method can be accessed by only one thread at a time. The synchronized modifier can be applied with any of the four access level modifiers.
Example
public synchronized void showDetails() {
.......
}
An instance variable is marked transient to indicate the JVM to skip the particular variable when serializing the object containing it.
This modifier is included in the statement that creates the variable, preceding the class or data type of the variable.
Example
public transient int limit = 55; // will not persist
public int b; // will persist
The volatile modifier is used to let the JVM know that a thread accessing the variable must always merge its own private copy of the variable with the master copy in the memory.
Accessing a volatile variable synchronizes all the cached copied of the variables in the main memory. Volatile can only be applied to instance variables, which are of type object or private. A volatile object reference can be null.
Example
public class MyRunnable implements Runnable {
private volatile boolean active;
public void run() {
active = true;
while (active) { // line 1
// some code here
}
}
public void stop() {
active = false; // line 2
}
}
Usually, run() is called in one thread (the one you start using the Runnable), and stop() is called from another thread. If in line 1, the cached value of active is used, the loop may not stop when you set active to false in line 2. That's when you want to use volatile. | [
{
"code": null,
"e": 2597,
"s": 2511,
"text": "Java provides a number of non-access modifiers to achieve many other functionalities."
},
{
"code": null,
"e": 2659,
"s": 2597,
"text": "The static modifier for creating class methods and variables."
},
{
"code": null,
"e... |
Python | Pandas DatetimeIndex.quarter | 24 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 DatetimeIndex.quarter attribute outputs the quarter of the date for each entries in the DatetimeIndex object.
Syntax: DatetimeIndex.quarter
Return: Index object
Example #1: Use DatetimeIndex.quarter attribute to find the quarter of the date for each entries in the DatetimeIndex object.
# importing pandas as pdimport pandas as pd # Create the DatetimeIndex# Here 'M' represents Monthly frequencydidx = pd.DatetimeIndex(start ='2014-08-01 10:05:45', freq ='M', periods = 5, tz ='Asia/Calcutta') # Print the DatetimeIndexprint(didx)
Output :
Now we want to find quarter of the date for each entries in the DatetimeIndex object.
# find the quarter of datedidx.quarter
Output :As we can see in the output, the function has returned an Index object containing the quarter value of the date for each entry of the DatetimeIndex object. Example #2: Use DatetimeIndex.quarter attribute to find the quarter of the date for each entries in the DatetimeIndex object.
# importing pandas as pdimport pandas as pd # Create the DatetimeIndex# Here 'Q' represents Quarterly frequencydidx = pd.DatetimeIndex(start ='2000-01-10 06:30', freq ='Q', periods = 5, tz ='Asia/Calcutta') # Print the DatetimeIndexprint(didx)
Output :Now we want to find quarter of the date for each entries in the DatetimeIndex object.
# find the quarter of datedidx.quarter
Output :As we can see in the output, the function has returned an Index object containing the quarter value of the date for each entry of the DatetimeIndex object.
Python pandas-datetimeIndex
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Create a directory in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Dec, 2018"
},
{
"code": null,
"e": 242,
"s": 28,
"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 imp... |
Running Extra scripts in Django | 16 Mar, 2021
Running extra scripts or processes is always needed when you have some new idea that works with web development and in Python!!! it is always.
It can be any script that may include a loading of data, processing, and cleaning of data, or any ML phase when making an application providing business logic directly in views or models is not always best. As django conventions refer to ‘thin views’, we must try to trim out the logic and try to embed it in some other files.
Django extensions in a package that enables you to run the extra scripts you need to install it using pip, use terminal and type
pip install django-extensions
add the django-extensions in installed apps found in setting.py file
INSTALLED_APPS = [
...
...
'django_extensions',
]
Now create a folder named scripts in your project that will contain all the python files which you can execute add an empty python file named ‘__init__.py’ this specifies that scripts in also part of Django projects
create new files that will contain the code that you need to execute, name anything you like
example: To load data from CSV files to the database before running the server
load.py
import csv
from site.models import Destination
def run():
# All data in run method only will be executed
fhand = open('location.csv')
reader = csv.reader(fhand)
next(reader)
for row in reader:
latitude = row[0]
longitude = row[1]
name = row[2]
item = Destination.objects.create(name=name,latitude=latitude,longitude=longitude)
item.save()
print("Data Added")
Now to run the script simply fire the command as below where ‘load’ is a file name
python manage.py runscript load
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Mar, 2021"
},
{
"code": null,
"e": 171,
"s": 28,
"text": "Running extra scripts or processes is always needed when you have some new idea that works with web development and in Python!!! it is always."
},
{
"code": null,
... |
Python Bokeh – Plot for all Types of Google Maps ( roadmap, satellite, hybrid, terrain) | 03 Jul, 2020
Bokeh is a Python interactive data visualization. It renders its plots using HTML and JavaScript. It targets modern web browsers for presentation providing elegant, concise construction of novel graphics with high-performance interactivity. Bokeh can be used to display Google maps. To use Google maps in Bokeh, we will use the gmap() function of the plotting class.
There are 4 basic types of Google maps – roadmap, satellite, hybrid, terrainWe need to configure the Google map using GMapOptions() function. The GMapOptions() function contains the parameter map_type. Using this parameter we can determine the map type of the Google map. Assign one of the 4 values to this parameter discussed above.
In order to use these maps we have to :
Import the required libraries and modules :gmap from bokeh.plottingGMapOptions from bokeh.modelsoutput_file and show from bokeh.ioCreate a file to store our model using output_file().Configure the Google map using GMapOptions(). During the configuration, assign the desired value to the map_type parameter.Generate a GoogleMap object using gmap().Display the Google map using show().
Import the required libraries and modules :gmap from bokeh.plottingGMapOptions from bokeh.modelsoutput_file and show from bokeh.io
gmap from bokeh.plotting
GMapOptions from bokeh.models
output_file and show from bokeh.io
Create a file to store our model using output_file().
Configure the Google map using GMapOptions(). During the configuration, assign the desired value to the map_type parameter.
Generate a GoogleMap object using gmap().
Display the Google map using show().
This displays the default road map view. In this type of map, the terrain is smoothened and the roads are highlighted. It is suited to navigate an area in a vehicle. This is the default map type.
# importing the required modulesfrom bokeh.plotting import gmapfrom bokeh.models import GMapOptionsfrom bokeh.io import output_file, show # file to save the modeloutput_file("gfg.html") # configuring the Google maplat = 30.3165lng = 78.0322map_type = "roadmap"zoom = 12google_map_options = GMapOptions(lat = lat, lng = lng, map_type = map_type, zoom = zoom) # generating the Google mapgoogle_api_key = ""title = "Dehradun"google_map = gmap(google_api_key, google_map_options, title = title) # displaying the modelshow(google_map)
Output :
This displays the Google Earth satellite view. It is the bird-eye view without any sort of graphics.
# importing the required modulesfrom bokeh.plotting import gmapfrom bokeh.models import GMapOptionsfrom bokeh.io import output_file, show # file to save the modeloutput_file("gfg.html") # configuring the Google maplat = 30.3165lng = 78.0322map_type = "satellite"zoom = 12google_map_options = GMapOptions(lat = lat, lng = lng, map_type = map_type, zoom = zoom) # generating the Google mapgoogle_api_key = ""title = "Dehradun"google_map = gmap(google_api_key, google_map_options, title = title) # displaying the modelshow(google_map)
Output :
As the name suggests, this displays the combination of road map and satellite map. The satellite map is overlayed with graphics of roads.
# importing the required modulesfrom bokeh.plotting import gmapfrom bokeh.models import GMapOptionsfrom bokeh.io import output_file, show # file to save the modeloutput_file("gfg.html") # configuring the Google maplat = 30.3165lng = 78.0322map_type = "hybrid"zoom = 12google_map_options = GMapOptions(lat = lat, lng = lng, map_type = map_type, zoom = zoom) # generating the Google mapgoogle_api_key = ""title = "Dehradun"google_map = gmap(google_api_key, google_map_options, title = title) # displaying the modelshow(google_map)
Output :
This displays a physical map based on the terrain information.
# importing the required modulesfrom bokeh.plotting import gmapfrom bokeh.models import GMapOptionsfrom bokeh.io import output_file, show # file to save the modeloutput_file("gfg.html") # configuring the Google maplat = 30.3165lng = 78.0322map_type = "terrain"zoom = 12google_map_options = GMapOptions(lat = lat, lng = lng, map_type = map_type, zoom = zoom) # generating the Google mapgoogle_api_key = ""title = "Dehradun"google_map = gmap(google_api_key, google_map_options, title = title) # displaying the modelshow(google_map)
Output :
Data Visualization
Python-Bokeh
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Different ways to create Pandas Dataframe
Taking input in Python
Enumerate() in Python
Read a file line by line in Python
Python String | replace() | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Jul, 2020"
},
{
"code": null,
"e": 395,
"s": 28,
"text": "Bokeh is a Python interactive data visualization. It renders its plots using HTML and JavaScript. It targets modern web browsers for presentation providing elegant, concise co... |
Perl | Searching in a File using regex | 07 Jun, 2019
Prerequisite: Perl | Regular Expressions
Regular Expression (Regex or Regexp or RE) in Perl is a special text string for describing a search pattern within a given text. Regex in Perl is linked to host language and are not the same as in PHP, Python, etc. Sometimes these are termed as “Perl 5 Compatible Regular Expressions”. To use the Regex, Binding operators like =~ (Regex Operator) and !~ (Negated Regex Operator) are used.These Binding regex operators are used to match a string from a regular expression. The left-hand side of the statement will contain a string which will be matched with the right-hand side which will contain the specified pattern. Negated regex operator checks if the string is not equal to the regular expression specified on the right-hand side.
Regex operators help in searching for a specific word or a group of words in a file. This can be done in multiple ways as per the user’s requirement. Searching in Perl follows the standard format of first opening the file in the read mode and further reading the file line by line and then look for the required string or group of strings in each line. When the required match is found, then the statement following the search expression will determine what is the next step to do with the matched string, it can be either added to any other file specified by the user or simply printed on the console.
Within the regular expression created to match the required string with the file, there can be multiple ways to search for the required string:
This is the basic pattern of writing a regular expression which looks for the required string within the specified file. Following is the syntax of such a Regular Expression:
$String =~ /the/
This expression will search for the lines in the file which contain a word with letters ‘the‘ in it and store that word in the variable $String. Further, this variable’s value can be copied to a file or simply printed on the console.
Example:
use strict;use warnings; sub main{ my $file = 'C:\Users\GeeksForGeeks\GFG.txt'; open(FH, $file) or die("File $file not found"); while(my $String = <FH>) { if($String =~ /the/) { print "$String \n"; } } close(FH);}main();
Output:As it can be seen that the above search also results in the selection of words which have ‘the’ as a part of it. To avoid such words the regular expression can be changed in the following manner:
$String =~ / the /
By providing spaces before and after the required word to be searched, the searched word is isolated from both the ends and no such word that contains it as a part of it is returned in the searching process. This will solve the problem of searching extra words which are not required. But, this will result in excluding the words that contain comma or full stop immediately after the requested search word.To avoid such situation, there are other ways as well which help in limiting the search to a specific word, one of such ways is using the word boundary.
As seen in the above Example, regular search results in returning either the extra words which contain the searched word as a part of it or excluding some of the words if searched with spaces before and after the required word. To avoid such a situation, word boundary is used which is denoted by ‘\b‘.
$String =~ /\bthe\b/;
This will limit the words which contain the requested word to be searched as a part of it and will not exclude the words that end with a comma or full stop.
Example:
use strict;use warnings; sub main{ my $file = 'C:\Users\GeeksForGeeks\GFG.txt'; open(FH, $file) or die("File $file not found"); while(my $String = <FH>) { if($String =~ /\bthe\b/) { print "$String \n"; } } close(FH);}main();
Output:As it can be seen in the above given example, the word which is ending with full stop is included in the search but the words which contain the searched words as a part are excluded. Hence, word boundary can help overcome the problem created in the Regular Search method.
What if there is a case in which there is a need to find words that either start or end or both with specific characters? Then that can’t be done with the use of Regular Search or the word boundary. For cases like these, Perl allows the use of WildCards in the Regular Expression.
Perl allows to search for a specific set of words or the words that follow a specific pattern in the given file with the use of Wild cards in Regular Expression. Wild cards are ‘dots’ placed within the regex along with the required word to be searched. These wildcards allow the regex to search for all the related words that follow the given pattern and will display the same. Wild cards help in reducing the number of iterations involved in searching for various different words which have a pattern of letters in common.
$String =~ /t..s/;
Above pattern will search for all the words which start with t, end with s, and have two letters/characters between them.
Example:
use strict;use warnings; sub main{ my $file = 'C:\Users\GeeksForGeeks\GFG.txt'; open(FH, $file) or die("File $file not found"); while(my $String = <FH>) { if($String =~ /t..s/) { print "$String \n"; } } close(FH);}main();
Output:Above code contains all the words as specified in the given pattern.
In this method of printing the searched words, the whole line that contains that word gets printed which makes it difficult to find out exactly what word is searched by the user. To avoid this confusion, we can only print the searched words and not the whole sentence. This is done by grouping the searched pattern with the use of parentheses. To print this grouping of words, $number variables are used.$number variables are the matches from the last successful match of the capture groups that are formed in the regular expression. e.g. if there are multiple groupings in the regular expression then $1 will print the words that match the first grouping, similarly, $2 will match the second grouping and so on.
Given below is the above program transformed using the $number variables to show only the searched words and not the whole sentence:
use strict;use warnings; sub main{ my $file = 'C:\Users\GeeksForGeeks\GFG.txt'; open(FH, $file) or die("File $file not found"); while(my $String = <FH>) { if($String =~ /(t..s)/) { print "$1 \n"; } } close(FH);}main();
Output:
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Perl | Arrays
Perl Tutorial - Learn Perl With Examples
Perl | Boolean Values
Perl | length() Function
Perl | Subroutines or Functions
Perl | Basic Syntax of a Perl Program
Use of print() and say() in Perl
Hello World Program in Perl
Introduction to Perl
Perl | eq operator | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Jun, 2019"
},
{
"code": null,
"e": 69,
"s": 28,
"text": "Prerequisite: Perl | Regular Expressions"
},
{
"code": null,
"e": 805,
"s": 69,
"text": "Regular Expression (Regex or Regexp or RE) in Perl is a special tex... |
Difference between SCTP and TCP | 09 May, 2022
1. Stream Control Transmission Protocol (SCTP) : SCTP is connection- oriented protocol in computer networks which provides full-duplex association i.e., transmitting multiple streams of data between two end points at the same time that have established connection in network.
2. Transmission Control Protocol (TCP) : TCP is connection oriented reliable protocol which supports guaranteed data transmission. TCP provides reliable data transmission from the connection establishment itself.
Difference between SCTP and TCP :
navinpatnacitynav
Computer Networks
Difference Between
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of Network Topology
RSA Algorithm in Cryptography
TCP Server-Client implementation in C
Socket Programming in Python
GSM in Wireless Communication
Class method vs Static method in Python
Difference between BFS and DFS
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 May, 2022"
},
{
"code": null,
"e": 329,
"s": 52,
"text": "1. Stream Control Transmission Protocol (SCTP) : SCTP is connection- oriented protocol in computer networks which provides full-duplex association i.e., transmitting multiple... |
ReactJS setState() | 18 May, 2022
All the React components can have a state associated with them. The state of a component can change either due to a response to an action performed by the user or an event triggered by the system. Whenever the state changes, React re-renders the component to the browser. Before updating the value of the state, we need to build an initial state setup. Once we are done with it, we use the setState() method to change the state object. It ensures that the component has been updated and calls for re-rendering of the component.
setState is asynchronous call means if synchronous call get called it may not get updated at right time like to know current value of object after update using setState it may not get give current updated value on console. To get some behavior of synchronous need to pass function instead of object to setState.
Syntax: We can use setState() to change the state of the component directly as well as through an arrow function.
setState({ stateName : updatedStateValue })
// OR
setState((prevState) => ({
stateName: prevState.stateName + 1
}))
Creating React Application:
Step 1: Create a React application using the following command:npx create-react-app foldername
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Example 1: Updating single attribute.
We set up our initial state value inside constructor function and create another function updateState() for updating the state. Now when we click on the button, the latter gets triggered as an onClick event which changes the state value. We perform setState() method in our updateState() function by writing:
this.setState({greeting : 'GeeksForGeeks welcomes you !!'})
As you can see, we are passing an object to setState(). This object contains the part of the state we want to update which, in this case, is the value of greeting. React takes this value and merges it into the object that needs it. It’s just like the button component asks what it should use for updating the value of greeting and setState() responds with an answer.
App.js
import React, { Component } from 'react' class App extends Component { constructor(props){ super(props) // Set initial state this.state = {greeting : 'Click the button to receive greetings'} // Binding this keyword this.updateState = this.updateState.bind(this) } updateState(){ // Changing state this.setState({greeting : 'GeeksForGeeks welcomes you !!'}) } render(){ return ( <div> <h2>Greetings Portal</h2> <p>{this.state.greeting}</p> {/* Set click handler */} <button onClick={this.updateState}> Click me! </button> </div> ) } } export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Example 2: Updating multiple attributes.
The state object of a component may contain multiple attributes and React allows using setState() function to update only a subset of those attributes as well as using multiple setState() methods to update each attribute value independently.
We set our initial state by initializing three different attributes, and then we create a function updateState() which updates its value whenever it is called. Once again this function gets triggered as an onClick event and we get the updated values of our states at the same time.
App.js
import React, { Component } from 'react' class App extends Component { constructor(props){ super(props) // Set initial state this.state = { test: "Nil", questions: "0", students: "0" } // Binding this keyword this.updateState = this.updateState.bind(this) } updateState(){ // Changing state this.setState({ test: 'Programming Quiz', questions: '10', students: '30' }) } render(){ return ( <div> <h2>Test Portal</h2> <p>{this.state.test}</p> <p>{this.state.questions}</p> <p>{this.state.students}</p> {/* Set click handler */} <button onClick={this.updateState}> Click me! </button> </div> ) } } export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Example 3: Updating state values using props.
We set up an array of strings testTopics as props for our component. A function listOfTopics is created to map all the strings as list items in our state topics. The function updateState gets triggered and sets the topics to list items. When we click on the button, we get updated state values. This method is well-known for handling complex data and updating the state very easily.
App.js
import React, { Component } from 'react' class App extends Component { static defaultProps = { testTopics : [ 'React JS', 'Node JS', 'Compound components', 'Lifecycle Methods', 'Event Handlers', 'Router', 'React Hooks', 'Redux', 'Context' ] } constructor(props){ super(props) // Set initial state this.state = { testName: "React js Test", topics: '' } // Binding this keyword this.updateState = this.updateState.bind(this) } listOfTopics(){ return ( <ul> {this.props.testTopics.map(topic => ( <li>{topic}</li> ))} </ul> ) } updateState(){ // Changing state this.setState({ testName: 'Test topics are:', topics: this.listOfTopics() }) } render(){ return ( <div> <h2>Test Information</h2> <p>{this.state.testName}</p> <p>{this.state.topics}</p> {/* Set click handler */} <button onClick={this.updateState}> Click me! </button> </div> ) } } export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Example 4. Updating the state using its previous value.
We create an initial state count having a value of 0. The function updateState() increments the present value of the state by 1 whenever it is called. This time we use setState() method in an arrow function by passing prevState as a parameter. The current value of the state is accessed with prevState.stateName which gets incremented by 1 whenever we press the button. This method is really useful when we are setting a value in the state in such a way that it depends on its previous value. For example, toggling a boolean (true/false) or incrementing/decrementing a number.
App.js
import React, { Component } from 'react' class App extends Component { constructor(props){ super(props) // Set initial state this.state = { count: 0 } // Binding this keyword this.updateState = this.updateState.bind(this) } updateState(){ // Changing state this.setState((prevState) => { return { count: prevState.count + 1} }) } render(){ return ( <div> <h2>Click Counter</h2> <p>You have clicked me {this.state.count} times.</p> {/* Set click handler */} <button onClick={this.updateState}> Click me! </button> </div> ) } } export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
surbhikumaridav
Picked
ReactJS-Basics
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ReactJS useNavigate() Hook
How to fetch data from APIs using Asynchronous await in ReactJS ?
How to connect ReactJS as a front-end with PHP as a back-end ?
Axios in React: A Guide for Beginners
How to write comments in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Node.js fs.readFileSync() Method
How to set the default value for an HTML <select> element ? | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n18 May, 2022"
},
{
"code": null,
"e": 582,
"s": 54,
"text": "All the React components can have a state associated with them. The state of a component can change either due to a response to an action performed by the user or an event tr... |
How to Create Categorical Variables in R? | 19 Dec, 2021
In this article, we will learn how to create categorical variables in the R Programming language.
In statistics, variables can be divided into two categories, i.e., categorical variables and quantitative variables. The variables which consist of numerical quantifiable values are known as quantitative variables and a categorical variable is a variable that can take on one of a limited, and usually fixed, number of possible values, assigning each individual or other unit of observation to a particular group or nominal category on the basis of some qualitative property.
To create a categorical variable from scratch i.e. by giving manual value for each row of data, we use the factor() function and pass the data column that is to be converted into a categorical variable. This factor() function converts the quantitative variable into a categorical variable by grouping the same values together.
Syntax:
df$categorical_variable <- factor( categorical_vector )
where
df: determines the data frame.
categorical_variable: determines the final column variable which will contain categorical data.
categorical_vector: is the vector that has to be converted.
Example:
Here, is a basic data frame where a new column group is added as a categorical variable.
R
# create sample data framedf <- data.frame(x=c(10, 23, 13, 41, 15), y=c(71, 17, 28, 32, 12)) # create categorical vectorgroup_vector <- c('A','B','C','D','E') # Add categorical variable to the data framedf$group <- factor(group_vector) # print data framedf
Output:
x y group
1 10 71 A
2 23 17 B
3 13 28 C
4 41 32 D
5 15 12 E
To create a categorical variable from the existing column, we use an if-else statement within the factor() function and give a value to a column if a certain condition is true otherwise give another value.
Syntax:
df$categorical_variable <- as.factor( ifelse(condition, val1, val2) )
where
df: determines the data frame.
categorical_variable: determines the final column variable which will contain categorical data.
condition: determines the condition to be checked, if the condition is true, use val1 otherwise val2.
Example:
Here, is a basic data frame where a new column group is added as a categorical variable from an if-else condition.
R
# create sample data framedf <- data.frame(x=c(10, 23, 13, 41, 15), y=c(71, 17, 28, 32, 12)) # Add categorical variable to the data framedf$group <- as.factor(ifelse(df$x >20, 'A', 'B')) # print data framedf
Output:
x y group
1 10 71 B
2 23 17 A
3 13 28 B
4 41 32 A
5 15 12 B
To create a categorical variable from the existing column, we use multiple if-else statements within the factor() function and give a value to a column if a certain condition is true, if none of the conditions are true we use the else value of the last statement.
Syntax:
df$categorical_variable <- as.factor( ifelse(condition, val,ifelse(condition, val,ifelse(condition, val, ifelse(condition, val, vale_else)))))
where
df: determines the data frame.
categorical_variable: determines the final column variable which will contain categorical data.
condition: determines the condition to be checked, if the condition is true, use val.
val_else: determines the value if no condition is true.
Example:
Here, is a basic data frame where a new column group is added as a categorical variable from multiple if-else conditions.
R
# create sample data framedf <- data.frame(x=c(10, 23, 13, 41, 15, 11, 23, 45, 95, 23, 75), y=c(71, 17, 28, 32, 12, 13, 41, 15, 11, 23, 34)) # Add categorical variable to the data framedf$group <- as.factor(ifelse(df$x<20, 'A', ifelse(df$x<30, 'B', ifelse(df$x<50, 'C', ifelse(df$x<90, 'D', 'E'))))) # print data framedf
Output:
x y group
1 10 71 A
2 23 17 B
3 13 28 A
4 41 32 C
5 15 12 A
6 11 13 A
7 23 41 B
8 45 15 C
9 95 11 E
10 23 23 B
11 75 34 D
Picked
R-DataFrame
R-Factors
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Loops in R (for, while, repeat)
Group by function in R using Dplyr
How to change Row Names of DataFrame in R ?
How to Change Axis Scales in R Plots?
Logistic Regression in R Programming
R - if statement
How to filter R DataFrame by values in a column? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Dec, 2021"
},
{
"code": null,
"e": 126,
"s": 28,
"text": "In this article, we will learn how to create categorical variables in the R Programming language."
},
{
"code": null,
"e": 602,
"s": 126,
"text": "In stati... |
What are C++ Integer Constants? | Integer constants are constant data elements that have no fractional parts or exponents. They always begin with a digit. You can specify integer constants in decimal, octal, or hexadecimal form. They can specify signed or unsigned types and long or short types.
In C++ you can use the following code to create an integer constant −
#include<iostream>
using namespace std;
int main() {
const int x = 15; // 15 is decimal integer constant while x is a constant int.
int y = 015; // 15 is octal integer constant while y is an int.
return 0;
}
You can find the complete grammar to specify integer constants on https://msdn.microsoft.com/en-us/library/00a1awxf.aspx. | [
{
"code": null,
"e": 1324,
"s": 1062,
"text": "Integer constants are constant data elements that have no fractional parts or exponents. They always begin with a digit. You can specify integer constants in decimal, octal, or hexadecimal form. They can specify signed or unsigned types and long or shor... |
SVN - Branching | Branch operation creates another line of development. It is useful when someone wants the development process to fork off into two different directions. Let us suppose you have released a product of version 1.0, you might want to create new branch so that development of 2.0 can be kept separate from 1.0 bug fixes.
In this section, we will see how to create, traverse and merge branch. Jerry is not happy because of the conflict, so he decides to create a new private branch.
[jerry@CentOS project_repo]$ ls
branches tags trunk
[jerry@CentOS project_repo]$ svn copy trunk branches/jerry_branch
A branches/jerry_branch
[jerry@CentOS project_repo]$ svn status
A + branches/jerry_branch
[jerry@CentOS project_repo]$ svn commit -m "Jerry's private branch"
Adding branches/jerry_branch
Adding branches/jerry_branch/README
Committed revision 9.
[jerry@CentOS project_repo]$
Now Jerry is working in his private branch. He adds sort operation for the array. Jerry's modified code looks like this.
[jerry@CentOS project_repo]$ cd branches/jerry_branch/
[jerry@CentOS jerry_branch]$ cat array.c
The above command will produce the following result.
#include <stdio.h>
#define MAX 16
void bubble_sort(int *arr, int n)
{
int i, j, temp, flag = 1;
for (i = 1; i < n && flag == 1; ++i) {
flag = 0;
for (j = 0; j < n - i; ++j) {
if (arr[j] > arr[j + 1]) {
flag = 1;
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
void accept_input(int *arr, int n)
{
int i;
for (i = 0; i < n; ++i)
scanf("%d", &arr[i]);
}
void display(int *arr, int n)
{
int i;
for (i = 0; i < n; ++i)
printf("|%d| ", arr[i]);
printf("\n");
}
int main(void)
{
int i, n, key, ret, arr[MAX];
printf("Enter the total number of elements: ");
scanf("%d", &n);
/* Error handling for array overflow */
if (n >MAX) {
fprintf(stderr, "Number of elements must be less than %d\n", MAX);
return 1;
}
printf("Enter the elements\n");
accept_input(arr, n);
printf("Array has following elements\n");
display(arr, n);
printf("Sorted data is\n");
bubble_sort(arr, n);
display(arr, n);
return 0;
}
Jerry compiles and tests his code and is ready to commit his changes.
[jerry@CentOS jerry_branch]$ make array
cc array.c -o array
[jerry@CentOS jerry_branch]$ ./array
The above command will produce the following result.
Enter the total number of elements: 5
Enter the elements
10
-4
2
7
9
Array has following elements
|10| |-4| |2| |7| |9|
Sorted data is
|-4| |2| |7| |9| |10|
[jerry@CentOS jerry_branch]$ svn status
? array
M array.c
[jerry@CentOS jerry_branch]$ svn commit -m "Added sort operation"
Sending jerry_branch/array.c
Transmitting file data .
Committed revision 10.
Meanwhile, over in the trunk, Tom decides to implement search operation. Tom adds code for search operation and his code looks like this.
[tom@CentOS trunk]$ svn diff
The above command will produce the following result.
Index: array.c
===================================================================
--- array.c (revision 10)
+++ array.c (working copy)
@@ -2,6 +2,27 @@
#define MAX 16
+int bin_search(int *arr, int n, int key)
+{
+ int low, high, mid;
+
+ low = 0;
+ high = n - 1;
+ mid = low + (high - low) / 2;
+
+ while (low <= high) {
+ if (arr[mid] == key)
+ return mid;
+ if (arr[mid] > key)
+ high = mid - 1;
+ else
+ low = mid + 1;
+ mid = low + (high - low) / 2;
+ }
+
+ return -1;
+}
+
void accept_input(int *arr, int n)
{
int i;
@@ -22,7 +43,7 @@
int main(void)
{
- int i, n, arr[MAX];
+ int i, n, ret, key, arr[MAX];
printf("Enter the total number of elements: ");
scanf("%d", &n);
@@ -39,5 +60,16 @@
printf("Array has following elements\n");
display(arr, n);
+ printf("Enter the element to be searched: ");
+ scanf("%d", &key);
+
+ ret = bin_search(arr, n, key);
+ if (ret < 0) {
+ fprintf(stderr, "%d element not present in array\n", key);
+ return 1;
+ }
+
+ printf("%d element found at location %d\n", key, ret + 1);
+
return 0;
}
After reviewing, he commits his changes.
[tom@CentOS trunk]$ svn status
? array
M array.c
[tom@CentOS trunk]$ svn commit -m "Added search operation"
Sending trunk/array.c
Transmitting file data .
Committed revision 11.
But Tom is curious about what Jerry has been doing in his private branch.
[tom@CentOS trunk]$ cd ../branches/
[tom@CentOS branches]$ svn up
A jerry_branch
A jerry_branch/array.c
A jerry_branch/README
[tom@CentOS branches]$ svn log
------------------------------------------------------------------------
r9 | jerry | 2013-08-27 21:56:51 +0530 (Tue, 27 Aug 2013) | 1 line
Added sort operation
------------------------------------------------------------------------
By viewing the Subversion's log message, Tom found that Jerry implemented 'sort' operation. Tom implemented search operation using binary search algorithm, it always expects data in sorted order. But what if the user provides data in an unsorted order? In that situation, binary search operation will fail. So he decides to take Jerry's code to sort data before search operation. So he asks Subversion to merge code from Jerry's branch into trunk.
[tom@CentOS trunk]$ pwd
/home/tom/project_repo/trunk
[tom@CentOS trunk]$ svn merge ../branches/jerry_branch/
--- Merging r9 through r11 into '.':
U array.c
After merging, array.c will look like this.
[tom@CentOS trunk]$ cat array.c
The above command will produce the following result.
#include <stdio.h>
#define MAX 16
void bubble_sort(int *arr, int n)
{
int i, j, temp, flag = 1;
for (i = 1; i < n && flag == 1; ++i) {
flag = 0;
for (j = 0; j < n - i; ++j) {
if (arr[j] > arr[j + 1]) {
flag = 1;
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int bin_search(int *arr, int n, int key)
{
int low, high, mid;
low = 0;
high = n - 1;
mid = low + (high - low) / 2;
while (low <= high) {
if (arr[mid] == key)
return mid;
if (arr[mid] > key)
high = mid - 1;
else
low = mid + 1;
mid = low + (high - low) / 2;
}
return -1;
}
void accept_input(int *arr, int n)
{
int i;
for (i = 0; i < n; ++i)
scanf("%d", &arr[i]);
}
void display(int *arr, int n)
{
int i;
for (i = 0; i < n; ++i)
printf("|%d| ", arr[i]);
printf("\n");
}
int main(void)
{
int i, n, ret, key, arr[MAX];
printf("Enter the total number of elements: ");
scanf("%d", &n);
/* Error handling for array overflow */
if (n > MAX) {
fprintf(stderr, "Number of elements must be less than %d\n", MAX);
return 1;
}
printf("Enter the elements\n");
accept_input(arr, n);
printf("Array has following elements\n");
display(arr, n);
printf("Sorted data is\n");
bubble_sort(arr, n);
display(arr, n);
printf("Enter the element to be searched: ");
scanf("%d", &key);
ret = bin_search(arr, n, key);
if (ret < 0) {
fprintf(stderr, "%d element not present in array\n", key);
return 1;
}
printf("%d element found at location %d\n", key, ret + 1);
return 0;
}
After compilation and testing, Tom commits his changes to the repository.
[tom@CentOS trunk]$ make array
cc array.c -o array
[tom@CentOS trunk]$ ./array
Enter the total number of elements: 5
Enter the elements
10
-2
8
15
3
Array has following elements
|10| |-2| |8| |15| |3|
Sorted data is
|-2| |3| |8| |10| |15|
Enter the element to be searched: -2
-2 element found at location 1
[tom@CentOS trunk]$ svn commit -m "Merge changes from Jerry's code"
Sending trunk
Sending trunk/array.c
Transmitting file data .
Committed revision 12.
[tom@CentOS trunk]$
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2092,
"s": 1776,
"text": "Branch operation creates another line of development. It is useful when someone wants the development process to fork off into two different directions. Let us suppose you have released a product of version 1.0, you might want to create new branch so th... |
Embedded Systems - Instructions | The flow of program proceeds in a sequential manner, from one instruction to the next instruction, unless a control transfer instruction is executed. The various types of control transfer instruction in assembly language include conditional or unconditional jumps and call instructions.
Repeating a sequence of instructions a certain number of times is called a loop. An instruction DJNZ reg, label is used to perform a Loop operation. In this instruction, a register is decremented by 1; if it is not zero, then 8051 jumps to the target address referred to by the label.
The register is loaded with the counter for the number of repetitions prior to the start of the loop. In this instruction, both the registers decrement and the decision to jump are combined into a single instruction. The registers can be any of R0–R7. The counter can also be a RAM location.
Multiply 25 by 10 using the technique of repeated addition.
Solution − Multiplication can be achieved by adding the multiplicand repeatedly, as many times as the multiplier. For example,
25 * 10 = 250(FAH)
25 + 25 + 25 + 25 + 25 + 25 + 25 + 25 + 25 + 25 = 250
MOV A,#0 ;A = 0,clean ACC
MOV R2,#10 ; the multiplier is replaced in R2
Add A,#25 ;add the multiplicand to the ACC
AGAIN:DJNZ R2,
AGAIN:repeat until R2 = 0 (10 times)
MOV R5 , A ;save A in R5 ;R5 (FAH)
Drawback in 8051 − Looping action with the instruction DJNZ Reg label is limited to 256 iterations only. If a conditional jump is not taken, then the instruction following the jump is executed.
When we use a loop inside another loop, it is called a nested loop. Two registers are used to hold the count when the maximum count is limited to 256. So we use this method to repeat the action more times than 256.
Example
Write a program to −
Load the accumulator with the value 55H.
Complement the ACC 700 times.
Solution − Since 700 is greater than 255 (the maximum capacity of any register), two registers are used to hold the count. The following code shows how to use two registers, R2 and R3, for the count.
MOV A,#55H ;A = 55H
NEXT: MOV R3,#10 ;R3 the outer loop counter
AGAIN:MOV R2,#70 ;R2 the inner loop counter
CPL A ;complement
The following table lists the conditional jumps used in 8051 −
JZ (jump if A = 0) − In this instruction, the content of the accumulator is checked. If it is zero, then the 8051 jumps to the target address. JZ instruction can be used only for the accumulator, it does not apply to any other register.
JZ (jump if A = 0) − In this instruction, the content of the accumulator is checked. If it is zero, then the 8051 jumps to the target address. JZ instruction can be used only for the accumulator, it does not apply to any other register.
JNZ (jump if A is not equal to 0) − In this instruction, the content of the accumulator is checked to be non-zero. If it is not zero, then the 8051 jumps to the target address.
JNZ (jump if A is not equal to 0) − In this instruction, the content of the accumulator is checked to be non-zero. If it is not zero, then the 8051 jumps to the target address.
JNC (Jump if no carry, jumps if CY = 0) − The Carry flag bit in the flag (or PSW) register is used to make the decision whether to jump or not "JNC label". The CPU looks at the carry flag to see if it is raised (CY = 1). If it is not raised, then the CPU starts to fetch and execute instructions from the address of the label. If CY = 1, it will not jump but will execute the next instruction below JNC.
JNC (Jump if no carry, jumps if CY = 0) − The Carry flag bit in the flag (or PSW) register is used to make the decision whether to jump or not "JNC label". The CPU looks at the carry flag to see if it is raised (CY = 1). If it is not raised, then the CPU starts to fetch and execute instructions from the address of the label. If CY = 1, it will not jump but will execute the next instruction below JNC.
JC (Jump if carry, jumps if CY = 1) − If CY = 1, it jumps to the target address.
JC (Jump if carry, jumps if CY = 1) − If CY = 1, it jumps to the target address.
JB (jump if bit is high)
JB (jump if bit is high)
JNB (jump if bit is low)
JNB (jump if bit is low)
Note − It must be noted that all conditional jumps are short jumps, i.e., the address of the target must be within –128 to +127 bytes of the contents of the program counter.
There are two unconditional jumps in 8051 −
LJMP (long jump) − LJMP is 3-byte instruction in which the first byte represents opcode, and the second and third bytes represent the 16-bit address of the target location. The 2-byte target address is to allow a jump to any memory location from 0000 to FFFFH.
LJMP (long jump) − LJMP is 3-byte instruction in which the first byte represents opcode, and the second and third bytes represent the 16-bit address of the target location. The 2-byte target address is to allow a jump to any memory location from 0000 to FFFFH.
SJMP (short jump) − It is a 2-byte instruction where the first byte is the opcode and the second byte is the relative address of the target location. The relative address ranges from 00H to FFH which is divided into forward and backward jumps; that is, within –128 to +127 bytes of memory relative to the address of the current PC (program counter). In case of forward jump, the target address can be within a space of 127 bytes from the current PC. In case of backward jump, the target address can be within –128 bytes from the current PC.
SJMP (short jump) − It is a 2-byte instruction where the first byte is the opcode and the second byte is the relative address of the target location. The relative address ranges from 00H to FFH which is divided into forward and backward jumps; that is, within –128 to +127 bytes of memory relative to the address of the current PC (program counter). In case of forward jump, the target address can be within a space of 127 bytes from the current PC. In case of backward jump, the target address can be within –128 bytes from the current PC.
All conditional jumps (JNC, JZ, and DJNZ) are short jumps because they are 2-byte instructions. In these instructions, the first byte represents opcode and the second byte represents the relative address. The target address is always relative to the value of the program counter. To calculate the target address, the second byte is added to the PC of the instruction immediately below the jump. Take a look at the program given below −
Line PC Op-code Mnemonic Operand
1 0000 ORG 0000
2 0000 7800 MOV R0,#003
3 0002 7455 MOV A,#55H0
4 0004 6003 JZ NEXT
5 0006 08 INC R0
6 0007 04 AGAIN: INC A
7 0008 04 INC A
8 0009 2477 NEXT: ADD A, #77h
9 000B 5005 JNC OVER
10 000D E4 CLR A
11 000E F8 MOV R0, A
12 000F F9 MOV R1, A
13 0010 FA MOV R2, A
14 0011 FB MOV R3, A
15 0012 2B OVER: ADD A, R3
16 0013 50F2 JNC AGAIN
17 0015 80FE HERE: SJMP HERE
18 0017 END
In case of a forward jump, the displacement value is a positive number between 0 to 127 (00 to 7F in hex). However, for a backward jump, the displacement is a negative value of 0 to –128.
CALL is used to call a subroutine or method. Subroutines are used to perform operations or tasks that need to be performed frequently. This makes a program more structured and saves memory space. There are two instructions − LCALL and ACALL.
LCALL is a 3-byte instruction where the first byte represents the opcode and the second and third bytes are used to provide the address of the target subroutine. LCALL can be used to call subroutines which are available within the 64K-byte address space of the 8051.
To make a successful return to the point after execution of the called subroutine, the CPU saves the address of the instruction immediately below the LCALL on the stack. Thus, when a subroutine is called, the control is transferred to that subroutine, and the processor saves the PC (program counter) on the stack and begins to fetch instructions from the new location. The instruction RET (return) transfers the control back to the caller after finishing execution of the subroutine. Every subroutine uses RET as the last instruction.
ACALL is a 2-byte instruction, in contrast to LCALL which is 3 bytes. The target address of the subroutine must be within 2K bytes because only 11 bits of the 2 bytes are used for address. The difference between the ACALL and LCALL is that the target address for LCALL can be anywhere within the 64K-bytes address space of the 8051, while the target address of CALL is within a 2K-byte range.
65 Lectures
6.5 hours
Amit Rana
36 Lectures
4.5 hours
Amit Rana
33 Lectures
3 hours
Ashraf Said
23 Lectures
2 hours
Smart Logic Academy
66 Lectures
5.5 hours
NerdyElectronics
49 Lectures
8.5 hours
Rahul Shrivastava
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2170,
"s": 1883,
"text": "The flow of program proceeds in a sequential manner, from one instruction to the next instruction, unless a control transfer instruction is executed. The various types of control transfer instruction in assembly language include conditional or unconditi... |
How to get the process id from Python Multiprocess? - GeeksforGeeks | 27 Mar, 2021
In this article, we will see how to get the process id from Python Multiprocess For this we should make use of method multiprocessing.current_process() to get the multiprocess id. Multiprocessing refers to the ability of a system to support more than one processor at the same time. Applications in a multiprocessing system are broken into smaller routines that run independently. The operating system allocates these threads to the processors improving the performance of the system.
Consider a computer system with a single processor. If it is assigned several processes at the same time, it will have to interrupt each task and switch briefly to another, to keep all the processes going.This situation is just like a chef working in a kitchen alone. He has to do several tasks like baking, stirring, kneading dough, etc.
Example 1:
First, we need to import a multiprocessing library in python.
Python3
# importing library
import multiprocessing
# define function
def twos_multiple(y):
# get current process
print(multiprocessing.current_process())
return y * 2
pro = multiprocessing.Pool()
print(pro.map(twos_multiple, range(10)))
Output:
Example 2:
Multiprocessing will maintain an itertools.counter object for each and every process, which is used to generate an _identity tuple for any child processes it spawns and the top-level process produces child process with single-value ids, and they spawn process with two-value ids, and so on. Then, if no names are passed to the Process constructor, it simply autogenerates the name based on the _identity, using ‘:’.join(...). Then Pool alters the name of the process using replace, leaving the autogenerated id the same.
The auto-generated names are unique. It will return the process object itself, there is a possibility of the process being its own identity.
The upshot of all this is that although two Processes may have the same name, because you may assign the same name to them when you create them, they are unique if you don’t touch the name parameter. Also, you could theoretically use _identity as a unique identifier; but I gather they made that variable private for a reason!
Python3
import multiprocessing
def twos_multiple(x):
proc = multiprocessing.Process()
curr_proc = multiprocessing.current_process()
print('current process:', curr_proc.name, curr_proc._identity)
print('created process:', proc.name, proc._identity)
return x * 2
pro = multiprocessing.Pool()
print(pro.map(twos_multiple, range(10)))
Output:
Picked
Python-multithreading
Python
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 unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python | [
{
"code": null,
"e": 24001,
"s": 23970,
"text": " \n27 Mar, 2021\n"
},
{
"code": null,
"e": 24487,
"s": 24001,
"text": "In this article, we will see how to get the process id from Python Multiprocess For this we should make use of method multiprocessing.current_process() to get t... |
Incron command in Linux with Examples - GeeksforGeeks | 30 Dec, 2021
Incron is an “inotify cron” system. It works very much like the regular cron, however, cron jobs are triggered by a moment in time (every Sunday, once a day at 12 am and so on), whereas incron jobs are triggered by filesystem events (such as creating, deleting or modifying files or directories). Here are few examples where incron can be used:
Monitoring file usage and statistics
Notifying programs (e.g. server daemons) if changes are made in the configuration files.
Protecting against changes in the critical files.
Automatic on-change backup or versioning.
Processing uploaded files.
Note: As incron is not recursive, so you have to also add all the sub-directories that you want it to watch. Do not do any action from within an incron job in a directory that you monitor to avoid loops.
Use the following command to install incron.
$sudo apt-get install incron
Configuration: To configure incron access we have to configure /etc/incron.allow and /etc/incron.deny files.
/etc/incron.allow : If this file exists only users listed here may use incron.
/etc/incron.deny : If this file exists only users NOT listed here may use incron.
If none of these files exists every user on the system is allowed to use incron.
<path> <mask> <command>
Here:
<path>is absolute path of the directory to watch.
<mask> is event mask(in symbolic or numerical form).
Event Symbols (Masks): IN_ACCESS File was accessed (read). IN_ATTRIB Metadata changed (permissions, timestamps, extended attributes, etc.). IN_CLOSE_WRITE File opened for writing was closed. IN_CLOSE_NOWRITE File not opened for writing was closed. IN_CREATE File/directory created in watched directory. IN_DELETE File/directory deleted from watched directory. IN_DELETE_SELF Watched file/directory was itself deleted. IN_MODIFY File was modified. IN_MOVE_SELF Watched file/directory was itself moved. IN_MOVED_FROM File moved out of watched directory. IN_MOVED_TO File moved into watched directory. IN_OPEN File was opened.
<command> is executable file (or script) with its arguments.
The following wildcards may be used inside the command specification. $$ Prints a dollar sign $@ Add the watched filesystem path $# Add the event-related file name $% Add the event flags (textually) $& Add the event flags (numerically)
After installation and configuration, you need to start incron daemon by using the following command:
$ /etc/init.d/incrond start
OR
$ systemctl start incron.service
You can check incron status using:
$ systemctl status incron.service
Now you have to add your user or root to the /etc/incron.allow config. file so that that user can access crontab.
$ sudo nano /etc/incron.allow
Using incrontab commands you can list (-l), edit (-e), and remove (-r) incrontab entries.
$ incrontab -l
$ incrontab -e
$ incrontab -r
Suppose, we want to monitor a file( /tmp/gfg/myfile.txt ) and for every change, we want to log the date and time of the modification to a log file( /tmp/logs/mylogs.txt ).
1. The content of “myfile.txt” are displayed below.
2. Create a script with name “action.sh” that will log the date and time to the log file, we will run this script every time changes are made to the myfile.txt.
3. Now you can edit crontab using command.
$ crontab -e:
4. Now let’s make changes to myfile.txt.
5. If we see logs we can see the date and time of changes.
Now let’s monitor directory( /tmp/gfg/) and for every new File/directory we log the date and time of the creation to a log file( /tmp/logs/mylogs.txt ). 1. Open incrontab file. Here we are passing “$#” wildcard in the command which will pass the event-related file name to the command.
2. We will update action.sh. Here we are using “$#” wildcard which was passed as a argument.
3. Now let’s try it out by creating a new file in our gfg directory and see the resultant in log file:
gulshankumarar231
anikakapoor
germanshephered48
linux-command
Linux-system-commands
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": "\n30 Dec, 2021"
},
{
"code": null,
"e": 24362,
"s": 24015,
"text": "Incron is an “inotify cron” system. It works very much like the regular cron, however, cron jobs are triggered by a moment in time (every Sunday, once a day at 12 ... |
C++ "Hello, World!" Program | C++ is a general purpose programming language that supports procedural, object-oriented and generic programming. C++ is a superset of C and all valid C programs are valid in C++ as well.
C++ supports object oriented programming with features such as data hiding, encapsulation, inheritance, polymorphism etc.
Let us see the first C++ program that prints Hello, World!.
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!" << endl; // This prints Hello, World!
return 0;
}
The output of the above program is as follows −
Hello, World!
The different parts of the above program are explained as follows.
There are different headers in C++, each of which contain information that is necessary in the program. The header is used in this program which provides basic input and output services for C++ programs.
Namespaces are a relatively recent addition to C++. The following line we saw above informs the compiler to use the std namespace −
using namespace std;
The program execution begins with the following line as the main() function is the entry point of any C++ program.
int main()
The message “Hello, World!” is displayed on the screen using the following statement −
cout << "Hello, World!" << endl;
Here, cout is an object of the class ostream and is associated with the standard C output stream stdout.
Single line comments in C++ begin with //. They are used to make the program easier to understand and are ignored by the compiler. The following comment in the above program is to clarify the purpose of the cout statement to the programmers.
// This prints Hello, World!
The termination of the main() function is signalled by the return(0); statement. After this, the value 0 is returned to the calling process. | [
{
"code": null,
"e": 1249,
"s": 1062,
"text": "C++ is a general purpose programming language that supports procedural, object-oriented and generic programming. C++ is a superset of C and all valid C programs are valid in C++ as well."
},
{
"code": null,
"e": 1371,
"s": 1249,
"tex... |
How to check if a vector exists in a list in R? | To check if a vector exists in a list, we can use %in%, and read the vector as list using list function. For example, if we have a list called LIST and a vector called V then we can check whether V exists in LIST using the command LIST %in% list(V).
Consider the below list −
Live Demo
List<-list(x1=LETTERS[1:26],x2=1:50,x3=rpois(50,5),x4=rnorm(50),x5=rpois(50,2),x6=rnorm(50,5,1),x7=letters[1:26],x8=runif(50,2,5),x9=rexp(50,3.24))
List
$x1
[1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S"
[20] "T" "U" "V" "W" "X" "Y" "Z"
$x2
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
[26] 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
$x3
[1] 4 5 5 5 7 4 7 3 2 9 11 4 5 3 10 5 4 4 8 3 1 7 3 6 5
[26] 2 5 3 1 3 1 4 4 9 7 5 6 2 6 6 5 11 5 5 5 7 3 6 3 3
$x4
[1] -0.09560671 0.41644849 1.52185081 1.25478269 -0.10120845 0.92858571
[7] -1.75769674 0.08586818 0.83654211 0.44516897 -0.42887927 -0.84480895
[13] -1.03752988 1.39581547 0.45523535 -1.23186748 0.28840459 0.09653478
[19] 0.27613359 0.25938658 1.35128069 0.21522862 -0.20182570 1.53706539
[25] 0.95243340 -0.77404491 -0.94918391 0.07563642 1.22060920 1.10518441
[31] 0.79664162 0.88648980 -0.22657289 0.00663885 1.66687832 -0.89556504
[37] -0.42351873 1.42195589 0.23710129 0.69048295 0.23026881 -0.31919684
[43] -0.71827618 -0.33974962 2.41356273 0.27326890 -1.35680540 -1.24595936
[49] 0.40430027 -0.53664646
$x5
[1] 0 2 2 6 0 2 1 3 2 4 2 1 5 3 2 0 2 2 2 1 1 5 1 1 3 5 2 3 6 5 3 2 1 0 2 0 0 0
[39] 5 3 2 3 0 2 2 1 0 3 1 3
$x6
[1] 6.134097 3.882553 4.462413 7.044883 4.229043 3.482663 3.943874 4.747332
[9] 3.167549 5.517625 4.169625 4.237116 4.316943 2.921994 3.610351 4.353406
[17] 5.295587 6.611960 2.964135 4.458357 4.936820 4.894477 3.117890 6.904135
[25] 5.057749 4.856171 5.242526 4.819986 4.443272 4.243939 5.945440 5.811889
[33] 6.494682 6.669360 5.126852 5.151575 4.993319 4.923821 6.486212 4.865304
[41] 5.446804 5.038247 4.934172 5.313578 3.632589 5.350681 4.257391 5.483359
[49] 5.142934 4.562802
$x7
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s"
[20] "t" "u" "v" "w" "x" "y" "z"
$x8
[1] 3.402047 4.446528 4.097843 3.979449 3.728044 4.324007 4.674882 4.360976
[9] 4.041636 3.853124 4.577922 3.594319 2.346518 3.195564 4.742620 3.547263
[17] 4.849656 3.062701 2.655747 3.456749 2.829216 4.407436 4.146494 4.866745
[25] 3.854683 2.255636 2.898519 3.255778 2.125811 3.399427 4.240987 4.598209
[33] 3.877593 4.557378 3.241529 3.862941 3.133698 3.670895 2.159567 3.583178
[41] 4.878772 4.984912 3.880342 4.502762 3.098179 4.472519 2.171510 2.299131
[49] 4.778286 4.869166
$x9
[1] 0.588381300 0.004375135 0.369618958 0.021075609 0.071974796 0.053904244
[7] 0.354839422 0.083627786 0.129399610 0.289138850 0.011676473 0.183556635
[13] 0.666047243 0.280067965 0.368349921 0.031696706 0.218040137 0.001709351
[19] 0.145331193 0.160332704 0.422142772 0.083291753 0.086747291 0.171843138
[25] 0.337125534 0.110894449 0.122360436 0.233614876 0.216746519 0.054293163
[31] 0.162507216 0.111237748 0.932469720 0.069711156 0.173526116 0.452977953
[37] 0.844435056 0.180822992 0.002493007 0.302044948 0.434001206 0.037101571
[43] 0.255578660 0.148020738 0.036570471 0.349629033 0.168946321 0.354580846
[49] 0.242166925 0.243347151
Consider the below vector −
y1=LETTERS[1:26]
Checking whether y1 exist in List −
List %in% list(y1)
[1] TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE | [
{
"code": null,
"e": 1312,
"s": 1062,
"text": "To check if a vector exists in a list, we can use %in%, and read the vector as list using list function. For example, if we have a list called LIST and a vector called V then we can check whether V exists in LIST using the command LIST %in% list(V)."
... |
DataTransfer object in HTML5 | The event listener methods for all the drag and drop events accept Event object that has a readonly attribute called dataTransfer. The event.dataTransfer returns DataTransfer object associated with the event as follows:
function EnterHandler(event) {
DataTransfer dt = event.dataTransfer;
...
}
You can try to run the following code to implement DataTransfer object:
<!DOCTYPE HTML>
<html>
<head>
<style>
#boxA, #boxB { float:left;padding:10px;margin:10px; -moz-user-select:none; }
#boxA { background-color: #6633FF; width:75px; height:75px; }
#boxB { background-color: #FF6699; width:150px; height:150px; }
</style>
<script>
function dragStart(ev) {
ev.dataTransfer.effectAllowed='move';
ev.dataTransfer.setData("Text", ev.target.getAttribute('id'));
ev.dataTransfer.setDragImage(ev.target,0,0);
return true;
}
</script>
</head>
<body>
<center>
<h2>Drag and drop HTML5 demo</h2>
<div>Try to drag the purple box around.</div>
<div id = "boxA" draggable = "true" ondragstart = "return dragStart(ev)">
<p>Drag Me</p>
</div>
<div id = "boxB">Dustbin</div>
</center>
</body>
</html> | [
{
"code": null,
"e": 1282,
"s": 1062,
"text": "The event listener methods for all the drag and drop events accept Event object that has a readonly attribute called dataTransfer. The event.dataTransfer returns DataTransfer object associated with the event as follows:"
},
{
"code": null,
"... |
How to Use SELECT In Order BY Specific Ids in SQL? - GeeksforGeeks | 28 Oct, 2021
The order by the statement is used in SQL to sort the result set in ascending or descending by mentioning it in the suffix as DESC (for descending) and for ASC(for ascending). In this article, we will be doing order by on a database with some specified values of the column only.
So let’s start by creating a Database first.
Step 1: Create a database
Query:
CREATE DATABASE GFG
Step 2: Use database
Query:
USE GFG
Step 3: Create a table
Query:
CREATE TABLE s_marks
(
studentid int PRIMARY KEY,
subjectid VARCHAR(10),
professorid int
)
Step 4: Insert some data in the table
Query:
INSERT INTO [dbo].[s_marks]
([studentid]
,[subjectid]
,[professorid])
VALUES(1, 'DSA', 6)
GO
INSERT INTO [dbo].[s_marks]
([studentid]
,[subjectid]
,[professorid])
VALUES(2, 'Compiler', 7)
GO
INSERT INTO [dbo].[s_marks]
([studentid]
,[subjectid]
,[professorid])
VALUES(3, 'ML', 8)
GO
INSERT INTO [dbo].[s_marks]
([studentid]
,[subjectid]
,[professorid])
VALUES(4, 'AI', 9)
GO
Step 5: Get the table data according to student id and order by using some ids.
Query:
SELECT studentid, subjectid FROM s_marks
WHERE studentid
IN
(1,4)
ORDER BY studentid DESC
Output:
So we can see that data is printed successfully with the order by as well as the respective ids.
Picked
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SQL | DROP, TRUNCATE
How to Select Data Between Two Dates and Times in SQL Server?
SQL vs NoSQL: Which one is better to use?
Advanced SQL Interview Questions
SQL | OFFSET-FETCH Clause
Insert multiple values into multiple tables using a single statement in SQL Server
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | Comments
SQL | CREATE
Adding multiple constraints in a single table | [
{
"code": null,
"e": 23903,
"s": 23875,
"text": "\n28 Oct, 2021"
},
{
"code": null,
"e": 24183,
"s": 23903,
"text": "The order by the statement is used in SQL to sort the result set in ascending or descending by mentioning it in the suffix as DESC (for descending) and for ASC(for... |
Outlier Detection — Theory, Visualizations, and Code | by Dimitris Effrosynidis | Towards Data Science | Outlier Detection is also known as anomaly detection, noise detection, deviation detection, or exception mining. There is no universally accepted definition. An early definition by (Grubbs, 1969) is: An outlying observation, or outlier, is one that appears to deviate markedly from other members of the sample in which it occurs. A more recent definition by (Barnett and Lewis, 1994) is:
An observation which appears to be inconsistent with the remainder of that set of data.
Straight from this excellent article, the most common causes of outliers are:
Human errors — Data entry errors
Instrument errors — Measurement errors
Experimental errors — data extraction or experiment planning/executing errors
Intentional — dummy outliers made to test detection methods
Data processing errors — data manipulation or data set unintended mutations
Sampling errors — extracting or mixing data from wrong or various sources
Natural — not an error, novelties in data
A list of applications that utilize outlier detection according to (Hodge, V.J. and Austin, J., 2014) is:
Fraud detection — detecting fraudulent applications for credit cards,state benefits or detecting fraudulent usage of credit cards or mobile phones.
Loan application processing — to detect fraudulent applications orpotentially problematic customers.
Intrusion detection — detecting unauthorized access in computernetworks.
Activity monitoring — detecting mobile phone fraud by monitoringphone activity or suspicious trades in the equity markets.
Network performance — monitoring the performance of computernetworks, for example, to detect network bottlenecks.
Fault diagnosis — monitoring processes to detect faults in motors,generators, pipelines, or space instruments on space shuttles forexample.
Structural defect detection — monitoring manufacturing lines todetect faulty production runs for example cracked beams.
Satellite image analysis — identifying novel features or misclassifiedfeatures.
Detecting novelties in images — for robot or surveillancesystems.
Motion segmentation — detecting image features moving independently of the background.
Time-series monitoring — monitoring safety-critical applicationssuch as drilling or high-speed milling.
Medical condition monitoring — such as heart-rate monitors.
Pharmaceutical research — identifying novel molecular structures.
Detecting novelty in the text — to detect the onset of news stories, fortopic detection and tracking or for traders to pinpoint equity, commodities, FX trading stories, outperforming or underperformingcommodities.
Detecting unexpected entries in databases — for data mining todetect errors, frauds, or valid but unexpected entries.
Detecting mislabelled data in a training data set.
There are 3 outlier detection approaches:
1. Determine the outliers with no prior knowledge of the data. This is analogous to unsupervised clustering.2. Model both normality and abnormality. This is analogous to supervised classification and need labeled data.3. Model only normality. This is called novelty detection and is analogous to semi-supervised recognition. It needs labeled data that belong to the normal class.
I will deal with the first approach. It is the most common case. Most datasets don’t have labeled data concerning outliers.
According to Ben-Gal I., (2005) outlier detection methods can be divided between univariate methods and multivariate methods. Another fundamental taxonomy of outlier detection methods is between parametric (statistical) methods, which assume a known underlying distribution of the observations, and non-parametric methods that are model-free like distance-based methods and clustering techniques.
I will use the Pokemon dataset and perform Outlier Detection on 2 columns [‘HP’, ‘Speed’] It is a fun dataset to play with, it has few observations and the computations will be very fast and a lot of people are familiar with it. The choice of only two columns has been taken for visualization purposes only (two dimensions). To observe the results in a scatter plot. The methods can be scaled in multiple dimensions.
The algorithms that will follow are:
Isolation Forest
Extended Isolation Forest
Local Outlier Factor
DBSCAN
One Class SVM
The ensemble of the above
The code for this article is on my GitHub. I will not include code in the article to keep it compact and shorter.
After reading the data, the first five rows are like this:
Isolation Forest, like any tree ensemble method, is built on the basis of decision trees. In these trees, partitions are created by first randomly selecting a feature and then selecting a random split value between the minimum and maximum value of the selected feature.
In order to create a branch in the tree, first, a random feature is selected. Afterward, a random split value (between min and max value) is chosen for that feature. If the given observation has a lower value of this feature then the one selected it follows the left branch, otherwise the right one. This process is continued until a single point is isolated or specified maximum depth is reached.
In principle, outliers are less frequent than regular observations and are different from them in terms of values (they lie further away from the regular observations in the feature space). That is why by using such random partitioning they should be identified closer to the root of the tree (shorter average path length, i.e., the number of edges an observation must pass in the tree going from the root to the terminal node), with fewer splits necessary.
More on Isolation Forest:
Isolation Forest — Paper
Outlier Detection with Isolation Forest
I will use IsolationForest from the sklearn library. When defining the algorithm there is an important parameter called contamination. It is the percentage of observations that the algorithm will expect as outliers. I set it equal to 2%. We fit the X (2 features HP and Speed) to the algorithm and use fit_predict to use it also on X. This produces plain outliers (-1 is outlier, 1 is inlier). We can also use the function decision_function to get the scores Isolation Forest gave to each sample.
After running the algorithm it found 785 inliers and 15 outliers.
Let’s plot the results.
Or we can plot the pure scores rather than just outlier/inlier.
Visually the 15 outliers seem legit and outside of the main blob of data points.
We can make a more advanced visualization which except the inliers and outliers displays the decision boundaries of Isolation Forest.
The darker the color, the more outlier is the region.
Finally, we can see the distribution of the scores.
The distribution is important and helps us to better identify the correct contamination value for our case. If we change the contamination value, the isoletionForest_scores will change, but the distribution will stay the same. The algorithm will adjust the cutoff for outliers in the distribution plot.
Isolation Forest has a drawback: Its decision boundaries are either vertical or horizontal. As the lines can only be parallel to the axes, there are regions that contain many branch cuts and only a few or single observations, which results in improper anomaly scores for some of the observations.
Extended Isolation Forest selects 1) a random slope for the branch cut and 2) a random intercept chosen from the range of available values from the training data. These terms are the linear regression line actually.
More on Extended Isolation Forest:
- Extended Isolation Forest — Paper- Extended Isolation Forest — Github- Outlier Detection with Extended Isolation Forest
Extended Isolation Forest is not implemented in sklearn, but it is available on Github
We have to multiply its scores with -1 to be in the same form as the scores of the other algorithms.
Extended Isolation Forest does not provide plain outliers and inliers (as -1 and 1). We simply created them by taking the lowest 2% of the scores as outliers. The scores of this algorithm are different from the basic Isolation Forest. All scores here are negative.
If you check the code you may notice that I used cmap=plt.cm.Blues in this plot instead of cmap=plt.cm.Blues_r (reverse) of the previous. We can see how much smoother extended isolation forest is in the transitions between the different outlier regions.
The algorithm found 16 outliers.
The LOF is a calculation that looks at the neighbors of a certain point to find out its density and compare this to the density of other points later on.
The LOF of a point tells the density of this point compared to the density of its neighbors. If the density of a point is much smaller than the densities of its neighbors (LOF ≫1), the point is far from dense areas and, hence, an outlier.
This is useful because not all methods will not identify a point that’s an outlier relative to a nearby cluster of points (a local outlier) if that whole region is not an outlying region in the global space of data points.
The LOF for a point P will have a:
High value if → P is far from its neighbors and its neighbors have high densities (are close to their neighbors) (LOF = (high distance sum) x (high density sum) = High value)
Less high value if -> P is far from its neighbors, but its neighbors have low densities (LOF = (high sum) x (low sum) = middle value)
Less high value if -> P is close to its neighbors and its neighbors have low densities (LOF = (low sum) x (low sum) = low value )
More on Local Outlier Factor:
LoOP: Local Outlier Probabilities — Paper
Local Outlier Factor for Anomaly Detection
After running the code from the sklearn library, it determines 21 local outliers.
We can create another interesting plot, where the bigger the local outlier the bigger the circle around it.
This algorithm is much different than the previous ones. It also finds outliers, but in a different manner. It finds local outliers. Did you notice that there are outliers inside the main mass of the plot?
A classic clustering algorithm that works as follows:
Randomly select a point not already assigned to a cluster or designated as an outlier. Determine if it’s a core point by seeing if there are at least min_samples points around it within epsilon distance.
Create a cluster of this core point and all points within epsilon distance of it (all directly reachable points).
Find all points that are within epsilon distance of each point in the cluster and add them to the cluster. Find all points that are within epsilon distance of all newly added points and add these to the cluster. Rinse and repeat. (i.e. perform “neighborhood jumps” to find all density-reachable points and add them to the cluster).
For our sample, it found 13 outliers after tuning the epsilon parameter.
The algorithm does not provide scores for outlier strength.
A one-class classifier is fit on a training dataset that only has examples from the normal class, but it can also be used for all data. Once prepared, the model is used to classify new examples as either normal or not-normal.
The main difference from a standard SVM is that it is fit in an unsupervised manner and does not provide the normal hyperparameters for tuning the margin like C. Instead, it provides a hyperparameter “nu” that controls the sensitivity of the support vectors and should be tuned to the approximate ratio of outliers in the data.
More on One-Class SVM
Outlier Detection with One-Class SVMs
One-Class Classification Algorithms for Imbalanced Datasets
After running the algorithm I get the following scatter plot
It doesn’t seem to work in this data. I couldn't find a better nu. For other nu values, the outliers were more than the inliers. If someone has any idea please share and I will update!
Finally, let’s combine the 5 algorithms to make a robust one. I will simply add the outlier columns which are either -1 for outlier and 1 for inlier.
I will not use One-Class SVM.
After adding together the results we get:
data['outliers_sum'].value_counts()value count 4 770 2 15 -4 7 -2 7 0 1
Observations with outliers_sum=4, mean than all 4 algorithms agreed that it is an inlier, while for complete outlier agreement the sum is -4.
Let’s first see for which 7 pokemon all algorithms agree for outliers. We can also keep as inliers the observations where sum=4 and the rest as outliers. It is up to us.
data.loc[data[‘outliers_sum’]==-4][‘Name’]121 Chansey155 Snorlax217 Wobbuffet261 Blissey313 Slaking431 DeoxysSpeed Forme495 Munchlax
These are our outliers on HP and Speed combined!
Thanks for reading! | [
{
"code": null,
"e": 435,
"s": 47,
"text": "Outlier Detection is also known as anomaly detection, noise detection, deviation detection, or exception mining. There is no universally accepted definition. An early definition by (Grubbs, 1969) is: An outlying observation, or outlier, is one that appears... |
BabylonJS - Import Mesh | In this section, we will learn how to import mesh using Babylon −
Blender is an open source software. You can download same from their official site www.blender.org.
Download the software as per your operatingsystem. Install the software and follow the steps given below to create the mesh in blender.
Consider the steps shown below to work with Blender −
Step 1 − First we need to install the plugin for convertingblender to babylonjs. We can get the plugin from Blender2Babylon-X.X.zip. In Expoters/Blender copy the io_export_babylon.py or _init_.py file and paste it in Blenders Addons directory as shown below.
Follow these steps to install the exporter into Blender −
Step 1 − Open the Blender software and from the file, choose userpreferences. Now, go to the Addons Tab.
At the bottom, you will see the Install from File icon.
Step 2 − Choose the file from the Babylon directory, i.e., the zip downloaded in step 1. Take the file io_export_babylon.py or __init_.py and click on Install from file option on right side.
Step 3 − After Installation, you will get Import-Export: Babylon.js option. Click the checkbox and the Save User Settings.
Now you can export any blender file to .babylon.
Step 4 − Choose the blender file that you want to be export to babylonjs. Incase you don’thave any blender files you can get the same from www.blender.org
Step 5 − Open the blender file.
If you want, you can add the changes if any and export as shown below.
From the blender, export the file and store it in scenes/ folder locally as buggy2.1.babylon. It is a json file which has all the positions and necessary details to create the mesh. In the code given below, we have used the file exported from blender.
<!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);
scene.clearColor = new BABYLON.Color3(1, 1, 1);
//Adding a light
var light = new BABYLON.HemisphericLight("Hemi", new BABYLON.Vector3(0, 1, 0), scene);
//Adding an Arc Rotate Camera
var camera = new BABYLON.ArcRotateCamera("Camera", -1.85, 1.2, 200, BABYLON.Vector3.Zero(), scene);
camera.attachControl(canvas, true);
// The first parameter can be used to specify which mesh to import. Here we import all meshes
BABYLON.SceneLoader.ImportMesh("", "scenes/", "buggy2.1.babylon", scene, function (newMeshes) {
var buggy2 = newMeshes[0];
camera.target = buggy2;
var decalMaterial = new BABYLON.StandardMaterial("decalMat", scene);
var ground = BABYLON.MeshBuilder.CreateGround("ground", {width: 300, height:15}, scene);
ground.material = decalMaterial;
});
return scene;
};
var scene = createScene();
engine.runRenderLoop(function() {
scene.render();
});
</script>
</body>
</html>
The above line of code will generate the following output −
To import the mesh created by you, execute the following line of code −
BABYLON.SceneLoader.ImportMesh("", "scenes/", "buggy2.1.babylon", scene, function (newMeshes) {})
Import mesh takes the .babylon files stored from the folder and allows access to the properties of mesh thedetails of which are available in newMeshes.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2249,
"s": 2183,
"text": "In this section, we will learn how to import mesh using Babylon −"
},
{
"code": null,
"e": 2349,
"s": 2249,
"text": "Blender is an open source software. You can download same from their official site www.blender.org."
},
{
"c... |
DynamoDB - Delete Table | In this chapter, we will discuss regarding how we can delete a table and also the different ways of deleting a table.
Table deletion is a simple operation requiring little more than the table name. Utilize the GUI console, Java, or any other option to perform this task.
Perform a delete operation by first accessing the console at −
https://console.aws.amazon.com/dynamodb.
Choose Tables from the navigation pane, and choose the table desired for deletion from the table list as shown in the following screeenshot.
Finally, select Delete Table. After choosing Delete Table, a confirmation appears. Your table is then deleted.
Use the delete method to remove a table. An example is given below to explain the concept better.
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import com.amazonaws.services.dynamodbv2.document.Table;
public class ProductsDeleteTable {
public static void main(String[] args) throws Exception {
AmazonDynamoDBClient client = new AmazonDynamoDBClient()
.withEndpoint("http://localhost:8000");
DynamoDB dynamoDB = new DynamoDB(client);
Table table = dynamoDB.getTable("Products");
try {
System.out.println("Performing table delete, wait...");
table.delete();
table.waitForDelete();
System.out.print("Table successfully deleted.");
} catch (Exception e) {
System.err.println("Cannot perform table delete: ");
System.err.println(e.getMessage());
}
}
}
16 Lectures
1.5 hours
Harshit Srivastava
49 Lectures
3.5 hours
Niyazi Erdogan
48 Lectures
3 hours
Niyazi Erdogan
13 Lectures
1 hours
Harshit Srivastava
45 Lectures
4 hours
Pranjal Srivastava, Harshit Srivastava
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2509,
"s": 2391,
"text": "In this chapter, we will discuss regarding how we can delete a table and also the different ways of deleting a table."
},
{
"code": null,
"e": 2662,
"s": 2509,
"text": "Table deletion is a simple operation requiring little more than ... |
Position of the K-th set bit in a number in C++ | In this problem, we are given two integers N and K. Our task is to find the index of Kth set a bit of the number N, counted from right.
Set bits are checked from the binary representation of the number. The indexing in binary representation starts from index 0 from the right direction and propagates towards left.
Example − in the binary number ‘011101’, at index 0 from right we have 1, at index 1 from right we have 0, and so on.
Now, let’s take an example to understand the problem
Input − N = 6, K = 2
Output − 2
Explanation − The binary representation of 6 is 0110. The 2nd set bit from the right will be at index 2.
To solve this problem, we will have to check if the current bit is set, if it is then we will decrease the value of K. After every check, we will shift the number bt 1, this will give the next bit, also we will maintain the number of shifts done. Once the value of K becomes 0, we will print the count of shifts done.
Program to show the implementation of our logic
Live Demo
#include <iostream>
using namespace std;
int FindIndexKthBit(int N, int K) {
int index=0;
while (N) {
if (N & 1)
K--;
if (!K)
return index;
index++;
N = N >> 1;
}
return -1;
}
int main() {
int N = 12, K = 2;
cout<<"The "<<K<<"th set bit of the number "<<N<<" is at index : \t";
int index = FindIndexKthBit(N, K);
if (index!=-1)
cout<<index;
else
cout<<"\nsorry no index found";
return 0;
}
The 2th set bit of the number 12 is at index : 3 | [
{
"code": null,
"e": 1198,
"s": 1062,
"text": "In this problem, we are given two integers N and K. Our task is to find the index of Kth set a bit of the number N, counted from right."
},
{
"code": null,
"e": 1377,
"s": 1198,
"text": "Set bits are checked from the binary represent... |
MongoDB query to fetch array values | Use find() along with $elemMatch to fetch array values. Let us first create a collection with documents −
> db.fetchingArrayValuesDemo.insertOne(
... {
... "StudentName": "David",
... "StudentDetails": [
... {
... "FatherName": "Bob",
... "CountryName": "US",
...
... "Favourite": [
... {
... "Teacher": "DAVID",
... "Subject": [
... "MySQL",
... "MongoDB",
... "Java"
... ],
... "Marks": [
... 50,
... 60,
... 65
... ]
... }
... ]
...
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e06fc3425ddae1f53b621fa")
}
> db.fetchingArrayValuesDemo.insertOne(
... {
... "StudentName": "Robert",
... "StudentDetails": [
... {
... "FatherName": "Sam",
... "CountryName": "AUS",
...
... "Favourite": [
... {
... "Teacher": "MIKE",
... "Subject": [
... "Python",
... "C",
... "C++"
... ],
... "Marks": [
... 76,
... 89,
... 91
... ]
... }
... ]
...
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e06fc6825ddae1f53b621fb")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.fetchingArrayValuesDemo.find();
This will produce the following output −
{ "_id" : ObjectId("5e06fc3425ddae1f53b621fa"), "StudentName" : "David", "StudentDetails" : [ { "FatherName" : "Bob", "CountryName" : "US", "Favourite" : [ { "Teacher" : "DAVID", "Subject" : [ "MySQL", "MongoDB", "Java" ], "Marks" : [ 50, 60, 65 ] } ] } ] }
{ "_id" : ObjectId("5e06fc6825ddae1f53b621fb"), "StudentName" : "Robert", "StudentDetails" : [ { "FatherName" : "Sam", "CountryName" : "AUS", "Favourite" : [ { "Teacher" : "MIKE", "Subject" : [ "Python", "C", "C++" ], "Marks" : [ 76, 89, 91 ] } ] } ] }
Here is the query to fetch array values −
> db.fetchingArrayValuesDemo.find({
... StudentDetails:{
... $elemMatch: {
... Favourite: {
... $elemMatch: {
... Teacher: "DAVID"
... }
... }
... }
... }
... });
This will produce the following output −
{ "_id" : ObjectId("5e06fc3425ddae1f53b621fa"), "StudentName" : "David", "StudentDetails" : [ { "FatherName" : "Bob", "CountryName" : "US", "Favourite" : [ { "Teacher" : "DAVID", "Subject" : [ "MySQL", "MongoDB", "Java" ], "Marks" : [ 50, 60, 65 ] } ] } ] } | [
{
"code": null,
"e": 1168,
"s": 1062,
"text": "Use find() along with $elemMatch to fetch array values. Let us first create a collection with documents −"
},
{
"code": null,
"e": 2643,
"s": 1168,
"text": "> db.fetchingArrayValuesDemo.insertOne(\n... {\n... \"StudentName\": \"Da... |
How are arguments passed by value or by reference in Python? | Python uses a mechanism, which is known as "Call-by-Object", sometimes also called "Call by Object Reference" or "Call by Sharing"
If you pass immutable arguments like integers, strings or tuples to a function, the passing acts like Call-by-value. It's different, if we pass mutable arguments.
All parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function.
student={'Archana':28,'krishna':25,'Ramesh':32,'vineeth':25}
def test(student):
new={'alok':30,'Nevadan':28}
student.update(new)
print("Inside the function",student)
return
test(student)
print("outside the function:",student)
Inside the function {'Archana': 28, 'krishna': 25, 'Ramesh': 32, 'vineeth': 25, 'alok': 30, 'Nevadan': 28}
outside the function: {'Archana': 28, 'krishna': 25, 'Ramesh': 32, 'vineeth': 25, 'alok': 30, 'Nevadan': 28} | [
{
"code": null,
"e": 1193,
"s": 1062,
"text": "Python uses a mechanism, which is known as \"Call-by-Object\", sometimes also called \"Call by Object Reference\" or \"Call by Sharing\""
},
{
"code": null,
"e": 1356,
"s": 1193,
"text": "If you pass immutable arguments like integers... |
cPanel - Logging into cPanel Dashboard | In this chapter, we will learn to login into the cPanel Dashboard. For logging into the dashboard, you will need your login credentials. This information is sent to you, when you have signed up for cPanel hosting or you may have created during purchase of hosting.
cPanel Dashboard is accessible by two ports – 2082 for unsecured connections and 2083 for secured connection, many hosting providers support unsecured connections, but it is always recommended that you should use a secured connection only.
There are many ways to find the login screen of a cPanel. Recommended is that you may use the IP address of your cPanel, you may find the cPanel using IP address by typing the following in address bar −
https://<your_IP_address>:2083
https://<your_IP_address>/cpanel
If you have already updated your Nameservers for your domain, then you may use your domain for directly accessing cPanel by your domain. You may find cPanel login screen using your domain by typing the following into the address bar −
https://<your_domain>:2083
https://<your_domain>/cpanel
Once you are redirected to your login screen, you will find the login screen like shown below.
You can enter the Username and Password and press the Log in button to login into the cPanel Dashboard.
10 Lectures
47 mins
Laurence Svekis
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3322,
"s": 3057,
"text": "In this chapter, we will learn to login into the cPanel Dashboard. For logging into the dashboard, you will need your login credentials. This information is sent to you, when you have signed up for cPanel hosting or you may have created during purchase ... |
Angular PrimeNG Avatar Component - GeeksforGeeks | 24 Aug, 2021
Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the Avatar component in Angular PrimeNG. Let’s learn about the properties, styling & their syntaxes that will be used in the code.
Avatar component: It is used to represent a person as an icon, image or label.
Properties of Avatar:
label: It is used to define the text to display. It is of string data type, the default value is null.
icon: It is used to define the icon to display. It is of string data type, the default value is null.
image: It is used to define the image to display. It is of string data type, the default value is null.
size: It is used to set the size of the element, valid options are “large” and “xlarge”. It is of string data type, the default value is null.
shape: It is used to set the shape of the element, valid options are “square” and “circle”. It is of string data type, the default value is square.
style: It is used to set the inline style of the component. It is of object data type, the default value is null.
styleClass: It is used to define the style class of the component. It is of string data type, the default value is null.
Properties for AvatarGroup:
style: Here, in this case also, is used to set the inline style of the component. It is of object data type, the default value is null.
styleClass: Here, in this case also, is used to define the style class of the component. It is of string data type, the default value is null.
Styling of Avatar:
p-avatar: It is the container element.
p-avatar-image: It is the container element in image mode.
p-avatar-circle: It is the container element with a circle shape.
p-avatar-text: It is the text element of the avatar.
p-avatar-icon: It is the style icon of the avatar.
p-avatar-lg: It is the container element with large size.
p-avatar-xl: It is the container element with an xlarge size.
Styling of AvatarGroup:
p-avatar-group: It is used for the container of an element.
Creating Angular application & module installation:
Step 1: Create an Angular application using the following command.ng new appname
Step 1: Create an Angular application using the following command.
ng new appname
Step 2: After creating your project folder i.e. appname, move to it using the following command.cd appname
Step 2: After creating your project folder i.e. appname, move to it using the following command.
cd appname
Step 3: Install PrimeNG in your given directory.npm install primeng --save
npm install primeicons --save
Step 3: Install PrimeNG in your given directory.
npm install primeng --save
npm install primeicons --save
Project Structure: It will look like the following:
Example 1: This is the basic example that shows how to use the avatar component.
app.component.html
<h2>GeeksforGeeks</h2><h5>PrimeNg Avatar Component</h5><p-avatar label="A" styleClass="p-mr-1"></p-avatar><p-avatar label="B" styleClass="p-mr-1" size="large" [style]="{'background-color':'#3714e3', 'color': '#ffffff'}"></p-avatar> <p-avatar label="C" styleClass="p-mr-1" size="xlarge" [style]="{'background-color':'#1eff00', 'color': '#ff8400'}"></p-avatar>
app.module.ts
import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { BrowserAnimationsModule } from "@angular/platform-browser/animations";import { AppComponent } from "./app.component";import { AvatarModule } from "primeng/avatar"; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, AvatarModule], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}
Output:
Example 2: In this example, we will be making circle-shaped avatars with icons.
app.component.html
<div class="card"> <h5>Circle shaped avatar with icon</h5> <div> <p-avatar icon="pi pi-user" size="small" [style]="{'background-color': 'red', 'color': '#ffffff'}" shape="circle"> </p-avatar> </div> <div> <p-avatar icon="pi pi-user" [style]="{'background-color': 'black', 'color': '#ffffff'}" shape="circle"> </p-avatar> </div> <div> <p-avatar icon="pi pi-user" size="large" [style]="{'background-color':'green', 'color': '#ffffff'}" shape="circle"> </p-avatar> </div> <div> <p-avatar icon="pi pi-user" size="xlarge" shape="circle"></p-avatar> </div></div>
app.module.ts
import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { BrowserAnimationsModule } from "@angular/platform-browser/animations";import { AppComponent } from "./app.component";import { AvatarModule } from "primeng/avatar"; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, AvatarModule], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}
Output:
Reference: https://primefaces.org/primeng/showcase/#/avatar
Angular-PrimeNG
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Angular Libraries For Web Developers
Angular 10 (blur) Event
Angular PrimeNG Dropdown Component
How to make a Bootstrap Modal Popup in Angular 9/8 ?
How to create module with Routing in Angular 9 ?
Roadmap to Become a Web Developer in 2022
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
Installation of Node.js on Linux
Convert a string to an integer in JavaScript | [
{
"code": null,
"e": 25109,
"s": 25081,
"text": "\n24 Aug, 2021"
},
{
"code": null,
"e": 25481,
"s": 25109,
"text": "Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make resp... |
LeafletJS - Markers | To mark a single location on the map, leaflet provides markers. These markers use a standard symbol and these symbols can be customized. In this chapter, we will see how to add markers and how to customize, animate, and remove them.
To add a marker to a map using Leaflet JavaScript library, follow the steps given below −
Step 1 − Create a Map object by passing a <div> element (String or object) and map options (optional).
Step 2 − Create a Layer object by passing the URL of the desired tile.
Step 3 − Add the layer object to the map using the addLayer() method of the Map class.
Step 4 − Instantiate the Marker class by passing a latlng object representing the position to be marked, as shown below.
// Creating a marker
var marker = new L.Marker([17.385044, 78.486671]);
Step 5 − Add the marker object created in the previous steps to the map using the addTo() method of the Marker class.
// Adding marker to the map
marker.addTo(map);
The following code sets the marker on the city named Hyderabad (India).
<!DOCTYPE html>
<html>
<head>
<title>Leaflet sample</title>
<link rel = "stylesheet" href = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css"/>
<script src = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
</head>
<body>
<div id = "map" style = "width:900px; height:580px"></div>
<script>
// Creating map options
var mapOptions = {
center: [17.385044, 78.486671],
zoom: 10
}
// Creating a map object
var map = new L.map('map', mapOptions);
// Creating a Layer object
var layer = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');
// Adding layer to the map
map.addLayer(layer);
// Creating a marker
var marker = L.marker([17.385044, 78.486671]);
// Adding marker to the map
marker.addTo(map);
</script>
</body>
</html>
It generates the following output −
To bind a simple popup displaying a message to a marker, follow the steps given below −
Step 1 − Create a Map object by passing a <div> element (String or object) and map options (optional).
Step 2 − Create a Layer object by passing the URL of the desired tile.
Step 3 − Add the layer object to the map using the addLayer() method of the Map class.
Step 4 − Instantiate the Marker class by passing a latlng object representing the position to be marked.
Step 5 − Attach popup to the marker using bindPopup() as shown below.
// Adding pop-up to the marker
marker.bindPopup('Hi Welcome to Tutorialspoint').openPopup();
Step 6 − Finally, add the Marker object created in the previous steps to the map using the addTo() method of the Marker class.
The following code sets the marker on the city Hyderabad (India) and adds a pop-up to it.
<!DOCTYPE html>
<html>
<head>
<title>Binding pop-Ups to marker</title>
<link rel = "stylesheet" href = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css"/>
<script src = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
</head>
<body>
<div id = "map" style = "width:900px; height:580px"></div>
<script>
// Creating map options
var mapOptions = {
center: [17.385044, 78.486671],
zoom: 15
}
var map = new L.map('map', mapOptions); // Creating a map object
// Creating a Layer object
var layer = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');
map.addLayer(layer); // Adding layer to the map
var marker = L.marker([17.438139, 78.395830]); // Creating a Marker
// Adding popup to the marker
marker.bindPopup('This is Tutorialspoint').openPopup();
marker.addTo(map); // Adding marker to the map
</script>
</body>
</html>
It generates the following output
While creating a marker, you can also pass a marker options variable in addition to the latlang object. Using this variable, you can set values to various options of the marker such as icon, dragable, keyboard, title, alt, zInsexOffset, opacity, riseOnHover, riseOffset, pane, dragable, etc.
To create a map using map options, you need to follow the steps given below −
Step 1 − Create a Map object by passing a <div> element (String or object) and map options (optional).
Step 2 − Create a Layer object by passing the URL of the desired tile.
Step 3 − Add the layer object to the map using the addLayer() method of the Map class.
Step 4 − Create a variable for markerOptions and specify values to the required options.
Create a markerOptions object (it is created just like a literal) and set values for the options iconUrl and iconSize.
// Options for the marker
var markerOptions = {
title: "MyLocation",
clickable: true,
draggable: true
}
Step 5 − Instantiate the Marker class by passing a latlng object representing the position to be marked and the options object, created in the previous step.
// Creating a marker
var marker = L.marker([17.385044, 78.486671], markerOptions);
Step 6 − Finally, add the Marker object created in the previous steps to the map using the addTo() method of the Marker class.
The following code sets the marker on the city Hyderabad (India). This marker is clickable, dragable with the title MyLocation.
<html>
<head>
<title>Marker Options Example</title>
<link rel = "stylesheet" href = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css"/>
<script src = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
</head>
<body>
<div id = "map" style = "width:900px; height:580px"></div>
<script>
// Creating map options
var mapOptions = {
center: [17.385044, 78.486671],
zoom: 10
}
// Creating a map object
var map = new L.map('map', mapOptions);
// Creating a Layer object
var layer = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');
// Adding layer to the map
map.addLayer(layer);
// Creating a Marker
var markerOptions = {
title: "MyLocation",
clickable: true,
draggable: true
}
// Creating a marker
var marker = L.marker([17.385044, 78.486671], markerOptions);
// Adding marker to the map
marker.addTo(map);
</script>
</body>
</html>
It generates the following output
Instead of the default icon provided by the Leaflet library, you can also add your own icon. You can use the following steps to add a custom icon to the map instead of the default one.
Step 1 − Create a Map object by passing a <div> element (String or object) and map options (optional).
Step 2 − Create a Layer object by passing the URL of the desired tile.
Step 3 − Add the layer object to the map using the addLayer() method of the Map class.
Step 4 − Create a variable for markerOptions and specify values to the required options −
iconUrl − As a value to this option, you need to pass a String object specifying the path of the image which you want to use as an icon.
iconUrl − As a value to this option, you need to pass a String object specifying the path of the image which you want to use as an icon.
iconSize − Using this option, you can specify the size of the icon.
iconSize − Using this option, you can specify the size of the icon.
Note − In addition to these, you can also set values to other options such as iconSize, shadowSize, iconAnchor, shadowAnchor, and popupAnchor.
Create a custom icon using L.icon() by passing the above options variable as shown below.
// Icon options
var iconOptions = {
iconUrl: 'logo.png',
iconSize: [50, 50]
}
// Creating a custom icon
var customIcon = L.icon(iconOptions);
Step 5 − Create a variable for markerOptions and specify values to the required options. In addition to these, specify the icon by passing the icon variable created in the previous step as a value.
// Options for the marker
var markerOptions = {
title: "MyLocation",
clickable: true,
draggable: true,
icon: customIcon
}
Step 6 − Instantiate the Marker class by passing a latlng object representing the position to be marked and the options object created in the previous step.
// Creating a marker
var marker = L.marker([17.438139, 78.395830], markerOptions);
Step 7 − Finally, add the Marker object created in the previous steps to the map using the addTo() method of the Marker class.
The following code sets the marker on the location of Tutorialspoint. Here we are using the logo of Tutorialspoint instead of the default marker.
<!DOCTYPE html>
<html>
<head>
<title>Marker Custom Icons Example</title>
<link rel = "stylesheet" href = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css"/>
<script src = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
</head>
<body>
<div id = "map" style = "width:900px; height:580px"></div>
<script>
// Creating map options
var mapOptions = {
center: [17.438139, 78.395830],
zoom: 10
}
// Creating a map object
var map = new L.map('map', mapOptions);
// Creating a Layer object
var layer = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');
// Adding layer to the map
map.addLayer(layer);
// Icon options
var iconOptions = {
iconUrl: 'logo.png',
iconSize: [50, 50]
}
// Creating a custom icon
var customIcon = L.icon(iconOptions);
// Creating Marker Options
var markerOptions = {
title: "MyLocation",
clickable: true,
draggable: true,
icon: customIcon
}
// Creating a Marker
var marker = L.marker([17.438139, 78.395830], markerOptions);
// Adding popup to the marker
marker.bindPopup('Hi welcome to Tutorialspoint').openPopup();
// Adding marker to the map
marker.addTo(map);
</script>
</body>
</html>
It generates the following output
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2031,
"s": 1798,
"text": "To mark a single location on the map, leaflet provides markers. These markers use a standard symbol and these symbols can be customized. In this chapter, we will see how to add markers and how to customize, animate, and remove them."
},
{
"code"... |
MVVM â WPF Data Bindings | In this chapter, we will be learn how data binding supports the MVVM pattern. Data binding is the key feature that differentiates MVVM from other UI separation patterns like MVC and MVP.
For data binding you need to have a view or set of UI elements constructed, and then you need some other object that the bindings are going to point to.
For data binding you need to have a view or set of UI elements constructed, and then you need some other object that the bindings are going to point to.
The UI elements in a view are bound to the properties which are exposed by the ViewModel.
The UI elements in a view are bound to the properties which are exposed by the ViewModel.
The order that the View and ViewModel are constructed on depends on the situation, as we have covered the View first.
The order that the View and ViewModel are constructed on depends on the situation, as we have covered the View first.
A View and ViewModel get constructed and the DataContext of the View gets set to the ViewModel.
A View and ViewModel get constructed and the DataContext of the View gets set to the ViewModel.
Bindings can either be OneWay or TwoWay data bindings to flow data back and forth between the View and ViewModel.
Bindings can either be OneWay or TwoWay data bindings to flow data back and forth between the View and ViewModel.
Let's take a look at data bindings in the same example. Below is the XAML code of StudentView.
<UserControl x:Class = "MVVMDemo.Views.StudentView"
xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d = "http://schemas.microsoft.com/expression/blend/2008"
xmlns:local = "clr-namespace:MVVMDemo.Views"
xmlns:viewModel = "clr-namespace:MVVMDemo.ViewModel"
xmlns:vml = "clr-namespace:MVVMDemo.VML"
vml:ViewModelLocator.AutoHookedUpViewModel = "True"
mc:Ignorable = "d" d:DesignHeight = "300" d:DesignWidth = "300">
<!--<UserControl.DataContext>
<viewModel:StudentViewModel/>
</UserControl.DataContext>-->
<Grid>
<StackPanel HorizontalAlignment = "Left">
<ItemsControl ItemsSource = "{Binding Path = Students}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation = "Horizontal">
<TextBox Text = "{Binding Path = FirstName, Mode = TwoWay}"
Width = "100" Margin = "3 5 3 5"/>
<TextBox Text = "{Binding Path = LastName, Mode = TwoWay}"
Width = "100" Margin = "0 5 3 5"/>
<TextBlock Text = "{Binding Path = FullName, Mode = OneWay}"
Margin = "0 5 3 5"/>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</Grid>
</UserControl>
If you look at the above XAML code you will see that ItemsControl is bound to the Students collection exposed by ViewModel.
If you look at the above XAML code you will see that ItemsControl is bound to the Students collection exposed by ViewModel.
You can also see that the property of Student model has their own individual bindings as well, and these are bound to the Textboxes and TextBlock.
You can also see that the property of Student model has their own individual bindings as well, and these are bound to the Textboxes and TextBlock.
The ItemSource of ItemsControl is able to bind to the Students property, because the overall DataContext for the View is set to ViewModel.
The ItemSource of ItemsControl is able to bind to the Students property, because the overall DataContext for the View is set to ViewModel.
The individual bindings of properties here are also DataContext bindings, but they're not binding against the ViewModel itself, because of the way an ItemSource works.
The individual bindings of properties here are also DataContext bindings, but they're not binding against the ViewModel itself, because of the way an ItemSource works.
When an item source binds to its collection it renders out a container for each item at rendering, and it sets the DataContext of that container to the item. So the overall DataContext for each textbox and textblock within a row is going to be an individual Student in the collection. And you can also see that these bindings for TextBoxes are TwoWay data binding and for TextBlock it is OneWay data binding as you can’t edit TextBlock.
When an item source binds to its collection it renders out a container for each item at rendering, and it sets the DataContext of that container to the item. So the overall DataContext for each textbox and textblock within a row is going to be an individual Student in the collection. And you can also see that these bindings for TextBoxes are TwoWay data binding and for TextBlock it is OneWay data binding as you can’t edit TextBlock.
When you run this application again, you will see the following output.
Let us now change the text in the second textbox of first row from Allain to Upston and press tab to lose focus. You will see that the TextBlock text is also updated.
This is because the bindings of the TextBoxes are set to TwoWay and it updates the Model as well, and from the model again the TextBlock is updated.
38 Lectures
2 hours
Skillbakerystudios
22 Lectures
1 hours
CLEMENT OCHIENG
14 Lectures
2 hours
DevTechie
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2129,
"s": 1942,
"text": "In this chapter, we will be learn how data binding supports the MVVM pattern. Data binding is the key feature that differentiates MVVM from other UI separation patterns like MVC and MVP."
},
{
"code": null,
"e": 2282,
"s": 2129,
"tex... |
JavaFX - Event Handling | In JavaFX, we can develop GUI applications, web applications and graphical applications. In such applications, whenever a user interacts with the application (nodes), an event is said to have been occurred.
For example, clicking on a button, moving the mouse, entering a character through keyboard, selecting an item from list, scrolling the page are the activities that causes an event to happen.
The events can be broadly classified into the following two categories −
Foreground Events − Those events which require the direct interaction of a user. They are generated as consequences of a person interacting with the graphical components in a Graphical User Interface. For example, clicking on a button, moving the mouse, entering a character through keyboard, selecting an item from list, scrolling the page, etc.
Foreground Events − Those events which require the direct interaction of a user. They are generated as consequences of a person interacting with the graphical components in a Graphical User Interface. For example, clicking on a button, moving the mouse, entering a character through keyboard, selecting an item from list, scrolling the page, etc.
Background Events − Those events that don't require the interaction of end-user are known as background events. The operating system interruptions, hardware or software failure, timer expiry, operation completion are the example of background events.
Background Events − Those events that don't require the interaction of end-user are known as background events. The operating system interruptions, hardware or software failure, timer expiry, operation completion are the example of background events.
JavaFX provides support to handle a wide varieties of events. The class named Event of the package javafx.event is the base class for an event.
An instance of any of its subclass is an event. JavaFX provides a wide variety of events. Some of them are are listed below.
Mouse Event − This is an input event that occurs when a mouse is clicked. It is represented by the class named MouseEvent. It includes actions like mouse clicked, mouse pressed, mouse released, mouse moved, mouse entered target, mouse exited target, etc.
Mouse Event − This is an input event that occurs when a mouse is clicked. It is represented by the class named MouseEvent. It includes actions like mouse clicked, mouse pressed, mouse released, mouse moved, mouse entered target, mouse exited target, etc.
Key Event − This is an input event that indicates the key stroke occurred on a node. It is represented by the class named KeyEvent. This event includes actions like key pressed, key released and key typed.
Key Event − This is an input event that indicates the key stroke occurred on a node. It is represented by the class named KeyEvent. This event includes actions like key pressed, key released and key typed.
Drag Event − This is an input event which occurs when the mouse is dragged. It is represented by the class named DragEvent. It includes actions like drag entered, drag dropped, drag entered target, drag exited target, drag over, etc.
Drag Event − This is an input event which occurs when the mouse is dragged. It is represented by the class named DragEvent. It includes actions like drag entered, drag dropped, drag entered target, drag exited target, drag over, etc.
Window Event − This is an event related to window showing/hiding actions. It is represented by the class named WindowEvent. It includes actions like window hiding, window shown, window hidden, window showing, etc.
Window Event − This is an event related to window showing/hiding actions. It is represented by the class named WindowEvent. It includes actions like window hiding, window shown, window hidden, window showing, etc.
Event Handling is the mechanism that controls the event and decides what should happen, if an event occurs. This mechanism has the code which is known as an event handler that is executed when an event occurs.
JavaFX provides handlers and filters to handle events. In JavaFX every event has −
Target − The node on which an event occurred. A target can be a window, scene, and a node.
Target − The node on which an event occurred. A target can be a window, scene, and a node.
Source − The source from which the event is generated will be the source of the event. In the above scenario, mouse is the source of the event.
Source − The source from which the event is generated will be the source of the event. In the above scenario, mouse is the source of the event.
Type − Type of the occurred event; in case of mouse event – mouse pressed, mouse released are the type of events.
Type − Type of the occurred event; in case of mouse event – mouse pressed, mouse released are the type of events.
Assume that we have an application which has a Circle, Stop and Play Buttons inserted using a group object as follows −
If you click on the play button, the source will be the mouse, the target node will be the play button and the type of the event generated is the mouse click.
Whenever an event is generated, JavaFX undergoes the following phases.
Whenever an event is generated, the default/initial route of the event is determined by construction of an Event Dispatch chain. It is the path from the stage to the source Node.
Following is the event dispatch chain for the event generated, when we click on the play button in the above scenario.
After the construction of the event dispatch chain, the root node of the application dispatches the event. This event travels to all nodes in the dispatch chain (from top to bottom). If any of these nodes has a filter registered for the generated event, it will be executed. If none of the nodes in the dispatch chain has a filter for the event generated, then it is passed to the target node and finally the target node processes the event.
In the event bubbling phase, the event is travelled from the target node to the stage node (bottom to top). If any of the nodes in the event dispatch chain has a handler registered for the generated event, it will be executed. If none of these nodes have handlers to handle the event, then the event reaches the root node and finally the process will be completed.
Event filters and handlers are those which contains application logic to process an event. A node can register to more than one handler/filter. In case of parent–child nodes, you can provide a common filter/handler to the parents, which is processed as default for all the child nodes.
As mentioned above, during the event, processing is a filter that is executed and during the event bubbling phase, a handler is executed. All the handlers and filters implement the interface EventHandler of the package javafx.event.
To add an event filter to a node, you need to register this filter using the method addEventFilter() of the Node class.
//Creating the mouse event handler
EventHandler<MouseEvent> eventHandler = new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent e) {
System.out.println("Hello World");
circle.setFill(Color.DARKSLATEBLUE);
}
};
//Adding event Filter
Circle.addEventFilter(MouseEvent.MOUSE_CLICKED, eventHandler);
In the same way, you can remove a filter using the method removeEventFilter() as shown below −
circle.removeEventFilter(MouseEvent.MOUSE_CLICKED, eventHandler);
Following is an example demonstrating the event handling in JavaFX using the event filters. Save this code in a file with name EventFiltersExample.java.
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class EventFiltersExample extends Application {
@Override
public void start(Stage stage) {
//Drawing a Circle
Circle circle = new Circle();
//Setting the position of the circle
circle.setCenterX(300.0f);
circle.setCenterY(135.0f);
//Setting the radius of the circle
circle.setRadius(25.0f);
//Setting the color of the circle
circle.setFill(Color.BROWN);
//Setting the stroke width of the circle
circle.setStrokeWidth(20);
//Setting the text
Text text = new Text("Click on the circle to change its color");
//Setting the font of the text
text.setFont(Font.font(null, FontWeight.BOLD, 15));
//Setting the color of the text
text.setFill(Color.CRIMSON);
//setting the position of the text
text.setX(150);
text.setY(50);
//Creating the mouse event handler
EventHandler<MouseEvent> eventHandler = new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent e) {
System.out.println("Hello World");
circle.setFill(Color.DARKSLATEBLUE);
}
};
//Registering the event filter
circle.addEventFilter(MouseEvent.MOUSE_CLICKED, eventHandler);
//Creating a Group object
Group root = new Group(circle, text);
//Creating a scene object
Scene scene = new Scene(root, 600, 300);
//Setting the fill color to the scene
scene.setFill(Color.LAVENDER);
//Setting title to the Stage
stage.setTitle("Event Filters Example");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
Compile and execute the saved java file from the command prompt using the following commands.
javac EventFiltersExample.java
java EventFiltersExample
On executing, the above program generates a JavaFX window as shown below.
To add an event handler to a node, you need to register this handler using the method addEventHandler() of the Node class as shown below.
//Creating the mouse event handler
EventHandler<javafx.scene.input.MouseEvent> eventHandler =
new EventHandler<javafx.scene.input.MouseEvent>() {
@Override
public void handle(javafx.scene.input.MouseEvent e) {
System.out.println("Hello World");
circle.setFill(Color.DARKSLATEBLUE);
}
};
//Adding the event handler
circle.addEventHandler(javafx.scene.input.MouseEvent.MOUSE_CLICKED, eventHandler);
In the same way, you can remove an event handler using the method removeEventHandler() as shown below −
circle.removeEventHandler(MouseEvent.MOUSE_CLICKED, eventHandler);
The following program is an example demonstrating the event handling in JavaFX using the event handlers.
Save this code in a file with name EventHandlersExample.java.
import javafx.animation.RotateTransition;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.PerspectiveCamera;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyEvent;
import javafx.scene.paint.Color;
import javafx.scene.paint.PhongMaterial;
import javafx.scene.shape.Box;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.scene.transform.Rotate;
import javafx.stage.Stage;
import javafx.util.Duration;
public class EventHandlersExample extends Application {
@Override
public void start(Stage stage) {
//Drawing a Box
Box box = new Box();
//Setting the properties of the Box
box.setWidth(150.0);
box.setHeight(150.0);
box.setDepth(100.0);
//Setting the position of the box
box.setTranslateX(350);
box.setTranslateY(150);
box.setTranslateZ(50);
//Setting the text
Text text = new Text("Type any letter to rotate the box,
and click on the box to stop the rotation");
//Setting the font of the text
text.setFont(Font.font(null, FontWeight.BOLD, 15));
//Setting the color of the text
text.setFill(Color.CRIMSON);
//setting the position of the text
text.setX(20);
text.setY(50);
//Setting the material of the box
PhongMaterial material = new PhongMaterial();
material.setDiffuseColor(Color.DARKSLATEBLUE);
//Setting the diffuse color material to box
box.setMaterial(material);
//Setting the rotation animation to the box
RotateTransition rotateTransition = new RotateTransition();
//Setting the duration for the transition
rotateTransition.setDuration(Duration.millis(1000));
//Setting the node for the transition
rotateTransition.setNode(box);
//Setting the axis of the rotation
rotateTransition.setAxis(Rotate.Y_AXIS);
//Setting the angle of the rotation
rotateTransition.setByAngle(360);
//Setting the cycle count for the transition
rotateTransition.setCycleCount(50);
//Setting auto reverse value to false
rotateTransition.setAutoReverse(false);
//Creating a text filed
TextField textField = new TextField();
//Setting the position of the text field
textField.setLayoutX(50);
textField.setLayoutY(100);
//Handling the key typed event
EventHandler<KeyEvent> eventHandlerTextField = new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
//Playing the animation
rotateTransition.play();
}
};
//Adding an event handler to the text feld
textField.addEventHandler(KeyEvent.KEY_TYPED, eventHandlerTextField);
//Handling the mouse clicked event(on box)
EventHandler<javafx.scene.input.MouseEvent> eventHandlerBox =
new EventHandler<javafx.scene.input.MouseEvent>() {
@Override
public void handle(javafx.scene.input.MouseEvent e) {
rotateTransition.stop();
}
};
//Adding the event handler to the box
box.addEventHandler(javafx.scene.input.MouseEvent.MOUSE_CLICKED, eventHandlerBox);
//Creating a Group object
Group root = new Group(box, textField, text);
//Creating a scene object
Scene scene = new Scene(root, 600, 300);
//Setting camera
PerspectiveCamera camera = new PerspectiveCamera(false);
camera.setTranslateX(0);
camera.setTranslateY(0);
camera.setTranslateZ(0);
scene.setCamera(camera);
//Setting title to the Stage
stage.setTitle("Event Handlers Example");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
Compile and execute the saved java file from the command prompt using the following commands.
javac EventHandlersExample.java
java EventHandlersExample
On executing, the above program generates a JavaFX window displaying a text field and a 3D box as shown below −
Here, if you type a letter in the text field, the 3D box starts rotating along the x axis. If you click on the box again the rotation stops.
Some of the classes in JavaFX define event handler properties. By setting the values to these properties using their respective setter methods, you can register to an event handler. These methods are known as convenience methods.
Most of these methods exist in the classes like Node, Scene, Window, etc., and they are available to all their sub classes.
For example, to add a mouse event listener to a button, you can use the convenience method setOnMouseClicked() as shown below.
playButton.setOnMouseClicked((new EventHandler<MouseEvent>() {
public void handle(MouseEvent event) {
System.out.println("Hello World");
pathTransition.play();
}
}));
The following program is an example that demonstrates the event handling in JavaFX using the convenience methods.
Save this code in a file with the name ConvinienceMethodsExample.java.
import javafx.animation.PathTransition;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.LineTo;
import javafx.scene.shape.MoveTo;
import javafx.scene.shape.Path;
import javafx.stage.Stage;
import javafx.util.Duration;
public class ConvinienceMethodsExample extends Application {
@Override
public void start(Stage stage) {
//Drawing a Circle
Circle circle = new Circle();
//Setting the position of the circle
circle.setCenterX(300.0f);
circle.setCenterY(135.0f);
//Setting the radius of the circle
circle.setRadius(25.0f);
//Setting the color of the circle
circle.setFill(Color.BROWN);
//Setting the stroke width of the circle
circle.setStrokeWidth(20);
//Creating a Path
Path path = new Path();
//Moving to the staring point
MoveTo moveTo = new MoveTo(208, 71);
//Creating 1st line
LineTo line1 = new LineTo(421, 161);
//Creating 2nd line
LineTo line2 = new LineTo(226,232);
//Creating 3rd line
LineTo line3 = new LineTo(332,52);
//Creating 4th line
LineTo line4 = new LineTo(369, 250);
//Creating 5th line
LineTo line5 = new LineTo(208, 71);
//Adding all the elements to the path
path.getElements().add(moveTo);
path.getElements().addAll(line1, line2, line3, line4, line5);
//Creating the path transition
PathTransition pathTransition = new PathTransition();
//Setting the duration of the transition
pathTransition.setDuration(Duration.millis(1000));
//Setting the node for the transition
pathTransition.setNode(circle);
//Setting the path for the transition
pathTransition.setPath(path);
//Setting the orientation of the path
pathTransition.setOrientation(
PathTransition.OrientationType.ORTHOGONAL_TO_TAN GENT);
//Setting the cycle count for the transition
pathTransition.setCycleCount(50);
//Setting auto reverse value to true
pathTransition.setAutoReverse(false);
//Creating play button
Button playButton = new Button("Play");
playButton.setLayoutX(300);
playButton.setLayoutY(250);
circle.setOnMouseClicked (new EventHandler<javafx.scene.input.MouseEvent>() {
@Override
public void handle(javafx.scene.input.MouseEvent e) {
System.out.println("Hello World");
circle.setFill(Color.DARKSLATEBLUE);
}
});
playButton.setOnMouseClicked((new EventHandler<MouseEvent>() {
public void handle(MouseEvent event) {
System.out.println("Hello World");
pathTransition.play();
}
}));
//Creating stop button
Button stopButton = new Button("stop");
stopButton.setLayoutX(250);
stopButton.setLayoutY(250);
stopButton.setOnMouseClicked((new EventHandler<MouseEvent>() {
public void handle(MouseEvent event) {
System.out.println("Hello World");
pathTransition.stop();
}
}));
//Creating a Group object
Group root = new Group(circle, playButton, stopButton);
//Creating a scene object
Scene scene = new Scene(root, 600, 300);
scene.setFill(Color.LAVENDER);
//Setting title to the Stage
stage.setTitle("Convenience Methods Example");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
Compile and execute the saved java file from the command prompt using the following commands.
javac ConvinienceMethodsExample.java
java ConvinienceMethodsExample
On executing, the above program generates a JavaFX window as shown below. Here click on the play button to start the animation and click on the stop button to stop the animation.
33 Lectures
7.5 hours
Syed Raza
64 Lectures
12.5 hours
Emenwa Global, Ejike IfeanyiChukwu
20 Lectures
4 hours
Emenwa Global, Ejike IfeanyiChukwu
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2107,
"s": 1900,
"text": "In JavaFX, we can develop GUI applications, web applications and graphical applications. In such applications, whenever a user interacts with the application (nodes), an event is said to have been occurred."
},
{
"code": null,
"e": 2298,
... |
Check if two line segments intersect | Let two line-segments are given. The points p1, p2 from the first line segment and q1, q2 from the second line segment. We have to check whether both line segments are intersecting or not.
We can say that both line segments are intersecting when these cases are satisfied:
When (p1, p2, q1) and (p1, p2, q2) have a different orientation and
(q1, q2, p1) and (q1, q2, p2) have a different orientation.
There is another condition is when (p1, p2, q1), (p1, p2, q2), (q1, q2, p1), (q1, q2, p2) are collinear.
Input:
Points of two line-segments
Line-segment 1: (0, 0) to (5, 5)
Line-segment 2: (2, -10) to (3, 10)
Output:
Lines are intersecting
direction(a, b, c)
Input: Three points.
Output: Check whether they are collinear or anti-clockwise or clockwise direction.
Begin
val := (b.y-a.y)*(c.x-b.x)-(b.x-a.x)*(c.y-b.y)
if val = 0, then
return collinear
else if val < 0, then
return anti-clockwise
return clockwise
End
isIntersect(l1, l2)
Input: Two line segments, each line has two points p1 and p2.
Output: True, when they are intersecting.
Begin
dir1 = direction(l1.p1, l1.p2, l2.p1);
dir2 = direction(l1.p1, l1.p2, l2.p2);
dir3 = direction(l2.p1, l2.p2, l1.p1);
dir4 = direction(l2.p1, l2.p2, l1.p2);
if dir1 ≠ dir2 and dir3 ≠ dir4, then
return true
if dir1 =0 and l2.p1 on the line l1, then
return true
if dir2 = 0 and l2.p2 on the line l1, then
return true
if dir3 = 0 and l1.p1 on the line l2, then
return true
if dir4 = 0 and l1.p2 on the line l2, then
return true
return false
End
#include<iostream>
using namespace std;
struct Point {
int x, y;
};
struct line {
Point p1, p2;
};
bool onLine(line l1, Point p) { //check whether p is on the line or not
if(p.x <= max(l1.p1.x, l1.p2.x) && p.x <= min(l1.p1.x, l1.p2.x) &&
(p.y <= max(l1.p1.y, l1.p2.y) && p.y <= min(l1.p1.y, l1.p2.y)))
return true;
return false;
}
int direction(Point a, Point b, Point c) {
int val = (b.y-a.y)*(c.x-b.x)-(b.x-a.x)*(c.y-b.y);
if (val == 0)
return 0; //colinear
else if(val < 0)
return 2; //anti-clockwise direction
return 1; //clockwise direction
}
bool isIntersect(line l1, line l2) {
//four direction for two lines and points of other line
int dir1 = direction(l1.p1, l1.p2, l2.p1);
int dir2 = direction(l1.p1, l1.p2, l2.p2);
int dir3 = direction(l2.p1, l2.p2, l1.p1);
int dir4 = direction(l2.p1, l2.p2, l1.p2);
if(dir1 != dir2 && dir3 != dir4)
return true; //they are intersecting
if(dir1==0 && onLine(l1, l2.p1)) //when p2 of line2 are on the line1
return true;
if(dir2==0 && onLine(l1, l2.p2)) //when p1 of line2 are on the line1
return true;
if(dir3==0 && onLine(l2, l1.p1)) //when p2 of line1 are on the line2
return true;
if(dir4==0 && onLine(l2, l1.p2)) //when p1 of line1 are on the line2
return true;
return false;
}
int main() {
line l1 = {{0,0}, {5, 5}};
line l2 = {{2,-10}, {3, 10}};
if(isIntersect(l1, l2))
cout << "Lines are intersecting";
else
cout << "Lines are not intersecting";
}
Lines are intersecting | [
{
"code": null,
"e": 1251,
"s": 1062,
"text": "Let two line-segments are given. The points p1, p2 from the first line segment and q1, q2 from the second line segment. We have to check whether both line segments are intersecting or not."
},
{
"code": null,
"e": 1335,
"s": 1251,
"t... |
RadioButton in Kotlin - GeeksforGeeks | 19 Feb, 2021
Android Radio Button is bi-state button which can either be checked or unchecked. Also, it’s working is same as Checkbox except that radio button can not allow to be unchecked once it was selected.
Generally, we use RadioButton controls to allow users to select one option from multiple options.
By default, the RadioButton in OFF(Unchecked) state but we can change the default state of RadioButton by using android:checked attribute.
Following steps to create new project-
Click on File,then New => New Project.
Then, check Include Kotlin Support and click next button.
Select minimum SDK, whatever you need.
Select Empty activity and then click finish.
We can write the name of the application as RadioButtonInKotlin and write other strings which can be used.
<resources> <string name="app_name">RadioButtonInKotlin</string> <string name="checked">checked</string> <string name="unchecked">unchecked</string></resources>
In android, we use radio buttons inside RadioGroup to combine set of radio buttons into single group and it will make sure that user can select only button from the group of buttons.
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/root_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="16dp"> <RadioGroup android:id="@+id/radio_group" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#dbeceb" android:padding="15dp"> <TextView android:id="@+id/title" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Which is your favorite color?" android:textStyle="bold" android:textSize="20sp"/> <RadioButton android:id="@+id/red" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="RED" android:onClick="radio_button_click"/> <RadioButton android:id="@+id/green" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="GREEN" android:onClick="radio_button_click"/> <RadioButton android:id="@+id/yellow" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="YELLOW" android:onClick="radio_button_click"/> <RadioButton android:id="@+id/pink" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="PINK" android:onClick="radio_button_click"/> </RadioGroup> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Get Selected Color"/></LinearLayout>
Here, we are trying to implement a scenario where you need to select your favorite color. So, in activity_main.xml file, we have added 4 radio buttons inside a radio group. Each button represent a color. Now, only one radio button can be selected at a time. *
Now, we will access this widget in kotlin file and show a proper message whenever a radio button is selected.
package com.geeksforgeeks.myfirstkotlinapp import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.view.Viewimport android.widget.*import kotlinx.android.synthetic.main.activity_main.*import android.widget.RadioGroup class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Get radio group selected item using on checked change listener radio_group.setOnCheckedChangeListener( RadioGroup.OnCheckedChangeListener { group, checkedId -> val radio: RadioButton = findViewById(checkedId) Toast.makeText(applicationContext," On checked change :"+ " ${radio.text}", Toast.LENGTH_SHORT).show() }) // Get radio group selected status and text using button click event button.setOnClickListener{ // Get the checked radio button id from radio group var id: Int = radio_group.checkedRadioButtonId if (id!=-1){ // If any radio button checked from radio group // Get the instance of radio button using id val radio:RadioButton = findViewById(id) Toast.makeText(applicationContext,"On button click :" + " ${radio.text}", Toast.LENGTH_SHORT).show() }else{ // If no radio button checked in this radio group Toast.makeText(applicationContext,"On button click :" + " nothing selected", Toast.LENGTH_SHORT).show() } } } // Get the selected radio button text using radio button on click listener fun radio_button_click(view: View){ // Get the clicked radio button instance val radio: RadioButton = findViewById(radio_group.checkedRadioButtonId) Toast.makeText(applicationContext,"On click : ${radio.text}", Toast.LENGTH_SHORT).show() }}
In MainActivity.kt file, we have accessed radio group in which I have added four radio buttons. Then, we have set a listener to display toast message whenever radio button selection changes.
Since AndroidManifest.xml file is very important in any android application, we are also going to mention it here.
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.geeksforgeeks.myfirstkotlinapp"> <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>
When You run the application, you will get the output as shown below
Android-Button
Kotlin Android
Picked
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Create and Add Data to SQLite Database in Android?
Broadcast Receiver in Android With Example
Android RecyclerView in Kotlin
Content Providers in Android with Example
Navigation Drawer in Android
Broadcast Receiver in Android With Example
Android UI Layouts
Android RecyclerView in Kotlin
Content Providers in Android with Example
Retrofit with Kotlin Coroutine in Android | [
{
"code": null,
"e": 23815,
"s": 23787,
"text": "\n19 Feb, 2021"
},
{
"code": null,
"e": 24013,
"s": 23815,
"text": "Android Radio Button is bi-state button which can either be checked or unchecked. Also, it’s working is same as Checkbox except that radio button can not allow to ... |
Multinomial Naive Bayes Classifier for Text Analysis (Python) | by Syed Sadat Nazrul | Towards Data Science | One of the most popular applications of machine learning is the analysis of categorical data, specifically text data. Issue is that, there are a ton of tutorials out there for numeric data but very little for texts. Considering how most of my past blogs on Machine Learning were based on Scikit-Learn, I decided to have some fun with this one by implementing the whole thing on my own.
In this blog, I will cover how you can implement a Multinomial Naive Bayes Classifier for the 20 Newsgroups dataset. The 20 newsgroups dataset comprises around 18000 newsgroups posts on 20 topics split in two subsets: one for training (or development) and the other one for testing (or for performance evaluation). The split between the train and test set is based upon a messages posted before and after a specific date.
First, let us import the libraries needed for writing the implementation:
import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport operator
First, we calculate the fraction of documents in each class:
#Training labeltrain_label = open('20news-bydate/matlab/train.label')#pi is the fraction of each classpi = {}#Set a class index for each document as keyfor i in range(1,21): pi[i] = 0 #Extract values from training labelslines = train_label.readlines()#Get total number of documentstotal = len(lines)#Count the occurence of each classfor line in lines: val = int(line.split()[0]) pi[val] += 1#Divide the count of each class by total documents for key in pi: pi[key] /= total print("Probability of each class:")print("\n".join("{}: {}".format(k, v) for k, v in pi.items()))
Let’s first create the Pandas Dataframe
#Training datatrain_data = open('20news-bydate/matlab/train.data')df = pd.read_csv(train_data, delimiter=' ', names=['docIdx', 'wordIdx', 'count'])#Training labellabel = []train_label = open('/home/sadat/Downloads/HW2_210/20news-bydate/matlab/train.label')lines = train_label.readlines()for line in lines: label.append(int(line.split()[0]))#Increase label length to match docIdxdocIdx = df['docIdx'].valuesi = 0new_label = []for index in range(len(docIdx)-1): new_label.append(label[i]) if docIdx[index] != docIdx[index+1]: i += 1new_label.append(label[i]) #for-loop ignores last value#Add label columndf['classIdx'] = new_labeldf.head()
For calculating our probability, we will find the average of each word for a given class.
For class j and word i, the average is given by:
However, since some words will have 0 counts, we will perform a Laplace Smoothing with low ɑ:
where V is an array of all the words in the vocabulary
#Alpha value for smoothinga = 0.001#Calculate probability of each word based on classpb_ij = df.groupby(['classIdx','wordIdx'])pb_j = df.groupby(['classIdx'])Pr = (pb_ij['count'].sum() + a) / (pb_j['count'].sum() + 16689) #Unstack seriesPr = Pr.unstack()#Replace NaN or columns with 0 as word count with a/(count+|V|+1)for c in range(1,21): Pr.loc[c,:] = Pr.loc[c,:].fillna(a/(pb_j['count'].sum()[c] + 16689))#Convert to dictionary for greater speedPr_dict = Pr.to_dict()Pr
Stop words are words that show up a lot in every document (e.g. prepositions and pronouns).
#Common stop words from onlinestop_words = ["a", "about", "above", "across", "after", "afterwards", "again", "all", "almost", "alone", "along", "already", "also", "although", "always", "am", "among", "amongst", "amoungst", "amount", "an", "and", "another", "any", "anyhow", "anyone", "anything", "anyway", "anywhere", "are", "as", "at", "be", "became", "because", "become","becomes", "becoming", "been", "before", "behind", "being", "beside", "besides", "between", "beyond", "both", "but", "by","can", "cannot", "cant", "could", "couldnt", "de", "describe", "do", "done", "each", "eg", "either", "else", "enough", "etc", "even", "ever", "every", "everyone", "everything", "everywhere", "except", "few", "find","for","found", "four", "from", "further", "get", "give", "go", "had", "has", "hasnt", "have", "he", "hence", "her", "here", "hereafter", "hereby", "herein", "hereupon", "hers", "herself", "him", "himself", "his", "how", "however", "i", "ie", "if", "in", "indeed", "is", "it", "its", "itself", "keep", "least", "less", "ltd", "made", "many", "may", "me", "meanwhile", "might", "mine", "more", "moreover", "most", "mostly", "much", "must", "my", "myself", "name", "namely", "neither", "never", "nevertheless", "next","no", "nobody", "none", "noone", "nor", "not", "nothing", "now", "nowhere", "of", "off", "often", "on", "once", "one", "only", "onto", "or", "other", "others", "otherwise", "our", "ours", "ourselves", "out", "over", "own", "part","perhaps", "please", "put", "rather", "re", "same", "see", "seem", "seemed", "seeming", "seems", "she", "should","since", "sincere","so", "some", "somehow", "someone", "something", "sometime", "sometimes", "somewhere", "still", "such", "take","than", "that", "the", "their", "them", "themselves", "then", "thence", "there", "thereafter", "thereby", "therefore", "therein", "thereupon", "these", "they","this", "those", "though", "through", "throughout","thru", "thus", "to", "together", "too", "toward", "towards","under", "until", "up", "upon", "us","very", "was", "we", "well", "were", "what", "whatever", "when","whence", "whenever", "where", "whereafter", "whereas", "whereby","wherein", "whereupon", "wherever", "whether", "which", "while", "who", "whoever", "whom", "whose", "why", "will", "with","within", "without", "would", "yet", "you", "your", "yours", "yourself", "yourselves"]
Now, let’s create the vocabulary dataframe
vocab = open('vocabulary.txt') vocab_df = pd.read_csv(vocab, names = ['word']) vocab_df = vocab_df.reset_index() vocab_df['index'] = vocab_df['index'].apply(lambda x: x+1) vocab_df.head()
Getting the counts of each word in the vocabulary and setting stop words to 0:
#Index of all wordstot_list = set(vocab_df['index'])#Index of good wordsvocab_df = vocab_df[~vocab_df['word'].isin(stop_words)]good_list = vocab_df['index'].tolist()good_list = set(good_list)#Index of stop wordsbad_list = tot_list - good_list#Set all stop words to 0for bad in bad_list: for j in range(1,21): Pr_dict[j][bad] = a/(pb_j['count'].sum()[j] + 16689)
Multinomial Naive Bayes Classifier
Combining probability distribution of P with fraction of documents belonging to each class.
For class j, word i at a word frequency of f:
In order to avoid underflow, we will use the sum of logs:
One issue is that, if a word appears again, the probability of it appearing again goes up. In order to smooth this, we take the log of the frequency:
Also, in order to take stop words into account, we will add a Inverse Document Frequency (IDF)weight on each word:
Even though the stop words have already been set to 0 for this specific use case, the IDF implementation is being added to generalize the function.
#Calculate IDF tot = len(df['docIdx'].unique()) pb_ij = df.groupby(['wordIdx']) IDF = np.log(tot/pb_ij['docIdx'].count()) IDF_dict = IDF.to_dict()def MNB(df, smooth = False, IDF = False): ''' Multinomial Naive Bayes classifier :param df [Pandas Dataframe]: Dataframe of data :param smooth [bool]: Apply Smoothing if True :param IDF [bool]: Apply Inverse Document Frequency if True :return predict [list]: Predicted class ID ''' #Using dictionaries for greater speed df_dict = df.to_dict() new_dict = {} prediction = [] #new_dict = {docIdx : {wordIdx: count},....} for idx in range(len(df_dict['docIdx'])): docIdx = df_dict['docIdx'][idx] wordIdx = df_dict['wordIdx'][idx] count = df_dict['count'][idx] try: new_dict[docIdx][wordIdx] = count except: new_dict[df_dict['docIdx'][idx]] = {} new_dict[docIdx][wordIdx] = count #Calculating the scores for each doc for docIdx in range(1, len(new_dict)+1): score_dict = {} #Creating a probability row for each class for classIdx in range(1,21): score_dict[classIdx] = 1 #For each word: for wordIdx in new_dict[docIdx]: #Check for frequency smoothing #log(1+f)*log(Pr(i|j)) if smooth: try: probability=Pr_dict[wordIdx][classIdx] power = np.log(1+ new_dict[docIdx][wordIdx]) #Check for IDF if IDF: score_dict[classIdx]+=( power*np.log( probability*IDF_dict[wordIdx])) else: score_dict[classIdx]+=power*np.log( probability) except: #Missing V will have log(1+0)*log(a/16689)=0 score_dict[classIdx] += 0 #f*log(Pr(i|j)) else: try: probability = Pr_dict[wordIdx][classIdx] power = new_dict[docIdx][wordIdx] score_dict[classIdx]+=power*np.log( probability) #Check for IDF if IDF: score_dict[classIdx]+= power*np.log( probability*IDF_dict[wordIdx]) except: #Missing V will have 0*log(a/16689) = 0 score_dict[classIdx] += 0 #Multiply final with pi score_dict[classIdx] += np.log(pi[classIdx]) #Get class with max probabilty for the given docIdx max_score = max(score_dict, key=score_dict.get) prediction.append(max_score) return prediction
Comparing the effects of smoothing and IDF:
regular_predict = MNB(df, smooth=False, IDF=False)smooth_predict = MNB(df, smooth=True, IDF=False)tfidf_predict = MNB(df, smooth=False, IDF=True)all_predict = MNB(df, smooth=True, IDF=True)#Get list of labelstrain_label = pd.read_csv('20news-bydate/matlab/train.label', names=['t'])train_label= train_label['t'].tolist()total = len(train_label) models = [regular_predict, smooth_predict, tfidf_predict, all_predict] strings = ['Regular', 'Smooth', 'IDF', 'Both'] for m,s in zip(models,strings): val = 0 for i,j in zip(m, train_label): if i != j: val +=1 else: pass print(s,"Error:\t\t",val/total * 100, "%")
As we can see, IDF has little effect as we removed the stop words. Smoothing, however, makes the model more accurate.
Hence, our optimal model is:
Now that we have out model, let’s use it to predict our test data.
#Get test datatest_data = open('20news-bydate/matlab/test.data')df = pd.read_csv(test_data, delimiter=' ', names=['docIdx', 'wordIdx', 'count'])#Get list of labelstest_label = pd.read_csv('/home/sadat/Downloads/HW2_210/20news-bydate/matlab/test.label', names=['t'])test_label= test_label['t'].tolist()#MNB Calculationpredict = MNB(df, smooth = True, IDF = False)total = len(test_label)val = 0for i,j in zip(predict, test_label): if i == j: val +=1 else: passprint("Error:\t",(1-(val/total)) * 100, "%") | [
{
"code": null,
"e": 557,
"s": 171,
"text": "One of the most popular applications of machine learning is the analysis of categorical data, specifically text data. Issue is that, there are a ton of tutorials out there for numeric data but very little for texts. Considering how most of my past blogs o... |
Barnsley Fern in Python | In this tutorial, we are going to learn about the Barnsley Fern, which is created by Michael Barnsley. The features of Barnsley Fern is similar to the fern shape. It is created by iterating over the four mathematical equations known as Iterated Function System(IFS). The transformation has the following formula.
f(x,y)=[abcd][xy]+[ef]
Source − Wikipedia
The values of the variables are −
Source − Wikipedia
The four equation that Barnsley Fern proposed are −
Source − Wikipedia
Now, we will see code to create the fern shape in Python.
# importing matplotlib module for the plot
import matplotlib.pyplot as plot
# importing random module to generate random integers for the plot
import random
# initialising the lists
x = [0]
y = [0]
# initialising a variable to zero to track position
current = 0
for i in range(1, 1000):
# generating a random integer between 1 and 100
z = random.randint(1, 100)
# checking the z range and appending corresponding values to x and y
# appending values to the x and y
if z == 1:
x.append(0)
y.append(0.16 * y[current])
if z >= 2 and z <= 86:
x.append(0.85 * x[current] + 0.04 * y[current])
y.append(-0.04 * x[current] + 0.85 * y[current] +1.6)
if z>= 87 and z<= 93:
x.append(0.2 * x[current] - 0.26 * y[current])
y.append(0.23 * x[current] + 0.22*(y[current])+1.6)
if z >= 94 and z <= 100:
x.append(-0.15 * x[current] + 0.28 * y[current])
y.append(0.26 * x[current] + 0.24 * y[current] + 0.44)
# incrementing the current value
current += 1
# plotting the graph using x and y
plot.scatter(x, y, s = 0.2, edgecolor = 'green')
plot.show()
If you run the above code, you will get the following result.
If you have any doubts in the tutorial, mention them in the comment section.
Reference −Wikipedia | [
{
"code": null,
"e": 1375,
"s": 1062,
"text": "In this tutorial, we are going to learn about the Barnsley Fern, which is created by Michael Barnsley. The features of Barnsley Fern is similar to the fern shape. It is created by iterating over the four mathematical equations known as Iterated Function... |
GATE | GATE-IT-2004 | Question 83 - GeeksforGeeks | 28 Jun, 2021
A 20 Kbps satellite link has a propagation delay of 400 ms. The transmitter employs the “go back n ARQ” scheme with n set to 10. Assuming that each frame is 100 bytes long, what is the maximum data rate possible?(A) 5Kbps(B) 10Kbps(C) 15Kbps(D) 20KbpsAnswer: (B)Explanation:
It uses the sliding window protocol for transmission of data.
The question takes into consideration the variant of sliding window protocol
namely GO BACK N ARQ. In this protocol the sender can have up to N packets
unacknowledged that are still remaining in the pipeline. The receiver only
sends cumulative acknowledgements. In case of encountering an error the sender
has to resend all the data frames following the error.
According to the question:
The data rate of the link is 20 Kbps and the propagation delay = 400 ms
So, the time required to transmit 100 bytes long data will be given by
Transmission Time t = Number of bits to be transmitted / data rate of the link
= (100* 8 bits) /20 Kbps = 40 ms
Now, the propagation delay is given as d = 400 ms
So the efficiency of the link is given by:
Efficiency E = N * t / ( t+ 2 * d )
Where N = window size
E = 10 * 40 / (40+2*400) = 0.476
So, the maximum data rate attainable = 0.476 * 20 Kbps = 9.52 Kbps
This is close to 10.
So, the answer will be 10Kbps.
This explanation has been contributed by Namita Singh.Quiz of this Question
GATE IT 2004
GATE-GATE IT 2004
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-IT-2004 | Question 12
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2007 | Question 17
GATE | GATE-CS-2007 | Question 64
GATE | GATE-CS-2009 | Question 28
GATE | GATE CS 2019 | Question 37
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2006 | Question 46 | [
{
"code": null,
"e": 24347,
"s": 24319,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 24622,
"s": 24347,
"text": "A 20 Kbps satellite link has a propagation delay of 400 ms. The transmitter employs the “go back n ARQ” scheme with n set to 10. Assuming that each frame is 100 by... |
GATE | GATE-CS-2005 | Question 80 - GeeksforGeeks | 28 Jun, 2021
Consider the following data path of a CPU.
The, ALU, the bus and all the registers in the data path are of identical size. All operations including incrementation of the PC and the GPRs are to be carried out in the ALU. Two clock cycles are needed for memory read operation – the first one for loading address in the MAR and the next one for loading data from the memory bus into the MDR79.The instruction “call Rn, sub” is a two word instruction. Assuming that PC is incremented during the fetch cycle of the first word of the instruction, its register transfer interpretation is
Rn < = PC + 1;
PC < = M[PC];
The minimum number of CPU clock cycles needed during the execution cycle of this instruction is:(A) 2(B) 3(C) 4(D) 5Answer: (B)Explanation: One cycle to increment PC, one cycle to load PC into MAR, one cycle to fetch memory content and load into PC.Quiz of this Question
GATE-CS-2005
GATE-GATE-CS-2005
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE CS 2018 | Question 37
GATE | GATE-IT-2004 | Question 83
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2016 (Set 1) | Question 63
GATE | GATE-IT-2004 | Question 12
GATE | GATE-CS-2007 | Question 17
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2010 | Question 33
GATE | GATE-CS-2007 | Question 64 | [
{
"code": null,
"e": 24363,
"s": 24335,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 24406,
"s": 24363,
"text": "Consider the following data path of a CPU."
},
{
"code": null,
"e": 24944,
"s": 24406,
"text": "The, ALU, the bus and all the registers in the ... |
Building an Image Color Analyzer using Python | by Behic Guven | Towards Data Science | In this post, I will show you how to create a program that can detect colors and then calculate the weights of the colors in an image. This will be a fun and straightforward machine learning based computer vision project, where we will use Scikit-learn and OpenCV as our main modules. Especially, graphic designers and web designers will find this program very helpful. Not only detecting the colors but also seeing their volume levels in an image is a super neat feature.
As a technology and art enthusiast, I enjoy working on projects that are very much related to both fields. And that’s what I love about programming. Your limit is your imagination!
If you are into art/ programming, you can find many hands-on projects like this on my blog. Without losing any time, let’s get to work!
Getting Started
Libraries
Reading an Image
Functions
Image Color Analyzer in Action
Conclusion
We will be using two main modules in this color analysis project. And they are Scikit-learn and OpenCV. Scikit-learn is a well-known artificial intelligence and machine learning module. And OpenCV is a must-have computer vision module. Here is a short definition of OpenCV.
OpenCV (Open Source Computer Vision Library) is an open-source computer vision and machine learning software library. OpenCV was built to provide a common infrastructure for computer vision applications and accelerate machine perception in commercial products.
Reference: https://opencv.org
First things first, let me introduce you to the libraries. We will need five libraries for this project. And these libraries can be listed as following: OpenCV, Scikit-learn, NumPy, Matplotlib and Collections.
Now, let’s install them using pip, which is a python library manager. By the way, we don’t need to install collections; it comes by default with Python.
pip install opencv-python scikit-learn numpy matplotlib
After the installation is completed, we can go ahead and import them. By the way, I will use Jupyter Notebook for this project. Great way to keep a timeline of the process.
from collections import Counterfrom sklearn.cluster import KMeansfrom matplotlib import colorsimport matplotlib.pyplot as pltimport numpy as npimport cv2
Here are the official links for each library. Feel free to check them out to learn more about them.
OpenCV
Scikit-learn
Matplotlib
Numpy
Collections
We need to choose an image to get started. Here is the image that I will be using for this project.
image = cv2.imread('test_image.jpg')image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)plt.imshow(image)
We are using imread method by OpenCV to read the image. And then, we are converting the color format from BGR to RGB using cvtColor. The everyday images that we see on our devices are in RGB format.
In this step, as you can understand from the title, we will be writing functions. I will define three functions that will be helpful for us. Functions are also an excellent method to simplify your programs.
Here are the functions with their definitions.
def rgb_to_hex(rgb_color): hex_color = "#" for i in rgb_color: i = int(i) hex_color += ("{:02x}".format(i)) return hex_color
In this function, we are converting an RGB color into Hex color format. This function will help at the end when visualizing the results of our analysis. Instead of having three different values (red, green, blue), we will have one output: hex value.
def prep_image(raw_img): modified_img = cv2.resize(raw_img, (900, 600), interpolation = cv2.INTER_AREA) modified_img = modified_img.reshape(modified_img.shape[0]*modified_img.shape[1], 3) return modified_img
This function basically does the preprocessing of the image. If you want to make any changes to the picture before analyzing the colors, this is the function that you can use. We will resize and reshape the image in this step. Resizing is optional, but reshaping is needed for the color analysis model to work correctly. We will see it in the following function.
This is the function where the magic happens. I will cover in bullet points what is happening in the function.
def color_analysis(img): clf = KMeans(n_clusters = 5) color_labels = clf.fit_predict(img) center_colors = clf.cluster_centers_ counts = Counter(color_labels) ordered_colors = [center_colors[i] for i in counts.keys()] hex_colors = [rgb_to_hex(ordered_colors[i]) for i in counts.keys()] plt.figure(figsize = (12, 8)) plt.pie(counts.values(), color_labels = hex_colors, colors = hex_colors) plt.savefig("color_analysis_report.png") print(hex_colors)
First, we are using k-Means to cluster the top colors. Inside the function we are passing the value of how many clusters do we want to divide. Here is the documentation for K-Means clustering. After clustering we predict the colors that weigh the most — meaning getting the most area on the image.
Secondly, we are calling the Counter function. Counter creates a container to the elements as dictionary keys, and their volume is store as dictionary values. If you are not familiar with dictionaries, they store data in key: value pairs. They are like function, and when you pass in the “key,” you can “value” as a return. Then we are ordering the colors according to the keys.
Thirdly, we are passing those colors in the rgb_to_hex function so that we can get the hex values of the colors.
And lastly, the visualization of the result. I decided to go with a pie chart, which will be helpful to understand the weight of each color in the whole picture. After plotting the figure, I am also saving it into the computer using the savefig method. This way, we have a record of the result.
Before we move to the final step, I would like to share a compelling article related to our computer vision project: Object Detection via Color-based Image Segmentation using Python by Salma Ghoneim.
Almost done! We got the behind-the-scenes ready. Now we can get to the action part. We have the image defined earlier and assigned to the “image” variable. We will call the prep_image function to preprocess the image.
modified_image = prep_image(image)color_analysis(modified_image)
Congratulations! We have created a program that analyzes an image and returns the color report as a plot. One exciting feature is that we can define how many clusters we want to divide the colors into. I used five clusters, but feel free to try the model with different values. And the rest is done with Scikit-learn K-means model prediction and OpenCV.
Here comes the final result:
Hoping that you enjoyed reading this article and learned something new today. Working on hands-on programming projects is the best way to sharpen your coding skills. Feel free to reach me if you have any questions while implementing the code.
Let’s connect. Check my blog and youtube to stay inspired. Thank you, | [
{
"code": null,
"e": 645,
"s": 172,
"text": "In this post, I will show you how to create a program that can detect colors and then calculate the weights of the colors in an image. This will be a fun and straightforward machine learning based computer vision project, where we will use Scikit-learn an... |
Amortized analysis for increment in counter in C++ | Amortized analysis for a sequence of operations is used to determine the run time, the average time required by the sequence. In cannot be treated as an average-case analysis done on the algorithm as it does not always take the average case scenario. There are cases that occur as a worst-case scenario of analysis. So, amortized analysis can be treated as a worst-case analysis for multiple operations in a sequence. Here, the cost of doing each operations in different and for some its high. This problem is a general view using the binary counter.
Let’s see the working and implementation in c++ programming language so that we will be clear with the concepts.
A k-bit binary counter is implemented using a binary array of length k which is initially valued 0. On this value, the increment operation is performed multiple times. Here is how the binary 8-bit array will behave on the increment operation performed on it.
Initially, 00000000 > 00000001 > 00000010 > 00000011 > 00000100 > 00000101 >.... > 11111111.
This logic is to check for the occurrence of first 0 from the last bit of the number and flip it to 1 and all the bits sequentially following it to 0.
#include <iostream>
using namespace std;
int main(){
int number[] = {1,0,0,1,0,1,1,1};
int length = 8;
int i = length - 1;
while (number[i] == 1) {
number[i] = 0;
i--;
}
if (i >= 0)
str[i] = 1;
for(int i = 0 ; i<length ; i++)
cout<<number[i]<<" ";
}
1 0 0 1 0 0 0 0
In this problem, the cost of each operation is constant and does not depend on the number of bits,
Here the asymptotic analysis for the cost of a sequence is O(n).
The total number of flips that are done in n operations is − n + n/2 + n/4 + ..... + n/k2 k in the number of flips.
This is a GP with HP in the denominator.
The sum of flip
Sum = n + n/2 + n/4 + ..... + n/k2 < n/(1-1/2) = 2n
Now, aromatized cost of operation is O(n) / 2n = O(1)
The order is O(1) which is not proportional to n the number of bits in the number. | [
{
"code": null,
"e": 1613,
"s": 1062,
"text": "Amortized analysis for a sequence of operations is used to determine the run time, the average time required by the sequence. In cannot be treated as an average-case analysis done on the algorithm as it does not always take the average case scenario. Th... |
Spring JDBC - Create Query | The following example will demonstrate how to create a query using Insert query with the help of Spring JDBC. We'll insert a few records in Student Table.
String insertQuery = "insert into Student (name, age) values (?, ?)";
jdbcTemplateObject.update( insertQuery, name, age);
Where,
insertQuery − Insert query having placeholders.
insertQuery − Insert query having placeholders.
jdbcTemplateObject − StudentJDBCTemplate object to insert student object in database.
jdbcTemplateObject − StudentJDBCTemplate object to insert student object in database.
To understand the above-mentioned concepts related to Spring JDBC, let us write an example which will insert a query. To write our example, let us have a working Eclipse IDE in place and use the following steps to create a Spring application.
Following is the content of the Data Access Object interface file StudentDAO.java.
package com.tutorialspoint;
import java.util.List;
import javax.sql.DataSource;
public interface StudentDAO {
/**
* This is the method to be used to initialize
* database resources ie. connection.
*/
public void setDataSource(DataSource ds);
/**
* This is the method to be used to create
* a record in the Student table.
*/
public void create(String name, Integer age);
/**
* This is the method to be used to list down
* all the records from the Student table.
*/
public List<Student> listStudents();
}
Following is the content of the Student.java file.
package com.tutorialspoint;
public class Student {
private Integer age;
private String name;
private Integer id;
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
}
Following is the content of the StudentMapper.java file.
package com.tutorialspoint;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
public class StudentMapper implements RowMapper<Student> {
public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
Student student = new Student();
student.setId(rs.getInt("id"));
student.setName(rs.getString("name"));
student.setAge(rs.getInt("age"));
return student;
}
}
Following is the implementation class file StudentJDBCTemplate.java for the defined DAO interface StudentDAO.
package com.tutorialspoint;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
public class StudentJDBCTemplate implements StudentDAO {
private DataSource dataSource;
private JdbcTemplate jdbcTemplateObject;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
this.jdbcTemplateObject = new JdbcTemplate(dataSource);
}
public void create(String name, Integer age) {
String insertQuery = "insert into Student (name, age) values (?, ?)";
jdbcTemplateObject.update( insertQuery, name, age);
System.out.println("Created Record Name = " + name + " Age = " + age);
return;
}
public List<Student> listStudents() {
String SQL = "select * from Student";
List <Student> students = jdbcTemplateObject.query(SQL, new StudentMapper());
return students;
}
}
Following is the content of the MainApp.java file.
package com.tutorialspoint;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.tutorialspoint.StudentJDBCTemplate;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
StudentJDBCTemplate studentJDBCTemplate = (StudentJDBCTemplate)context.getBean("studentJDBCTemplate");
System.out.println("------Records Creation--------" );
studentJDBCTemplate.create("Zara", 11);
studentJDBCTemplate.create("Nuha", 2);
studentJDBCTemplate.create("Ayan", 15);
System.out.println("------Listing Multiple Records--------" );
List<Student> students = studentJDBCTemplate.listStudents();
for (Student record : students) {
System.out.print("ID : " + record.getId() );
System.out.print(", Name : " + record.getName() );
System.out.println(", Age : " + record.getAge());
}
}
}
Following is the configuration file Beans.xml.
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd ">
<!-- Initialization for data source -->
<bean id = "dataSource"
class = "org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name = "driverClassName" value = "com.mysql.cj.jdbc.Driver"/>
<property name = "url" value = "jdbc:mysql://localhost:3306/TEST"/>
<property name = "username" value = "root"/>
<property name = "password" value = "admin"/>
</bean>
<!-- Definition for studentJDBCTemplate bean -->
<bean id = "studentJDBCTemplate"
class = "com.tutorialspoint.StudentJDBCTemplate">
<property name = "dataSource" ref = "dataSource" />
</bean>
</beans>
Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message.
------Records Creation--------
Created Record Name = Zara Age = 11
Created Record Name = Nuha Age = 2
Created Record Name = Ayan Age = 15
------Listing Multiple Records--------
ID : 1, Name : Zara, Age : 11
ID : 2, Name : Nuha, Age : 2
ID : 3, Name : Ayan, Age : 15
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2551,
"s": 2396,
"text": "The following example will demonstrate how to create a query using Insert query with the help of Spring JDBC. We'll insert a few records in Student Table."
},
{
"code": null,
"e": 2674,
"s": 2551,
"text": "String insertQuery = \"inse... |
MySQL update a column with an int based on order? | The syntax is as follows to update a column with an int based on order
set @yourVariableName=0;
update yourTableName
set yourColumnName=(@yourVariableName:=@yourVariableName+1)
order by yourColumnName ASC;
To understand the above syntax, let us create a table. The query to create a table is as follows
mysql> create table updateColumnDemo
-> (
-> Id int,
-> OrderCountryName varchar(100),
-> OrderAmount int
-> );
Query OK, 0 rows affected (1.76 sec)
Insert some records in the table using insert command.
The query is as follows
mysql> insert into updateColumnDemo(Id,OrderCountryName) values(10,'US');
Query OK, 1 row affected (0.46 sec)
mysql> insert into updateColumnDemo(Id,OrderCountryName) values(20,'UK');
Query OK, 1 row affected (0.98 sec)
mysql> insert into updateColumnDemo(Id,OrderCountryName) values(30,'AUS');
Query OK, 1 row affected (0.77 sec)
mysql> insert into updateColumnDemo(Id,OrderCountryName) values(40,'France');
Query OK, 1 row affected (1.58 sec)
Display all records from the table using select statement.
The query is as follows
mysql> select *from updateColumnDemo;
The following is the output
+------+------------------+-------------+
| Id | OrderCountryName | OrderAmount |
+------+------------------+-------------+
| 10 | US | NULL |
| 20 | UK | NULL |
| 30 | AUS | NULL |
| 40 | France | NULL |
+------+------------------+-------------+
4 rows in set (1.00 sec)
Here is the query to update a column with an int based on order
mysql> set @sequenceNumber=0;
Query OK, 0 rows affected (0.00 sec)
mysql> update updateColumnDemo
-> set OrderAmount=(@sequenceNumber:=@sequenceNumber+1)
-> order by OrderAmount ASC;
Query OK, 4 rows affected (0.25 sec)
Rows matched: 4 Changed: 4 Warnings: 0
Let us check the table records once again.
The query is as follows
mysql> select *from updateColumnDemo;
The following is the output
+------+------------------+-------------+
| Id | OrderCountryName | OrderAmount |
+------+------------------+-------------+
| 10 | US | 1 |
| 20 | UK | 2 |
| 30 | AUS | 3 |
| 40 | France | 4 |
+------+------------------+-------------+
4 rows in set (0.00 sec) | [
{
"code": null,
"e": 1133,
"s": 1062,
"text": "The syntax is as follows to update a column with an int based on order"
},
{
"code": null,
"e": 1268,
"s": 1133,
"text": "set @yourVariableName=0;\nupdate yourTableName\nset yourColumnName=(@yourVariableName:=@yourVariableName+1)\nor... |
Deploy Your Machine Learning Model as a REST API | by Dario Radečić | Towards Data Science | After reading the article you will be able to deploy machine learning models and make predictions from any programming language you want. That’s right, you can stick to Python, or you could make predictions directly inside your Android app via Java or Kotlin. Also, you could use the model directly in your web application — the options are endless. For simplicity's sake, I will use Postman.
I, however, won’t explain how to put the model on a live server, because the options are endless and it’s a possibly good idea for another post. The model will be running on your localhost, so no, you won’t be able to access it from a different network (but feel free to google how to deploy models to AWS or something like that).
I’ve gone ahead and made the following directory structure:
ML-Deploy
model / Train.py
app.py
Now if you have your Python installed through Anaconda, then you probably already have all the libraries pre-installed, except for Flask. So fire up the terminal and execute the following:
pip install Flaskpip install Flask-RESTful
That went well? Good. Let’s dive into some good stuff now.
If you are following along with the directory structure, you should open up the model/Train.py file now. The goal is to load in the Iris dataset and use a simple Decision Tree Classifier to train the model. I will use joblib library to save the model once the training is complete, and I’ll also report the accuracy score back to the user.
Nothing complex here, as machine learning isn’t the point of the article, only the model deployment. Here’s the whole script:
from sklearn import datasetsfrom sklearn.tree import DecisionTreeClassifierfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import accuracy_scorefrom sklearn.externals import joblibdef train_model(): iris_df = datasets.load_iris() x = iris_df.data y = iris_df.target X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.25) dt = DecisionTreeClassifier().fit(X_train, y_train) preds = dt.predict(X_test) accuracy = accuracy_score(y_test, preds) joblib.dump(dt, 'iris-model.model') print('Model Training Finished.\n\tAccuracy obtained: {}'.format(accuracy))
Now you’re ready to open the app.py file and do some imports. You’ll need the os module, a couple of things from Flask and Flask-RESTful, the model training script created 10 seconds ago, and the joblib to load in the trained model:
import osfrom flask import Flask, jsonify, requestfrom flask_restful import Api, Resourcefrom model.Train import train_modelfrom sklearn.externals import joblib
Now you should make an instance of Flask and Api from Flask-RESTful. Nothing complex:
app = Flask(__name__)api = Api(app)
The next thing to do is to check whether the model is already trained or not. In the Train.py you’ve declared that the model will be saved in the file iris-model.model, and if that file doesn’t exist, the model should be trained first. Once trained, you can load it in via joblib:
if not os.path.isfile('iris-model.model'): train_model()model = joblib.load('iris-model.model')
Now you’ll need to declare a class for making predictions. Flask-RESTful uses this coding convention, so your class will need to inherit from the Flask-RESTful Resource module. Inside the class, you can declare get(), post(), or any other method for handling data.
We’ll use post(), so the data isn’t passed directly through the URL. You’ll need to fetch attributes from the user input (prediction is made based on attribute value the user has entered). Then, you can call .predict() function of the loaded model. Just because the target variable of this dataset is in the form (0, 1, 2) instead of (‘Iris-setosa’, ‘Iris-versicolor’, ‘Iris-virginica’), you’ll also want to address that. Finally, you can return JSON representation of the prediction:
class MakePrediction(Resource): @staticmethod def post(): posted_data = request.get_json() sepal_length = posted_data['sepal_length'] sepal_width = posted_data['sepal_width'] petal_length = posted_data['petal_length'] petal_width = posted_data['petal_width'] prediction = model.predict([[sepal_length, sepal_width, petal_length, petal_width]])[0] if prediction == 0: predicted_class = 'Iris-setosa' elif prediction == 1: predicted_class = 'Iris-versicolor' else: predicted_class = 'Iris-virginica' return jsonify({ 'Prediction': predicted_class })
We’re almost there, so hang in tight! You’ll also need to declare a route, the part of URL which will be used to handle requests:
api.add_resource(MakePrediction, '/predict')
And the final thing is to tell Python to run the app in debug mode:
if __name__ == '__main__': app.run(debug=True)
And that’s it. You’re ready to launch the model and make predictions, either through Postman or some other tool.
Just in case you missed something, here’s the entire app.py file:
import osfrom flask import Flask, jsonify, requestfrom flask_restful import Api, Resourcefrom model.Train import train_modelfrom sklearn.externals import joblibapp = Flask(__name__)api = Api(app)if not os.path.isfile('iris-model.model'): train_model()model = joblib.load('iris-model.model')class MakePrediction(Resource): @staticmethod def post(): posted_data = request.get_json() sepal_length = posted_data['sepal_length'] sepal_width = posted_data['sepal_width'] petal_length = posted_data['petal_length'] petal_width = posted_data['petal_width'] prediction = model.predict([[sepal_length, sepal_width, petal_length, petal_width]])[0] if prediction == 0: predicted_class = 'Iris-setosa' elif prediction == 1: predicted_class = 'Iris-versicolor' else: predicted_class = 'Iris-virginica' return jsonify({ 'Prediction': predicted_class })api.add_resource(MakePrediction, '/predict')if __name__ == '__main__': app.run(debug=True)
Okay, are you ready?
Great. Navigate to the root directory (where app.py is located), fire up the terminal and execute the following:
python app.py
After a second or so you’ll get an output showing you the app is running on the localhost.
Now I will open Postman and do the following:
Change the method to POST
Enter localhost:5000/predict as the URL
Inside the Body tab choose JSON
Enter some JSON for prediction
You can then hit Send:
And voila! Almost instantly you’ll get the prediction back from your model.
I hope you’ve managed to get through this article. You should be good to go if you just copy-pasted everything, provided that you have all the necessary libraries installed.
I would strongly advise utilizing this newly acquired knowledge on your own datasets, and your own business problems. It comes in handy if you’re coding the app in some other language than Python, and are using Python just for data and machine learning related stuff.
Thanks for reading, take care.
Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you. | [
{
"code": null,
"e": 565,
"s": 172,
"text": "After reading the article you will be able to deploy machine learning models and make predictions from any programming language you want. That’s right, you can stick to Python, or you could make predictions directly inside your Android app via Java or Kot... |
Target Encoding For Multi-Class Classification | Towards Data Science | This article is in continuation of my previous article that explained how target encoding actually works. The article explained the encoding method on a binary classification task through theory and an example, and how category-encoders library gives incorrect results for multi-class target. This article shows when TargetEncoder of category_encoders fails, gives a snip of the theory behind encoding multi-class target, and provides the correct code, along with an example.
Look at this data. Color is a feature, and Target is well... target. Our aim is to encode Color based on Target.
Let’s do the usual target encoding on this.
import category_encoders as cece.TargetEncoder(smoothing=0).fit_transform(df.Color,df.Target)
Hmm, that doesn’t look right, does it? All the colors were replaced with 1. Why? Because TargetEncoder takes mean of all the Target values for each color, instead of probability.
While TargetEncoder works for the case when you have a binary target having 0 and 1s, it won’t work for two cases:
When the target is binary, but not 0/1. Such as 1 and 2s.When the target is multi-class, as in the above example.
When the target is binary, but not 0/1. Such as 1 and 2s.
When the target is multi-class, as in the above example.
So, what to do!?
Here is what the original paper by Daniele Micci-Barreca that introduced mean target encoding says for multi-class targets.
Let’s say there are n classes in the label.
The theory says, first step is to one-hot encode your label. This gives n binary columns, one corresponding to each class of the target. However, only n-1 binary columns will be linearly independent. So, any one of these columns can be dropped. Now, use the usual target encoding for each categorical feature using each binary label, one at a time. Therefore, for one categorical feature you get n-1 target encoded features. If there are k categorical features in the dataset, you get k times (n-1) features in total.
Let’s understand using an example.
Let’s continue with the previous data.
Step 1: One-hot encode the label.
enc=ce.OneHotEncoder().fit(df.Target.astype(str))y_onehot=enc.transform(df.Target.astype(str))y_onehot
Notice that Target_1 column represents presence or absence of 0 in the Target. It’s 1 if there is a 0 in Target, and 0 otherwise. Similarly, Target_2 column represents presence or absence of 1 in the Target.
Step 2: Target encode Color using each of the one-hot encoded Targets.
class_names=y_onehot.columnsfor class_ in class_names: enc=ce.TargetEncoder(smoothing=0) print(enc.fit_transform(X,y_onehot[class_]))
Step 3: If there are more categorical features other than Color, repeat step 1 and 2 for all.
And it’s done!
Thus, the dataset transforms as:
Note that for the sake of clarity, I encoded all the three Color_Target columns. If you know one-hot encoding then you know that one of the columns can be removed without any loss of information. Therefore, here we can safely remove Color_Target_3 column, without any loss of information.
You are here for the code, aren’t you!?
I give here a function, which takes as input a pandas dataframe of features, and a pandas series of the target label. The feature df can have a mixture of numeric and categorical features.
def target_encode_multiclass(X,y): #X,y are pandas df and series y=y.astype(str) #convert to string to onehot encode enc=ce.OneHotEncoder().fit(y) y_onehot=enc.transform(y) class_names=y_onehot.columns #names of onehot encoded columns X_obj=X.select_dtypes('object') #separate categorical columns X=X.select_dtypes(exclude='object') for class_ in class_names: enc=ce.TargetEncoder() enc.fit(X_obj,y_onehot[class_]) #convert all categorical temp=enc.transform(X_obj) #columns for class_ temp.columns=[str(x)+'_'+str(class_) for x in temp.columns] X=pd.concat([X,temp],axis=1) #add to original dataset return X
In this article, I pointed out what’s wrong with category_encoder’s TargetEncoder. I explained what the original paper on target encoding has to say for multi-class labels. I explained the same through an example and provided a working modular code for you to plug and play in your application.
Connect with me on LinkedIn!
Check out some of my cool projects on GitHub! | [
{
"code": null,
"e": 648,
"s": 172,
"text": "This article is in continuation of my previous article that explained how target encoding actually works. The article explained the encoding method on a binary classification task through theory and an example, and how category-encoders library gives inco... |
Scala Int isValidLong() method with example - GeeksforGeeks | 30 Jan, 2020
The isValidLong() method is utilized to return true if the specified int number is either zero or lies within the range of scala.long MinValue and MaxValue; otherwise returns false.
Method Definition: (Int_Number).isValidLong
Return Type: It returns true if the specified number is either zero or lies within the range of scala.long MinValue and MaxValue; otherwise returns false.
Example #1:
// Scala program of Int isValidLong()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying isValidLong method val result = (0).isValidLong // Displays output println(result) }}
true
Example #2:
// Scala program of Int isValidLong()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying isValidLong method val result = (5).isValidLong // Displays output println(result) }}
true
Scala
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Inheritance in Scala
Hello World in Scala
Scala | Option
How to install Scala on Windows?
Scala | Case Class and Case Object
Scala | Decision Making (if, if-else, Nested if-else, if-else if)
Scala Map get() method with example
Scala List map() method with example
Scala Sequence
Scala List exists() method with example | [
{
"code": null,
"e": 24006,
"s": 23978,
"text": "\n30 Jan, 2020"
},
{
"code": null,
"e": 24188,
"s": 24006,
"text": "The isValidLong() method is utilized to return true if the specified int number is either zero or lies within the range of scala.long MinValue and MaxValue; otherw... |
How to Create a Scatterplot in R with Multiple Variables? - GeeksforGeeks | 19 Dec, 2021
In this article, we will be looking at the way to create a scatter plot with multiple variables in the R programming language.
In this approach to create a scatter plot with multiple variables, the user needs to call the plot() function
Plot() function: This is a generic function for the plotting of R objects.
Syntax:
plot(x, y, ...)
Parameters:
x: the x coordinates of points in the plot.
y: the y coordinates of points in the plot
Points() function: It is a generic function to draw a sequence of points at the specified coordinates
Syntax:
points(x,y = NULL, type = “p”, ...)
Parameters:
x, y: coordinate vectors of points to plot.
type: character indicating the type of plotting; actually any of the types as in plot.default.
...: Further graphical parameters may also be supplied as arguments.
Example 1:
In this example, we will be creating a scatter plot of 2 different variables using the plot() and the point() function in the R programming language.
R
# Creating First variablegfg_x1 = c(9,1,8,7,7,3,2,4,5,6)gfg_y1 = c(7,4,1,5,9,6,3,3,6,9) # Creating Second variablegfg_x2 = c(4,1,5,9,7,4,5,2,8,4)gfg_y2 = c(9,1,5,7,4,1,3,6,5,2) # creating scatterplot of gfg_x1 vs. gfg_y1plot(gfg_x1,gfg_y1, col='darkgreen', pch=19) # Adding scatterplot of gfg_x2 vs gfg_y2points(gfg_x2, gfg_y2, col='red', pch=19) legend(1,9,legend=c('Variable 1', 'Variable 2'), pch=c(19, 19), col=c('darkgreen', 'red'))
Output:
Example 2:
Here, we will be creating a scatter plot of 4 different variables.
R
# Creating First variablegfg_x1 = c(9,1,8,7,7,3,2,4,5,6)gfg_y1 = c(7,4,1,5,9,6,3,3,6,9) # Creating Second variablegfg_x2 = c(4,1,5,9,7,4,5,2,8,4)gfg_y2 = c(9,1,5,7,4,1,3,6,5,2) # Creating Third variablegfg_x3 = c(6,8,5,7,4,1,6,3,2,9)gfg_y3 = c(7,4,6,1,5,6,3,5,4,1) # Creating Forth variablegfg_x4 = c(1,8,7,5,6,3,2,4,5,6)gfg_y4 = c(2,5,8,6,5,8,6,9,2,1) # creating scatterplot of gfg_x1 vs. gfg_y1plot(gfg_x1,gfg_y1, col='darkgreen', pch=19) # Adding scatterplot of gfg_x2 vs gfg_y2points(gfg_x2, gfg_y2, col='red', pch=19) # Adding scatterplot of gfg_x3 vs gfg_y3points(gfg_x3, gfg_y3, col='blue', pch=19) # Adding scatterplot of gfg_x4 vs gfg_y4points(gfg_x4, gfg_y4, col='orange', pch=19) legend('topleft',legend=c('Variable 1', 'Variable 2','Variable 3','Variable 4'), pch=c(19, 19), col=c('darkgreen', 'red','blue','orange'))
Output:
Example 3:
Here, we will be creating a scatter plot of 6 different variables.
R
# Creating First variablegfg_x1 = c(9,1,8,7,7,3,2,4,5,6)gfg_y1 = c(7,4,1,5,9,6,3,3,6,9) # Creating Second variablegfg_x2 = c(4,1,5,9,7,4,5,2,8,4)gfg_y2 = c(9,1,5,7,4,1,3,6,5,2) # Creating Third variablegfg_x3 = c(6,8,5,7,4,1,6,3,2,9)gfg_y3 = c(7,4,6,1,5,6,3,5,4,1) # Creating Forth variablegfg_x4 = c(1,8,7,5,6,3,2,4,5,6)gfg_y4 = c(2,5,8,6,5,8,6,9,2,1) # Creating Fifth variablegfg_x5 = c(8,9,5,6,2,4,4,6,4,1)gfg_y5 = c(3,5,7,4,5,6,4,6,5,7) # Creating Sixth variablegfg_x6 = c(4,5,6,3,2,2,5,5,9,6)gfg_y6 = c(7,8,5,6,3,5,9,4,5,7) # creating scatterplot of gfg_x1 vs. gfg_y1plot(gfg_x1,gfg_y1, col='darkgreen', pch=19) # Adding scatterplot of gfg_x2 vs gfg_y2points(gfg_x2, gfg_y2, col='red', pch=19) # Adding scatterplot of gfg_x3 vs gfg_y3points(gfg_x3, gfg_y3, col='blue', pch=19) # Adding scatterplot of gfg_x4 vs gfg_y4points(gfg_x4, gfg_y4, col='orange', pch=19) # Adding scatterplot of gfg_x5 vs gfg_y5points(gfg_x5, gfg_y5, col='purple', pch=19) # Adding scatterplot of gfg_x6 vs gfg_y6points(gfg_x6, gfg_y6, col='black', pch=19) legend('topleft',legend=c('Variable 1', 'Variable 2','Variable 3','Variable 4', 'Variable 5','Variable 6'), pch=c(19, 19), col=c('darkgreen', 'red','blue','orange','purple','black'))
Output:
Picked
R-Charts
R-Graphs
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
Data Visualization in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
Logistic Regression in R Programming
How to Split Column Into Multiple Columns in R DataFrame?
Control Statements in R Programming
How to import an Excel File into R ?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column? | [
{
"code": null,
"e": 25162,
"s": 25134,
"text": "\n19 Dec, 2021"
},
{
"code": null,
"e": 25289,
"s": 25162,
"text": "In this article, we will be looking at the way to create a scatter plot with multiple variables in the R programming language."
},
{
"code": null,
"e":... |
TCL script to demonstrate procedures - GeeksforGeeks | 02 Jun, 2021
In this article, we will know how to use procedures in TCL. Procedures are just like functions we use in any other programming language such as C, Java, Python, etc. Just like functions, procedures take arguments and return some value. Let’s go through a simple program that calls procedures to print add, subtract, multiply, divide, and modulo two numbers step-by-step.
Pre-requisite –If you want to know the basics of TCL script then kindly go through this article https://www.geeksforgeeks.org/basics-of-ns2-and-otcltcl-script/.
Overview:We will try to understand the syntax of a procedure in TCL by exploring the code block-by-block. Furthermore, we will also look at the syntax for procedures in C programming to compare with and understand better.
TCL script to demonstrate procedures :Let’s discuss the following steps as follows.
Step-1 : Let’s first define our procedures. We do that using the proc keyword. The procedures addnumbers {}, sub numbers {}, mulnumbers {}, divnumbers {} and modnumbers {} are created to compute the sum, difference, product, division, and modulo of two numbers respectively.
TCL script -
//Addition
proc addnumbers { a b } {
return [expr $a + $b]
}
//Subtraction
proc subnumbers { a b } {
return [expr $a - $b]
}
//Multiplication
proc mulnumbers { a b } {
return [expr $a * $b]
}
//Division
proc divnumbers { a b } {
return [expr $a / $b]
}
//Modulus
proc modnumbers { a b } {
return [expr $a % $b]
}
As shown above, the syntax can be generalized as follows.
proc procedurename {arguments} {
#body of the procedure
}
Note – The syntax has to be exactly as shown above. If you neglect the spaces or type the opening curly brace in a new line, the result will be an error. The same syntax is followed by all conditional statements in TCL. Also note that procedures like functions, may or may not have a return type. Now let’s look at how the above set of functions would look like in C programming.
C
//Additionint addnumbers(int a, int b) { return a + b; } //Subtractionint subnumbers(int a, int b) { return a - b; } //Multiplicationint mulnumbers(int a, int b) { return a * b; } //Divisionfloat divnumbers(float a, float b) { return a / b; } //Modulusint modnumbers(int a, int b) { return a % b; }
Step-2 : The next step is to read two numbers a and b using gets.
puts "Enter the first number"
gets stdin a
puts "Enter the second number"
gets stdin b
Step-3 : The final step is to print all the required values. Here, we will also look at the syntax in C programming to understand how we call a function in TCL.
puts "The sum of two numbers is [addnumbers $a $b]"
puts "The difference between the two numbers is [subnumbers $a $b]"
puts "The product of the two numbers is [subnumbers $a $b]"
puts "The division of the two numbers is [divnumbers $a $b]"
puts "The modulo of the two numbers is [modnumbers $a $b]"
So, we saw above the syntax to call a procedure would look like the following.
[procedurename $argument1 $argument2 .....]
Now let’s compare with the syntax in C programming to call a function.
functionname(argument1,argument2,.....)
Step-4 :Finally, we view the entire code with the output as follows.
Code –
//Addition
proc addnumbers {a b} {
return [expr $a+$b]
}
//Subtraction
proc subnumbers {a b} {
return [expr $a-$b]
}
//Multiplication
proc mulnumbers {a b} {
return [expr $a*$b]
}
//Division
proc divnumbers {a b} {
return [expr $a/$b]
}
//Modulus
proc modnumbers {a b} {
return [expr $a%$b]
}
//Input-1
puts "Enter the first number"
gets stdin a
//Input-2
puts "Enter the second number"
gets stdin b
//called procedures
puts "The sum of two numbers is [addnumbers $a $b]"
puts "The difference between the two numbers is [subnumbers $a $b]"
puts "The product of the two numbers is [subnumbers $a $b]"
puts "The division of the two numbers is [divnumbers $a $b]"
puts "The modulo of the two numbers is [modnumbers $a $b]"
Output :
Output for a=123 and b=486
zyeshwanth
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Advanced Encryption Standard (AES)
Active and Passive attacks in Information Security
Cryptography and its Types
Multiple Access Protocols in Computer Network
Architecture of Internet of Things (IoT)
Bluetooth
Intrusion Detection System (IDS)
GSM in Wireless Communication
Congestion Control in Computer Networks
TCP Congestion Control | [
{
"code": null,
"e": 24119,
"s": 24091,
"text": "\n02 Jun, 2021"
},
{
"code": null,
"e": 24490,
"s": 24119,
"text": "In this article, we will know how to use procedures in TCL. Procedures are just like functions we use in any other programming language such as C, Java, Python, et... |
fmt.Fprint() Function in Golang With Examples - GeeksforGeeks | 05 May, 2020
In Go language, fmt package implements formatted I/O with functions analogous to C’s printf() and scanf() function. The fmt.Fprint() function in Go language formats using the default formats for its operands and writes to w. Here Spaces are added between operands when any string is not used as a parameter. Moreover, this function is defined under the fmt package. Here, you need to import the “fmt” package in order to use these functions.
Syntax:
func Fprint(w io.Writer, a ...interface{}) (n int, err error)
Parameters: This function accepts two parameters which are illustrated below:
w io.Writer: This is the specified standard input or output.
a ...interface{}: This is containing some strings or constant variables used in the code.
Return Value: It returns the number of bytes written and any write error encountered.
Example 1:
// Golang program to illustrate the usage of// fmt.Fprint() function // Including the main packagepackage main // Importing fmt and osimport ( "fmt" "os") // Calling mainfunc main() { // Declaring some const variables const name, dept = "GeeksforGeeks", "CS" // Calling Fprint() function which returns // "n" as the number of bytes written and // "err" as any error ancountered n, err := fmt.Fprint(os.Stdout, name, " is a ", dept, " portal.\n") // Printing the number of bytes written fmt.Print(n, " bytes written.\n") // Printing if any error encountered fmt.Print(err) }
Output:
GeeksforGeeks is a CS portal.
30 bytes written.
<nil>
Example 2:
// Golang program to illustrate the usage of// fmt.Fprint() function // Including the main packagepackage main // Importing fmt and osimport ( "fmt" "os") // Calling mainfunc main() { // Declaring some const variables const num1, num2, num3 = "a", "b", "c" // Calling Fprint() function which returns // "n" as the number of bytes written and // "err" as any error encountered n, err := fmt.Fprint(os.Stdout, num1, num2, num3, "\n") // Printing the number of bytes written fmt.Print(n, " bytes written.\n") // Printing if any error encountered fmt.Print(err) }
Output:
abc
4 bytes written.
<nil>
In the above code, the constant variables used are strings hence spaces are not added in between two strings shown above in the output.
Example 3:
// Golang program to illustrate the usage of// fmt.Fprint() function // Including the main packagepackage main // Importing fmt and osimport ( "fmt" "os") // Calling mainfunc main() { // Declaring some const variables const num1, num2, num3 = 5, 15, 15 // Calling Fprint() function which returns // "n" as the number of bytes written and // "err" as any error encountered n, err := fmt.Fprint(os.Stdout, num1, num2, num3, "\n") // Printing the number of bytes written fmt.Print(n, " bytes written.\n") // Printing if any error encountered fmt.Print(err) }
Output:
5 15 15
8 bytes written.
<nil>
In the above code, the constant variables used are numbers hence spaces are added in between two numbers shown above in the output.
Golang-fmt
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Parse JSON in Golang?
Defer Keyword in Golang
time.Parse() Function in Golang With Examples
Anonymous function in Go Language
Time Durations in Golang
Strings in Golang
How to convert a string in uppercase in Golang?
Loops in Go Language
Structures in Golang
Class and Object in Golang | [
{
"code": null,
"e": 24380,
"s": 24352,
"text": "\n05 May, 2020"
},
{
"code": null,
"e": 24822,
"s": 24380,
"text": "In Go language, fmt package implements formatted I/O with functions analogous to C’s printf() and scanf() function. The fmt.Fprint() function in Go language format... |
Object Oriented Python - Quick Guide | Programming languages are emerging constantly, and so are different methodologies.Object-oriented programming is one such methodology that has become quite popular over past few years.
This chapter talks about the features of Python programming language that makes it an object-oriented programming language.
Python can be characterized under object-oriented programming methodologies. The following image shows the characteristics of various programming languages. Observe the features of Python that makes it object-oriented.
Object Oriented means directed towards objects. In other words, it means functionally directed towards modelling objects. This is one of the many techniques used for modelling complex systems by describing a collection of interacting objects via their data and behavior.
Python, an Object Oriented programming (OOP), is a way of programming that focuses on using objects and classes to design and build applications.. Major pillars of Object Oriented Programming (OOP) are Inheritance, Polymorphism, Abstraction, ad Encapsulation.
Object Oriented Analysis(OOA) is the process of examining a problem, system or task and identifying the objects and interactions between them.
Python was designed with an object-oriented approach. OOP offers the following advantages −
Provides a clear program structure, which makes it easy to map real world problems and their solutions.
Provides a clear program structure, which makes it easy to map real world problems and their solutions.
Facilitates easy maintenance and modification of existing code.
Facilitates easy maintenance and modification of existing code.
Enhances program modularity because each object exists independently and new features can be added easily without disturbing the existing ones.
Enhances program modularity because each object exists independently and new features can be added easily without disturbing the existing ones.
Presents a good framework for code libraries where supplied components can be easily adapted and modified by the programmer.
Presents a good framework for code libraries where supplied components can be easily adapted and modified by the programmer.
Imparts code reusability
Imparts code reusability
Procedural based programming is derived from structural programming based on the concepts of functions/procedure/routines. It is easy to access and change the data in procedural oriented programming. On the other hand, Object Oriented Programming (OOP) allows decomposition of a problem into a number of units called objects and then build the data and functions around these objects. It emphasis more on the data than procedure or functions. Also in OOP, data is hidden and cannot be accessed by external procedure.
The table in the following image shows the major differences between POP and OOP approach.
Difference between Procedural Oriented Programming(POP)vs. Object Oriented Programming(OOP).
Object Oriented Programming (OOP) is based on the concept of objects rather than actions, and data rather than logic. In order for a programming language to be object-oriented, it should have a mechanism to enable working with classes and objects as well as the implementation and usage of the fundamental object-oriented principles and concepts namely inheritance, abstraction, encapsulation and polymorphism.
Let us understand each of the pillars of object-oriented programming in brief −
This property hides unnecessary details and makes it easier to manage the program structure. Each object’s implementation and state are hidden behind well-defined boundaries and that provides a clean and simple interface for working with them. One way to accomplish this is by making the data private.
Inheritance, also called generalization, allows us to capture a hierarchal relationship between classes and objects. For instance, a ‘fruit’ is a generalization of ‘orange’. Inheritance is very useful from a code reuse perspective.
This property allows us to hide the details and expose only the essential features of a concept or object. For example, a person driving a scooter knows that on pressing a horn, sound is emitted, but he has no idea about how the sound is actually generated on pressing the horn.
Poly-morphism means many forms. That is, a thing or action is present in different forms or ways. One good example of polymorphism is constructor overloading in classes.
The heart of Python programming is object and OOP, however you need not restrict yourself to use the OOP by organizing your code into classes. OOP adds to the whole design philosophy of Python and encourages a clean and pragmatic way to programming. OOP also enables in writing bigger and complex programs.
When working on Modules, note the following points −
A Python module is a package to encapsulate reusable code.
A Python module is a package to encapsulate reusable code.
Modules reside in a folder with a __init__.py file on it.
Modules reside in a folder with a __init__.py file on it.
Modules contain functions and classes.
Modules contain functions and classes.
Modules are imported using the import keyword.
Modules are imported using the import keyword.
Recall that a dictionary is a key-value pair. That means if you have a dictionary with a key EmployeID and you want to retrieve it, then you will have to use the following lines of code −
employee = {“EmployeID”: “Employee Unique Identity!”}
print (employee [‘EmployeID])
You will have to work on modules with the following process −
A module is a Python file with some functions or variables in it.
A module is a Python file with some functions or variables in it.
Import the file you need.
Import the file you need.
Now, you can access the functions or variables in that module with the ‘.’ (dot) Operator.
Now, you can access the functions or variables in that module with the ‘.’ (dot) Operator.
Consider a module named employee.py with a function in it called employee. The code of the function is given below −
# this goes in employee.py
def EmployeID():
print (“Employee Unique Identity!”)
Now import the module and then access the function EmployeID −
import employee
employee. EmployeID()
You can insert a variable in it named Age, as shown −
def EmployeID():
print (“Employee Unique Identity!”)
# just a variable
Age = “Employee age is **”
Now, access that variable in the following way −
import employee
employee.EmployeID()
print(employee.Age)
Now, let’s compare this to dictionary −
Employee[‘EmployeID’] # get EmployeID from employee
Employee.employeID() # get employeID from the module
Employee.Age # get access to variable
Notice that there is common pattern in Python −
Take a key = value style container
Take a key = value style container
Get something out of it by the key’s name
Get something out of it by the key’s name
When comparing module with a dictionary, both are similar, except with the following −
In the case of the dictionary, the key is a string and the syntax is [key].
In the case of the dictionary, the key is a string and the syntax is [key].
In the case of the module, the key is an identifier, and the syntax is .key.
In the case of the module, the key is an identifier, and the syntax is .key.
Module is a specialized dictionary that can store Python code so you can get to it with the ‘.’ Operator. A class is a way to take a grouping of functions and data and place them inside a container so you can access them with the ‘.‘operator.
If you have to create a class similar to the employee module, you can do it using the following code −
class employee(object):
def __init__(self):
self. Age = “Employee Age is ##”
def EmployeID(self):
print (“This is just employee unique identity”)
Note − Classes are preferred over modules because you can reuse them as they are and without much interference. While with modules, you have only one with the entire program.
A class is like a mini-module and you can import in a similar way as you do for classes, using the concept called instantiate. Note that when you instantiate a class, you get an object.
You can instantiate an object, similar to calling a class like a function, as shown −
this_obj = employee() # Instantiatethis_obj.EmployeID() # get EmployeId from the class
print(this_obj.Age) # get variable Age
You can do this in any of the following three ways −
# dictionary style
Employee[‘EmployeID’]
# module style
Employee.EmployeID()
Print(employee.Age)
# Class style
this_obj = employee()
this_obj.employeID()
Print(this_obj.Age)
This chapter will explain in detail about setting up the Python environment on your local computer.
Before you proceed with learning further on Python, we suggest you to check whether the following prerequisites are met −
Latest version of Python is installed on your computer
Latest version of Python is installed on your computer
An IDE or text editor is installed
An IDE or text editor is installed
You have basic familiarity to write and debug in Python, that is you can do the
following in Python −
Able to write and run Python programs.
Debug programs and diagnose errors.
Work with basic data types.
Write for loops, while loops, and if statements
Code functions
You have basic familiarity to write and debug in Python, that is you can do the
following in Python −
Able to write and run Python programs.
Able to write and run Python programs.
Debug programs and diagnose errors.
Debug programs and diagnose errors.
Work with basic data types.
Work with basic data types.
Write for loops, while loops, and if statements
Write for loops, while loops, and if statements
Code functions
Code functions
If you don’t have any programming language experience, you can find lots of beginner tutorials in Python on
The following steps show you in detail how to install Python on your local computer −
Step 1 − Go to the official Python website https://www.python.org/, click on the Downloads menu and choose the latest or any stable version of your choice.
Step 2 − Save the Python installer exe file that you’re downloading and once you have downloaded it, open it. Click on Run and choose Next option by default and finish the installation.
Step 3 − After you have installed, you should now see the Python menu as shown in the image below. Start the program by choosing IDLE (Python GUI).
This will start the Python shell. Type in simple commands to check the installation.
An Integrated Development Environment is a text editor geared towards software
development. You will have to install an IDE to control the flow of your programming and to group projects together when working on Python. Here are some of IDEs avaialable
online. You can choose one at your convenience.
Pycharm IDE
Komodo IDE
Eric Python IDE
Note − Eclipse IDE is mostly used in Java, however it has a Python plugin.
Pycharm, the cross-platform IDE is one of the most popular IDE currently available. It provides coding assistance and analysis with code completion, project and code navigation, integrated unit testing, version control integration, debugging and much more
Languages Supported − Python, HTML, CSS, JavaScript, Coffee Script, TypeScript, Cython,AngularJS, Node.js, template languages.
PyCharm offers the following features and benefits for its users −
Cross platform IDE compatible with Windows, Linux, and Mac OS
Includes Django IDE, plus CSS and JavaScript support
Includes thousands of plugins, integrated terminal and version control
Integrates with Git, SVN and Mercurial
Offers intelligent editing tools for Python
Easy integration with Virtualenv, Docker and Vagrant
Simple navigation and search features
Code analysis and refactoring
Configurable injections
Supports tons of Python libraries
Contains Templates and JavaScript debuggers
Includes Python/Django debuggers
Works with Google App Engine, additional frameworks and libraries.
Has customizable UI, VIM emulation available
It is a polyglot IDE which supports 100+ languages and basically for dynamic languages such as Python, PHP and Ruby. It is a commercial IDE available for 21 days free trial with full functionality. ActiveState is the software company managing the development of the Komodo IDE. It also offers a trimmed version of Komodo known as Komodo Edit for simple programming tasks.
This IDE contains all kinds of features from most basic to advanced level. If you are a student or a freelancer, then you can buy it almost half of the actual price. However, it’s completely free for teachers and professors from recognized institutions and universities.
It got all the features you need for web and mobile development, including support for all your languages and frameworks.
The download links for Komodo Edit(free version) and Komodo IDE(paid version) are as
given here −
Komodo Edit (free)
Komodo IDE (paid)
Powerful IDE with support for Perl, PHP, Python, Ruby and many more.
Cross-Platform IDE.
It includes basic features like integrated debugger support, auto complete, Document Object Model(DOM) viewer, code browser, interactive shells, breakpoint configuration,
code profiling, integrated unit testing. In short, it is a professional IDE with a host of productivity-boosting features.
It is an open-source IDE for Python and Ruby. Eric is a full featured editor and IDE, written in Python. It is based on the cross platform Qt GUI toolkit, integrating the highly flexible Scintilla editor control. The IDE is very much configurable and one can choose what to use and what not. You can download Eric IDE from below link:
Great indentation, error highlighting.
Code assistance
Code completion
Code cleanup with PyLint
Quick search
Integrated Python debugger.
You may not always need an IDE. For tasks such as learning to code with Python or Arduino, or when working on a quick script in shell script to help you automate some tasks a simple and light weight code-centric text editor will do. Also many text editors offer features such as syntax highlighting and in-program script execution, similar to IDEs. Some of the text editors are given here −
Atom
Sublime Text
Notepad++
Atom is a hackable text editor built by the team of GitHub. It is a free and open source text and code editor which means that all the code is available for you to read, modify for your own use and even contribute improvements. It is a cross-platform text editor compatible for macOS, Linux, and Microsoft Windows with support for plug-ins written in Node.js and embedded Git Control.
C/C++, C#, CSS, CoffeeScript, HTML, JavaScript, Java, JSON, Julia, Objective-C, PHP, Perl, Python, Ruby on Rails, Ruby, Shell script, Scala, SQL, XML, YAML and many more.
Sublime text is a proprietary software and it offers you a free trial version
to test it before you purchase it. According to stackoverflow.com, it’s the fourth most popular Development Environment.
Some of the advantages it provides is its incredible speed, ease of use and community support. It also supports many programming languages and mark-up languages, and functions can be added by users with plugins, typically community-built and maintained under free-software licenses.
Python, Ruby, JavaScript etc.
Customize key bindings, menus, snippets, macros, completions and more.
Customize key bindings, menus, snippets, macros, completions and more.
Auto completion feature
Auto completion feature
Quickly Insert Text & code with sublime text snippets using snippets, field
markers and place holders
Opens Quickly
Opens Quickly
Cross Platform support for Mac, Linux and Windows.
Cross Platform support for Mac, Linux and Windows.
Jump the cursor to where you want to go
Jump the cursor to where you want to go
Select Multiple Lines, Words and Columns
Select Multiple Lines, Words and Columns
It’s a free source code editor and Notepad replacement that supports several languages from Assembly to XML and including Python. Running in the MS windows environment, its use is governed by GPL license. In addition to syntax highlighting, Notepad++ has some features that are particularly useful to coders.
Syntax highlighting and syntax folding
PCRE (Perl Compatible Regular Expression) Search/Replace
Entirely customizable GUI
SAuto completion
Tabbed editing
Multi-View
Multi-Language environment
Launchable with different arguments
Almost every language (60+ languages) like Python, C, C++, C#, Java etc.
Python data structures are very intuitive from a syntax point of view and they offer a large choice of operations. You need to choose Python data structure depending on what the data involves, if it needs to be modified, or if it is a fixed data and what access type is required, such as at the beginning/end/random etc.
A List represents the most versatile type of data structure in Python. A list is a container which holds comma-separated values (items or elements) between square brackets. Lists are helpful when we want to work with multiple related values. As lists keep data together, we can perform the same methods and operations on multiple values at once. Lists indices start from zero and unlike strings, lists are mutable.
>>>
>>> # Any Empty List
>>> empty_list = []
>>>
>>> # A list of String
>>> str_list = ['Life', 'Is', 'Beautiful']
>>> # A list of Integers
>>> int_list = [1, 4, 5, 9, 18]
>>>
>>> #Mixed items list
>>> mixed_list = ['This', 9, 'is', 18, 45.9, 'a', 54, 'mixed', 99, 'list']
>>> # To print the list
>>>
>>> print(empty_list)
[]
>>> print(str_list)
['Life', 'Is', 'Beautiful']
>>> print(type(str_list))
<class 'list'>
>>> print(int_list)
[1, 4, 5, 9, 18]
>>> print(mixed_list)
['This', 9, 'is', 18, 45.9, 'a', 54, 'mixed', 99, 'list']
Each item of a list is assigned a number – that is the index or position of that number.Indexing always start from zero, the second index is one and so forth. To access items in a list, we can use these index numbers within a square bracket. Observe the following code for example −
>>> mixed_list = ['This', 9, 'is', 18, 45.9, 'a', 54, 'mixed', 99, 'list']
>>>
>>> # To access the First Item of the list
>>> mixed_list[0]
'This'
>>> # To access the 4th item
>>> mixed_list[3]
18
>>> # To access the last item of the list
>>> mixed_list[-1]
'list'
Empty Objects are the simplest and most basic Python built-in types. We have used them multiple times without noticing and have extended it to every class we have created. The main purpose to write an empty class is to block something for time being and later extend and add a behavior to it.
To add a behavior to a class means to replace a data structure with an object and change all references to it. So it is important to check the data, whether it is an object in disguise, before you create anything. Observe the following code for better understanding:
>>> #Empty objects
>>>
>>> obj = object()
>>> obj.x = 9
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
obj.x = 9
AttributeError: 'object' object has no attribute 'x'
So from above, we can see it’s not possible to set any attributes on an object that was instantiated directly. When Python allows an object to have arbitrary attributes, it takes a certain amount of system memory to keep track of what attributes each object has, for
storing both the attribute name and its value. Even if no attributes are stored, a certain amount of memory is allocated for potential new attributes.
So Python disables arbitrary properties on object and several other built-ins, by default.
>>> # Empty Objects
>>>
>>> class EmpObject:
pass
>>> obj = EmpObject()
>>> obj.x = 'Hello, World!'
>>> obj.x
'Hello, World!'
Hence, if we want to group properties together, we could store them in an empty object as shown in the code above. However, this method is not always suggested. Remember
that classes and objects should only be used when you want to specify both data and
behaviors.
Tuples are similar to lists and can store elements. However, they are immutable, so we cannot add, remove or replace objects. The primary benefits tuple provides because of its immutability is that we can use them as keys in dictionaries, or in other locations where
an object requires a hash value.
Tuples are used to store data, and not behavior. In case you require behavior to
manipulate a tuple, you need to pass the tuple into a function(or method on another
object) that performs the action.
As tuple can act as a dictionary key, the stored values are different from each other. We can create a tuple by separating the values with a comma. Tuples are wrapped in parentheses but not mandatory. The following code shows two identical assignments .
>>> stock1 = 'MSFT', 95.00, 97.45, 92.45
>>> stock2 = ('MSFT', 95.00, 97.45, 92.45)
>>> type (stock1)
<class 'tuple'>
>>> type(stock2)
<class 'tuple'>
>>> stock1 == stock2
True
>>>
Tuples are very similar to list except that the whole set of elements are enclosed in parentheses instead of square brackets.
Just like when you slice a list, you get a new list and when you slice a tuple, you get a new
tuple.
>>> tupl = ('Tuple','is', 'an','IMMUTABLE', 'list')
>>> tupl
('Tuple', 'is', 'an', 'IMMUTABLE', 'list')
>>> tupl[0]
'Tuple'
>>> tupl[-1]
'list'
>>> tupl[1:3]
('is', 'an')
The following code shows the methods in Python tuples −
>>> tupl
('Tuple', 'is', 'an', 'IMMUTABLE', 'list')
>>> tupl.append('new')
Traceback (most recent call last):
File "<pyshell#148>", line 1, in <module>
tupl.append('new')
AttributeError: 'tuple' object has no attribute 'append'
>>> tupl.remove('is')
Traceback (most recent call last):
File "<pyshell#149>", line 1, in <module>
tupl.remove('is')
AttributeError: 'tuple' object has no attribute 'remove'
>>> tupl.index('list')
4
>>> tupl.index('new')
Traceback (most recent call last):
File "<pyshell#151>", line 1, in <module>
tupl.index('new')
ValueError: tuple.index(x): x not in tuple
>>> "is" in tupl
True
>>> tupl.count('is')
1
From the code shown above, we can understand that tuples are immutable and hence −
You cannot add elements to a tuple.
You cannot add elements to a tuple.
You cannot append or extend a method.
You cannot append or extend a method.
You cannot remove elements from a tuple.
You cannot remove elements from a tuple.
Tuples have no remove or pop method.
Tuples have no remove or pop method.
Count and index are the methods available in a tuple.
Count and index are the methods available in a tuple.
Dictionary is one of the Python’s built-in data types and it defines one-to-one relationships
between keys and values.
Observe the following code to understand about defining a dictionary −
>>> # empty dictionary
>>> my_dict = {}
>>>
>>> # dictionary with integer keys
>>> my_dict = { 1:'msft', 2: 'IT'}
>>>
>>> # dictionary with mixed keys
>>> my_dict = {'name': 'Aarav', 1: [ 2, 4, 10]}
>>>
>>> # using built-in function dict()
>>> my_dict = dict({1:'msft', 2:'IT'})
>>>
>>> # From sequence having each item as a pair
>>> my_dict = dict([(1,'msft'), (2,'IT')])
>>>
>>> # Accessing elements of a dictionary
>>> my_dict[1]
'msft'
>>> my_dict[2]
'IT'
>>> my_dict['IT']
Traceback (most recent call last):
File "<pyshell#177>", line 1, in <module>
my_dict['IT']
KeyError: 'IT'
>>>
From the above code we can observe that:
First we create a dictionary with two elements and assign it to the variable
my_dict. Each element is a key-value pair, and the whole set of elements is
enclosed in curly braces.
First we create a dictionary with two elements and assign it to the variable
my_dict. Each element is a key-value pair, and the whole set of elements is
enclosed in curly braces.
The number 1 is the key and msft is its value. Similarly, 2 is the key and IT is its
value.
The number 1 is the key and msft is its value. Similarly, 2 is the key and IT is its
value.
You can get values by key, but not vice-versa. Thus when we try my_dict[‘IT’] ,
it raises an exception, because IT is not a key.
You can get values by key, but not vice-versa. Thus when we try my_dict[‘IT’] ,
it raises an exception, because IT is not a key.
Observe the following code to understand about modifying a dictionary −
>>> # Modifying a Dictionary
>>>
>>> my_dict
{1: 'msft', 2: 'IT'}
>>> my_dict[2] = 'Software'
>>> my_dict
{1: 'msft', 2: 'Software'}
>>>
>>> my_dict[3] = 'Microsoft Technologies'
>>> my_dict
{1: 'msft', 2: 'Software', 3: 'Microsoft Technologies'}
From the above code we can observe that −
You cannot have duplicate keys in a dictionary. Altering the value of an existing key will delete the old value.
You cannot have duplicate keys in a dictionary. Altering the value of an existing key will delete the old value.
You can add new key-value pairs at any time.
You can add new key-value pairs at any time.
Dictionaries have no concept of order among elements. They are simple unordered collections.
Dictionaries have no concept of order among elements. They are simple unordered collections.
Observe the following code to understand about mixing data types in a dictionary −
>>> # Mixing Data Types in a Dictionary
>>>
>>> my_dict
{1: 'msft', 2: 'Software', 3: 'Microsoft Technologies'}
>>> my_dict[4] = 'Operating System'
>>> my_dict
{1: 'msft', 2: 'Software', 3: 'Microsoft Technologies', 4: 'Operating System'}
>>> my_dict['Bill Gates'] = 'Owner'
>>> my_dict
{1: 'msft', 2: 'Software', 3: 'Microsoft Technologies', 4: 'Operating System',
'Bill Gates': 'Owner'}
From the above code we can observe that −
Not just strings but dictionary value can be of any data type including strings, integers, including the dictionary itself.
Not just strings but dictionary value can be of any data type including strings, integers, including the dictionary itself.
Unlike dictionary values, dictionary keys are more restricted, but can be of any type like strings, integers or any other.
Unlike dictionary values, dictionary keys are more restricted, but can be of any type like strings, integers or any other.
Observe the following code to understand about deleting items from a dictionary −
>>> # Deleting Items from a Dictionary
>>>
>>> my_dict
{1: 'msft', 2: 'Software', 3: 'Microsoft Technologies', 4: 'Operating System',
'Bill Gates': 'Owner'}
>>>
>>> del my_dict['Bill Gates']
>>> my_dict
{1: 'msft', 2: 'Software', 3: 'Microsoft Technologies', 4: 'Operating System'}
>>>
>>> my_dict.clear()
>>> my_dict
{}
From the above code we can observe that −
del − lets you delete individual items from a dictionary by key.
del − lets you delete individual items from a dictionary by key.
clear − deletes all items from a dictionary.
clear − deletes all items from a dictionary.
Set() is an unordered collection with no duplicate elements. Though individual items are immutable, set itself is mutable, that is we can add or remove elements/items from the set. We can perform mathematical operations like union, intersection etc. with set.
Though sets in general can be implemented using trees, set in Python can be implemented using a hash table. This allows it a highly optimized method for checking whether a specific
element is contained in the set
A set is created by placing all the items (elements) inside curly braces {}, separated by comma or by using the built-in function set(). Observe the following lines of code −
>>> #set of integers
>>> my_set = {1,2,4,8}
>>> print(my_set)
{8, 1, 2, 4}
>>>
>>> #set of mixed datatypes
>>> my_set = {1.0, "Hello World!", (2, 4, 6)}
>>> print(my_set)
{1.0, (2, 4, 6), 'Hello World!'}
>>>
Observe the following code to understand about methods for sets −
>>> >>> #METHODS FOR SETS
>>>
>>> #add(x) Method
>>> topics = {'Python', 'Java', 'C#'}
>>> topics.add('C++')
>>> topics
{'C#', 'C++', 'Java', 'Python'}
>>>
>>> #union(s) Method, returns a union of two set.
>>> topics
{'C#', 'C++', 'Java', 'Python'}
>>> team = {'Developer', 'Content Writer', 'Editor','Tester'}
>>> group = topics.union(team)
>>> group
{'Tester', 'C#', 'Python', 'Editor', 'Developer', 'C++', 'Java', 'Content
Writer'}
>>> # intersets(s) method, returns an intersection of two sets
>>> inters = topics.intersection(team)
>>> inters
set()
>>>
>>> # difference(s) Method, returns a set containing all the elements of
invoking set but not of the second set.
>>>
>>> safe = topics.difference(team)
>>> safe
{'Python', 'C++', 'Java', 'C#'}
>>>
>>> diff = topics.difference(group)
>>> diff
set()
>>> #clear() Method, Empties the whole set.
>>> group.clear()
>>> group
set()
>>>
Observe the following code to understand about operators for sets −
>>> # PYTHON SET OPERATIONS
>>>
>>> #Creating two sets
>>> set1 = set()
>>> set2 = set()
>>>
>>> # Adding elements to set
>>> for i in range(1,5):
set1.add(i)
>>> for j in range(4,9):
set2.add(j)
>>> set1
{1, 2, 3, 4}
>>> set2
{4, 5, 6, 7, 8}
>>>
>>> #Union of set1 and set2
>>> set3 = set1 | set2 # same as set1.union(set2)
>>> print('Union of set1 & set2: set3 = ', set3)
Union of set1 & set2: set3 = {1, 2, 3, 4, 5, 6, 7, 8}
>>>
>>> #Intersection of set1 & set2
>>> set4 = set1 & set2 # same as set1.intersection(set2)
>>> print('Intersection of set1 and set2: set4 = ', set4)
Intersection of set1 and set2: set4 = {4}
>>>
>>> # Checking relation between set3 and set4
>>> if set3 > set4: # set3.issuperset(set4)
print('Set3 is superset of set4')
elif set3 < set4: #set3.issubset(set4)
print('Set3 is subset of set4')
else: #set3 == set4
print('Set 3 is same as set4')
Set3 is superset of set4
>>>
>>> # Difference between set3 and set4
>>> set5 = set3 - set4
>>> print('Elements in set3 and not in set4: set5 = ', set5)
Elements in set3 and not in set4: set5 = {1, 2, 3, 5, 6, 7, 8}
>>>
>>> # Check if set4 and set5 are disjoint sets
>>> if set4.isdisjoint(set5):
print('Set4 and set5 have nothing in common\n')
Set4 and set5 have nothing in common
>>> # Removing all the values of set5
>>> set5.clear()
>>> set5 set()
In this chapter, we will discuss object oriented terms and programming concepts in detail.Class is a just a factory for an instance. This factory contains the blueprint which describes
how to make the instances. An instances or object are constructed from the class. In most cases, we can have more than one instances of a class. Every instance has a set of attribute and these attributes are defined in a class, so every instance of a particular class is expected to have the same attributes.
A class will let you bundle together the behavior and state of an object. Observe the
following diagram for better understanding −
The following points are worth notable when discussing class bundles −
The word behavior is identical to function – it is a piece of code that does something (or implements a behavior)
The word behavior is identical to function – it is a piece of code that does something (or implements a behavior)
The word state is identical to variables – it is a place to store values within a class.
The word state is identical to variables – it is a place to store values within a class.
When we assert a class behavior and state together, it means that a class packages functions and variables.
When we assert a class behavior and state together, it means that a class packages functions and variables.
In Python, creating a method defines a class behavior. The word method is the OOP name given to a function that is defined within a class. To sum up −
Class functions − is synonym for methods
Class functions − is synonym for methods
Class variables − is synonym for name attributes.
Class variables − is synonym for name attributes.
Class − a blueprint for an instance with exact behavior.
Class − a blueprint for an instance with exact behavior.
Object − one of the instances of the class, perform functionality defined in the class.
Object − one of the instances of the class, perform functionality defined in the class.
Type − indicates the class the instance belongs to
Type − indicates the class the instance belongs to
Attribute − Any object value: object.attribute
Attribute − Any object value: object.attribute
Method − a “callable attribute” defined in the class
Method − a “callable attribute” defined in the class
Observe the following piece of code for example −
var = “Hello, John”
print( type (var)) # < type ‘str’> or <class 'str'>
print(var.upper()) # upper() method is called, HELLO, JOHN
The following code shows how to create our first class and then its instance.
class MyClass(object):
pass
# Create first instance of MyClass
this_obj = MyClass()
print(this_obj)
# Another instance of MyClass
that_obj = MyClass()
print (that_obj)
Here we have created a class called MyClass and which does not do any task. The argument object in MyClass class involves class inheritance and will be discussed in later chapters. pass in the above code indicates that this block is empty, that is it is an empty class definition.
Let us create an instance this_obj of MyClass() class and print it as shown −
<__main__.MyClass object at 0x03B08E10>
<__main__.MyClass object at 0x0369D390>
Here, we have created an instance of MyClass. The hex code refers to the address where the object is being stored. Another instance is pointing to another address.
Now let us define one variable inside the class MyClass() and get the variable from the instance of that class as shown in the following code −
class MyClass(object):
var = 9
# Create first instance of MyClass
this_obj = MyClass()
print(this_obj.var)
# Another instance of MyClass
that_obj = MyClass()
print (that_obj.var)
You can observe the following output when you execute the code given above −
9
9
As instance knows from which class it is instantiated, so when requested for an attribute from an instance, the instance looks for the attribute and the class. This is called the attribute lookup.
A function defined in a class is called a method. An instance method requires an instance in order to call it and requires no decorator. When creating an instance method, the first parameter is always self. Though we can call it (self) by any other name, it is recommended to use self, as it is a naming convention.
class MyClass(object):
var = 9
def firstM(self):
print("hello, World")
obj = MyClass()
print(obj.var)
obj.firstM()
You can observe the following output when you execute the code given above −
9
hello, World
Note that in the above program, we defined a method with self as argument. But we cannot call the method as we have not declared any argument to it.
class MyClass(object):
def firstM(self):
print("hello, World")
print(self)
obj = MyClass()
obj.firstM()
print(obj)
You can observe the following output when you execute the code given above −
hello, World
<__main__.MyClass object at 0x036A8E10>
<__main__.MyClass object at 0x036A8E10>
Encapsulation is one of the fundamentals of OOP. OOP enables us to hide the complexity
of the internal working of the object which is advantageous to the developer in the
following ways −
Simplifies and makes it easy to understand to use an object without knowing the internals.
Simplifies and makes it easy to understand to use an object without knowing the internals.
Any change can be easily manageable.
Any change can be easily manageable.
Object-oriented programming relies heavily on encapsulation. The terms encapsulation and abstraction (also called data hiding) are often used as synonyms. They are nearly synonymous, as abstraction is achieved through encapsulation.
Encapsulation provides us the mechanism of restricting the access to some of the object’s
components, this means that the internal representation of an object can’t be seen from outside of the object definition. Access to this data is typically achieved through special
methods − Getters and Setters.
This data is stored in instance attributes and can be manipulated from anywhere outside the class. To secure it, that data should only be accessed using instance methods. Direct access should not be permitted.
class MyClass(object):
def setAge(self, num):
self.age = num
def getAge(self):
return self.age
zack = MyClass()
zack.setAge(45)
print(zack.getAge())
zack.setAge("Fourty Five")
print(zack.getAge())
You can observe the following output when you execute the code given above −
45
Fourty Five
The data should be stored only if it is correct and valid, using Exception handling
constructs. As we can see above, there is no restriction on the user input to setAge()
method. It could be a string, a number, or a list. So we need to check onto above code to ensure correctness of being stored.
class MyClass(object):
def setAge(self, num):
self.age = num
def getAge(self):
return self.age
zack = MyClass()
zack.setAge(45)
print(zack.getAge())
zack.setAge("Fourty Five")
print(zack.getAge())
The __init__ method is implicitly called as soon as an object of a class is instantiated.This will initialize the object.
x = MyClass()
The line of code shown above will create a new instance and assigns this object to the
local variable x.
The instantiation operation, that is calling a class object, creates an empty object. Many classes like to create objects with instances customized to a specific initial state. Therefore, a class may define a special method named ‘ __init__() ‘ as shown −
def __init__(self):
self.data = []
Python calls __init__ during the instantiation to define an additional attribute that should occur when a class is instantiated that may be setting up some beginning values for that object or running a routine required on instantiation. So in this example, a new, initialized
instance can be obtained by −
x = MyClass()
The __init__() method can have single or multiple arguments for a greater flexibility. The init stands for initialization, as it initializes attributes of the instance. It is called the
constructor of a class.
class myclass(object):
def __init__(self,aaa, bbb):
self.a = aaa
self.b = bbb
x = myclass(4.5, 3)
print(x.a, x.b)
4.5 3
The attribute defined in the class is called “class attributes’ and the attributes defined in the function is called ‘instance attributes’. While defining, these attributes are not prefixed
by self, as these are the property of the class and not of a particular instance.
The class attributes can be accessed by the class itself ( className.attributeName) as well as by the instances of the class (inst.attributeName). So, the instances have access to both the instance attribute as well as class attributes.
>>> class myclass():
age = 21
>>> myclass.age
21
>>> x = myclass()
>>> x.age
21
>>>
A class attribute can be overridden in an instance, even though it is not a good method to break encapsulation.
There is a lookup path for attributes in Python. The first being the method defined within
the class, and then the class above it.
>>> class myclass(object):
classy = 'class value'
>>> dd = myclass()
>>> print (dd.classy) # This should return the string 'class value'
class value
>>>
>>> dd.classy = "Instance Value"
>>> print(dd.classy) # Return the string "Instance Value"
Instance Value
>>>
>>> # This will delete the value set for 'dd.classy' in the instance.
>>> del dd.classy
>>> >>> # Since the overriding attribute was deleted, this will print 'class
value'.
>>> print(dd.classy)
class value
>>>
We are overriding the ‘classy’ class attribute in the instance dd. When it’s overridden, the Python interpreter reads the overridden value. But once the new value is deleted with ‘del’, the overridden value is no longer present in the instance, and hence the lookup goes a level above and gets it from the class.
In this section, let us understand how the class data relates to the instance data. We can store data either in a class or in an instance. When we design a class, we decide which data belongs to the instance and which data should be stored into the overall class.
An instance can access the class data. If we create multiple instances, then these instances can access their individual attribute values as well the overall class data.
Thus, a class data is the data that is shared among all the instances. Observe the code given below for better undersanding −
class InstanceCounter(object):
count = 0 # class attribute, will be accessible to all instances
def __init__(self, val):
self.val = val
InstanceCounter.count +=1 # Increment the value of class attribute, accessible through class name
# In above line, class ('InstanceCounter') act as an object
def set_val(self, newval):
self.val = newval
def get_val(self):
return self.val
def get_count(self):
return InstanceCounter.count
a = InstanceCounter(9)
b = InstanceCounter(18)
c = InstanceCounter(27)
for obj in (a, b, c):
print ('val of obj: %s' %(obj.get_val())) # Initialized value ( 9, 18, 27)
print ('count: %s' %(obj.get_count())) # always 3
val of obj: 9
count: 3
val of obj: 18
count: 3
val of obj: 27
count: 3
In short, class attributes are same for all instances of class whereas instance attributes is particular for each instance. For two different instances, we will have two different instance attributes.
class myClass:
class_attribute = 99
def class_method(self):
self.instance_attribute = 'I am instance attribute'
print (myClass.__dict__)
You can observe the following output when you execute the code given above −
{'__module__': '__main__', 'class_attribute': 99, 'class_method': <function myClass.class_method at 0x04128D68>, '__dict__': <attribute '__dict__' of 'myClass' objects>, '__weakref__': <attribute '__weakref__' of 'myClass' objects>, '__doc__': None}
The instance attribute myClass.__dict__ as shown −
>>> a = myClass()
>>> a.class_method()
>>> print(a.__dict__)
{'instance_attribute': 'I am instance attribute'}
This chapter talks in detail about various built-in functions in Python, file I/O operations and overloading concepts.
The Python interpreter has a number of functions called built-in functions that are readily available for use. In its latest version, Python contains 68 built-in functions as listed in the table given below −
This section discusses some of the important functions in brief −
The len() function gets the length of strings, list or collections. It returns the length or number of items of an object, where object can be a string, list or a collection.
>>> len(['hello', 9 , 45.0, 24])
4
len() function internally works like list.__len__() or tuple.__len__(). Thus, note that len() works only on objects that has a __len__() method.
>>> set1
{1, 2, 3, 4}
>>> set1.__len__()
4
However, in practice, we prefer len() instead of the __len__() function because of the following reasons −
It is more efficient. And it is not necessary that a particular method is written to refuse access to special methods such as __len__.
It is more efficient. And it is not necessary that a particular method is written to refuse access to special methods such as __len__.
It is easy to maintain.
It is easy to maintain.
It supports backward compatibility.
It supports backward compatibility.
It returns the reverse iterator. seq must be an object which has __reversed__() method or supports the sequence protocol (the __len__() method and the __getitem__() method). It is generally used in for loops when we want to loop over items from back to front.
>>> normal_list = [2, 4, 5, 7, 9]
>>>
>>> class CustomSequence():
def __len__(self):
return 5
def __getitem__(self,index):
return "x{0}".format(index)
>>> class funkyback():
def __reversed__(self):
return 'backwards!'
>>> for seq in normal_list, CustomSequence(), funkyback():
print('\n{}: '.format(seq.__class__.__name__), end="")
for item in reversed(seq):
print(item, end=", ")
The for loop at the end prints the reversed list of a normal list, and instances of the two custom sequences. The output shows that reversed() works on all the three of them, but has a very different results when we define __reversed__.
You can observe the following output when you execute the code given above −
list: 9, 7, 5, 4, 2,
CustomSequence: x4, x3, x2, x1, x0,
funkyback: b, a, c, k, w, a, r, d, s, !,
The enumerate () method adds a counter to an iterable and returns the enumerate object.
The syntax of enumerate () is −
enumerate(iterable, start = 0)
Here the second argument start is optional, and by default index starts with zero (0).
>>> # Enumerate
>>> names = ['Rajesh', 'Rahul', 'Aarav', 'Sahil', 'Trevor']
>>> enumerate(names)
<enumerate object at 0x031D9F80>
>>> list(enumerate(names))
[(0, 'Rajesh'), (1, 'Rahul'), (2, 'Aarav'), (3, 'Sahil'), (4, 'Trevor')]
>>>
So enumerate() returns an iterator which yields a tuple that keeps count of the elements in the sequence passed. Since the return value is an iterator, directly accessing it is not much useful. A better approach for enumerate() is keeping count within a for loop.
>>> for i, n in enumerate(names):
print('Names number: ' + str(i))
print(n)
Names number: 0
Rajesh
Names number: 1
Rahul
Names number: 2
Aarav
Names number: 3
Sahil
Names number: 4
Trevor
There are many other functions in the standard library, and here is another list of some more widely used functions −
hasattr, getattr, setattr and delattr, which allows attributes of an object to be manipulated by their string names.
hasattr, getattr, setattr and delattr, which allows attributes of an object to be manipulated by their string names.
all and any, which accept an iterable object and return True if all, or any, of the items evaluate to be true.
all and any, which accept an iterable object and return True if all, or any, of the items evaluate to be true.
nzip, which takes two or more sequences and returns a new sequence of tuples, where each tuple contains a single value from each sequence.
nzip, which takes two or more sequences and returns a new sequence of tuples, where each tuple contains a single value from each sequence.
The concept of files is associated with the term object-oriented programming. Python has wrapped the interface that operating systems provided in abstraction that allows us to work with file objects.
The open() built-in function is used to open a file and return a file object. It is the most commonly used function with two arguments −
open(filename, mode)
The open() function calls two argument, first is the filename and second is the mode. Here mode can be ‘r’ for read only mode, ‘w’ for only writing (an existing file with the same name will be erased), and ‘a’ opens the file for appending, any data written to the file is automatically added to the end. ‘r+’ opens the file for both reading and writing. The default mode is read only.
On windows, ‘b’ appended to the mode opens the file in binary mode, so there are also modes like ‘rb’, ‘wb’ and ‘r+b’.
>>> text = 'This is the first line'
>>> file = open('datawork','w')
>>> file.write(text)
22
>>> file.close()
In some cases, we just want to append to the existing file rather then over-writing it, for that we could supply the value ‘a’ as a mode argument, to append to the end of the file, rather than completely overwriting existing file contents.
>>> f = open('datawork','a')
>>> text1 = ' This is second line'
>>> f.write(text1)
20
>>> f.close()
Once a file is opened for reading, we can call the read, readline, or readlines method to get the contents of the file. The read method returns the entire contents of the file as a str or bytes object, depending on whether the second argument is ‘b’.
For readability, and to avoid reading a large file in one go, it is often better to use a for loop directly on a file object. For text files, it will read each line, one at a time, and we can process it inside the loop body. For binary files however it’s better to read fixed-sized chunks of data using the read() method, passing a parameter for the maximum number of bytes to read.
>>> f = open('fileone','r+')
>>> f.readline()
'This is the first line. \n'
>>> f.readline()
'This is the second line. \n'
Writing to a file, through write method on file objects will writes a string (bytes for binary data) object to the file. The writelines method accepts a sequence of strings and write each of the iterated values to the file. The writelines method does not append a new line after each item in the sequence.
Finally the close() method should be called when we are finished reading or writing the file, to ensure any buffered writes are written to the disk, that the file has been properly cleaned up and that all resources tied with the file are released back to the operating system. It’s a better approach to call the close() method but technically this will happen automatically when the script exists.
Method overloading refers to having multiple methods with the same name that accept different sets of arguments.
Given a single method or function, we can specify the number of parameters ourself. Depending on the function definition, it can be called with zero, one, two or more parameters.
class Human:
def sayHello(self, name = None):
if name is not None:
print('Hello ' + name)
else:
print('Hello ')
#Create Instance
obj = Human()
#Call the method, else part will be executed
obj.sayHello()
#Call the method with a parameter, if part will be executed
obj.sayHello('Rahul')
Hello
Hello Rahul
A callable object is an object can accept some arguments and possibly will return an object. A function is the simplest callable object in Python, but there are others too like classes or certain class instances.
Every function in a Python is an object. Objects can contain methods or functions but object is not necessary a function.
def my_func():
print('My function was called')
my_func.description = 'A silly function'
def second_func():
print('Second function was called')
second_func.description = 'One more sillier function'
def another_func(func):
print("The description:", end=" ")
print(func.description)
print('The name: ', end=' ')
print(func.__name__)
print('The class:', end=' ')
print(func.__class__)
print("Now I'll call the function passed in")
func()
another_func(my_func)
another_func(second_func)
In the above code, we are able to pass two different functions as argument into our third function, and get different Output for each one −
The description: A silly function
The name: my_func
The class:
Now I'll call the function passed in
My function was called
The description: One more sillier function
The name: second_func
The class:
Now I'll call the function passed in
Second function was called
Just as functions are objects that can have attributes set on them, it is possible to create an object that can be called as though it were a function.
In Python any object with a __call__() method can be called using function-call syntax.
Inheritance and polymorphism – this is a very important concept in Python. You must understand it better if you want to learn.
One of the major advantages of Object Oriented Programming is re-use. Inheritance is one of the mechanisms to achieve the same. Inheritance allows programmer to create a general or a base class first and then later extend it to more specialized class. It allows programmer to write better code.
Using inheritance you can use or inherit all the data fields and methods available in your base class. Later you can add you own methods and data fields, thus inheritance provides a way to organize code, rather than rewriting it from scratch.
In object-oriented terminology when class X extend class Y, then Y is called super/parent/base class and X is called subclass/child/derived class. One point to note here is that only data fields and method which are not private are accessible by child classes. Private data fields and methods are accessible only inside the class.
syntax to create a derived class is −
class BaseClass:
Body of base class
class DerivedClass(BaseClass):
Body of derived class
Now look at the below example −
We first created a class called Date and pass the object as an argument, here-object is built-in class provided by Python. Later we created another class called time and called the Date class as an argument. Through this call we get access to all the data and attributes of Date class into the Time class. Because of that when we try to get the get_date method from the Time class object tm we created earlier possible.
Object.Attribute Lookup Hierarchy
The instance
The class
Any class from which this class inherits
Let’s take a closure look into the inheritance example −
Let’s create couple of classes to participate in examples −
Animal − Class simulate an animal
Cat − Subclass of Animal
Dog − Subclass of Animal
In Python, constructor of class used to create an object (instance), and assign the value for the attributes.
Constructor of subclasses always called to a constructor of parent class to initialize value for the attributes in the parent class, then it start assign value for its attributes.
In the above example, we see the command attributes or methods we put in the parent class so that all subclasses or child classes will inherits that property from the parent class.
If a subclass try to inherits methods or data from another subclass then it will through an error as we see when Dog class try to call swatstring() methods from that cat class, it throws an error(like AttributeError in our case).
Polymorphism is an important feature of class definition in Python that is utilized when you have commonly named methods across classes or subclasses. This permits functions to use entities of different types at different times. So, it provides flexibility and loose coupling so that code can be extended and easily maintained over time.
This allows functions to use objects of any of these polymorphic classes without needing to be aware of distinctions across the classes.
Polymorphism can be carried out through inheritance, with subclasses making use of base class methods or overriding them.
Let understand the concept of polymorphism with our previous inheritance example and add one common method called show_affection in both subclasses −
From the example we can see, it refers to a design in which object of dissimilar type can be treated in the same manner or more specifically two or more classes with method of the same name or common interface because same method(show_affection in below example) is called with either type of objects.
So, all animals show affections (show_affection), but they do differently. The “show_affection” behaviors is thus polymorphic in the sense that it acted differently depending on the animal. So, the abstract “animal” concept does not actually “show_affection”, but specific animals(like dogs and cats) have a concrete implementation of the action “show_affection”.
Python itself have classes that are polymorphic. Example, the len() function can be used with multiple objects and all return the correct output based on the input parameter.
In Python, when a subclass contains a method that overrides a method of the superclass, you can also call the superclass method by calling
Super(Subclass, self).method instead of self.method.
class Thought(object):
def __init__(self):
pass
def message(self):
print("Thought, always come and go")
class Advice(Thought):
def __init__(self):
super(Advice, self).__init__()
def message(self):
print('Warning: Risk is always involved when you are dealing with market!')
If we see from our previous inheritance example, __init__ was located in the parent class in the up ‘cause the child class dog or cat didn’t‘ve __init__ method in it. Python used the inheritance attribute lookup to find __init__ in animal class. When we created the child class, first it will look the __init__ method in the dog class, then it didn’t find it then looked into parent class Animal and found there and called that there. So as our class design became complex we may wish to initialize a instance firstly processing it through parent class constructor and then through child class constructor.
In above example- all animals have a name and all dogs a particular breed. We called parent class constructor with super. So dog has its own __init__ but the first thing that happen is we call super. Super is built in function and it is designed to relate a class to its super class or its parent class.
In this case we saying that get the super class of dog and pass the dog instance to whatever method we say here the constructor __init__. So in another words we are calling parent class Animal __init__ with the dog object. You may ask why we won’t just say Animal __init__ with the dog instance, we could do this but if the name of animal class were to change, sometime in the future. What if we wanna rearrange the class hierarchy,so the dog inherited from another class. Using super in this case allows us to keep things modular and easy to change and maintain.
So in this example we are able to combine general __init__ functionality with more specific functionality. This gives us opportunity to separate common functionality from the specific functionality which can eliminate code duplication and relate class to one another in a way that reflects the system overall design.
__init__ is like any other method; it can be inherited
__init__ is like any other method; it can be inherited
If a class does not have a __init__ constructor, Python will check its parent class to see if it can find one.
If a class does not have a __init__ constructor, Python will check its parent class to see if it can find one.
As soon as it finds one, Python calls it and stops looking
As soon as it finds one, Python calls it and stops looking
We can use the super () function to call methods in the parent class.
We can use the super () function to call methods in the parent class.
We may want to initialize in the parent as well as our own class.
We may want to initialize in the parent as well as our own class.
As its name indicates, multiple inheritance is Python is when a class inherits from multiple classes.
For example, a child inherits personality traits from both parents (Mother and Father).
To make a class inherits from multiple parents classes, we write the the names of these classes inside the parentheses to the derived class while defining it. We separate these names with comma.
Below is an example of that −
>>> class Mother:
pass
>>> class Father:
pass
>>> class Child(Mother, Father):
pass
>>> issubclass(Child, Mother) and issubclass(Child, Father)
True
Multiple inheritance refers to the ability of inheriting from two or more than two class. The complexity arises as child inherits from parent and parents inherits from the grandparent class. Python climbs an inheriting tree looking for attributes that is being requested to be read from an object. It will check the in the instance, within class then parent class and lastly from the grandparent class. Now the question arises in what order the classes will be searched - breath-first or depth-first. By default, Python goes with the depth-first.
That’s is why in the below diagram the Python searches the dothis() method first in class A. So the method resolution order in the below example will be
Mro- D→B→A→C
Look at the below multiple inheritance diagram −
Let’s go through an example to understand the “mro” feature of an Python.
Let’s take another example of “diamond shape” multiple inheritance.
Above diagram will be considered ambiguous. From our previous example understanding “method resolution order” .i.e. mro will be D→B→A→C→A but it’s not. On getting the second A from the C, Python will ignore the previous A. so the mro will be in this case will be D→B→C→A.
Let’s create an example based on above diagram −
Simple rule to understand the above output is- if the same class appear in the method resolution order, the earlier appearances of this class will be remove from the method resolution order.
In conclusion −
Any class can inherit from multiple classes
Any class can inherit from multiple classes
Python normally uses a “depth-first” order when searching inheriting classes.
Python normally uses a “depth-first” order when searching inheriting classes.
But when two classes inherit from the same class, Python eliminates the first appearances of that class from the mro.
But when two classes inherit from the same class, Python eliminates the first appearances of that class from the mro.
Functions(or methods) are created by def statement.
Though methods works in exactly the same way as a function except one point where method first argument is instance object.
We can classify methods based on how they behave, like
Simple method − defined outside of a class. This function can access class attributes by feeding instance argument:
Simple method − defined outside of a class. This function can access class attributes by feeding instance argument:
def outside_func(():
Instance method −
Instance method −
def func(self,)
Class method − if we need to use class attributes
Class method − if we need to use class attributes
@classmethod
def cfunc(cls,)
Static method − do not have any info about the class
Static method − do not have any info about the class
@staticmethod
def sfoo()
Till now we have seen the instance method, now is the time to get some insight into the other two methods,
The @classmethod decorator, is a builtin function decorator that gets passed the class it was called on or the class of the instance it was called on as first argument. The result of that evaluation shadows your function definition.
class C(object):
@classmethod
def fun(cls, arg1, arg2, ...):
....
fun: function that needs to be converted into a class method
returns: a class method for function
They have the access to this cls argument, it can’t modify object instance state. That would require access to self.
It is bound to the class and not the object of the class.
It is bound to the class and not the object of the class.
Class methods can still modify class state that applies across all instances of the class.
Class methods can still modify class state that applies across all instances of the class.
A static method takes neither a self nor a cls(class) parameter but it’s free to accept an arbitrary number of other parameters.
syntax
class C(object):
@staticmethod
def fun(arg1, arg2, ...):
...
returns: a static method for function funself.
A static method can neither modify object state nor class state.
They are restricted in what data they can access.
We generally use class method to create factory methods. Factory methods return class object (similar to a constructor) for different use cases.
We generally use class method to create factory methods. Factory methods return class object (similar to a constructor) for different use cases.
We generally use static methods to create utility functions.
We generally use static methods to create utility functions.
Modern software development needs to address complex business requirements. It also needs to take into account factors such as future extensibility and maintainability. A good design of a software system is vital to accomplish these goals. Design patterns play an important role in such systems.
To understand design pattern, let’s consider below example −
Every car’s design follows a basic design pattern, four wheels, steering wheel, the core drive system like accelerator-break-clutch, etc.
Every car’s design follows a basic design pattern, four wheels, steering wheel, the core drive system like accelerator-break-clutch, etc.
So, all things repeatedly built/ produced, shall inevitably follow a pattern in its design.. it cars, bicycle, pizza, atm machines, whatever...even your sofa bed.
Designs that have almost become standard way of coding some logic/mechanism/technique in software, hence come to be known as or studied as, Software Design Patterns.
Benefits of using Design Patterns are −
Helps you to solve common design problems through a proven approach.
Helps you to solve common design problems through a proven approach.
No ambiguity in the understanding as they are well documented.
No ambiguity in the understanding as they are well documented.
Reduce the overall development time.
Reduce the overall development time.
Helps you deal with future extensions and modifications with more ease than otherwise.
Helps you deal with future extensions and modifications with more ease than otherwise.
May reduce errors in the system since they are proven solutions to common problems.
May reduce errors in the system since they are proven solutions to common problems.
The GoF (Gang of Four) design patterns are classified into three categories namely creational, structural and behavioral.
Creational design patterns separate the object creation logic from the rest of the system. Instead of you creating objects, creational patterns creates them for you. The creational patterns include Abstract Factory, Builder, Factory Method, Prototype and Singleton.
Creational Patterns are not commonly used in Python because of the dynamic nature of the language. Also language itself provide us with all the flexibility we need to create in a sufficient elegant fashion, we rarely need to implement anything on top, like singleton or Factory.
Also these patterns provide a way to create objects while hiding the creation logic, rather than instantiating objects directly using a new operator.
Sometimes instead of starting from scratch, you need to build larger structures by using an existing set of classes. That’s where structural class patterns use inheritance to build a new structure. Structural object patterns use composition/ aggregation to obtain a new functionality. Adapter, Bridge, Composite, Decorator, Façade, Flyweight and Proxy are Structural Patterns. They offers best ways to organize class hierarchy.
Behavioral patterns offers best ways of handling communication between objects. Patterns comes under this categories are: Visitor, Chain of responsibility, Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy and Template method are Behavioral Patterns.
Because they represent the behavior of a system, they are used generally to describe the functionality of software systems.
It is one of the most controversial and famous of all design patterns. It is used in overly object-oriented languages, and is a vital part of traditional object-oriented programming.
The Singleton pattern is used for,
When logging needs to be implemented. The logger instance is shared by all the components of the system.
When logging needs to be implemented. The logger instance is shared by all the components of the system.
The configuration files is using this because cache of information needs to be maintained and shared by all the various components in the system.
The configuration files is using this because cache of information needs to be maintained and shared by all the various components in the system.
Managing a connection to a database.
Managing a connection to a database.
Here is the UML diagram,
class Logger(object):
def __new__(cls, *args, **kwargs):
if not hasattr(cls, '_logger'):
cls._logger = super(Logger, cls).__new__(cls, *args, **kwargs)
return cls._logger
In this example, Logger is a Singleton.
When __new__ is called, it normally constructs a new instance of that class. When we override it, we first check if our singleton instance has been created or not. If not, we create it using a super call. Thus, whenever we call the constructor on Logger, we always get the exact same instance.
>>>
>>> obj1 = Logger()
>>> obj2 = Logger()
>>> obj1 == obj2
True
>>>
>>> obj1
<__main__.Logger object at 0x03224090>
>>> obj2
<__main__.Logger object at 0x03224090>
In this we will look into some of the advanced features which Python provide
In this we will look onto, how Python allows us to take advantage of operators in our classes. Python is largely objects and methods call on objects and this even goes on even when its hidden by some convenient syntax.
>>> var1 = 'Hello'
>>> var2 = ' World!'
>>> var1 + var2
'Hello World!'
>>>
>>> var1.__add__(var2)
'Hello World!'
>>> num1 = 45
>>> num2 = 60
>>> num1.__add__(num2)
105
>>> var3 = ['a', 'b']
>>> var4 = ['hello', ' John']
>>> var3.__add__(var4)
['a', 'b', 'hello', ' John']
So if we have to add magic method __add__ to our own classes, could we do that too. Let’s try to do that.
We have a class called Sumlist which has a contructor __init__ which takes list as an argument called my_list.
class SumList(object):
def __init__(self, my_list):
self.mylist = my_list
def __add__(self, other):
new_list = [ x + y for x, y in zip(self.mylist, other.mylist)]
return SumList(new_list)
def __repr__(self):
return str(self.mylist)
aa = SumList([3,6, 9, 12, 15])
bb = SumList([100, 200, 300, 400, 500])
cc = aa + bb # aa.__add__(bb)
print(cc) # should gives us a list ([103, 206, 309, 412, 515])
[103, 206, 309, 412, 515]
But there are many methods which are internally managed by others magic methods. Below are some of them,
'abc' in var # var.__contains__('abc')
var == 'abc' # var.__eq__('abc')
var[1] # var.__getitem__(1)
var[1:3] # var.__getslice__(1, 3)
len(var) # var.__len__()
print(var) # var.__repr__()
Classes can also inherit from built-in types this means inherits from any built-in and take advantage of all the functionality found there.
In below example we are inheriting from dictionary but then we are implementing one of its method __setitem__. This (setitem) is invoked when we set key and value in the dictionary. As this is a magic method, this will be called implicitly.
class MyDict(dict):
def __setitem__(self, key, val):
print('setting a key and value!')
dict.__setitem__(self, key, val)
dd = MyDict()
dd['a'] = 10
dd['b'] = 20
for key in dd.keys():
print('{0} = {1}'.format(key, dd[key]))
setting a key and value!
setting a key and value!
a = 10
b = 20
Let’s extend our previous example, below we have called two magic methods called __getitem__ and __setitem__ better invoked when we deal with list index.
# Mylist inherits from 'list' object but indexes from 1 instead for 0!
class Mylist(list): # inherits from list
def __getitem__(self, index):
if index == 0:
raise IndexError
if index > 0:
index = index - 1
return list.__getitem__(self, index) # this method is called when
# we access a value with subscript like x[1]
def __setitem__(self, index, value):
if index == 0:
raise IndexError
if index > 0:
index = index - 1
list.__setitem__(self, index, value)
x = Mylist(['a', 'b', 'c']) # __init__() inherited from builtin list
print(x) # __repr__() inherited from builtin list
x.append('HELLO'); # append() inherited from builtin list
print(x[1]) # 'a' (Mylist.__getitem__ cutomizes list superclass
# method. index is 1, but reflects 0!
print (x[4]) # 'HELLO' (index is 4 but reflects 3!
['a', 'b', 'c']
a
HELLO
In above example, we set a three item list in Mylist and implicitly __init__ method is called and when we print the element x, we get the three item list ([‘a’,’b’,’c’]). Then we append another element to this list. Later we ask for index 1 and index 4. But if you see the output, we are getting element from the (index-1) what we have asked for. As we know list indexing start from 0 but here the indexing start from 1 (that’s why we are getting the first item of the list).
In this we will look into names we’ll used for variables especially private variables and conventions used by Python programmers worldwide. Although variables are designated as private but there is not privacy in Python and this by design. Like any other well documented languages, Python has naming and style conventions that it promote although it doesn’t enforce them. There is a style guide written by “Guido van Rossum” the originator of Python, that describe the best practices and use of name and is called PEP8. Here is the link for this, https://www.python.org/dev/peps/pep-0008/
PEP stands for Python enhancement proposal and is a series of documentation that distributed among the Python community to discuss proposed changes. For example it is recommended all,
Module names − all_lower_case
Class names and exception names − CamelCase
Global and local names − all_lower_case
Functions and method names − all_lower_case
Constants − ALL_UPPER_CASE
These are just the recommendation, you can vary if you like. But as most of the developers follows these recommendation so might me your code is less readable.
We can follow the PEP recommendation we it allows us to get,
More familiar to the vast majority of developers
Clearer to most readers of your code.
Will match style of other contributers who work on same code base.
Mark of a professional software developers
Everyone will accept you.
In Python, when we are dealing with modules and classes, we designate some variables or attribute as private. In Python, there is no existence of “Private” instance variable which cannot be accessed except inside an object. Private simply means they are simply not intended to be used by the users of the code instead they are intended to be used internally. In general, a convention is being followed by most Python developers i.e. a name prefixed with an underscore for example. _attrval (example below) should be treated as a non-public part of the API or any Python code, whether it is a function, a method or a data member. Below is the naming convention we follow,
Public attributes or variables (intended to be used by the importer of this module or user of this class) −regular_lower_case
Public attributes or variables (intended to be used by the importer of this module or user of this class) −regular_lower_case
Private attributes or variables (internal use by the module or class) −_single_leading_underscore
Private attributes or variables (internal use by the module or class) −_single_leading_underscore
Private attributes that shouldn’t be subclassed −__double_leading_underscore
Private attributes that shouldn’t be subclassed −__double_leading_underscore
Magic attributes −__double_underscores__(use them, don’t create them)
Magic attributes −__double_underscores__(use them, don’t create them)
class GetSet(object):
instance_count = 0 # public
__mangled_name = 'no privacy!' # special variable
def __init__(self, value):
self._attrval = value # _attrval is for internal use only
GetSet.instance_count += 1
@property
def var(self):
print('Getting the "var" attribute')
return self._attrval
@var.setter
def var(self, value):
print('setting the "var" attribute')
self._attrval = value
@var.deleter
def var(self):
print('deleting the "var" attribute')
self._attrval = None
cc = GetSet(5)
cc.var = 10 # public name
print(cc._attrval)
print(cc._GetSet__mangled_name)
setting the "var" attribute
10
no privacy!
Strings are the most popular data types used in every programming language. Why? Because we, understand text better than numbers, so in writing and talking we use text and words, similarly in programming too we use strings. In string we parse text, analyse text semantics, and do data mining – and all this data is human consumed text.The string in Python is immutable.
In Python, string can be marked in multiple ways, using single quote ( ‘ ), double quote( “ ) or even triple quote ( ‘’’ ) in case of multiline strings.
>>> # String Examples
>>> a = "hello"
>>> b = ''' A Multi line string,
Simple!'''
>>> e = ('Multiple' 'strings' 'togethers')
String manipulation is very useful and very widely used in every language. Often, programmers are required to break down strings and examine them closely.
Strings can be iterated over (character by character), sliced, or concatenated. The syntax is the same as for lists.
The str class has numerous methods on it to make manipulating strings easier. The dir and help commands provides guidance in the Python interpreter how to use them.
Below are some of the commonly used string methods we use.
isalpha()
Checks if all characters are Alphabets
isdigit()
Checks Digit Characters
isdecimal()
Checks decimal Characters
isnumeric()
checks Numeric Characters
find()
Returns the Highest Index of substrings
istitle()
Checks for Titlecased strings
join()
Returns a concatenated string
lower()
returns lower cased string
upper()
returns upper cased string
partion()
Returns a tuple
bytearray()
Returns array of given byte size
enumerate()
Returns an enumerate object
isprintable()
Checks printable character
Let’s try to run couple of string methods,
>>> str1 = 'Hello World!'
>>> str1.startswith('h')
False
>>> str1.startswith('H')
True
>>> str1.endswith('d')
False
>>> str1.endswith('d!')
True
>>> str1.find('o')
4
>>> #Above returns the index of the first occurence of the character/substring.
>>> str1.find('lo')
3
>>> str1.upper()
'HELLO WORLD!'
>>> str1.lower()
'hello world!'
>>> str1.index('b')
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
str1.index('b')
ValueError: substring not found
>>> s = ('hello How Are You')
>>> s.split(' ')
['hello', 'How', 'Are', 'You']
>>> s1 = s.split(' ')
>>> '*'.join(s1)
'hello*How*Are*You'
>>> s.partition(' ')
('hello', ' ', 'How Are You')
>>>
In Python 3.x formatting of strings has changed, now it more logical and is more flexible. Formatting can be done using the format() method or the % sign(old style) in format string.
The string can contain literal text or replacement fields delimited by braces {} and each replacement field may contains either the numeric index of a positional argument or the name of a keyword argument.
str.format(*args, **kwargs)
>>> '{} {}'.format('Example', 'One')
'Example One'
>>> '{} {}'.format('pie', '3.1415926')
'pie 3.1415926'
Below example allows re-arrange the order of display without changing the arguments.
>>> '{1} {0}'.format('pie', '3.1415926')
'3.1415926 pie'
Padding and aligning strings
A value can be padded to a specific length.
>>> #Padding Character, can be space or special character
>>> '{:12}'.format('PYTHON')
'PYTHON '
>>> '{:>12}'.format('PYTHON')
' PYTHON'
>>> '{:<{}s}'.format('PYTHON',12)
'PYTHON '
>>> '{:*<12}'.format('PYTHON')
'PYTHON******'
>>> '{:*^12}'.format('PYTHON')
'***PYTHON***'
>>> '{:.15}'.format('PYTHON OBJECT ORIENTED PROGRAMMING')
'PYTHON OBJECT O'
>>> #Above, truncated 15 characters from the left side of a specified string
>>> '{:.{}}'.format('PYTHON OBJECT ORIENTED',15)
'PYTHON OBJECT O'
>>> #Named Placeholders
>>> data = {'Name':'Raghu', 'Place':'Bangalore'}
>>> '{Name} {Place}'.format(**data)
'Raghu Bangalore'
>>> #Datetime
>>> from datetime import datetime
>>> '{:%Y/%m/%d.%H:%M}'.format(datetime(2018,3,26,9,57))
'2018/03/26.09:57'
Strings as collections of immutable Unicode characters. Unicode strings provide an opportunity to create software or programs that works everywhere because the Unicode strings can represent any possible character not just the ASCII characters.
Many IO operations only know how to deal with bytes, even if the bytes object refers to textual data. It is therefore very important to know how to interchange between bytes and Unicode.
Converting text to bytes
Converting a strings to byte object is termed as encoding. There are numerous forms of encoding, most common ones are: PNG; JPEG, MP3, WAV, ASCII, UTF-8 etc. Also this(encoding) is a format to represent audio, images, text, etc. in bytes.
This conversion is possible through encode(). It take encoding technique as argument. By default, we use ‘UTF-8’ technique.
>>> # Python Code to demonstrate string encoding
>>>
>>> # Initialising a String
>>> x = 'TutorialsPoint'
>>>
>>> #Initialising a byte object
>>> y = b'TutorialsPoint'
>>>
>>> # Using encode() to encode the String >>> # encoded version of x is stored in z using ASCII mapping
>>> z = x.encode('ASCII')
>>>
>>> # Check if x is converted to bytes or not
>>>
>>> if(z==y):
print('Encoding Successful!')
else:
print('Encoding Unsuccessful!')
Encoding Successful!
Converting bytes to text
Converting bytes to text is called the decoding. This is implemented through decode(). We can convert a byte string to a character string if we know which encoding is used to encode it.
So Encoding and decoding are inverse processes.
>>>
>>> # Python code to demonstrate Byte Decoding
>>>
>>> #Initialise a String
>>> x = 'TutorialsPoint'
>>>
>>> #Initialising a byte object
>>> y = b'TutorialsPoint'
>>>
>>> #using decode() to decode the Byte object
>>> # decoded version of y is stored in z using ASCII mapping
>>> z = y.decode('ASCII')
>>> #Check if y is converted to String or not
>>> if (z == x):
print('Decoding Successful!')
else:
print('Decoding Unsuccessful!') Decoding Successful!
>>>
Operating systems represents files as a sequence of bytes, not text.
A file is a named location on disk to store related information. It is used to permanently store data in your disk.
In Python, a file operation takes place in the following order.
Open a file
Read or write onto a file (operation).Open a file
Close the file.
Python wraps the incoming (or outgoing) stream of bytes with appropriate decode (or encode) calls so we can deal directly with str objects.
Python has a built-in function open() to open a file. This will generate a file object, also called a handle as it is used to read or modify the file accordingly.
>>> f = open(r'c:\users\rajesh\Desktop\index.webm','rb')
>>> f
<_io.BufferedReader name='c:\\users\\rajesh\\Desktop\\index.webm'>
>>> f.mode
'rb'
>>> f.name
'c:\\users\\rajesh\\Desktop\\index.webm'
For reading text from a file, we only need to pass the filename into the function. The file will be opened for reading, and the bytes will be converted to text using the platform default encoding.
In general, an exception is any unusual condition. Exception usually indicates errors but sometimes they intentionally puts in the program, in cases like terminating a procedure early or recovering from a resource shortage. There are number of built-in exceptions, which indicate conditions like reading past the end of a file, or dividing by zero. We can define our own exceptions called custom exception.
Exception handling enables you handle errors gracefully and do something meaningful about it. Exception handling has two components: “throwing” and ‘catching’.
Every error occurs in Python result an exception which will an error condition identified by its error type.
>>> #Exception
>>> 1/0
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
1/0
ZeroDivisionError: division by zero
>>>
>>> var = 20
>>> print(ver)
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
print(ver)
NameError: name 'ver' is not defined
>>> #Above as we have misspelled a variable name so we get an NameError.
>>>
>>> print('hello)
SyntaxError: EOL while scanning string literal
>>> #Above we have not closed the quote in a string, so we get SyntaxError.
>>>
>>> #Below we are asking for a key, that doen't exists.
>>> mydict = {}
>>> mydict['x']
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
mydict['x']
KeyError: 'x'
>>> #Above keyError
>>>
>>> #Below asking for a index that didn't exist in a list.
>>> mylist = [1,2,3,4]
>>> mylist[5]
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
mylist[5]
IndexError: list index out of range
>>> #Above, index out of range, raised IndexError.
When something unusual occurs in your program and you wish to handle it using the exception mechanism, you ‘throw an exception’. The keywords try and except are used to catch exceptions. Whenever an error occurs within a try block, Python looks for a matching except block to handle it. If there is one, execution jumps there.
try:
#write some code
#that might throw some exception
except <ExceptionType>:
# Exception handler, alert the user
The code within the try clause will be executed statement by statement.
If an exception occurs, the rest of the try block will be skipped and the except clause will be executed.
try:
some statement here
except:
exception handling
Let’s write some code to see what happens when you not use any error handling mechanism in your program.
number = int(input('Please enter the number between 1 & 10: '))
print('You have entered number',number)
Above programme will work correctly as long as the user enters a number, but what happens if the users try to puts some other data type(like a string or a list).
Please enter the number between 1 > 10: 'Hi'
Traceback (most recent call last):
File "C:/Python/Python361/exception2.py", line 1, in <module>
number = int(input('Please enter the number between 1 & 10: '))
ValueError: invalid literal for int() with base 10: "'Hi'"
Now ValueError is an exception type. Let’s try to rewrite the above code with exception handling.
import sys
print('Previous code with exception handling')
try:
number = int(input('Enter number between 1 > 10: '))
except(ValueError):
print('Error..numbers only')
sys.exit()
print('You have entered number: ',number)
If we run the program, and enter a string (instead of a number), we can see that we get a different result.
Previous code with exception handling
Enter number between 1 > 10: 'Hi'
Error..numbers only
To raise your exceptions from your own methods you need to use raise keyword like this
raise ExceptionClass(‘Some Text Here’)
Let’s take an example
def enterAge(age):
if age<0:
raise ValueError('Only positive integers are allowed')
if age % 2 ==0:
print('Entered Age is even')
else:
print('Entered Age is odd')
try:
num = int(input('Enter your age: '))
enterAge(num)
except ValueError:
print('Only positive integers are allowed')
Run the program and enter positive integer.
Enter your age: 12
Entered Age is even
But when we try to enter a negative number we get,
Enter your age: -2
Only positive integers are allowed
You can create a custom exception class by Extending BaseException class or subclass of BaseException.
From above diagram we can see most of the exception classes in Python extends from the BaseException class. You can derive your own exception class from BaseException class or from its subclass.
Create a new file called NegativeNumberException.py and write the following code.
class NegativeNumberException(RuntimeError):
def __init__(self, age):
super().__init__()
self.age = age
Above code creates a new exception class named NegativeNumberException, which consists of only constructor which call parent class constructor using super()__init__() and sets the age.
Now to create your own custom exception class, will write some code and import the new exception class.
from NegativeNumberException import NegativeNumberException
def enterage(age):
if age < 0:
raise NegativeNumberException('Only positive integers are allowed')
if age % 2 == 0:
print('Age is Even')
else:
print('Age is Odd')
try:
num = int(input('Enter your age: '))
enterage(num)
except NegativeNumberException:
print('Only positive integers are allowed')
except:
print('Something is wrong')
Enter your age: -2
Only positive integers are allowed
Another way to create a custom Exception class.
class customException(Exception):
def __init__(self, value):
self.parameter = value
def __str__(self):
return repr(self.parameter)
try:
raise customException('My Useful Error Message!')
except customException as instance:
print('Caught: ' + instance.parameter)
Caught: My Useful Error Message!
The class hierarchy for built-in exceptions is −
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- StopAsyncIteration
+-- ArithmeticError
| +-- FloatingPointError
| +-- OverflowError
| +-- ZeroDivisionError
+-- AssertionError
+-- AttributeError
+-- BufferError
+-- EOFError
+-- ImportError
+-- LookupError
| +-- IndexError
| +-- KeyError
+-- MemoryError
+-- NameError
| +-- UnboundLocalError
+-- OSError
| +-- BlockingIOError
| +-- ChildProcessError
| +-- ConnectionError
| | +-- BrokenPipeError
| | +-- ConnectionAbortedError
| | +-- ConnectionRefusedError
| | +-- ConnectionResetError
| +-- FileExistsError
| +-- FileNotFoundError
| +-- InterruptedError
| +-- IsADirectoryError
| +-- NotADirectoryError
| +-- PermissionError
| +-- ProcessLookupError
| +-- TimeoutError
+-- ReferenceError
+-- RuntimeError
| +-- NotImplementedError
| +-- RecursionError
+-- SyntaxError
| +-- IndentationError
| +-- TabError
+-- SystemError
+-- TypeError
+-- ValueError
| +-- UnicodeError
| +-- UnicodeDecodeError
| +-- UnicodeEncodeError
| +-- UnicodeTranslateError
+-- Warning
+-- DeprecationWarning
+-- PendingDeprecationWarning
+-- RuntimeWarning
+-- SyntaxWarning
+-- UserWarning
+-- FutureWarning
+-- ImportWarning
+-- UnicodeWarning
+-- BytesWarning
+-- ResourceWarning
In the context of data storage, serialization is the process of translating data structures or object state into a format that can be stored (for example, in a file or memory buffer) or transmitted and reconstructed later.
In serialization, an object is transformed into a format that can be stored, so as to be able to deserialize it later and recreate the original object from the serialized format.
Pickling is the process whereby a Python object hierarchy is converted into a byte stream (usually not human readable) to be written to a file, this is also known as Serialization. Unpickling is the reverse operation, whereby a byte stream is converted back into a working Python object hierarchy.
Pickle is operationally simplest way to store the object. The Python Pickle module is an object-oriented way to store objects directly in a special storage format.
Pickle can store and reproduce dictionaries and lists very easily.
Stores object attributes and restores them back to the same State.
It does not save an objects code. Only it’s attributes values.
It cannot store file handles or connection sockets.
In short we can say, pickling is a way to store and retrieve data variables into and out from files where variables can be lists, classes, etc.
To Pickle something you must −
import pickle
Write a variable to file, something like
pickle.dump(mystring, outfile, protocol),
where 3rd argument protocol is optional
To unpickling something you must −
Import pickle
Write a variable to a file, something like
myString = pickle.load(inputfile)
The pickle interface provides four different methods.
dump() − The dump() method serializes to an open file (file-like object).
dump() − The dump() method serializes to an open file (file-like object).
dumps() − Serializes to a string
dumps() − Serializes to a string
load() − Deserializes from an open-like object.
load() − Deserializes from an open-like object.
loads() − Deserializes from a string.
loads() − Deserializes from a string.
Based on above procedure, below is an example of “pickling”.
My Cat pussy is White and has 4 legs
Would you like to see her pickled? Here she is!
b'\x80\x03c__main__\nCat\nq\x00)\x81q\x01}q\x02(X\x0e\x00\x00\x00number_of_legsq\x03K\x04X\x05\x00\x00\x00colorq\x04X\x05\x00\x00\x00Whiteq\x05ub.'
So, in the example above, we have created an instance of a Cat class and then we’ve pickled it, transforming our “Cat” instance into a simple array of bytes.
This way we can easily store the bytes array on a binary file or in a database field and restore it back to its original form from our storage support in a later time.
Also if you want to create a file with a pickled object, you can use the dump() method ( instead of the dumps*()* one) passing also an opened binary file and the pickling result will be stored in the file automatically.
[....]
binary_file = open(my_pickled_Pussy.bin', mode='wb')
my_pickled_Pussy = pickle.dump(Pussy, binary_file)
binary_file.close()
The process that takes a binary array and converts it to an object hierarchy is called unpickling.
The unpickling process is done by using the load() function of the pickle module and returns a complete object hierarchy from a simple bytes array.
Let’s use the load function in our previous example.
MeOw is black
Pussy is white
JSON(JavaScript Object Notation) has been part of the Python standard library is a lightweight data-interchange format. It is easy for humans to read and write. It is easy to parse and generate.
Because of its simplicity, JSON is a way by which we store and exchange data, which is accomplished through its JSON syntax, and is used in many web applications. As it is in human readable format, and this may be one of the reasons for using it in data transmission, in addition to its effectiveness when working with APIs.
An example of JSON-formatted data is as follow −
{"EmployID": 40203, "Name": "Zack", "Age":54, "isEmployed": True}
Python makes it simple to work with Json files. The module sused for this purpose is the JSON module. This module should be included (built-in) within your Python installation.
So let’s see how can we convert Python dictionary to JSON and write it to a text file.
Reading JSON means converting JSON into a Python value (object). The json library parses JSON into a dictionary or list in Python. In order to do that, we use the loads() function (load from a string), as follow −
Below is one sample json file,
data1.json
{"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}}
Above content (Data1.json) looks like a conventional dictionary. We can use pickle to store this file but the output of it is not human readable form.
JSON(Java Script Object Notification) is a very simple format and that’s one of the reason for its popularity. Now let’s look into json output through below program.
Above we open the json file (data1.json) for reading, obtain the file handler and pass on to json.load and getting back the object. When we try to print the output of the object, its same as the json file. Although the type of the object is dictionary, it comes out as a Python object. Writing to the json is simple as we saw this pickle. Above we load the json file, add another key value pair and writing it back to the same json file. Now if we see out data1.json, it looks different .i.e. not in the same format as we see previously.
To make our Output looks same (human readable format), add the couple of arguments into our last line of the program,
json.dump(conf, fh, indent = 4, separators = (‘,’, ‘: ‘))
Similarly like pickle, we can print the string with dumps and load with loads. Below is an example of that,
YAML may be the most human friendly data serialization standard for all programming languages.
Python yaml module is called pyaml
YAML is an alternative to JSON −
Human readable code − YAML is the most human readable format so much so that even its front-page content is displayed in YAML to make this point.
Human readable code − YAML is the most human readable format so much so that even its front-page content is displayed in YAML to make this point.
Compact code − In YAML we use whitespace indentation to denote structure not brackets.
Compact code − In YAML we use whitespace indentation to denote structure not brackets.
Syntax for relational data − For internal references we use anchors (&) and aliases (*).
Syntax for relational data − For internal references we use anchors (&) and aliases (*).
One of the area where it is used widely is for viewing/editing of data structures − for example configuration files, dumping during debugging and document headers.
One of the area where it is used widely is for viewing/editing of data structures − for example configuration files, dumping during debugging and document headers.
As yaml is not a built-in module, we need to install it manually. Best way to install yaml on windows machine is through pip. Run below command on your windows terminal to install yaml,
pip install pyaml (Windows machine)
sudo pip install pyaml (*nix and Mac)
On running above command, screen will display something like below based on what’s the current latest version.
Collecting pyaml
Using cached pyaml-17.12.1-py2.py3-none-any.whl
Collecting PyYAML (from pyaml)
Using cached PyYAML-3.12.tar.gz
Installing collected packages: PyYAML, pyaml
Running setup.py install for PyYAML ... done
Successfully installed PyYAML-3.12 pyaml-17.12.1
To test it, go to the Python shell and import the yaml module,
import yaml, if no error is found, then we can say installation is successful.
After installing pyaml, let’s look at below code,
script_yaml1.py
Above we created three different data structure, dictionary, list and tuple. On each of the structure, we do yaml.dump. Important point is how the output is displayed on the screen.
Dictionary output looks clean .ie. key: value.
White space to separate different objects.
List is notated with dash (-)
Tuple is indicated first with !!Python/tuple and then in the same format as lists.
Loading a yaml file
So let’s say I have one yaml file, which contains,
---
# An employee record
name: Raagvendra Joshi
job: Developer
skill: Oracle
employed: True
foods:
- Apple
- Orange
- Strawberry
- Mango
languages:
Oracle: Elite
power_builder: Elite
Full Stack Developer: Lame
education:
4 GCSEs
3 A-Levels
MCA in something called com
Now let’s write a code to load this yaml file through yaml.load function. Below is code for the same.
As the output doesn’t looks that much readable, I prettify it by using json in the end. Compare the output we got and the actual yaml file we have.
One of the most important aspect of software development is debugging. In this section we’ll see different ways of Python debugging either with built-in debugger or third party debuggers.
The module PDB supports setting breakpoints. A breakpoint is an intentional pause of the program, where you can get more information about the programs state.
To set a breakpoint, insert the line
pdb.set_trace()
pdb_example1.py
import pdb
x = 9
y = 7
pdb.set_trace()
total = x + y
pdb.set_trace()
We have inserted a few breakpoints in this program. The program will pause at each breakpoint (pdb.set_trace()). To view a variables contents simply type the variable name.
c:\Python\Python361>Python pdb_example1.py
> c:\Python\Python361\pdb_example1.py(8)<module>()
-> total = x + y
(Pdb) x
9
(Pdb) y
7
(Pdb) total
*** NameError: name 'total' is not defined
(Pdb)
Press c or continue to go on with the programs execution until the next breakpoint.
(Pdb) c
--Return--
> c:\Python\Python361\pdb_example1.py(8)<module>()->None
-> total = x + y
(Pdb) total
16
Eventually, you will need to debug much bigger programs – programs that use subroutines. And sometimes, the problem that you’re trying to find will lie inside a subroutine. Consider the following program.
import pdb
def squar(x, y):
out_squared = x^2 + y^2
return out_squared
if __name__ == "__main__":
#pdb.set_trace()
print (squar(4, 5))
Now on running the above program,
c:\Python\Python361>Python pdb_example2.py
> c:\Python\Python361\pdb_example2.py(10)<module>()
-> print (squar(4, 5))
(Pdb)
We can use ? to get help, but the arrow indicates the line that’s about to be executed. At this point it’s helpful to hit s to s to step into that line.
(Pdb) s
--Call--
>c:\Python\Python361\pdb_example2.py(3)squar()
-> def squar(x, y):
This is a call to a function. If you want an overview of where you are in your code, try l −
(Pdb) l
1 import pdb
2
3 def squar(x, y):
4 -> out_squared = x^2 + y^2
5
6 return out_squared
7
8 if __name__ == "__main__":
9 pdb.set_trace()
10 print (squar(4, 5))
[EOF]
(Pdb)
You can hit n to advance to the next line. At this point you are inside the out_squared method and you have access to the variable declared inside the function .i.e. x and y.
(Pdb) x
4
(Pdb) y
5
(Pdb) x^2
6
(Pdb) y^2
7
(Pdb) x**2
16
(Pdb) y**2
25
(Pdb)
So we can see the ^ operator is not what we wanted instead we need to use ** operator to do squares.
This way we can debug our program inside the functions/methods.
The logging module has been a part of Python’s Standard Library since Python version 2.3. As it’s a built-in module all Python module can participate in logging, so that our application log can include your own message integrated with messages from third party module. It provides a lot of flexibility and functionality.
Diagnostic logging − It records events related to the application’s operation.
Diagnostic logging − It records events related to the application’s operation.
Audit logging − It records events for business analysis.
Audit logging − It records events for business analysis.
Messages are written and logged at levels of “severity” &minu
DEBUG (debug()) − diagnostic messages for development.
DEBUG (debug()) − diagnostic messages for development.
INFO (info()) − standard “progress” messages.
INFO (info()) − standard “progress” messages.
WARNING (warning()) − detected a non-serious issue.
WARNING (warning()) − detected a non-serious issue.
ERROR (error()) − encountered an error, possibly serious.
ERROR (error()) − encountered an error, possibly serious.
CRITICAL (critical()) − usually a fatal error (program stops).
CRITICAL (critical()) − usually a fatal error (program stops).
Let’s looks into below simple program,
import logging
logging.basicConfig(level=logging.INFO)
logging.debug('this message will be ignored') # This will not print
logging.info('This should be logged') # it'll print
logging.warning('And this, too') # It'll print
Above we are logging messages on severity level. First we import the module, call basicConfig and set the logging level. Level we set above is INFO. Then we have three different statement: debug statement, info statement and a warning statement.
INFO:root:This should be logged
WARNING:root:And this, too
As the info statement is below debug statement, we are not able to see the debug message. To get the debug statement too in the Output terminal, all we need to change is the basicConfig level.
logging.basicConfig(level = logging.DEBUG)
And in the Output we can see,
DEBUG:root:this message will be ignored
INFO:root:This should be logged
WARNING:root:And this, too
Also the default behavior means if we don’t set any logging level is warning. Just comment out the second line from the above program and run the code.
#logging.basicConfig(level = logging.DEBUG)
WARNING:root:And this, too
Python built in logging level are actually integers.
>>> import logging
>>>
>>> logging.DEBUG
10
>>> logging.CRITICAL
50
>>> logging.WARNING
30
>>> logging.INFO
20
>>> logging.ERROR
40
>>>
We can also save the log messages into the file.
logging.basicConfig(level = logging.DEBUG, filename = 'logging.log')
Now all log messages will go the file (logging.log) in your current working directory instead of the screen. This is a much better approach as it lets us to do post analysis of the messages we got.
We can also set the date stamp with our log message.
logging.basicConfig(level=logging.DEBUG, format = '%(asctime)s %(levelname)s:%(message)s')
Output will get something like,
2018-03-08 19:30:00,066 DEBUG:this message will be ignored
2018-03-08 19:30:00,176 INFO:This should be logged
2018-03-08 19:30:00,201 WARNING:And this, too
Benchmarking or profiling is basically to test how fast is your code executes and where the bottlenecks are? The main reason to do this is for optimization.
Python comes with a in-built module called timeit. You can use it to time small code snippets. The timeit module uses platform-specific time functions so that you will get the most accurate timings possible.
So, it allows us to compare two shipment of code taken by each and then optimize the scripts to given better performance.
The timeit module has a command line interface, but it can also be imported.
There are two ways to call a script. Let’s use the script first, for that run the below code and see the Output.
import timeit
print ( 'by index: ', timeit.timeit(stmt = "mydict['c']", setup = "mydict = {'a':5, 'b':10, 'c':15}", number = 1000000))
print ( 'by get: ', timeit.timeit(stmt = 'mydict.get("c")', setup = 'mydict = {"a":5, "b":10, "c":15}', number = 1000000))
by index: 0.1809192126703489
by get: 0.6088525265034692
Above we use two different method .i.e. by subscript and get to access the dictionary key value. We execute statement 1 million times as it executes too fast for a very small data. Now we can see the index access much faster as compared to the get. We can run the code multiply times and there will be slight variation in the time execution to get the better understanding.
Another way is to run the above test in the command line. Let’s do it,
c:\Python\Python361>Python -m timeit -n 1000000 -s "mydict = {'a': 5, 'b':10, 'c':15}" "mydict['c']"
1000000 loops, best of 3: 0.187 usec per loop
c:\Python\Python361>Python -m timeit -n 1000000 -s "mydict = {'a': 5, 'b':10, 'c':15}" "mydict.get('c')"
1000000 loops, best of 3: 0.659 usec per loop
Above output may vary based on your system hardware and what all applications are running currently in your system.
Below we can use the timeit module, if we want to call to a function. As we can add multiple statement inside the function to test.
import timeit
def testme(this_dict, key):
return this_dict[key]
print (timeit.timeit("testme(mydict, key)", setup = "from __main__ import testme; mydict = {'a':9, 'b':18, 'c':27}; key = 'c'", number = 1000000))
0.7713474590139164
Requests is a Python module which is an elegant and simple HTTP library for Python. With this you can send all kinds of HTTP requests. With this library we can add headers, form data, multipart files and parameters and access the response data.
As Requests is not a built-in module, so we need to install it first.
You can install it by running the following command in the terminal −
pip install requests
Once you have installed the module, you can verify if the installation is successful by typing below command in the Python shell.
import requests
If the installation has been successful, you won’t see any error message.
As a means of example we’ll be using the “pokeapi”
The requests library methods for all of the HTTP verbs currently in use. If you wanted to make a simple POST request to an API endpoint then you can do that like so −
req = requests.post(‘http://api/user’, data = None, json = None)
This would work in exactly the same fashion as our previous GET request, however it features two additional keyword parameters −
data which can be populated with say a dictionary, a file or bytes that will be passed in the HTTP body of our POST request.
data which can be populated with say a dictionary, a file or bytes that will be passed in the HTTP body of our POST request.
json which can be populated with a json object that will be passed in the body of our HTTP request also.
json which can be populated with a json object that will be passed in the body of our HTTP request also.
Pandas is an open-source Python Library providing high-performance data manipulation and analysis tool using its powerful data structures. Pandas is one of the most widely used Python libraries in data science. It is mainly used for data munging, and with good reason: Powerful and flexible group of functionality.
Built on Numpy package and the key data structure is called the DataFrame. These dataframes allows us to store and manipulate tabular data in rows of observations and columns of variables.
There are several ways to create a DataFrame. One way is to use a dictionary. For example −
From the output we can see new brics DataFrame, Pandas has assigned a key for each country as the numerical values 0 through 4.
If instead of giving indexing values from 0 to 4, we would like to have different index values, say the two letter country code, you can do that easily as well −
Adding below one lines in the above code, gives
brics.index = ['BR', 'RU', 'IN', 'CH', 'SA']
Pygame is the open source and cross-platform library that is for making multimedia applications including games. It includes computer graphics and sound libraries designed to be used with the Python programming language. You can develop many cool games with Pygame.’
Pygame is composed of various modules, each dealing with a specific set of tasks. For example, the display module deals with the display window and screen, the draw module provides functions to draw shapes and the key module works with the keyboard. These are just some of the modules of the library.
The home of the Pygame library is at https://www.pygame.org/news
To make a Pygame application, you follow these steps −
Import the Pygame library
import pygame
Initialize the Pygame library
pygame.init()
Create a window.
screen = Pygame.display.set_mode((560,480))
Pygame.display.set_caption(‘First Pygame Game’)
Initialize game objects
In this step we load images, load sounds, do object positioning, set up some state variables, etc.
Start the game loop.
It is just a loop where we continuously handle events, checks for input, move objects, and draw them. Each iteration of the loop is called a frame.
Let’s put all the above logic into one below program,
Pygame_script.py
The general idea behind web scraping is to get the data that exists on a website, and convert it into some format that is usable for analysis.
It’s a Python library for pulling data out of HTML or XML files. With your favourite parser it provide idiomatic ways of navigating, searching and modifying the parse tree.
As BeautifulSoup is not a built-in library, we need to install it before we try to use it. To install BeautifulSoup, run the below command
$ apt-get install Python-bs4 # For Linux and Python2
$ apt-get install Python3-bs4 # for Linux based system and Python3.
$ easy_install beautifulsoup4 # For windows machine,
Or
$ pip instal beatifulsoup4 # For window machine
Once the installation is done, we are ready to run few examples and explores Beautifulsoup in details,
Below are some simple ways to navigate that data structure −
One common task is extracting all the URLs found within a page’s <a> tags −
Another common task is extracting all the text from a page −
14 Lectures
1.5 hours
Harshit Srivastava
60 Lectures
8 hours
DigiFisk (Programming Is Fun)
11 Lectures
35 mins
Sandip Bhattacharya
21 Lectures
2 hours
Pranjal Srivastava
6 Lectures
43 mins
Frahaan Hussain
49 Lectures
4.5 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1995,
"s": 1810,
"text": "Programming languages are emerging constantly, and so are different methodologies.Object-oriented programming is one such methodology that has become quite popular over past few years."
},
{
"code": null,
"e": 2119,
"s": 1995,
"text"... |
jQuery Tutorial | This jQuery Tutorial has been prepared by well experienced front end programmers who are using Javascript and jQuery extensively in their projects. This tutorial has been developed for the jQuery beginners to help them understand the basics to advanced of jQuery Framework. After completing this tutorial, you will find yourself at a great level of expertise in jQuery Framework, from where you can take yourself to the next levels.
jQuery is a lightweight Javascript library which is blazing fast and concise. This library was created by John Resig in 2006 and
jQuery has been designed to simplify HTML DOM tree traversal and manipulation, as well as event handling, CSS animation, and Ajax.
jQuery can be used to find a particular HTML element in the HTML document with a certain ID, class or attribute and later we can use jQuery to change one or more of attributes of the same element like color, visibility etc. jQuery can also be used to make a webpage interactive by responding to an event like a mouse click.
jQuery has been developed with the following principles:
Separation of JavaScript and HTML, which encourages developers to completely separate JavaScript code from HTML markup.
Separation of JavaScript and HTML, which encourages developers to completely separate JavaScript code from HTML markup.
Brevity and clarity promotes features like chainable functions and shorthand function names.
Brevity and clarity promotes features like chainable functions and shorthand function names.
Eliminates of cross-browser incompatibilities, so developers does not need to worry about browser compatibility while writing code using jQuery library.
Eliminates of cross-browser incompatibilities, so developers does not need to worry about browser compatibility while writing code using jQuery library.
Extensibility, which means new events, elements, and methods can be easily added in jQuery library and then reused as a plugin.
Extensibility, which means new events, elements, and methods can be easily added in jQuery library and then reused as a plugin.
We have provided jQuery Online Editor which helps you to Edit and Execute the code directly from your browser. Try to click the icon to run the following jQuery code to print conventional "Hello, World!".
<html>
<head>
<title>The jQuery Example</title>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js">
</script>
<script type = "text/javascript">
$(document).ready(function() {
document.write("Hello, World!");
});
</script>
</head>
<body>
<h1>Hello</h1>
</body>
</html>
As of April 2022, jQuery 3.0 and newer supports "current-1 versions" of Firefox, Chrome, Safari, and Edge as well as Internet Explorer 9 and newer versions. On mobile it supports iOS 7 and newer, and Android 4.0 and newer.
jQuery and Javascripts both are very high in demand and all major web applications are making use of jQuery in one or another way. We explored many major job websites before writing this tutorial and found that there are numerous openings across the world in multi national companies.
Average annual salary for a Javascript and jQuery developer is around $150,000. Though it can vary depending on the location. Following are the great companies who are using Kotlin:
Google
Google
Amazon
Amazon
Netflix
Netflix
Zomato
Zomato
Uber
Uber
Trello
Trello
Coursera
Coursera
Basecamp
Basecamp
Unacademy
Unacademy
Byjus
Byjus
Many more...
Many more...
So, you could be the next potential employee for any of these major companies. We have develop a great learning material for jQuery which will help you to prepare for the technical interviews and certification exams based on jQuery. So, start learning jQuery using our simple and effective tutorial anywhere and anytime absolutely at your pace.
Before proceeding with this tutorial, you should have a basic understanding of HTML, CSS, JavaScript, Document Object Model (DOM) and any text editor. As we are going to develop web based application using jQuery, it will be good if you have understanding on how internet and web based applications work.
27 Lectures
1 hours
Mahesh Kumar
27 Lectures
1.5 hours
Pratik Singh
72 Lectures
4.5 hours
Frahaan Hussain
60 Lectures
9 hours
Eduonix Learning Solutions
17 Lectures
2 hours
Sandip Bhattacharya
12 Lectures
53 mins
Laurence Svekis
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2755,
"s": 2322,
"text": "This jQuery Tutorial has been prepared by well experienced front end programmers who are using Javascript and jQuery extensively in their projects. This tutorial has been developed for the jQuery beginners to help them understand the basics to advanced ... |
How to Build a Simple Movie Recommender System with Tags | by Johnson Kuan | Towards Data Science | Let’s suppose you’re launching the next great subscription video-on-demand (SVOD) streaming service and you’ve secured the rights to stream all major movie titles released in the past 100 years. Congrats on this incredible feat!
Now that’s a lot of movies. Without some sort of recommender system, you’re concerned that users may be inundated over time with movies they don’t care about. This could drive customer churn which is the last thing you want!
So you decide to build a movie recommender system. Since your service is new, you don’t have enough data yet on what movies are being watched by which users. This is known as the cold start problem and it precludes you from recommending movies based only on the historical viewership of users.
Luckily, even without adequate viewership data we can still build a decent recommender system with movie metadata. That’s where MovieLens comes in. MovieLens provides a public dataset with keyword tags for each movie. These tags are quite informative. For example, check out the top community tags below for Good Will Hunting.
In the rest of this post, I’ll answer three business questions that are critical to building a simple content-based recommender system with tags from MovieLens:
How many tags do we need for each movie?How do we use tags to measure the similarity between movies?How do we use tags to generate movie recommendations for a user?
How many tags do we need for each movie?
How do we use tags to measure the similarity between movies?
How do we use tags to generate movie recommendations for a user?
Excerpt from wikipedia page on content-based recommender systems:
“Content-based filtering methods are based on a description of the item and a profile of the user’s preferences. These methods are best suited to situations where there is known data on an item (name, location, description, etc.), but not on the user. Content-based recommenders treat recommendation as a user-specific classification problem and learn a classifier for the user’s likes and dislikes based on product features.”
The code for this analysis can be found here along with the data and Conda environment YAML file for you to easily reproduce the results.
There are about 10K unique movies and 1K unique tags in the MovieLens tags genome dataset. Each movie has a relevance score for every tag so that’s about 10M movie-tag pairs. The relevance score ranges from 0 to 1.
Not every tag is relevant for a movie so we need to only keep the most relevant tags. First, we can rank order the tags for each movie based on the relevance score. For example, below top 10 tags for Remember the Titans. Note that the relevance scores are well above 0.9 which indicate that they’re very relevant tags.
Next, we confirm in the chart below that higher ranked tags for a movie tend to have higher median relevance scores. Tags in the 1st rank for a movie have a median relevance score of almost 1. We can see that the median relevance score gradually decreases as we go down to the 50th rank.
To find the most relevant tags for a movie, we can keep the top N tags for a movie based on relevance score. Here, we need to pick N carefully. If N is small, we have very relevant but few tags. If N is large, we have many tags but a lot of them could be irrelevant.
Chart below shows the percent change in median relevance score as we go from tags in the 1st to 100th rank. We see an inflection point around the 50th rank when the relevance score starts to become more stable. Thus, we can chose N = 50 as a reasonable number of tags to keep for each movie. Note that this is quite a simple “elbow method” styled approach which can be optimized later.
Now we can get the list of top 50 tags for each movie which we’ll use in the next sections. For example, below top 50 tags for Toy Story.
Before generating movie recommendations for a user, we need a way to measure the similarity between movies based on their top 50 tags. In content-based recommender systems, users will be recommended movies that are similar to movies they’ve already watched.
Here, I’ll demonstrate two ways of measuring similarity:
Jaccard Index of two sets of movie tagsCosine Similarity of movie vectors (aka content embeddings) based on tags
Jaccard Index of two sets of movie tags
Cosine Similarity of movie vectors (aka content embeddings) based on tags
Jaccard Index
The first approach with Jaccard Index measures the similarity between two sets A and B as the size of the intersection divided by the size of the union. When measuring the similarity between movies, we can compute this index for the two sets of movie tags.
For example, let’s say we have three movies below and their top 3 tags:
movie A tags = (action, space, friendship)
movie B tags = (adventure, space, friendship)
movie C tags = (romantic, comedy, coming-of-age)
Intuitively, we can see that movie A is more similar to B than C. This is because movies A and B share two tags (space, friendship) whereas movies A and C don’t share any tags.
Below top 10 movies similar to Good Will Hunting based on Jaccard Index. For viewers of Good Will Hunting, these look like reasonable recommendations. Note that I included Good Will Hunting on the list to show that the Jaccard Index = 1 when comparing a movie with itself.
Below top 10 movies similar to Interstellar based on Jaccard Index. For viewers of Interstellar, these also look like reasonable recommendations.
To further illustrate the effectiveness of Jaccard Index, see below word cloud based on tag frequency from movies similar to Interstellar. Here, we can see which tags are more prominent in the similarity calculation (e.g. science fiction, great ending, dystopic future, philosophical, cerebral).
Cosine Similarity of Movie Vectors (aka Content Embeddings)
The first approach with Jaccard Index helped us build an intuition about what it means to be similar with tags. The second approach here with cosine similarity is a bit more complex. It requires that we represent our movies as a vector. Here, a vector is just a set of numbers.
For example, we can represent the same movies before as a set of three real numbers:
movie A = (1.1, 2.3, 5.1)
movie B = (1.3, 2.1, 4.9)
movie C = (5.1, 6.2, 1.1)
Intuitively, again we can see that movie A is more similar to B than C. This is because movies A and B have closer numbers in each dimension (e.g. 1.1 vs 1.3 in the first dimension).
To find a good vector representation of movies, I use the Doc2Vec (PV-DBOW) technique from this paper which takes a movie (document) and learns a mapping to a latent K dimensional vector space based on its tags (words in the document). I won’t go into the details here, but this is how we can represent movies as a vector based on tags.
Once we can represent each movie as a vector, we can compute the cosine similarity between vectors to find movies that are similar. I won’t go into the details of cosine similarity here, but at a high level it tells us how similar movie vectors are to each other which we can use to generate recommendations.
Below I visualize the movie vectors in 2D with UMAP which is a popular non-linear dimensionality reduction technique. We can see that movies that are closer together in this vector space are more similar (e.g. Toy Story and Monsters, Inc.).
Now that we can measure the similarity between movies with tags, we can start generating movie recommendations to users.
Remember that in content-based recommender systems, users will be recommended movies that are similar to movies they’ve already watched. If the user has only seen one movie (e.g. Good Will Hunting), we can simply use the Jaccard Index (or Cosine Similarity) as before to generate a list of similar movies to recommend.
More realistically, a user will have watched a set of movies and we need to generate recommendations based on the combined attributes of these movies.
One simple way is to compute a user vector as an average of the movie vectors that they’ve seen. These user vectors can represent the user’s profile of movie preferences.
For example, if a user has only seen movies A and B below:
Movie A = (1, 2, 3)
Movie B = (7, 2, 1)
User vector = average of movies A and B = (4, 2, 2)
Below are movies that I watch and enjoy. How do we generate movie recommendations using tags from these movies?
Interstellar, Good Will Hunting, Gattaca, Almost Famous, The Shawshank Redemption, Edge of Tomorrow, Jerry Maguire, Forrest Gump, Back to the Future
Well my user vector would be an average of the movie vectors for the nine movies above. I can take my user vector and find the most similar movies (based on cosine similarity) that I haven’t watched yet. Below are my movie recommendations which are surprisingly good considering we’re only using movie tags here! Feel free to play with the notebook and generate your own recommendations.
The Theory of EverythingCast AwayDead Poets SocietyCharlyRain ManGroundhog DayPay It ForwardA Beautiful MindE.T. the Extra-TerrestrialMr. Holland's OpusOn Golden PondIt's a Wonderful LifeChildren of a Lesser GodThe Curious Case of Benjamin ButtonStar Trek II: The Wrath of KhanCinema ParadisoMr. Smith Goes to WashingtonThe TerminalHerThe World's Fastest IndianThe Truman ShowStar Trek: First ContactThe Family Man
Below summary of our content-based recommender system. Note that we can precompute the user vector and similarity scores in a batch process to speedup the serving of recommendations if we deploy our system as an API.
Input: User vector (average of movie vectors learned from tags)
Output: List of movies that are similar to the user based on cosine similarity of user and movie vectors | [
{
"code": null,
"e": 400,
"s": 171,
"text": "Let’s suppose you’re launching the next great subscription video-on-demand (SVOD) streaming service and you’ve secured the rights to stream all major movie titles released in the past 100 years. Congrats on this incredible feat!"
},
{
"code": null... |
Apache Derby - Create Table | The CREATE TABLE statement is used for creating a new table in Derby database.
Following is the syntax of the CREATE statement.
CREATE TABLE table_name (
column_name1 column_data_type1 constraint (optional),
column_name2 column_data_type2 constraint (optional),
column_name3 column_data_type3 constraint (optional)
);
Another way to create a table in Apache Derby is that you can specify the column names and data types using a query. The syntax for this is given below −
CREATE TABLE table_name AS SELECT * FROM desired_table WITH NO DATA;
The following SQL statement creates a table named Student with four columns, where id is the primary key and it is auto generated.
ij> CREATE TABLE Student (
Id INT NOT NULL GENERATED ALWAYS AS IDENTITY,
Age INT NOT NULL,
First_Name VARCHAR(255),
last_name VARCHAR(255),
PRIMARY KEY (Id)
);
> > > > > > > 0 rows inserted/updated/deleted
The DESCRIBE command describes specified table by listing the columns and their details, if the table exists. You can use this command to verify if the table is created.
ij> DESCRIBE Student;
COLUMN_NAME |TYPE_NAME |DEC&|NUM&|COLUM&|COLUMN_DEF|CHAR_OCTE&|IS_NULL&
------------------------------------------------------------------------------
ID |INTEGER |0 |10 |10 |AUTOINCRE&|NULL |NO
AGE |INTEGER |0 |10 |10 |NULL |NULL |NO
FIRST_NAME |VARCHAR |NULL|NULL|255 |NULL |510 |YES
LAST_NAME |VARCHAR |NULL|NULL|255 |NULL |510 |YES
4 rows selected
This section teaches you how to create a table in Apache Derby database using JDBC application.
If you want to request the Derby network server using network client, make sure that the server is up and running. The class name for the Network client driver is org.apache.derby.jdbc.ClientDriver and the URL is jdbc:derby://localhost:1527/DATABASE_NAME;create=true;user=USER_NAME;passw
ord=PASSWORD".
Follow the steps given below to create a table in Apache Derby −
To communicate with the database, first of all, you need to register the driver. The forName() method of the class, Class accepts a String value representing a class name loads it in to the memory, which automatically registers it. Register the driver using this method.
In general, the first step we do to communicate to the database is to connect with it. The Connection class represents the physical connection with a database server. You can create a connection object by invoking the getConnection() method of the DriverManager class. Create a connection using this method.
You need to create a Statement or PreparedStatement or, CallableStatement objects to send SQL statements to the database. You can create these using the methods createStatement(), prepareStatement() and, prepareCall() respectively. Create either of these objects using the appropriate method.
After creating a statement, you need to execute it. The Statement class provides various methods to execute a query like the execute() method to execute a statement that returns more than one result set. The executeUpdate() method executes queries like INSERT, UPDATE, DELETE. The executeQuery() method to results that returns data etc. Use either of these methods and execute the statement created previously.
Following JDBC example demonstrates how to create a table in Apache Derby using JDBC program. Here, we are connecting to a database named sampleDB (will create if it does not exist) using the embedded driver.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class CreateTable {
public static void main(String args[]) throws Exception {
//Registering the driver
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
//Getting the Connection object
String URL = "jdbc:derby:sampleDB;create=true";
Connection conn = DriverManager.getConnection(URL);
//Creating the Statement object
Statement stmt = conn.createStatement();
//Executing the query
String query = "CREATE TABLE Employees( "
+ "Id INT NOT NULL GENERATED ALWAYS AS IDENTITY, "
+ "Name VARCHAR(255), "
+ "Salary INT NOT NULL, "
+ "Location VARCHAR(255), "
+ "PRIMARY KEY (Id))";
stmt.execute(query);
System.out.println("Table created");
}
}
On executing the above program, you will get the following output
Table created
46 Lectures
3.5 hours
Arnab Chakraborty
23 Lectures
1.5 hours
Mukund Kumar Mishra
16 Lectures
1 hours
Nilay Mehta
52 Lectures
1.5 hours
Bigdata Engineer
14 Lectures
1 hours
Bigdata Engineer
23 Lectures
1 hours
Bigdata Engineer
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2259,
"s": 2180,
"text": "The CREATE TABLE statement is used for creating a new table in Derby database."
},
{
"code": null,
"e": 2308,
"s": 2259,
"text": "Following is the syntax of the CREATE statement."
},
{
"code": null,
"e": 2508,
"s": 23... |
7 Steps to Design a Basic Neural Network (part 1 of 2) | by Gabe Verzino | Towards Data Science | This two-part article takes a more holistic, overarching (and yes, less math-y) approach to building a neural network from scratch. Python for completing the network is also included in each of the 7 steps.
Part One: (1) Define the network structure, (2) Initialize parameters, and (3) Implement forward propagation. Part Two: (4) Estimate cost, (5) Implement backward propagation, (6) Update parameters, and (7) Make predictions.
Data is often non-linearly distributed, or contains unusual boundaries for which traditional classification models can’t differentiate very well. For example, let’s say we want to correctly classify the red and blue dots in the dataset below:
We can start with a logistic regression — the go-to model for binary classification problems. As usual, we’ll import the necessary libraries and fit the logistic model to our X variable (i.e. the x-axis and y-axis coordinates of the dots above) and our Y outcome variable (i.e. red or blue dots).
import pandas as pdfrom sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import classification_report, confusion_matrixlogmodel = LogisticRegression()logmodel.fit(X.T, Y.T)predictions = logmodel.predict(X.T)
Applying the boundary predictions for the logistic regression model, we can immediately see some misclassification occurring.
plot_decision_boundary(lambda x: logmodel.predict(x), X, Y)plt.title("Logistic Regression")
While most dots got predicted accurately, some red dots are getting classified as blue, and vice-versa. This model is a bit too general and under-fits the data, which will result in high bias. Running a quick classification report and confusion matrix shows the accuracy of our logistic model is about 87%.
print(classification_report(predictions, Y.T))
conf_matrix = np.array(confusion_matrix(Y.T, predictions))pd.DataFrame(conf_matrix, index=['Purple','Red'],columns=['Predicted Purple','Predicted Red'])
While this might suffice for some data tasks — a basic prediction model or a quick gut-check — neural networks can do a much better job at recognizing complex patterns (like the above) and optimizing your prediction.
Alrighty, so let’s get to it!
People compare neural networks to neurons in the brain because they look similar and are both involved in learning. Truth is, unlike brain neurons, neural networks “fire messages” both ways, and this unique bi-directionality is central to learning that occurs in backward propagation (covered in Part 2).
With that visual in mind, we first have to structure our neural network. As shown below, networks contain nodes and layers (columns of nodes).
Input Layer: From left to right, we begin with the input layer and 2 nodes, each node representing a variable from our dataset (our X variable contains both X- and Y-axis coordinate data, so it becomes X1 and X2).
Hidden Layer: In a process known as forward propagation, input layer data is transmitted to each of 4 nodes in the hidden layer. The number of nodes you choose in the hidden later is important; too few nodes and your model may underfit, and too many nodes may cause your model to overfit and run slowly. Given the information explained in this StackExchange post, we’ll choose 4 nodes for our hidden layer.
Output Layer: Information from the hidden layer is then transferred to the output layer to make our final predictions (i.e. is the dot blue or red?). This is made possible by completing some steps mentioned later on in this article (estimating cost, backward propagation, and updating our parameters).
So let’s create these 3 layers now with their corresponding number of nodes.
def layer_sizes(X, Y): """Takes the arguments: X = shape of feature variable data Y = shape of the output data Returns: n_x = input layer size n_h = hidden layer size n_y = output layer size""" n_x = X.shape[0] n_h = 4 n_y = Y.shape[0] return(n_x, n_h, n_y)(n_x, n_h, n_y) = layer_sizes(X, Y)print("The size of the input layer is: n_x = " + str(n_x))print("The size of the hidden layer is: n_h = " + str(n_h))print("The size of the output layer is: n_y = " + str(n_y))
The output of which is:
Now that we have defined our network structure, we need to think about building functions that will transfer input-layer data into our hidden layer to kick-start the neural network process. However, these functions contain terms (called parameters) for which we must initialize (i.e. set values).
Here’s our first function that will be used (in Step 3. Forward Propagation):
In this function, we already have x our input data, w the weight (significance) to that data, and b our bias term. The w and b are the parameters. And because we don’t have values for the parameters yet we must initialize them.
How and why we initialize these parameters has a great deal to do with gradient descent — a central component to neural network behavior. So let’s chat about that briefly.
Like many nondeterministic models, neural networks operate on the premise of stochastic gradient descent. During training, these algorithms take incremental steps to minimize cost — a single value that reflects how well the model performed as a whole (i.e. error between predicted and actual values). And the “learning steps” they take to achieve that depends on our w (weights) and b (biases).
For our model, we want the lowest cost possible. Imagine the gradient descent process as a ball rolling down hills, attempting to find the lowest point (cost).
In good (not great) models, the cost can get stuck at a lower point from where it began (a local minimum), but not at an absolute low (the global minimum). So, because we (1) can’t visualize our search space in advance, and (2) don’t want to “trap” our model in a suboptimal cost, a good approach is to initialize our parameters w (weights) and b (biases) with random values. This ensures gradient descent begins anywhere without injecting our own bias.
Secondly, we want small values for our parameters — for example, something on the order of 0.01. It’s a bit of Goldilocks here with our choice; a value too large and the cost will oscillate too much around a minimum value (i.e. an “exploding gradient problem”), and a value of zero basically prevents our gradient from updating any weights. This is called “failing to break symmetry” and results from neurons computing similar outputs, preventing independent learning, and essentially nullifying the advantages of neural networks.
The parameters we need to initialize will span the input layer to the hidden layer (call them W1 and b1), and then the hidden layer to the output layer (call them W2 and b2). And as we mentioned just above, we’ll initialize them as random, small values. Note that the bias terms b1 and b2 are vectors, and because they are added to the w*x products through broadcasting, they can just be initialized as zeros with columns of size 1.
def initialize_parameters(n_x, n_h, n_y): """Initialize the parameters for weight matrix w1, w2 and bias vectors b1, b2. Where: n_x -- size of the input layer n_h -- size of the hidden layer n_y -- size of the output layer Returns: params -- python dictionary containing your parameters: W1 -- weight matrix of shape (n_h, n_x) b1 -- bias vector of shape (n_h, 1) W2 -- weight matrix of shape (n_y, n_h) b2 -- bias vector of shape (n_y, 1) """ np.random.seed(2) W1 = np.random.randn(n_h, n_x) * 0.01 b1 = np.zeros((n_h, 1)) W2 = np.random.randn(n_y, n_h) * 0.01 b2 = np.zeros((n_y, 1)) assert (W1.shape == (n_h, n_x)) assert (b1.shape == (n_h, 1)) assert (W2.shape == (n_y, n_h)) assert (b2.shape == (n_y, 1)) parameters = {'W1': W1, 'b1': b1, 'W2': W2, 'b2': b2} return parameters
Let’s take a look at what these parameters will look like:
parameters = initialize_parameters(n_x, n_h, n_y)print("W1 = " + str(parameters["W1"]))print("b1 = " + str(parameters["b1"]))print("W2 = " + str(parameters["W2"]))print("b2 = " + str(parameters["b2"]))
Returns:
With our parameters initialized, we can now implement our linear functions (z = w * x + b) as described above. However, linear functions alone would just result in a neural network that performs similar to logistic or linear regression. So, we must also pass our z outputs into non-linear functions called activation functions.
The intuition here is that we have a noisy dataset with non-linear decision boundaries — so why apply linear models? It’s these non-linear activation functions that will take an additional step to transform outputs from our linear function (z = w * x + b) to better classify our non-linear data.
There are a number of activation functions we can use in neural networks, each with its own pros and cons. For our neural network, we’ll choose a tanh activation function in the hidden layer and a sigmoid activation function in the output layer. Tanh computes outputs between -1 and 1 with the mean of activations at zero. This has the effect of naturally centering our data, which allows learning between hidden layers to compute faster. Sigmoid is ideal in the output layer, especially for binary classification problems, because it computes outputs between 0 and 1.
There are slight drawbacks to both sigmoid and tanh if our z inputs are very large or very small; the gradient (or slope) becomes very small (sometimes close to zero) and can slow down gradient descent.
Let’s unpack details from the 4 functions shown above.
The first linear z[1] function computes the product of all input layer data a[0] (a way to represent all our X feature data) and input layer weights W[1], and adds all input layer bias terms b[1].
The activation function a[1] is the tanh function of the z[1] output.
The second linear z[2] function computes the product of all hidden layer data a[1] (a way to represent all our initial activation functions) and hidden layer weights W[2], and adds all hidden layer bias terms b[2].
The activation function a[2] is the sigmoid function of the z[2] output.
We can code the described functions above for z[1], a[1], z[2] and a[2]. Then we can store these values into a dictionary called “cache” for later usage.
def forward_propagation(X, parameters): """Forward propagation will compute activations functions for the hidden and output layer, producting outputs A1 and A2. Arguments: Takes X data and parameter variables (W1, W2, b1, b2) """ #retrieve each of the paramters from the dictionary W1 = parameters['W1'] b1 = parameters['b1'] W2 = parameters['W2'] b2 = parameters['b2'] Z1 = np.dot(W1,X) + b1 A1 = np.tanh(Z1) Z2 = np.dot(W2, A1) + b2 A2 = sigmoid(Z2) cache = {"Z1": Z1, "A1": A1, "Z2": Z2, "A2": A2} return A2, cache
Now we have our linear Z functions (z[1], z[2]) and activation functions (a[1], a[2]) defined in a cache for later usage.
Great job getting this far! We have learned how to create a neural network structure, initialize parameters, implement some activation functions, and yes, even survived a little math.
In Part 2 of this post, we’ll cover the remaining steps of building our neural network model: (4) defining cost, (5) implementing backward propagation, (6) updating parameters, and (7) making predictions. | [
{
"code": null,
"e": 378,
"s": 171,
"text": "This two-part article takes a more holistic, overarching (and yes, less math-y) approach to building a neural network from scratch. Python for completing the network is also included in each of the 7 steps."
},
{
"code": null,
"e": 602,
"s... |
Strategic Analysis of Trump Rallies with NLP and Time Series | by Tan Pengshi Alvin | Towards Data Science | The United States Presidential election will be decided on 3 November 2020, with highly reverberating effects on America and the world. While some people see Trump as a good president, others see him as a populist. Regardless of one’s political inclination, for good or worse, the consequences of the 2020 election could potentially be earth-shattering.
Nonetheless in this article, I will present to you a strategic analysis of Trump rallies, playing as a de facto data scientist on the side of the Biden-Harris campaign. I will attempt to topic-model the rallies with Natural Language Processing (NLP), and then I will identify topic trends in the rallies with time series, before offering a strategic analysis. Firstly, I obtained transcripts of Trump rallies from https://factba.se/transcripts.
In total, I obtained data of about 100 Trump rallies transcripts from his first rally (Melbourne, Florida) in 2017, up till the first rally (Sanford, Florida) after Trump recovered from Covid-19 on 12 October 2020. Thereafter, I cast the data into a Pandas data frame with the Venue, Date and Transcripts as columns. Below is an excerpt from Trump’s rally in Sanford, Florida, and immediately we see the need for text processing:
‘Hello, everybody. Hello, Orlando. Hello, Sanford. It’s great to be with you. Thank you. It’s great to be back. [Audience chants “USA”] That’s a lot of people. You know our competitor, sleepy Joe, he had a rally today and practically nobody showed up. I don’t know what’s going on. Sleepy Joe, but it’s great to be back in my home state, Florida to make my official return to the campaign trail. I am so energized by your prayers and humbled by your support. We’ve had such incredible support and here we are. It’s you know, here we are. But we’re going to finish, we’re going to make this country greater than ever before. [Audience chants “We love you”] Thank you. Thank you. Thank you very much.
With regular expressions, I removed the audience inputs (in square brackets) from the transcripts. I further used NLTK’s RegexpTokenizer to tokenize words with 3 or more letters and removing words with any punctuation, before joining them again into a processed/fragmented transcript.
With a ‘cleaned’ set of transcripts, I proceed to begin modeling. On exploratory data analysis, I used WordCloud to generate the top 50 words that Trump often used in his first 2 rallies and the last 2 rallies that I obtained:
For WordCloud images, the larger the word implies the more frequently the word being appearing in the transcript. With the above visualization, we may see why Trump is so influential to his supporters, with frequent words such as ‘going’, ‘great’, ‘people’ and ‘country’, arousing emotions and a constant call to action. Also we see ‘obamacare’ appearing, demonstrating Trump’s fixation in his early years of presidency.
In the last two rallies obtained, we see that not a lot has changed in Trump’s usage of words. Words such as ‘going’, ‘people’ and ‘great’ continue to be top words, while words such as ‘biden’ and ‘china’ appear as Trump begins to attack political rivals closer to the election.
Coming to topic modeling, we usually use Scikit-Learn’s Count Vectorizer or TFIDF Vectorizer to quantize all words in the transcripts into features. Thereafter, we reduce all features into components (linear combination of the features) through Latent Semantic Analysis (LSA), Non-negative Matrix Factorization (NMF) or Latent Dirichlet Allocation (LDA). The main topics can thus be identified by filtering the top words of the components.
After some trial-and-error, I have identified Count Vectorizer (total of 11353 unique words) with NMF to be the most definitive for Trump’s rallies. And exercising careful analysis and discernment, I identified the 3 topics (using 90 top words) from the NMF components as such:
Topic 1 : Touting Achievements
know, said, right, people, like, great, got, think, going, want, good, lot, years, president, guy, time, thing, look, won, sir, trump, love, way, big, billion, remember, come, let, money, million, went, deal, better, tell, little, year, new, mean, guys, world, things, came, democrats, thank, bad, win, state, best, country, beautiful, hell, times, ago, believe, actually, michigan, true, took, somebody, party, crazy, obama, american, incredible, fake, getting, job, place, happened, day, greatest, man, long, china, away, saying, number, news, america, election, night, nice, wouldn, states, care, history, wanted, everybody, texas, maybe
Topic 2 : Plans and Appealing for Support
going, great, want, people, country, thank, vote, know, america, american, right, like, years, president, got, democrats, way, good, jobs, time, lot, need, think, said, come, new, state, job, let, love, incredible, care, states, americans, tell, united, believe, history, tax, borders, look, election, democrat, big, working, republicans, military, wall, coming, happen, world, percent, law, republican, border, taxes, won, billion, protect, trump, work, things, man, governor, happening, thing, pay, win, deal, ice, beautiful, day, remember, party, veterans, help, folks, voted, passed, everybody, greatest, strong, florida, called, bad, women, illegal, hard, unemployment, today
Topic 3: Attacking Political Adversaries
going, know, said, people, got, biden, great, like, right, want, think, years, joe, good, way, thank, china, remember, america, lot, country, let, thing, look, tell, win, guy, time, job, big, world, left, president, american, mean, police, law, bad, won, states, happen, called, things, deal, history, better, love, state, hell, ago, new, took, end, little, wants, half, ballots, happened, vote, open, year, everybody, come, wall, jobs, went, crazy, news, second, terrible, governor, day, sleepy, bernie, order, pennsylvania, peace, north, military, energy, seen, watch, saw, suburbs, gave, closed, war, fake, trump, saying
Taking the new components as features of the model (instead of the quantized words from Count Vectorizer), NMF is able to attribute topic relevance scores to each of the rallies. Subsequently, I proceed to plot the time series of topic relevance across the rallies:
From the time series, we can see that while the topic on ‘Touting Achievements’ does not show a clear trend, the topic on ‘Plans and Appealing for Support’ seem to be on the downward trend closer to election. The topic on ‘Attacking Political Adversaries’ shows an obvious upward trend towards a plateau closer to election. As such, it seems that there is a shift in tone in Trump’s rallies towards the election — Trump seems less optimistic on his plans and is attacking his opponent more. This also can be clearly observed with a Cosine Similarity Heatmap:
Looking at the first column of the heat map (in comparison with the rally on 12 October), there seems to be a sudden shift in tone of Trump on the rally on 2 March 2020. Could the sudden onset of Covid-19 in the United States made Trump insecure, and therefore prompted him to attack his opponents more?
Also, we observe another shift in tone on the rally on 18 September 2020 — Trump appears to spike in jubilance on his achievements according to the time series. Coincidentally, it was also the day that Supreme Court Justice Ginsburg (Democrat) passed away. Could that also contributed to Trump’s shift in tone?
To further analyze Trump rallies, let us explore if we could break them down into clusters, based on their topic relevance. It turns out that we could, after plotting Sum Inertia against No. of Clusters and Silhouette Coefficient against No. of Clusters:
Although we cannot clearly identify an elbow (Elbow Method) in the Sum Inertia against Clusters plot, the Silhouette Coefficient plot clearly showed that the optimum number of clusters is two! Silhouette Coefficient is typically scored between 1 and -1, and quantifies the closeness of a point to the cluster centroid and away from other clusters’ centroids.
Moving on, we produced a 3-Dimensional plot of Trump rallies with Plotly, where we see 2 types of Trump rallies where he is mainly attacking political adversaries or mainly appealing to voters:
Going back to our time series plots, we noticed something interesting — there seems to be a hint of periodicity of topic relevance in Trump rallies. Also the topics on ‘Plans and Appealing for Support’ and ‘Attacking Political Adversaries’ seem to be have a trend component. As such, the time series are non-stationary, and we could potentially use the model Seasonal Autoregressive Integrated Moving Average (SARIMA) for predictive analytics.
Following the path of exploration, I conducted a simple forward validation by splitting the data set into Training, Validation and Test set with a ratio of 90:5:5
After performing a simple grid search on the optimum hyperparameters with SARIMA, I obtained following Mean Absolute Error (MAE) scores:
Using the optimum hyperparameters, I re-trained the Training and Validation set together with the SARIMA model, and then evaluate on the Test set. The following error scores I found were still quite reasonable:
The time series prediction model could be used to discover potential peaks and troughs in future Trump rally topics. While the Biden-Harris campaign might have its own set of strategy against the Trump campaign, one could also take reference from an ancient Chinese strategy manual, the Sun Tze Art of War, which advocates doing the inverse of that of the opponent.
“When strong, avoid them. If of high morale, depress them. Seem humble to fill them with conceit. If at ease, exhaust them. If united, separate them. Attack their weaknesses. Emerge to their surprise.” ― Sun Tzu
For instance, Biden could attack Trump more on periods when he is predicted to be less aggressive. Conversely, Biden could appeal to the crowd and talks about his plans when Trump is predicted to be more aggressive. As such, a model which could predict Trump temperament and tone in his campaigning would be very useful for the Biden-Harris camp.
In summary, I have completed an insightful exploratory data analysis on Trump’s rallies, and also created a predictive model on Trump’s topic trend, as a case study.
This careful analysis is created as Project 4 of the Metis Data Science Bootcamp (Singapore), and I would like to thank everyone, especially my instructor Neo Han Wei, who has guided me thus far. It has been an exhilarating experience, and an amazing learning journey. Thank you!
Here is the link to my GitHub, which contains all the codes and presentation slides for this project. Also reach me on my LinkedIn or comment here below to discuss!
Support me! — If you are not subscribed to Medium, and like my content, do consider supporting me by subscribing via my referral link here. | [
{
"code": null,
"e": 526,
"s": 172,
"text": "The United States Presidential election will be decided on 3 November 2020, with highly reverberating effects on America and the world. While some people see Trump as a good president, others see him as a populist. Regardless of one’s political inclinatio... |
Improve your MLflow experiment, keeping track of historical metrics | by Stefano Bosisio | Towards Data Science | medium.com
Welcome back to the second part of our journey in MLflow. Today we’ll extend the current SDK implementation with two functions for reporting historical metrics and custom metrics. Then, we’ll finally see the SDK working with a simple example. Next time, we’ll dig into MLflow plugins and we’ll create a “deployment” plugin for GCP AI platform
Here my first article about MLflow SDK creation:
towardsdatascience.com
— What do we need today— — Report experiment’s runs metrics to the most recent run — — Report custom metrics to a run — — Update the experiment tracking interface — Create your final MLflow SDK and install it — SDK in action!
Firstly, let’s think of the design of the main SDK protocol. The aim today is to allow data scientists to:
add to a given experiment’s run the historical metrics computed in previous runsadd custom computed metrics to a specific run
add to a given experiment’s run the historical metrics computed in previous runs
add custom computed metrics to a specific run
Thus, we can think of implementing the two following functions:
report_metrics_to_experiment : this function will collect all the metrics from previous experiment’s runs and will group them in an interactive plot, so users can immediately spot issues and understand the overall trend
report_custom_metrics : this function return data scientists’ metrics annotations, posting a dictionary to a given experiment. This may be useful if a data scientist would like to stick to a specific experiment with some metrics on unseen data.
This function makes use of the MLflowClient Client in MLflow Tracking manages experiments and their runs. From MLflowClient we can retrieve all the runs for a given experiment. From there, we can extract each run’s metrics. Once we gather together all the metrics we can proceed with a second step, where we are going to use plotly to have an interactive html plot. In this way, users can analyse each single data point for all the runs in the MLflow server artefacts box.
Fig.1 shows the first part of report_metrics_to_experiment function. Firstly, the MlflowClient is initiated, with the given input tracking_uri . Then, the experiment’s information is retrieved with client.get_experiment_by_name and converted to a dictionary. From here each experiment’s run is listed, runs_list . Each run has its run_id which is practical to store metrics information in a dictionary models_metrics . Additionally, metrics can be access via run.to_dictionary()['data']['metrics'] . This value returns the name of the metric.
From the metric’s name, the metric’s data points can be recorded through client.get_metric_history() This attribute returns the steps and the values of the metric, so we can append to lists and saved them in models_metrics[single_run_id][metric] = [x_axis, y_axis]
Fig.2 shows the second part of report_metrics_to_experiment Firstly, a new plotly figure is initialised fig = go.Figure(). Metrics are then read from models_metrics and added as a scatter plot. The final plot is saved in html format, to have an interactive visualization.
The final function we are going to implement today, reports a custom input to a specific run. In this case a data scientist may have some metrics obtained from a run’s model with unseen data. This function is shown in fig.3. Given an input dictionary custom_metrics (e.g. {accuracy_on_datasetXYZ: 0.98} ) the function uses MlflowClient to log_metric for a specific run_id
Now that two news functions have been added to the main MLflow protocol, let’s encapsulate them in our experiment_tracking_training.py In particular, end_training_job could call report_metrics_to_experiment , so, at the end of any training, we can keep track of all the historical metrics for a given experiment, as shown in fig.4
Additionally, to allow users to add their own metrics to specific runs, we can think of an add_metrics_to_run function, which receives as input the experiment tracking parameters, the run_id we want to work on and the custom dictionary custom_metrics (fig.5):
Patching all the pieces together, the SDK package should be structured in a similar way:
mlflow_sdk/ mlflow_sdk/ __init__.py ExperimentTrackingInterface.py experiment_tracking_training.py requirements.txt setup.py README.md
The requirements.txt contains all the packages we need to install our SDK, in particular you’ll need numpy, mlflow, pandas, matplotlib, scikit_learn, seaborn, plotly as default.
setup.py allows to install your own MLflow SDK in a given Python environment and the script should be structured in this way:
To install the SDK just use Python or a virtualenv Python as: python setup.py install
It’s time to put in action what our MLflow SDK. We’ll test it with a sklearn.ensemble.RandomForestClassifier and the iris dataset1 2 3 4 5 (source and license, Open Data Commons Public Domain Dedication and License). Fig.7 shows the full example script we are going to use (my script name is 1_iris_random_forest.py)
tracking_params contains all the relevant info for setting up the MLflow server, as well as the run and experiment name. After loading the dataset, we are going to create a train test split with sklearn.model_selection.train_test_split . To show different metrics and plots in the MLflow artefacts I run 1_iris_random_forest.py 5 times, varying the test_size with the following values:0.3, 0.2, 0.1, 0.05, 0.01
Once the data have been set up, clf=RandomForestClassifier(n_estimators=2) we can call experiment_tracking_training.start_training_job. This module will interact with the MLflow context manager and it will report to the MLflow server the script that is running the model as well as model’s info and artefacts.
At the end of the training we want to report all the experiment run’s metrics in a single plot and, just for testing, we are going to save also some “fake” metrics like false_metrics = {"test_metric1":0.98, ... }
Before running the 1_iris_random_forest.py in a new terminal tab open up the connection with the MLflow server as mlflow ui and navigate to http://localhost:5000 or http://127.0.0.1:5000 . Then, run the example above as python 1_iris_random_forest.py and repeat the run 5 times for different values of test_size
Fig.8 should be similar to what you have after running the example script. Under Experimentsthe experiments’ names are listed. For each experiment there is a series of runs, in particular, under random_forest you’ll find your random forest runs, from 1_iris_random_forest.py
For each run we can immediately see some parameters, which are automatically logged by mlflow.sklearn.autolog() as well as our fake metrics (e.g. test_metric1 ) The autolog function saves also Tags , reporting the estimator class (e.g. sklearn.ensemble._forest.RandomForestClassifier) and method ( RandomForestClassifier ).
Clicking on a single run more details are shown. At first you’ll see all the model parameters, which, again, are automatically reported by the autolog function. Scrolling down the page we can access the Metrics plots. In this case we have just a single data point, but you can have a full plot as a function of the number of steps for more complicated models.
The most important information will then be stored under the Artifacts box (fig.9). Here you can find different folders which have been created by our mlflow_sdk:
Firstly, code is a folder which stores the script used to run our model — this was done in experiment_tracking_training on line 24 with traceback , here the link, and pushed to MLflow artefacts on line 31 of run_training function, here the link).
Following, model stores binary pickle files. MLflow automatically saves model files as well as its requirements to allow reproducibility of the results. This will be super helpful at deployment time.
Finally, you’ll see all the interactive plots. ( *.html ), generated at the end of the training, as well as additional metrics we have computed during the training, such as training_confusion_matrix.png
As you can see, with minimal intervention we have added a full tracking routing to our ML models. Experimenting is crucial at development time and in this way, data scientists could easily use MLflow Tracking functionality without over modifying their existent codes. From here you can explore different “shades” of reports, adding further information for each run as well as running MLflow on a dedicated server to allow cross-teams collaborations.
1 Fisher, Ronald A. “The use of multiple measurements in taxonomic problems.” Annals of eugenics 7.2 (1936): 179–188.
2 Deming, W. Edwards. “Contributions to Mathematical Statistics. RA. New York: Wiley; London: Chapman & Hall, 1950. 655 pp. ” Science 113.2930 (1951): 216–217.
3 Duda, R. O., and P. E. Hart. “Pattern Classification and Scene Analysis.(Q327. D83) John Wiley & Sons.” (1973): 218.
4 Dasarathy, Belur V. “Nosing around the neighborhood: A new system structure and classification rule for recognition in partially exposed environments.” IEEE Transactions on Pattern Analysis and Machine Intelligence 1 (1980): 67–71.
5 Gates, Geoffrey. “The reduced nearest neighbor rule (corresp.).” IEEE transactions on information theory 18.3 (1972): 431–433.
That’s all for today! I hope you enjoyed these two articles about MLflow and its SDK development. Next time we’ll dig into MLflow plugins world, which, in theory, could lead your team to the deployment phase as well.
If you have any question or curiosity, just write me an email at stefanobosisio1@gmail.com | [
{
"code": null,
"e": 183,
"s": 172,
"text": "medium.com"
},
{
"code": null,
"e": 526,
"s": 183,
"text": "Welcome back to the second part of our journey in MLflow. Today we’ll extend the current SDK implementation with two functions for reporting historical metrics and custom metr... |
DBMS - Joins | We understand the benefits of taking a Cartesian product of two relations, which gives us all the possible tuples that are paired together. But it might not be feasible for us in certain cases to take a Cartesian product where we encounter huge relations with thousands of tuples having a considerable large number of attributes.
Join is a combination of a Cartesian product followed by a selection process. A Join operation pairs two tuples from different relations, if and only if a given join condition is satisfied.
We will briefly describe various join types in the following sections.
Theta join combines tuples from different relations provided they satisfy the theta condition. The join condition is denoted by the symbol θ.
R1 ⋈θ R2
R1 and R2 are relations having attributes (A1, A2, .., An) and (B1, B2,.. ,Bn) such that the attributes don’t have anything in common, that is R1 ∩ R2 = Φ.
Theta join can use all kinds of comparison operators.
Student_Detail −
STUDENT ⋈Student.Std = Subject.Class SUBJECT
When Theta join uses only equality comparison operator, it is said to be equijoin. The above example corresponds to equijoin.
Natural join does not use any comparison operator. It does not concatenate the way a Cartesian product does. We can perform a Natural Join only if there is at least one common attribute that exists between two relations. In addition, the attributes must have the same name and domain.
Natural join acts on those matching attributes where the values of attributes in both the relations are same.
Theta Join, Equijoin, and Natural Join are called inner joins. An inner join includes only those tuples with matching attributes and the rest are discarded in the resulting relation. Therefore, we need to use outer joins to include all the tuples from the participating relations in the resulting relation. There are three kinds of outer joins − left outer join, right outer join, and full outer join.
All the tuples from the Left relation, R, are included in the resulting relation. If there are tuples in R without any matching tuple in the Right relation S, then the S-attributes of the resulting relation are made NULL.
All the tuples from the Right relation, S, are included in the resulting relation. If there are tuples in S without any matching tuple in R, then the R-attributes of resulting relation are made NULL.
All the tuples from both participating relations are included in the resulting relation. If there are no matching tuples for both relations, their respective unmatched attributes are made NULL.
178 Lectures
14.5 hours
Arnab Chakraborty
194 Lectures
16 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2612,
"s": 2282,
"text": "We understand the benefits of taking a Cartesian product of two relations, which gives us all the possible tuples that are paired together. But it might not be feasible for us in certain cases to take a Cartesian product where we encounter huge relation... |
Android - Spinner | Spinner allows you to select an item from a drop down menu
For example. When you are using Gmail application you would get drop down menu as shown below, you need to select an item from a drop down menu.
This example demonstrates the category of computers, you need to select a category from the category.
To experiment with this example, you need to run this on an actual device on after developing the application according to the steps below.
Following is the content of the modified main activity file src/com.example.spinner/AndroidSpinnerExampleActivity.java.
package com.example.spinner;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
class AndroidSpinnerExampleActivity extends Activity implements OnItemSelectedListener{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Spinner element
Spinner spinner = (Spinner) findViewById(R.id.spinner);
// Spinner click listener
spinner.setOnItemSelectedListener(this);
// Spinner Drop down elements
List<String> categories = new ArrayList<String>();
categories.add("Automobile");
categories.add("Business Services");
categories.add("Computers");
categories.add("Education");
categories.add("Personal");
categories.add("Travel");
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
String item = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
Modify the content of res/layout/activity_main.xml to the following
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:padding="10dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dip"
android:text="Category:"
android:layout_marginBottom="5dp"/>
<Spinner
android:id="@+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:prompt="@string/spinner_title"/>
</LinearLayout>
Modify the res/values/string.xml to the following
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">AndroidSpinnerExample</string>
</resources>
This is the default AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.spinner" >
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.spinner.AndroidSpinnerExampleActivity"
android:label="@string/app_name" >
<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 AndroidSpinnerExample 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. Before starting your application,Android studio will display following window to select an option where you want to run your Android application.
If you click on spinner button, It will a drop down menu as shown below
46 Lectures
7.5 hours
Aditya Dua
32 Lectures
3.5 hours
Sharad Kumar
9 Lectures
1 hours
Abhilash Nelson
14 Lectures
1.5 hours
Abhilash Nelson
15 Lectures
1.5 hours
Abhilash Nelson
10 Lectures
1 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3666,
"s": 3607,
"text": "Spinner allows you to select an item from a drop down menu"
},
{
"code": null,
"e": 3811,
"s": 3666,
"text": "For example. When you are using Gmail application you would get drop down menu as shown below, you need to select an item f... |
Difference between npm i and npm ci in Node.js - GeeksforGeeks | 02 Feb, 2022
The following difference covers how npm i and npm ci command are different from each other and their functioning. The npm which is called a node package manager which is used for managing modules needed for our application.
npm i: The npm i (or npm install) is used to install all dependencies or devDependencies from a package.json file.
Syntax:
npm install "package-name"
// OR
npm i "package-name"
npm ci: CI stands for continuous integration and npm ci is used to install all exact version dependencies or devDependencies from a package-lock.json file.
Syntax:
npm ci
Differences between npm i and npm ci are:
S.No.
npm i
npm ci
wua92cbrovlggb9ksnk9i8j3vxe1yf9wer133kjt
q4ok2xsrp23ug90isn3i3y8ns544rge54aetgjt1
Node.js-Misc
Difference Between
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference between Informed and Uninformed Search in AI
Difference between HashMap and HashSet
Difference between Internal and External fragmentation
Installation of Node.js on Linux
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Node.js fs.readFile() Method
How to update NPM ? | [
{
"code": null,
"e": 24729,
"s": 24701,
"text": "\n02 Feb, 2022"
},
{
"code": null,
"e": 24953,
"s": 24729,
"text": "The following difference covers how npm i and npm ci command are different from each other and their functioning. The npm which is called a node package manager wh... |
What are different Python Data Types - 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
Data Type represents a type of data present in a variable. In this tutorial, we will see what are the different types of Python data types.
As we seen in Advantages of Python, in Python, we are not required to specify a type explicitly to a variable. Based on the value provided to the variable, the type will be assigned automatically. Hence the Python is consider to be a dynamically typed language.
int
float
complex
bool
str
bytes
bytearray
range
list
tuple
set
frozenset
dict
None
int
float
complex
bool
str
bytes
bytearray
range
list
tuple
set
frozenset
dict
None
The above mentioned data types are inbuilt data types. Based on the value present in side the variable Python internally assigns these data types to a variable.
Though these are assigned by the python internally, if we really want to check the type of a variable, python given us an inbuilt function called type() it gives us the type of a variable.
We can use the int data type to represent numbers.
x = 10
type(a)
<class 'int'>
float data type represents the decimal/floating point numbers.
>>>x=10.5
>>>type(x)
<class 'float'>
Python complex datatype holds complex numbers, its basically a combination of real and imaginary numbers.
>>>x = 10+5j
>>>type(c)
<class 'complex'>
>>>c.real
10.0
>>>c.imag
5.0
Bool datatype represents logical values, it only holds either True or False.
>>>flag=True
>>>flag=False
>>>type(flag)
<class 'bool'>
Python Str datatype represents a sequence of characters.
>>>s='chandra'
>>>type(s)
<class 'str'>
>>>s='chandra shekhar goka'
>>>type(s)
<class 'str'>
bytes datatype represents a sequence of byte values with in the range of 0-255.
>>> list=[20,30,40,50]
>>> b=bytes(list)
>>> type(b)
<class 'bytes'>
bytes datatype represents a sequence of byte values with in the range of 0-255. Difference between byte and bytearray is : byte data type is immutable (once it is defined we can’t change it) where as bytearray datatype mutable (we can change the values after defining).
>>>list=[50,60,70]
>>>barray= bytearray(list)
>>>type(barray)
<class 'bytearray'>
range datatype is used to define a range of values.
>>>r=range(10)
>>>r1=range(0,50)
>>>r2=range(0,50,10)
list datatype represents an ordered collection of objects.
>>>l=[1,5,6,7,8,9]
>>>type(l)
<class 'list'>
tuple datatype represents an ordered collection of objects. The only difference between list vs tuple is : list is an mutable ordered collection where as tuple is immutable ordered collection.
>>>t=(1,5,6,7,8,9)
>>>type(t)
<class 'tuple'>
Set represents an un-ordered collection of unique objects. it doesn’t allowed duplicate values inside it. Set is an mutable collection.
>>>s={1,2,4,3,5,7,6,9}
>>>type(s)
<class 'set'>
frozenset represents an un-ordered collection of unique objects. it doesn’t allowed duplicate values inside it. frozenset is an immutable collection.
>>>s={10,20,'chandra',50,'shekhar'}
>>>fs = frozenset(s)
>>>type(fs)
<class 'frozenset'>
dict represents a group of key->value pairs.
>>>d={100:'JAVA',101:'Python',102:'PHP'}
>>>type(d)
<class 'dict'>
If a variable or def, doesn’t having any value init, the default datatype is None.
>>>def sample():
>>>a=20
>>>print(sample())
None
Happy Learning 🙂
Different ways to do String formatting in Python
How to remove special characters from String in Python
Python List comprehension usage and advantages
Organization of data In Data Structures
How to create Python Iterable class ?
What is Python NumPy Library
How to get Characters Count in Python from a File
Python TypeCasting for Different Types
Python List Data Structure In Depth
Python Tuple Data Structure in Depth
PHP Data types Example Tutorials
Python Set Data Structure in Depth
Python Operators Example
Features of Python Language
Modes of Python Program
Different ways to do String formatting in Python
How to remove special characters from String in Python
Python List comprehension usage and advantages
Organization of data In Data Structures
How to create Python Iterable class ?
What is Python NumPy Library
How to get Characters Count in Python from a File
Python TypeCasting for Different Types
Python List Data Structure In Depth
Python Tuple Data Structure in Depth
PHP Data types Example Tutorials
Python Set Data Structure in Depth
Python Operators Example
Features of Python Language
Modes of Python Program
Δ
Python – Introduction
Python – Features
Python – Install on Windows
Python – Modes of Program
Python – Number System
Python – Identifiers
Python – Operators
Python – Ternary Operator
Python – Command Line Arguments
Python – Keywords
Python – Data Types
Python – Upgrade Python PIP
Python – Virtual Environment
Pyhton – Type Casting
Python – String to Int
Python – Conditional Statements
Python – if statement
Python – *args and **kwargs
Python – Date Formatting
Python – Read input from keyboard
Python – raw_input
Python – List In Depth
Python – List Comprehension
Python – Set in Depth
Python – Dictionary in Depth
Python – Tuple in Depth
Python – Stack Datastructure
Python – Classes and Objects
Python – Constructors
Python – Object Introspection
Python – Inheritance
Python – Decorators
Python – Serialization with Pickle
Python – Exceptions Handling
Python – User defined Exceptions
Python – Multiprocessing
Python – Default function parameters
Python – Lambdas Functions
Python – NumPy Library
Python – MySQL Connector
Python – MySQL Create Database
Python – MySQL Read Data
Python – MySQL Insert Data
Python – MySQL Update Records
Python – MySQL Delete Records
Python – String Case Conversion
Howto – Find biggest of 2 numbers
Howto – Remove duplicates from List
Howto – Convert any Number to Binary
Howto – Merge two Lists
Howto – Merge two dicts
Howto – Get Characters Count in a File
Howto – Get Words Count in a File
Howto – Remove Spaces from String
Howto – Read Env variables
Howto – Read a text File
Howto – Read a JSON File
Howto – Read Config.ini files
Howto – Iterate Dictionary
Howto – Convert List Of Objects to CSV
Howto – Merge two dict in Python
Howto – create Zip File
Howto – Get OS info
Howto – Get size of Directory
Howto – Check whether a file exists
Howto – Remove key from dictionary
Howto – Sort Objects
Howto – Create or Delete Directories
Howto – Read CSV File
Howto – Create Python Iterable class
Howto – Access for loop index
Howto – Clear all elements from List
Howto – Remove empty lists from a List
Howto – Remove special characters from String
Howto – Sort dictionary by key
Howto – Filter a list | [
{
"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,
... |
random.shuffle() function in Python - GeeksforGeeks | 18 Jan, 2022
shuffle() is an inbuilt method of the random module. It is used to shuffle a sequence (list). Shuffling means changing the position of the elements of the sequence. Here, the shuffling operation is inplace.
Syntax : random.shuffle(sequence, function)
Parameters :
sequence : can be a list
function : optional and by default is random(). It should return a value between 0 and 1.
Returns : nothing
Python3
# import the random moduleimport random # declare a listsample_list = ['A', 'B', 'C', 'D', 'E'] print("Original list : ")print(sample_list) # first shufflerandom.shuffle(sample_list)print("\nAfter the first shuffle : ")print(sample_list) # second shufflerandom.shuffle(sample_list)print("\nAfter the second shuffle : ")print(sample_list)
Output :
Original list :
['A', 'B', 'C', 'D', 'E']
After the first shuffle :
['A', 'B', 'E', 'C', 'D']
After the second shuffle :
['C', 'E', 'B', 'D', 'A']
The shuffle() method cannot be used to shuffle immutable datatypes like strings.
Python3
# import the random moduleimport random # user defined function to shuffledef sample_function(): return 0.5 sample_list = ['A', 'B', 'C', 'D', 'E']print("Original list : ")print(sample_list) # as sample_function returns the same value# each time, the order of shuffle will be the# same each timerandom.shuffle(sample_list, sample_function)print("\nAfter the first shuffle : ")print(sample_list) sample_list = ['A', 'B', 'C', 'D', 'E'] random.shuffle(sample_list, sample_function)print("\nAfter the second shuffle : ")print(sample_list)
Output :
Original list :
['A', 'B', 'C', 'D', 'E']
After the first shuffle :
['A', 'D', 'B', 'E', 'C']
After the second shuffle :
['A', 'D', 'B', 'E', 'C']
gireshdatta
Python-random
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": 23925,
"s": 23897,
"text": "\n18 Jan, 2022"
},
{
"code": null,
"e": 24132,
"s": 23925,
"text": "shuffle() is an inbuilt method of the random module. It is used to shuffle a sequence (list). Shuffling means changing the position of the elements of the sequence... |
C# | Type.Equals() Method | 01 May, 2019
Type.Equals() Method is used to check whether the underlying system type of the current Type is the same as the underlying system type of the specified Object or Type. There are 2 methods in the overload list of this method as follows:
Equals(Type) Method
Equals(Object) Method
This method is used to check whether the underlying system type of the current Type is the same as the underlying system type of the specified Type.
Syntax: public virtual bool Equals (Type o);Here, it takes the object whose underlying system type is to be compared with the underlying system type of the current Type.
Return Value: This method returns true if the underlying system type of o is the same as the underlying system type of the current Type otherwise, it returns false.
Below programs illustrate the use of Type.Equals() Method:
Example 1:
// C# program to demonstrate the// Type.Equals(Type) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // Declaring and initializing value1 Type value1 = typeof(System.String); // Declaring and initializing value2 Type value2 = typeof(System.Int32); // using Equals(Type) method bool status = value1.Equals(value2); // checking the status if (status) Console.WriteLine("{0} is equal to {1}", value1, value2); else Console.WriteLine("{0} is not equal to {1}", value1, value2); }}
System.String is not equal to System.Int32
Example 2:
// C# program to demonstrate the// Type.Equals(Type) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // calling get() method get(typeof(System.String), typeof(System.String)); get(typeof(System.String), typeof(System.Int32)); get(typeof(System.Decimal), typeof(System.Double)); } // defining get() method public static void get(Type value1, Type value2) { // using Equals(Type) method bool status = value1.Equals(value2); // checking the status if (status) Console.WriteLine("{0} is equal to {1}", value1, value2); else Console.WriteLine("{0} is not equal to {1}", value1, value2); }}
System.String is equal to System.String
System.String is not equal to System.Int32
System.Decimal is not equal to System.Double
This method is used to check whether the underlying system type of the current defined Type object is exactly same as the underlying system type of the specified Object.
Syntax: public override bool Equals (object obj);Here, it takes the object whose underlying system type is to be compared with the underlying system type of the current Type. For the comparison to succeed, obj must be able to be cast or converted to an object of type Type.
Return Value: This method returns true if the underlying system type of obj is the same as the underlying system type of the current Type otherwise, it returns false. This method also returns false if obj is null or cannot be cast or converted to a Type object.
Below programs illustrate the use of the above-discussed method:
Example 1:
// C# program to demonstrate the// Type.Equals(Object) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // Declaring and initializing value1 Type value1 = typeof(int); // Declaring and initializing value2 object value2 = typeof(int); // using Equals(Object) method bool status = value1.Equals(value2); // checking the status if (status) Console.WriteLine("{0} is equal to {1}", value1, value2); else Console.WriteLine("{0} is not equal to {1}", value1, value2); }}
System.Int32 is equal to System.Int32
Example 2:
// C# program to demonstrate the// Type.Equals(Object) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // calling get() method get(typeof(int), new Object()); get(typeof(System.String), (object)5.5); get(typeof(System.String), null); } // defining get() method public static void get(Type value1, object value2) { // using Equals(Object) method bool status = value1.Equals(value2); // checking the status if (status) Console.WriteLine("{0} is equal to {1}", value1, value2); else Console.WriteLine("{0} is not equal to {1}", value1, value2); }}
System.Int32 is not equal to System.Object
System.String is not equal to 5.5
System.String is not equal to
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.type.equals?view=netcore-3.0
CSharp-method
CSharp-Type-Class
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 May, 2019"
},
{
"code": null,
"e": 264,
"s": 28,
"text": "Type.Equals() Method is used to check whether the underlying system type of the current Type is the same as the underlying system type of the specified Object or Type. There a... |
Scala String | 18 Aug, 2021
A string is a sequence of characters. In Scala, objects of String are immutable which means a constant and cannot be changed once created.
There are two ways to create a string in Scala:
Here, when the compiler meet to a string literal and creates a string object str. Syntax:
var str = "Hello! GFG"
or
val str = "Hello! GFG"
Here, a String type is specified before meeting the string literal. Syntax:
var str: String = "Hello! GFG"
or
val str: String = "Hello! GFG"
Note: If you need to append to the original string, then use StringBuilder class. Example:
Scala
// Scala program to illustrate how to // create a stringobject Main{ // str1 and str2 are two different strings var str1 = "Hello! GFG" val str2: String = "GeeksforGeeks" def main(args: Array[String]) { // Display both strings println(str1); println(str2); }}
Output:
Hello! GFG
GeeksforGeeks
An accessor method is those methods which are used to find the information about the object. So, a length() method is the accessor method in Scala, which is used to find the length of the given string. Or in other words, length() method returns the number of characters that are present in the string object. Syntax:
var len1 = str1.length();
Example:
Scala
// Scala program to illustrate how to // get the length of the given stringobject Main { // str1 and str2 are two strings var str1 = "Hello! GFG" var str2: String = "GeeksforGeeks" // Main function def main(args: Array[String]) { // Get the length of str1 and str2 strings // using length() function var LEN1 = str1.length(); var LEN2 = str2.length(); // Display both strings with their length println("String 1:" + str1 + ", Length :" + LEN1); println("String 2:" + str2 + ", Length :" + LEN2); }}
Output:
String 1:Hello! GFG, Length :10
String 2:GeeksforGeeks, Length :13
when a new string is created by adding two strings is known as a concatenation of strings. Scala provides concat() method to concatenate two strings, this method returns a new string which is created using two strings. You can also use ‘+’ operator to concatenate two strings. Syntax:
str1.concat(str2);
or Syntax:
"welcome" + "GFG"
Example:
Scala
// Scala program to illustrate how to // concatenate stringsobject Main { // str1 and str2 are two strings var str1 = "Welcome! GeeksforGeeks " var str2 = " to Portal" // Main function def main(args: Array[String]) { // concatenate str1 and str2 strings // using concat() function var Newstr = str1.concat(str2); // Display strings println("String 1:" +str1); println("String 2:" +str2); println("New String :" +Newstr); // Concatenate strings using '+' operator println("This is the tutorial" + " of Scala language" + " on GFG portal"); }}
Output:
String 1:Welcome! GeeksforGeeks
String 2: to Portal
New String :Welcome! GeeksforGeeks to Portal
This is the tutorial of Scala language on GFG portal
When you required format number or values in your string you will use printf() or format() methods. Other than these methods, String class also provides a methods named as format() method, this method return a String object instead of PrintStream object. Example:
Scala
// Scala program to illustrate how to // Creating format stringobject Main { // two strings var A_name = "Ankita " var Ar_name = "Scala|Strings" var total = 130 // Main function def main(args: Array[String]) { // using format() function println("%s, %s, %d".format(A_name, Ar_name, total)); }}
Output:
Ankita , Scala|Strings, 130
kapoorsagar226
Scala
Scala-Strings
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Aug, 2021"
},
{
"code": null,
"e": 169,
"s": 28,
"text": "A string is a sequence of characters. In Scala, objects of String are immutable which means a constant and cannot be changed once created. "
},
{
"code": null,
"e... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.