<commit_before>var isLoggedIn = false;

// This is called with the results from from FB.getLoginStatus().

function statusChangeCallback(response) {
    console.log('statusChangeCallback');
    console.log(response);
    // The response object is returned with a status field that lets the
    // app know the current login status of the person.
    // Full docs on the response object can be found in the documentation
    // for FB.getLoginStatus().
    if (response.status === 'connected') {
        // Logged into your app and Facebook.
        loginUserIntoApplication();
        document.getElementById('login_btn').style = "display: none";
        document.getElementById('logout_btn').style = "display: block";
        if(somePlaceIsSelected){
            document.getElementById('actions').style = "visibility: visible";
        }
        isLoggedIn = true;

    } else if (response.status === 'not_authorized') {
        // The person is logged into Facebook, but not your app.
        document.getElementById('status').innerHTML = 'Přihlašte se do této aplikace.';
        document.getElementById('login_btn').style = "display: block";
        document.getElementById('logout_btn').style = "display: none";
        document.getElementById('actions').style = "visibility: hidden";
        isLoggedIn = false;

    } else {
        // The person is not logged into Facebook, so we're not sure if
        // they are logged into this app or not.
        document.getElementById('status').innerHTML = 'Přihlašte se pomocí Facebooku.';
        document.getElementById('login_btn').style = "display: block";
        document.getElementById('logout_btn').style = "display: none";
        document.getElementById('actions').style = "visibility: hidden";
        isLoggedIn = false;

    }
}

function subscribeToEvents() {
    FB.Event.subscribe('auth.logout', logout_event);
}

// This function is called when someone finishes with the Login
// Button.  See the onlogin handler attached to it in the sample
// code below.
function checkLoginState() {
    FB.getLoginStatus(function(response) {
        statusChangeCallback(response);
    });
}

window.fbAsyncInit = function() {
    FB.init({
        appId      : '177757152673157',
        cookie     : true,  // enable cookies to allow the server to access
                            // the session
        xfbml      : true,  // parse social plugins on this page
        version    : 'v2.5' // use graph api version 2.5
    });

    // Now that we've initialized the JavaScript SDK, we call
    // FB.getLoginStatus().  This function gets the state of the
    // person visiting this page and can return one of three states to
    // the callback you provide.  They can be:
    //
    // 1. Logged into your app ('connected')
    // 2. Logged into Facebook, but not your app ('not_authorized')
    // 3. Not logged into Facebook and can't tell if they are logged into
    //    your app or not.
    //
    // These three cases are handled in the callback function.

    FB.getLoginStatus(function(response) {
        statusChangeCallback(response);
    });

};

// Load the SDK asynchronously
(function(d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

function loginUserIntoApplication() {
    console.log('Welcome!  Fetching your information.... ');
    FB.api('/me',{ fields: 'name, email' }, function(response) {
        console.log('Successful login for: ' + response.name + " "+response.email);
        makeCorsRequest("GET", "https://ivebeenthereapi-matyapav.rhcloud.com/users", null, function (responseText) {
            var alreadyExists = false;
            if(responseText){
                var users = JSON.parse(responseText);
                for (id in users){
                    if(users[id].email == response.email){
                        alreadyExists = true;
                        break;
                    };
                }
            }
            if(!alreadyExists){
                var data = "name="+response.name+"&email="+response.email;
                makeCorsRequest("POST", "https://ivebeenthereapi-matyapav.rhcloud.com/users", data, function (responseText) {
                    console.log(responseText);
                })
            }
        });
        document.getElementById('status').innerHTML =
            'Přihlášen jako, ' + response.name + '!';
    });
}
function fblogin()
{

    FB.login(function (response) {
        if (response.authResponse) {
            checkLoginState();
        } else {
            console.log('User cancelled login or did not fully authorize.');
        }
    }, { scope: 'email' });

}

var logout_event = function(response) {
    console.log("logout_event");
    console.log(response.status);
    console.log(response);
    checkLoginState();
}

// Create the XHR object.
function createCORSRequest(method, url) {
    var xhr = new XMLHttpRequest();
    if ("withCredentials" in xhr) {
        // XHR for Chrome/Firefox/Opera/Safari.
        xhr.open(method, url, true);
    } else if (typeof XDomainRequest != "undefined") {
        // XDomainRequest for IE.
        xhr = new XDomainRequest();
        xhr.open(method, url);
    } else {
        // CORS not supported.
        xhr = null;
    }
    return xhr;
}

// Make the actual CORS request.
function makeCorsRequest(method, url, data, callback) {
    // This is a sample server that supports CORS.

    var xhr = createCORSRequest(method, url);
    if (!xhr) {
        alert('CORS not supported');
        return null;
    }

    // Response handlers.
    xhr.onload = function() {
        callback(xhr.responseText);
    };

    xhr.onerror = function() {
        alert('Woops, there was an error making the request.');
        return null;
    };
    if(data && method == "POST"){
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.send(data)
    }else{
        xhr.send();
    }

}<commit_msg>Test fetchnuti useru z meho API #9.2<commit_after>var isLoggedIn = false;

// This is called with the results from from FB.getLoginStatus().

function statusChangeCallback(response) {
    console.log('statusChangeCallback');
    console.log(response);
    // The response object is returned with a status field that lets the
    // app know the current login status of the person.
    // Full docs on the response object can be found in the documentation
    // for FB.getLoginStatus().
    if (response.status === 'connected') {
        // Logged into your app and Facebook.
        loginUserIntoApplication();
        document.getElementById('login_btn').style = "display: none";
        document.getElementById('logout_btn').style = "display: block";
        if(somePlaceIsSelected){
            document.getElementById('actions').style = "visibility: visible";
        }
        isLoggedIn = true;

    } else if (response.status === 'not_authorized') {
        // The person is logged into Facebook, but not your app.
        document.getElementById('status').innerHTML = 'Přihlašte se do této aplikace.';
        document.getElementById('login_btn').style = "display: block";
        document.getElementById('logout_btn').style = "display: none";
        document.getElementById('actions').style = "visibility: hidden";
        isLoggedIn = false;

    } else {
        // The person is not logged into Facebook, so we're not sure if
        // they are logged into this app or not.
        document.getElementById('status').innerHTML = 'Přihlašte se pomocí Facebooku.';
        document.getElementById('login_btn').style = "display: block";
        document.getElementById('logout_btn').style = "display: none";
        document.getElementById('actions').style = "visibility: hidden";
        isLoggedIn = false;

    }
}

function subscribeToEvents() {
    FB.Event.subscribe('auth.logout', logout_event);
}

// This function is called when someone finishes with the Login
// Button.  See the onlogin handler attached to it in the sample
// code below.
function checkLoginState() {
    FB.getLoginStatus(function(response) {
        statusChangeCallback(response);
    });
}

window.fbAsyncInit = function() {
    FB.init({
        appId      : '177757152673157',
        cookie     : true,  // enable cookies to allow the server to access
                            // the session
        xfbml      : true,  // parse social plugins on this page
        version    : 'v2.5' // use graph api version 2.5
    });

    // Now that we've initialized the JavaScript SDK, we call
    // FB.getLoginStatus().  This function gets the state of the
    // person visiting this page and can return one of three states to
    // the callback you provide.  They can be:
    //
    // 1. Logged into your app ('connected')
    // 2. Logged into Facebook, but not your app ('not_authorized')
    // 3. Not logged into Facebook and can't tell if they are logged into
    //    your app or not.
    //
    // These three cases are handled in the callback function.

    FB.getLoginStatus(function(response) {
        statusChangeCallback(response);
    });

};

// Load the SDK asynchronously
(function(d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

function loginUserIntoApplication() {
    console.log('Welcome!  Fetching your information.... ');
    FB.api('/me',{ fields: 'name, email' }, function(response) {
        console.log('Successful login for: ' + response.name + " "+response.email);
        makeCorsRequest("GET", "https://ivebeenthereapi-matyapav.rhcloud.com/users", null, function (responseText) {
            var alreadyExists = false;
            if(responseText){
                var users = JSON.parse(responseText);
                for (id in users){
                    if(users[id].email == response.email){
                        alreadyExists = true;
                        break;
                    };
                }
            }
            if(!alreadyExists){
                var data = "name="+response.name+"&email="+response.email;
                makeCorsRequest("POST", "https://ivebeenthereapi-matyapav.rhcloud.com/users", data, function (responseText) {
                    console.log(JSON.parse(responseText).message);
                })
            }
        });
        document.getElementById('status').innerHTML =
            'Přihlášen jako, ' + response.name + '!';
    });
}
function fblogin()
{

    FB.login(function (response) {
        if (response.authResponse) {
            checkLoginState();
        } else {
            console.log('User cancelled login or did not fully authorize.');
        }
    }, { scope: 'email' });

}

var logout_event = function(response) {
    console.log("logout_event");
    console.log(response.status);
    console.log(response);
    checkLoginState();
}

// Create the XHR object.
function createCORSRequest(method, url) {
    var xhr = new XMLHttpRequest();
    if ("withCredentials" in xhr) {
        // XHR for Chrome/Firefox/Opera/Safari.
        xhr.open(method, url, true);
    } else if (typeof XDomainRequest != "undefined") {
        // XDomainRequest for IE.
        xhr = new XDomainRequest();
        xhr.open(method, url);
    } else {
        // CORS not supported.
        xhr = null;
    }
    return xhr;
}

// Make the actual CORS request.
function makeCorsRequest(method, url, data, callback) {
    // This is a sample server that supports CORS.

    var xhr = createCORSRequest(method, url);
    if (!xhr) {
        alert('CORS not supported');
        return null;
    }

    // Response handlers.
    xhr.onload = function() {
        callback(xhr.responseText);
    };

    xhr.onerror = function() {
        alert('Woops, there was an error making the request.');
        return null;
    };
    if(data && method == "POST"){
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.send(data)
    }else{
        xhr.send();
    }

}<|endoftext|>


<commit_before>import Vue from './Vue'
import App from './App'
import About from './components/Aboutme'
import Profile from './components/Profile'
import Contact from './components/Contact'
import Products from './components/ProductList'
import NotFoundComponent from './NotFound'
import store from './store'
import VueRouter from 'vue-router'

const router = new VueRouter({
  mode: 'history',
  root: '/',
  routes: [
    {path: '/contact', component: Contact},
    {path: '/about', component: About},
    {path: '/profile/:username', component: Profile},
    {path: '/products', component: Products},
    {path: '/', redirect: '/about'},
    {path: '*', component: NotFoundComponent}
  ]
})

Vue.use(VueRouter)

/* eslint-disable no-new */
new Vue({
  el: '#app',
  store,
  render: h => h(App),
  router
})
<commit_msg>Update Component split lazy loading<commit_after>import Vue from './Vue'
import App from './App'
import store from './store'
import VueRouter from 'vue-router'

// Component split lazy loading
const About = resolve => {
  // require.ensure is Webpack's special syntax for a code-split point.
  require.ensure(['./components/Aboutme.vue'], () => {
    resolve(require('./components/Aboutme.vue'))
  })
}

const Profile = resolve => require(['./components/Profile.vue'], resolve)
const Contact = resolve => require(['./components/Contact.vue'], resolve)
const Products = resolve => require(['./components/ProductList.vue'], resolve)
const NotFound = resolve => require(['./NotFound.vue'], resolve)

const router = new VueRouter({
  mode: 'history',
  root: '/',
  routes: [
    {path: '/contact', component: Contact},
    {path: '/about', component: About},
    {path: '/profile/:username', component: Profile},
    {path: '/products', component: Products},
    {path: '/', redirect: '/about'},
    {path: '*', component: NotFound}
  ]
})

Vue.use(VueRouter)

/* eslint-disable no-new */
new Vue({
  el: '#app',
  store,
  render: h => h(App),
  router
})
<|endoftext|>


<commit_before>var base58 = require('./base58');
var Hash = require('./hash');
var Keypair = require('./keypair');
var Pubkey = require('./pubkey');
var Privkey = require('./privkey');
var Point = require('./point');
var Random = require('./random');
var bn = require('./bn');
var constants = require('./constants');

var BIP32 = function BIP32() {
  if (!(this instanceof BIP32))
    return new BIP32();
}

BIP32.prototype.fromRandom = function(networkstr) {
  if (!networkstr)
    networkstr = 'mainnet';
  this.version = constants[networkstr].bip32privkey;
  this.depth = 0x00;
  this.parentFingerprint = new Buffer([0, 0, 0, 0]);
  this.childIndex = new Buffer([0, 0, 0, 0]);
  this.chainCode = Random.getRandomBuffer(32);
  this.key = (new Keypair()).fromRandom();
  this.hasPrivateKey = true;
  this.pubKeyHash = Hash.sha256ripemd160(this.key.pubkey.toBuffer());
  this.buildExtendedPublicKey();
  this.buildExtendedPrivateKey();
};

BIP32.prototype.fromString = function(str) {
  var decoded = base58.decode(str);
  if (decoded.length != 82)
    throw new Error('Not enough data, expected 82 and received ' + decoded.length);
  var checksum = decoded.slice(78, 82);
  var bytes = decoded.slice(0, 78);

  var hash = Hash.sha256sha256(bytes);

  if (hash[0] != checksum[0] || hash[1] != checksum[1] || hash[2] != checksum[2] || hash[3] != checksum[3])
    throw new Error('Invalid checksum');

  if (bytes !== undefined && bytes !== null)
    this.initFromBytes(bytes);

  return this;
};

BIP32.prototype.fromSeed = function(bytes, networkstr) {
  if (!networkstr)
    networkstr = 'mainnet';

  if (!Buffer.isBuffer(bytes))
    throw new Error('bytes must be a buffer');
  if (bytes.length < 128 / 8)
    throw new Error('Need more than 128 bytes of entropy');
  if (bytes.length > 512 / 8)
    throw new Error('More than 512 bytes of entropy is nonstandard');
  var hash = Hash.sha512hmac(bytes, new Buffer('Bitcoin seed'));

  this.depth = 0x00;
  this.parentFingerprint = new Buffer([0, 0, 0, 0]);
  this.childIndex = new Buffer([0, 0, 0, 0]);
  this.chainCode = hash.slice(32, 64);
  this.version = constants[networkstr].bip32privkey;
  this.key = new Keypair();
  this.key.privkey = new Privkey({bn: bn.fromBuffer(hash.slice(0, 32))});
  this.key.privkey2pubkey();
  this.hasPrivateKey = true;
  this.pubKeyHash = Hash.sha256ripemd160(this.key.pubkey.toBuffer());

  this.buildExtendedPublicKey();
  this.buildExtendedPrivateKey();

  return this;
};

BIP32.prototype.initFromBytes = function(bytes) {
  // Both pub and private extended keys are 78 bytes
  if (bytes.length != 78)
    throw new Error('not enough data');

  this.version = u32(bytes.slice(0, 4));
  this.depth = u8(bytes.slice(4, 5));
  this.parentFingerprint = bytes.slice(5, 9);
  this.childIndex = u32(bytes.slice(9, 13));
  this.chainCode = bytes.slice(13, 45);

  var keyBytes = bytes.slice(45, 78);

  var isPrivate =
    (this.version == constants.mainnet.bip32privkey ||
      this.version == constants.testnet.bip32privkey);

  var isPublic =
    (this.version == constants.mainnet.bip32pubkey ||
      this.version == constants.testnet.bip32pubkey);

  if (isPrivate && keyBytes[0] == 0) {
    this.key = new Keypair();
    this.key.privkey = new Privkey({bn: bn.fromBuffer(keyBytes.slice(1, 33))});
    this.key.privkey2pubkey();
    this.pubKeyHash = Hash.sha256ripemd160(this.key.pubkey.toBuffer());
    this.hasPrivateKey = true;
  } else if (isPublic && (keyBytes[0] == 0x02 || keyBytes[0] == 0x03)) {
    this.key = new Keypair();
    this.key.pubkey = (new Pubkey()).fromDER(keyBytes);
    this.pubKeyHash = Hash.sha256ripemd160(this.key.pubkey.toBuffer());
    this.hasPrivateKey = false;
  } else {
    throw new Error('Invalid key');
  }

  this.buildExtendedPublicKey();
  this.buildExtendedPrivateKey();
}

BIP32.prototype.buildExtendedPublicKey = function() {
  this.extendedPublicKey = new Buffer([]);

  var v = null;
  switch (this.version) {
    case constants.mainnet.bip32pubkey:
    case constants.mainnet.bip32privkey:
      v = constants.mainnet.bip32pubkey;
      break;
    case constants.testnet.bip32pubkey:
    case constants.testnet.bip32privkey:
      v = constants.testnet.bip32pubkey;
      break;
    default:
      throw new Error('Unknown version');
  }

  // Version
  this.extendedPublicKey = Buffer.concat([
    new Buffer([v >> 24]),
    new Buffer([(v >> 16) & 0xff]),
    new Buffer([(v >> 8) & 0xff]),
    new Buffer([v & 0xff]),
    new Buffer([this.depth]),
    this.parentFingerprint,
    new Buffer([this.childIndex >>> 24]),
    new Buffer([(this.childIndex >>> 16) & 0xff]),
    new Buffer([(this.childIndex >>> 8) & 0xff]),
    new Buffer([this.childIndex & 0xff]),
    this.chainCode,
    this.key.pubkey.toBuffer()
  ]);
}

BIP32.prototype.extendedPublicKeyString = function(format) {
  if (format === undefined || format === 'base58') {
    var hash = Hash.sha256sha256(this.extendedPublicKey);
    var checksum = hash.slice(0, 4);
    var data = Buffer.concat([this.extendedPublicKey, checksum]);
    return base58.encode(data);
  } else if (format === 'hex') {
    return this.extendedPublicKey.toString('hex');;
  } else {
    throw new Error('bad format');
  }
}

BIP32.prototype.buildExtendedPrivateKey = function() {
  if (!this.hasPrivateKey) return;
  this.extendedPrivateKey = new Buffer([]);

  var v = this.version;

  this.extendedPrivateKey = Buffer.concat([
    new Buffer([v >> 24]),
    new Buffer([(v >> 16) & 0xff]),
    new Buffer([(v >> 8) & 0xff]),
    new Buffer([v & 0xff]),
    new Buffer([this.depth]),
    this.parentFingerprint,
    new Buffer([this.childIndex >>> 24]),
    new Buffer([(this.childIndex >>> 16) & 0xff]),
    new Buffer([(this.childIndex >>> 8) & 0xff]),
    new Buffer([this.childIndex & 0xff]),
    this.chainCode,
    new Buffer([0]),
    this.key.privkey.bn.toBuffer({size: 32})
  ]);
}

BIP32.prototype.extendedPrivateKeyString = function(format) {
  if (format === undefined || format === 'base58') {
    var hash = Hash.sha256sha256(this.extendedPrivateKey);
    var checksum = hash.slice(0, 4);
    var data = Buffer.concat([this.extendedPrivateKey, checksum]);
    return base58.encode(data);
  } else if (format === 'hex') {
    return this.extendedPrivateKey.toString('hex');
  } else {
    throw new Error('bad format');
  }
}

BIP32.prototype.derive = function(path) {
  var e = path.split('/');

  // Special cases:
  if (path == 'm' || path == 'M' || path == 'm\'' || path == 'M\'')
    return this;

  var bip32 = this;
  for (var i in e) {
    var c = e[i];

    if (i == 0) {
      if (c != 'm') throw new Error('invalid path');
      continue;
    }

    if (parseInt(c.replace("'", "")).toString() !== c.replace("'", ""))
      throw new Error('invalid path');

    var usePrivate = (c.length > 1) && (c[c.length - 1] == '\'');
    var childIndex = parseInt(usePrivate ? c.slice(0, c.length - 1) : c) & 0x7fffffff;

    if (usePrivate)
      childIndex += 0x80000000;

    bip32 = bip32.deriveChild(childIndex);
  }

  return bip32;
}

BIP32.prototype.deriveChild = function(i) {
  if (typeof i !== 'number')
    throw new Error('i must be a number');

  var ib = [];
  ib.push((i >> 24) & 0xff);
  ib.push((i >> 16) & 0xff);
  ib.push((i >> 8) & 0xff);
  ib.push(i & 0xff);
  ib = new Buffer(ib);

  var usePrivate = (i & 0x80000000) != 0;

  var isPrivate =
    (this.version == constants.mainnet.bip32privkey ||
      this.version == constants.testnet.bip32privkey);

  if (usePrivate && (!this.hasPrivateKey || !isPrivate))
    throw new Error('Cannot do private key derivation without private key');

  var ret = null;
  if (this.hasPrivateKey) {
    var data = null;

    if (usePrivate) {
      data = Buffer.concat([new Buffer([0]), this.key.privkey.bn.toBuffer({size: 32}), ib]);
    } else {
      data = Buffer.concat([this.key.pubkey.toBuffer({size: 32}), ib]);
    }

    var hash = Hash.sha512hmac(data, this.chainCode);
    var il = bn.fromBuffer(hash.slice(0, 32), {size: 32});
    var ir = hash.slice(32, 64);

    // ki = IL + kpar (mod n).
    var k = il.add(this.key.privkey.bn).mod(Point.getN());

    ret = new BIP32();
    ret.chainCode = ir;

    ret.key = new Keypair();
    ret.key.privkey = new Privkey({bn: k});
    ret.key.privkey2pubkey();
    ret.hasPrivateKey = true;

  } else {
    var data = Buffer.concat([this.key.pubkey.toBuffer(), ib]);
    var hash = Hash.sha512hmac(data, this.chainCode);
    var il = bn(hash.slice(0, 32));
    var ir = hash.slice(32, 64);

    // Ki = (IL + kpar)*G = IL*G + Kpar
    var ilG = Point.getG().mul(il);
    var Kpar = this.key.pubkey.point;
    var Ki = ilG.add(Kpar);
    var newpub = new Pubkey();
    newpub.point = Ki;

    ret = new BIP32();
    ret.chainCode = ir;

    var key = new Keypair();
    key.pubkey = newpub;
    ret.key = key;
    ret.hasPrivateKey = false;
  }

  ret.childIndex = i;
  ret.parentFingerprint = this.pubKeyHash.slice(0, 4);
  ret.version = this.version;
  ret.depth = this.depth + 1;

  ret.pubKeyHash = Hash.sha256ripemd160(ret.key.pubkey.toBuffer());

  ret.buildExtendedPublicKey();
  ret.buildExtendedPrivateKey();

  return ret;
}

BIP32.prototype.toString = function() {
  var isPrivate =
    (this.version == constants.mainnet.bip32privkey ||
      this.version == constants.testnet.bip32privkey);

  if (isPrivate)
    return this.extendedPrivateKeyString();
  else
    return this.extendedPublicKeyString();
};

function uint(f, size) {
  if (f.length < size)
    throw new Error('not enough data');
  var n = 0;
  for (var i = 0; i < size; i++) {
    n *= 256;
    n += f[i];
  }
  return n;
}

function u8(f) {
  return uint(f, 1);
}

function u16(f) {
  return uint(f, 2);
}

function u32(f) {
  return uint(f, 4);
}

function u64(f) {
  return uint(f, 8);
}

module.exports = BIP32;
<commit_msg>use base58check in fromString<commit_after>var base58 = require('./base58');
var Base58Check = require('./base58check');
var Hash = require('./hash');
var Keypair = require('./keypair');
var Pubkey = require('./pubkey');
var Privkey = require('./privkey');
var Point = require('./point');
var Random = require('./random');
var bn = require('./bn');
var constants = require('./constants');

var BIP32 = function BIP32() {
  if (!(this instanceof BIP32))
    return new BIP32();
}

BIP32.prototype.fromRandom = function(networkstr) {
  if (!networkstr)
    networkstr = 'mainnet';
  this.version = constants[networkstr].bip32privkey;
  this.depth = 0x00;
  this.parentFingerprint = new Buffer([0, 0, 0, 0]);
  this.childIndex = new Buffer([0, 0, 0, 0]);
  this.chainCode = Random.getRandomBuffer(32);
  this.key = (new Keypair()).fromRandom();
  this.hasPrivateKey = true;
  this.pubKeyHash = Hash.sha256ripemd160(this.key.pubkey.toBuffer());
  this.buildExtendedPublicKey();
  this.buildExtendedPrivateKey();
};

BIP32.prototype.fromString = function(str) {
  var bytes = Base58Check.decode(str);
  this.initFromBytes(bytes);
  return this;
};

BIP32.prototype.fromSeed = function(bytes, networkstr) {
  if (!networkstr)
    networkstr = 'mainnet';

  if (!Buffer.isBuffer(bytes))
    throw new Error('bytes must be a buffer');
  if (bytes.length < 128 / 8)
    throw new Error('Need more than 128 bytes of entropy');
  if (bytes.length > 512 / 8)
    throw new Error('More than 512 bytes of entropy is nonstandard');
  var hash = Hash.sha512hmac(bytes, new Buffer('Bitcoin seed'));

  this.depth = 0x00;
  this.parentFingerprint = new Buffer([0, 0, 0, 0]);
  this.childIndex = new Buffer([0, 0, 0, 0]);
  this.chainCode = hash.slice(32, 64);
  this.version = constants[networkstr].bip32privkey;
  this.key = new Keypair();
  this.key.privkey = new Privkey({bn: bn.fromBuffer(hash.slice(0, 32))});
  this.key.privkey2pubkey();
  this.hasPrivateKey = true;
  this.pubKeyHash = Hash.sha256ripemd160(this.key.pubkey.toBuffer());

  this.buildExtendedPublicKey();
  this.buildExtendedPrivateKey();

  return this;
};

BIP32.prototype.initFromBytes = function(bytes) {
  // Both pub and private extended keys are 78 bytes
  if (bytes.length != 78)
    throw new Error('not enough data');

  this.version = u32(bytes.slice(0, 4));
  this.depth = u8(bytes.slice(4, 5));
  this.parentFingerprint = bytes.slice(5, 9);
  this.childIndex = u32(bytes.slice(9, 13));
  this.chainCode = bytes.slice(13, 45);

  var keyBytes = bytes.slice(45, 78);

  var isPrivate =
    (this.version == constants.mainnet.bip32privkey ||
      this.version == constants.testnet.bip32privkey);

  var isPublic =
    (this.version == constants.mainnet.bip32pubkey ||
      this.version == constants.testnet.bip32pubkey);

  if (isPrivate && keyBytes[0] == 0) {
    this.key = new Keypair();
    this.key.privkey = new Privkey({bn: bn.fromBuffer(keyBytes.slice(1, 33))});
    this.key.privkey2pubkey();
    this.pubKeyHash = Hash.sha256ripemd160(this.key.pubkey.toBuffer());
    this.hasPrivateKey = true;
  } else if (isPublic && (keyBytes[0] == 0x02 || keyBytes[0] == 0x03)) {
    this.key = new Keypair();
    this.key.pubkey = (new Pubkey()).fromDER(keyBytes);
    this.pubKeyHash = Hash.sha256ripemd160(this.key.pubkey.toBuffer());
    this.hasPrivateKey = false;
  } else {
    throw new Error('Invalid key');
  }

  this.buildExtendedPublicKey();
  this.buildExtendedPrivateKey();
}

BIP32.prototype.buildExtendedPublicKey = function() {
  this.extendedPublicKey = new Buffer([]);

  var v = null;
  switch (this.version) {
    case constants.mainnet.bip32pubkey:
    case constants.mainnet.bip32privkey:
      v = constants.mainnet.bip32pubkey;
      break;
    case constants.testnet.bip32pubkey:
    case constants.testnet.bip32privkey:
      v = constants.testnet.bip32pubkey;
      break;
    default:
      throw new Error('Unknown version');
  }

  // Version
  this.extendedPublicKey = Buffer.concat([
    new Buffer([v >> 24]),
    new Buffer([(v >> 16) & 0xff]),
    new Buffer([(v >> 8) & 0xff]),
    new Buffer([v & 0xff]),
    new Buffer([this.depth]),
    this.parentFingerprint,
    new Buffer([this.childIndex >>> 24]),
    new Buffer([(this.childIndex >>> 16) & 0xff]),
    new Buffer([(this.childIndex >>> 8) & 0xff]),
    new Buffer([this.childIndex & 0xff]),
    this.chainCode,
    this.key.pubkey.toBuffer()
  ]);
}

BIP32.prototype.extendedPublicKeyString = function(format) {
  if (format === undefined || format === 'base58') {
    var hash = Hash.sha256sha256(this.extendedPublicKey);
    var checksum = hash.slice(0, 4);
    var data = Buffer.concat([this.extendedPublicKey, checksum]);
    return base58.encode(data);
  } else if (format === 'hex') {
    return this.extendedPublicKey.toString('hex');;
  } else {
    throw new Error('bad format');
  }
}

BIP32.prototype.buildExtendedPrivateKey = function() {
  if (!this.hasPrivateKey) return;
  this.extendedPrivateKey = new Buffer([]);

  var v = this.version;

  this.extendedPrivateKey = Buffer.concat([
    new Buffer([v >> 24]),
    new Buffer([(v >> 16) & 0xff]),
    new Buffer([(v >> 8) & 0xff]),
    new Buffer([v & 0xff]),
    new Buffer([this.depth]),
    this.parentFingerprint,
    new Buffer([this.childIndex >>> 24]),
    new Buffer([(this.childIndex >>> 16) & 0xff]),
    new Buffer([(this.childIndex >>> 8) & 0xff]),
    new Buffer([this.childIndex & 0xff]),
    this.chainCode,
    new Buffer([0]),
    this.key.privkey.bn.toBuffer({size: 32})
  ]);
}

BIP32.prototype.extendedPrivateKeyString = function(format) {
  if (format === undefined || format === 'base58') {
    var hash = Hash.sha256sha256(this.extendedPrivateKey);
    var checksum = hash.slice(0, 4);
    var data = Buffer.concat([this.extendedPrivateKey, checksum]);
    return base58.encode(data);
  } else if (format === 'hex') {
    return this.extendedPrivateKey.toString('hex');
  } else {
    throw new Error('bad format');
  }
}

BIP32.prototype.derive = function(path) {
  var e = path.split('/');

  // Special cases:
  if (path == 'm' || path == 'M' || path == 'm\'' || path == 'M\'')
    return this;

  var bip32 = this;
  for (var i in e) {
    var c = e[i];

    if (i == 0) {
      if (c != 'm') throw new Error('invalid path');
      continue;
    }

    if (parseInt(c.replace("'", "")).toString() !== c.replace("'", ""))
      throw new Error('invalid path');

    var usePrivate = (c.length > 1) && (c[c.length - 1] == '\'');
    var childIndex = parseInt(usePrivate ? c.slice(0, c.length - 1) : c) & 0x7fffffff;

    if (usePrivate)
      childIndex += 0x80000000;

    bip32 = bip32.deriveChild(childIndex);
  }

  return bip32;
}

BIP32.prototype.deriveChild = function(i) {
  if (typeof i !== 'number')
    throw new Error('i must be a number');

  var ib = [];
  ib.push((i >> 24) & 0xff);
  ib.push((i >> 16) & 0xff);
  ib.push((i >> 8) & 0xff);
  ib.push(i & 0xff);
  ib = new Buffer(ib);

  var usePrivate = (i & 0x80000000) != 0;

  var isPrivate =
    (this.version == constants.mainnet.bip32privkey ||
      this.version == constants.testnet.bip32privkey);

  if (usePrivate && (!this.hasPrivateKey || !isPrivate))
    throw new Error('Cannot do private key derivation without private key');

  var ret = null;
  if (this.hasPrivateKey) {
    var data = null;

    if (usePrivate) {
      data = Buffer.concat([new Buffer([0]), this.key.privkey.bn.toBuffer({size: 32}), ib]);
    } else {
      data = Buffer.concat([this.key.pubkey.toBuffer({size: 32}), ib]);
    }

    var hash = Hash.sha512hmac(data, this.chainCode);
    var il = bn.fromBuffer(hash.slice(0, 32), {size: 32});
    var ir = hash.slice(32, 64);

    // ki = IL + kpar (mod n).
    var k = il.add(this.key.privkey.bn).mod(Point.getN());

    ret = new BIP32();
    ret.chainCode = ir;

    ret.key = new Keypair();
    ret.key.privkey = new Privkey({bn: k});
    ret.key.privkey2pubkey();
    ret.hasPrivateKey = true;

  } else {
    var data = Buffer.concat([this.key.pubkey.toBuffer(), ib]);
    var hash = Hash.sha512hmac(data, this.chainCode);
    var il = bn(hash.slice(0, 32));
    var ir = hash.slice(32, 64);

    // Ki = (IL + kpar)*G = IL*G + Kpar
    var ilG = Point.getG().mul(il);
    var Kpar = this.key.pubkey.point;
    var Ki = ilG.add(Kpar);
    var newpub = new Pubkey();
    newpub.point = Ki;

    ret = new BIP32();
    ret.chainCode = ir;

    var key = new Keypair();
    key.pubkey = newpub;
    ret.key = key;
    ret.hasPrivateKey = false;
  }

  ret.childIndex = i;
  ret.parentFingerprint = this.pubKeyHash.slice(0, 4);
  ret.version = this.version;
  ret.depth = this.depth + 1;

  ret.pubKeyHash = Hash.sha256ripemd160(ret.key.pubkey.toBuffer());

  ret.buildExtendedPublicKey();
  ret.buildExtendedPrivateKey();

  return ret;
}

BIP32.prototype.toString = function() {
  var isPrivate =
    (this.version == constants.mainnet.bip32privkey ||
      this.version == constants.testnet.bip32privkey);

  if (isPrivate)
    return this.extendedPrivateKeyString();
  else
    return this.extendedPublicKeyString();
};

function uint(f, size) {
  if (f.length < size)
    throw new Error('not enough data');
  var n = 0;
  for (var i = 0; i < size; i++) {
    n *= 256;
    n += f[i];
  }
  return n;
}

function u8(f) {
  return uint(f, 1);
}

function u16(f) {
  return uint(f, 2);
}

function u32(f) {
  return uint(f, 4);
}

function u64(f) {
  return uint(f, 8);
}

module.exports = BIP32;
<|endoftext|>


<commit_before>var FPS = 30;

function Karel2DWorld() {
    this.animationMode = 0;
}

Karel2DWorld.prototype.initialize = function(jqueryObj){
    this.renderer = jqueryObj;
};

Karel2DWorld.prototype.clear = function(){
    this.renderer.html("");
};

Karel2DWorld.prototype.resetKarelData = function () {
    this.karel = {};
    this.karel.x = this.karelStart.position[0];
    this.karel.y = this.karelStart.position[1];
    this.karel.direction = this.karelStart.direction;
};

Karel2DWorld.prototype.loadMap = function(mapObj){

    var _this = this;
    function drawKarel () {
        $("body").append("

");
        _this.$myKarel = $("#mykarel");
        var xy = _this.defineRealPos(_this.karel.x, _this.karel.y);
        _this.$myKarel.offset({left: xy[0], top: xy[1]});
        _this.showKarelDirection();
    }

    this.map = mapObj.map;
    this.karelStart = mapObj.karel;

    this.resetKarelData();

    var field = this.createDomMap();
    this.renderer.html(field);

    drawKarel();
};

Karel2DWorld.prototype.defineRealPos = function (x, y) {
    var id = "y" + y + "x" + x;
    var realKarelXY = $("#"+id).offset();
    var res = [];
    res.push(realKarelXY.left);
    res.push(realKarelXY.top);
    return res;
};

Karel2DWorld.prototype.createDomMap = function() {
    var table = '
';
    for (var row = 0; row < this.map.length; row++) {
        table = table + '
';
        for (var cell = 0; cell < this.map[row].length; cell++) {
            var domCell = this.analyzeCell(row, cell, this.map[row][cell], this);
            table = table + "" + domCell + "	"
        }
        table = table + "
";
    }
    return table + "
";
};

Karel2DWorld.prototype.analyzeCell = function (y, x, cell){
    var id = "y" + y + "x" + x;
    if (cell == "x") {
        return '

';
    }
    var retStr = '
';

    var numBeepers = parseInt(cell);
    if (numBeepers > 0) {
        retStr += '
' + numBeepers + '
';
    }
    retStr += '
';
    return retStr;
};

Karel2DWorld.prototype.karelMove = function (duration, cb, cbArgs) {
    var _this=this;
    function defineNextKarelCell() {
        var res = [];
        res[0] = _this.karel.x; res[1] = _this.karel.y;
        if (_this.karel.direction == 1) { // right
            res[0]++;
        } else if (_this.karel.direction == 3) { // right
            res[0]--;
        } else if (_this.karel.direction == 0) { // right
            res[1]++;
        } else if (_this.karel.direction == 2) { // right
            res[1]--;
        }
        return res;
    }

    function animateKarelMove(curKarelPos, nextKarelPos) {
        var numTacts = duration * FPS;
        var refreshInterval = 1000 / FPS;

        var dx = nextKarelPos[0] - curKarelPos[0];
        var dy = nextKarelPos[1] - curKarelPos[1];

        var tact = 0;

        var animFuncID = setInterval(function(){
            if (_this.animationMode == 0) {
                tact ++;
                //console.log("tact", tact);
                if (tact > numTacts) {
                    clearInterval(animFuncID);
                    _this.showKarelDirection();
                    cb();
                    return;
                }
                _this.$myKarel.offset ({left: curKarelPos[0] + dx * tact/numTacts, top: curKarelPos[1] + dy * tact/numTacts});
            } if (_this.animationMode == 2) { // reserved for stop
                clearInterval(animFuncID);
                _this.showKarelDirection();
                cb();
                return;
            }
        }, refreshInterval);
    }

    var curKarelPos = this.defineRealPos (this.karel.x, this.karel.y);

    var nextKarelCell = defineNextKarelCell();
    var nextKarelPos = this.defineRealPos (nextKarelCell[0], nextKarelCell[1]); // yx

    this.karel.x = nextKarelCell[0];
    this.karel.y = nextKarelCell[1];

    this.hideKarelDirection();
    animateKarelMove (curKarelPos, nextKarelPos);
};

Karel2DWorld.prototype.showKarelDirection = function () {
    var dirClassName = "mydirection-";
    if (this.karel.direction == 0) {
        dirClassName += "south";
    } else if (this.karel.direction == 1) {
        dirClassName += "east";
    } else if (this.karel.direction == 2) {
        dirClassName += "north";
    } else {
        dirClassName += "west";
    }
    $("body").append("

");
    this.$mykarelDirection = $("#mykarelDirection");
    var xy = this.defineRealPos(this.karel.x, this.karel.y);
    this.$mykarelDirection.offset({left: xy[0], top: xy[1]});
};

Karel2DWorld.prototype.hideKarelDirection = function () {
    this.$mykarelDirection.detach();
};

Karel2DWorld.prototype.karelTurnRight = function (duration, cb, cbArgs){
    this.hideKarelDirection();
    this.karel.direction--;
    if (this.karel.direction<0) {
        this.karel.direction = 3;
    }
    var _this=this;
    setTimeout(function(){
        _this.showKarelDirection();
        setTimeout(function(){
            cb();
        }, duration/2*1000);
    }, duration/2*1000);
};

Karel2DWorld.prototype.karelTurnLeft = function (duration, cb, cbArgs) {
    this.hideKarelDirection();
    this.karel.direction++;
    if (this.karel.direction>3) {
        this.karel.direction = 0;
    }
    var _this=this;
    setTimeout(function(){
        _this.showKarelDirection();
        setTimeout(function(){
            cb();
        }, duration/2*1000);
    }, duration/2*1000);
};

Karel2DWorld.prototype.redrawMap = function () {
    $map_field.html(this.createDomMap());
    //var _this = this;
    //$map_field.css( 'transform', 'scale(' + _this.scale + ', ' + _this.scale + ')' );
};

Karel2DWorld.prototype.karelPutBeeper = function (duration, cb, cbArgs){
    var beepersInCell = parseInt(this.map[this.karel.y][this.karel.x]);
    if (!beepersInCell){
        beepersInCell = 0;
    }
    beepersInCell++;
    this.map[this.karel.y][this.karel.x] = beepersInCell;
    var _this = this;
    setTimeout(function(){
        _this.redrawMap();
        setTimeout(function(){
            cb();
        }, duration/2*1000);
    }, duration/2*1000);
};

Karel2DWorld.prototype.karelTakeBeeper = function (duration, cb, cbArgs){
    var beepersInCell = parseInt(this.map[this.karel.y][this.karel.x]);
    if (!beepersInCell){
        beepersInCell = 0;
    }
    beepersInCell--;
    this.map[this.karel.y][this.karel.x] = beepersInCell;
    var _this = this;
    setTimeout(function(){
        _this.redrawMap();
        setTimeout(function(){
            cb();
        }, duration/2*1000);
    }, duration/2*1000);
};

Karel2DWorld.prototype.setSpeed = function (speedCOeficient){
// ???
};

Karel2DWorld.prototype.stopWorld = function () {
    this.animationMode = 1;
};
Karel2DWorld.prototype.startWorld =function() {
    this.animationMode = 0;
};

var k2dw = new Karel2DWorld();
var $map_field = $('#map-field');
k2dw.initialize($map_field);

var map =  {
    name: 'some map name',
    original: {
        map:[
            ['x', '', '', 3, '', 2, 3],
            ['x', '', 4, 3, 'x', 1, ''],
            ['', '', 'x', 1, 'x', '', ''],
            ['', 'x', 3, 'x', 2, '', 5],
            ['', 'x', '', 1, 'x', 'x', ''],
            [2,  '',   1, 3, 'x', 'x', ''],
            ['x', '', 'x', 3, '', 1, '']
        ],
        karel: {
            position: [0, 5],
            direction: 1,
            beepers: 1000
        }
    },
    final:  [{
        map:[
            ['x', '', '', 3, '', 2, 3],
            ['x', '', 4, 3, 'x', 1, ''],
            ['', '', 'x', 1, 'x', '', ''],
            ['', 'x', 1, 'x', 2, '', 5],
            ['', 'x', 1, 1, 'x', 'x', ''],
            [1, 1, 1, 1, 'x', 'x', ''],
            ['x', '', 'x', 3, '', 1, '']
        ],
        karel: {
            position: [0, 5],
            direction: 1
        }
    }],
    description: 'problem solving'
};

k2dw.loadMap(map.original);
k2dw.karelMove(2, function(){
    k2dw.karelPutBeeper(2, function(){
        k2dw.karelTurnLeft(2, function(){
            k2dw.karelMove(2, function(){
                console.log("finished");
            });
        });
    });
});<commit_msg>karel animation lib6<commit_after>var FPS = 30;

function Karel2DWorld() {
    this.animationMode = 0;
}

Karel2DWorld.prototype.initialize = function(jqueryObj){
    this.renderer = jqueryObj;
    this.speedCoeficient = 1;
    this.scale = 1;
    var _this = this;
    this.renderer.mousedown(function() {
        _this.renderer.draggable();
    });
};

Karel2DWorld.prototype.clear = function(){
    this.renderer.html("");
};

Karel2DWorld.prototype.resetKarelData = function () {
    this.karel = {};
    this.karel.x = this.karelStart.position[0];
    this.karel.y = this.karelStart.position[1];
    this.karel.direction = this.karelStart.direction;
};

Karel2DWorld.prototype.loadMap = function(mapObj){

    var _this = this;
    function drawKarel () {
        $("body").append("

");
        _this.$myKarel = $("#mykarel");
        var xy = _this.defineRealPos(_this.karel.x, _this.karel.y);
        _this.$myKarel.offset({left: xy[0], top: xy[1]});
        _this.$myKarel.css( 'transform', 'scale(' + _this.scale + ', ' + _this.scale + ')');
        _this.showKarelDirection();
    }

    this.map = mapObj.map;
    this.karelStart = mapObj.karel;

    this.resetKarelData();

    var field = this.createDomMap();
    this.renderer.html(field);

    drawKarel();
};

Karel2DWorld.prototype.defineRealPos = function (x, y) {
    var id = "y" + y + "x" + x;
    var realKarelXY = $("#"+id).offset();
    var res = [];
    res.push(realKarelXY.left);
    res.push(realKarelXY.top);
    return res;
};

Karel2DWorld.prototype.createDomMap = function() {
    var table = '
';
    for (var row = 0; row < this.map.length; row++) {
        table = table + '
';
        for (var cell = 0; cell < this.map[row].length; cell++) {
            var domCell = this.analyzeCell(row, cell, this.map[row][cell], this);
            table = table + "" + domCell + "	"
        }
        table = table + "
";
    }
    return table + "
";
};

Karel2DWorld.prototype.analyzeCell = function (y, x, cell){
    var id = "y" + y + "x" + x;
    if (cell == "x") {
        return '

';
    }
    var retStr = '
';

    var numBeepers = parseInt(cell);
    if (numBeepers > 0) {
        retStr += '
' + numBeepers + '
';
    }
    retStr += '
';
    return retStr;
};

Karel2DWorld.prototype.karelMove = function (duration, cb, cbArgs) {
    var _this=this;
    function defineNextKarelCell() {
        var res = [];
        res[0] = _this.karel.x; res[1] = _this.karel.y;
        if (_this.karel.direction == 1) { // right
            res[0]++;
        } else if (_this.karel.direction == 3) { // right
            res[0]--;
        } else if (_this.karel.direction == 0) { // right
            res[1]++;
        } else if (_this.karel.direction == 2) { // right
            res[1]--;
        }
        return res;
    }

    function animateKarelMove(curKarelPos, nextKarelPos) {
        _this.numTacts = duration/_this.speedCoeficient * FPS;
        var refreshInterval = 1000 / FPS;

        var dx = nextKarelPos[0] - curKarelPos[0];
        var dy = nextKarelPos[1] - curKarelPos[1];

        var tact = 0;

        var anymFunc = function() {
            if (_this.animationMode == 0) {
                tact++;
                //console.log("tact", tact);
                if (tact > _this.numTacts) {
                    _this.showKarelDirection();
                    cb();
                    return;
                }
                _this.$myKarel.offset({
                    left: curKarelPos[0] + dx * tact / _this.numTacts,
                    top: curKarelPos[1] + dy * tact / _this.numTacts
                });
            }
            setTimeout (anymFunc, refreshInterval);
        };
        setTimeout (anymFunc, refreshInterval);

        //var animFuncID = setInterval(function(){
        //    if (_this.animationMode == 0) {
        //        tact ++;
        //        //console.log("tact", tact);
        //        if (tact > numTacts) {
        //            clearInterval(animFuncID);
        //            _this.showKarelDirection();
        //            cb();
        //            return;
        //        }
        //        _this.$myKarel.offset ({left: curKarelPos[0] + dx * tact/numTacts, top: curKarelPos[1] + dy * tact/numTacts});
        //    } if (_this.animationMode == 2) { // reserved for stop
        //        clearInterval(animFuncID);
        //        _this.showKarelDirection();
        //        cb();
        //        return;
        //    }
        //}, refreshInterval);
    }

    var curKarelPos = this.defineRealPos (this.karel.x, this.karel.y);

    var nextKarelCell = defineNextKarelCell();
    var nextKarelPos = this.defineRealPos (nextKarelCell[0], nextKarelCell[1]); // yx

    this.karel.x = nextKarelCell[0];
    this.karel.y = nextKarelCell[1];

    this.hideKarelDirection();
    animateKarelMove (curKarelPos, nextKarelPos);
};

Karel2DWorld.prototype.showKarelDirection = function () {
    var dirClassName = "mydirection-";
    if (this.karel.direction == 0) {
        dirClassName += "south";
    } else if (this.karel.direction == 1) {
        dirClassName += "east";
    } else if (this.karel.direction == 2) {
        dirClassName += "north";
    } else {
        dirClassName += "west";
    }
    $("body").append("

");
    this.$mykarelDirection = $("#mykarelDirection");
    var xy = this.defineRealPos(this.karel.x, this.karel.y);
    this.$mykarelDirection.offset({left: xy[0], top: xy[1]});
    var _this=this;
    this.$mykarelDirection.css( 'transform', 'scale(' + _this.scale + ', ' + _this.scale + ')' );
};

Karel2DWorld.prototype.hideKarelDirection = function () {
    this.$mykarelDirection.detach();
};

Karel2DWorld.prototype.karelTurnRight = function (duration, cb, cbArgs){
    this.hideKarelDirection();
    this.karel.direction--;
    if (this.karel.direction<0) {
        this.karel.direction = 3;
    }
    var _this=this;
    setTimeout(function(){
        _this.showKarelDirection();
        setTimeout(function(){
            cb();
        }, duration/_this.speedCoeficient/2*1000);
    }, duration/_this.speedCoeficient/2*1000);
};

Karel2DWorld.prototype.karelTurnLeft = function (duration, cb, cbArgs) {
    this.hideKarelDirection();
    this.karel.direction++;
    if (this.karel.direction>3) {
        this.karel.direction = 0;
    }
    var _this=this;
    setTimeout(function(){
        _this.showKarelDirection();
        setTimeout(function(){
            cb();
        }, duration/_this.speedCoeficient/2*1000);
    }, duration/_this.speedCoeficient/2*1000);
};

Karel2DWorld.prototype.redrawMap = function () {
    $map_field.html(this.createDomMap());
    var _this = this;
    $map_field.css( 'transform', 'scale(' + _this.scale + ', ' + _this.scale + ')' );
};

Karel2DWorld.prototype.karelPutBeeper = function (duration, cb, cbArgs){
    var beepersInCell = parseInt(this.map[this.karel.y][this.karel.x]);
    if (!beepersInCell){
        beepersInCell = 0;
    }
    beepersInCell++;
    this.map[this.karel.y][this.karel.x] = beepersInCell;
    var _this = this;
    setTimeout(function(){
        _this.redrawMap();
        setTimeout(function(){
            cb();
        }, duration/_this.speedCoeficient/2*1000);
    }, duration/_this.speedCoeficient/2*1000);
};

Karel2DWorld.prototype.karelTakeBeeper = function (duration, cb, cbArgs){
    var beepersInCell = parseInt(this.map[this.karel.y][this.karel.x]);
    if (!beepersInCell){
        beepersInCell = 0;
    }
    beepersInCell--;
    this.map[this.karel.y][this.karel.x] = beepersInCell;
    var _this = this;
    setTimeout(function(){
        _this.redrawMap();
        setTimeout(function(){
            cb();
        }, duration/_this.speedCoeficient/2*1000);
    }, duration/_this.speedCoeficient/2*1000);
};

Karel2DWorld.prototype.setSpeed = function (speedCoeficient){
    this.speedCoeficient = speedCoeficient;
};

Karel2DWorld.prototype.stopWorld = function () {
    this.animationMode = 1;
};

Karel2DWorld.prototype.startWorld =function() {
    this.animationMode = 0;
};

Karel2DWorld.prototype.scaleUp =function() {
    this.scale += 0.1;
    this.redrawMap();
    var _this=this;
    this.$mykarelDirection.css( 'transform', 'scale(' + _this.scale + ', ' + _this.scale + ')' );
    this.$myKarel.css( 'transform', 'scale(' + _this.scale + ', ' + _this.scale + ')');
};

Karel2DWorld.prototype.scaleDown =function() {
    this.scale -= 0.1;
    this.redrawMap();
    var _this=this;
    this.$mykarelDirection.css( 'transform', 'scale(' + _this.scale + ', ' + _this.scale + ')' );
    this.$myKarel.css( 'transform', 'scale(' + _this.scale + ', ' + _this.scale + ')');
};

var k2dw = new Karel2DWorld();
var $map_field = $('#map-field');
k2dw.initialize($map_field);

var map =  {
    name: 'some map name',
    original: {
        map:[
            ['x', '', '', 3, '', 2, 3],
            ['x', '', 4, 3, 'x', 1, ''],
            ['', '', 'x', 1, 'x', '', ''],
            ['', 'x', 3, 'x', 2, '', 5],
            ['', 'x', '', 1, 'x', 'x', ''],
            [2,  '',   1, 3, 'x', 'x', ''],
            ['x', '', 'x', 3, '', 1, '']
        ],
        karel: {
            position: [0, 5],
            direction: 1,
            beepers: 1000
        }
    },
    final:  [{
        map:[
            ['x', '', '', 3, '', 2, 3],
            ['x', '', 4, 3, 'x', 1, ''],
            ['', '', 'x', 1, 'x', '', ''],
            ['', 'x', 1, 'x', 2, '', 5],
            ['', 'x', 1, 1, 'x', 'x', ''],
            [1, 1, 1, 1, 'x', 'x', ''],
            ['x', '', 'x', 3, '', 1, '']
        ],
        karel: {
            position: [0, 5],
            direction: 1
        }
    }],
    description: 'problem solving'
};

k2dw.loadMap(map.original);
k2dw.karelMove(2, function(){
    k2dw.karelPutBeeper(2, function(){
        k2dw.karelTurnLeft(2, function(){
            k2dw.karelMove(2, function(){
                console.log("finished");
            });
        });
    });
});

document.onkeydown = checkKey;

function checkKey(e) {
    e = e || window.event;
    if (e.keyCode == '38') { // up arrow
        console.log("+");
        k2dw.scaleUp();
    }
    else if (e.keyCode == '40') { // down arrow
        console.log("-");
        k2dw.scaleDown();
    }
}<|endoftext|>


<commit_before>import React, {PropTypes, Component} from 'react'
import { connect } from 'react-redux'
import { Button, InputGroup, FormGroup, FormControl,
  Badge, Pagination }
    from 'react-bootstrap'
import Helmet from 'react-helmet'
import { debounce, find } from 'lodash'
import Entry from './Entry'
import NewLanguageModal from './NewLanguageModal'
import { Icon, Notification, LoaderText } from '../../components'

import {
  initialLoad,
  handleDelete,
  handleUpdatePageSize,
  handleUpdateSort,
  handleUpdateSearch,
  handlePageUpdate,
  handleNewLanguageDisplay,
  pageSizeOption,
  sortOption
} from '../../actions/languages'

class Languages extends Component {
  componentDidMount () {
    this.props.handleInitLoad()
  }

  render () {
    const {
      searchText,
      size,
      sort,
      page,
      results,
      totalCount,
      permission,
      user,
      loading,
      deleting,
      notification,
      handleDelete,
      handleOnUpdatePageSize,
      handleOnUpdateSort,
      handleOnUpdateSearch,
      handlePageChanged,
      handleOnDisplayNewLanguage
    } = this.props

    const totalPage = Math.floor(totalCount / size) +
      (totalCount % size > 0 ? 1 : 0)

    return (

        {notification &&
        (<Notification severity={notification.severity}
          message={notification.message}
          details={notification.details}
          show={!!notification} />
        )
        }
        <Helmet title='Languages' />

                    Languages {!loading &&
                      <Badge className='default'>{totalCount}</Badge>}

                  {permission.canAddLocale &&

                      <Button className='primary'
                        id='btn-language-add-new'
                        onClick={handleOnDisplayNewLanguage}>
                        <Icon name='plus'
                          title='plus' /> Add new language
                      </Button>
                      <NewLanguageModal />

                  }

                      <FormGroup>
                        <InputGroup>
                          <FormControl type='text'
                            defaultValue={searchText}
                            onChange={handleOnUpdateSearch} />
                          <InputGroup.Button>
                            <Button>
                              <Icon name='search'
                                className='s1'
                                title='search' />
                            </Button>
                          </InputGroup.Button>
                        </InputGroup>
                      </FormGroup>

                  {loading
                      ?

                        <LoaderText theme={{ base: { fz: 'Fz(ms1)' } }}
                          size='2' loading />

                      : (

                          <FormControl componentClass='select'
                            className='pull-right' id='sort-options'
                            onChange={handleOnUpdateSort} value={sort.value}>
                            {sortOption.map(function (sort, i) {
                              return <option key={i} value={sort.value}>
                                {sort.display}</option>
                            })}
                          </FormControl>

                          Show
                          <FormControl inline componentClass='select'
                            onChange={handleOnUpdatePageSize} value={size}
                            id='page-size-options'>
                            {pageSizeOption.map(function (value, i) {
                              return <option key={i} value={value}>
                                {value}</option>
                            })}
                          </FormControl>

                          <Pagination
                            prev
                            next
                            bsSize='medium'
                            items={totalPage}
                            activePage={page}
                            onSelect={handlePageChanged} />

)
                  }

                  {!loading &&

                            Language

                        {results.map(function (value, i) {
                          return <Entry key={i} locale={value}
                            userLanguageTeams={user.languageTeams}
                            permission={permission}
                            handleDelete={handleDelete}
                            isDeleting={deleting} />
                        })}

}

    )
  }
}

Languages.propTypes = {
  page: PropTypes.number,
  notification: PropTypes.object,
  permission: PropTypes.object,
  user: PropTypes.object,
  searchText: PropTypes.string,
  size: PropTypes.number,
  sort: PropTypes.object,
  results: PropTypes.array,
  totalCount: PropTypes.number,
  loading: PropTypes.bool,
  deleting: PropTypes.bool,
  handleInitLoad: PropTypes.func,
  handleDelete: PropTypes.func,
  handleOnUpdatePageSize: PropTypes.func,
  handleOnUpdateSort: PropTypes.func,
  handleOnUpdateSearch: PropTypes.func,
  handlePageChanged: PropTypes.func,
  handleOnDisplayNewLanguage: PropTypes.func
}

const mapStateToProps = (state) => {
  let urlSort = state.routing.location.query.sort
  if (urlSort) {
    urlSort = find(sortOption, function (sort) {
      return sort.value === urlSort
    })
    if (!urlSort) {
      urlSort = sortOption[0]
    }
  } else {
    urlSort = sortOption[0]
  }

  const {
    locales,
    loading,
    permission,
    user,
    notification,
    deleting
  } = state.languages
  return {
    searchText: state.routing.location.query.search || '',
    page: parseInt(state.routing.location.query.page) || 1,
    size: parseInt(state.routing.location.query.size) || pageSizeOption[0],
    sort: urlSort,
    results: locales.results,
    totalCount: locales.totalCount,
    loading,
    permission,
    user,
    notification,
    deleting
  }
}

const mapDispatchToProps = (dispatch) => {
  const updateSearch = debounce((val) =>
    dispatch(handleUpdateSearch(val)), 200)

  return {
    handleInitLoad: () => {
      dispatch(initialLoad())
    },
    handleDelete: (localeId) => {
      dispatch(handleDelete(localeId))
    },
    handleOnUpdatePageSize: (event) => {
      dispatch(handleUpdatePageSize(event.target.value || ''))
    },
    handleOnUpdateSort: (event) => {
      dispatch(handleUpdateSort(event.target.value || ''))
    },
    handleOnUpdateSearch: (event) => {
      updateSearch(event.target.value || '')
    },
    handlePageChanged: (page) => {
      dispatch(handlePageUpdate(page))
    },
    handleOnDisplayNewLanguage: () => {
      dispatch(handleNewLanguageDisplay(true))
    }
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Languages)
<commit_msg>WIP: removed unnecessary divs, fixed linting issues<commit_after>import React, {PropTypes, Component} from 'react'
import {connect} from 'react-redux'
import {
  Button, InputGroup, FormGroup, FormControl,
  Badge, Pagination
}
  from 'react-bootstrap'
import Helmet from 'react-helmet'
import {debounce, find} from 'lodash'
import Entry from './Entry'
import NewLanguageModal from './NewLanguageModal'
import {Icon, Notification, LoaderText} from '../../components'

import {
  initialLoad,
  handleDelete,
  handleUpdatePageSize,
  handleUpdateSort,
  handleUpdateSearch,
  handlePageUpdate,
  handleNewLanguageDisplay,
  pageSizeOption,
  sortOption
} from '../../actions/languages'

class Languages extends Component {
  componentDidMount () {
    this.props.handleInitLoad()
  }

  render () {
    const {
      searchText,
      size,
      sort,
      page,
      results,
      totalCount,
      permission,
      user,
      loading,
      deleting,
      notification,
      handleDelete,
      handleOnUpdatePageSize,
      handleOnUpdateSort,
      handleOnUpdateSearch,
      handlePageChanged,
      handleOnDisplayNewLanguage
    } = this.props

    const totalPage = Math.floor(totalCount / size) +
      (totalCount % size > 0 ? 1 : 0)

    return (

        {notification &&
        (<Notification severity={notification.severity}
          message={notification.message}
          details={notification.details}
          show={!!notification} />
        )
        }
        <Helmet title='Languages' />

              Languages {!loading &&
                <Badge className='default'>{totalCount}</Badge>}

            {permission.canAddLocale &&

                <Button className='primary'
                  id='btn-language-add-new'
                  onClick={handleOnDisplayNewLanguage}>
                  <Icon name='plus'
                    title='plus' /> Add new language
                </Button>
                <NewLanguageModal />

            }

                <FormGroup>
                  <InputGroup>
                    <FormControl type='text'
                      defaultValue={searchText}
                      onChange={handleOnUpdateSearch} />
                    <InputGroup.Button>
                      <Button>
                        <Icon name='search'
                          className='s1'
                          title='search' />
                      </Button>
                    </InputGroup.Button>
                  </InputGroup>
                </FormGroup>

              {loading
                ?

                  <LoaderText theme={{base: {fz: 'Fz(ms1)'}}}
                    size='2' loading />

                : (

                    <FormControl componentClass='select'
                      className='pull-right' id='sort-options'
                      onChange={handleOnUpdateSort} value={sort.value}>
                    {sortOption.map(function (sort, i) {
                      return <option key={i} value={sort.value}>
                        {sort.display}</option>
                    })}
                    </FormControl>

                    Show
                    <FormControl inline componentClass='select'
                      onChange={handleOnUpdatePageSize} value={size}
                      id='page-size-options'>
                    {pageSizeOption.map(function (value, i) {
                      return <option key={i} value={value}>
                        {value}</option>
                    })}
                    </FormControl>

                    <Pagination
                      prev
                      next
                      bsSize='medium'
                      items={totalPage}
                      activePage={page}
                      onSelect={handlePageChanged} />

)
              }

            {!loading &&

                      Language

                    {results.map(function (value, i) {
                      return <Entry key={i} locale={value}
                        userLanguageTeams={user.languageTeams}
                        permission={permission}
                        handleDelete={handleDelete}
                        isDeleting={deleting} />
                    })}

}

    )
  }
}

Languages.propTypes = {
  page: PropTypes.number,
  notification: PropTypes.object,
  permission: PropTypes.object,
  user: PropTypes.object,
  searchText: PropTypes.string,
  size: PropTypes.number,
  sort: PropTypes.object,
  results: PropTypes.array,
  totalCount: PropTypes.number,
  loading: PropTypes.bool,
  deleting: PropTypes.bool,
  handleInitLoad: PropTypes.func,
  handleDelete: PropTypes.func,
  handleOnUpdatePageSize: PropTypes.func,
  handleOnUpdateSort: PropTypes.func,
  handleOnUpdateSearch: PropTypes.func,
  handlePageChanged: PropTypes.func,
  handleOnDisplayNewLanguage: PropTypes.func
}

const mapStateToProps = (state) => {
  let urlSort = state.routing.location.query.sort
  if (urlSort) {
    urlSort = find(sortOption, function (sort) {
      return sort.value === urlSort
    })
    if (!urlSort) {
      urlSort = sortOption[0]
    }
  } else {
    urlSort = sortOption[0]
  }

  const {
    locales,
    loading,
    permission,
    user,
    notification,
    deleting
  } = state.languages
  return {
    searchText: state.routing.location.query.search || '',
    page: parseInt(state.routing.location.query.page) || 1,
    size: parseInt(state.routing.location.query.size) || pageSizeOption[0],
    sort: urlSort,
    results: locales.results,
    totalCount: locales.totalCount,
    loading,
    permission,
    user,
    notification,
    deleting
  }
}

const mapDispatchToProps = (dispatch) => {
  const updateSearch = debounce((val) =>
    dispatch(handleUpdateSearch(val)), 200)

  return {
    handleInitLoad: () => {
      dispatch(initialLoad())
    },
    handleDelete: (localeId) => {
      dispatch(handleDelete(localeId))
    },
    handleOnUpdatePageSize: (event) => {
      dispatch(handleUpdatePageSize(event.target.value || ''))
    },
    handleOnUpdateSort: (event) => {
      dispatch(handleUpdateSort(event.target.value || ''))
    },
    handleOnUpdateSearch: (event) => {
      updateSearch(event.target.value || '')
    },
    handlePageChanged: (page) => {
      dispatch(handlePageUpdate(page))
    },
    handleOnDisplayNewLanguage: () => {
      dispatch(handleNewLanguageDisplay(true))
    }
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Languages)
<|endoftext|>


<commit_before>/**
* CJ Ramki
* Access the CJ Ramki contents from JavaScript side.
*
* Copyright (c) 2014 CJ Ramki
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* */
function loadFeed(url, element, num = null) {
    google.load("feeds", "1");

    function initialize() {
        var feed = new google.feeds.Feed(url);
        if (num !== null) {
            feed.includeHistoricalEntries();
            feed.setNumEntries(num);
        }
        feed.load(function (result) {
            if (!result.error) {
                var container = document.getElementById(element);

                //Feed title Section
                var feedTitle = document.createElement('h2');
                //use ".feed_title"  in css to style Title of the Feed
                feedTitle.class = 'feed_title';
                feedTitle.innerHTML = result.feed.title;
                container.appendChild(feedTitle);

                //Feed Entries section
                for (var i = 0; i < result.feed.entries.length; i++) {
                    var entry = result.feed.entries[i];
                    var post = document.createElement('h3');
                    var postTitle = document.createElement("a");
                    postTitle.class = 'post_title';
                    //use ".post_title"  in css to style Title of the Post
                    postTitle.href = entry.link;
                    postTitle.appendChild(document.createTextNode(entry.title));
                    post.appendChild(postTitle);

                    //Feed Content Snippet section
                    var content = document.createElement('div');
                    //use ".post_content"  in css to style Title of the Post
                    content.class = 'post_content';
                    content.innerHTML = entry.contentSnippet;
                    container.appendChild(post);
                    container.appendChild(content);
                }
            }
        });
    }
    google.setOnLoadCallback(initialize);
}
<commit_msg>Update loader.js<commit_after>/**
* CJ Ramki
* Access the CJ Ramki contents from JavaScript side.
*
* Copyright (c) 2014 CJ Ramki
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* */
function loadFeed(url, element, num = null, enableContent = false) {
    google.load("feeds", "1");

    function initialize() {
        var feed = new google.feeds.Feed(url);
        if (num !== null) {
            feed.includeHistoricalEntries();
            feed.setNumEntries(num);
        }
        feed.load(function (result) {
            if (!result.error) {
                var container = document.getElementById(element);

                //Feed title Section
                var feedTitle = document.createElement('h2');
                //use ".feed_title"  in css to style Title of the Feed
                feedTitle.className = 'feed_title';
                feedTitle.innerHTML = result.feed.title;
                container.appendChild(feedTitle);

                //Feed Entries section
                for (var i = 0; i < result.feed.entries.length; i++) {
                    var entry = result.feed.entries[i];
                    var postTitle = document.createElement("a");
                    //use ".post_title"  in css to style Title of the Post
                    postTitle.className = 'post_title';
                    postTitle.href = entry.link;
                    postTitle.appendChild(document.createTextNode(entry.title));
                    postTitle.appendChild(document.createElement('br'));
                    container.appendChild(postTitle);
                    //alert(content);
                    if (enableContent) {
                        //Feed Content Snippet section
                        var content = document.createElement('div');
                        //use ".post_content"  in css to style Title of the Post
                        content.className = 'post_content';
                        content.innerHTML = entry.contentSnippet;
                        container.appendChild(content);
                    }
                }
            }
        });
    }
    google.setOnLoadCallback(initialize);
}
<|endoftext|>


<commit_before>import classNames from 'classnames'
import { div, span, button, li, ul, h2, section, table, th, tr, td, label } from '@cycle/dom'
import {propEq, find} from 'ramda'

import {videoIconSvg, playIconSvg, pauseIconSvg} from './widgets/icons'
import icon from './widgets/icon'

export default function drawPrintersList (state) {
  const printers = table('.printersList', state.printing.printers
    .map(function (printer) {
      const isSelected = state.printing.activePrinterId === printer.id
      const isClaimed = printer.claimed
      const isPaused = true
      const activePrinter = find(propEq('id', state.printing.activePrinterId))(state.printing.printers)

      const printerName = printer.friendlyName ? printer.friendlyName : printer.name
      const printerText = isSelected ? `${printerName} ${state.printing.printerStatus.message}` : printerName

      const classes = classNames({'.selected': isSelected, '.printerL': true})

      /*const claimButtons = isClaimed // buttons to claim / unclaim printer
        ? button('.unClaim .claimed', {attrs: {'data-id': printer.id}}, 'unClaim')
        : button('.claim', {attrs: {'data-id': printer.id}}, 'claim')*/
      const claimToggler = isClaimed // buttons to claim / unclaim printer
        ? td('.unClaim .claimed', {attrs: {'data-id': printer.id}}, 'unClaim')
        : td('.claim', {attrs: {'data-id': printer.id}}, 'claim')

      const pauseResumeButton = isClaimed ? (isPaused ? icon(playIconSvg) : icon(pauseIconSvg)) : ''
      const videoFramesButton = isClaimed ? icon(videoIconSvg) : ''

      return tr(classes, {attrs: {'data-id': printer.id}}, [
        td([printerText]),
        td(['connected']),
        td([pauseResumeButton]),

        td([videoFramesButton]),

        td(['190°C']),
        td(['205°C']),
        td(['65°C']),

        td([
          span('.gnok', 'foobar')
        ]),
        claimToggler
      ])
    })
  )
  const noPrinters = table('.printersList', [
    tr([td('please wait fetching printers')])
  ])
  const printerSetup = section('', [
    state.printing.printers.length > 0 ? printers : noPrinters
  ])

  // console.log(activePrinter, state.activePrinter)
  const newPrintDisabled = state.buildplate.entities.length === 0 || state.printing.printerStatus.busy === true
  return printerSetup
}
<commit_msg>feat(printersList): stripped down printerslist to something more minimal<commit_after>import classNames from 'classnames'
import { div, span, button, li, ul, h2, section, table, th, tr, td, label } from '@cycle/dom'
import {propEq, find} from 'ramda'

import {videoIconSvg, playIconSvg, pauseIconSvg} from './widgets/icons'
import icon from './widgets/icon'

export default function drawPrintersList (state) {
  const printers = table('.printersList', state.printing.printers
    .map(function (printer) {
      const isSelected = state.printing.activePrinterId === printer.id
      const isClaimed = printer.claimed
      const isConnected = printer.claimed // FIXME: for now reusing claimed state
      const isPaused = true
      const activePrinter = find(propEq('id', state.printing.activePrinterId))(state.printing.printers)

      const printerName = printer.friendlyName ? printer.friendlyName : printer.name
      const printerText = isSelected ? `${printerName} ${state.printing.printerStatus.message}` : printerName

      const t0Temp = isConnected ? '190°C' : ''
      const t1Temp = isConnected ? '205°C' : ''
      const bedTemp = isConnected ? '65°C' : ''

      const classes = classNames({'.selected': isSelected, '.printerL': true})

      const claimToggler = isClaimed // buttons to claim / unclaim printer
        ? td('.claimer .unClaim .claimed', {attrs: {'data-id': printer.id}}, 'unClaim')
        : td('.claimer .claim', {attrs: {'data-id': printer.id}}, 'claim')

      const pauseResumeButton = isClaimed ? (isPaused ? icon(playIconSvg) : icon(pauseIconSvg)) : ''
      const videoFramesButton = isClaimed ? icon(videoIconSvg) : ''

      return tr(classes, {attrs: {'data-id': printer.id}}, [
        td(printerText),
        /*td(isConnected ? 'connected' : 'not connected'),
        td([pauseResumeButton]),

        td([videoFramesButton]),

        td(t0Temp),
        td(t1Temp),
        td(bedTemp),*/

        /*td([
          span('.gnok', 'foobar')
        ]),*/
        claimToggler
      ])
    })
  )
  const noPrinters = table('.printersList', [
    tr([td('please wait fetching printers')])
  ])
  const printerSetup = section('', [
    state.printing.printers.length > 0 ? printers : noPrinters
  ])

  // console.log(activePrinter, state.activePrinter)
  const newPrintDisabled = state.buildplate.entities.length === 0 || state.printing.printerStatus.busy === true
  return printerSetup
}
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";

var cp = require("child_process");
var fs = require("fs");

/**
 * Example use:
 *
 * var ports = require("./BBIO.js");
 * ports.SPI.enable(0);
 * ports.UART.enable(5);
 */

var BBIO = {
  /**
   * Gets the path to the bone_capemgr device.
   *
   * @return string
   *         For example, "/sys/devices/bone_capemgr.8/".
   */
  getCapeManager: function() {
    var path = "/sys/devices";
    var devices = fs.readdirSync(path);

    return devices.filter(function(s) {
      return s.indexOf("bone_capemgr") == 0;
    }).pop();
  },

  /**
   * Compiles and enables a device tree overlay.
   *
   * @param string capemgr
   *        The path to the bone_capemgr device.
   * @param string dts
   *        A device tree identifier, like "BB-SPI0-01" or "BB-UART1".
   */
  enable: function(capemgr, dts) {
    cp.exec("dtc -O dtb -o " + dts + "-00A0.dtbo -b 0 -@ " + dts + "-00A0.dts");
    cp.exec("cp " + dts + "-00A0.dtbo /lib/firmware/");
    try {
      fs.appendFileSync("/sys/devices/" + capemgr + "/slots", dts);
    } catch (e) {
      console.error(e);
    }
  }
};

BBIO.SPI = {
  /**
   * Enables the SPI ports on the BeagleBone Black.
   *
   * @param number index [optional]
   *        The SPI port to enable. Can be either 0 or 1 (there are only two
   *        SPI ports on the BeagleBone Black). If unspecified, both SPI ports
   *        will be enabled.
   */
  enable: function(index) {
    var capemgr = BBIO.getCapeManager();

    if (index == 0 || index === undefined) {
      BBIO.enable(capemgr, "BB-SPI0-01");
    }
    if (index == 1 || index === undefined) {
      BBIO.enable(capemgr, "BB-SPI1-01");
    }
  },
};

BBIO.UART = {
  /**
   * Enables the UART (serial tty*) ports on the BeagleBone Black.
   *
   * @param number index [optional]
   *        The UART port to enable. Can be either 1, 2, 4 or 5 (port 0 is
   *        enabled by default and has a dedicated header, while port 3 is
   *        sort of irrelevant as it can't receive data). If unspecified, all
   *        supported UART ports will be enabled.
   */
  enable: function(index) {
    var capemgr = BBIO.getCapeManager();

    if (index == 1 || index === undefined) {
      BBIO.enable(capemgr, "BB-UART1");
    }
    if (index == 2 || index === undefined) {
      BBIO.enable(capemgr, "BB-UART2");
    }
    if (index == 4 || index === undefined) {
      BBIO.enable(capemgr, "BB-UART4");
    }
    if (index == 5 || index === undefined) {
      BBIO.enable(capemgr, "BB-UART5");
    }
  }
};

module.exports = BBIO;
<commit_msg>Disallow enabling all SPI or all UART ports by default<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";

var cp = require("child_process");
var fs = require("fs");

/**
 * Example use:
 *
 * var ports = require("./BBIO.js");
 * ports.SPI.enable(0);
 * ports.UART.enable(5);
 */

var BBIO = {
  /**
   * Gets the path to the bone_capemgr device.
   *
   * @return string
   *         For example, "/sys/devices/bone_capemgr.8/".
   */
  getCapeManager: function() {
    var path = "/sys/devices";
    var devices = fs.readdirSync(path);

    return devices.filter(function(s) {
      return s.indexOf("bone_capemgr") == 0;
    }).pop();
  },

  /**
   * Compiles and enables a device tree overlay.
   *
   * @param string capemgr
   *        The path to the bone_capemgr device.
   * @param string dts
   *        A device tree identifier, like "BB-SPI0-01" or "BB-UART1".
   */
  enable: function(capemgr, dts) {
    cp.exec("dtc -O dtb -o " + dts + "-00A0.dtbo -b 0 -@ " + dts + "-00A0.dts");
    cp.exec("cp " + dts + "-00A0.dtbo /lib/firmware/");
    try {
      fs.appendFileSync("/sys/devices/" + capemgr + "/slots", dts);
    } catch (e) {
      console.error(e);
    }
  }
};

BBIO.SPI = {
  /**
   * Enables the SPI ports on the BeagleBone Black.
   *
   * @param number index
   *        The SPI port to enable. Can be either 0 or 1 (there are only two
   *        SPI ports on the BeagleBone Black).
   */
  enable: function(index) {
    var capemgr = BBIO.getCapeManager();

    if (index == 0) {
      BBIO.enable(capemgr, "BB-SPI0-01");
    }
    else if (index == 1) {
      BBIO.enable(capemgr, "BB-SPI1-01");
    }
  },
};

BBIO.UART = {
  /**
   * Enables the UART (serial tty*) ports on the BeagleBone Black.
   *
   * @param number index
   *        The UART port to enable. Can be either 1, 2, 4 or 5 (port 0 is
   *        enabled by default and has a dedicated header, while port 3 is
   *        sort of irrelevant as it can't receive data).
   */
  enable: function(index) {
    var capemgr = BBIO.getCapeManager();

    if (index == 1) {
      BBIO.enable(capemgr, "BB-UART1");
    }
    else if (index == 2) {
      BBIO.enable(capemgr, "BB-UART2");
    }
    else if (index == 4) {
      BBIO.enable(capemgr, "BB-UART4");
    }
    else if (index == 5) {
      BBIO.enable(capemgr, "BB-UART5");
    }
  }
};

module.exports = BBIO;
<|endoftext|>


<commit_before>'use strict';

//////////////////////////////
// Requires
//////////////////////////////

const autoprefixer = require('gulp-autoprefixer');
const browserSync = require('browser-sync').create();
const nodemon = require('gulp-nodemon');
const concat = require('gulp-concat');
const del = require('del');
const gulp = require('gulp');
const jshint = require('gulp-jshint');
const lazypipe = require('lazypipe');
const merge = require('merge-stream');
const plumber = require('gulp-plumber');
const rename = require('gulp-rename');
const replace = require('gulp-replace');
const runSequence = require('run-sequence');
const sass = require('gulp-sass');
const sassLint = require('gulp-sass-lint');
const stylish = require('jshint-stylish');
const uglify = require('gulp-uglify');
const sourcemaps = require('gulp-sourcemaps');
const webpack = require('webpack');
const gutil = require('gulp-util');

//////////////////////////////
// Variables
//////////////////////////////

const PATHS = {
  static: 'static',
  clean: [
    'static/**/*.{css,woff,woff2,png,svg,jpeg,js,map}',
    '_styles.scss'
  ],
  scripts: {
    all: [
      'base-elements/**/*.js',
      'components/**/*.js',
      'app.js'
    ],
    main: 'app.js'
  },
  scss: {
    all: [
      'base-elements/**/*.scss',
      'components/**/*.scss',
      '*.scss'
    ],
    main: 'dev.scss'
  },
  html: './**/*.html',
  images: 'images/**/*.{png,jpeg,jpg,svg}'
}

const importPaths = {
  icons: '../bluemix-icons/icons',
  ibmColors: '../IBM-Design-Colors/ibm-colors'
}

//////////////////////////////
// BrowserSync + Nodemon
//////////////////////////////

gulp.task('browser-sync', function() {
  browserSync.init({
    logPrefix: "Bluemix Components",
    open: false,
    proxy: 'localhost:8080'
  });
});

gulp.task('nodemon', function() {
  nodemon({
    script: 'server.js',
    ext: 'dust',
  });
});

process.once('SIGINT', function() {
  process.exit(0);
})

//////////////////////////////
// Clean
//////////////////////////////

gulp.task('clean', function() {
  return del(PATHS.clean);
});

//////////////////////////////
// JavaScript Tasks
//////////////////////////////

gulp.task('scripts', function(cb) {
  webpack({
    devtool: 'source-maps',
    entry: './app.js',
    output: {
      path: PATHS.static + '/js',
      filename: 'bundle.js'
    },
    module: {
      loaders: [
        {
          test: /\.js?$/,
          exclude: /node_modules/,
          loaders: ['babel'],
        },
      ],
    },
  }, function(err, stats) {
    if (err) throw new gutil.PluginError('webpack', err);
    gutil.log('[webpack]', stats.toString({
      progress: true,
      colors: true
    }));
    browserSync.reload();
    cb();
  });
});

//////////////////////////////
// Sass Tasks
//////////////////////////////

gulp.task('sass', function() {

  var compile = gulp.src(PATHS.scss.all)
    .pipe(sourcemaps.init())
    .pipe(sass().on('error', sass.logError))
    .pipe(autoprefixer({
      browsers: ['> 1%', 'last 2 versions']
    }))
    .pipe(sourcemaps.write())
    .pipe(gulp.dest(PATHS.static + '/css'))
    .pipe(browserSync.stream());

  var bower = gulp.src(PATHS.scss.main)
    .pipe(replace('bower_components/bluemix-icons/icons', importPaths.icons))
    .pipe(replace('bower_components/IBM-Design-Colors/ibm-colors', importPaths.ibmColors))
    .pipe(rename('_styles.scss'))
    .pipe(gulp.dest('.'));

  return merge(compile, bower);
});

/////////////////////////////
// Sass Linter
// This is a WIP -- usage may break
// until SassLint is updated > 1.3.3
/////////////////////////////

gulp.task('sass-lint', function() {
  gulp.src(PATHS.scss.all)
    .pipe(sassLint())
    .pipe(sassLint.format())
    .pipe(sassLint.failOnError());
});

/////////////////////////////
// Copy
/////////////////////////////

gulp.task('copy:fonts', function() {
  let fonts = 'global/fonts/*.{woff,woff2}';

  return gulp.src(fonts)
    .pipe(gulp.dest(PATHS.static + '/css'));
});

gulp.task('copy:images', function() {
  return gulp.src(PATHS.images)
    .pipe(gulp.dest(PATHS.static + '/images'));
});

gulp.task('copy', ['copy:fonts', 'copy:images']);

//////////////////////////////
// Running Tasks
//////////////////////////////

gulp.task('watch', function() {
  gulp.watch(PATHS.html).on('change', browserSync.reload);
  gulp.watch(PATHS.scripts.all, ['scripts']);
  gulp.watch(PATHS.scss.all, ['sass']);
});

gulp.task('build', function () {
  runSequence('clean', ['sass', 'scripts', 'copy']);
});

gulp.task('default', function () {
  runSequence('build', 'nodemon', ['browser-sync', 'watch']);
});
<commit_msg>nodemon watches for restart event to fix #505<commit_after>'use strict';

//////////////////////////////
// Requires
//////////////////////////////

const autoprefixer = require('gulp-autoprefixer');
const browserSync = require('browser-sync').create();
const nodemon = require('gulp-nodemon');
const concat = require('gulp-concat');
const del = require('del');
const gulp = require('gulp');
const jshint = require('gulp-jshint');
const lazypipe = require('lazypipe');
const merge = require('merge-stream');
const plumber = require('gulp-plumber');
const rename = require('gulp-rename');
const replace = require('gulp-replace');
const runSequence = require('run-sequence');
const sass = require('gulp-sass');
const sassLint = require('gulp-sass-lint');
const stylish = require('jshint-stylish');
const uglify = require('gulp-uglify');
const sourcemaps = require('gulp-sourcemaps');
const webpack = require('webpack');
const gutil = require('gulp-util');

//////////////////////////////
// Variables
//////////////////////////////

const PATHS = {
  static: 'static',
  clean: [
    'static/**/*.{css,woff,woff2,png,svg,jpeg,js,map}',
    '_styles.scss'
  ],
  scripts: {
    all: [
      'base-elements/**/*.js',
      'components/**/*.js',
      'app.js'
    ],
    main: 'app.js'
  },
  scss: {
    all: [
      'base-elements/**/*.scss',
      'components/**/*.scss',
      '*.scss'
    ],
    main: 'dev.scss'
  },
  html: './**/*.html',
  images: 'images/**/*.{png,jpeg,jpg,svg}'
}

const importPaths = {
  icons: '../bluemix-icons/icons',
  ibmColors: '../IBM-Design-Colors/ibm-colors'
}

//////////////////////////////
// BrowserSync + Nodemon
//////////////////////////////

gulp.task('browser-sync', function() {
  browserSync.init({
    logPrefix: "Bluemix Components",
    open: false,
    proxy: 'localhost:8080',
    reloadDelay: 500
  });
});

gulp.task('nodemon', function() {
  nodemon({
    script: 'server.js',
    ext: 'dust',
  }).on('restart', () => {
    browserSync.reload;
  });
});

process.once('SIGINT', function() {
  process.exit(0);
})

//////////////////////////////
// Clean
//////////////////////////////

gulp.task('clean', function() {
  return del(PATHS.clean);
});

//////////////////////////////
// JavaScript Tasks
//////////////////////////////

gulp.task('scripts', function(cb) {
  webpack({
    devtool: 'source-maps',
    entry: './app.js',
    output: {
      path: PATHS.static + '/js',
      filename: 'bundle.js'
    },
    module: {
      loaders: [
        {
          test: /\.js?$/,
          exclude: /node_modules/,
          loaders: ['babel'],
        },
      ],
    },
  }, function(err, stats) {
    if (err) throw new gutil.PluginError('webpack', err);
    gutil.log('[webpack]', stats.toString({
      progress: true,
      colors: true
    }));
    browserSync.reload();
    cb();
  });
});

//////////////////////////////
// Sass Tasks
//////////////////////////////

gulp.task('sass', function() {

  var compile = gulp.src(PATHS.scss.all)
    .pipe(sourcemaps.init())
    .pipe(sass().on('error', sass.logError))
    .pipe(autoprefixer({
      browsers: ['> 1%', 'last 2 versions']
    }))
    .pipe(sourcemaps.write())
    .pipe(gulp.dest(PATHS.static + '/css'))
    .pipe(browserSync.stream());

  var bower = gulp.src(PATHS.scss.main)
    .pipe(replace('bower_components/bluemix-icons/icons', importPaths.icons))
    .pipe(replace('bower_components/IBM-Design-Colors/ibm-colors', importPaths.ibmColors))
    .pipe(rename('_styles.scss'))
    .pipe(gulp.dest('.'));

  return merge(compile, bower);
});

/////////////////////////////
// Sass Linter
// This is a WIP -- usage may break
// until SassLint is updated > 1.3.3
/////////////////////////////

gulp.task('sass-lint', function() {
  gulp.src(PATHS.scss.all)
    .pipe(sassLint())
    .pipe(sassLint.format())
    .pipe(sassLint.failOnError());
});

/////////////////////////////
// Copy
/////////////////////////////

gulp.task('copy:fonts', function() {
  let fonts = 'global/fonts/*.{woff,woff2}';

  return gulp.src(fonts)
    .pipe(gulp.dest(PATHS.static + '/css'));
});

gulp.task('copy:images', function() {
  return gulp.src(PATHS.images)
    .pipe(gulp.dest(PATHS.static + '/images'));
});

gulp.task('copy', ['copy:fonts', 'copy:images']);

//////////////////////////////
// Running Tasks
//////////////////////////////

gulp.task('watch', function() {
  gulp.watch(PATHS.html).on('change', browserSync.reload);
  gulp.watch(PATHS.scripts.all, ['scripts']);
  gulp.watch(PATHS.scss.all, ['sass']);
});

gulp.task('build', function () {
  runSequence('clean', ['sass', 'scripts', 'copy']);
});

gulp.task('default', function () {
  runSequence('build', 'nodemon', ['browser-sync', 'watch']);
});
<|endoftext|>