https://hyperledger.github.io/composer/v0.19/tutorials/playground-tutorial.html
International Corporate Trainer | Technical Consultant | Data Scientist | IoT Solution Architect | Blockchain Architect | Industry 4.0 Architect
Friday, 8 March 2019
Hyperledger - First DAPP
BNA for Basic CU
option
It will demonstrates the core functionality
of Hyperledger Composer by changing the value of an asset.
Participant - SampleParticipant
Asset -
SampleAsset
Transaction - SampleTransaction
Event - SampleEvent
SampleAssets are owned by a
SampleParticipant, and the value property on a SampleAsset can be modified by
submitting a SampleTransaction. The SampleTransaction emits a SampleEvent that
notifies applications of the old and new values for each modified SampleAsset.
Create a
SampleParticipant participant:
{
"$class": "org.example.basic.SampleParticipant",
"participantId": "EMP1",
"firstName": "Manish",
"lastName": "Jain"
}
Create
a
SampleAsset asset:
{
"$class": "org.example.basic.SampleAsset",
"assetId": "assetId:1",
"owner": "resource:org.example.basic.SampleParticipant#EMP1",
"value": "HP Laptop"
}
Submit
a
SampleTransaction transaction:
{
"$class": "org.example.basic.SampleTransaction",
"asset":
"resource:org.example.basic.SampleAsset#assetId:1",
"newValue": "Dell Laptop"
}
After submitting this transaction, you should
now see the transaction in the Transaction Registry and that a
SampleEvent has
been emitted. As a result, the value of the assetId:1 should
now be new value in the Asset Registry.
'o' indicates has-a relationship
'-->'
indicates pass by reference
Models/Sample.cto
namespace org.example.basic
asset SampleAsset identified by assetId {
o
String assetId
--> SampleParticipant owner
o
String value
}
participant SampleParticipant identified by
participantId {
o
String participantId
o
String firstName
o
String lastName
}
transaction SampleTransaction {
--> SampleAsset asset
o
String newValue
}
event SampleEvent {
--> SampleAsset asset
o
String oldValue
o
String newValue
}
Lib/sample.js
async function sampleTransaction(tx) {
// Save the old
value of the asset.
const oldValue
= tx.asset.value;
// Update the
asset with the new value.
tx.asset.value
= tx.newValue;
// Get the
asset registry for the asset.
const
assetRegistry = await getAssetRegistry('org.example.basic.SampleAsset');
// Update the
asset in the asset registry.
await assetRegistry.update(tx.asset);
// Emit an
event for the modified asset.
let event =
getFactory().newEvent('org.example.basic', 'SampleEvent');
event.asset =
tx.asset;
event.oldValue
= oldValue;
event.newValue
= tx.newValue;
emit(event);
}
Permission.acl
rule EverybodyCanReadEverything {
description:
"Allow all participants read access to all resources"
participant:
"org.example.basic.SampleParticipant"
operation: READ
resource:
"org.example.basic.*"
action: ALLOW
}
rule EverybodyCanSubmitTransactions {
description:
"Allow all participants to submit transactions"
participant:
"org.example.basic.SampleParticipant"
operation:
CREATE
resource:
"org.example.basic.SampleTransaction"
action: ALLOW
}
rule OwnerHasFullAccessToTheirAssets {
description:
"Allow all participants full access to their assets"
participant(p):
"org.example.basic.SampleParticipant"
operation: ALL
resource(r):
"org.example.basic.SampleAsset"
condition:
(r.owner.getIdentifier() === p.getIdentifier())
action: ALLOW
}
rule SystemACL {
description:
"System ACL to permit all access"
participant:
"org.hyperledger.composer.system.Participant"
operation: ALL
resource:
"org.hyperledger.composer.system.**"
action: ALLOW
}
rule NetworkAdminUser {
description:
"Grant business network administrators full access to user resources"
participant:
"org.hyperledger.composer.system.NetworkAdmin"
operation: ALL
resource:
"**"
action: ALLOW
}
rule NetworkAdminSystem {
description:
"Grant business network administrators full access to system
resources"
participant:
"org.hyperledger.composer.system.NetworkAdmin"
operation: ALL
resource:
"org.hyperledger.composer.system.**"
action: ALLOW
}
Monday, 25 February 2019
OpenCV
import numpy as np
import cv2
# multiple cascades: https://github.com/Itseez/opencv/tree/master/data/haarcascades
#https://github.com/Itseez/opencv/blob/master/data/haarcascades/haarcascade_frontalface_default.xml
face_cascade = cv2.CascadeClassifier('D:\\opencv\\OpenCV Final Softwares\\opencv\\sources\\data\\haarcascades\\haarcascade_frontalface_default.xml')
#https://github.com/Itseez/opencv/blob/master/data/haarcascades/haarcascade_eye.xml
eye_cascade = cv2.CascadeClassifier('D:\\opencv\\OpenCV Final Softwares\\opencv\\sources\\data\\haarcascades\\haarcascade_eye.xml')
cap = cv2.VideoCapture(0)
while 1:
ret, img = cap.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
eyes = eye_cascade.detectMultiScale(roi_gray)
for(ex,ey,ew,eh) in eyes:
cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
cv2.imshow('img',img)
k = cv2.waitKey(30) & 0xff
if k == 27:
break
cap.release()
cv2.destroyAllWindows()
import cv2
# multiple cascades: https://github.com/Itseez/opencv/tree/master/data/haarcascades
#https://github.com/Itseez/opencv/blob/master/data/haarcascades/haarcascade_frontalface_default.xml
face_cascade = cv2.CascadeClassifier('D:\\opencv\\OpenCV Final Softwares\\opencv\\sources\\data\\haarcascades\\haarcascade_frontalface_default.xml')
#https://github.com/Itseez/opencv/blob/master/data/haarcascades/haarcascade_eye.xml
eye_cascade = cv2.CascadeClassifier('D:\\opencv\\OpenCV Final Softwares\\opencv\\sources\\data\\haarcascades\\haarcascade_eye.xml')
cap = cv2.VideoCapture(0)
while 1:
ret, img = cap.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
eyes = eye_cascade.detectMultiScale(roi_gray)
for(ex,ey,ew,eh) in eyes:
cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
cv2.imshow('img',img)
k = cv2.waitKey(30) & 0xff
if k == 27:
break
cap.release()
cv2.destroyAllWindows()
ANN-ML3
from numpy import exp, array, random, dot
training_set_inputs = array([[0, 0, 1], [1, 1, 1], [1, 0, 1],
[0, 1, 1]])
training_set_outputs = array([[0, 1, 1, 0]]).T
random.seed(1)
synaptic_weights = 2 * random.random((3, 1)) - 1
for iteration in range(10000):
output = 1 / (1 +
exp(-(dot(training_set_inputs, synaptic_weights))))
synaptic_weights +=
dot(training_set_inputs.T, (training_set_outputs - output) * output * (1 -
output))
print (1 / (1 + exp(-(dot(array([1, 0, 0]), synaptic_weights)))))
DT-ML2
pip install sklearn
pip install scipy
____________________
from sklearn
import
tree
clf =
tree.DecisionTreeClassifier()
#[height,
hair-length,
voice-pitch]
X = [ [180,
15,0],
[167,
42,1],
[136,
35,1],
[174,
15,0],
[141,
28,1]]
Y = ['man',
'woman', 'woman', 'man',
'woman']
clf = clf.fit(X,
Y)
prediction =
clf.predict([[133,
37,1]])
print(prediction)
LR - ML1
import numpy as np
import matplotlib.pyplot as plt
def estimate_coefficients(x, y):
# size of the
dataset OR number of observations/points
n = np.size(x)
# mean of x and
y
# Since we are
using numpy just calling mean on numpy is sufficient
mean_x, mean_y
= np.mean(x), np.mean(y)
# calculating
cross-deviation and deviation about x
SS_xy=np.sum(y*x)-(n*mean_y*mean_x)
SS_xx=np.sum(x*x)-(n*mean_x*mean_x)
SS_xx=np.sum(x*x)-(n*mean_x*mean_x)
# calculating
regression coefficients
b_1 = SS_xy /
SS_xx
b_0 = mean_y -
b_1*mean_x
return(b_0,
b_1)
# x,y are the
location of points on graph
# color of the
points change it to red blue orange play around
def plot_regression_line(x, y, b):
# plotting the
points as per dataset on a graph
plt.scatter(x,
y, color = "m",marker = "o", s = 30)
# predicted
response vector
y_pred = b[0] +
b[1]*x
# plotting the
regression line
plt.plot(x,
y_pred, color = "g")
# putting
labels for x and y axis
plt.xlabel('Size')
plt.ylabel('Cost')
# figimage only adds a background to the
current figure. If you don't have an already existing figure, the command wont
render anything.
data =
np.random.randn(500, 500)
plt.figimage(data)
# function to
show plotted graph
plt.show()
def main():
# Datasets
which we create
x = np.array([
1, 2,
3, 4, 5,
6, 7, 8,
9, 10])
y =
np.array([300, 350, 500, 700, 800, 850, 900, 900, 1000, 1200])
# estimating
coefficients
b =
estimate_coefficients(x, y)
print("Estimated coefficients:\nb_0 = {} \nb_1 =
{}".format(b[0], b[1]))
# plotting
regression line
plot_regression_line(x, y, b)
if __name__ == "__main__":
main()
Wednesday, 13 February 2019
AngularJS , ExpressJS and MongoDB connectivity
Creating a Node
Application with MongoDB Connectivity
mkdir
node-demo
cd node-demo
cd node-demo
Once we are in the
directory we will need to create an application and we can do this by running
the command
npm init
Installing
Express
npm install express --save
Create app.js file
var express
= require("express");var app = express();var port = 3000;app.get("/", (req, res)
=> { res.send("Hello World");});app.listen(port, () => { console.log("Server listening on port
" + port);});
To test our application
you can go to the terminal and enter the command
node app.js
Open up a browser and
navigate to the url
http://localhost:3000

Creating
Website to Save Data to MongoDB Database
Create index.html
<!DOCTYPE html><html><head><title>Intro to Node and MongoDB</title></head><body><h1>Into to Node and MongoDB</h1><form method="post" action="/addname"><label>Enter Your Name</label><br><input type="text" name="firstName" placeholder="Enter first name..." required><input type="text" name="lastName" placeholder="Enter last name..." required><input type="submit" value="Add Name"></form></body></html>
The
app.get lines
will need to be changed app.get("/", (req, res) => { res.sendFile(__dirname +
"/index.html");});
Once
you have saved your app.js file, we can test it by going to terminal and
running
node
app.js
Open your browser
and navigate to “http://localhost:3000”. You will see the following

Connecting
to the Database
To connect to the
MongoDB database we are going to use a module called Mongoose. We will need to
install mongoose module just like we did with express. Go to your terminal and
enter the following command.
npm install mongoose –save
Connecting
to the Database
Now that we have
the mongoose module installed, we need to connect to the database in our app.js
file. MongoDB, by default, runs on port 27017. You connect to the database by
telling it the location of the database and the name of the database.
In our app.js file
after the line for the port and before the app.get line, enter the following
two lines to get access to mongoose and to connect to the database. For the
database, I am going to use “node-demo”.
var mongoose = require("mongoose");
mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost:27017/node-demo");
var User = mongoose.model("User", nameSchema);
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
Creating a Database Schema
var nameSchema = new mongoose.Schema({
firstName:
String,
lastName:
String
});
var User = mongoose.model("User", nameSchema);
Creating a
RESTful API
We will need to
create an endpoint that will be used to send data to our server. Once the
server receives this data then it will store the data in the database.
An endpoint is a
route that our server will be listening to to get data from the browser. We
already have one route that we have created already in the application and that
is the route that is listening at the endpoint “/” which is the homepage of our
application.
HTML Verbs
in a REST API
The
communication between the client(the browser) and the server is done through an
HTTP verb. The most common HTTP verbs are
GET, PUT, POST, and DELETE.
HTTP
Verb Operation
|
|
GET
Read
|
|
POST
Create
|
|
PUT
Update
|
|
DELETE
Delete
|
Building a
CRUD endpoint
If you remember,
the form in our index.html file used a post method to call this endpoint. We
will now create this endpoint.
In our previous
endpoint we used a “GET” http verb to display the index.html file. We are going
to do something very similar but instead of using “GET”, we are going to use
“POST”. To get started this is what the framework of our endpoint will look
like.
app.post("/addname", (req, res) => {});
Express
Middleware
To fill out the
contents of our endpoint, we want to store the firstName and lastName entered
by the user into the database. The values for firstName and lastName are in the
body of the request that we send to the server. We want to capture that data,
convert it to JSON and store it into the database.
Express.js version
4 removed all middleware. To parse the data in the body we will need to add
middleware into our application to provide this functionality. We will be using
the body-parser module. We need to install it, so in your terminal window enter
the following command.
npm install body-parser --save
To
add the body-parser middleware to our application and configure it, we can add
the following lines directly after the line that sets our port.
var bodyParser = require('body-parser');app.use(bodyParser.json());app.use(bodyParser.urlencoded({ extended: true }));
Saving
data to database
Mongoose provides a
save function that will take a JSON object and store it in the database. Our
body-parser middleware, will convert the user’s input into the JSON format for
us.
To save the data
into the database, we need to create a new instance of our model that we
created early. We will pass into this instance the user’s input. Once we have it
then we just need to enter the command “save”.
app.post("/addname", (req, res) => {var myData = new User(req.body);myData.save().then(item => {res.send("item saved to database");}).catch(err => {res.status(400).send("unable to save to database");});});
Testing
our code
Save your code. Go to your terminal and enter the
command
node app.js to
start our server. Open up your browser and navigate to the URL
“http://localhost:3000”. You will see our index.html file displayed to you.Friday, 1 February 2019
Blockchain - Solidity - GUI - Video
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="main.css">
<script src="./node_modules/web3/dist/web3.min.js"></script>
</head>
<body>
<div class="container">
<h1>Coursetro Instructor</h1>
<h2 id="instructor"></h2>
<label for="name" class="col-lg-2 control-label">Instructor Name</label>
<input id="name" type="text">
<label for="name" class="col-lg-2 control-label">Instructor Age</label>
<input id="age" type="text">
<button id="button">Update Instructor</button>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script>
if (typeof web3 !== 'undefined') {
web3 = new Web3(web3.currentProvider);
} else {
// set the provider you want from Web3.providers
web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
}
web3.eth.defaultAccount = web3.eth.accounts[0];
var CoursetroContract = web3.eth.contract([
{
"constant": false,
"inputs": [
{
"name": "_fName",
"type": "string"
},
{
"name": "_age",
"type": "uint256"
}
],
"name": "setInstructor",
"outputs": [],
"payable": false,
"type": "function",
"stateMutability": "nonpayable"
},
{
"constant": true,
"inputs": [],
"name": "getInstructor",
"outputs": [
{
"name": "",
"type": "string"
},
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"type": "function",
"stateMutability": "view"
}
]);
var Coursetro = CoursetroContract.at('0xcc74d5766c8d3d611a7db8881fa7d518a2958f75');
console.log(Coursetro);
Coursetro.getInstructor(function(error, result){
if(!error)
{
$("#instructor").html(result[0]+' ('+result[1]+' years old)');
console.log(result);
}
else
console.error(error);
});
$("#button").click(function() {
Coursetro.setInstructor($("#name").val(), $("#age").val());
});
</script>
</body>
</html>
Subscribe to:
Posts (Atom)
