Friday, 21 February 2020

Manipal Blockchain

pragma solidity ^0.4.0;
contract SimpleStorage{
    uint a;
    uint b;
    uint c;
    function set( uint balu, uint bunny)public{
        a = balu;
       b = bunny;
    }
    function add()public constant returns(uint){
        c = a+b;
        return c;
    }
     function sub()public constant returns(uint){
        c = a-b;
        return c;
    } function mul()public constant returns(uint){
        c = a*b;
        return c;
    } function div()public constant returns(uint){
        c = a/b;
        return c;
    }
   
}

Saturday, 8 February 2020

IIT Indore

str = 'Hello World!’

print(str) # Prints complete string
print(str[0]) # Prints first character of the string
print(str[2:5]) # Prints characters starting from 3rd to 5th
print(str[2:]) # Prints string starting from 3rd character
print(str * 2) # Prints string two times
print(str + "TEST") # Prints concatenated string
print(str[:-2])    # Hello Worl
print(str[::-1])  # Reverse   !dlroW olleH
print(str[::-2])  # Alternative reverse    !lo le
len(str) # 12 including space
str.count(' ')   # Space Count
____________________________________________________

list = [ ‘xyz', 123, 1.23, ‘RAM', 17.5 ]
tinylist = [123, ‘RAM']
print(list) # Prints complete list
print(list[0]) # Prints first element of the list
print(list[1:3]) # Prints elements starting from 2nd till 3rd
print(list[2:]) # Prints elements starting from 3rd element
print(tinylist * 2) # Prints list two times
print(list + tinylist) # Prints concatenated lists
list.append(“Manish”) #Applicable
print(“list[3:] = ", list[3:]) 
___________________________________________________

tuple = (‘xyz', 123, 1.23, ‘RAM', 17.5 )
tinytuple = (123, ‘RAM‘)
print(tuple) # Prints complete list
print(tuple[0]) # Prints first element of the list
print(tuple[1:3]) # Prints elements starting from 2nd till 3rd
print(tuple[2:]) # Prints elements starting from 3rd element
print(tinytuple * 2) # Prints list two times
print (tuple + tinytuple) # Prints concatenated lists
tuple.append(‘Manish’) # Not Applicable
____________________________________________________

dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': ‘RAM','code:8989:, 'dept': ‘IT'}
print(dict['one']) # Prints value for 'one' key
print(dict[2]) # Prints value for 2 key
print(tinydict) # Prints complete dictionary
print(tinydict.keys()) # Prints all the keys
print(tinydict.values()) # Prints all the values
___________________________________________________

num1 = 1.5
num2 = 6.3
sum = float(num1) + float(num2)
 print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
______________________________________________________
num = float(input('Enter a number: '))
num_sqrt = num ** 0.5
print('The square root of %0.3f is %0.3f'%(num ,num_sqrt))
______________________________________________________
a=b=c=5
s = (a + b + c) / 2
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)



Tuesday, 28 January 2020

Blockchain R

block_example = list(index = 1,
                      timestamp = "2018-01-05 18.00 GMT",
                      data = "some data",
                      previous_hash = 0,
                      proof = 9,
                      new_hash = NULL)

#################################################################

library("digest")
digest("Manish" ,"sha256")
digest("BD" ,"sha256")
###############################################################

#Function that creates a hashed "block"
hash_block = function(block){
  block$new_hash <- digest(c(block$index,
                             block$timestamp,
                             block$data,
                             block$previous_hash), "sha256")
  return(block)
}
#################################################################

### Simple Proof of Work Alogrithm
proof_of_work <- function(last_proof){
  proof <- last_proof + 1
 
  # Increment the proof number until a number is found that is divisable by 99 and by the proof of the previous block
  while (!(proof %% 99 == 0 & proof %% last_proof == 0 )){
    proof <- proof + 1
  }
  return(proof)
}
##################################################################

#A function that takes the previous block and normally some data (in our case the data is a string indicating which block in the chain it is)
gen_new_block <- function(previous_block){
 
  #Proof-of-Work
  new_proof <- proof_of_work(previous_block$proof)
 
  #Create new Block
  new_block <- list(index = previous_block$index + 1,
                    timestamp = Sys.time(),
                    data = paste0("this is block ", previous_block$index +1),
                    previous_hash = previous_block$new_hash,
                    proof = new_proof)
 
  #Hash the new Block
  new_block_hashed <- hash_block(new_block)
 
  return(new_block_hashed)
}
############################################################################

# Define Genesis Block (index 1 and arbitrary previous hash)
block_genesis <-  list(index = 1,
                       timestamp = Sys.time(),
                       data = "Genesis Block",
                       previous_hash = "0",
                       proof = 1)
########################################################################

blockchain <- list(block_genesis)
previous_block <- blockchain[[1]]

# How many blocks should we add to the chain after the genesis block
num_of_blocks_to_add <- 5

# Add blocks to the chain
for (i in 1: num_of_blocks_to_add){
  block_to_add <- gen_new_block(previous_block)
  blockchain[i+1] <- list(block_to_add)
  previous_block <- block_to_add
 
  print(cat(paste0("Block ", block_to_add$index, " has been added", "\n",
                   "\t", "Proof: ", block_to_add$proof, "\n",
                   "\t", "Hash: ", block_to_add$new_hash)))
}

Saturday, 25 January 2020

BDTASK - Blockchain

pragma solidity ^0.4.0;
contract Payroll {
    // define variables
    address public CompanyOwner;

    uint employeeId;

    // create Employee object
    struct Employee {
        uint employeeId;
        address employeeAddress;
        uint wages;
        uint balance;
    }

    // employees contain Employee
    Employee[] public employees;

    // run this on contract creation just once
    function Payroll() {
        // make CompanyOwner the person who deploys the contract
        CompanyOwner = msg.sender;
        employeeId = 0;
        // add the company owner as an employee with a wage of 0
        AddEmployee(msg.sender, 0);
    }

    // function for checking number of employees
    function NumberOfEmployees() returns (uint _numEmployees) {
        return employeeId;
    }

    // allows function initiator to withdraw funds if they're an employee equal to their balance
    function WithdrawPayroll() returns (bool _success) {
        var employeeId = GetCurrentEmployeeId();
        if (employeeId != 999999) {
            // they are an employee
            if (employees[employeeId].balance > 0) {
                // if they have a balance
                if (this.balance >= employees[employeeId].balance) {
                    // if the balance of the contract is greater than or equal to employee balance
                    // then send them the money from the contract and set balance back to 0
                    msg.sender.send(employees[employeeId].balance);
                    employees[employeeId].balance = 0;
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    function GetCurrentEmployeeId() returns (uint _employeeId) {
        // loop through employees
        for (var i = 0; i < employees.length; i++) {
            // if the initiator of the function's address exists in the employeeAddress area of an Employee, return ID
            if (msg.sender == employees[i].employeeAddress) {
                return employees[i].employeeId;
            }
        }
        return 999999;
    }

    // function for getting an ID by address if needed
    function GetEmployeeIdByAddress(address _employee) returns (uint _employeeId) {
        for (var i = 0; i < employees.length; i++) {
            if (_employee == employees[i].employeeAddress) {
                return employees[i].employeeId;
            }
        }
        return 999999;
    }


    /* OWNER ONLY FUNCTIONS */
    // add an employee given an address and wages
    function AddEmployee(address _employee, uint _wages) returns (bool _success) {
        if (msg.sender != CompanyOwner) {
            return false;
        } else {
            employees.push(Employee(employeeId, _employee, _wages, 0));
            employeeId++;
            return true;
        }
    }

    // pay the employee their wages given an employee ID
    function PayEmployee(uint _employeeId) returns (bool _success) {
        if (msg.sender != CompanyOwner) {
            return false;
        } else {
            // TODO: need to figure out how to check to make sure employees[_employeeId] exists
            employees[_employeeId].balance += employees[_employeeId].wages;
            return true;
        }
    }

    // modify the employee wages given an employeeId and a new wage
    function ModifyEmployeeWages(uint _employeeId, uint _newWage) returns (bool _success) {
        if (msg.sender != CompanyOwner) {
            return false;
        } else {
            // TODO: need to figure out how to check to make sure employees[_employeeId] exists
            // change employee wages to new wage
            employees[_employeeId].wages = _newWage;
            return true;
        }
    }

    // check how much money is in the contract
    function CheckContractBalance() returns (uint _balance) {
        return this.balance;
    }

}

Monday, 13 January 2020

UPES DDU

void setup() {
  pinMode(D1, OUTPUT);
}
void loop() {
  digitalWrite(D1, HIGH); 
  delay(1000);   
  digitalWrite(D1, LOW); 
  delay(1000);           
}

________________________________


void setup() {
  Serial.begin(115200);
}

void loop() {
  int sensorValue = analogRead(A0);
  Serial.println(sensorValue);
  delay(1);     
}

Thursday, 9 January 2020

ST1- Shiny

library(shiny)
ui <- fluidPage(
   titlePanel("TABLE"),
    sidebarLayout(
      sidebarPanel(
        sliderInput("num", "integer", 1, 20, 1,
                    step = 1, animate =
                      animationOptions(interval=400, loop=TRUE))),
      mainPanel(
        tableOutput("prod")
      )) )
 
server <- function(input, output) {
    output$prod <- renderPrint({ x<-input$num
    for(i in 1:10){
      a=x*i
      cat(x,"x",i,"=",a,"<br>")
       }})}

shinyApp(ui = ui, server = server)

Wednesday, 1 January 2020

OpenCV


import cv2
import numpy as np
cam = cv2.VideoCapture(0)
cv2.namedWindow("test")
img_counter = 0
while True:
    ret, frame = cam.read()
    cv2.imshow("test", frame)
    if not ret:
        break
    k = cv2.waitKey(1)
    if k%256 == 27:
        # ESC pressed
print("Escape hit, closing...")
        break
elif k%256 == 32:
        # SPACE pressed
img_name = "opencv_frame_{}.png".format(img_counter)
        cv2.imwrite(img_name, frame)
print("{} written!".format(img_name))
img_counter += 1
cam.release()
cv2.destroyAllWindows()

________________________________________________________

import cv2
import numpy as np
cap = cv2.VideoCapture(0)


while(1):

    # Take each frame
    _, frame = cap.read()

    # Convert BGR to HSV
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

    # define range of blue color in HSV
lower_blue = np.array([110,50,50])
upper_blue = np.array([130,255,255])

    # Threshold the HSV image to get only blue colors
    mask = cv2.inRange(hsv, lower_blue, upper_blue)

    # Bitwise-AND mask and original image
    res = cv2.bitwise_and(frame,frame, mask= mask)

    cv2.imshow('frame',frame)
    cv2.imshow('mask',mask)
    cv2.imshow('res',res)
    k = cv2.waitKey(5) & 0xFF
    if k == 27:
        break


cv2.destroyAllWindows()

Tuesday, 31 December 2019

ANN




import numpy as np 
feature_set = np.array([[0,1,0],[0,0,1],[1,0,0],[1,1,0],[1,1,1]]) 
labels = np.array([[1,0,0,1,1]]) 
labels = labels.reshape(5,1)

#define hyper parameters for our neural network

np.random.seed(42)  #random.seed function so that we can get the same random values whenever the script is executed.
weights = np.random.rand(3,1) 
bias = np.random.rand(1) 
lr = 0.05

def sigmoid(x):    #activation function is the sigmoid function
    return 1/(1+np.exp(-x))

def sigmoid_der(x):    #calculates the derivative of the sigmoid function
    return sigmoid(x)*(1-sigmoid(x))

#train our neural network that will be able to predict whether a person is
#obese or not.

# An epoch is basically the number of times we want to train the algorithm on our data.
#We will train the algorithm on our data 20,000 times. The ultimate goal i
#s to minimize the error.

for epoch in range(20000): 
    inputs = feature_set

#Here we find the dot product of the input and the weight vector and add bias to it.

    # feedforward step1
    XW = np.dot(feature_set, weights) + bias
   
#We pass the dot product through the sigmoid activation function

    #feedforward step2
    z = sigmoid(XW)
   
#The variable z contains the predicted outputs. The first step of the backpropagation is to find the error.

    # backpropagation step 1
    error = z - labels

    print(error.sum())

    # backpropagation step 2
    dcost_dpred = error
    dpred_dz = sigmoid_der(z)
   
#Here we have the z_delta variable, which contains the product of dcost_dpred and dpred_dz.
#Instead of looping through each record and multiplying the input with corresponding z_delta,
#we take the transpose of the input feature matrix and multiply it with the z_delta.
#Finally, we multiply the learning rate variable lr with the derivative to increase the speed of convergence.

    z_delta = dcost_dpred * dpred_dz

    inputs = feature_set.T
    weights -= lr * np.dot(inputs, z_delta)

    for num in z_delta:
        bias -= lr * num


#You can see that error is extremely small at the end of the
#training of our neural network.
#At this point of time our weights and bias will have values that can be used to detect whether a person is diabetic or not,
#based on his smoking habits, obesity, and exercise habits.

#TEST : suppose we have a record of a patient that comes
#in who smokes, is not obese, and doesn't exercise.
#Let's find if he is likely to be diabetic or not. The input feature will look like this: [1,0,0].

single_point = np.array([1,0,0]) 
result = sigmoid(np.dot(single_point, weights) + bias) 
print(result)