Tuesday, 9 April 2019

Modify 3 Dice outcomes to a Single Die Throw


Σ  Face Values #
3 (1,1,1)* 1
4 (1,1,2)+  3
5 (1,1,3)+ (1,2,2)+  6
6 (1,1,4)+ (1,2,3)- (2,2,2)* 10
7 (1,1,5)+ (1,2,4)- (1,3,3)+ (2,2,3)+  15
8 (1,1,6)+ (1,2,5)- (1,3,4)- (2,2,4)+ (2,3,3)+  21
9 (1,2,6)- (1,3,5)- (1,4,4)+ (2,2,5)+ (2,3,4)- (3,3,3)* 25
10 (1,3,6)- (1,4,5)- (2,2,6)+ (2,3,5)- (2,4,4)+ (3,3,4)+ 27
11 (1,4,6)- (1,5,5)+ (2,3,6)- (2,4,5)- (3,3,5)+ (3,4,4)+ 27
12 (1,5,6)- (2,4,6)- (2,5,5)+ (3,4,5)- (3,3,6)+ (4,4,4)* 25
13 (1,6,6)+ (2,5,6)- (3,4,6)- (3,5,5)+ (4,4,5)+  21
14 (2,6,6)+ (3,5,6)- (4,4,6)+ (4,5,5)+  15
15 (3,6,6)+ (4,5,6)- (5,5,5)*  10
16 (4,6,6)+ (5,5,6)+ 6
17 (5,6,6)+ 3
18 (6,6,6)* 1
     
  TOTAL OUTCOMES 216
     
Keys * == unique (#1),  + == 3! / 2! (#3) , - == 3!  (#6)  


import java.util.* ;

int [] sumOfThree = new int[19] ;

void setup() {

    // 3 dice summation simulation
    
    for (int d1 = 1 ; d1 < 7 ; d1++) {
      for(int d2 = 1 ; d2 < 7 ; d2++) {
        for (int d3 = 1 ; d3 < 7 ; d3++) {
              int sum = (d1 + d2 + d3) ; 
              sumOfThree[sum]++ ;
        }
      }
    }
    
    for(int i = 3 ; i < 19 ; i++) {
      println("Sum ",i,"# outcomes",sumOfThree[i]) ;  
    }
    
    // Group sum outcomes together and check if the are equally distrubuted
    // Note all these groups should be the same - 6 groups of 36  (216 outcomes - throwing 3 dice)
    
    println("Group 1", sumOfThree[3]  + sumOfThree[6] + sumOfThree[9]) ;
    println("Group 2",sumOfThree[18]  + sumOfThree[15] + sumOfThree[12]) ;

    println("Group 3",sumOfThree[4]  + sumOfThree[5] + sumOfThree[10]) ;
    println("Group 4",sumOfThree[17]  + sumOfThree[16] + sumOfThree[11]) ;
    
    println("Group 5",sumOfThree[7]  + sumOfThree[8]) ;
    println("Group 6",sumOfThree[13]  + sumOfThree[14]) ;
    
    // Generate a HashMap which maps sum of 3 dice to a single die throw outcome.
    // We have noted that the 3 dice 'summation' outcomes can be split into 
    // the groups (3,6,9), (4,5,10), (7,8), (13,14) (11,16,17), (12,15,18)
    // with each of these SIX groups adding up to 36.
    
    Map<Integer,Integer> singleThrow = new HashMap() ;
    
    // Throw 1
    singleThrow.put(3,1) ; singleThrow.put(6,1) ; singleThrow.put(9,1) ;
    
    // Throw 2
    singleThrow.put(18,2) ; singleThrow.put(15,2) ; singleThrow.put(12,2) ;
    
    // Throw 3
    singleThrow.put(4,3) ; singleThrow.put(5,3) ; singleThrow.put(10,3) ;

    // Throw 4
    singleThrow.put(17,4) ; singleThrow.put(16,4) ; singleThrow.put(11,4) ;

    // Throw 5
    singleThrow.put(7,5) ; singleThrow.put(8,5) ; 

   // Throw 6
    singleThrow.put(14,6) ; singleThrow.put(13,6) ; 


    // We now have a new map which maps the sum of 3 dice to a single die outcome.
    // go through all 216 outcomes and make sure that our 'roll' comes out evenly distributed.
    int [] roll = new int[7] ;

    for (int d1 = 1 ; d1 < 7 ; d1++) {
      for(int d2 = 1 ; d2 < 7 ; d2++) {
        for (int d3 = 1 ; d3 < 7 ; d3++) {
              int sum = (d1 + d2 + d3) ; 
              int die = singleThrow.get(sum) ;
              roll[die - 1]++ ;
        }
      }
    }
    
    for(int i = 0 ; i < 6 ; i++) {
      println("Die Face ",(i + 1),"Outcomes of of 216 = ",roll[i], "Pass:", roll[i] == 36) ;  
    }

    exit() ;
    
}

Thursday, 21 March 2019

Microcode for a SWAP Reg0, Reg1 (3 Clock Cycles)




For those wanted to extend their instruction set - without adding too much complexity to microcode instructions - a SWAP instruction, where two registers are swapped over - can be implemented in 3 clock cycles just by using a series of 3 exclusive-or operations between the two registers. I'm assuming that 'setting a register' is done on the opposing edge of the exclusive-or operation. We can achieve a swap with the following microcode instructions. SWAP A, B A <- A XOR B CLK 1 B <- A XOR B CLK 2 A <- A XOR B CLK 3 For example, if we start off with the two registers A and B A = 3, B = 32 CLK 0 A = 35, B = 32 CLK 1 A = 35, B = 3 CLK 2 A = 32, B = 3 CLK 3 I hope - someone finds this helpful!

Sunday, 17 March 2019

Git Cheat Sheet

git init   # initialise directory for git repos
git status # tells user what possible files need to be 'added' or what files have changed.
git add . # add all files
git add filename1 filename2 # add numerous files to git 'staging area'
git log # show log of commits with their hash codes


git diff filename # to find out difference between working directory and last commit in staging directory
git checkout filename # to revert back a particular commit (last commit ) COMPARE THIS TO BRANCH CREATION

git checkout -b branchname #

git remote add origin https://github.com/johnny/myproject.git
#git remote add <REMOTE> GIT_URL
git remote -v # check settings

git push -u origin master
git push -u <REMOTE> <BRANCH>


git clone https://github.com/johnny/myproject.git 

Sunday, 10 March 2019

BootStrap Grid layout - Base 12 System


<div class='row'>
    <div class='col' style='background-color:red; border: 1px solid;'>
        col
    </div>
    
    <div class='col' style='background-color:red; border: 1px solid;'>
       col
    </div>
</div>

<div class='row'>
    <div class='col-6' style='background-color:green; border: 1px solid;'>
        col-6
    </div>
    <div class='col-3' style='background-color:green; border: 1px solid;'>
        col-4
    </div>
    <div class='col-2' style='background-color:green; border: 1px solid;'>
        col-2
    </div>
    <div class='col-1' style='background-color:green; border: 1px solid;'>
        col-1
    </div>
</div>

<div class='row'>
    <div class='col-6' style='background-color:blue; border: 1px solid;'>
        col-6
    </div>
    <div class='col-6' style='background-color:blue; border: 1px solid;'>
        col-6
    </div>
</div>

<div class='row'>
    <div class='col-md-6' style='background-color:yellow; border: 1px solid;'>
        col-md-6
    </div>
    <div class='col-md-6' style='background-color:yellow; border: 1px solid;'>
        col-md-6
    </div>
    
</div>


<div class='row'>

    <div class='col-lg-3 col-md-4 col-sm-6' style='background-color:pink; border: 1px solid;'>
        col-lg-3 col-md-4 col-sm-6
    </div>

    <div class='col-lg-3 col-md-4 col-sm-6' style='background-color:pink; border: 1px solid;'>
        col-lg-3 col-md-4 col-sm-6
    </div>

    <div class='col-lg-3 col-md-4 col-sm-6' style='background-color:pink; border: 1px solid;'>
        col-lg-3 col-md-4 col-sm-6
    </div>

    <div class='col-lg-3 col-md-4 col-sm-6' style='background-color:pink; border: 1px solid;'>
        col-lg-3 col-md-4 col-sm-6
    </div>

</div>

<div class='row'>
    
 <div class='col-lg-2 col-md-3 col-sm-12' style='background-color:blue; border: 1px solid;'>
        col-lg-3 col-md-4 col-sm-6
 </div>
 <div class='col-lg-2 col-md-3 col-sm-12' style='background-color:blue; border: 1px solid;'>
        col-lg-3 col-md-4 col-sm-6
 </div>
  <div class='col-lg-2 col-md-3 col-sm-12' style='background-color:blue; border: 1px solid;'>
        col-lg-3 col-md-4 col-sm-6
 </div>
  <div class='col-lg-2 col-md-3 col-sm-12' style='background-color:blue; border: 1px solid;'>
        col-lg-3 col-md-4 col-sm-6
 </div>
  <div class='col-lg-2 col-md-3 col-sm-12' style='background-color:blue; border: 1px solid;'>
        col-lg-3 col-md-4 col-sm-6
 </div>
  <div class='col-lg-2 col-md-3 col-sm-12' style='background-color:blue; border: 1px solid;'>
        col-lg-3 col-md-4 col-sm-6
 </div>
</div>

Thursday, 7 March 2019

CSS 'position' property

DOCTYPE html>
<html lang="en" dir="ltr">

  <head>
    <meta charset="utf-8">
    <title>Colour Block Alignment with absolute position</title>
    <script>
      var t = 0 ;
      var refresh = 24 ;
      var freq = 0.33 ;
      var radius = 80 ;
      var centre_x = 180 ;
      var centre_y = 180 ;

      function onLoad() {

        window.setInterval(function(){

          var el = document.getElementById('animate-block');
          el.style.backgroundColor = "green";

          var y = centre_y + radius * Math.sin(6.3 * freq * t) ;
          var x = centre_x + radius * Math.cos(6.3 * freq * t) ;

          el.style.top = y + 'px' ;
          el.style.left = x + 'px' ;

          t += (refresh/1000)
          console.log('t = ' + t) ;

        }, refresh);
      }

    </script>
  </head>

  <body onload="onLoad()">

    <div class='middle_container' style="background-color: purple; width:200px; height:300px;">
        middle container
    </div>

    <div class='colourblocktest' id='animate-block' style="z-index: -1; background-color: green; width:300px; height:300px; position: absolute; left: 60px; top: 37px; ">

      <div class='red' style="background-color: red; width:100px; height:100px; position: absolute; left: 200px; top: 200px">
      </div>

      <div class='blue' style="background-color: blue; width:100px; height:100px;position: absolute; left: 100px; top: 100px">
      </div>

      <div class='yellow' style="background-color: yellow; width:100px; height:100px;position: absolute; left: 0px; top: 0px">
      </div>

    </div>


  </body>
</html>

Monday, 4 March 2019

Crude Permutations


import java.util.*;


public class Dynamic {


public int calls = 0;

public int depth = 0;

public HashMap<String,HashSet<String> > cache = new HashMap<>();

public boolean cacheCheck = true;

public HashSet<String> preIndexList(String preIndexChr, HashSet<String> list) {

        // insert preindex char 'preIndexChr' to each element in list
        //System.out.printf("Pre Indexing with %s lst = %s",preIndexChr,list) ;
        HashSet<String> nList = new HashSet<>();
        for(String ele : list) {
                nList.add(preIndexChr + ele);
        }
        return nList;
}

// Depth

public HashSet<String> perm(String s,int dpth) {
        if (dpth > depth) {
                depth = dpth;
                //System.out.printf("Depth %d\n",depth) ;
        }
        if (cacheCheck && cache.containsKey(s)) {
                return cache.get(s);
        }

        calls++;


        HashSet<String> slst =  new HashSet<>();


        if (s.length() == 1) {

                slst.add(s);
                cache.put(s,slst);
                return slst;
        }

        for(int i = 0; i < s.length(); i++) {


                String left = s.substring(0,1);

                String right = s.substring(1);
                slst.addAll(preIndexList(left,perm(right,dpth++)));
                s = right + left;
        }
        cache.put(s,slst);
        return slst;

}


public String buildString(int size) {

        char [] ch = new char[size];
        for(int i = 0; i < size; i++) {
                ch[i] =  (char)(65 + i);
        }
        return new String(ch);
}
public static void main(String [] args) {
        for(int i = 1; i < 10; i++) {
                Dynamic d = new Dynamic();
                String s = d.buildString(i );
                HashSet<String> r = d.perm(s,0);
                //    System.out.printf("Perm of '%s' size = %d (built with %d calls)\nLIST %s\n",s,r.size(),d.calls,r) ;
                //System.out.printf("Size of HashMap %d\n",d.cache.size()) ;
                //System.out.printf("Perm of '%s' size = %d (built with %d calls)\n",s,r.size(),d.calls) ;
                // number of Calls can be expressed as recurance relation.
                // Kn = n * Kn-1 +  1
                System.out.printf("'%s' string size = %d list size = %d calls %d  depth %d\n",s,s.length(),r.size(),d.calls,d.depth);
                //System.out.printf("LIST %s",r) ;
        }
}

}


Friday, 1 March 2019

Docker Cheat List

# Swarm App Lifecycle

## Using Secrets With Local Docker Compose

docker node ls

docker-compose up -d

docker-compose exec psql cat /run/secrets/psql_user

docker-compose 11

pcat docker-compose.yml

## Full App Lifecycle: Dev, Build and Deploy With a Single Compose Design

docker-compose up -d

docker inspect TAB COMPLETION

docker-compose down

docker-compose -f docker-compose.yml -f docker-compose.test.yml up -d

docker inspect TAB COMPLETION

docker-compose -f docker-compose.yml -f docker-compose.prod.yml config --help

docker-compose -f docker-compose.yml -f docker-compose.prod.yml config

docker-compose -f docker-compose.yml -f docker-compose.prod.yml config > output.yml

## Service Updates: Changing Things In Flight

docker service create -p 8088:80 --name web nginx:1.13.7

docker service ls

docker service scale web=5

docker service update --image nginx:1.13.6 web

docker service update --publish-rm 8088 --publish-add 9090:80

docker service update --force web

## Healthchecks in Dockerfiles

docker container run --name p1 -d postgres

docker container ls

docker container run --name p2 -d --health-cmd="pg_isready -U postgres || exit 1" postgres

docker container ls

docker container inspect p2

docker service create --name p1 postgres

docker service create --name p2 --health-cmd="pg_isready -U postgres || exit 1" postgres

Thursday, 28 February 2019

Health Checking With Docker Stack

# Docker Swarm/Stack Compose file 'docker stack deploy <stackname> -c docker-stack-compose.yml
# docker swarm leave --force
# docker swarm init
# docker node update $(docker node inspect self --format '{{.ID}}') --label-add DrupalReady=true
# docker node inspect self --format '{{.Spec.Labels}}'

# docker secret rm postgres_password 
# echo 'SomeSecretPassword!' | docker secret create --label SOMELABEL=WHAT postgres_password -
# docker secret inspect postgres_password

#
#
#
# docker stack deploy drupalstack -c docker-stack-compose.yml 
#  docker stack ps $(docker stack ls --format '{{.Name}}') 
#

# Grab Info on all containers in our current stacks.
# docker container inspect $(docker stack ps --no-trunc $(docker stack ls --format '{{.Name}}') --format '{{.Name}}.{{.ID}}')

version: '3.1'
services:

# DRUPAL MAIN APP 
 drupal:
   image: drupal:8.2
   ports:
    - "8070:80"
   volumes:
     - webdata:/var/www/html

#   healthcheck:
#    test: ["CMD-SHELL", "curl -f http://127.0.0.1 || exit 1"]
#    interval: 20s
#    timeout: 10s
#    retries: 3
#    start-period: 10s
#    disable: true
    
   depends_on:
      - postgres
   deploy:
     replicas: 1
     placement:
        constraints: [node.labels.DrupalReady == true ]

# docker run -p 9009:9009 -v /var/run/docker.sock:/var/run/docker.sock moimhossain/viswar
# STACK VISUALISER
 viz:
  image: bretfisher/visualizer
  ports:
   - "8080:8080"
  volumes:
   - /var/run/docker.sock:/var/run/docker.sock
  deploy:
   placement:
    constraints: [node.role == manager]

# DB 
 postgres:
   image:
    postgres:9.6
   
   healthcheck:
    test: ["CMD-SHELL", "pg_isready -U postgres || exit 1"]
    interval: 30s
    timeout: 10s
    retries: 3
#   start-period: 10s

   secrets:
    - postgres_password

   environment:
    - POSTGRES_PASSWORD_FILE=/run/secrets/postgres_password
    - POSTGRES_USER=drupaluser
    - POSTGRES_DB=egdbase

   volumes:
       - postgresdata:/var/lib/postgresql/data

   deploy:
    restart_policy:
     condition: on-failure
     delay: 5s
     max_attempts: 3


volumes:
 postgresdata:
 webdata:
secrets:
 postgres_password:
  external: true

Docker Stack Script with 'Secrets'

Execute docker stack compose script with the commanddocker stack deploy <stackname> -c docker-stack-compose.yml


# Docker Swarm/Stack Compose file 'docker stack deploy <stackname> -c docker-stack-compose.yml
# docker swarm leave --force
# docker swarm init
# docker node update $(docker node inspect self --format '{{.ID}}') --label-add DrupalReady=true
# docker node inspect self --format '{{.Spec.Labels}}'

# docker secret rm postgres_password 
# echo 'SomeSecretPassword!' | docker secret create --label SOMELABEL=WHAT postgres_password -
# docker secret inspect postgres_password

#
#
#
# docker stack deploy drupalstack -c docker-stack-compose.yml 
#  docker stack ps $(docker stack ls --format '{{.Name}}') 
#

# Grab Info on all containers in our current stacks.
# docker container inspect $(docker stack ps --no-trunc $(docker stack ls --format '{{.Name}}') --format '{{.Name}}.{{.ID}}')

version: '3.1'
services:

# DRUPAL MAIN APP 
 drupal:
   image: drupal:8.2
   ports:
    - "8070:80"
   volumes:
     - webdata:/var/www/html
   depends_on:
      - postgres
   deploy:
     replicas: 1
     placement:
        constraints: [node.labels.DrupalReady == true ]

# docker run -p 9009:9009 -v /var/run/docker.sock:/var/run/docker.sock moimhossain/viswar
# STACK VISUALISER
 viz:
  image: bretfisher/visualizer
  ports:
   - "8080:8080"
  volumes:
   - /var/run/docker.sock:/var/run/docker.sock
  deploy:
   placement:
    constraints: [node.role == manager]

# DB 
 postgres:
   image:
    postgres:9.6

   secrets:
    - postgres_password

   environment:
    - POSTGRES_PASSWORD_FILE=/run/secrets/postgres_password
    - POSTGRES_USER=drupaluser
    - POSTGRES_DB=egdbase

   volumes:
       - postgresdata:/var/lib/postgresql/data

   deploy:
    restart_policy:
     condition: on-failure
     delay: 5s
     max_attempts: 3


volumes:
 postgresdata:
 webdata:
secrets:
 postgres_password:

  external: true

Wednesday, 27 February 2019

Installing a Docker Registry Cache on your Raspberry Pi



In this example - our local Raspberry Pi has the IP address 192.168.1.194

On your Pi – First install ‘Go version 1.8’ -

cd ~

tar -C /usr/local -xzf go1.8.linux-armv6l.tar.gz

export PATH=$PATH:/usr/local/go/bin

Now Clone, build and install the Docker Registry project

git clone https://github.com/docker/distribution.git

cd distribution

go get ./...


GOOS=linux GOARCH=arm make binaries

After making the binaries – you should issue the command

ls bin/

and you should see files: digest, registry, registryapidescriptortemplate


Before running the service you need to set up a config file to tell the registry service where to put images and to tell it to behave as a proxy for the main Docker repos images (nginx:latest, httpd:alpine etc) .

Create ~/distribution/bin/registry-config.yml and copy the following content into it:

version: 0.1
storage:
  cache:
    blobdescriptor: inmemory
  filesystem:
    rootdirectory: /var/lib/registry
http:
  addr: :5000
proxy:
 remoteurl: https://registry-1.docker.io


Create ~/distribution/bin/registry-config.yml and copy the following content into it:
Finally make a directory to store the images on your Pi

sudo mkdir p /var/lib/registry
sudo chown $USER /var/lib/registry


Finally start up your Registry Server.

cd ~/distribution/bin/
./registry serve ~/registryconfig.yml




On your Desktop/Laptop (Docker Client)



Under the Docker Preferences setup your PI server as a
‘Registry Mirror’




Apply and Restart your Docker Application



Testing


On your Docker client desktop/laptop – open up a browser and after making sure you’re on the same subnet as your Pi – go to the location
http://192.168.1.194:5000/v2


You should notice the empty ‘{ }’ JSON response on your browser.





If you have a shell open where your Pi is running the service – you’ll notice the response.




Now let’s pull some images from the main Docker Repo.

Using a terminal – on your Client machine (Desktop or Laptop)

Issue the following commands

docker image rm hello-world  

Don’t worry if you get an error on this command.

docker image pull hello-world


When the client starts to pull the image – you should notice DEBUG information on your Pi terminal – indicating that the image is being cached on its system.


After the ‘pull’ command has  been completed – issue another ‘rm command’

docker image rm hello-world  

And then another ‘pull’
docker image pull hello-world


On the Pi console – you will notice that the image is now being pulled from the local Pi directory rather than over the internet.


On your Docker Client machine (Desktop/Laptop) – issue the _catalog service on the browser (http://192.168.1.194:5000/v2/_catalog)

You should notice – a list of cached images stored on the Pi.

 


 Finally


On your Pi - you may want to bind mount /var/library/registry on a USB drive

sudo mount /dev/sda1 /var/lib/registry/ -o umask=000    

#sudo umount /var/lib/registry/