Thursday, November 17, 2016

Swift 3 by example

//: Playground - noun: a place where people can play

import UIKit

// Mutable variable
var str = "Hello, playground"

// Array
var myarr : [String] = ["Watsh", "Rajneesh"]

// Dictionary
var mydict : [String:String] = ["tic": "tac", "ping": "pong"]

// constants
let conststr = "My Const String"
let countup = ["one", "two"]
let mapNameToParkingSpace = ["Alice": 10, "Rajneesh": 12]

// subscript of array
let elem = countup[1]

// Initializers
let emptyString = String()
let emptyArr = [Int]()

let emptySet = Set<Float>()

let defaultNum = Int()

let defaultBool = Bool()

let defaultFloat = Float()

// initializing a set
let availableRoomsSet = Set([1,2,3, 4])

// Properties

// Optionals - can be value of the said datatype or nil
var anOptionalFloat: Float?
var anOptionalArrayOfStrings: [String]?
var anOptionalArrayOfOptionalStrings: [String?]?

var reading1: Float?
var reading2: Float?

reading1 = 1.0
reading2 = 2.0

// to use the value we need to unwrap the optional

// 1. forced unwrapping - used when sure that value will not be nil
// if reading2 assignment commented - this will result in error

let avgReading = (reading1! + reading2!)/2

// 2. Optional binding - safe to use always
//  if reading2 assignment is commented out, will go to else block
if let r1 = reading1,
    let r2 = reading2 {
    let avg = (r1 + r2)/2
} else {
    print("reading nil")

// Subscripting dictionary
let nameByParkingSpace = [13: "Alice", 27: "Bob"]
let space13Assignee: String? = nameByParkingSpace[13]
let space42Assignee: String? = nameByParkingSpace[42]

if let space13Assignee = nameByParkingSpace[13] {
    print("Key 13 is assigned in the dictionary!")

// looping
let range = 0 ..< countup.count

for i in range {
    let string = countup[i]
    // Use 'string'

for string in countup {
    // Use 'string'

// return a tuple of index and value in array
for (i, string) in countup.enumerated() {
    // (0, "one"), (1, "two")

// iterating dictionary
for (space, name) in nameByParkingSpace {
    let permit = "Space \(space): \(name)"

// enum
enum PieType {
    case Apple
    case Cherry
    case Pecan

let favoritePie = PieType.Apple

let name: String

// switch-case with enum
// no break required as only the code within the matching case is executed so break is implicit
// fallthrough behavior can be set
switch favoritePie {
case .Apple:
    name = "Apple"
case .Cherry:
    name = "Cherry"
case .Pecan:
    name = "Pecan"

let osxVersion: Int = 7
switch osxVersion {
case 0...8:
    print("A big cat")
case 9:
case 10:
    print("Greetings, people of the future! What's new in 10.\(osxVersion)?")

// Value associated with enum
enum PieTypeInt: Int {
    case Apple = 0
    case Cherry
    case Pecan

Friday, November 11, 2016

Understanding Bitcoin technology

A short summary of what i understood so far about Bitcoin technology:
  1. It is a digital cryptocurrency - uses asymmetric encryption (private/public key pairs) during transactions and hashing (SHA256) to generate bitcoin addresses (which is analogous to a bank account number)
  2. The main author of this technology and initial software is Satoshi Nakamoto but no one knows him/her/them. Satoshi released the bitcoin software in Jan 2009. 
  3. It is decentralized - like gold and unlike paper currency which is centrally managed by governments of countries - so it is also called Digital Gold.
  4. An upper limit is set to the number of bitcoins that will be mined or generated. It is 21 million bitcoins (or BTC or XBT) and this number will be reached by the year 2040. At present the total bitcoins are around 16 million at the time of this writing ( That the upper limit is fixed so the value of the bitcoin will keep increasing as time goes by. This is called deflation. For paper currency government's print more money to offset any deficit causing the existing value of money to reduce - and this is inflation. Bitcoin, like gold, is deflationary and its value keeps increasing unlike paper currency whose value is decreasing due to inflation.
  5. The lowest unit in bitcoin cryptocurrency is (0.000000001 bitcoin) which is called a "satoshi". Then there is 0.0000001 micro bitcoin or bit and 0.0001 milli bitcoin. So we can go very granular and can make transactions with very small fractions like 0.000345 bitcoin or BTC.
  6. Value of 1BTC at the time of this writing is $717 approx.
  7. It uses a peer-to-peer (P2P) network of computers. 
  8. A set of transactions is grouped in a structure called "block" and added to the end of the "blockchain". Blockchain is like a ledger of all transactions ever done using bitcoins. All nodes running the bitcoin software get a copy of this ledger (initially it takes quite a while to download the blockchain data). After initial download all transactions are added to the blockchain. 
  9. Every 10 mins the blocks of transactions will be synched to all nodes in the bitcoin network but only one node  (also called "miners") that wins a lottery (there could be just one such winner usually) will be able to change the blockchain and add the blocks of transactions it received to the blockchain. This then makes the transactions permanent in the blockchain and it will be synched to all thousands of miner nodes in the P2P network (thus no one central node maintains the ledger and it is virtually impossible to delete a transaction once done). The idea is that every 10 mins only one node in the P2P network will win the chance to add blocks to the blockchain. 
  10. If there happens to be a collision (meaning 2 nodes win the lottery at the same time) then only one of them will hold once in the next 10 mins the next winner node adds a block to one of the previous lottery winning node's blockchain. Then that (longest blockchain) remains as the source of truth and the other blockchain becomes orphaned. This protocol where nodes in the distributed computing environment arrive at a consensus and choose a winner every 10 mins is said to solve a byzantine general's problem that was deemed unsolvable earlier.
  11. The miners are rewarded in 2 ways - 
    1. each transaction has a fee associated with it that is earned as a reward by the miner that wins the lottery. It is generally a small value (0.0002 BTC at the time of this writing in Bitcoin-core wallet program). 
    2. when bitcoins were introduced in Jan 2009 then miners that used to win in those days until next 4 years were rewarded with 50 BTC every 10mins. Then in the following 4 years this reward was halved to 25 BTC and then in the following 4 years to 12.5 BTC and so on. This value will keep reducing and so the reward fee value will keep increasing. The reason that it is reducing is to ensure the total "mined" or generated bitcoins will not go beyond 21 Million BTC.
  12. The incentive to "find" a block (akin to mining and finding gold) in bitcoin is why several folks invested in hardware that can do bitcoin mining on the P2P network and be compensated by the fee associated with all transactions that make that block they find and also the share of new bitcoins mined which also goes to the miner that found the block.

Wednesday, November 09, 2016

git clone shows all files as deleted or changed

When git clone shows all files as deleted or changed then do the following:

Ensure the following property is set or else windows will not be able to handle file path names longer than 260 chars. Thus resulting in odd behavior of git.

git config --system core.longpaths true

git reset --hard origin/[your_branch]-- this will reset local git repo index to match the one at remote branch.

Monday, October 17, 2016

Good Health numbers

HDL (good cholestrol) > 50
LDL (bad cholestrol) < 100 (best is < 50 - that is centenarian type)

Total cholestrol (HDL + LDL) < 200

High cholestrol means heart attack risk (#1 killer)
Obesity, diabetes, high blood pressure and smoking are 4 other risk factors.

Cholesterol ---   <  200
HDL  ---  40  ---  60
LDL  ---    <  100
VLDL --     <  30
Triglycerides --   <  150

Borderline --200 -- 239
High ----    >  240
V.High --    >  250

Borderline --130 ---159
High ---  160  ---  189
V.High --  > 190

Borderline - 150 -- 199
High --   200  ---  499
V.High --     >   500

1.50  Lac  ----  4.50 Lac

Vitamin-D --  50   ----  80
Uric Acid --  3.50  ---  7.20

Urea  ---   17   ---   43
Calcium --  8.80  --  10.60
Sodium --  136  ---  146
Protein  --   6.40  ---  8.30

           HIGH BP
120/80 --  Normal
130/85 --Normal  (Control)
140/90 --  High
150/95 --  V.High

         LOW BP
120/80 --  Normal
110/75 --  Normal  (Control)
100/70 --  Low
90//65 --   V.Low

Glucose (F) --  70  ---  100
(12 hrs Fasting)
Glucose (PP) --  70  --- 140
(2 hrs after eating)
Glucose (R) --  70  ---  140
(After 2 hrs)
Male --  13  ---  17
Female --  11 ---  15
RBC Count  -- 4.50 -- 5.50

72  per minute (standard)
60 --- 80 p.m. (Normal)
40 -- 180  p.m.(abnormal)

98.4 F    (Normal)
99.0 F Above  (Fever)

Please help your Relatives, Friends by sharing this information....

Heart Attacks And Drinking Warm Water:

This is a very good article. Not only about the warm water after your meal, but about Heart Attack's . The Chinese and Japanese drink hot tea with their meals, not cold water, maybe it is time we adopt their drinking habit while eating. For those who like to drink cold water, this article is applicable to you. It is very Harmful to have Cold Drink/Water during a meal. Because, the cold water will solidify the oily stuff that you have just consumed. It will slow down the digestion. Once this 'sludge' reacts with the acid, it will break down and be absorbed by the intestine faster than the solid food. It will line the intestine. Very soon, this will turn into fats and lead to cancer . It is best to drink hot soup or warm water after a meal.

French fries and Burgers
are the biggest enemy of heart health. A coke after that gives more power to this demon. Avoid them for
your Heart's & Health.

Drink one glass of warm water just when you are about to go to bed to avoid clotting of the blood at night to avoid heart attacks or strokes.

Sunday, October 16, 2016

A Virtual assistant for Raspberrry Pi

It is made following the nice book on the subject by Tanay Pant - Building a Virtual Assistant for Raspberry Pi (APress)
This is similar though much simplified version of products like Google Home or Amazon Echo.
The idea is to use the Raspberry Pi based Virtual Assistant as one of the interfaces for Amigo chatbot project.
Ria uses Google STT (Speech to text) API and espeak on Linux (or say on OSX) for TTS (Text to speech).
Currently supported skills/features:
  1. Play music from configured path on local disk
  2. Read news headlines scrapping news from
  3. Take notes and store in local sqllite DB
  4. Tell time
  5. Tell local weather of configured city
  6. Post tweets on twitter
  7. Look up wikipedia and read a short description for any term, person or place (anything on wikipedia).

Source available on Github:

Movie Recommender System (CMPE 277)

Movie recommender built using Apache Spark + mongo DB + Android App

Uses Spark MLlib model based collaborative filtering for movie recommendation (Alternating Least Squares algorithm).

Project sources are at:

  1. - Apache Spark + Mongo DB based backend service for movie recommendations
  2. - Android App

Thursday, September 08, 2016

AWS Kinesis and AWS IoT services

Amazon Kinesis Service: is a platform for streaming data on AWS. It helps to load and analyze streaming data and build custom applications like:
  • 1.     Recommendation engine.
  • 2.     Real-time metering and billing system.
  • 3.     Loading data from transactional databases to data warehouses can use Kinesis for temporary durable storage of data in transit.

Data generated by web applications, mobile devices, IoT sensors, wearable devices etc. can be in the tune of TBs/hr. This data needs to be collected in real-time and processed and stored continuously. Amazon Kinesis service enables one to do this.

The streaming data can be captured and submitted to Amazon Kinesis Firehose, which loads streaming data continuously into S3, Redshift and Amazon Elasticsearch domains. The streaming data is then analyzed from these stores using Business Intelligence tools.

Amazon Analytics: enables running standard SQL queries against data streams. Kinesis analytics can then be used to feed into other analytics tools.

AWS IoT: enables device to device and device to cloud applications communication. It can support billions of devices exchanging trillions of messages and can process and route those messages to AWS endpoints and to other devices reliably and securely. AWS IoT services can be used to build IoT applications that gather, process, analyze and act on data generated by connected devices, without having to manage any infrastructure.
It supports the following communication protocols:
1.     HTTP
2.     Websockets
3.     MQTT

The connection between devices and application are authenticated at AWS IoT service and only authenticated users are allowed to control the state of the device or the authenticated device connections to AWS IoT endpoints are allowed.

At AWS IoT service, one can filter, transform and act upon device data on the fly (say invoke a lambda function). The last state of device is persisted which can be read even when the device goes offline. The state change for the device can be requested while it is offline to be implemented on the device when it is online again by AWS IoT backend.

 How it works: 

Comparison of IoT  supported across cloud providers: 

IBM IoT Foundation
Microsoft IoT
HTTP, MQTT, Websockets, custom protocols
HTTP, AMQP, MQTT and custom protocols
Certified Hardware Platforms
Broadcom, Marvell, Renesas, Texas Instruments, Microchip, Intel, Mediatek, QualComm, Seeed, BeagleBoard
ARM mbed, Texas Instruments, Raspberry Pi, Arduino Uno, Intel
Intel, Raspberry Pi 2, Freescale, Texas Instruments, MinnowBoard, BeagleBoard, Seeed,
Paying million messages traffic (published from devices + delivered to devices)
Paying related to number of devices, data traffic and storage.
Paying for IoT Hub unit related to number of devices and messages per day
Communication Patterns
Telemetry, Command
Telemetry, Command
Telemetry, Command
C, Node.js
C, C#, Python, Java, Node.js
.Net, Java, C, Node.js
TLS (mutual auth)
TLS (sever only auth)
X.509 certificate client authentication, IAM service, Cognito service
Per-device with token
Per-device with SAS token