Sunday 18 October 2020

IOT and COVID 19

 





COVID 19 and Blockchain

 

MAJOR CHALLENGES OF COVID-19

·        One major issue is how prepared the world’s health systems are to respond to this outbreak.

·        Tracking a huge population of infectious patients to stop epidemics

·        Another is the immediate requirement for developing better diagnostics, vaccines, and targeted therapeutics.

·        Misinformation and conspiracy theories spread through social media platforms.

·        Various limitations while accessing the tools when required. 

·        No adequate measures to adopt in a crisis situation. 

CAN BLOCKCHAIN HELP IN PREVENTING PANDEMICS?

With Blockchain we can share any transaction / information, real time, between relevant parties present as nodes in the chain, in a secure and immutable fashion. In this case, had there been a blockchain where WHO, Health Ministry of each country and may be even relevant nodal hospitals of each country, were connected, sharing real time information, about any new communicable disease, then the world might have woken up much earlier. We might have seen travel restrictions given sooner, quarantining policies set sooner and social distancing implemented faster. And may be fewer countries would have got impacted.

What every country is doing now fighting this pandemic, would have been restricted to fewer countries and in a much smaller scale. The usage of a Blockchain to share the information early on, might have saved the world a lot of pain.

The world had not seen anything like COVID-19 pandemic before in the recent history. Today we need to take a hard look at the reporting infrastructure available for communicable diseases, both technology and regulations and improve upon that, such that we do not need to face another pandemic like this in the future. 

 

Source : https://www.bbvaopenmind.com/en/technology/digital-world/blockchain-technology-and-covid-19/

Sunday 15 March 2020

Tkinter Game

import tkinter
#...and for creating random numbers.
import random
 
#the list of possible colour.
colours = ['Red','Blue','Green','Pink','Black','Yellow','Orange','White','Purple','Brown']
#the player's score, initially 0.
score=0
#the game time left, initially 30 seconds.
timeleft=30
 
#a function that will start the game.
def startGame(event):
 
    #if there's still time left...
    if timeleft == 30:
        #start the countdown timer.
        countdown()
        
    #run the function to choose the next colour.
    nextColour()
 
#function to choose and display the next colour.
def nextColour():
 
    #use the globally declared 'score' and 'play' variables above.
    global score
    global timeleft
 
    #if a game is currently in play...
    if timeleft > 0:
 
        #...make the text entry box active.
        e.focus_set()
 
        #if the colour typed is equal to the colour of the text...
        if e.get().lower() == colours[1].lower():
            #...add one to the score.
            score += 1
 
        #clear the text entry box.
        e.delete(0, tkinter.END)
        #shuffle the list of colours.
        random.shuffle(colours)
        #change the colour to type, by changing the text _and_ the colour to a random colour value
        label.config(fg=str(colours[1]), text=str(colours[0]))
        #update the score.
        scoreLabel.config(text="Score: " + str(score))
 
#a countdown timer function. 
def countdown():
 
    #use the globally declared 'play' variable above.
    global timeleft
 
    #if a game is in play...
    if timeleft > 0:
 
        #decrement the timer.
        timeleft -= 1
        #update the time left label.
        timeLabel.config(text="Time left: " + str(timeleft))
        #run the function again after 1 second.
        timeLabel.after(1000, countdown)
    
#create a GUI window.
root = tkinter.Tk()
#set the title.
root.title("TTCANTW")
#set the size.
root.geometry("375x200")
 
#add an instructions label.
instructions = tkinter.Label(root, text="Type in the colour of the words, and not the word text!", font=('Helvetica', 12))
instructions.pack()
 
#add a score label.
scoreLabel = tkinter.Label(root, text="Press enter to start", font=('Helvetica', 12))
scoreLabel.pack()
 
#add a time left label.
timeLabel = tkinter.Label(root, text="Time left: " + str(timeleft), font=('Helvetica', 12))
timeLabel.pack()
 
#add a label for displaying the colours.
label = tkinter.Label(root, font=('Helvetica', 60))
label.pack()
 
#add a text entry box for typing in colours.
e = tkinter.Entry(root)
#run the 'startGame' function when the enter key is pressed.
root.bind('<Return>', startGame)
e.pack()
#set focus on the entry box.
e.focus_set()
 
#start the GUI
root.mainloop()

MR Python

from pandas import DataFrame
from sklearn import linear_model
import statsmodels.api as sm

#statsmodels is a Python module that provides classes and functions
#for the estimation of many different statistical models,
#as well as for conducting statistical tests, and statistical
#data exploration.

Stock_Market = {'Year': [2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016],
                'Month': [12, 11,10,9,8,7,6,5,4,3,2,1,12,11,10,9,8,7,6,5,4,3,2,1],
                'Interest_Rate': [2.75,2.5,2.5,2.5,2.5,2.5,2.5,2.25,2.25,2.25,2,2,2,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75],
                'Unemployment_Rate': [5.3,5.3,5.3,5.3,5.4,5.6,5.5,5.5,5.5,5.6,5.7,5.9,6,5.9,5.8,6.1,6.2,6.1,6.1,6.1,5.9,6.2,6.2,6.1],
                'Stock_Index_Price': [1464,1394,1357,1293,1256,1254,1234,1195,1159,1167,1130,1075,1047,965,943,958,971,949,884,866,876,822,704,719]       
                }

df = DataFrame(Stock_Market,columns=['Year','Month','Interest_Rate',
                                     'Unemployment_Rate','Stock_Index_Price'])

X = df[['Interest_Rate','Unemployment_Rate']] # here we have 2 variables for multiple regression. If you just want to use one variable for simple linear regression, then use X = df['Interest_Rate'] for example.Alternatively, you may add additional variables within the brackets
Y = df['Stock_Index_Price']

# with sklearn
regr = linear_model.LinearRegression()
regr.fit(X, Y)

print('Intercept: \n', regr.intercept_)
print('Coefficients: \n', regr.coef_)

# prediction with sklearn
New_Interest_Rate = 2.75
New_Unemployment_Rate = 5.3
print ('Predicted Stock Index Price: \n',
       regr.predict([[New_Interest_Rate ,New_Unemployment_Rate]]))

# with statsmodels
X = sm.add_constant(X) # adding a constant

#OLS stands for ordinary least squares
#As we know, the simplest linear regression algorithm assumes
#that the relationship between an independent variable (x)
#and dependent variable (y) is of the following form: y = mx + c,
#which is the equation of a line.
#In line with that, OLS is an estimator in which the values of m and
#c (from the above equation) are chosen in such a
#way as to minimize the sum of the squares of the differences between the
#observed dependent variable and predicted dependent variable.
#That’s why it’s named ordinary
#least squares.Also, it should be noted that when the sum of
#the squares of the differences is minimum,
#the loss is also minimum—hence the prediction is better.

model = sm.OLS(Y, X).fit()
predictions = model.predict(X)

print_model = model.summary()
print(print_model)


#Stock_Index_Price = (Intercept) + (Interest_Rate coef)*X1 + (Unemployment_Rate coef)*X2
#Stock_Index_Price = (1798.4040) + (345.5401)*X1 + (-250.1466)*X2
Interest Rate = 2.75 (i.e., X1= 2.75)
Unemployment Rate = 5.3 (i.e., X2= 5.3)

#Stock_Index_Price = (1798.4040) + (345.5401)*(2.75) + (-250.1466)*(5.3) = 1422.86

Saturday 14 March 2020

Tkinter2

from openpyxl.workbook import Workbook
import tkinter as tk
import pandas as pd

def saveinfo():
    valor1 = entry1.get()
    valor2 = entry2.get()
    valor3 = entry3.get()

    data.append([valor1, valor2, valor3])
    print(data)

def export():
    df = pd.DataFrame(data)
    df.to_excel("DataBase.xlsx")

def opennewwindow():
    global entry1
    global entry2
    global entry3

    window.destroy()

    newwindow = tk.Tk()

    tk.Label(newwindow, text="Please, enter data: ").grid(column=0, row=0, columnspan=3)

    tk.Label(newwindow, text="Number").grid(column=0, row=1)
    entry1 = tk.Entry(newwindow)
    entry1.grid(column=1, row=1)

    tk.Label(newwindow, text="Description", ).grid(column=0, row=2)
    entry2 = tk.Entry(newwindow)
    entry2.grid(column=1, row=2)

    tk.Label(newwindow, text="Brand").grid(column=0, row=3)
    entry3 = tk.Entry(newwindow)
    entry3.grid(column=1, row=3)

    tk.Button(newwindow, text="Save", command=saveinfo).grid(column=2, row=2, sticky='we')
    tk.Button(newwindow, text="Export", command=export).grid(column=2, row=3, sticky='we')

    newwindow.mainloop()

# --- main ---

df = pd.DataFrame
data = []

window = tk.Tk()
tk.Label(window, text="Platform").grid(column=0, row=0)
tk.Button(window, text="Choose an element: ", command=opennewwindow).grid(column=0, row=1)

window.mainloop()

Tkinter1

import tkinter as tk

root= tk.Tk()

canvas1 = tk.Canvas(root, width = 400, height = 300,  relief = 'raised')
canvas1.pack()

label1 = tk.Label(root, text='Calculate the Square Root')
label1.config(font=('helvetica', 14))
canvas1.create_window(200, 25, window=label1)

label2 = tk.Label(root, text='Type your Number:')
label2.config(font=('helvetica', 10))
canvas1.create_window(200, 100, window=label2)

entry1 = tk.Entry (root)
canvas1.create_window(200, 140, window=entry1)

def getSquareRoot ():
 
    x1 = entry1.get()
 
    label3 = tk.Label(root, text= 'The Square Root of ' + x1 + ' is:',font=('helvetica', 10))
    canvas1.create_window(200, 210, window=label3)
 
    label4 = tk.Label(root, text= float(x1)**0.5,font=('helvetica', 10, 'bold'))
    canvas1.create_window(200, 230, window=label4)
 
button1 = tk.Button(text='Get the Square Root', command=getSquareRoot, bg='brown', fg='white', font=('helvetica', 9, 'bold'))
canvas1.create_window(200, 180, window=button1)

root.mainloop()

Ganpat Uni

from tkinter import *
parent = Tk()
name = Label(parent,text = "Name").grid(row = 0, column = 0)
e1 = Entry(parent).grid(row = 0, column = 1)
password = Label(parent,text = "Password").grid(row = 1, column = 0)
e2 = Entry(parent).grid(row = 1, column = 1)
submit = Button(parent, text = "Submit").grid(row = 4, column = 0)
parent.mainloop()

______________________________________________________

import tkinter
#...and for creating random numbers.
import random
 
#the list of possible colour.
colours = ['Red','Blue','Green','Pink','Black','Yellow','Orange','White','Purple','Brown']
#the player's score, initially 0.
score=0
#the game time left, initially 30 seconds.
timeleft=30
 
#a function that will start the game.
def startGame(event):
 
    #if there's still time left...
    if timeleft == 30:
        #start the countdown timer.
        countdown()
        
    #run the function to choose the next colour.
    nextColour()
 
#function to choose and display the next colour.
def nextColour():
 
    #use the globally declared 'score' and 'play' variables above.
    global score
    global timeleft
 
    #if a game is currently in play...
    if timeleft > 0:
 
        #...make the text entry box active.
        e.focus_set()
 
        #if the colour typed is equal to the colour of the text...
        if e.get().lower() == colours[1].lower():
            #...add one to the score.
            score += 1
 
        #clear the text entry box.
        e.delete(0, tkinter.END)
        #shuffle the list of colours.
        random.shuffle(colours)
        #change the colour to type, by changing the text _and_ the colour to a random colour value
        label.config(fg=str(colours[1]), text=str(colours[0]))
        #update the score.
        scoreLabel.config(text="Score: " + str(score))
 
#a countdown timer function. 
def countdown():
 
    #use the globally declared 'play' variable above.
    global timeleft
 
    #if a game is in play...
    if timeleft > 0:
 
        #decrement the timer.
        timeleft -= 1
        #update the time left label.
        timeLabel.config(text="Time left: " + str(timeleft))
        #run the function again after 1 second.
        timeLabel.after(1000, countdown)
    
#create a GUI window.
root = tkinter.Tk()
#set the title.
root.title("TTCANTW")
#set the size.
root.geometry("375x200")
 
#add an instructions label.
instructions = tkinter.Label(root, text="Type in the colour of the words, and not the word text!", font=('Helvetica', 12))
instructions.pack()
 
#add a score label.
scoreLabel = tkinter.Label(root, text="Press enter to start", font=('Helvetica', 12))
scoreLabel.pack()
 
#add a time left label.
timeLabel = tkinter.Label(root, text="Time left: " + str(timeleft), font=('Helvetica', 12))
timeLabel.pack()
 
#add a label for displaying the colours.
label = tkinter.Label(root, font=('Helvetica', 60))
label.pack()
 
#add a text entry box for typing in colours.
e = tkinter.Entry(root)
#run the 'startGame' function when the enter key is pressed.
root.bind('<Return>', startGame)
e.pack()
#set focus on the entry box.
e.focus_set()
 
#start the GUI
root.mainloop()

Thursday 12 March 2020

Ganpat University

https://drive.google.com/open?id=1oD1mFi4zmqz5xGuCJ7_OdUKZgW5fekct

https://drive.google.com/file/d/1M4sGfss3DLYosCxWZoai2i9X1AMZoolb/view?usp=sharing

https://drive.google.com/open?id=1ayhZqjZfCQep_1q6LypAv9HMMyq11HzD

Tuesday 10 March 2020

code

http://www-eio.upc.edu/~pau/cms/rdata/datasets.html



## KAJAL

import pandas as pd
import numpy as np
z= [];
letters = [];
for num in range(1, 20):
   
    # checking condition
    if num % 2 != 0:
        z.append(num)
     
print(z)

for c in range(97, 107):
        letters.append(chr(c))
print(letters)
numbers = np.random.randint(100,200,10)
df=pd.DataFrame({"a":z,"b":letters,"c":numbers})
df
________________________________________________

## Abhishek

l = []
for i in range (1,20) :
    if(i %2 != 0):
        l.append(i)
l1= []
for letter in 'abcdefghij':
    l1.append(letter)

import random
l2=random.sample(range(1,100),10)

df=pd.DataFrame(list(zip(l,l1,l2)))

Saturday 7 March 2020

IIT Indore

library(shiny)

ui = fluidPage(
   titlePanel("TABLE"),
    sidebarLayout(
      sidebarPanel(
        sliderInput("num", "integer", 1, 200, 1,step = 1, animate =
animationOptions(interval=400, loop=TRUE))),
      mainPanel(
        tableOutput("iit")
      )) )

server = function(input, output) {
    output$iit = renderPrint({ x<-input$num
    for(i in 1:10){
      a=x*i
      cat(x,"x",i,"=",a,"<br>")
       }})}

shinyApp(ui = ui, server = server)
_______________________________________________________

library(shiny)
ui<-fluidPage(
  sidebarPanel(
    sliderInput("num","integer",1,200,5,step=1,animate = animationOptions(interval = 1000,loop = TRUE))),
  radioButtons("radio",label = h1("Choose one"),choices = list("Table"=1,"Even/Odd"=2,"Fact"=3),selected = 1),
  hr(),
  mainPanel(
    tableOutput("abc")
  )
)


server<-function(input,output)
{

    output$abc<-renderPrint({
      r<-input$radio
      x<-input$num
      if(r==1){
        for(i in 1:10)
        {
          cat(x,"X",i,"=",x*i,"<br>")
        }
      }else if(r==2)
      {
        if(x%%2==0)
        {
          print("Even")
        }else{
          print("Odd")
        }
      }
      else{
        print(factorial(x))
      }
    })
 

 
shinyApp(ui=ui,server=server)

____________________________________________________________


# Splitting the dataset into the Training set and Test set

install.packages('caTools')
library(caTools)

set.seed(123)
split = sample.split(dataset$Purchased, SplitRatio = 0.75)

training_set = subset(dataset, split == TRUE)
test_set = subset(dataset, split == FALSE)
View(training_set)
View(test_set)

# Feature Scaling

training_set[-3] = scale(training_set[-3])
test_set[-3] = scale(test_set[-3])

View(training_set)
View(test_set)
##############################################

# Fitting SVM to the Training set
install.packages('e1071')
library(e1071)

classifier = svm(formula = Purchased ~ .,
                 data = training_set,
                 type = 'C-classification',
                 kernel = 'linear')

print(classifier)

A=classifier$SV
Print(A)

# Predicting the Test set results

y_pred = predict(classifier, newdata = test_set[-3])


# Making the Confusion Matrix

cm = table(test_set[, 3], y_pred)
print(cm)
################################################

#Visualizing the Training set results

# installing library ElemStatLearn
library(ElemStatLearn)

# Plotting the training data set results
set = training_set
X1 = seq(min(set[, 1]) - 1, max(set[, 1]) + 1, by = 0.01)
X2 = seq(min(set[, 2]) - 1, max(set[, 2]) + 1, by = 0.01)

grid_set = expand.grid(X1, X2)
colnames(grid_set) = c('Age', 'EstimatedSalary')
y_grid = predict(classifier, newdata = grid_set)

plot(set[, -3],
     main = 'SVM (Training set)',
     xlab = 'Age', ylab = 'Estimated Salary',
     xlim = range(X1), ylim = range(X2))

contour(X1, X2, matrix(as.numeric(y_grid), length(X1), length(X2)), add = TRUE)
points(grid_set, pch = '.', col = ifelse(y_grid == 1, 'coral1', 'aquamarine'))
points(set, pch = 21, bg = ifelse(set[, 3] == 1, 'green4', 'red3'))

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

#Visualizing the Test set results
set = test_set
X1 = seq(min(set[, 1]) - 1, max(set[, 1]) + 1, by = 0.01)
X2 = seq(min(set[, 2]) - 1, max(set[, 2]) + 1, by = 0.01)

grid_set = expand.grid(X1, X2)
colnames(grid_set) = c('Age', 'EstimatedSalary')
y_grid = predict(classifier, newdata = grid_set)

plot(set[, -3], main = 'SVM (Test set)',
     xlab = 'Age', ylab = 'Estimated Salary',
     xlim = range(X1), ylim = range(X2))

contour(X1, X2, matrix(as.numeric(y_grid), length(X1), length(X2)), add = TRUE)

points(grid_set, pch = '.', col = ifelse(y_grid == 1, 'coral1', 'aquamarine'))

points(set, pch = 21, bg = ifelse(set[, 3] == 1, 'green4', 'red3'))

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

Wednesday 4 March 2020

IBM BigData


CREATE TABLE feedback_vnr(comments STRING);
load data LOCAL INPATH '/home/cloudera/Desktop/file.txt' INTO TABLE feedback_vnr;
select * from feedback_vnr;
select split(comments,' ') FROM feedback_vnr;
select explode(split(comments,' ')) FROM feedback_vnr
select word,count(*) from (select explode(split(comments,' ')) as word from feedback_vnr)  tmp GROUP BY word;

___________________________

A = load '/user/cloudera/55';
B = foreach A generate flatten(TOKENIZE((chararray)$0)) as word;
C = filter B by word matches '\\w+';
D = group C by word;
E = foreach D generate COUNT(C),group;
store E into '/user/cloudera/n66';
____________________________



 Most occurred first character in the word of a  file


lines  = LOAD '/user/cloudera/my-friends' AS (line: chararray); 
tokens = FOREACH lines GENERATE flatten(TOKENIZE(line)) As token:chararray;
letters = FOREACH tokens  GENERATE SUBSTRING(token,0,1) As letter:chararray;
lettergrp = GROUP letters by letter; 
countletter  = FOREACH  lettergrp  GENERATE group,COUNT(letters);
OrderCnt = ORDER countletter BY $1 DESC; 
result = LIMIT OrderCnt 1;
STORE result into '/user/cloudera/dummy5556777777';

____________________________________



tier1.sources  = source1
tier1.channels = channel1
tier1.sinks    = sink1 

tier1.sources.source1.type     = netcat
tier1.sources.source1.bind     = 127.0.0.1
tier1.sources.source1.port     = 44444
tier1.sources.source1.channels = channel1

tier1.channels.channel1.type   = memory
tier1.channels.channel1.capacity = 100

tier1.sinks.sink1.type= HDFS
tier1.sinks.sink1.fileType=DataStream
tier1.sinks.sink1.channel      = channel1

tier1.sinks.sink1.hdfs.path = hdfs://localhost:8020/user/cloudera/flume/events_manish_rvim

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