text:
#!/usr/bin/env node

function iobCalc(treatment, time, dia) {
    var diaratio = dia / 3;
    var peak = 75 * diaratio;
    //var sens = profile_data.sens;
    if (typeof time === 'undefined') {
        var time = new Date();
    }

    if (treatment.insulin) {
        var bolusTime=new Date(treatment.date);
        var minAgo=(time-bolusTime)/1000/60;

        if (minAgo < 0) {
            var iobContrib=0;
            var activityContrib=0;
        }
        if (minAgo < peak) {
            var x = (minAgo/5 + 1) * diaratio;
            var iobContrib=treatment.insulin*(1-0.001852*x*x+0.001852*x);
            //var activityContrib=sens*treatment.insulin*(2/dia/60/peak)*minAgo;
            var activityContrib=treatment.insulin*(2/dia/60/peak)*minAgo;

        }
        else if (minAgo < 180) {
            var x = (minAgo-peak)/5 * diaratio;
            var iobContrib=treatment.insulin*(0.001323*x*x - .054233*x + .55556);
            //var activityContrib=sens*treatment.insulin*(2/dia/60-(minAgo-peak)*2/dia/60/(60*dia-peak));
            var activityContrib=treatment.insulin*(2/dia/60-(minAgo-peak)*2/dia/60/(60*dia-peak));
        }
        else {
            var iobContrib=0;
            var activityContrib=0;
        }
        return {
            iobContrib: iobContrib,
            activityContrib: activityContrib
        };
    }
    else {
        return '';
    }
}
function iobTotal(treatments, time) {
    var iob = 0;
    var bolusiob = 0;
    var activity = 0;
    if (!treatments) return {};
    //if (typeof time === 'undefined') {
        //var time = new Date();
    //}

    treatments.forEach(function(treatment) {
        if(treatment.date < time.getTime( )) {
            var dia = profile_data.dia;
            var tIOB = iobCalc(treatment, time, dia);
            if (tIOB && tIOB.iobContrib) iob += tIOB.iobContrib;
            if (tIOB && tIOB.activityContrib) activity += tIOB.activityContrib;
            // keep track of bolus IOB separately for snoozes, but decay it three times as fast
            if (treatment.insulin >= 0.2 && treatment.started_at) {
                var bIOB = iobCalc(treatment, time, dia/3)
                //console.log(treatment);
                //console.log(bIOB);
                if (bIOB && bIOB.iobContrib) bolusiob += bIOB.iobContrib;
            }
        }
    });

    return {
        iob: iob,
        activity: activity,
        bolusiob: bolusiob
    };
}

function calcTempTreatments() {
    var tempHistory = [];
    var tempBoluses = [];
    var now = new Date();
    var timeZone = now.toString().match(/([-\+][0-9]+)\s/)[1]
    for (var i=0; i < pumpHistory.length; i++) {
        var current = pumpHistory[i];
        //if(pumpHistory[i].date < time) {
            if (pumpHistory[i]._type == "Bolus") {
                //console.log(pumpHistory[i]);
                var temp = {};
                temp.timestamp = current.timestamp;
                //temp.started_at = new Date(current.date);
                temp.started_at = new Date(current.timestamp + timeZone);
                //temp.date = current.date
                temp.date = temp.started_at.getTime();
                temp.insulin = current.amount
                tempBoluses.push(temp);
            } else if (pumpHistory[i]._type == "TempBasal") {
                if (current.temp == 'percent') {
                    continue;
                }
                var rate = pumpHistory[i].rate;
                var date = pumpHistory[i].date;
                if (i>0 && pumpHistory[i-1].date == date && pumpHistory[i-1]._type == "TempBasalDuration") {
                    var duration = pumpHistory[i-1]['duration (min)'];
                } else if (i+1<pumpHistory.length && pumpHistory[i+1].date == date && pumpHistory[i+1]._type == "TempBasalDuration") {
                    var duration = pumpHistory[i+1]['duration (min)'];
                } else { console.log("No duration found for "+rate+" U/hr basal"+date); }
                var temp = {};
                temp.rate = rate;
                //temp.date = date;
                temp.timestamp = current.timestamp;
                //temp.started_at = new Date(temp.date);
                temp.started_at = new Date(temp.timestamp + timeZone);
                temp.date = temp.started_at.getTime();
                temp.duration = duration;
                tempHistory.push(temp);
            }
        //}
    };
    for (var i=0; i+1 < tempHistory.length; i++) {
        if (tempHistory[i].date + tempHistory[i].duration*60*1000 > tempHistory[i+1].date) {
            tempHistory[i].duration = (tempHistory[i+1].date - tempHistory[i].date)/60/1000;
        }
    }
    var tempBolusSize;
    var now = new Date();
    var timeZone = now.toString().match(/([-\+][0-9]+)\s/)[1]
    for (var i=0; i < tempHistory.length; i++) {
        if (tempHistory[i].duration > 0) {
            var netBasalRate = tempHistory[i].rate-profile_data.current_basal;
            if (netBasalRate < 0) { tempBolusSize = -0.05; }
            else { tempBolusSize = 0.05; }
            var netBasalAmount = Math.round(netBasalRate*tempHistory[i].duration*10/6)/100
            var tempBolusCount = Math.round(netBasalAmount / tempBolusSize);
            var tempBolusSpacing = tempHistory[i].duration / tempBolusCount;
            for (var j=0; j < tempBolusCount; j++) {
                var tempBolus = {};
                tempBolus.insulin = tempBolusSize;
                tempBolus.date = tempHistory[i].date + j * tempBolusSpacing*60*1000;
                tempBolus.created_at = new Date(tempBolus.date);
                tempBoluses.push(tempBolus);
            }
        }
    }
    return [ ].concat(tempBoluses).concat(tempHistory);
    return {
        tempBoluses: tempBoluses,
        tempHistory: tempHistory
    };

}

if (!module.parent) {
    var iob_input = process.argv.slice(2, 3).pop()
    var profile_input = process.argv.slice(3, 4).pop()
    var clock_input = process.argv.slice(4, 5).pop()
  if (!iob_input || !profile_input) {
    console.log('usage: ', process.argv.slice(0, 2), '<pumphistory> <profile.json> <clock.json>');
    process.exit(1);
  }
    var cwd = process.cwd()
    var all_data = require(cwd + '/' + iob_input);
    var profile_data = require(cwd + '/' + profile_input);
    var clock_data = require(cwd + '/' + clock_input);
    var pumpHistory = all_data;
  pumpHistory.reverse( );

  var all_treatments =  calcTempTreatments( );
  //console.log(all_treatments);
  var treatments = all_treatments; // .tempBoluses.concat(all_treatments.tempHistory);
  treatments.sort(function (a, b) { return a.date > b.date });
  //var lastTimestamp = new Date(treatments[treatments.length -1].date + 1000 * 60);
  //console.log(clock_data);
  var now = new Date();
  var timeZone = now.toString().match(/([-\+][0-9]+)\s/)[1]
  var clock_iso = clock_data + timeZone;
  var clock = new Date(clock_iso);
  //console.log(clock);
  var iob = iobTotal(treatments, clock);
  //var iobs = iobTotal(treatments, lastTimestamp);
  // console.log(iobs);
  console.log(JSON.stringify(iob));
}


text:
<?php
namespace PhpTelzio;

use PhpTelzio\Entity\Call;

class LogResult
{

    protected $count;
    protected $totalCount;
    protected $offset;
    protected $calls;

    /**
     * @return mixed
     */
    public function getCount()
    {
        return $this->count;
    }

    /**
     * @param mixed $count
     */
    public function setCount($count)
    {
        $this->count = $count;
    }

    /**
     * @return mixed
     */
    public function getTotalCount()
    {
        return $this->totalCount;
    }

    /**
     * @param mixed $totalCount
     */
    public function setTotalCount($totalCount)
    {
        $this->totalCount = $totalCount;
    }

    /**
     * @return mixed
     */
    public function getOffset()
    {
        return $this->offset;
    }

    /**
     * @param mixed $offset
     */
    public function setOffset($offset)
    {
        $this->offset = $offset;
    }

    /**
     * @return mixed
     */
    public function getCalls()
    {
        return $this->calls;
    }

    /**
     * @param mixed $calls
     */
    public function setCalls($calls)
    {
        $this->calls = $calls;
    }

    public function addCall(Call $call)
    {
        $this->calls[] = $call;
    }

}

redpajama_set_name: RedPajamaGithub


text:
require 'spec_helper_acceptance'

describe 'ejabberd class' do

  context 'default parameters' do
    # Using puppet_apply as a helper
    it 'should work with no errors' do
      pp = <<-EOS
      class { 'ejabberd': }
      EOS

      # Run it twice and test for idempotency
      expect(apply_manifest(pp).exit_code).to_not eq(1)
      expect(apply_manifest(pp).exit_code).to eq(0)
    end

    describe package('ejabberd') do
      it { should be_installed }
    end

    describe service('ejabberd') do
      it { should be_enabled }
      it { should be_running }

      describe port(5222) do
        it { is_expected.to be_listening }
      end

    end

    describe user('ejabberd') do
       it { should exist }
    end

    describe file('/etc/ejabberd/ejabberd.cfg') do
      it { should contain 'localhost' }
    end
  end
end


text:
#pragma once

#include <iostream>
#include <opencv2/opencv.hpp>

#define MIN_Cr 113
#define MAX_Cr 173
#define MIN_Cb 77
#define MAX_Cb 127
#define MIN_Y 30

#define THRESHOLD_AREA 20
#define MAX_CONTOURS_SIZE 8
#define THRESHOLD_ANGLE 90
#define BLUR_KSIZE 5
//#define PI 3.14

namespace on_paper {
	using namespace cv;
	using namespace std;

	enum ColorSpaceType {
		C_YCrCb, C_YUV, C_HSV
	};

	typedef Vec<Point, 3> Vec3p;

	class HandDetector
	{

	public:
		HandDetector(int tar_width);

		void train(const Mat& img, const Mat& mask);
		void process(const Mat& src, Mat& des);
		Point get_fingertip();
		vector<Vec3p> get_defects();

	private:
		void init(int src_width);

		// two methods of hand mask
		void hand_mask(const Mat& src_std, Mat& dst);
		void hand_mask2(const Mat& src_std, Mat& dst);

		// detect and handle contours
		void hand_contours(const Mat& src, Mat& dst);
		void handle_contour(Mat& dst, const vector<Point> &contour);
		void draw_contour(Mat& dst, const vector<Point> &contour, const Scalar& color, int thickness = 1);
		int biggest_contour(vector<vector<Point> > &contours);

		// palm center and radius
		void detect_palm(const Mat& src_hand, const vector<Point>& contour);

		// tools
		void ori_correct(Mat& dst, const vector<Point> &contour);
		Point cvt_prop(Point p);

		// threshold for skin
		void threashold_C(const Mat& src, Mat& dst, int color_code);
		void threashold_YCrCb(const Mat& src, Mat& dst);
		void threashold_YUV(const Mat& src, Mat& dst);
		void threashold_Y(const Mat& src, Mat& dst);

		int _tar_width;		// 处理图像宽度
		Point _ctl_point;	// 指尖(最长手指)
		double _prop;		// 缩放比例

		vector<Vec3p> _defects;		// 凸缺陷
		Point _center;		// 掌心坐标
		int _r;				// 掌心半径
	};

}


text:
from ..encoding import wif_to_secret_exponent
from ..convention import tx_fee

from .Spendable import Spendable
from .Tx import Tx
from .TxOut import TxOut, standard_tx_out_script
from .pay_to import build_hash160_lookup

class SecretExponentMissing(Exception):
    pass

class LazySecretExponentDB(object):
    """
    The pycoin pure python implementation that converts secret exponents
    into public pairs is very slow, so this class does the conversion lazily
    and caches the results to optimize for the case of a large number
    of secret exponents.
    """
    def __init__(self, wif_iterable, secret_exponent_db_cache):
        self.wif_iterable = iter(wif_iterable)
        self.secret_exponent_db_cache = secret_exponent_db_cache

    def get(self, v):
        if v in self.secret_exponent_db_cache:
            return self.secret_exponent_db_cache[v]
        for wif in self.wif_iterable:
            secret_exponent = wif_to_secret_exponent(wif)
            d = build_hash160_lookup([secret_exponent])
            self.secret_exponent_db_cache.update(d)
            if v in self.secret_exponent_db_cache:
                return self.secret_exponent_db_cache[v]
        self.wif_iterable = []
        return None

def create_tx(spendables, payables, fee="standard", lock_time=0, version=1):
    """
    This function provides the easiest way to create an unsigned transaction.

    All coin values are in satoshis.

    spendables:
        a list of Spendable objects, which act as inputs. These can
        be either a Spendable or a Spendable.as_text or a Spendable.as_dict
        if you prefer a non-object-based input (which might be easier for
        airgapped transactions, for example).
    payables:
        a list where each entry is a bitcoin address, or a tuple of
        (bitcoin address, coin_value). If the coin_value is missing or
        zero, this address is thrown into the "split pool". Funds not
        explicitly claimed by the fee or a bitcoin address are shared as
        equally as possible among the split pool. [Minor point: if the
        amount to be split does not divide evenly, some of the earlier
        bitcoin addresses will get an extra satoshi.]
    fee:
        a value, or "standard" for it to be calculated.
    version:
        the version to use in the transaction. Normally 1.
    lock_time:
        the lock_time to use in the transaction. Normally 0.

    Returns the unsigned Tx transaction. Note that unspents are set, so the
    transaction can be immediately signed.

    Example:

    tx = create_tx(
        spendables_for_address("1BgGZ9tcN4rm9KBzDn7KprQz87SZ26SAMH"),
        ["1cMh228HTCiwS8ZsaakH8A8wze1JR5ZsP"],
        fee=0)

    This will move all available reported funds from 1BgGZ9tcN4rm9KBzDn7KprQz87SZ26SAMH
    to 1cMh228HTCiwS8ZsaakH8A8wze1JR5ZsP, with no transaction fees (which means it might
    take a while to confirm, possibly never).
    """

    def _fix_spendable(s):
        if isinstance(s, Spendable):
            return s
        if not hasattr(s, "keys"):
            return Spendable.from_text(s)
        return Spendable.from_dict(s)

    spendables = [_fix_spendable(s) for s in spendables]
    txs_in = [spendable.tx_in() for spendable in spendables]

    txs_out = []
    for payable in payables:
        if len(payable) == 2:
            bitcoin_address, coin_value = payable
        else:
            bitcoin_address = payable
            coin_value = 0
        script = standard_tx_out_script(bitcoin_address)
        txs_out.append(TxOut(coin_value, script))

    tx = Tx(version=version, txs_in=txs_in, txs_out=txs_out, lock_time=lock_time)
    tx.set_unspents(spendables)

    distribute_from_split_pool(tx, fee)
    return tx

def distribute_from_split_pool(tx, fee):
    """
    This function looks at TxOut items of a transaction tx and
    and puts TxOut items with a coin value of zero into a "split pool".
    Funds not explicitly claimed by the fee or other TxOut items are
    shared as equally as possible among the split pool. If the amount
    to be split does not divide evenly, some of the earlier TxOut items
    will get an extra satoshi.
    tx:
        the transaction
    fee:
        the reserved fee set aside
    """

    # calculate fees
    if fee == 'standard':
        # TODO: improve this
        # 1: the tx is not fully built out, so it will actually be larger than implied at this point
        # 2: recommended_fee_for_tx gives estimates that are too high
        fee = tx_fee.recommended_fee_for_tx(tx)

    zero_count = sum(1 for tx_out in tx.txs_out if tx_out.coin_value == 0)
    if zero_count > 0:
        total_coin_value = sum(spendable.coin_value for spendable in tx.txs_in_as_spendable())
        coins_allocated = sum(tx_out.coin_value for tx_out in tx.txs_out) + fee
        remaining_coins = total_coin_value - coins_allocated
        if remaining_coins < 0:
            raise ValueError("insufficient inputs for outputs")
        value_each, extra_count = divmod(remaining_coins, zero_count)
        if value_each < 1:
            raise ValueError("not enough to pay nonzero amounts to at least one of the unspecified outputs")
        for tx_out in tx.txs_out:
            if tx_out.coin_value == 0:
                tx_out.coin_value = value_each + (1 if extra_count > 0 else 0)
                extra_count -= 1
    return zero_count

def sign_tx(tx, wifs=[], secret_exponent_db={}):
    """
    This function provides an convenience method to sign a transaction.

    The transaction must have "unspents" set by, for example,
    calling tx.unspents_from_db.

    wifs:
        the list of WIFs required to sign this transaction.
    secret_exponent_db:
        an optional dictionary (or any object with a .get method) that contains
        a bitcoin address => (secret_exponent, public_pair, is_compressed)
        tuple. This will be built automatically lazily with the list of WIFs.
        You can pass in an empty dictionary and as WIFs are processed, they
        will be cached here. If you have multiple transactions to sign, each with
        the same WIF list, passing a cache dictionary in may speed things up a bit.

    Returns the signed Tx transaction, or raises an exception.

    At least one of "wifs" and "secret_exponent_db" must be included for there
    to be any hope of signing the transaction.

    Example:

    sign_tx(wifs=["KwDiBf89QgGbjEhKnhXJuH7LrciVrZi3qYjgd9M7rFU73sVHnoWn"])
    """
    tx.sign(LazySecretExponentDB(wifs, secret_exponent_db))

def create_signed_tx(spendables, payables, wifs=[], fee="standard",
                     lock_time=0, version=1, secret_exponent_db={}):
    """
    This function provides an easy way to create and sign a transaction.

    All coin values are in satoshis.

    spendables, payables, fee, lock_time, version are as in create_tx, above.
    wifs, secret_exponent_db are as in sign_tx, above.

    Returns the signed Tx transaction, or raises an exception.

    At least one of "wifs" and "secret_exponent_db" must be included for there
    to be any hope of signing the transaction.

    Example:

    tx = create_signed_tx(
        spendables_for_address("1BgGZ9tcN4rm9KBzDn7KprQz87SZ26SAMH"),
        ["1cMh228HTCiwS8ZsaakH8A8wze1JR5ZsP"],
        wifs=["KwDiBf89QgGbjEhKnhXJuH7LrciVrZi3qYjgd9M7rFU73sVHnoWn"],
        fee=0)

    This will move all available reported funds from 1BgGZ9tcN4rm9KBzDn7KprQz87SZ26SAMH
    to 1cMh228HTCiwS8ZsaakH8A8wze1JR5ZsP, with no transaction fees (which means it might
    take a while to confirm, possibly never).
    """

    tx = create_tx(spendables, payables, fee=fee, lock_time=lock_time, version=version)
    sign_tx(tx, wifs=wifs, secret_exponent_db=secret_exponent_db)
    for idx, tx_out in enumerate(tx.txs_in):
        if not tx.is_signature_ok(idx):
            raise SecretExponentMissing("failed to sign spendable for %s" %
                                        tx.unspents[idx].bitcoin_address())
    return tx


text:
(function(global){if(!String.prototype.contains) String.prototype.contains=function(str){return this.indexOf(str)!==-1};
if(!String.prototype.startsWith) String.prototype.startsWith=function(str,pos){return this.indexOf(str,pos)===0};
if(!String.prototype.endsWith) String.prototype.endsWith=function(str,pos){ var d=this.length-str.length; return d >= 0 && this.indexOf(str,d)===d; };

if (!String.prototype.trimLeft || !String.prototype.trimRight){
	var ws = "[" + "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003" +
	"\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028" +
	"\u2029\uFEFF"+ "]";
	var trimBeginRegexp = new RegExp("^" + ws + ws + "*"), trimEndRegexp = new RegExp(ws + ws + "*$");
	String.prototype.trimLeft = function(){ return String(this).replace(trimBeginRegexp, ""); };
	String.prototype.trimRight = function(){ return String(this).replace(trimEndRegexp, ""); };
}

if(!String.prototype.repeat) String.prototype.repeat=function(count){
	//return new Array(count + 1).join(this)
	if(count < 1) return '';
	/* Growing pattern : http://jsfiddle.net/disfated/GejWV/ */
	var result = '',pattern=this.valueOf();
	while(count > 0){
		if (count & 1) result += pattern;
		count >>= 1, pattern += pattern;
	}
	return result;
};

/* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String */
// Assumes all supplied String instance methods already present (one may use shims for these if not available)
(function () {
    'use strict';

    var i,
        // We could also build the array of methods with the following, but the
        //   getOwnPropertyNames() method is non-shimable:
        // Object.getOwnPropertyNames(String).filter(function (methodName) {return typeof String[methodName] === 'function'});
        methods = [
            /*'quote', */'substring', 'toLowerCase', 'toUpperCase', 'charAt',
            'charCodeAt', 'indexOf', 'lastIndexOf', 'startsWith', 'endsWith',
            'trim', 'trimLeft', 'trimRight', 'toLocaleLowerCase',
            'toLocaleUpperCase', 'localeCompare', 'match', 'search',
            'replace', 'split', 'substr', 'concat', 'slice', 'fromCharCode'
        ],
        methodCount = methods.length,
        assignStringGeneric = function (methodName) {
            var method = String.prototype[methodName];

            String[methodName] = function (arg1) {

                return method.apply(arg1, Array.prototype.slice.call(arguments, 1));
            };
        };

    for (i = 0; i < methodCount; i++) {
        assignStringGeneric(methods[i]);
    }
}());
/* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Array_generic_methods */
if(!Array.forEach)
	(function () {
		'use strict';

		var i,
			// We could also build the array of methods with the following, but the
			//   getOwnPropertyNames() method is non-shimable:
			// Object.getOwnPropertyNames(Array).filter(function (methodName) {return typeof Array[methodName] === 'function'});
			methods = [
				'join', 'reverse', 'sort', 'push', 'pop', 'shift', 'unshift',
				'splice', 'concat', 'slice', 'indexOf', 'lastIndexOf',
				'forEach', 'map', 'reduce', 'reduceRight', 'filter',
				'some', 'every'
			],
			methodCount = methods.length,
			assignArrayGeneric = function (methodName) {
				var method = Array.prototype[methodName];
				Array[methodName] = function (arg1) {
					return method.apply(arg1, UArray.slice1(arguments));
				};
			};

		for (i = 0; i < methodCount; i++) {
			assignArrayGeneric(methods[i]);
		}
	}());
/* https://github.com/WebReflection/es6-collections */
/* https://raw.github.com/eriwen/es6-map-shim/master/es6-map-shim.js */

/* chrome pre-implementation is lacking of the iterator method. Must be activated in prefs (like node --harmony) so most users won't have any implementation '*/
if(global.Map && (!global.Map.prototype.iterator || !global.Map.prototype.clear)) global.Map=null;

global.Map = global.Map || (function(){

	var Map=function(iterator){
		this.items = {}; this.size = 0;
		if(iterator) iterator.forEach(function(kv){
			this.items[kv[0]] = kv[1];
		}.bind(this));
	};
	Object.defineProperties(Map.prototype,{
		set:{ value:function(k,v){
			if(!this.items.hasOwnProperty(k))
				this.size++;
			this.items[k]=v;
		} },
		get:{ value:function(k){
			return this.items[k];
		} },
		has:{ value:function(k){
			return this.items.hasOwnProperty(k);
		} },
		'delete':{ value:function(k){
			if(this.items.hasOwnProperty(k)){
				this.size--;
				delete this.items[k];
			}
		} },
		clear:{ value:function(){
			this.size = 0;
			this.items = {};
		} },
		iterator:{ value:function(){
			return UObj.iterator(this.items);
		} },
		/*
		forEach:{ value:function(callback){
			UObj.forEach(this.items,callback,this);
		} },*/
		toString:{ value: function() {
			return '[Object Map]';
		} }
	});
	return Map;
})();
/* firefox implementation is lacking of the forEach method*/
if(!Map.prototype.forEach)
	/**
	 * Given a callback function and optional context, invoke the callback on all
	 * entries in this Map.
	 *
	 * @param callbackFn {Function}
	 */
	Map.prototype.forEach=function(callbackfn){
		console.log('Map.prototype.forEach');
		/*var iter = this.iterator();
		while(true){
			var current;
			try{ current=iter.next(); }catch(err){ return; }
			callbackfn.call(this,current[0],current[1]);
		}*/
		var it=S.iterator(this);
		while(it.hasNext()){
			var next = it.next();
			callbackfn.call(this,next[1],next[0]);
		}
	};

/* chrome pre-implementation is lacking of the iterator method. Must be activated in prefs (like node --harmony) so most users won't have any implementation '*/
if(global.Set && (!global.Set.prototype.iterator || !global.Set.prototype.clear)) global.Set=null;

global.Set = global.Set || (function(){

	var Set=function(iterator){
		this.items = []; this.size = 0;
		if(iterator) iterator.forEach(function(v){
			this.items.push(v);
		}.bind(this));
	};
	Object.defineProperties(Set.prototype,{
		add:{ value:function(v){
			if(!this.has(v)){
				this.size++;
				this.items.push(v);
			}
		} },
		has:{ value:function(v){
			return UArray.has(this.items,v);
		} },
		'delete':{ value:function(v){
			var i=this.items.indexOf(v);
			if(i!==-1){
				this.size--;
				this.items = this.items.slice(i,1);
			}
		} },
		clear:{ value:function(){
			this.size = 0;
			this.items = [];
		} },
		iterator:{ value:function(){
			var it = UArray.iterator(this.items);
			return Object.freeze({
				hasNext:it.hasNext.bind(it),
				next:function(){
					return this.items[it.next()];
				}.bind(this)
			});
		} },
		forEach:{ value:function(callback){
			this.items.forEach.call(this.items,callback,this);
		} },
		toString:{ value: function() {
			return '[Object Set]';
		} }
	});
	return Set;
})();
/* firefox implementation is lacking of the forEach method*/
if(!Set.prototype.forEach)
	/**
	 * Given a callback function and optional context, invoke the callback on all
	 * entries in this Map.
	 *
	 * @param callbackFn {Function}
	 */
	Map.prototype.forEach=function(callbackfn){
		var it=S.iterator(this);
		while(it.hasNext())
			callbackfn.apply(this,it.next());
	};

/* loaded by :
 * https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent
 *  => Firefox < 11, Chrome < 15, IE, Opera < 11.6, Safari
 *
 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Array_generic_methods
 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/contains
 *  => Almost all except Firefox > 19
 *
 * -
 * http://kangax.github.com/es5-compat-table/es6/
 */

// document.head (HTML5)
if(!document.head) document.head = document.getElementsByTagName('head')[0];
// Iterators
window.StopIteration=window.StopIteration || {};

/*/new Event (ie10)
try{
	var e=new Event('__es6Event__');
}catch(err){
	window.Event=function(name){
		var event = document.createEvent('Event');
		event.initEvent(name, true, true);
		return event;
	}
}*/

/* DOM-shim : https://github.com/Raynos/DOM-shim/tree/master/src/all/interfaces */

var shim=function(name,shim){
	var constructor = window[name];
	if (!constructor)
		constructor = window[name] = shim.interface;
	delete shim.interface;
	var proto = constructor && constructor.prototype;
	if (shim.prototype) {
		proto = constructor.prototype = shim.prototype;
		delete shim.prototype;
	}

	console&&console.log("adding interface ", name);

	if (shim.hasOwnProperty("constructor")) {
		window[name] = constructor = shim.constructor;
		proto && (shim.constructor.prototype = proto);
		delete shim.constructor;
	}
};

shim('Event',{
	constructor: function(type, dict){
		var e = document.createEvent("Event");
		dict = dict || {};
		dict.bubbles = dict.bubbles || false;
		dict.catchable = dict.catchable || false;
		e.initEvent(type, dict.bubbles, dict.catchable);
		return e;
	}
});

shim('EventTarget',{
	interface: window.Node || window.Element
});

shim('CustomEvent',{
	interface: window.Event,
	constructor: function(type, dict){
		var e = document.createEvent("CustomEvent");
		dict = dict || {};
		dict.detail = dict.detail || null;
		dict.bubbles = dict.bubbles || false;
		dict.catchable = dict.catchable || false;
		if (e.initCustomEvent) {
			e.initCustomEvent(type, dict.bubbles, dict.catchable, dict.detail);
		} else {
			e.initEvent(type, dict.bubbles, dict.catchable);
			e.detail = dict.detail;
		}
		return e;
	}
});

})(window);


text:
import {ApiEdgeDefinition} from "../edge/ApiEdgeDefinition";
import {ApiEdgeAction} from "../edge/ApiEdgeAction";
import {Api} from "../Api";
import {ApiEdgeMethod} from "../edge/ApiEdgeMethod";
import {ApiEdgeRelation} from "../relations/ApiEdgeRelation";
import {ApiEdgeSchema} from "../edge/ApiEdgeSchema";
import {ApiEdgeQueryContext} from "../edge/ApiEdgeQueryContext";

export class LazyApiEdge implements ApiEdgeDefinition {
    private realEdge: ApiEdgeDefinition;
    private readonly resolver: () => Promise<ApiEdgeDefinition|undefined>;

    constructor(api: Api, name: string, plural: boolean, resolver: () => Promise<ApiEdgeDefinition|undefined>) {
        this.api = api;
        this.resolver = resolver;

        if(plural) {
            this.pluralName = name
        }
        else {
            this.name = name
        }
    }

    async resolve() {
        if(!this.realEdge) {
            const realEdge = await this.resolver();
            if (realEdge) {
                this.realEdge = realEdge;
                this.name = realEdge.name;
                this.pluralName = realEdge.pluralName;
                this.relations = realEdge.relations;
                this.methods = realEdge.methods;
                this.actions = realEdge.actions;
                return true
            }

            return false
        }

        return true
    }

    actions: ApiEdgeAction[] = [];
    methods: ApiEdgeMethod[] = [];
    relations: ApiEdgeRelation[] = [];

    get allowCreate() { return this.realEdge.allowCreate }
    set allowCreate(value: boolean) { this.realEdge.allowCreate = value }
    get allowExists() { return this.realEdge.allowExists }
    set allowExists(value: boolean) { this.realEdge.allowExists = value }
    get allowGet() { return this.realEdge.allowGet }
    set allowGet(value: boolean) { this.realEdge.allowGet = value }
    get allowList() { return this.realEdge.allowList }
    set allowList(value: boolean) { this.realEdge.allowList = value }
    get allowPatch() { return this.realEdge.allowPatch }
    set allowPatch(value: boolean) { this.realEdge.allowPatch = value }
    get allowRemove() { return this.realEdge.allowRemove }
    set allowRemove(value: boolean) { this.realEdge.allowRemove = value }
    get allowUpdate() { return this.realEdge.allowUpdate }
    set allowUpdate(value: boolean) { this.realEdge.allowUpdate = value }

    get idField() { return this.realEdge.idField }
    set idField(value: string) { this.realEdge.idField = value }

    get schema() { return this.realEdge.schema }
    set schema(value: ApiEdgeSchema) { this.realEdge.schema = value }

    api: Api;
    external = true;
    name: string;
    pluralName: string;

    createEntry = async (context: ApiEdgeQueryContext, entryFields: any) => {
        return this.realEdge.createEntry(context, entryFields)
    };

    exists = async (context: ApiEdgeQueryContext) => {
        return this.realEdge.exists(context)
    };

    getEntry = async (context: ApiEdgeQueryContext) => {
        return this.realEdge.getEntry(context)
    };

    listEntries = async (context: ApiEdgeQueryContext) => {
        return this.realEdge.listEntries(context)
    };

    patchEntry = async (context: ApiEdgeQueryContext, entryFields: any) => {
        return this.realEdge.patchEntry(context, entryFields)
    };

    relation = async (name: string) => {
        return this.realEdge.relation(name)
    };

    removeEntry = async (context: ApiEdgeQueryContext, entryFields: any) => {
        return this.realEdge.removeEntry(context, entryFields)
    };

    updateEntry = async (context: ApiEdgeQueryContext, entryFields: any) => {
        return this.realEdge.updateEntry(context, entryFields)
    };

    prepare = () => Promise.resolve();

    metadata = () => this.realEdge.metadata();

    get(key: string): any {
        this.realEdge.get(key)
    }

    set(key: string, value: any): any {
        this.realEdge.set(key, value)
    }
}


text:
___

Exercises from courses

* Run a Job
* Deploy a Pod
* Create the service
* Explore the Sandbox
* Deployments - Rollout
* Setting Container Environment Variables
* Scaling Practice
* Label ALL THE THINGS!
* Raise a DaemonSet
* Replication Controllers, Replica Sets, and Deployments
* Label a Node & Schedule a Pod
* Multiple Schedulers
* View The Logs
* Maintenance on Node 3!
* Cluster DNS & Service Discovery

## Run a Job

Applications that run to completion inside a pod are called "jobs."  This is useful for doing batch processing.

Most Kubernetes objects are created using yaml. Here is some sample yaml for a job which uses perl to calculate pi to 2000 digits and then stops.

```yaml
apiVersion: batch/v1
kind: Job
metadata:
  name: pi
spec:
  template:
    spec:
      containers:
      - name: pi
        image: perl
        command: ["perl",  "-Mbignum=bpi", "-wle", "print bpi(2000)"]
      restartPolicy: Never
  backoffLimit: 4
```

Create this yaml file on your master node and call it "pi-job.yaml". Run the job with the command:

```bash
kubectl create -f pi-job.yaml
```

1. Check the status of the job using the `kubectl describe jobs` command.
2. When the job is complete, view the results by using the `kubectl logs <JOB_NAME>` command on the appropriate pod.
3. Write yaml for a new job.  Use the image "busybox" and have it sleep for 10 seconds and then complete.  Run your job to be sure it works.

```yaml
apiVersion: batch/v1
kind: Job
metadata:
  name: sleep
spec:
  template:
    spec:
      containers:
      - name: sleep
        image: busybox
        command: ["sleep", "10"]
      restartPolicy: Never
  backoffLimit: 4
```
* Commands
```bash
kubectl create -f job-sleep.yml
kubectl describe jobs
kubectl get pods
kubectl get pods --show-all
kubectl logs sleep-wht9w
kubectl describe jobs
kubectl delete jobs sleep
```

## Deploy a Pod

Pods usually represent running applications in a Kubernetes cluster.  Here is an example of some yaml which defines a pod:

```yaml
apiVersion: v1
kind: Pod
metadata:
  name: alpine
  namespace: default
spec:
  containers:
  - name: alpine
    image: alpine
    command:
      - sleep
      - "3600"
    imagePullPolicy: IfNotPresent
  restartPolicy: Always

```
1. Looking at the yaml, describe what the pod will do.
2. Run the pod.
3. Delete the pod.

```bash
kubectl create -f pod-alpine.yaml
kubectl get pods
kubectl desccribe pods
```

4. Write yaml for a pod that runs the nginx image.
5. Run your yaml to ensure it functions as expected.

```yaml
apiVersion: v1
kind: Pod
metadata:
  name: nginx-pod
spec:
  containers:
    - name: nginx
      image: nginx
  restartPolicy: Always
```

```bash
kubectl create -f nginx-pod.yaml
kubectl get pods
```

Delete any user pods you created during this exercise.

```bash
kubectl delete -f pod-alpine.yaml
kubectl delete pod nginx-prod
kubectl delete pod/nginx-prod
```

## Create the service

* Setup

```yaml
apiVersion: v1
kind: Service
metadata:
  name: nginx-service
  labels:
    app: nginx-service
spec:
  ports:
    - port: 8000
      targetPort: 80
      protocol: TCP
  selector:
    app: nginx

```

```bash
kubectl create -f service-nginx.yaml
```

* Check

```bash
kubectl get services
kubectl describe service nginx-service
```

* Test

```bash
kubectl run busybox --generator=run-pod/v1 --image=busybox --restart=Never --tty -i
wget -qO- http://10.111.20.191:8000
```

## Explore the Sandbox

* **Description**

1. Examine the current status of your cluster. Are all the nodes ready? How do you know?
2. Are there any pods running on node 2 of your cluster? How can you tell?
3. Is the master node low on memory currently? How can you tell?
4. What pods are running in the kube-system namespace? What command did you use to find out?

* **Answers**

1. The command kubectl get nodes will give the current status of all nodes.
2. You can get this information in a variety of ways:
* kubectl describe node node-name
* kubectl get pods --all-namespaces -o wide will list all pods and which nodes they are currently running on.
3. kubectl describe node node-2-name will list DiskPressure and MemoryPressure statuses so you can see how it is doing.
4. kubectl get pods -n kube-system will provide the desired results.

## Deployments - Rollout

* **Description**

Here is some yaml for an nginx deployment:

```yaml
apiVersion: apps/v1beta2
kind: Deployment
metadata:
  name: nginx-deployment
spec:
  selector:
    matchLabels:
      app: nginx
  replicas: 2
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.7.9
        ports:
        - containerPort: 80
```

1. Create the deployment.
2. Which nodes are the pods running on. How can you tell?
3. Update the deployment to use the 1.8 version of the nginx container and roll it out.
4. Update the deployment to use the 1.9.1 version of the nginx container and roll it out.
5. Roll back the deployment to the 1.8 version of the container.
6. Remove the deployment

* **Answer**

1. Create the yaml file and name it something. I chose `nginx-deployment.yaml`. Create the deployment object by calling `kubectl create -f nginx-deployment.yaml`.
2. You can find this answer by doing a `kubectl describe deployment nginx-deployment`.
3. There are many ways to get this:
* `kubectl get pods -l app=nginx -o wide` gives you the results in one step and uses a label selector.
Or, you could:
* `kubectl describe deployment nginx-deployment` to get the pod information about the deployment and, using that,
`kubectl get pods name-of-pods -o wide`

4. There are many ways. Here are two:
* `kubectl set image deployment nginx-deployment nginx=nginx:1.8`. This will work just fine but is not the preferred method because now the yaml is inconsistent with what you've got running in the cluster. Anyone coming across your yaml will assume it's what is up and running and it isn't.
* Update the line in the yaml to the 1.8 version of the image, and apply the changes with `kubectl apply -f nginx-deployment.yaml`
5. Same as above. Don't forget you can watch the status of the rollout with the command `kubectl rollout status deployment nginx-deployment`.

6. `kubectl rollout undo deployment nginx-deployment` will undo the previous rollout, or if you want to go to a specific point in history, you can view the history with `kubectl rollout history deployment nginx-deployment` and roll back to a specific state with `kubectl rollout history deployment nginx-deployment --revision=x`.

## Setting Container Environment Variables

* **Description**

1. Write yaml for a job that will run the busybox image and will print out its environment variables and shut down.
2. Add the following environment variables to the pod definition:
```
STUDENT_NAME="Your Name"
SCHOOL="Linux Academy"
KUBERNETES="is awesome"
```
3. Run the job.
4. Verify that the environment variables were added.

* **Answer**

1. There are lots of possibilities, but here is what I came up with:

```yaml
apiVersion: v1
kind: Pod
metadata:
  name: env-dump
spec:
  containers:
  - name: busybox
    image: busybox
    command:
      - env
```
2. Change the yaml to something like this:

```yaml
apiVersion: v1
kind: Pod
metadata:
  name: env-dump
spec:
  containers:
  - name: busybox
    image: busybox
    command:
      - env
    env:
    - name: STUDENT_NAME
      value: "Your Name"
    - name: SCHOOL
      value: "Linux Academy"
    - name: KUBERNETES
      value: "is awesome"
```
3. kubectl create -f env-dump.yaml and wait for the pod to return the status of "Completed."
4. kubectl logs env-dump will show all the environment variables.

## Scaling Practice

* **Description**

Consider this YAML for an nginx deployment:

```yaml
apiVersion: apps/v1beta2
kind: Deployment
metadata:
  name: nginx-deployment
spec:
  selector:
    matchLabels:
      app: nginx
  replicas: 2
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx
        ports:
        - containerPort: 80
```

Complete and answer the following:

1. Scale the deployment up to 4 pods without editing the YAML.
1. Edit the YAML so that 3 pods are available and can apply the changes to the existing deployment.
1. Which of these methods do you think is preferred and why?

* **Answers**

To scale the deployment up to 4 pods, use: `kubectl scale deployment nginx-deployment --replicas=4`

To make it so 3 pods can be available and apply the changes to the existing deployment, complete the following:

1. Edit the YAML as follows:
```yaml
apiVersion: apps/v1beta2
kind: Deployment
metadata:
  name: nginx-deployment
spec:
  selector:
    matchLabels:
      app: nginx
  replicas: 3
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx
        ports:
        - containerPort: 80
```
2. Execute the command: `kubectl -f apply nginx-deployment `

Performing the edit in the YAML is the preferred one, as it keeps the YAML on disk in sync with the state of the cluster.

## Label ALL THE THINGS!

* **Description**

Putting labels on objects in Kubernetes allow you to identify and select objects in as wide or granular style as you like.

1. Label each of your nodes with a "color" tag. The master should be black; node 2 should be red; node 3 should be green and node 4 should be blue.
2. If you have pods already running in your cluster in the default namespace, label them with the key/value pair running=beforeLabels.
3. Create a new alpine deployment that sleeps for one minute and is then restarted from a yaml file that you write that labels these container with the key/value pair running=afterLabels.
4. List all running pods in the default namespace that have the key/value pair running=beforeLabels.
5. Label all pods in the default namespace with the key/value pair tier=linuxAcademyCloud.
6. List all pods in the default namespace with the key/value pair running=afterLabels and tier=linuxAcademyCloud.

* **Answers**

1.

* `kubectl label node node1-name color=black` for the master.
* `kubectl label node node2-name color=red` for node 2.
* `kubectl label node node3-name color=green` for node 3.
* `kubectl label node node4-name color=blue` for node 4.

2. `kubectl label pods -n default running=beforeLabels --all`

3. create `alpine-label.yaml`:

```yaml
apiVersion: v1
kind: Pod
metadata:
  name: alpine
  namespace: default
  labels:
    running: afterLabels
spec:
  containers:
  - name: alpine
    image: alpine
    command:
      - sleep
      - "60"
  restartPolicy: Always
```

4. `kubectl get pods -l running=beforeLabels -n default`
5. `kubectl label pods --all -n default tier=linuxAcademyCloud`
6. `kubectl get pods -l running=afterLabels -l tier=linuxAcademyCloud`

## Raise a DaemonSet

* **Description**

No black magic is required, just a bit of yaml.

Write the yaml to deploy a DaemonSet (just use an nginx image) and then test it to be sure it gets deployed on each node.  Delete the pods when you've completed this exorcism.  Er... Exercise.

* **Answers**

There are lots of possible solutions to this exercise, but here is what I came up with:

```yaml
apiVersion: apps/v1
kind: DaemonSet
metadata:
  name: cthulu
  labels:
    daemon: "yup"
spec:
  selector:
    matchLabels:
      daemon: "pod"
  template:
    metadata:
      labels:
        daemon: pod
    spec:
      tolerations:
      - key: node-role.kubernetes.io/master
        effect: NoSchedule
      containers:
      - name: cthulu-jr
        image: nginx
```

## Label a Node & Schedule a Pod

* **Description**

1. Pretend that node 3 is your favorite node.  Maybe it's got all SSDs.  Maybe it's got a fast network or a GPU.  Or maybe it sent you a nice tweet.  Label this node in some way so that you can schedule a pod to it.
2. Create a yaml for a busybox sleeper/restarter that will get scheduled to your favorite node from #1.

* **Answers**

There are many possible answers to this exercise, here is what I came up with:

1. To mark my favorite node, I used `kubectl label node node3-name myDarling=bestOne`.
2. For my pod to be launched on my favorite node, I used this yaml:

```yaml
apiVersion: v1
kind: Pod
metadata:
  name: busybox
  namespace: default
spec:
  containers:
  - name: busybox
    image: busybox
    command:
      - sleep
      - "300"
    imagePullPolicy: IfNotPresent
  restartPolicy: Always
  nodeSelector:
    myDarling: bestOne

```

## Multiple Schedulers

* **Description**

Pods generally are scheduled by the default scheduler, and their yaml might look like this:

```yaml
apiVersion: v1
kind: Pod
metadata:
  name: annotation-default-scheduler
  labels:
    name: multischeduler
spec:
  schedulerName: default-scheduler
  containers:
  - name: pod-container
    image: k8s.gcr.io/pause:2.0
```

Ordinarily, we don't need to specify the scheduler's name in the spec because everyone uses a single default one. Sometimes, however, developers need to have custom schedulers in charge of placing pods due to legacy or specialized hardware constraints.

Rewrite the yaml for this pod so it makes use of a scheduler called custom-scheduler, and annotate the pod accordingly.

* **Answers**

```yaml

apiVersion: v1
kind: Pod
metadata:
  name: annotation-default-scheduler
  labels:
    name: multischeduler
  annotations:
    scheduledBy: custom-scheduler
spec:
  schedulerName: custom-scheduler
  containers:
  - name: pod-container
    image: k8s.gcr.io/pause:2.0

```

## Replication Controllers, Replica Sets, and Deployments

* **Description**

Deployments replaced the older ReplicationController functionality, but it never hurts to know where you came from.  Deployments are easier to work with, and here's a brief exercise to show you how.

A Replication Controller ensures that a specified number of pod replicas are running at any one time. In other words, a Replication Controller makes sure that a pod or a homogeneous set of pods is always up and available.

1. **Write a YAML file that will create a Replication Controller that will maintain three copies of an nginx container.  Execute your YAML and make sure it works.**

> A Replica Set is a more advanced version of a Replication Controller that is used when more low-level control is needed.  While these are commonly managed with deployments in modern K8s, it's good to have experience with them.

2. **Write the YAML that will maintain three copies of an nginx container using a Replica Set.  Test it to be sure it works, then delete it.**

> A deployment is used to manage Replica Sets.

3. **Write the YAML for a deployment that will maintain three copies of an nginx container.  Test it to be sure it works, then delete it.**

* **Answers**

To create the replication controller, write the following YAML file:

Replication Controller:

```yaml
apiVersion: v1
kind: ReplicationController
metadata:
  name: nginx
spec:
  replicas: 3
  selector:
    app: nginx
  template:
    metadata:
      name: nginx
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx
        ports:
        - containerPort: 80
```

To maintain three copies of an nginx container in a replica set, write the following YAML file:

Replication Set:

```yaml
apiVersion: apps/v1beta2
kind: ReplicaSet
metadata:
  name: nginx
  labels:
    app: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx
        ports:
        - containerPort: 80
```

To perform a deployment for the Replica Set, write the following YAML file:

Deployment:

```yaml
apiVersion: apps/v1beta2 # for versions before 1.8.0 use apps/v1beta1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx
        ports:
        - containerPort: 80
```

## View The Logs

* **Description**

Create this object in your cluster:

```yaml
apiVersion: v1
kind: Pod
metadata:
  name: counter
  labels:
    demo: logger
spec:
  containers:
  - name: count
    image: busybox
    args: [/bin/sh, -c, 'i=0; while true; do echo "$i: $(date)"; i=$((i+1)); sleep 3; done']
```
This is a small container which wakes up every three seconds and logs the date and a count to stdout.

1. View the current logs of the counter.
2. Allow the container to run for a few minutes while viewing the log interactively.
3. Have the command only print the last 10 lines of the log.
4. Look at the logs for the scheduler. Have there been any problems lately that you can see?
5. Kubernetes uses etcd for its key-value store. Take a look at its logs and see if it has had any problems lately.
6. Kubernetes API server also runs as a pod in the cluster. Find and examine its logs.

* **Answers**

1. `kubectl logs counter`
2. `kubectl logs counter -f`
3. `kubectl logs counter --tail=10` or, since `--tail` defaults to 10, just `kubectl logs counter --tail`
4. This question really wants to know if you can find the logs for the scheduler. They're in the master in the `/var/log/containers` directory. There, a symlink has been create to the appropriate container's log file, and the symlink will have a name that begins with "kube-scheduler-" These logs belong to root, so you will have to sudo to view them.
5. The etcd logs are in the same directory as the logs for the previous question, only the name of the symlink begins with "etcd-", and also belongs to root.
6. The API server also lives in the same directory and begins with "kube-apiserver-", and also belongs to root.

## Maintenance on Node 3!

* **Description**

Node 3 (Hey, isn't that your favorite node?) needs to have some maintenance done on it. The ionic defibulizer needs a new multiverse battery and the guys in the data center are impatient to get started.

1. Prepare node 3 for maintenance by preventing the scheduler from putting new pods on to it and evicting any existing pods. Ignore the DaemonSets -- those pods are only providing services to other local pods and will come back up when the node comes back up.

2. When you think you've done everything correctly, go to the Cloud Servers page and shut node 3 down. Don't delete it! Just stop it. While it's down, we'll pretend that it's getting that new multiverse battery. While you wait for the cluster to stabilize, practice your yaml writing skills by creating yaml for a new deployment that will run six replicas of an image called k8s.gcr.io/pause:2.0. Name this deployment "lots-of-nothing".

3. Bring the "lots-of-nothing" deployment up on your currently 75% active cluster. Notice where the pods land.

4. Imagine you just got a text message from the server maintenance crew saying that the installation is complete. Go back to the Cloud Server tab and start Node 3 up again. Fiddle with your phone and send someone a text message if it helps with the realism.  Once Node 3 is back up and running and showing a "Ready" status, allow the scheduler to use it again.

5. Did any of your pods move to take advantage of the additional power?  You get 143 bonus points for this exercise if you know what an ionic defibulizer is.  Tweet the answer to me @OpenChad.  Use the hashtag #NoYouDontReallyGetPoints.

* **Answers**

1. `kubectl drain node3-name --ignore-daemonsets`

2. Again, there are lots of possible answers, but here's one that I wrote:

```yaml
apiVersion: apps/v1beta2
kind: Deployment
metadata:
  name: lots-of-nothing
spec:
  selector:
    matchLabels:
      timeToGet: schwifty
  replicas: 6
  template:
    metadata:
      labels:
        timeToGet: schwifty
    spec:
      containers:
      - name: pickle-rick
        image: k8s.gcr.io/pause:2.0
```

3. `kubectl create -f lots-of-nothing.yaml` will bring it up if you named the yaml the same way I did. If you set up your labels like I did, then the command to show you where all the pods wound up is `kubectl get pods -o wide -l timeToGet=schwifty`. My point here is beyond just being a little silly -- your labels can be whatever you want them to, so it makes a lot of sense to think through some conventions and standards with your colleagues and other users of your cluster, otherwise you will end up with nonsensical labels like mine.

4.`kubectl uncordon node3-name` will allow the scheduler to once again allow pods to be scheduled on the node.

5. No, the uncordon only affects pods being scheduled and won't move any back unless other nodes are experiencing MemoryPressure or DiskPressure.

## Cluster DNS & Service Discovery

* **Description**

In a Kubernetes cluster, services discover one another through the Cluster DNS.  Names of services resolve to their ClusterIP, allowing application developers to only know the name of the service deployed in the cluster and not have to figure out how to get all the right IP addresses into the right containers at deploy time.

Here is yaml for a deployment:
```yaml
apiVersion: apps/v1beta2
kind: Deployment
metadata:
  name: bit-of-nothing
spec:
  selector:
    matchLabels:
      app: pause
  replicas: 2
  template:
    metadata:
      labels:
        app: pause
    spec:
      containers:
      - name: bitty
        image: k8s.gcr.io/pause:2.0
```

Create this file and name it `bit-of-nothing.yaml`.

1. Run the deployment and verify that the pods have started.

2. Start a busybox pod you can use to check DNS resolution (you can use my yaml, below, if you like, but it's good practice to write your own!)

```yaml
apiVersion: v1
kind: Pod
metadata:
  name: busybox
  namespace: default
spec:
  containers:
  - name: busybox
    image: busybox
    command:
      - sleep
      - "3600"
    imagePullPolicy: IfNotPresent
  restartPolicy: Always
```

3. Check to see whether or not bit-of-nothing is currently being resolved in the cluster via your busybox container.
4. Expose the bit-of-nothing deployment as a ClusterIP service.
5. Verify that "bit-of-nothing" is now being resolved to an IP address in your cluster.

* **Answers**

1. `kubectl create -f bit-of-nothing.yaml` At this point, this command should be second nature to you, unless you're doing a lot of skipping around.
2. `kubectl create -f busybox.yaml`
3. `kubectl exec -it busybox -- nslookup bit-of-nothing` should error out with not found.
4. `kubectl expose deployment bit-of-nothing --type=ClusterIP --port 80`
5. `kubectl exec -it busybox -- nslookup bit-of-nothing` should return an IP address after a few moments.


text:
namespace Merchello.Core.Observation
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics.CodeAnalysis;
    using System.Linq;

    using Umbraco.Core.Logging;

    /// <summary>
    /// Defines an <see cref="TriggerBase{T}"/> base class
    /// </summary>
    /// <typeparam name="T">The type of the model used by the trigger</typeparam>
    public abstract class TriggerBase<T> : IObservableTrigger<T>
    {
        /// <summary>
        /// Gets the collection of <see cref="IObserver{T}"/>
        /// </summary>
        [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1306:FieldNamesMustBeginWithLowerCaseLetter", Justification = "Reviewed. Suppression is OK here."),
        SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Reviewed. Suppression is OK here.")]
        protected List<IObserver<T>> Observers = new List<IObserver<T>>();

        /// <summary>
        /// Gets a value indicating whether or not this trigger is being monitored
        /// </summary>
        public bool HasMonitors
        {
            get { return Observers.Any(); }
        }

        /// <summary>
        /// Gets the number of monitor observing this trigger
        /// </summary>
        public int MonitorCount
        {
            get { return Observers.Count; }
        }

        /// <summary>
        /// Subscribes an <see cref="IObserver{T}"/>
        /// </summary>
        /// <param name="observer">The monitor</param>
        /// <returns>The disposable</returns>
        public virtual IDisposable Subscribe(IObserver<T> observer)
        {
            if (!Observers.Contains(observer)) Observers.Add(observer);
            return GetUnsubscriber(observer);
        }

        /// <summary>
        /// Returns true/false indicating whether or not the model passed "Will Work" for this trigger
        /// </summary>
        /// <param name="model">
        /// An object representing the model to be passed to the various Monitors
        /// </param>
        /// <typeparam name="TModel">The type of the input model</typeparam>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        internal virtual bool WillWork<TModel>(object model)
        {
            var type = typeof(TModel);
            var isOfType = type.IsInstanceOfType(model);
            if (isOfType == false)
            {
                LogHelper.Info<TriggerBase<T>>("Found model of an unexpected type.");
            }

            return model == null || type.IsInstanceOfType(model); ////model.GetType().IsAssignableFrom(type);
        }

        /// <summary>
        /// The get unsubscriber.
        /// </summary>
        /// <param name="observer">
        /// The observer.
        /// </param>
        /// <returns>
        /// The <see cref="IDisposable"/>.
        /// </returns>
        protected IDisposable GetUnsubscriber(IObserver<T> observer)
        {
            return new Unsubscriber<T>(Observers, observer);
        }

        /// <summary>
        /// Notifiy all the monitors of the change
        /// </summary>
        /// <param name="monitorModel">The model/value to pass to each monitor</param>
        protected virtual void NotifyMonitors(T monitorModel)
        {
            foreach (var o in Observers)
            {
                try
                {
                    o.OnNext(monitorModel);
                }
                catch (Exception ex)
                {
                    o.OnError(ex);
                }
            }
        }
    }
}


text:
<?php
/* require the roadie as the parameter */
if(isset($_GET['roadid']) && strval($_GET['roadid'])) {

	/* soak in the passed variable or set our own */
	$roadid = strval($_GET['roadid']); //no default
        $format = isset($_GET['format']) ? strval($_GET['format']) : 'xml';

	/* connect to the db - add your own db info*/
	$link = mysql_connect('url','username','password') or die('Cannot connect to the DB');
	mysql_select_db('penndot_cameras',$link) or die('Cannot select the DB');

		$query = "SELECT * FROM cameras where cameras.road_id = '$roadid'";

	/* grab the cameras from the db */

	$result = mysql_query($query,$link) or die('Errant query:  '.$query);
	/* create one master array of the records */
	$cameras = array();
	if(mysql_num_rows($result)) {
		while($camera = mysql_fetch_assoc($result)) {
			$cameras[] = array('camera'=>$camera);
		}
	}

	/* output in necessary format */
	if($format == 'json') {
		header('Content-type: application/json');
		echo json_encode(array('cameras'=>$cameras));
	}
	else {
		header('Content-type: text/xml');
		echo '<cameras>';
		foreach($cameras as $index => $camera) {
			if(is_array($camera)) {
				foreach($camera as $key => $value) {
					echo '<',$key,'>';
					if(is_array($value)) {
						foreach($value as $tag => $val) {
							echo '<',$tag,'>',htmlentities($val),'</',$tag,'>';
						}
					}
					echo '</',$key,'>';
				}
			}
		}
		echo '</cameras>';
	}

	/* disconnect from the db */
	@mysql_close($link);
}
?>


text:
// This file is part of OpenTSDB.
// Copyright (C) 2013  The OpenTSDB Authors.
//
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 2.1 of the License, or (at your
// option) any later version.  This program is distributed in the hope that it
// will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser
// General Public License for more details.  You should have received a copy
// of the GNU Lesser General Public License along with this program.  If not,
// see <http://www.gnu.org/licenses/>.
package net.opentsdb.tsd;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import net.opentsdb.core.IncomingDataPoint;
import net.opentsdb.core.TSDB;
import net.opentsdb.stats.StatsCollector;
import net.opentsdb.utils.JSON;

import org.jboss.netty.channel.Channel;
import org.jboss.netty.handler.codec.http.HttpMethod;
import org.jboss.netty.handler.codec.http.HttpResponseStatus;

import com.stumbleupon.async.Deferred;

/**
 * Handles fetching statistics from all over the code, collating them in a
 * string buffer or list, and emitting them to the caller. Stats are collected
 * lazily, i.e. only when this method is called.
 * This class supports the 1.x style HTTP call as well as the 2.x style API
 * calls.
 * @since 2.0
 */
public final class StatsRpc implements TelnetRpc, HttpRpc {

  /**
   * Telnet RPC responder that returns the stats in ASCII style
   * @param tsdb The TSDB to use for fetching stats
   * @param chan The netty channel to respond on
   * @param cmd call parameters
   */
  public Deferred<Object> execute(final TSDB tsdb, final Channel chan,
      final String[] cmd) {
    final boolean canonical = tsdb.getConfig().getBoolean("tsd.stats.canonical");
    final StringBuilder buf = new StringBuilder(1024);
    final ASCIICollector collector = new ASCIICollector("tsd", buf, null);
    doCollectStats(tsdb, collector, canonical);
    chan.write(buf.toString());
    return Deferred.fromResult(null);
  }

  /**
   * HTTP resposne handler
   * @param tsdb The TSDB to which we belong
   * @param query The query to parse and respond to
   */
  public void execute(final TSDB tsdb, final HttpQuery query) {
    // only accept GET/POST
    if (query.method() != HttpMethod.GET && query.method() != HttpMethod.POST) {
      throw new BadRequestException(HttpResponseStatus.METHOD_NOT_ALLOWED,
          "Method not allowed", "The HTTP method [" + query.method().getName() +
          "] is not permitted for this endpoint");
    }

    final boolean canonical = tsdb.getConfig().getBoolean("tsd.stats.canonical");

    // if we don't have an API request we need to respond with the 1.x version
    if (query.apiVersion() < 1) {
      final boolean json = query.hasQueryStringParam("json");
      final StringBuilder buf = json ? null : new StringBuilder(2048);
      final ArrayList<String> stats = json ? new ArrayList<String>(64) : null;
      final ASCIICollector collector = new ASCIICollector("tsd", buf, stats);
      doCollectStats(tsdb, collector, canonical);
      if (json) {
        query.sendReply(JSON.serializeToBytes(stats));
      } else {
        query.sendReply(buf);
      }
      return;
    }

    // we have an API version, so go newschool
    final List<IncomingDataPoint> dps = new ArrayList<IncomingDataPoint>(64);
    final SerializerCollector collector = new SerializerCollector("tsd", dps,
        canonical);
    ConnectionManager.collectStats(collector);
    RpcHandler.collectStats(collector);
    tsdb.collectStats(collector);
    query.sendReply(query.serializer().formatStatsV1(dps));
  }

  /**
   * Helper to record the statistics for the current TSD
   * @param tsdb The TSDB to use for fetching stats
   * @param collector The collector class to call for emitting stats
   */
  private void doCollectStats(final TSDB tsdb, final StatsCollector collector,
      final boolean canonical) {
    collector.addHostTag(canonical);
    ConnectionManager.collectStats(collector);
    RpcHandler.collectStats(collector);
    tsdb.collectStats(collector);
  }

  /**
   * Implements the StatsCollector with ASCII style output. Builds a string
   * buffer response to send to the caller
   */
  final class ASCIICollector extends StatsCollector {

    final StringBuilder buf;
    final ArrayList<String> stats;

    /**
     * Default constructor
     * @param prefix The prefix to prepend to all statistics
     * @param buf The buffer to store responses in
     * @param stats An array of strings to write for the old style JSON output
     * May be null. If that's the case, we'll try to write to the {@code buf}
     */
    public ASCIICollector(final String prefix, final StringBuilder buf,
        final ArrayList<String> stats) {
      super(prefix);
      this.buf = buf;
      this.stats = stats;
    }

    /**
     * Called by the {@link #record} method after a source writes a statistic.
     */
    @Override
    public final void emit(final String line) {
      if (stats != null) {
        stats.add(line.substring(0, line.length() - 1));  // strip the '\n'
      } else {
        buf.append(line);
      }
    }
  }

  /**
   * Implements the StatsCollector with a list of IncomingDataPoint objects that
   * can be passed on to a serializer for output.
   */
  final class SerializerCollector extends StatsCollector {

    final boolean canonical;
    final List<IncomingDataPoint> dps;

    /**
     * Default constructor
     * @param prefix The prefix to prepend to all statistics
     * @param dps The array to store objects in
     */
    public SerializerCollector(final String prefix,
        final List<IncomingDataPoint> dps, final boolean canonical) {
      super(prefix);
      this.dps = dps;
      this.canonical = canonical;
    }

    /**
     * Override that records the stat to an IncomingDataPoint object and puts it
     * in the list
     * @param name Metric name
     * @param value The value to store
     * @param xtratag An optional extra tag in the format "tagk=tagv". Can only
     * have one extra tag
     */
    @Override
    public void record(final String name, final long value,
        final String xtratag) {

      final IncomingDataPoint dp = new IncomingDataPoint();
      dp.setMetric(prefix + "." + name);
      dp.setTimestamp(System.currentTimeMillis() / 1000L);
      dp.setValue(Long.toString(value));

      String tagk = "";
      if (xtratag != null) {
        if (xtratag.indexOf('=') != xtratag.lastIndexOf('=')) {
          throw new IllegalArgumentException("invalid xtratag: " + xtratag
              + " (multiple '=' signs), name=" + name + ", value=" + value);
        } else if (xtratag.indexOf('=') < 0) {
          throw new IllegalArgumentException("invalid xtratag: " + xtratag
              + " (missing '=' signs), name=" + name + ", value=" + value);
        }
        final String[] pair = xtratag.split("=");
        tagk = pair[0];
        addExtraTag(tagk, pair[1]);
      }

      addHostTag(canonical);

      final HashMap<String, String> tags =
        new HashMap<String, String>(extratags);
      dp.setTags(tags);
      dps.add(dp);

      if (!tagk.isEmpty()) {
        clearExtraTag(tagk);
      }
    }

  }
}


text:
using System;
using System.Runtime.InteropServices;

namespace WProject.GenericLibrary.WinApi
{
    public enum WindowShowStyle : uint
    {
        /// Hides the window and activates another window.
        /// <remarks>See SW_HIDE</remarks>
        Hide = 0,
        /// Activates and displays a window. If the window is minimized
        /// or maximized, the system restores it to its original size and
        /// position. An application should specify this flag when displaying
        /// the window for the first time.
        /// <remarks>See SW_SHOWNORMAL</remarks>
        ShowNormal = 1,
        /// Activates the window and displays it as a minimized window.
        /// <remarks>See SW_SHOWMINIMIZED</remarks>
        ShowMinimized = 2,
        /// Activates the window and displays it as a maximized window.
        /// <remarks>See SW_SHOWMAXIMIZED</remarks>
        ShowMaximized = 3,
        /// Maximizes the specified window.
        /// <remarks>See SW_MAXIMIZE</remarks>
        Maximize = 3,
        /// Displays a window in its most recent size and position.
        /// This value is similar to "ShowNormal", except the window is not
        /// actived.
        /// <remarks>See SW_SHOWNOACTIVATE</remarks>
        ShowNormalNoActivate = 4,
        /// Activates the window and displays it in its current size
        /// and position.
        /// <remarks>See SW_SHOW</remarks>
        Show = 5,
        /// Minimizes the specified window and activates the next
        /// top-level window in the Z order.
        /// <remarks>See SW_MINIMIZE</remarks>
        Minimize = 6,
        /// Displays the window as a minimized window. This value is
        /// similar to "ShowMinimized", except the window is not activated.
        /// <remarks>See SW_SHOWMINNOACTIVE</remarks>
        ShowMinNoActivate = 7,
        /// Displays the window in its current size and position. This
        /// value is similar to "Show", except the window is not activated.
        /// <remarks>See SW_SHOWNA</remarks>
        ShowNoActivate = 8,
        /// Activates and displays the window. If the window is
        /// minimized or maximized, the system restores it to its original size
        /// and position. An application should specify this flag when restoring
        /// a minimized window.
        /// <remarks>See SW_RESTORE</remarks>
        Restore = 9,
        /// Sets the show state based on the SW_ value specified in the
        /// STARTUPINFO structure passed to the CreateProcess function by the
        /// program that started the application.
        /// <remarks>See SW_SHOWDEFAULT</remarks>
        ShowDefault = 10,
        /// Windows 2000/XP: Minimizes a window, even if the thread
        /// that owns the window is hung. This flag should only be used when
        /// minimizing windows from a different thread.
        /// <remarks>See SW_FORCEMINIMIZE</remarks>
        ForceMinimized = 11
    }

    ///
    ///     Special window handles
    ///
    public enum SpecialWindowHandles
    {
        // ReSharper disable InconsistentNaming
        ///
        ///     Places the window at the top of the Z order.
        ///
        HWND_TOP = 0,
        ///
        ///     Places the window at the bottom of the Z order. If the hWnd parameter identifies a topmost window, the window loses its topmost status and is placed at the bottom of all other windows.
        ///
        HWND_BOTTOM = 1,
        ///
        ///     Places the window above all non-topmost windows. The window maintains its topmost position even when it is deactivated.
        ///
        HWND_TOPMOST = -1,
        ///
        ///     Places the window above all non-topmost windows (that is, behind all topmost windows). This flag has no effect if the window is already a non-topmost window.
        ///
        HWND_NOTOPMOST = -2
        // ReSharper restore InconsistentNaming
    }

    [Flags]
    public enum SetWindowPosFlags : uint
    {
        ///
        ///     If the calling thread and the thread that owns the window are attached to different input queues, the system posts the request to the thread that owns the window. This prevents the calling thread from blocking its execution while other threads process the request.
        ///
        SWP_ASYNCWINDOWPOS = 0x4000,

        ///
        ///     Prevents generation of the WM_SYNCPAINT message.
        ///
        SWP_DEFERERASE = 0x2000,

        ///
        ///     Draws a frame (defined in the window's class description) around the window.
        ///
        SWP_DRAWFRAME = 0x0020,

        ///
        ///     Applies new frame styles set using the SetWindowLong function. Sends a WM_NCCALCSIZE message to the window, even if the window's size is not being changed. If this flag is not specified, WM_NCCALCSIZE is sent only when the window's size is being changed.
        ///
        SWP_FRAMECHANGED = 0x0020,

        ///
        ///     Hides the window.
        ///
        SWP_HIDEWINDOW = 0x0080,

        ///
        ///     Does not activate the window. If this flag is not set, the window is activated and moved to the top of either the topmost or non-topmost group (depending on the setting of the hWndInsertAfter parameter).
        ///
        SWP_NOACTIVATE = 0x0010,

        ///
        ///     Discards the entire contents of the client area. If this flag is not specified, the valid contents of the client area are saved and copied back into the client area after the window is sized or repositioned.
        ///
        SWP_NOCOPYBITS = 0x0100,

        ///
        ///     Retains the current position (ignores X and Y parameters).
        ///
        SWP_NOMOVE = 0x0002,

        ///
        ///     Does not change the owner window's position in the Z order.
        ///
        SWP_NOOWNERZORDER = 0x0200,

        ///
        ///     Does not redraw changes. If this flag is set, no repainting of any kind occurs. This applies to the client area, the nonclient area (including the title bar and scroll bars), and any part of the parent window uncovered as a result of the window being moved. When this flag is set, the application must explicitly invalidate or redraw any parts of the window and parent window that need redrawing.
        ///
        SWP_NOREDRAW = 0x0008,

        ///
        ///     Same as the SWP_NOOWNERZORDER flag.
        ///
        SWP_NOREPOSITION = 0x0200,

        ///
        ///     Prevents the window from receiving the WM_WINDOWPOSCHANGING message.
        ///
        SWP_NOSENDCHANGING = 0x0400,

        ///
        ///     Retains the current size (ignores the cx and cy parameters).
        ///
        SWP_NOSIZE = 0x0001,

        ///
        ///     Retains the current Z order (ignores the hWndInsertAfter parameter).
        ///
        SWP_NOZORDER = 0x0004,

        ///
        ///     Displays the window.
        ///
        SWP_SHOWWINDOW = 0x0040
    }

    public enum ScrollBarDirection
    {
        SB_HORZ = 0x0,
        SB_VERT = 0x1,
        SB_CTL = 0x2,
        SB_BOTH = 0x3
    }

    public static class User32
    {
        ///
        ///
        ///
        /// <param name="hWnd">Window handle</param>
        /// <param name="hWndInsertAfter">Placement-order handle</param>
        /// <param name="X">Horizontal position</param>
        /// <param name="Y">Vertical position</param>
        /// <param name="cx">Width</param>
        /// <param name="cy">Height</param>
        /// <param name="uFlags">Window positioning flags</param>
        /// <returns></returns>
        [DllImport("user32.dll", EntryPoint = "SetWindowPos")]
        public static extern bool SetWindowPos(int hWnd, int hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);

        [DllImport("user32.dll")]
        public static extern bool ShowWindow(IntPtr hWnd, WindowShowStyle nCmdShow);

        [DllImport("user32.dll", SetLastError = true)]
        public static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);

        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);

        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern bool UnhookWindowsHookEx(int idHook);

        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern int CallNextHookEx(int idHook, int nCode, IntPtr wParam, IntPtr lParam);

        [DllImport("user32.dll", SetLastError = true)]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll", SetLastError = true)]
        public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, SetWindowPosFlags uFlags);

        [DllImport("user32.dll")]
        public static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool ShowScrollBar(IntPtr hWnd, int wBar, bool bShow);
    }
}


text:
<?php

namespace Concrete\Core\Support\CodingStyle;

use PhpCsFixer\Differ\DifferInterface;
use SebastianBergmann\Diff\Differ as SBDiffer;

class Differ implements DifferInterface
{
    /**
     * @var int
     */
    protected $maxTrailingUnchangedLines;

    /**
     * @var \SebastianBergmann\Diff\Differ
     */
    protected $differ;

    /**
     * Initialize the instance.
     *
     * @param int $maxTrailingUnchangedLines the maximum number of unchanged trailing lines to be kept
     */
    public function __construct($maxTrailingUnchangedLines = 3)
    {
        $this->maxTrailingUnchangedLines = max(0, (int) $maxTrailingUnchangedLines);
        $this->differ = new SBDiffer();
    }

    /**
     * {@inheritdoc}
     *
     * @see \PhpCsFixer\Differ\DifferInterface::diff()
     */
    public function diff($old, $new)
    {
        $diff = $this->differ->diff($old, $new);
        $lines = explode("\n", rtrim($diff, "\n"));
        $trailingUnchangedLines = $this->countTrailingUnchangedLines($lines);
        $trailingLinesToRemove = $trailingUnchangedLines - $this->maxTrailingUnchangedLines;
        if ($trailingLinesToRemove <= 0) {
            return $diff;
        }
        array_splice($lines, count($lines) - $trailingLinesToRemove);

        return implode("\n", $lines) . "\n";
    }

    /**
     * Count the number of unchanged trailing lines.
     *
     * @param string[] $lines
     *
     * @return string
     */
    protected function countTrailingUnchangedLines(array &$lines)
    {
        $count = 0;
        for ($index = count($lines) - 1; $index >= 0; --$index) {
            if ($lines[$index] === '' || $lines[$index][0] !== ' ') {
                break;
            }
            ++$count;
        }

        return $count;
    }
}


text:
package telephony;

public class SmartPhone implements Callable, Browsable{

	private String action;

	public SmartPhone(String action) {
		this.action = action;
	}

	@Override
	public String browsing() {
		return String.format("Browsing: %s!", this.action);
	}

	@Override
	public String calling() {
		return String.format("Calling... %s", this.action);
	}

}


text:
<?php
/**
 * Created by PhpStorm.
 * User: JSS
 * Date: 2016/9/2
 * Time: 17:06
 */

use App\Model\BaseArticle;

class IndexController extends BaseController{
    public function article() {
        $article = new BaseArticle();
        $article = $article::all();
        $result = array();
        foreach ($article as $value) {
            array_push($result, $value->getAttributes());
        }
        echo json_encode($result);
    }
}


text:
package edu.rice.seclab.dso;

import java.util.HashSet;

import com.google.common.base.CharMatcher;

public class WCharInterpreter implements IStringInterpreter {
	static public HashSet<Byte> BYTES = null;
	static public HashSet<Byte> WHITE_SPACE = null;

	static public final String ENCODING = "wchar";
	private static final Integer MAX_CHAR_SIZE = 1;
	private static final Integer MIN_CHAR_SIZE = 1;
	static int CHAR_SIZE = 2;
	static long min_len = 4;
	static long max_len = Integer.MAX_VALUE;
	private boolean myLiveUpdate;

	public String getEncoding() {
		return ENCODING;
	}

	public Long getLength(byte[] myBytes) {
		return getLength(myBytes, 0L, (long)myBytes.length);
	}

	public Long getLength(byte[] myBytes, Long pos, Long end) {
		long cnt = 0;
		for (; pos < end; pos += CHAR_SIZE) {
			if (isValidChar(myBytes, pos)){
				cnt++;
			} else {
				break;
			}
		}
		return cnt*CHAR_SIZE;
	}

	public Long getLength(byte[] myBytes, Long pos) {
		return getLength(myBytes, pos, (long) myBytes.length);
	}

	public String printableString(byte[] myBytes) {
		char [] chars = new char[myBytes.length/2];
		for (int pos = 0; pos < chars.length; pos++) {
			chars[pos] = (char) ((myBytes[pos*2] << 8) + (myBytes[pos*2+1] & 0xff));;
		}
		return new String(chars);
	}

	public String noWhiteSpaceString(byte[] myBytes) {
		return noWhiteSpaceString(myBytes, "_") ;
	}

	public String noWhiteSpaceString(byte[] myBytes, String replace) {
		return printableString(myBytes).replaceAll("\\s+",replace) ;
	}

	public String noNewLineString(byte[] myBytes) {
		return noNewLineString(myBytes, "--linebreak--");
	}
	public String noNewLineString(byte[] myBytes, String replace) {
		return printableString(myBytes).replace("\r", replace).replace("\n", replace);
	}

	public byte[] hashAs(byte[] myBytes, String hashAlgo) {
		// TODO Auto-generated method stub
		return null;
	}

	public String defaultHash(byte[] value) {
		// TODO Auto-generated method stub
		return null;
	}

	public Long createHash(byte[] myBytes) {
		// TODO Auto-generated method stub
		return 0L;
	}

	public Integer maxSize() {
		return MIN_CHAR_SIZE;
	}

	public Integer minSize() {
		return MAX_CHAR_SIZE;
	}

	public void setMaxLen(long v) {
		max_len = v;

	}

	public void setMinLen(long v) {
		min_len = v;
	}

	public void setLiveUpdate(boolean x) {
		myLiveUpdate = x;
	}

	public long getMaxLen() {
		return max_len*CHAR_SIZE;
	}

	public long getMinLen() {
		return min_len*CHAR_SIZE;
	}

	public boolean isValidChar(byte[] myBytes) {
		return isValidChar(myBytes, 0);
	}

	public boolean preByteCheck(byte[] myBytes, int pos) {
		return preByteCheck(myBytes[pos]) && pos+1 < myBytes.length;
	}
	public boolean isValidChar(byte b) {
		if (BYTES == null || WHITE_SPACE == null) {
			BYTES = new HashSet<Byte>();
			WHITE_SPACE = new HashSet<Byte>();
			WHITE_SPACE.add((byte) 0x9);
			WHITE_SPACE.add((byte) 0xa);
			WHITE_SPACE.add((byte) 0xd);
			WHITE_SPACE.add((byte) 32);
			BYTES.add((byte) 0x9);
			//BYTES.add((byte) 0xa);
			//BYTES.add((byte) 0xd);
			for (byte a = 32; a < 127; a++)
				BYTES.add(a);
		}
		return BYTES.contains(b);
	}

	private boolean preByteCheck(byte b) {
		return b == 0;
	}

	public boolean isWhiteSpace(byte[] mybytes) {
		return isWhiteSpace(mybytes, 0);
	}

	public boolean isWhiteSpace(byte[] myBytes, long pos) {
		return  preByteCheck(myBytes, (int) pos) && WHITE_SPACE.contains(myBytes[(int) pos]);
	}

	public Long getStringLength(byte[] myBytes) {
		return getStringLength(myBytes, 0L);
	}

	public Long getStringLength(byte[] myBytes, Long pos) {
		return getStringLength(myBytes, pos, (long) myBytes.length);
	}

	public Long getStringLength(byte[] myBytes, Long pos, Long end) {
		Long cnt = getLength(myBytes, pos, end);
		return cnt/CHAR_SIZE;
	}

	public boolean isValidChar(byte[] myBytes, long pos) {
		return preByteCheck(myBytes, (int) pos) && isValidChar(myBytes[(int) pos+1]);
	}

	public boolean doliveUpdate() {
		return myLiveUpdate;
	}

}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Syst. mycol. (Lundae) 3(1): 66 (1829)

#### Original name
Cenococcum geophilum Fr., 1829

### Remarks
null


text:
package org.chargecar.experiments.thermal;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class ParseDynamics {
    //static double[] temps = new double[]{30,31,32,33,34,35,36,37,38,39,40,41};
    static double[] powers = new double[51];;
    static double[] massFlows = new double[]{0,0.001,0.0015,0.002,0.0025,0.003,0.0035,0.0042};

    public static void main(String[] args) throws IOException {
   	if (args == null || args.length < 1) {
   	    System.err.println("ERROR: No GPX directory path provided.");
   	    System.exit(1);
   	}

   	double[] temps = new double[111];
   	for(int i = 0;i<111;i++){
   	    temps[i] = 30+i*0.1;
   	}

   	String csvMatlab = args[0];
	String dynOut = args[1];

	powers = new double[51];
	double pInit = -45078;
	double pDiff = 3563.6;
	for(int i = 0;i<51;i++){
	    if(i == 13){
		powers[i] = 0;
	    }
	    else if(i > 13){
		powers[i] = pInit + pDiff*(i-1);
	    }
	    else{
		powers[i] = pInit + pDiff*i;
	    }

	}

   	double[][][] dynamics = new double[temps.length][powers.length][massFlows.length];
	for(int i=0;i<temps.length;i++){
	    for(int j=0;j<powers.length;j++){
		for(int k=0;k<massFlows.length;k++){
		    dynamics[i][j][k] = -1;
		}
	    }
	}

	BufferedReader CSVFile =
	        new BufferedReader(new FileReader(csvMatlab));

	  String dataRow = CSVFile.readLine(); // Read first line.
	  // The while checks to see if the data is null. If
	  // it is, we've hit the end of the file. If not,
	  // process the data.

	  while (dataRow != null){
	   String[] dataArray = dataRow.split(",");
	   double temp = Double.parseDouble(dataArray[0]);
	   double power = Double.parseDouble(dataArray[1]);
	   double massFlow = Double.parseDouble(dataArray[2]);
	   double tFinal = Double.parseDouble(dataArray[3]);

	   int tIndex = -1;
	   for(int i=0;i<temps.length;i++){
	       if(Math.abs(temp - temps[i]) < 0.05){
		   tIndex = i;
	       }
	   }

	   int pIndex = -1;
	   for(int i=0;i<powers.length;i++){
	       if(Math.abs(power - powers[i]) < 100){
		   pIndex = i;
	       }
	   }

	   int mIndex = -1;
	   for(int i=0;i<massFlows.length;i++){
	       if(Math.abs(massFlow - massFlows[i]) < 0.0001){
		   mIndex = i;
	       }
	   }

	   dynamics[tIndex][pIndex][mIndex] = tFinal;

	   dataRow = CSVFile.readLine(); // Read next line of data.
	  }
	  // Close the file once all data has been read.
	  CSVFile.close();

	  File dynamicsFile = new File(dynOut);
	  dynamicsFile.getParentFile().mkdirs();
	  dynamicsFile.createNewFile();
	  FileOutputStream fos = new FileOutputStream(dynamicsFile);
	    ObjectOutputStream oos = new ObjectOutputStream(fos);
	    oos.writeObject(dynamics);
    }
}


text:
require 'sinatra'
class AirQualityApp < Sinatra::Base
  suggestions_list=["Conserve energy – remember to turn off lights, computers, and electric appliances when not in use.",
  "Use energy efficient light bulbs and appliances.",
  "Participate in your local utility's energy conservation programs.",
  "Limit driving by carpooling, using public transportation, biking and walking.",
  "Combine errands for fewer trips.",
  "Keep your automobile well tuned and maintained. Follow the manufacturer's instructions on routine maintenance, such as changing the oil and filters, and checking tire pressure and wheel alignment.",
  "Avoid excessive idling of your automobile.",
  "Use electric or hand-powered lawn care equipment.",
  "Be careful not to spill gasoline when filling up your car or gasoline powered lawn and garden equipment.",
  "Run dishwashers and clothes washers only when full.",
  "Choose environmentally friendly cleaners.",
  "Use water-based or solvent free paints whenever possible and buy products that say low VOC.",
  "Seal containers of household cleaners, workshop chemicals and solvents, and garden chemicals to prevent volatile organic compounds from evaporating into the air.",
  "Purchase and use low-polluting outboard marine engines and personal watercraft (4-stroke and direct fuel injection 2-stroke outboard marine engines).",
  "Advocate for emission reductions from power plants and more stringent national vehicle emission standards."]

    set :views, "views"
    set :public_folder, 'public'

    get '/' do
        co = params['co'].to_i
        no2 = params['no2'].to_i
        o3 = params['o3'].to_i
        ppm = params['ppm'].to_i

        results = ""

        co_val = co_level(co)

        results+= "CO Level is DANGEROUS.\n " if co_val == 1
        results+= "CO Level is UNSAFE.\n" if co_val == 0
        results+= "CO Level is SAFE.\n" if co_val == -1

        no2_val = no2_level(no2)
        results+= "NO2 Level is DANGEROUS. \n" if no2_val == 1
        results+= "NO2 Level is UNSAFE.\n" if no2_val == 0
        results+= "NO2 Level is SAFE.\n" if no2_val == -1

        o3_val = o3_level(o3)
        results+= "O3 Level is DANGEROUS.\n " if o3_val == 1
        results+= "O3 Level is UNSAFE.\n " if o3_val == 0
        results+= "O3 Level is SAFE.\n  " if o3_val == -1

        ppm_val = ppm_level(ppm)

        results+= "Particulate matter Level is DANGEROUS. \n" if ppm_val == 1

        results+= "Particulate matter Level is UNSAFE.\n " if ppm_val == 0

        results+= "Particulate matter Level is SAFE.\n" if ppm_val == -1

        results+=suggestions_list.sample

        return results

    end

    def co_level(co)
      return 1 if co >= 10
      return 0 if co < 10 and co > 6
      return -1 if co < 6
    end

    def no2_level(no2)
      return 1 if no2 >= 200
      return 0 if no2 < 200 and no2 > 140
      return -1 if no2 < 140
    end

    def o3_level(o3)
      return 1 if o3 >= 120
      return 0 if o3 < 120 and o3 > 72
      return -1 if o3 < 72
    end

    def ppm_level(ppm)
      return 1 if ppm >= 25
      return 0 if ppm < 25 and ppm > 16
      return -1 if ppm < 16
    end

end

AirQualityApp.run!


text:
<TITLE>Review for Turbo: A Power Rangers Movie (1997)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Turbo: A Power Rangers Movie (1997)

reviewed by
Scott Renshaw

                        TURBO: A POWER RANGERS MOVIE
                       A film review by Scott Renshaw
                        Copyright 1997 Scott Renshaw

(20th Century Fox)
Starring:  Jason David Frank, Adam Yong Bosch, Catherine Sutherland, Nakia
Burrise, Blake Foster, Hilary Shepard Turner, Amy Jo Johnson, Austin St.
John, Jon Simanton.
Screenplay:  Shuki Levy and Shell Danielson.
Producer:  Jonathan Tzachor.
Directors:  David Winning and Shuki Levy.
MPAA Rating:  PG (violence, mild profanity)
Running Time:  100 minutes.
Reviewed by Scott Renshaw.

     You've got to hand it to Saban Entertainment, keepers of the Power
Rangers franchise.  In the notoriously fickle business of children's
entertainment and merchandising, the Rangers have survived by changing
just enough to keep their young fans interested.  Costumes have been
updated; new iterations of action figures have filled the shelves.  Even
characters have been replaced in rejuvenating line-up changes, making the
Rangers akin to a super-powered Menudo.  Yet the most misguided changes to
date have been those in 1995's lifeless MIGHTY MORPHIN POWER RANGERS: THE
MOVIE, which substituted high-tech hardware for low-tech charm.  TURBO: A
POWER RANGERS MOVIE is still dopey kiddie fare, but it's an improvement
over MMPR:TM by orders of magnitude, with a couple more changes still up
its sleeve.

     The Power Rangers are, of course, a team of teen do-gooders from
Angel Grove, currently consisting of Tommy (Jason David Frank), Adam
(Johnny Yong Bosch), Catherine (Catherine Sutherland), Tanya (Nakia
Burrise) and Rocky (Steve Cardenas).  The film begins with a karate
practice during which Rocky is injured, leaving the Rangers short-handed
at a particularly inopportune time.  it seems that evil galactic pirate
Divatox (Hilary Shepard Turner) has a plan to unleash a demon and gain
untold riches, a plan requiring the magic of a benevolent gnome-like
wizard named Lerigot (Jon Simanton).  When Lerigot flees to earth,
Divatox pursues, and the Rangers take on the task of protecting Lerigot
and foiling Divatox's nefarious scheme.

    It can be a monumental effort for anyone over 12 to make it through
Power Rangers material, simply because it is so steadfastly simplistic.
The Rangers themselves are distinguishable from one another strictly by
their color-coded clothing, making the line-up changes as significant
Curly Joe replacing Joe in the Three Stooges.  Low-brow comic relief is
provided by the dim-witted Bulk and Skulk (Jason Narvy and Paul Schrier)
and the incessantly "Ay-yi-yi!"-ing robot side-kick Alpha, and the plots
are elemental fantasy tales with an "Afterschool Special" moral usually
tacked on somewhere.  TURBO adds to the mix a lovable little character
who can heal with a touch and can't survive long on earth...no, not E.T.,
but an incredible simulation in the Muppet-faced Lerigot.

     The formula is so unshakeable in its blandness that, within the
context of the Rangers universe, the twists TURBO serves up can only be
described as ingenious.  The smartest is the inclusion of 10-year-old
Justin (Blake Foster) filling the Blue Ranger costume of the incapacitated
Rocky.  When he morphs, Justin instantly becomes a buffed, battling
teenager who gets to drive a souped-up truck; it's such an obvious child's
fantasy that it's astonishing nobody thought of it sooner.  It's also nice
to have someone repeating the Rangers' morphing mantra of "Awesome!" who
doesn't sound like an immature nit-wit while doing it.  Another nice idea
brings back Ranger alumni Kimberly (Amy Jo Johnson) and Jason (Austin St.
James), who become prisoners of Divatox and eventually transform into evil
dopplegangers who battle their former teammates.  The appearance is good
for a gasp of recognition from long-time Ranger watchers, but it also
gives the characters a dose of personality they never had as heroes.

     Kimberly and Jason actually spend most of their screen time trying to
break out of the cargo hold of Divatox's ship, and those scenes are
surprisingly well-crafted and tense.  For an action film designed for
children, TURBO is actually rather restrained, with more emphasis on
suspenseful escapes than special effects-laden free-for-alls.  There are
only a couple of lengthy fight scenes, and the Rangers in their full
costumed glory are saved for the climactic battle.  Directors David
Winning and Shuki Levy are working with some pretty limp material, but
they make the most of it.  They also correct the fatal flaw of the first
POWER RANGERS feature by dumping the computer-generated Zords and making
the final Megazord-vs.-megademon battle what it always should be:  a
battle of two guys in big rubber suits.  TURBO is unquestionably more fun
for kids than for adults, but it is put together with some care, and it's
a step in the right direction.  Who knows...some day the ever-evolving
Rangers might morph into a movie franchise worth watching.

     On the Renshaw scale of 0 to 10 turbo props:  5.

                     Visit Scott Renshaw's MoviePage
                http://www-leland.stanford.edu/~srenshaw
             Subscribe to receive reviews directly via email
                       See details on the MoviePage

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews