<commit_before>var exec = require('child_process').exec;
var SerialPort = require("serialport").SerialPort
var serialPort = new SerialPort("/dev/ttyAMA0", {
  baudrate: 19200
}, false); // this is the openImmediately flag [default is true]

function schrijflcd(tekst,cb) {
  serialPort.open(function(error) {
    if (error) {
      console.log('failed to open: ' + error);
    } else {
      console.log('open');
      serialPort.on('data', function(data) {
        console.log('data received: ' + data);
      });
      serialPort.write(String.fromCharCode(17), function(err, results) {
        serialPort.write(String.fromCharCode(12), function(err, results) {
          serialPort.write(tekst, function(err, results) {
            //serialPort.close();
            if (cb) cb();
          });
        });
      });
    }
  });
}

var lidstatus = "closed";

function beweeglid(command, cb) {
  var richting = "";
  switch (command) {
    case 'open':
      if (lidstatus !== 'closed') {
        console.log('nope -lid is open');
        return;
      }
      doelid("1", function() {
        console.log('opened');
        lidstatus = 'opened';
        cb();
      });
      break;
    case 'close':
      if (lidstatus !== 'opened') {
        console.log('nope - lid is closed');
        return;
      }
      doelid("0", function() {
        cb();
        lidstatus = 'closed';
      });
      break;
  }
}

function doelid(command, cb) {
  child = exec("./motor 730 0 " + command, function(error, stdout, stderr) {
    if (error !== null) {
      console.log('exec error: ' + error);
    }
    console.log('command finished', command);
    cb();
  });
}

var mqtt    = require('mqtt');
var client  = mqtt.connect('ws://opantwerpen.be:15674');
var Web3 = require('web3');

var host = "http://192.168.1.22:8545";

var contractabi = {"bytecode":"60606040526000805560018054600160a060020a0319163317905560f6806100276000396000f3606060405260e060020a600035046333ac20098114602e57806384394e6f146037578063fa52c7d8146060575b005b60776000545b90565b6077600160a060020a033316600090815260026020526040812054600114156089575060016034565b607760043560026020526000908152604090205481565b60408051918252519081900360200190f35b6040812060019081905581548101825554600160a060020a03168134606082818181858883f1505060408051600160a060020a033316815290517fc950a438e6ad1cf066a2ec63cd7e6753ed8e6fe1d55949e889204d0f0230a23f94509081900360200192509050a1603456","abi":[{"constant":true,"inputs":[],"name":"countValidations","outputs":[{"name":"count","type":"uint256"}],"type":"function"},{"constant":false,"inputs":[],"name":"addValidation","outputs":[{"name":"returnCode","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"validators","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"inputs":[],"type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"name":"validator","type":"address"}],"name":"ValidationAdded","type":"event"}]};

web3 = new Web3();
web3.setProvider(new web3.providers.HttpProvider(host));

client.on('connect', function () {
  client.subscribe('poezendoos');
  client.publish('poezendoos', 'Poezendoos online!');
});

generateCode(function(code){
  client.subscribe('poezendoos/'+code);
  client.publish('poezendoos/'+code, 'command|listening');
  schrijflcd("   poezendoos"+String.fromCharCode(13)+"     "+code);
});

client.on('message', function (topic, message) {
  // message is Buffer
  //console.log(message.toString());
  var msg = message.toString();

  var commandarray = msg.split("|");

  console.log(commandarray);
  // Check command and do something
  if(commandarray[0]==='checkContract'){
    var contractaddress = commandarray[1];
    var pincode = commandarray[2];

    schrijflcd(" de poezendoos "+String.fromCharCode(13)+" kijkt het na...");

    checkContract(contractaddress, function(result){
      console.log("ik heb een result: ", result);
      if (result>1){
        schrijflcd('u heeft ' + result + ' validaties');
        openDoor();
        client.publish(pincode, 'doosisopen');
      }else{
        schrijflcd('u heeft ' + result + ' validaties. Dat is niet genoeg');
      }
    });
    // check if the contract is valid.
    // checkContract(contractaddress, useraccount, function(result){
    //  if(result){
    //    openDoor();
    //  }
    // });
  };
  if(commandarray[0]==='sluitDoos'){
    console.log('doos gaat dicht.');
    closeDoor();
  }

  //client.end();

});

function openDoor(){

beweeglid('open', function() {
  schrijflcd('de doos is open');
});

};

function closeDoor(){
  beweeglid('close', function() {
    schrijflcd('de doos is terug toe');
    console.log('closed');
    generateCode(function(code){
  client.subscribe('poezendoos/'+code);
  client.publish('poezendoos/'+code, 'command|listening');
  schrijflcd("   poezendoos"+String.fromCharCode(13)+"     "+code);
});
  });
};

function generateCode(fn){
  var code = Math.floor(Math.random()*90000) + 10000;
  console.log(code);
  fn(code);
};

function checkContract(contractaddress, fn){
  console.log("Checking contract: ", contractaddress);
  console.log("Checking balance: ", web3.eth.getBalance(contractaddress).toNumber(10));
  var MyContract = web3.eth.contract(contractabi.abi);
  console.log("Mycontract: ", MyContract);
  var myContractInstance = MyContract.at(contractaddress);
  var result = myContractInstance.countValidations().toNumber(10);
  console.log("Result: ", result);
  fn(result);
};<commit_msg>host changed...<commit_after>var exec = require('child_process').exec;
var SerialPort = require("serialport").SerialPort
var serialPort = new SerialPort("/dev/ttyAMA0", {
  baudrate: 19200
}, false); // this is the openImmediately flag [default is true]
var host = "http://kingflurkel.dtdns.net:8545";

function schrijflcd(tekst,cb) {
  serialPort.open(function(error) {
    if (error) {
      console.log('failed to open: ' + error);
    } else {
      console.log('open');
      serialPort.on('data', function(data) {
        console.log('data received: ' + data);
      });
      serialPort.write(String.fromCharCode(17), function(err, results) {
        serialPort.write(String.fromCharCode(12), function(err, results) {
          serialPort.write(tekst, function(err, results) {
            //serialPort.close();
            if (cb) cb();
          });
        });
      });
    }
  });
}

var lidstatus = "closed";

function beweeglid(command, cb) {
  var richting = "";
  switch (command) {
    case 'open':
      if (lidstatus !== 'closed') {
        console.log('nope -lid is open');
        return;
      }
      doelid("1", function() {
        console.log('opened');
        lidstatus = 'opened';
        cb();
      });
      break;
    case 'close':
      if (lidstatus !== 'opened') {
        console.log('nope - lid is closed');
        return;
      }
      doelid("0", function() {
        cb();
        lidstatus = 'closed';
      });
      break;
  }
}

function doelid(command, cb) {
  child = exec("./motor 730 0 " + command, function(error, stdout, stderr) {
    if (error !== null) {
      console.log('exec error: ' + error);
    }
    console.log('command finished', command);
    cb();
  });
}

var mqtt    = require('mqtt');
var client  = mqtt.connect('ws://opantwerpen.be:15674');
var Web3 = require('web3');

var contractabi = {"bytecode":"60606040526000805560018054600160a060020a0319163317905560f6806100276000396000f3606060405260e060020a600035046333ac20098114602e57806384394e6f146037578063fa52c7d8146060575b005b60776000545b90565b6077600160a060020a033316600090815260026020526040812054600114156089575060016034565b607760043560026020526000908152604090205481565b60408051918252519081900360200190f35b6040812060019081905581548101825554600160a060020a03168134606082818181858883f1505060408051600160a060020a033316815290517fc950a438e6ad1cf066a2ec63cd7e6753ed8e6fe1d55949e889204d0f0230a23f94509081900360200192509050a1603456","abi":[{"constant":true,"inputs":[],"name":"countValidations","outputs":[{"name":"count","type":"uint256"}],"type":"function"},{"constant":false,"inputs":[],"name":"addValidation","outputs":[{"name":"returnCode","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"validators","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"inputs":[],"type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"name":"validator","type":"address"}],"name":"ValidationAdded","type":"event"}]};

web3 = new Web3();
web3.setProvider(new web3.providers.HttpProvider(host));

client.on('connect', function () {
  client.subscribe('poezendoos');
  client.publish('poezendoos', 'Poezendoos online!');
});

generateCode(function(code){
  client.subscribe('poezendoos/'+code);
  client.publish('poezendoos/'+code, 'command|listening');
  schrijflcd("   poezendoos"+String.fromCharCode(13)+"     "+code);
});

client.on('message', function (topic, message) {
  // message is Buffer
  //console.log(message.toString());
  var msg = message.toString();

  var commandarray = msg.split("|");

  console.log(commandarray);
  // Check command and do something
  if(commandarray[0]==='checkContract'){
    var contractaddress = commandarray[1];
    var pincode = commandarray[2];

    schrijflcd(" de poezendoos "+String.fromCharCode(13)+" kijkt het na...");

    checkContract(contractaddress, function(result){
      console.log("ik heb een result: ", result);
      if (result>1){
        schrijflcd('u heeft ' + result + ' validaties');
        openDoor();
        client.publish(pincode, 'doosisopen');
      }else{
        schrijflcd('u heeft ' + result + ' validaties. Dat is niet genoeg');
      }
    });
    // check if the contract is valid.
    // checkContract(contractaddress, useraccount, function(result){
    //  if(result){
    //    openDoor();
    //  }
    // });
  };
  if(commandarray[0]==='sluitDoos'){
    console.log('doos gaat dicht.');
    closeDoor();
  }

  //client.end();

});

function openDoor(){

beweeglid('open', function() {
  schrijflcd('de doos is open');
});

};

function closeDoor(){
  beweeglid('close', function() {
    schrijflcd('de doos is terug toe');
    console.log('closed');
    generateCode(function(code){
  client.subscribe('poezendoos/'+code);
  client.publish('poezendoos/'+code, 'command|listening');
  schrijflcd("   poezendoos"+String.fromCharCode(13)+"     "+code);
});
  });
};

function generateCode(fn){
  var code = Math.floor(Math.random()*90000) + 10000;
  console.log(code);
  fn(code);
};

function checkContract(contractaddress, fn){
  console.log("Checking contract: ", contractaddress);
  console.log("Checking balance: ", web3.eth.getBalance(contractaddress).toNumber(10));
  var MyContract = web3.eth.contract(contractabi.abi);
  console.log("Mycontract: ", MyContract);
  var myContractInstance = MyContract.at(contractaddress);
  var result = myContractInstance.countValidations().toNumber(10);
  console.log("Result: ", result);
  fn(result);
};<|endoftext|>


<commit_before>/**
 * React Starter Kit (https://www.reactstarterkit.com/)
 *
 * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */

import React, { PropTypes } from 'react';
import Helmet from 'react-helmet';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import RaisedButton from 'material-ui/RaisedButton';
import Layout from '../../components/Layout';
import Link from '../../components/Link';
import {Logo} from '../../components/Pictos';
import s from './Home.css';
// import theme from '../../components/theme';

function Home() {
  return (
    <Layout>
      <Helmet title="Accueil | Dérangeons la Chambre"/>

            <Logo style={{width:500, height: 'auto'}}/>

Dérangeons la Chambre

Assemblée Nationale : si on changeait les règles du jeu ?

          <Link to="/%C3%A9tude/introduction">
            <RaisedButton label="Dérangez la chambre"
              primary={true} style={{background:'none'}} overlayStyle={{ lineHeight: '30px'}}/>
          </Link>

    </Layout>
  );
}

Home.propTypes = {};

export default withStyles(s)(Home);
<commit_msg>Add nbsp; to avoid breaking in home title<commit_after>/**
 * React Starter Kit (https://www.reactstarterkit.com/)
 *
 * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */

import React, { PropTypes } from 'react';
import Helmet from 'react-helmet';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import RaisedButton from 'material-ui/RaisedButton';
import Layout from '../../components/Layout';
import Link from '../../components/Link';
import {Logo} from '../../components/Pictos';
import s from './Home.css';
// import theme from '../../components/theme';

function Home() {
  return (
    <Layout>
      <Helmet title="Accueil | Dérangeons la Chambre"/>

            <Logo style={{width:500, height: 'auto'}}/>

Dérangeons la Chambre

Assemblée Nationale : si on changeait les règles du jeu ?

          <Link to="/%C3%A9tude/introduction">
            <RaisedButton label="Dérangez la chambre"
              primary={true} style={{background:'none'}} overlayStyle={{ lineHeight: '30px'}}/>
          </Link>

    </Layout>
  );
}

Home.propTypes = {};

export default withStyles(s)(Home);
<|endoftext|>


<commit_before>/** @license
 * Copyright 2016 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

/**
 * @fileoverview Shaka Player demo, service worker.
 */

/**
 * The name of the cache for this version of the application.
 * This should be updated when old, unneeded application resources could be
 * cleaned up by a newer version of the application.
 *
 * @const {string}
 */
const CACHE_NAME = 'shaka-player-v2.5+';

/**
 * The prefix of all cache versions that belong to this application.
 * This is used to identify old caches to clean up.  Must match CACHE_NAME
 * above.
 *
 * @const {string}
 */
const CACHE_NAME_PREFIX = 'shaka-player';

console.assert(CACHE_NAME.startsWith(CACHE_NAME_PREFIX),
    'Cache name does not match prefix!');

/**
 * The maximum number of seconds to wait for an updated version of something
 * if we have a cached version we could use instead.
 *
 * @const {number}
 */
const NETWORK_TIMEOUT = 2;

/**
 * An array of resources that MUST be cached to make the application
 * available offline.
 *
 * @const {!Array.<string>}
 */
const CRITICAL_RESOURCES = [
  '.',  // This resolves to the page.
  'index.html',  // Another way to access the page.
  'app_manifest.json',
  'shaka_logo_trans.png',

  'load.js',
  '../dist/shaka-player.ui.js',
  '../dist/demo.compiled.js',
  '../dist/controls.css',
  '../dist/demo.css',

  // These files are required for the demo to include MDL.
  '../node_modules/material-design-lite/dist/material.min.js',

  // MDL modal dialogs are enabled by including these:
  '../node_modules/dialog-polyfill/dist/dialog-polyfill.js',

  // Datalist-like fields are enabled by including these:
  '../node_modules/awesomplete/awesomplete.min.js',

  // Tooltips are enabled by including these:
  '../node_modules/tippy.js/umd/index.min.js',
  '../node_modules/popper.js/dist/umd/popper.min.js',

  // PWA compatibility for iOS:
  '../node_modules/pwacompat/pwacompat.min.js',
];

/**
 * An array of resources that SHOULD be cached, but which are not critical.
 *
 * The application does not need to read these, so these can use the no-cors
 * flag and be cached as "opaque" resources.  This is critical for the cast
 * sender SDK below.
 *
 * @const {!Array.<string>}
 */
const OPTIONAL_RESOURCES = [
  // Optional graphics.  Without these, the site won't be broken.
  'favicon.ico',
  'https://shaka-player-demo.appspot.com/assets/poster.jpg',
  'https://shaka-player-demo.appspot.com/assets/audioOnly.gif',

  // The mux.js transmuxing library for MPEG-2 TS and CEA support.
  '../node_modules/mux.js/dist/mux.min.js',

  // The cast sender SDK.
  'https://www.gstatic.com/cv/js/sender/v1/cast_sender.js',

  // The IMA ads SDK.
  'http://imasdk.googleapis.com/js/sdkloader/ima3.js',
  'http://imasdk.googleapis.com/js/sdkloader/ima3_dai.js',
];

/**
 * An array of URI prefixes.  Matching resources SHOULD be cached whenever seen
 * and SHOULD be served from cache first without waiting for updated versions
 * from the network.
 *
 * @const {!Array.<string>}
 */
const CACHEABLE_URL_PREFIXES = [
  // Anything associated with this application is fair game to cache.
  // This would not be necessary if this demo were always served from the same
  // location and always used absolute URLs in the resources lists above.
  location.origin,

  // Google Web Fonts should be cached when first seen, without being explicitly
  // listed, and should be preferred from cache for speed.
  'https://fonts.gstatic.com/',
  // Same goes for asset icons.
  'https://storage.googleapis.com/shaka-asset-icons/',
];

/**
 * This event fires when the service worker is installed.
 *
 * @param {!InstallEvent} event
 */
function onInstall(event) {
  const preCacheApplication = async () => {
    const cache = await caches.open(CACHE_NAME);
    // Fetching these with addAll fails for CORS-restricted content, so we use
    // fetchAndCache with no-cors mode to work around it.

    // Optional resources: failure on these will NOT fail the Promise chain.
    // We will also not wait for them to be installed.
    for (const url of OPTIONAL_RESOURCES) {
      const request = new Request(url, {mode: 'no-cors'});
      fetchAndCache(cache, request).catch(() => {});
    }

    // Critical resources: failure on these will fail the Promise chain.
    // The installation will not be complete until these are all cached.
    const criticalFetches = [];
    for (const url of CRITICAL_RESOURCES) {
      const request = new Request(url, {mode: 'no-cors'});
      criticalFetches.push(fetchAndCache(cache, request));
    }
    return Promise.all(criticalFetches);
  };

  event.waitUntil(preCacheApplication());
}

/**
 * This event fires when the service worker is activated.
 * This can be after installation or upgrade.
 *
 * @param {!ExtendableEvent} event
 */
function onActivate(event) {
  // Delete old caches to save space.
  const dropOldCaches = async () => {
    const cacheNames = await caches.keys();

    // Return true on all the caches we want to clean up.
    // Note that caches are shared across the origin, so only remove
    // caches we are sure we created.
    const cleanTheseUp = cacheNames.filter((cacheName) =>
      cacheName.startsWith(CACHE_NAME_PREFIX) && cacheName != CACHE_NAME);

    const cleanUpPromises =
        cleanTheseUp.map((cacheName) => caches.delete(cacheName));

    await Promise.all(cleanUpPromises);
  };

  event.waitUntil(dropOldCaches());
}

/**
 * This event fires when any resource is fetched.
 * This is where we can use the cache to respond offline.
 *
 * @param {!FetchEvent} event
 */
function onFetch(event) {
  // For some reason, on a page load, we get hash parameters in the URL for this
  // event.  The hash should not be used when we do any of the lookups below.
  const url = event.request.url.split('#')[0];

  // Make sure this is a request we should be handling in the first place.
  // If it's not, it's important to leave it alone and not call respondWith.
  let useCache = false;
  for (const prefix of CACHEABLE_URL_PREFIXES) {
    if (url.startsWith(prefix)) {
      useCache = true;
      break;
    }
  }

  // Now we need to check our resource lists.  The list of prefixes above won't
  // cover everything that was installed initially, and those things still need
  // to be read from cache.  So we check if this request URL matches one of
  // those lists.
  // The resource lists contain some relative URLs and some absolute URLs.  The
  // check here will only be able to match the absolute ones, but that's enough,
  // because the relative ones are covered by the loop above.
  if (!useCache) {
    if (CRITICAL_RESOURCES.includes(url) ||
        OPTIONAL_RESOURCES.includes(url)) {
      useCache = true;
    }
  }

  if (useCache) {
    event.respondWith(fetchCacheableResource(event.request));
  }
}

/**
 * Fetch a cacheable resource.  Decide whether to request from the network,
 * the cache, or both, and return the appropriate version of the resource.
 *
 * @param {!Request} request
 * @return {!Promise.<!Response>}
 */
async function fetchCacheableResource(request) {
  const cache = await caches.open(CACHE_NAME);
  const cachedResponse = await cache.match(request);

  if (!navigator.onLine) {
    // We are offline, and we know it.  Just return the cached response, to
    // avoid a bunch of pointless errors in the JS console that will confuse
    // us developers.  If there is no cached response, this will just be a
    // failed request.
    return cachedResponse;
  }

  if (cachedResponse) {
    // We have it in cache.  Try to fetch a live version and update the cache,
    // but limit how long we will wait for the updated version.
    try {
      return await timeout(NETWORK_TIMEOUT, fetchAndCache(cache, request));
    } catch (error) {
      // We tried to fetch a live version, but it either failed or took too
      // long.  If it took too long, the fetch and cache operation will continue
      // in the background.  In both cases, we should go ahead with a cached
      // version.
      return cachedResponse;
    }
  } else {
    // We should have this in cache, but we don't.  Fetch and cache a fresh
    // copy and then return it.
    return fetchAndCache(cache, request);
  }
}

/**
 * Fetch the resource from the network, then store this new version in the
 * cache.
 *
 * @param {!Cache} cache
 * @param {!Request} request
 * @return {!Promise.<!Response>}
 */
async function fetchAndCache(cache, request) {
  const response = await fetch(request);
  cache.put(request, response.clone());
  return response;
}

/**
 * Returns a Promise which is resolved only if |asyncProcess| is resolved, and
 * only if it is resolved in less than |seconds| seconds.
 *
 * If the returned Promise is resolved, it returns the same value as
 * |asyncProcess|.
 *
 * If |asyncProcess| fails, the returned Promise is rejected.
 * If |asyncProcess| takes too long, the returned Promise is rejected, but
 * |asyncProcess| is still allowed to complete.
 *
 * @param {number} seconds
 * @param {!Promise.<T>} asyncProcess
 * @return {!Promise.<T>}
 * @template T
 */
function timeout(seconds, asyncProcess) {
  return Promise.race([
    asyncProcess,
    new Promise(((_, reject) => {
      setTimeout(reject, seconds * 1000);
    })),
  ]);
}

self.addEventListener('install', /** @type {function(!Event)} */(onInstall));
self.addEventListener('activate', /** @type {function(!Event)} */(onActivate));
self.addEventListener('fetch', /** @type {function(!Event)} */(onFetch));
<commit_msg>Convert relative URL list to absolute in service worker<commit_after>/** @license
 * Copyright 2016 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

/**
 * @fileoverview Shaka Player demo, service worker.
 */

/**
 * The name of the cache for this version of the application.
 * This should be updated when old, unneeded application resources could be
 * cleaned up by a newer version of the application.
 *
 * @const {string}
 */
const CACHE_NAME = 'shaka-player-v2.5+';

/**
 * The prefix of all cache versions that belong to this application.
 * This is used to identify old caches to clean up.  Must match CACHE_NAME
 * above.
 *
 * @const {string}
 */
const CACHE_NAME_PREFIX = 'shaka-player';

console.assert(CACHE_NAME.startsWith(CACHE_NAME_PREFIX),
    'Cache name does not match prefix!');

/**
 * The maximum number of seconds to wait for an updated version of something
 * if we have a cached version we could use instead.
 *
 * @const {number}
 */
const NETWORK_TIMEOUT = 2;

/**
 * An array of resources that MUST be cached to make the application
 * available offline.
 *
 * @const {!Array.<string>}
 */
const CRITICAL_RESOURCES = [
  '.',  // This resolves to the page.
  'index.html',  // Another way to access the page.
  'app_manifest.json',
  'shaka_logo_trans.png',

  'load.js',
  '../dist/shaka-player.ui.js',
  '../dist/demo.compiled.js',
  '../dist/controls.css',
  '../dist/demo.css',

  // These files are required for the demo to include MDL.
  '../node_modules/material-design-lite/dist/material.min.js',

  // MDL modal dialogs are enabled by including these:
  '../node_modules/dialog-polyfill/dist/dialog-polyfill.js',

  // Datalist-like fields are enabled by including these:
  '../node_modules/awesomplete/awesomplete.min.js',

  // Tooltips are enabled by including these:
  '../node_modules/tippy.js/umd/index.min.js',
  '../node_modules/popper.js/dist/umd/popper.min.js',

  // PWA compatibility for iOS:
  '../node_modules/pwacompat/pwacompat.min.js',
].map(resolveRelativeUrl);

/**
 * An array of resources that SHOULD be cached, but which are not critical.
 *
 * The application does not need to read these, so these can use the no-cors
 * flag and be cached as "opaque" resources.  This is critical for the cast
 * sender SDK below.
 *
 * @const {!Array.<string>}
 */
const OPTIONAL_RESOURCES = [
  // Optional graphics.  Without these, the site won't be broken.
  'favicon.ico',
  'https://shaka-player-demo.appspot.com/assets/poster.jpg',
  'https://shaka-player-demo.appspot.com/assets/audioOnly.gif',

  // The mux.js transmuxing library for MPEG-2 TS and CEA support.
  '../node_modules/mux.js/dist/mux.min.js',

  // The cast sender SDK.
  'https://www.gstatic.com/cv/js/sender/v1/cast_sender.js',

  // The IMA ads SDK.
  'http://imasdk.googleapis.com/js/sdkloader/ima3.js',
  'http://imasdk.googleapis.com/js/sdkloader/ima3_dai.js',
].map(resolveRelativeUrl);

/**
 * An array of URI prefixes.  Matching resources SHOULD be cached whenever seen
 * and SHOULD be served from cache first without waiting for updated versions
 * from the network.
 *
 * @const {!Array.<string>}
 */
const CACHEABLE_URL_PREFIXES = [
  // Anything associated with this application is fair game to cache.
  // This would not be necessary if this demo were always served from the same
  // location and always used absolute URLs in the resources lists above.
  location.origin,

  // Google Web Fonts should be cached when first seen, without being explicitly
  // listed, and should be preferred from cache for speed.
  'https://fonts.gstatic.com/',
  // Same goes for asset icons.
  'https://storage.googleapis.com/shaka-asset-icons/',
];

/**
 * This event fires when the service worker is installed.
 *
 * @param {!InstallEvent} event
 */
function onInstall(event) {
  const preCacheApplication = async () => {
    const cache = await caches.open(CACHE_NAME);
    // Fetching these with addAll fails for CORS-restricted content, so we use
    // fetchAndCache with no-cors mode to work around it.

    // Optional resources: failure on these will NOT fail the Promise chain.
    // We will also not wait for them to be installed.
    for (const url of OPTIONAL_RESOURCES) {
      const request = new Request(url, {mode: 'no-cors'});
      fetchAndCache(cache, request).catch(() => {});
    }

    // Critical resources: failure on these will fail the Promise chain.
    // The installation will not be complete until these are all cached.
    const criticalFetches = [];
    for (const url of CRITICAL_RESOURCES) {
      const request = new Request(url, {mode: 'no-cors'});
      criticalFetches.push(fetchAndCache(cache, request));
    }
    return Promise.all(criticalFetches);
  };

  event.waitUntil(preCacheApplication());
}

/**
 * This event fires when the service worker is activated.
 * This can be after installation or upgrade.
 *
 * @param {!ExtendableEvent} event
 */
function onActivate(event) {
  // Delete old caches to save space.
  const dropOldCaches = async () => {
    const cacheNames = await caches.keys();

    // Return true on all the caches we want to clean up.
    // Note that caches are shared across the origin, so only remove
    // caches we are sure we created.
    const cleanTheseUp = cacheNames.filter((cacheName) =>
      cacheName.startsWith(CACHE_NAME_PREFIX) && cacheName != CACHE_NAME);

    const cleanUpPromises =
        cleanTheseUp.map((cacheName) => caches.delete(cacheName));

    await Promise.all(cleanUpPromises);
  };

  event.waitUntil(dropOldCaches());
}

/**
 * This event fires when any resource is fetched.
 * This is where we can use the cache to respond offline.
 *
 * @param {!FetchEvent} event
 */
function onFetch(event) {
  // For some reason, on a page load, we get hash parameters in the URL for this
  // event.  The hash should not be used when we do any of the lookups below.
  const url = event.request.url.split('#')[0];

  // Make sure this is a request we should be handling in the first place.
  // If it's not, it's important to leave it alone and not call respondWith.
  let useCache = false;
  for (const prefix of CACHEABLE_URL_PREFIXES) {
    if (url.startsWith(prefix)) {
      useCache = true;
      break;
    }
  }

  // Now we need to check our resource lists.  The list of prefixes above won't
  // cover everything that was installed initially, and those things still need
  // to be read from cache.  So we check if this request URL matches one of
  // those lists.
  if (!useCache) {
    if (CRITICAL_RESOURCES.includes(url) ||
        OPTIONAL_RESOURCES.includes(url)) {
      useCache = true;
    }
  }

  if (useCache) {
    event.respondWith(fetchCacheableResource(event.request));
  }
}

/**
 * Fetch a cacheable resource.  Decide whether to request from the network,
 * the cache, or both, and return the appropriate version of the resource.
 *
 * @param {!Request} request
 * @return {!Promise.<!Response>}
 */
async function fetchCacheableResource(request) {
  const cache = await caches.open(CACHE_NAME);
  const cachedResponse = await cache.match(request);

  if (!navigator.onLine) {
    // We are offline, and we know it.  Just return the cached response, to
    // avoid a bunch of pointless errors in the JS console that will confuse
    // us developers.  If there is no cached response, this will just be a
    // failed request.
    return cachedResponse;
  }

  if (cachedResponse) {
    // We have it in cache.  Try to fetch a live version and update the cache,
    // but limit how long we will wait for the updated version.
    try {
      return await timeout(NETWORK_TIMEOUT, fetchAndCache(cache, request));
    } catch (error) {
      // We tried to fetch a live version, but it either failed or took too
      // long.  If it took too long, the fetch and cache operation will continue
      // in the background.  In both cases, we should go ahead with a cached
      // version.
      return cachedResponse;
    }
  } else {
    // We should have this in cache, but we don't.  Fetch and cache a fresh
    // copy and then return it.
    return fetchAndCache(cache, request);
  }
}

/**
 * Fetch the resource from the network, then store this new version in the
 * cache.
 *
 * @param {!Cache} cache
 * @param {!Request} request
 * @return {!Promise.<!Response>}
 */
async function fetchAndCache(cache, request) {
  const response = await fetch(request);
  cache.put(request, response.clone());
  return response;
}

/**
 * Returns a Promise which is resolved only if |asyncProcess| is resolved, and
 * only if it is resolved in less than |seconds| seconds.
 *
 * If the returned Promise is resolved, it returns the same value as
 * |asyncProcess|.
 *
 * If |asyncProcess| fails, the returned Promise is rejected.
 * If |asyncProcess| takes too long, the returned Promise is rejected, but
 * |asyncProcess| is still allowed to complete.
 *
 * @param {number} seconds
 * @param {!Promise.<T>} asyncProcess
 * @return {!Promise.<T>}
 * @template T
 */
function timeout(seconds, asyncProcess) {
  return Promise.race([
    asyncProcess,
    new Promise(((_, reject) => {
      setTimeout(reject, seconds * 1000);
    })),
  ]);
}

/**
 * @param {string} relativeUrl A URL which may be relative to this service
 *   worker.
 * @return {string} The same URL converted to an absolute URL.
 */
function resolveRelativeUrl(relativeUrl) {
  // NOTE: This is the URL of the service worker, not the main HTML document.
  const baseUrl = location.href;
  return (new URL(relativeUrl, baseUrl)).href;
}

self.addEventListener('install', /** @type {function(!Event)} */(onInstall));
self.addEventListener('activate', /** @type {function(!Event)} */(onActivate));
self.addEventListener('fetch', /** @type {function(!Event)} */(onFetch));
<|endoftext|>


<commit_before>"use strict";

/*global module, require*/

var d3 = require("d3"),
    _ = require("lodash"),
    helpers = require("./helpers.js"),
    callbacks = helpers.callbackHandler,
    legendFactory = require("./legend-data.js"),
    maxZoom = 17,
    baseUrl = (function() {
	var a = document.createElement("a");
	a.href = "/heat-map-cdn/Total Heat Density";
	return a.href;
    }());

module.exports = function(getZoom, errors) {
    var legendByZoom = d3.map(),
	onLoad = callbacks(),
	broken = false;

    // loop over the zoom levels
    _.range(1, maxZoom + 1).forEach(function(z) {
	d3.json(
	    baseUrl + "/legend_Z" + z + ".json",
	    function(error, data) {
		if (error) {
		    if (!broken) {
			errors.warnUser("Failed to load heat map legend: " + error.response);
			broken = true;
		    }
		} else {
		    var numbers = [],
			colours = [];

		    data.legend.forEach(function(range, i) {
			if (i === 0) {
			    numbers.push(range.min);
			}

			// Must be American spelling here
			colours.push(range.color);

			numbers.push(range.max);
		    });

		    legendByZoom.set(z, legendFactory(numbers, colours));

		    onLoad();
		}
	    });
    });

    var f = function() {
	var z = getZoom();

	if (z > maxZoom) {
	    z = maxZoom;
	}

	return legendByZoom.has(z) ?
	    legendByZoom.get(z) :
	    legendFactory([0], []);
    };

    f.units = 'kWh/m2/year';
    f.onLoad = onLoad.add;

    return f;
};
<commit_msg>Improved error handling for heat map legend.<commit_after>"use strict";

/*global module, require*/

var d3 = require("d3"),
    _ = require("lodash"),
    helpers = require("./helpers.js"),
    callbacks = helpers.callbackHandler,
    legendFactory = require("./legend-data.js"),
    maxZoom = 17,
    baseUrl = (function() {
	var a = document.createElement("a");
	a.href = "/heat-map-cdn/Total Heat Density";
	return a.href;
    }()),
    broken = false;

module.exports = function(getZoom, errors) {
    var legendByZoom = d3.map(),
	onLoad = callbacks();

    // loop over the zoom levels
    _.range(1, maxZoom + 1).forEach(function(z) {
	d3.json(
	    baseUrl + "/legend_Z" + z + ".json",
	    function(error, data) {
		if (error) {
		    if (!broken) {
			errors.warnUser("Failed to load heat map legend: " + error.response);
			broken = true;
		    }
		} else {
		    var numbers = [],
			colours = [];

		    data.legend.forEach(function(range, i) {
			if (i === 0) {
			    numbers.push(range.min);
			}

			// Must be American spelling here
			colours.push(range.color);

			numbers.push(range.max);
		    });

		    legendByZoom.set(z, legendFactory(numbers, colours));

		    onLoad();
		}
	    });
    });

    var f = function() {
	var z = getZoom();

	if (z > maxZoom) {
	    z = maxZoom;
	}

	return legendByZoom.has(z) ?
	    legendByZoom.get(z) :
	    legendFactory([0], []);
    };

    f.units = 'kWh/m2/year';
    f.onLoad = onLoad.add;

    return f;
};
<|endoftext|>


<commit_before>var http = require("http");

var jsonResponse = { "hello": "nodejs" };

var app = http.createServer(function(httpRequest, httpResponse){
    httpResponse.setHeader("Content-Type", "application/json");
    httpResponse.end(JSON.stringify(jsonResponse));
});

app.listen(8080);

console.log("NodeJS App running on Port 8080");
<commit_msg>reorganizing hello nodejs example<commit_after>var http = require("http");

var jsonResponse = { "hello": "nodejs" };

// To access the HTTP server, load this URL in your browser:
// http://localhost:8080
var app = http.createServer(function(httpRequest, httpResponse){
    httpResponse.setHeader("Content-Type", "application/json");
    httpResponse.end(JSON.stringify(jsonResponse));
});

app.listen(8080);

console.log("NodeJS App running on Port 8080");
<|endoftext|>


<commit_before>/**
 * Image Slider
 *
 * @category    jQuery Plugin
 * @license     http://www.opensource.org/licenses/mit-license.html  MIT License
 * @copyright   2014 Daiki Sato
 * @author      Daiki Sato <sato.dik@gmail.com>
 * @link        http://orememo-v2.tumblr.com/
 * @version     1.0
 * @since       2014.05.16
 */

;(function($, window, document, undefined) {

	var pluginName = 'imageslider',
			defaults = {
				slideItems: '.is-item',
				slideContainer: '.is-container',
				slideDistance: 1,
				slideDuration: 1,
				slideEasing: 'linear',
				resizable: false
			};

	function Plugin(element, options) {
		var self = this;

		self.element = element;
		self.settings = $.extend({}, defaults, options);
		self._defaults = defaults;
		self._name = pluginName;

		$(window).on('load', function() { self.init(); });
		// this.init();
	}

	Plugin.prototype.init = function() {
		var self = this;

		self.$element = $(self.element);
		self.$slideContainer = self.$element.find(self.settings.slideContainer);
		self.$slideItems = self.$element.find(self.settings.slideItems);
		self.elementW = self.$element.width();
		self.slideContainerW = calcContainerSize(self.$slideContainer, self.$slideItems);

		self.$slideContainer.width(self.slideContainerW);
		self.$element.css('overflow', 'hidden');

		if(self.settings.resizable) {
			$(window).on('resize', function(){ self.resizeContainer(); });
		}

		self.resizeContainer();
		self.startSlide();

	}
	Plugin.prototype.startSlide = function() {
		var self = this,
				$slideItemFirst = self.$slideContainer.find(self.settings.slideItems).eq(0),
				slideItemFirstW = $slideItemFirst.width();

		// スライドする要素の中で、一番最初の要素のmargin-leftを減らしていく
		// 画面の外に出たら一番後ろに持っていく
		// 以下、繰り返し
		$slideItemFirst.animate({
			marginLeft: parseInt($slideItemFirst.css('margin-left'), 10) - self.settings.slideDistance
		}, self.settings.slideDuration, self.settings.slideEasing, function() {
			if(Math.abs(parseInt($slideItemFirst.css('margin-left'), 10)) > slideItemFirstW) {
				$slideItemFirst.appendTo(self.$slideContainer).css('margin-left', 0);
			}
			self.startSlide();
		});
	}
	Plugin.prototype.stopSlide = function() {
		var self = this;

		self.$slideItems.stop();
	}
	Plugin.prototype.resizeContainer = function() {
		var self = this,
				elementW = self.$element.width(),
				itemsW = self.slideContainerW;

		// self.$slideContainerの横幅がself.$elementの横幅より小さい時、スライドする要素をコピー
		// if(elementW < self.slideContainerW) return false;

		// スライドを一旦ストップ
		self.stopSlide();

		// self.$elementの横幅を超えるまでスライドする要素をコピーする
		adjustItemsLength(self.$slideContainer, self.$slideItems, elementW, itemsW);

		// 各種要素更新
		self.$slideItems = self.$element.find(self.settings.slideItems);
		self.slideContainerW = calcContainerSize(self.$slideContainer, self.$slideItems);
		self.elementW = elementW;
		self.$slideContainer.width(self.slideContainerW);

		// スライドを再スタートする
		self.startSlide();
	}

	function adjustItemsLength($container, $items, elementW, itemsW) {
		$items.each(function() {
			if(itemsW > elementW * 2) return false;

			var $clone = $(this).clone().css('margin-left', 0);

			$clone.appendTo($container);
			itemsW += $clone.width();
		});
	} // end of adjustItemsLength

	// 親要素のサイズを設定
	function calcContainerSize($container, $items) {
		var containerW = $container.width(),
				resultW = 0;

		$items.each(function() {
			resultW += $(this).width();
		});

		return resultW;
	} // end of calcContainerSize()

	$.fn[pluginName] = function(options) {
		this.each(function() {
			if(!$.data(this, 'plugin_' + pluginName)) {
				$.data(this, 'plugin_' + pluginName, new Plugin(this, options));
			}
		});

		return this;
	}

})(jQuery, window, document, undefined);<commit_msg>バージョンを1.1.0に更新<commit_after>/**
 * Image Slider
 *
 * @category    jQuery Plugin
 * @license     http://www.opensource.org/licenses/mit-license.html  MIT License
 * @copyright   2014 Daiki Sato
 * @author      Daiki Sato <sato.dik@gmail.com>
 * @link        http://orememo-v2.tumblr.com/
 * @version     1.1.0
 * @since       2014.05.16
 */

;(function($, window, document, undefined) {

	var pluginName = 'imageslider',
			defaults = {
				slideItems: '.is-item',
				slideContainer: '.is-container',
				slideDistance: 1,
				slideDuration: 1,
				slideEasing: 'linear',
				resizable: false,
				reverse: false
			};

	function Plugin(element, options) {
		var self = this;

		self.element = element;
		self.settings = $.extend({}, defaults, options);
		self._defaults = defaults;
		self._name = pluginName;

		$(window).on('load', function() { self.init(); });
		// this.init();
	}

	Plugin.prototype.init = function() {
		var self = this;

		self.$element = $(self.element);
		self.$slideContainer = self.$element.find(self.settings.slideContainer);
		self.$slideItems = self.$element.find(self.settings.slideItems);
		self.elementW = self.$element.width();
		self.slideContainerW = calcContainerSize(self.$slideContainer, self.$slideItems);
		self.slideItemsLength = self.$slideItems.length;

		self.$slideContainer.width(self.slideContainerW);
		self.$element.css('overflow', 'hidden');

		if(self.settings.resizable) {
			$(window).on('resize', function(){ self.resizeContainer(); });
		}

		self.resizeContainer();
		// self.startSlide();
	}
	Plugin.prototype.startSlide = function() {
		var self = this,
				$slideItemFirst = self.$slideContainer.find(self.settings.slideItems).eq(0),
				$slideItemLast = self.$slideContainer.find(self.settings.slideItems).eq(self.slideItemsLength - 1),
				slideItemFirstW = $slideItemFirst.width(),
				slideItemLastW = $slideItemLast.width();

		if($slideItemFirst.is(':animated')) return false;

		if(!self.settings.reverse) {
			// 右->左にスライドする
			$slideItemFirst.animate({
				marginLeft: parseInt($slideItemFirst.css('margin-left'), 10) - self.settings.slideDistance
			}, self.settings.slideDuration, self.settings.slideEasing, function() {
				if(Math.abs(parseInt($slideItemFirst.css('margin-left'), 10)) > slideItemFirstW) {
					$slideItemFirst.appendTo(self.$slideContainer).css('margin-left', 0);
				}
				self.startSlide();
			});
		} else {
			// 左->右にスライドする
			if(parseInt($slideItemFirst.css('margin-left'), 10) >= 0) {
				$slideItemLast.prependTo(self.$slideContainer).css('margin-left', -slideItemLastW);
				self.startSlide();
				return false;
			}

			$slideItemFirst.animate({
				marginLeft: parseInt($slideItemFirst.css('margin-left'), 10) + self.settings.slideDistance
			}, self.settings.slideDuration, self.settings.slideEasing, function() {
				self.startSlide();
			});
		}
	}
	Plugin.prototype.stopSlide = function() {
		var self = this;

		self.$slideItems.stop();
	}
	Plugin.prototype.resizeContainer = function() {
		var self = this,
				elementW = self.$element.width(),
				itemsW = self.slideContainerW;

		// self.$slideContainerの横幅がself.$elementの横幅より小さい時、スライドする要素をコピー
		// if(elementW < self.slideContainerW) return false;

		// スライドを一旦ストップ
		self.stopSlide();

		// self.$elementの横幅を超えるまでスライドする要素をコピーする
		adjustItemsLength(self.$slideContainer, self.$slideItems, elementW, itemsW);

		// 各種要素更新
		self.$slideItems = self.$element.find(self.settings.slideItems);
		self.slideContainerW = calcContainerSize(self.$slideContainer, self.$slideItems);
		self.elementW = elementW;
		self.$slideContainer.width(self.slideContainerW);
		self.slideItemsLength = self.$slideItems.length;

		// スライドを再スタートする
		self.startSlide();
	}

	function adjustItemsLength($container, $items, elementW, itemsW) {
		$items.each(function() {
			if(itemsW > elementW * 2) return false;

			var $clone = $(this).clone().css('margin-left', 0);

			$clone.appendTo($container);
			itemsW += $clone.width();
		});
	} // end of adjustItemsLength

	// 親要素のサイズを設定
	function calcContainerSize($container, $items) {
		var containerW = $container.width(),
				resultW = 0;

		$items.each(function() {
			resultW += $(this).width();
		});

		return resultW;
	} // end of calcContainerSize()

	$.fn[pluginName] = function(options) {
		this.each(function() {
			if(!$.data(this, 'plugin_' + pluginName)) {
				$.data(this, 'plugin_' + pluginName, new Plugin(this, options));
			}
		});

		return this;
	}

})(jQuery, window, document, undefined);<|endoftext|>


<commit_before>define(["require","js/core/Component", "js/core/Content", "js/core/Binding", "inherit", "underscore"],
    function (require,Component, Content, Binding, inherit, _) {

        var rspace = /\s+/;
        var domEvents = ['click', 'dblclick', 'keyup', 'keydown' , 'change'];

        var ContentPlaceHolder;
        require(["js/ui/ContentPlaceHolder"],function(CP){
            ContentPlaceHolder = CP;
        });

        var DomElementFunctions = {
            defaults: {
                selected: undefined,
                selectable: undefined
            },
            $classAttributes:[
                /^\$/,
                /^data/,
                /^xmlns/,
                /^on/
            ],
            ctor: function (attributes, descriptor, systemManager, parentScope, rootScope) {
                this.$renderMap = {};
                this.$childViews = [];
                this.$contentChildren = [];

                // go inherit tree up and search for descriptors
                var current = this;
                while (current) {
                    if (current.$classAttributes) {
                        this.$classAttributes = this.$classAttributes.concat(current.$classAttributes);
                    }
                    current = current.base;
                }

                this.callBase();

                if (descriptor) {
                    if (!this.$tagName) {
                        this.$tagName = descriptor.tagName;
                    }
                    if (!this.$namespace) {
                        this.$namespace = descriptor.namespaceURI;
                    }
                }
            },
            _initializeAttributes: function (attributes) {
                this.callBase();

                if (attributes.tagName) {
                    this.$tagName = attributes.tagName;
                    delete(attributes.tagName);
                }
            },
            addChild: function (child) {
                this.callBase();
                if (child instanceof DomElement || child.render) {
                    this.$childViews.push(child);
                    if (this.isRendered()) {
                        this._renderChild(child);
                    }
                } else if (child instanceof Content) {
                    this.$contentChildren.push(child);
                }
            },

            getPlaceHolder: function (name) {

                for (var i = 0; i < this.$children.length; i++) {
                    if (this.$children[i].$.name === name) {
                        return this.$children[i];
                    }
                }
                var placeholder;
                for (i = 0; i < this.$children.length; i++) {
                    if (this.$children[i].getPlaceHolder) {
                        placeholder = this.$children[i].getPlaceHolder(name);
                        if (placeholder) {
                            return placeholder;
                        }
                    }

                }
                return null;
            },

            getContentPlaceHolders: function () {

                var ret = [];

                var child;
                for (var i = 0; i < this.$children.length; i++) {
                    child = this.$children[i];

                    if (ContentPlaceHolder && child instanceof ContentPlaceHolder) {
                        ret.push(child);
                    } else if (child instanceof DomElement) {
                        ret = ret.concat(child.getContentPlaceHolders());
                    }
                }

                return ret;

            },

            findContent: function (name) {

                var child,
                    content;

                for (var i = 0; i < this.$children.length; i++) {
                    child = this.$children[i];
                    if (child instanceof Content && child.$.name === name) {
                        return child;
                    }
                }

                for (i = 0; i < this.$children.length; i++) {
                    child = this.$children[i];
                    if (child.findContent) {
                        content = child.findContent(name);
                        if (content) {
                            return content;
                        }
                    }

                }

                return null;
            },

            render: function () {

                if (!this.$initialized) {
                    this._initialize(this.$creationPolicy);
                }
                // check if it is already rendered
                if (this.isRendered()) {
                    return this.$el;
                }

                this.$renderedChildren = [];

                this.$el = this.$systemManager.$document.createElement(this.$tagName);

                // TODO: read layout and create renderMAP
                /**
                 * <js:Template name="layout"><placeholder cid="icon"/><placeholder cid="label"/></js:Template>
                 */

                this._renderChildren(this.$childViews);
                this._renderContentChildren(this.$contentChildren);
                this._renderAttributes(this.$);
                this._bindDomEvents(this.$el);

                return this.$el;
            },
            _bindDomEvents: function (el) {
                var self = this, domEvent;

                function bindDomEvent(eventName, scope, fncName) {
                    self.bind(eventName, scope[fncName], scope);
                    domEvent = eventName.substr(2);
                    self.addEventListener(domEvent, function (e) {
                        self.trigger(eventName, e, self);
                    });
                }

                var eventDef;
                for (var i = 0; i < this.$eventDefinitions.length; i++) {
                    eventDef = this.$eventDefinitions[i];
                    if (!this._isComponentEvent(eventDef.name.substr(2))) {
                        bindDomEvent(eventDef.name, eventDef.scope, eventDef.fncName);
                    }

                }
            },
            _renderChildren: function (children) {
                // for all children
                var child;
                for (var i = 0; i < children.length; i++) {
                    child = children[i];
                    this._renderChild(child);
                }
            },
            _renderContentChildren: function (children) {
                var child;
                for (var i = 0; i < children.length; i++) {
                    child = children[i];
                    var ref = child.get('ref');
                    var placeHolder = this.getPlaceHolder(ref);
                    if (placeHolder) {
                        placeHolder.set({content: child});
                    }
                }
            },
            _renderChild: function (child) {
                if (_.isFunction(child.render)) {
                    var el = child.render();
                    this.$renderedChildren.push(child);
                    if (el) {
                        this.$el.appendChild(el);
                    }
                }
            },
            _removeRenderedChild: function (child) {
                if (this.isRendered()) {
                    var rc;
                    for (var i = this.$renderedChildren.length - 1; i >= 0; i--) {
                        rc = this.$renderedChildren[i];
                        if (child === rc) {
                            this.$el.removeChild(rc.$el);
                            this.$renderedChildren.splice(i, 1);
                            return;
                        }
                    }
                }
            },
            _clearRenderedChildren: function () {
                if (this.isRendered()) {
                    var rc;
                    for (var i = this.$renderedChildren.length - 1; i >= 0; i--) {
                        rc = this.$renderedChildren[i];
                        this.$el.removeChild(rc.$el);
                    }
                }
                this.$renderedChildren = [];
            },
            _getIndexOfPlaceHolder: function (placeHolder) {
                if (this.$layoutTpl) {
                    var child;
                    for (var i = 0; i < this.$layoutTpl.$children.length; i++) {
                        child = this.$layoutTpl.$children[i];
                        if (placeHolderId == child.$cid) {
                            return i;
                        }
                    }
                }
                return -1;
            },
            isRendered: function () {
                return typeof (this.$el) !== "undefined";
            },
            _renderAttributes: function (attributes) {
                var attr;
                for (var key in attributes) {
                    if (attributes.hasOwnProperty(key)) {
                        attr = attributes[key];
                        this._renderAttribute(key, attr);
                    }
                }
            },
            _renderAttribute: function (key, attr) {
                var method = this.$renderMap[key];
                var prev = this.$previousAttributes[key];

                if (_.isUndefined(method)) {
                    // generic call of render functions
                    var k = key[0].toUpperCase() + key.substr(1);
                    var methodName = "_render" + k;
                    method = this[methodName];

                    if (!_.isFunction(method)) {
                        method = false;
                    }

                    this.$renderMap[key] = method;
                }
                if (method !== false) {
                    method.call(this, attr, prev);
                } else {
                    var cAttr;
                    for(var i = 0; i < this.$classAttributes.length; i++){
                        cAttr = this.$classAttributes[i];
                        if(cAttr instanceof RegExp){
                            if(cAttr.test(key)){
                                return;
                            }
                        } else {
                            if(cAttr == key){
                                return;
                            }
                        }
                    }

                    if (!_.isUndefined(attr)) {
                        this.$el.setAttribute(key, attr);
                    }
                }
            },

            _renderVisible: function (visible) {
                if (visible === true) {
                    this.removeClass('hidden');
                } else if (visible === false) {
                    this.addClass('hidden');
                }
            },
            _renderHidden: function (hidden) {
                if (typeof(hidden) !== "undefined") {
                    this.set({visible: !hidden});
                }
            },
            _renderSelected: function (selected) {
                if (selected === true) {
                    this.addClass('active');
                } else if (selected === false) {
                    this.removeClass('active');
                }
            },
            _renderSelectable: function (selectable) {
                if (selectable === true) {
                    var self = this;
                    this.addEventListener('click', function (e) {
                        // e.preventDefault();
                        self.set({selected: !self.$.selected});
                    });
                } else {
                    this.set({selected: false});
                }
            },
            _renderWidth: function (width) {
                if (width) {
                    if (typeof(width) !== "string") {
                        width += "px";
                    }
                    this.$el.style.width = width;
                }
            },
            _renderHeight: function (height) {
                if (height) {
                    if (typeof(height) !== "string") {
                        height += "px";
                    }
                    this.$el.style.height = height;
                }
            },
            _commitChangedAttributes: function (attributes) {
                if (this.isRendered()) {
                    this._renderAttributes(attributes);
                }
            },
            html: function () {
                if (!this.isRendered()) {
                    this.render();
                }
                return this.$el.innerHTML;

            }.on('change'),
            dom: function (element) {
                return new DomManipulation(element || this);
            }

        };

        var DomManipulationFunctions = {
            hasClass: function (value) {
                // var classes = this.$el.className.split(" "+value+" ");

            },
            addClass: function (value) {
                var classNames = value.split(rspace);

                if (!this.$el.className && classNames.length === 1) {
                    this.$el.className = value;
                } else {
                    var setClasses = this.$el.className.split(rspace);

                    for (var i = 0; i < classNames.length; i++) {
                        if (setClasses.indexOf(classNames[i]) == -1) {
                            setClasses.push(classNames[i]);
                        }
                    }

                    this.$el.className = setClasses.join(" ");

                }
            },
            removeClass: function (value) {
                if (this.$el.className.length === 0) {
                    return;
                }
                var removeClasses = value.split(rspace);

                var classes = this.$el.className.split(rspace);

                for (var i = 0; i < removeClasses.length; i++) {
                    var index = classes.indexOf(removeClasses[i]);
                    if (index != -1) {
                        classes.splice(index, 1);
                    }
                }

                if (classes.length === 0) {
                    this.$el.removeAttribute('class');
                } else {
                    this.$el.className = classes.join(" ");
                }
            },
            addEventListener: function (type, eventHandle) {
                if (this.$el.addEventListener) {
                    this.$el.addEventListener(type, eventHandle, false);

                } else if (this.$el.attachEvent) {
                    this.$el.attachEvent("on" + type, eventHandle);
                }
            },
            removeEvent: function (type, handle) {
                if (this.$el.removeEventListener) {
                    this.$el.removeEventListener(type, handle, false);
                } else if (this.$el.detachEvent) {
                    this.$el.detachEvent("on" + type, handle);
                }

            }
        };

        var DomManipulation = inherit.Base.inherit(_.extend({
            ctor: function (elm) {
                this.$el = elm;
            }
        }, DomManipulationFunctions));
        var DomElement = Component.inherit("js.html.DomElement",
            _.extend(DomElementFunctions, DomManipulationFunctions));
        return DomElement;
    }
);<commit_msg>added destroy to dom element<commit_after>define(["require", "js/core/Component", "js/core/Content", "js/core/Binding", "inherit", "underscore"],
    function (require, Component, Content, Binding, inherit, _) {

        var rspace = /\s+/;
        var domEvents = ['click', 'dblclick', 'keyup', 'keydown' , 'change'];

        var ContentPlaceHolder;
        require(["js/ui/ContentPlaceHolder"], function (CP) {
            ContentPlaceHolder = CP;
        });

        var DomElementFunctions = {
            defaults: {
                selected: undefined,
                selectable: undefined
            },
            $classAttributes: [
                /^\$/,
                /^data/,
                /^xmlns/,
                /^on/
            ],
            ctor: function (attributes, descriptor, systemManager, parentScope, rootScope) {
                this.$renderMap = {};
                this.$childViews = [];
                this.$contentChildren = [];

                // go inherit tree up and search for descriptors
                var current = this;
                while (current) {
                    if (current.$classAttributes) {
                        this.$classAttributes = this.$classAttributes.concat(current.$classAttributes);
                    }
                    current = current.base;
                }

                this.callBase();

                if (descriptor) {
                    if (!this.$tagName) {
                        this.$tagName = descriptor.tagName;
                    }
                    if (!this.$namespace) {
                        this.$namespace = descriptor.namespaceURI;
                    }
                }
            },
            _initializeAttributes: function (attributes) {
                this.callBase();

                if (attributes.tagName) {
                    this.$tagName = attributes.tagName;
                    delete(attributes.tagName);
                }
            },
            addChild: function (child) {
                this.callBase();
                if (child instanceof DomElement || child.render) {
                    this.$childViews.push(child);
                    if (this.isRendered()) {
                        this._renderChild(child);
                    }
                } else if (child instanceof Content) {
                    this.$contentChildren.push(child);
                }
            },

            getPlaceHolder: function (name) {

                for (var i = 0; i < this.$children.length; i++) {
                    if (this.$children[i].$.name === name) {
                        return this.$children[i];
                    }
                }
                var placeholder;
                for (i = 0; i < this.$children.length; i++) {
                    if (this.$children[i].getPlaceHolder) {
                        placeholder = this.$children[i].getPlaceHolder(name);
                        if (placeholder) {
                            return placeholder;
                        }
                    }

                }
                return null;
            },

            getContentPlaceHolders: function () {

                var ret = [];

                var child;
                for (var i = 0; i < this.$children.length; i++) {
                    child = this.$children[i];

                    if (ContentPlaceHolder && child instanceof ContentPlaceHolder) {
                        ret.push(child);
                    } else if (child instanceof DomElement) {
                        ret = ret.concat(child.getContentPlaceHolders());
                    }
                }

                return ret;

            },

            findContent: function (name) {

                var child,
                    content;

                for (var i = 0; i < this.$children.length; i++) {
                    child = this.$children[i];
                    if (child instanceof Content && child.$.name === name) {
                        return child;
                    }
                }

                for (i = 0; i < this.$children.length; i++) {
                    child = this.$children[i];
                    if (child.findContent) {
                        content = child.findContent(name);
                        if (content) {
                            return content;
                        }
                    }

                }

                return null;
            },

            render: function () {

                if (!this.$initialized) {
                    this._initialize(this.$creationPolicy);
                }
                // check if it is already rendered
                if (this.isRendered()) {
                    return this.$el;
                }

                this.$renderedChildren = [];

                this.$el = this.$systemManager.$document.createElement(this.$tagName);

                // TODO: read layout and create renderMAP
                /**
                 * <js:Template name="layout"><placeholder cid="icon"/><placeholder cid="label"/></js:Template>
                 */

                this._renderChildren(this.$childViews);
                this._renderContentChildren(this.$contentChildren);
                this._renderAttributes(this.$);
                this._bindDomEvents(this.$el);

                return this.$el;
            },
            _bindDomEvents: function (el) {
                var self = this, domEvent;

                function bindDomEvent(eventName, scope, fncName) {
                    self.bind(eventName, scope[fncName], scope);
                    domEvent = eventName.substr(2);
                    self.addEventListener(domEvent, function (e) {
                        self.trigger(eventName, e, self);
                    });
                }

                var eventDef;
                for (var i = 0; i < this.$eventDefinitions.length; i++) {
                    eventDef = this.$eventDefinitions[i];
                    if (!this._isComponentEvent(eventDef.name.substr(2))) {
                        bindDomEvent(eventDef.name, eventDef.scope, eventDef.fncName);
                    }

                }
            },
            _renderChildren: function (children) {
                // for all children
                var child;
                for (var i = 0; i < children.length; i++) {
                    child = children[i];
                    this._renderChild(child);
                }
            },
            _renderContentChildren: function (children) {
                var child;
                for (var i = 0; i < children.length; i++) {
                    child = children[i];
                    var ref = child.get('ref');
                    var placeHolder = this.getPlaceHolder(ref);
                    if (placeHolder) {
                        placeHolder.set({content: child});
                    }
                }
            },
            _renderChild: function (child) {
                if (_.isFunction(child.render)) {
                    var el = child.render();
                    this.$renderedChildren.push(child);
                    if (el) {
                        this.$el.appendChild(el);
                    }
                }
            },
            _removeRenderedChild: function (child) {
                if (this.isRendered()) {
                    var rc;
                    for (var i = this.$renderedChildren.length - 1; i >= 0; i--) {
                        rc = this.$renderedChildren[i];
                        if (child === rc) {
                            this.$el.removeChild(rc.$el);
                            this.$renderedChildren.splice(i, 1);
                            return;
                        }
                    }
                }
            },
            _clearRenderedChildren: function () {
                if (this.isRendered()) {
                    var rc;
                    for (var i = this.$renderedChildren.length - 1; i >= 0; i--) {
                        rc = this.$renderedChildren[i];
                        this.$el.removeChild(rc.$el);
                    }
                }
                this.$renderedChildren = [];
            },
            _getIndexOfPlaceHolder: function (placeHolder) {
                if (this.$layoutTpl) {
                    var child;
                    for (var i = 0; i < this.$layoutTpl.$children.length; i++) {
                        child = this.$layoutTpl.$children[i];
                        if (placeHolderId == child.$cid) {
                            return i;
                        }
                    }
                }
                return -1;
            },
            isRendered: function () {
                return typeof (this.$el) !== "undefined";
            },
            _renderAttributes: function (attributes) {
                var attr;
                for (var key in attributes) {
                    if (attributes.hasOwnProperty(key)) {
                        attr = attributes[key];
                        this._renderAttribute(key, attr);
                    }
                }
            },
            _renderAttribute: function (key, attr) {
                var method = this.$renderMap[key];
                var prev = this.$previousAttributes[key];

                if (_.isUndefined(method)) {
                    // generic call of render functions
                    var k = key[0].toUpperCase() + key.substr(1);
                    var methodName = "_render" + k;
                    method = this[methodName];

                    if (!_.isFunction(method)) {
                        method = false;
                    }

                    this.$renderMap[key] = method;
                }
                if (method !== false) {
                    method.call(this, attr, prev);
                } else {
                    var cAttr;
                    for (var i = 0; i < this.$classAttributes.length; i++) {
                        cAttr = this.$classAttributes[i];
                        if (cAttr instanceof RegExp) {
                            if (cAttr.test(key)) {
                                return;
                            }
                        } else {
                            if (cAttr == key) {
                                return;
                            }
                        }
                    }

                    if (!_.isUndefined(attr)) {
                        this.$el.setAttribute(key, attr);
                    }
                }
            },

            _renderVisible: function (visible) {
                if (visible === true) {
                    this.removeClass('hidden');
                } else if (visible === false) {
                    this.addClass('hidden');
                }
            },
            _renderHidden: function (hidden) {
                if (typeof(hidden) !== "undefined") {
                    this.set({visible: !hidden});
                }
            },
            _renderSelected: function (selected) {
                if (selected === true) {
                    this.addClass('active');
                } else if (selected === false) {
                    this.removeClass('active');
                }
            },
            _renderSelectable: function (selectable) {
                if (selectable === true) {
                    var self = this;
                    this.addEventListener('click', function (e) {
                        // e.preventDefault();
                        self.set({selected: !self.$.selected});
                    });
                } else {
                    this.set({selected: false});
                }
            },
            _renderWidth: function (width) {
                if (width) {
                    if (typeof(width) !== "string") {
                        width += "px";
                    }
                    this.$el.style.width = width;
                }
            },
            _renderHeight: function (height) {
                if (height) {
                    if (typeof(height) !== "string") {
                        height += "px";
                    }
                    this.$el.style.height = height;
                }
            },
            _commitChangedAttributes: function (attributes) {
                if (this.isRendered()) {
                    this._renderAttributes(attributes);
                }
            },
            destroy: function () {
                this.callBase();

                if (this.$childViews) {
                    for(var i = 0; i < this.$childViews.length; i++){
                        this.$childViews[i].destroy();
                    }
                }
            },
            html: function () {
                if (!this.isRendered()) {
                    this.render();
                }
                return this.$el.innerHTML;

            }.on('change'),
            dom: function (element) {
                return new DomManipulation(element || this);
            }

        };

        var DomManipulationFunctions = {
            hasClass: function (value) {
                // var classes = this.$el.className.split(" "+value+" ");

            },
            addClass: function (value) {
                var classNames = value.split(rspace);

                if (!this.$el.className && classNames.length === 1) {
                    this.$el.className = value;
                } else {
                    var setClasses = this.$el.className.split(rspace);

                    for (var i = 0; i < classNames.length; i++) {
                        if (setClasses.indexOf(classNames[i]) == -1) {
                            setClasses.push(classNames[i]);
                        }
                    }

                    this.$el.className = setClasses.join(" ");

                }
            },
            removeClass: function (value) {
                if (this.$el.className.length === 0) {
                    return;
                }
                var removeClasses = value.split(rspace);

                var classes = this.$el.className.split(rspace);

                for (var i = 0; i < removeClasses.length; i++) {
                    var index = classes.indexOf(removeClasses[i]);
                    if (index != -1) {
                        classes.splice(index, 1);
                    }
                }

                if (classes.length === 0) {
                    this.$el.removeAttribute('class');
                } else {
                    this.$el.className = classes.join(" ");
                }
            },
            addEventListener: function (type, eventHandle) {
                if (this.$el.addEventListener) {
                    this.$el.addEventListener(type, eventHandle, false);

                } else if (this.$el.attachEvent) {
                    this.$el.attachEvent("on" + type, eventHandle);
                }
            },
            removeEvent: function (type, handle) {
                if (this.$el.removeEventListener) {
                    this.$el.removeEventListener(type, handle, false);
                } else if (this.$el.detachEvent) {
                    this.$el.detachEvent("on" + type, handle);
                }

            }
        };

        var DomManipulation = inherit.Base.inherit(_.extend({
            ctor: function (elm) {
                this.$el = elm;
            }
        }, DomManipulationFunctions));
        var DomElement = Component.inherit("js.html.DomElement",
            _.extend(DomElementFunctions, DomManipulationFunctions));
        return DomElement;
    }
);<|endoftext|>