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()