Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Part-1: C++
Introduction
OpenCV C++ program for face detection
Student data management in C++
Finding cabs nearby using Great Circle distance formula
Part-2: Java
Introduction
A Group chat application in java
Generating password and OTP in java
Creative Programming In Processing | Set 1 (Random
Walker)
1. Introduction
C++ is an object-oriented programming language. It was developed by Bjarne Stroustrup
at AT&T Bell laboratories in Murray Hill, New Jersey, USA, in the early 1980's. Stroustrup,
an admirer of Simula67 and a strong supporter of C, wanted to combine the best of both
the languages and create a more powerful language that could support object-oriented
programming features and still retain the power and elegance of C. The result was C++.
Therefore, C++ is an extension of C with a major addition of the class contruct feature of
Simula67.
C++ is a superset of C. Most of what we already know about C applies to C++ also.
Therefore, almost all C programs are also C++ programs. However, there are a few minor
differences that will prevent a C program to run under C++ compiler. We shall see these
differences later as and when they are encountered.
the object-oriented features in C++ allow programming to build large programs with
clarity, extensibility and ease of maintenance, incorporating the spirit and efficiency of C.
The eddition of new features has been transformed C from a language that currently
facilites top-down, structured design, to one that provides bottom-up, object-oriented
design.
This program uses the OpenCV library to detect faces in a live stream from webcam or in
a video file stored in the local machine. This program detects faces in real time and tracks
it. It uses pre-trained XML classifiers for the same. The classifiers used in this program
have facial features trained in them. Different classifiers can be used to detect different
objects.
Implementation:
// CPP program to detects face in a video
#include "/usr/local/include/opencv2/objdetect.hpp"
#include "/usr/local/include/opencv2/highgui.hpp"
#include "/usr/local/include/opencv2/imgproc.hpp"
#include <iostream>
VideoCapture capture;
double scale=1;
nestedCascade.load( "../../haarcascade_eye_tree_eyeglasses.xml" ) ;
cascade.load( "../../haarcascade_frontalcatface.xml" ) ;
if( capture.isOpened() )
while(1)
if( frame.empty() )
break;
char c = (char)waitKey(10);
break;
else
return 0;
CascadeClassifier& nestedCascade,
double scale)
{
vector<Rect> faces, faces2;
double fx = 1 / scale;
Rect r = faces[i];
Mat smallImgROI;
vector<Rect> nestedObjects;
Point center;
int radius;
else
cvPoint(cvRound((r.x + r.width-1)*scale),
if( nestedCascade.empty() )
continue;
smallImgROI = smallImg( r );
Rect nr = nestedObjects[j];
References:
1) http://docs.opencv.org/2.4/modules/contrib/doc/facerec/facerec_tutorial.html
2)http://docs.opencv.org/2.4/doc/tutorials/objdetect/cascade_classifier/cascade_classifier.html
#include<stdio.h>
#include<iostream>
#include<fstream>
#include<string.h>
int main(){
char data[15];
int n = 0, option = 0, count_n = 0;
ifstream f("Example.txt");
string line;
//The following for loop counts the total number of lines in the file.
count_n++;}
while(option != 6){
if(option == 1){
cin >> n;
count_n = count_n + n;
for (int i = 0;i < n;i++){
ofstream outfile;
outfile.open("Example.txt",ios::app);
len = len + 1;
}}
char regno[9];
ifstream infile;
int check = 0;
infile.open("Example.txt",ios::in);
//This loop prints out the data according to the registration number specified.
if (strcmp(data,regno) == 0){
infile>>data;
infile.close();
check = 1;}
if (check == 0){
//This loop is used to view and add marks to the database of a student.
char subcode[7];
ifstream infile;
int check = 0;
fstream file("Example.txt");
if(strcmp(subcode,code1.c_str()) == 0){
file.seekp(26+37*i,std::ios_base::beg);
cout << "Enter the mark of student#" << (i+1) << " : ";
file.write(mark.c_str(),2);}
if(strcmp(subcode,code2.c_str()) == 0){
file.seekp(29+37*i,std::ios_base::beg);
cout << "Enter the mark of student#" << (i+1) << " : ";
file.write(mark.c_str(),2);}
}
//This loop is used to view marks of a student.
//The extra infile commands have been used to get a specific mark
infile.open("Example.txt",ios::in);
if (strcmp(subcode,code1.c_str()) == 0){
check = 1;
infile.close();
infile.open("Example.txt",ios::in);
if(strcmp(subcode,code2.c_str()) == 0){
check = 1;
}}
infile.close();
if (check == 0){
//This loop displays all the details of students under the same proctor ID.
char procid[7];
int check = 1;
char temp1[100], temp2[100], temp3[100];
ifstream infile;
infile.open("Example.txt",ios::in);
if (strcmp(id,procid) == 0){
check = 1;
if (check == 0){
}}
//This loop acts as an admin view to see all the data in the file.
else if(option == 5)
char password[25];
if (strcmp(password,admin_pass.c_str()) == 0){
ifstream infile;
infile.open("Example.txt",ios::in);
char data[20];
}}
Reference: https://www.geeksforgeeks.org/student-data-management-c/
Examples:
Input : file customers.json which contains GPS co-ordinates of a person who needs a cab in degrees
and co-ordinates of all the cabs in the city stored in a text file in JSON format.
Output : file answers.json which contains user-id and Name of all the cab drivers available in 50 km
proximity stored in a new file.
Approach Used:
1. Obtain latitude and longitude of each cab in string format along with their user-id and name from
the JSON encoded input file.
2. Convert latitude and longitude of the cab present in string format to double.
3. Convert latitude and longitude of both, the user and the cab present in degrees to radians.
4. Calculate distance between the user’s location and the cab using Great Circle Distance formula.
5. If distance is found to be less than or equal to 50 kms then output the user-id and name of the cab
driver to a new file else take no action.
Procedure to run the program :
1. Save the code and the file customers.json in a same location.
2. Now, compile the code(using cmd : g++ file_name.cpp) and run it(using cmd : ./a.out
/home/gfg/customers.json) with passing file name customers.json along with proper location(e.g.
/home/gfg/customers.json).
3. A file named answers.json will be created on the same location where code and customers.json
file is existing.
#include <bits/stdc++.h>
#define pi 3.14159265358979323846
{
return ( deg * pi / 180);
delta_lon, central_ang;
lat1 = degtorad(lat1d);
lon1 = degtorad(lon1d);
lat2 = degtorad(lat2d);
lon2 = degtorad(lon2d);
sin(lat2) + cos(lat1) *
cos(lat2) * cos(delta_lon) );
}
// Structure which contains data and
struct json
*/
n, f, fi, id[100000];
char latitude_as_string[1000],
longitude_as_string[1000],
id_as_string[1000], name[1000];
double lat2d, lon2d;
// file as string.
string line;
void distance_calculator()
id[i] = atoll(id_as_string);
i++;
void json_parser()
{
if (customer_list.is_open())
f = 0; x = 0; y = 0; fi = 0; m = 0, n = 0;
length = line.size();
if (line[j] == '"')
f++;
fi++;
if (f == 3)
j++;
latitude_as_string[x] = line[j];
x++; j++;
else if (f == 13)
j++;
longitude_as_string[y] = line[j];
y++; j++;
if (fi == 2)
{
j += 2;
id_as_string[m] = line[j];
m++; j++;
fi++;
else if (fi == 4)
j += 2;
name[n] = line[j];
n++; j++;
fi++; f += 2;
}
// Converting latitude and longitude
// in string to float.
lat2d = atof(latitude_as_string);
lon2d = atof(longitude_as_string);
distance_calculator();
customer_list.close();
out.close();
};
int main()
json obj;
obj.json_parser();
return 0;
References:
1.Great Circle Distance
2. https://www.geeksforgeeks.org/finding-cabs-nearby-using-great-circle-distance-formula/
1. Introduction
Java is a general purpose, high-level programming language developed by Sun Microsystems.
The Java programming language was developed by a small team of engineers, known as
the Green Team, who initiated the language in 1991.
Originally called OAK, the Java language was designed for handheld devices and set-top boxes.
Oak was unsuccessful and in 1995 Sun changed the name to Java and modified the language to
take advantage of the burgeoning World Wide Web.
Later, in 2009, Oracle Corporation acquired Sun Microsystems and took ownership of two key
Sun software assets: Java and Solaris.
Implementation:
import java.net.*;
import java.io.*;
import java.util.*;
if (args.length != 2)
else
try
name = sc.nextLine();
socket.setTimeToLive(0);
socket.joinGroup(group);
ReadThread(socket,group,port));
t.start();
while(true)
String message;
message = sc.nextLine();
if(message.equalsIgnoreCase(GroupChat.TERMINATE))
{
finished = true;
socket.leaveGroup(group);
socket.close();
break;
DatagramPacket(buffer,buffer.length,group,port);
socket.send(datagram);
catch(SocketException se)
se.printStackTrace();
catch(IOException ie)
ie.printStackTrace();
}
}
this.socket = socket;
this.group = group;
this.port = port;
@Override
while(!GroupChat.finished)
DatagramPacket(buffer,buffer.length,group,port);
String message;
try
socket.receive(datagram);
message = new
String(buffer,0,datagram.getLength(),"UTF-8");
if(!message.startsWith(GroupChat.name))
System.out.println(message);
catch(IOException e)
System.out.println("Socket closed!");
Save the file as GroupChat.java and compile it using javac and then run the program using two
command line arguments as specified. A multicast host is specified by a class D IP address and
by a standard UDP port number. Class D IP addresses are in the range 224.0.0.0 to
239.255.255.255, inclusive. The address 224.0.0.0 is reserved and should not be used.
Additional points:
You can incorporate network security feature by performing encryption before sending the
message over the network.
Primitive techniques such as Caesar cipher or advanced methods such as RSA can be used
to perform encryption-decryption. You can try using Java’s RMI (Remote Method
Invocation) to perform the same task.
Here, you can leverage the abstraction offered by Java to maximum extent. However, if
your primary objective is efficiency, then Socket programming is the best choice. Since it
doesn’t require any run time support, it is a bit faster compared to RMI.
Reference: https://www.geeksforgeeks.org/a-group-chat-application-in-java/
Many a times we forget our passwords and we opt for Forget password option and within no
time we get a new password at our registered email-ID or phone no. to login our account.
And every time we get a different password.
Sometime we access our bank accounts while shopping from an online store or many more
ways, in order to verify our transition from the bank account they send us OTP(One Time
Password) on our registered phone no. or our email-ID, within no time.
The following code explains how to generate such Passwords and OTP within no time and
what code we can use if in case we need to do so.
Java program explaining the generation of Password
// password
// class in Java
import java.util.*;
// here to be 8
System.out.println(geek_Password(length));
numbers + symbols;
password[i] =
values.charAt(rndm_method.nextInt(values.length()));
return password;
// class in Java
import java.util.*;
otp[i] =
numbers.charAt(rndm_method.nextInt(numbers.length()));
return otp;
int length = 4;
System.out.println(OTP(length));
Reference: https://www.geeksforgeeks.org/generating-password-otp-java/
4. Creative Programming In Processing | Set 1 (Random
Walker)
Creative programming is a type of programming approach in which the goal is to
create something expressive and visual instead of something that is purely
functional. This type of programming approach is used to create live artworks,
graphical simulations and visualize algorithms. There exists a number of tools and
libraries for creative or visual programming of which Processing is the most widely
used. Processing is an open source programming language and IDE that built for
visual programming purposes. It is also available as a python dialect and a javascript
framework. In this article we will build a simple random walker program which is just
a ball moving randomly across the canvas.
Each processing sketch typically consists of two functions:
(i) setup() – It is called once at the beginning and is generally used for initialization
purposes.
(ii) draw() – It is called 30 times per second by default making the default framerate
of the animation being 30 frames per second.
Implementation of sketch:
The sample codes have been written in java using the processing library and the
processing IDE.
void walk()
{
// The x and y values of the location
// vector are incremented by a random value
// between -5 and 5
location.x += random(-5, 5);
location.y += random(-5, 5);
}
Reference: https://www.geeksforgeeks.org/creative-programming-processing-set-1-
random-walker/