<commit_before>/* @flow */

import type {Reporter} from '../../reporters/index.js';
import type Config from '../../config.js';
import {stringifyPerson} from '../../util/normalize-manifest/util.js';
import {registryNames} from '../../registries/index.js';
import Lockfile from '../../lockfile/wrapper.js';
import {Install} from './install.js';
import * as child from '../../util/child.js';
import * as fs from '../../util/fs.js';

const objectPath = require('object-path');
const path = require('path');

export const noArguments = true;

export async function run(
  config: Config,
  reporter: Reporter,
  flags: Object,
  args: Array<string>,
): Promise<void> {
  const lockfile = new Lockfile();
  const install = new Install(flags, config, reporter, lockfile);
  const manifests = await install.getRootManifests();

  let gitUrl;
  const author = {
    name: config.getOption('init-author-name'),
    email: config.getOption('init-author-email'),
    url: config.getOption('init-author-url'),
  };
  if (await fs.exists(path.join(config.cwd, '.git'))) {
    // get git origin of the cwd
    gitUrl = await child.spawn('git', ['config', 'remote.origin.url'], {cwd: config.cwd});

    // get author default based on git config
    author.name = author.name || await child.spawn('git', ['config', 'user.name']);
    author.email = author.email || await child.spawn('git', ['config', 'user.email']);
  }

  const keys = [
    {
      key: 'name',
      question: 'name',
      default: path.basename(config.cwd),
    },
    {
      key: 'version',
      question: 'version',
      default: String(config.getOption('init-version')),
    },
    {
      key: 'description',
      question: 'description',
      default: '',
    },
    {
      key: 'main',
      question: 'entry point',
      default: 'index.js',
    },
    {
      key: 'repository.url',
      question: 'git repository',
      default: gitUrl,
    },
    {
      key: 'author',
      question: 'author',
      default: stringifyPerson(author),
    },
    {
      key: 'license',
      question: 'license',
      default: String(config.getOption('init-license')),
    },
  ];

  // get answers
  const pkg = {};
  for (let {key: manifestKey, question, default: def} of keys) {
    for (let registryName of registryNames) {
      const {object} = manifests[registryName];
      const val = objectPath.get(object, manifestKey);
      if (val) {
        def = val;
        break;
      }
    }

    if (def) {
      question += ` (${def})`;
    }

    const answer = (await reporter.question(question)) || def;
    if (answer) {
      objectPath.set(pkg, manifestKey, answer);
    }
  }

  // if we have a git url then set the type
  if (pkg.repository.url) {
    pkg.repository.type = 'git';
  }

  // save answers
  const targetManifests = [];
  for (let registryName of registryNames) {
    const info = manifests[registryName];
    if (info.exists) {
      targetManifests.push(info);
    }
  }
  if (!targetManifests.length) {
    targetManifests.push(manifests.npm);
  }
  for (const targetManifest of targetManifests) {
    Object.assign(targetManifest.object, pkg);
    reporter.success(`Saved ${path.basename(targetManifest.loc)}`);
  }

  await install.saveRootManifests(manifests);
}
<commit_msg>more thorough repository check in `init` command<commit_after>/* @flow */

import type {Reporter} from '../../reporters/index.js';
import type Config from '../../config.js';
import {stringifyPerson} from '../../util/normalize-manifest/util.js';
import {registryNames} from '../../registries/index.js';
import Lockfile from '../../lockfile/wrapper.js';
import {Install} from './install.js';
import * as child from '../../util/child.js';
import * as fs from '../../util/fs.js';

const objectPath = require('object-path');
const path = require('path');

export const noArguments = true;

export async function run(
  config: Config,
  reporter: Reporter,
  flags: Object,
  args: Array<string>,
): Promise<void> {
  const lockfile = new Lockfile();
  const install = new Install(flags, config, reporter, lockfile);
  const manifests = await install.getRootManifests();

  let gitUrl;
  const author = {
    name: config.getOption('init-author-name'),
    email: config.getOption('init-author-email'),
    url: config.getOption('init-author-url'),
  };
  if (await fs.exists(path.join(config.cwd, '.git'))) {
    // get git origin of the cwd
    gitUrl = await child.spawn('git', ['config', 'remote.origin.url'], {cwd: config.cwd});

    // get author default based on git config
    author.name = author.name || await child.spawn('git', ['config', 'user.name']);
    author.email = author.email || await child.spawn('git', ['config', 'user.email']);
  }

  const keys = [
    {
      key: 'name',
      question: 'name',
      default: path.basename(config.cwd),
    },
    {
      key: 'version',
      question: 'version',
      default: String(config.getOption('init-version')),
    },
    {
      key: 'description',
      question: 'description',
      default: '',
    },
    {
      key: 'main',
      question: 'entry point',
      default: 'index.js',
    },
    {
      key: 'repository.url',
      question: 'git repository',
      default: gitUrl,
    },
    {
      key: 'author',
      question: 'author',
      default: stringifyPerson(author),
    },
    {
      key: 'license',
      question: 'license',
      default: String(config.getOption('init-license')),
    },
  ];

  // get answers
  const pkg = {};
  for (let {key: manifestKey, question, default: def} of keys) {
    for (let registryName of registryNames) {
      const {object} = manifests[registryName];
      const val = objectPath.get(object, manifestKey);
      if (val) {
        def = val;
        break;
      }
    }

    if (def) {
      question += ` (${def})`;
    }

    const answer = (await reporter.question(question)) || def;
    if (answer) {
      objectPath.set(pkg, manifestKey, answer);
    }
  }

  // if we have a git url then set the type
  if (pkg.repository && pkg.repository.url) {
    pkg.repository.type = 'git';
  }

  // save answers
  const targetManifests = [];
  for (let registryName of registryNames) {
    const info = manifests[registryName];
    if (info.exists) {
      targetManifests.push(info);
    }
  }
  if (!targetManifests.length) {
    targetManifests.push(manifests.npm);
  }
  for (const targetManifest of targetManifests) {
    Object.assign(targetManifest.object, pkg);
    reporter.success(`Saved ${path.basename(targetManifest.loc)}`);
  }

  await install.saveRootManifests(manifests);
}
<|endoftext|>


<commit_before>/*
  Copyright © 2012-2013 Inria. All rights reserved.
  Author: Stéphane Glondu <Stephane.Glondu@inria.fr>

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

"use strict";

// Significant Helios-C-specific code is inside the heliosc.* namespace
var heliosc = {};

heliosc.booth = {};

heliosc.booth.derive_key = function (election) {
    var n58 = BigInt.fromInt(58);
    var n53 = BigInt.fromInt(53); // previous_prime(58)
    var digits = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";

    // FIXME: for demonstration purposes, this is a constant. In
    // practice, it should be different (at least) for each election
    // (e.g. UUID?  fingerprint?).
    var salt = sjcl.codec.hex.toBits("ed3540246bb511e286793cd92b7981b8");

    // Check that a secret credential is well formed
    function check(s) {
        var n = s.length-1, res = BigInt.ZERO;
        if (n < 14) return false; // < 82 bits of security
        var i, j;
        // main
        for (i = 0; i < n; i++) {
            j = digits.indexOf(s[i]);
            if (j < 0) return false; // bad digit
            res = res.multiply(n58).add(BigInt.fromInt(j));
        }
        // checksum
        j = digits.indexOf(s[i]);
        if (j < 0) return false; // bad digit
        var checksum = res.add(BigInt.fromInt(j));
        if (!checksum.mod(n53).equals(BigInt.ZERO)) return false; // bad checksum
        return true;
    }

    // Derive a Schnorr keypair from the secret credential
    function derive_key(secret) {
        if (check(secret)) {
            var hexkey = sjcl.codec.hex.fromBits(sjcl.misc.pbkdf2(secret, salt, 1000, 256));
            var pk = election.public_key;
            var x = (new BigInt(hexkey, 16)).mod(pk.q);
            var y = pk.g.modPow(x, pk.p);
            return { x: x, y: y };
        } else {
            throw "Bad token";
        }
    }

    return derive_key;
}

HELIOS.EncryptedVote.prototype.doSignature = function(cred) {
    // Schnorr signature
    var pk = this.election.public_key;
    var w = Random.getRandomInteger(pk.q);
    var commitment = pk.g.modPow(w, pk.p);
    var prefix = "sig|" + commitment.toJSONObject() + "|";
    var challenge = (new BigInt(hex_sha1(prefix + _(this.encrypted_answers).map(function(ea) {
        return ElGamal.stringify_choices(ea.choices);
    }).join(",")), 16)).mod(pk.q);
    // we do (q-x*challenge)+w instead of directly w-x*challenge,
    // in case mod doesn't support negative numbers as expected
    var response = pk.q.subtract(cred.x.multiply(challenge).mod(pk.q));
    response = response.add(w).mod(pk.q);
    // hugly hijack of the DLogProof datatype... note: here, we
    // give public credential instead of commitment, which can be computed
    // from public credential, challenge and response
    this.signature = new ElGamal.DLogProof(cred.y, challenge, response);
}
<commit_msg>Key derivation (for credentials) depends on UUID<commit_after>/*
  Copyright © 2012-2013 Inria. All rights reserved.
  Author: Stéphane Glondu <Stephane.Glondu@inria.fr>

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

"use strict";

// Significant Helios-C-specific code is inside the heliosc.* namespace
var heliosc = {};

heliosc.booth = {};

heliosc.booth.derive_key = function (election) {
    var n58 = BigInt.fromInt(58);
    var n53 = BigInt.fromInt(53); // previous_prime(58)
    var digits = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
    var salt = sjcl.codec.hex.toBits(election.uuid.replace(/-/g, ""));

    // Check that a secret credential is well formed
    function check(s) {
        var n = s.length-1, res = BigInt.ZERO;
        if (n < 14) return false; // < 82 bits of security
        var i, j;
        // main
        for (i = 0; i < n; i++) {
            j = digits.indexOf(s[i]);
            if (j < 0) return false; // bad digit
            res = res.multiply(n58).add(BigInt.fromInt(j));
        }
        // checksum
        j = digits.indexOf(s[i]);
        if (j < 0) return false; // bad digit
        var checksum = res.add(BigInt.fromInt(j));
        if (!checksum.mod(n53).equals(BigInt.ZERO)) return false; // bad checksum
        return true;
    }

    // Derive a Schnorr keypair from the secret credential
    function derive_key(secret) {
        if (check(secret)) {
            var hexkey = sjcl.codec.hex.fromBits(sjcl.misc.pbkdf2(secret, salt, 1000, 256));
            var pk = election.public_key;
            var x = (new BigInt(hexkey, 16)).mod(pk.q);
            var y = pk.g.modPow(x, pk.p);
            return { x: x, y: y };
        } else {
            throw "Bad token";
        }
    }

    return derive_key;
}

HELIOS.EncryptedVote.prototype.doSignature = function(cred) {
    // Schnorr signature
    var pk = this.election.public_key;
    var w = Random.getRandomInteger(pk.q);
    var commitment = pk.g.modPow(w, pk.p);
    var prefix = "sig|" + commitment.toJSONObject() + "|";
    var challenge = (new BigInt(hex_sha1(prefix + _(this.encrypted_answers).map(function(ea) {
        return ElGamal.stringify_choices(ea.choices);
    }).join(",")), 16)).mod(pk.q);
    // we do (q-x*challenge)+w instead of directly w-x*challenge,
    // in case mod doesn't support negative numbers as expected
    var response = pk.q.subtract(cred.x.multiply(challenge).mod(pk.q));
    response = response.add(w).mod(pk.q);
    // hugly hijack of the DLogProof datatype... note: here, we
    // give public credential instead of commitment, which can be computed
    // from public credential, challenge and response
    this.signature = new ElGamal.DLogProof(cred.y, challenge, response);
}
<|endoftext|>


<commit_before>/*
 * This file is part of the geena package.
 * Copyright (c) 2013 Rhinostone <geena@rhinostone.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

/**
 * Geena Bootstrap
 *
 * @package    Geena
 * @author     Rhinostone <geena@rhinostone.com>
 */
var Gna     = {core:{}},
    Config  = require('./config'),
    Server  = require('./server'),
    Util    = require('util'),
    Proc    = require('geena.utils').Proc,
    EventEmitter = require('events').EventEmitter;

Gna.Utils = require('geena.utils');
Gna.Model = require('./model');

Log     = Gna.Utils.Logger;

var e = new EventEmitter();
Gna.initialized = false;

/**
 * On middleware initialization
 *
 * @callback callback
 *
 * */
Gna.onInitialize = function(callback){

    Gna.initialized = true;

    e.on('init', function(instance, express, conf){

        joinContext(conf.contexts);

        Gna.getConfig = function(name){
            var tmp = "";
            if ( typeof(name) != 'undefined' ) {
                try {
                    //Protect it.
                    tmp = JSON.stringify(conf.content[name]);
                    console.warn("parsing ", conf.content);
                    return JSON.parse(tmp);
                } catch (err) {
                    return undefined;
                }
            } else {
                //console.error("config!!!! ", conf);
                tmp = JSON.stringify(conf);
                return JSON.parse(tmp);
            }
        };
        callback(e, instance, express);
    });
};

/**
 * Start server
 *
 * @param {string} [executionPath]
 * */
Gna.start = function(executionPath){
    //WTF !.
    var core    = Gna.core,
        env     = process.argv[2];

    if( executionPath == undefined){
        var p = new _(process.argv[1]).toUnixStyle().split("/");
        var appName = p[p.length-1].split(".")[0];
        var executionPath = "";
        for (var i=0; i<p.length-1; ++i) {
            executionPath +=  p[i] + '/';
        }
        executionPath = executionPath.substring(0, executionPath.length-1);
    }

    var root = getPath('root');

    if ( root == undefined) {
        setPath( 'root', _(executionPath) );
        root = _(executionPath);
        var geenaPath = _(__dirname);
        setPath('geena.core', _(geenaPath +'/core'));
    }

    core.executionPath = _(executionPath);
    console.error("found context ",  core.executionPath);
    core.startingApp = appName;
    core.geenaPath = _(__dirname);

    //Inherits parent (geena) context.
    if ( typeof(process.argv[3]) != 'undefined' ) {
        setContext( JSON.parse(process.argv[3]) );
    }

    //Setting env.
    if (env != 'undefined') {
        Log.setEnv(env);
    }
    //Setting log paths.
    Log.init({
        logs : _(core.executionPath + '/logs'),
        core: _(__dirname)
    });

    var config = new Config({
        env : env,
        executionPath : core.executionPath,
        startingApp : core.startingApp
    });

    config.onReady( function(err, obj){
        var isStandalone = obj.isStandalone;

        Log.info('geena', 'CORE:INFO:2', 'Execution Path : ' + core.executionPath);
        Log.info('geena', 'CORE:INFO:3', 'Standalone mode : ' + isStandalone);

        Server.setConf({
                appName         : core.startingApp,
                //Apps list.
                bundles         : obj.bundles,
                allBundles      : obj.allBundles,
                env             : obj.env,
                isStandalone    : isStandalone,
                executionPath   : core.executionPath,
                geenaPath       : core.geenaPath,
                conf            : obj.conf
            },
            function(err, instance, express, conf){
                if (!err) {

                    Log.debug(
                        'geena',
                        'CORE:DEBUG:1',
                        'Server conf loaded',
                        __stack
                    );

                    Log.notice(
                        'geena',
                        'CORE:NOTICE:2',
                        'Starting [' + core.startingApp + '] instance'
                    );

                    //On user conf complete.
                    e.on('complete', function(instance){
                        Server.instance = instance;
                        Server.init();
                    });
                    e.emit('init', instance, express, conf);
                    //In case there is no user init.
                    if (!Gna.initialized) {
                        e.emit('complete', instance);
                    }
                } else {
                    Log.error(
                        'geena',
                        'CORE:ERROR:1',
                        'Geena::Core.setConf() error. '+ err
                    );
                }
            });

    });
};

/**
 * Stop server
 * */
Gna.stop = function(pid, code){
    log("stoped server");
    if(typeof(code) != "undefined")
        process.exit(code);

    process.exit();
};
/**
 * Get Status
 * */
Gna.status = function(){
    log("getting server status");
};
/**
 * Restart server
 * */
Gna.restart = function(){
    log("starting server");
};

module.exports = Gna;<commit_msg>pathHelper::mv() done<commit_after>/*
 * This file is part of the geena package.
 * Copyright (c) 2013 Rhinostone <geena@rhinostone.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

/**
 * Geena Bootstrap
 *
 * @package    Geena
 * @author     Rhinostone <geena@rhinostone.com>
 */
var Gna     = {core:{}},
    Config  = require('./config'),
    Server  = require('./server'),
    Util    = require('util'),
    Proc    = require('geena.utils').Proc,
    EventEmitter = require('events').EventEmitter;

Gna.Utils = require('geena.utils');
Gna.Model = require('./model');

Log     = Gna.Utils.Logger;

var e = new EventEmitter();
Gna.initialized = false;

if( Gna.executionPath == undefined){
    var p = new _(process.argv[1]).toUnixStyle().split("/");
    var appName = p[p.length-1].split(".")[0];
    Gna.executionPath = "";
    for (var i=0; i<p.length-1; ++i) {
        Gna.executionPath +=  p[i] + '/';
    }
    Gna.executionPath = Gna.executionPath.substring(0, Gna.executionPath.length-1);
}

var root = getPath('root');

if ( root == undefined) {
    setPath( 'root', _(Gna.executionPath) );
    root = _(Gna.executionPath);
    var geenaPath = _(__dirname);
    setPath('geena.core', _(geenaPath +'/core'));
}
/**
 * On middleware initialization
 *
 * @callback callback
 *
 * */
Gna.onInitialize = function(callback){

    Gna.initialized = true;

    e.on('init', function(instance, express, conf){

        joinContext(conf.contexts);

        Gna.getConfig = function(name){
            var tmp = "";
            if ( typeof(name) != 'undefined' ) {
                try {
                    //Protect it.
                    tmp = JSON.stringify(conf.content[name]);
                    console.warn("parsing ", conf.content);
                    return JSON.parse(tmp);
                } catch (err) {
                    return undefined;
                }
            } else {
                //console.error("config!!!! ", conf);
                tmp = JSON.stringify(conf);
                return JSON.parse(tmp);
            }
        };
        callback(e, instance, express);
    });
};

/**
 * Start server
 *
 * @param {string} [executionPath]
 * */
Gna.start = function(executionPath){
    //WTF !.
    var core    = Gna.core,
        env     = process.argv[2];

    if ( typeof(executionPath) != 'undefined' ) {
        Gna.executionPath = executionPath;
    } else {
        var executionPath = Gna.executionPath;
    }
    core.executionPath = _(executionPath);
    console.error("found context ",  core.executionPath);
    core.startingApp = appName;
    core.geenaPath = _(__dirname);

    //Inherits parent (geena) context.
    if ( typeof(process.argv[3]) != 'undefined' ) {
        setContext( JSON.parse(process.argv[3]) );
    }

    //Setting env.
    if (env != 'undefined') {
        Log.setEnv(env);
    }
    //Setting log paths.
    Log.init({
        logs : _(core.executionPath + '/logs'),
        core: _(__dirname)
    });

    var config = new Config({
        env : env,
        executionPath : core.executionPath,
        startingApp : core.startingApp
    });

    config.onReady( function(err, obj){
        var isStandalone = obj.isStandalone;

        Log.info('geena', 'CORE:INFO:2', 'Execution Path : ' + core.executionPath);
        Log.info('geena', 'CORE:INFO:3', 'Standalone mode : ' + isStandalone);

        Server.setConf({
                appName         : core.startingApp,
                //Apps list.
                bundles         : obj.bundles,
                allBundles      : obj.allBundles,
                env             : obj.env,
                isStandalone    : isStandalone,
                executionPath   : core.executionPath,
                geenaPath       : core.geenaPath,
                conf            : obj.conf
            },
            function(err, instance, express, conf){
                if (!err) {

                    Log.debug(
                        'geena',
                        'CORE:DEBUG:1',
                        'Server conf loaded',
                        __stack
                    );

                    Log.notice(
                        'geena',
                        'CORE:NOTICE:2',
                        'Starting [' + core.startingApp + '] instance'
                    );

                    //On user conf complete.
                    e.on('complete', function(instance){
                        Server.instance = instance;
                        Server.init();
                    });
                    e.emit('init', instance, express, conf);
                    //In case there is no user init.
                    if (!Gna.initialized) {
                        e.emit('complete', instance);
                    }
                } else {
                    Log.error(
                        'geena',
                        'CORE:ERROR:1',
                        'Geena::Core.setConf() error. '+ err
                    );
                }
            });

    });
};

/**
 * Stop server
 * */
Gna.stop = function(pid, code){
    log("stoped server");
    if(typeof(code) != "undefined")
        process.exit(code);

    process.exit();
};
/**
 * Get Status
 * */
Gna.status = function(){
    log("getting server status");
};
/**
 * Restart server
 * */
Gna.restart = function(){
    log("starting server");
};

module.exports = Gna;<|endoftext|>


<commit_before>!function (context) {

  /* bundle "src/remark/controller.js" */
  /* bundle "src/remark/converter.js" */
  /* bundle "src/remark/slideshow.js" */

  var remark = context.remark = context.remark || {};

  window.onload = function () {
    var sourceElement = document.getElementById('source')
      , slideshowElement = document.getElementById('slideshow')
      ;

    if (!sourceElement) {
      alert('remark error: source element not present.')
      return;
    }

    if (!slideshowElement) {
      alert('remark error: slideshow element not present.')
      return;
    }

    sourceElement.style.display = 'none';

    styleDocument();
    setupSlideshow(sourceElement, slideshowElement);
  };

  var setupSlideshow = function (sourceElement, slideshowElement) {
    var source = sourceElement.innerHTML
      , slideshow
      , controller
      ;

    slideshow = remark.slideshow.create(source, slideshowElement);
    controller = remark.controller.create(slideshow);
    mapKeys(controller);
  };

  var styleDocument = function () {
    var style = createStyle();
    addElementToHead(style);
  };

  var createStyle = function () {
    var style = document.createElement('style');
    style.type = 'text/css';
    style.innerHTML = '/* bundle "src/remark.css" */';

    return style;
  };

  var addElementToHead = function (element) {
    var head = document.getElementsByTagName('head')[0];
    head.insertBefore(element, head.firstChild);
  };

  var mapKeys = function (controller) {
    window.onkeydown = function (event) {
      switch (event.keyCode) {
        case 37:
        case 38:
        case 75:
          controller.gotoPreviousSlide();
          break;
        case 32:
        case 39:
        case 40:
        case 74:
          controller.gotoNextSlide();
          break;
      }
    };
  };

  var mapTouches = function (controller) {
    var width = window.innerWidth
      , touch
      ;

    document.addEventListener('touchend', function (event) {
      touch = event.changedTouches[0];

      if (touch.clientX < width / 2) {
        controller.gotoPreviousSlide();
      }
      else {
        controller.gotoNextSlide();
      }
    });

    document.addEventListener('touchmove', function (event) {
      event.preventDefault();
    });
  };

}(this);
<commit_msg>Added slide navigation using page up/down keys.<commit_after>!function (context) {

  /* bundle "src/remark/controller.js" */
  /* bundle "src/remark/converter.js" */
  /* bundle "src/remark/slideshow.js" */

  var remark = context.remark = context.remark || {};

  window.onload = function () {
    var sourceElement = document.getElementById('source')
      , slideshowElement = document.getElementById('slideshow')
      ;

    if (!sourceElement) {
      alert('remark error: source element not present.')
      return;
    }

    if (!slideshowElement) {
      alert('remark error: slideshow element not present.')
      return;
    }

    sourceElement.style.display = 'none';

    styleDocument();
    setupSlideshow(sourceElement, slideshowElement);
  };

  var setupSlideshow = function (sourceElement, slideshowElement) {
    var source = sourceElement.innerHTML
      , slideshow
      , controller
      ;

    slideshow = remark.slideshow.create(source, slideshowElement);
    controller = remark.controller.create(slideshow);
    mapKeys(controller);
  };

  var styleDocument = function () {
    var style = createStyle();
    addElementToHead(style);
  };

  var createStyle = function () {
    var style = document.createElement('style');
    style.type = 'text/css';
    style.innerHTML = '/* bundle "src/remark.css" */';

    return style;
  };

  var addElementToHead = function (element) {
    var head = document.getElementsByTagName('head')[0];
    head.insertBefore(element, head.firstChild);
  };

  var mapKeys = function (controller) {
    window.onkeydown = function (event) {
      switch (event.keyCode) {
        case 33:
        case 37:
        case 38:
        case 75:
          controller.gotoPreviousSlide();
          break;
        case 32:
        case 34:
        case 39:
        case 40:
        case 74:
          controller.gotoNextSlide();
          break;
      }
    };
  };

  var mapTouches = function (controller) {
    var width = window.innerWidth
      , touch
      ;

    document.addEventListener('touchend', function (event) {
      touch = event.changedTouches[0];

      if (touch.clientX < width / 2) {
        controller.gotoPreviousSlide();
      }
      else {
        controller.gotoNextSlide();
      }
    });

    document.addEventListener('touchmove', function (event) {
      event.preventDefault();
    });
  };

}(this);
<|endoftext|>


<commit_before>/**
 * Author: shuson
 * Date: Apr/02/2015
 */
'use strict';

var http = require('http');
var fs = require('fs');
var path = require('path');
var url = require('url');
var chalk = require('chalk');

var cmd = {
    "debug" : false,
    "config": undefined
};

var loadConfig = function () {
    var config = {};

    if(fs.existsSync(cmd.config)) {
        config = require(path.join(__dirname, "../", cmd.config)); //fs has different path with require module

        _reversedProxy(config);

        if(cmd.debug) console.log(config.port);
    }else{
        console.log(chalk.red(cmd.config + " doesn't exsist!"));
        process.exit(1);
    }
};

//create proxy-reverser server
var _reversedProxy = function (cfg){
    var pr_server = http.createServer();

    var host = cfg.host || "127.0.0.1";
    var port = cfg.port || "8090";

    pr_server.on("request", function (req, res){
        if(cmd.debug) console.log("connected by " + req.headers.host);

        var vhosts = cfg.vhosts;

        vhosts.forEach(function(vhost){

            vhost.rules.forEach(function(rule){
                var regxRule = new RegExp(rule);

                if(regxRule.test(req.url)) {
                    var options = {
                        hostname: vhost.host,
                        port: vhost.port,
                        path: req.url,
                        method: req.method,
                        headers: req.headers
                    };

                    var reversedReq = http.request(options, function(reverseRes) {
                        if(cmd.debug) console.log('Status Code: ' + reverseRes.statusCode);
                        if(cmd.debug) console.log('Headers: ' + JSON.stringify(reverseRes.headers));

                        reverseRes.setEncoding('utf8');
                        reverseRes.on('data', function (chunk) {
                            if(cmd.debug) console.log('BODY: ' + chunk);

                            res.write(chunk);
                            res.end();
                        });
                    });

                    reversedReq.on('error', function(e) {
                        console.log('problem with request: ' + e.message);
                    });

                    reversedReq.end();
                    break;
                }
            });
        });
    });

    pr_server.listen(port, host, function (){
        console.log("Server is on %s:%s", host, port);
    });
}

module.exports = {
    cmd: cmd,
    run: loadConfig
};<commit_msg>Update proxy-reverser.js<commit_after>/**
 * Author: shuson
 * Date: Apr/02/2015
 */
'use strict';

var http = require('http');
var fs = require('fs');
var path = require('path');
var url = require('url');
var chalk = require('chalk');

var cmd = {
    "debug" : false
};

var loadConfig = function () {
    var config = {};

    if(fs.existsSync(cmd.config)) {
        config = require(path.join(__dirname, "../", cmd.config)); //fs has different path with require module

        _reversedProxy(config);

        if(cmd.debug) console.log(config.port);
    }else{
        console.log(chalk.red(cmd.config + " doesn't exsist!"));
        process.exit(1);
    }
};

//create proxy-reverser server
var _reversedProxy = function (cfg){
    var pr_server = http.createServer();

    var host = cfg.host || "127.0.0.1";
    var port = cfg.port || "8090";

    pr_server.on("request", function (req, res){
        if(cmd.debug) console.log("connected by " + req.headers.host);

        var vhosts = cfg.vhosts;

        vhosts.forEach(function(vhost){

            vhost.rules.forEach(function(rule){
                var regxRule = new RegExp(rule);

                if(regxRule.test(req.url)) {
                    var options = {
                        hostname: vhost.host,
                        port: vhost.port,
                        path: req.url,
                        method: req.method,
                        headers: req.headers
                    };

                    var reversedReq = http.request(options, function(reverseRes) {
                        if(cmd.debug) console.log('Status Code: ' + reverseRes.statusCode);
                        if(cmd.debug) console.log('Headers: ' + JSON.stringify(reverseRes.headers));

                        reverseRes.setEncoding('utf8');
                        reverseRes.on('data', function (chunk) {
                            if(cmd.debug) console.log('BODY: ' + chunk);

                            res.write(chunk);
                            res.end();
                        });
                    });

                    reversedReq.on('error', function(e) {
                        console.log('problem with request: ' + e.message);
                    });

                    reversedReq.end();
                    break;
                }
            });
        });
    });

    pr_server.listen(port, host, function (){
        console.log("Server is on %s:%s", host, port);
    });
}

module.exports = {
    cmd: cmd,
    run: loadConfig
};
<|endoftext|>


<commit_before>exports.tests = [
	{
		css: '.foo { } .bar { }',
		metrics: {
			duplicatedSelectors: 0
		}
	},
	{
		css: '.foo, #bar { } .foo { }',
		metrics: {
			duplicatedSelectors: 0
		}
	},
	// media queries
	{
		css: '.foo { } @media screen { .foo { } }',
		metrics: {
			duplicatedSelectors: 0
		}
	},
	{
		css: '@media print { .foo { } } @media screen { .foo { } } .foo {}',
		metrics: {
			duplicatedSelectors: 0
		}
	},
	{
		css: '.foo { } @media screen { .foo { } } .foo { color: red }',
		metrics: {
			duplicatedSelectors: 1
		}
	},
	{
		css: '#foo { } @media screen { .foo { } } @media screen { .foo { color: red } }',
		metrics: {
			duplicatedSelectors: 1
		}
	},
	// duplicated selectors
	{
		css: '.foo { } .foo { }',
		metrics: {
			duplicatedSelectors: 1
		}
	},
	{
		css: '.foo { } .bar .foo { } .foo { }',
		metrics: {
			duplicatedSelectors: 1
		}
	},
	{
		css: '.foo { } .foo { } .foo { }',
		metrics: {
			duplicatedSelectors: 1
		}
	},
	{
		css: '.foo { } .bar { } .foo { } .bar { } #foo { } .bar { }',
		metrics: {
			duplicatedSelectors: 2
		}
	},
	// @font-face (see #52)
	{
		css: '@font-face { font-family: myFont; src: url(sansation.woff);} @font-face { font-family: myFont; src: url(sansation_bold.woff); font-weight: bold;} ',
		metrics: {
			duplicatedSelectors: 0
		}
	},
	{
		css: '@font-face { font-family: myFont; src: url(sansation_foo.woff);} @font-face { font-family: myFontFoo; src: url(sansation_foo.woff); font-weight: bold;} ',
		metrics: {
			duplicatedSelectors: 1
		}
	},
	// duplicated properties
	{
		css: '#foo { background: none; background-color: red;}',
		metrics: {
			duplicatedProperties: 0
		}
	},
	{
		css: '#foo { background: none; background-color: red; background: transparent}',
		metrics: {
			duplicatedProperties: 1
		}
	},
	{
		css: '#foo { color: #000; background: none; background-color: red; color: red; color: blue; background: none}',
		metrics: {
			duplicatedProperties: 3 // color x3, background x2
		}
	},
	{
		css: 'button{background-color:#006cb0; background-image:-moz-linear-gradient(top,#008be3 35%,#006cb0 65%);background-image:-webkit-gradient(linear,0% 0%,0% 100%,color-stop(35%,#008be3),color-stop(65%,#006cb0));background-image:-o-linear-gradient(top,#008be3 35%,#006cb0 65%);background-image:-ms-linear-gradient(top,#008be3 35%,#006cb0 65%);  border:1px solid #006cb0;border-radius:4px;}',
		metrics: {
			duplicatedProperties: 0 // browser prefixes should not be included
		}
	},
];
<commit_msg>duplicatedProperties: add test case for "background" (pointed out by @gmetais)<commit_after>exports.tests = [
	{
		css: '.foo { } .bar { }',
		metrics: {
			duplicatedSelectors: 0
		}
	},
	{
		css: '.foo, #bar { } .foo { }',
		metrics: {
			duplicatedSelectors: 0
		}
	},
	// media queries
	{
		css: '.foo { } @media screen { .foo { } }',
		metrics: {
			duplicatedSelectors: 0
		}
	},
	{
		css: '@media print { .foo { } } @media screen { .foo { } } .foo {}',
		metrics: {
			duplicatedSelectors: 0
		}
	},
	{
		css: '.foo { } @media screen { .foo { } } .foo { color: red }',
		metrics: {
			duplicatedSelectors: 1
		}
	},
	{
		css: '#foo { } @media screen { .foo { } } @media screen { .foo { color: red } }',
		metrics: {
			duplicatedSelectors: 1
		}
	},
	// duplicated selectors
	{
		css: '.foo { } .foo { }',
		metrics: {
			duplicatedSelectors: 1
		}
	},
	{
		css: '.foo { } .bar .foo { } .foo { }',
		metrics: {
			duplicatedSelectors: 1
		}
	},
	{
		css: '.foo { } .foo { } .foo { }',
		metrics: {
			duplicatedSelectors: 1
		}
	},
	{
		css: '.foo { } .bar { } .foo { } .bar { } #foo { } .bar { }',
		metrics: {
			duplicatedSelectors: 2
		}
	},
	// @font-face (see #52)
	{
		css: '@font-face { font-family: myFont; src: url(sansation.woff);} @font-face { font-family: myFont; src: url(sansation_bold.woff); font-weight: bold;} ',
		metrics: {
			duplicatedSelectors: 0
		}
	},
	{
		css: '@font-face { font-family: myFont; src: url(sansation_foo.woff);} @font-face { font-family: myFontFoo; src: url(sansation_foo.woff); font-weight: bold;} ',
		metrics: {
			duplicatedSelectors: 1
		}
	},
	// duplicated properties
	{
		css: '#foo { background: none; background-color: red;}',
		metrics: {
			duplicatedProperties: 0
		}
	},
	{
		css: '#foo { background: none; background-color: red; background: transparent}',
		metrics: {
			duplicatedProperties: 1
		}
	},
	{
		css: '#foo { color: #000; background: none; background-color: red; color: red; color: blue; background: none}',
		metrics: {
			duplicatedProperties: 3 // color x3, background x2
		}
	},
	{
		css: 'button{background-color:#006cb0; background-image:-moz-linear-gradient(top,#008be3 35%,#006cb0 65%);background-image:-webkit-gradient(linear,0% 0%,0% 100%,color-stop(35%,#008be3),color-stop(65%,#006cb0));background-image:-o-linear-gradient(top,#008be3 35%,#006cb0 65%);background-image:-ms-linear-gradient(top,#008be3 35%,#006cb0 65%);  border:1px solid #006cb0;border-radius:4px;}',
		metrics: {
			duplicatedProperties: 0 // browser prefixes should not be included
		}
	},
	{
		css: 'button{background-color:#006cb0; background:-moz-linear-gradient(top,#008be3 35%,#006cb0 65%);background:-webkit-gradient(linear,0% 0%,0% 100%,color-stop(35%,#008be3),color-stop(65%,#006cb0));background:-o-linear-gradient(top,#008be3 35%,#006cb0 65%);background:-ms-linear-gradient(top,#008be3 35%,#006cb0 65%);  border:1px solid #006cb0;border-radius:4px;}',
		metrics: {
			duplicatedProperties: 0 // browser prefixes should not be included
		}
	},
];
<|endoftext|>


<commit_before>import { getScope, getDataAttribute, isObject, toArray, find, getPath, hasPath, isNullOrUndefined, isCallable } from './utils';

/**
 * Generates the options required to construct a field.
 */
export default class Generator {
  static generate (el, binding, vnode, options = {}) {
    const model = Generator.resolveModel(binding, vnode);

    return {
      name: Generator.resolveName(el, vnode),
      el: el,
      listen: !binding.modifiers.disable,
      scope: Generator.resolveScope(el, binding, vnode),
      vm: Generator.makeVM(vnode.context),
      expression: binding.value,
      component: vnode.child,
      classes: options.classes,
      classNames: options.classNames,
      getter: Generator.resolveGetter(el, vnode, model),
      events: Generator.resolveEvents(el, vnode) || options.events,
      model,
      delay: Generator.resolveDelay(el, vnode, options),
      rules: Generator.resolveRules(el, binding),
      initial: !!binding.modifiers.initial,
      alias: Generator.resolveAlias(el, vnode),
      validity: options.validity,
      aria: options.aria,
      initialValue: Generator.resolveInitialValue(vnode)
    };
  }

  static getCtorConfig (vnode) {
    if (!vnode.child) return null;

    const config = getPath('child.$options.$_veeValidate', vnode);

    return config;
  }

  /**
   *
   * @param {*} el
   * @param {*} binding
   */
  static resolveRules (el, binding) {
    if (!binding || !binding.expression) {
      return getDataAttribute(el, 'rules');
    }

    if (typeof binding.value === 'string') {
      return binding.value;
    }

    if (~['string', 'object'].indexOf(typeof binding.value.rules)) {
      return binding.value.rules;
    }

    return binding.value;
  }

  /**
   * @param {*} vnode
   */
  static resolveInitialValue (vnode) {
    const model = vnode.data.model || find(vnode.data.directives, d => d.name === 'model');

    return model && model.value;
  }

  /**
   * Creates a non-circular partial VM instance from a Vue instance.
   * @param {*} vm
   */
  static makeVM (vm) {
    return {
      get $el () {
        return vm.$el;
      },
      get $refs () {
        return vm.$refs;
      },
      $watch: vm.$watch ? vm.$watch.bind(vm) : () => {},
      $validator: vm.$validator ? {
        errors: vm.$validator.errors,
        validate: vm.$validator.validate.bind(vm.$validator),
        update: vm.$validator.update.bind(vm.$validator)
      } : null
    };
  }

  /**
   * Resolves the delay value.
   * @param {*} el
   * @param {*} vnode
   * @param {Object} options
   */
  static resolveDelay (el, vnode, options = {}) {
    return getDataAttribute(el, 'delay') || (vnode.child && vnode.child.$attrs && vnode.child.$attrs['data-vv-delay']) || options.delay;
  }

  /**
   * Resolves the alias for the field.
   * @param {*} el
   * @param {*} vnode
   * @return {Function} alias getter
   */
  static resolveAlias (el, vnode) {
    return () => getDataAttribute(el, 'as') || (vnode.child && vnode.child.$attrs && vnode.child.$attrs['data-vv-as']) || el.title || null;
  }

  /**
   * Resolves the events to validate in response to.
   * @param {*} el
   * @param {*} vnode
   */
  static resolveEvents (el, vnode) {
    let events = getDataAttribute(el, 'validate-on');

    if (!events && vnode.child && vnode.child.$attrs) {
      events = vnode.child.$attrs['data-vv-validate-on'];
    }

    if (!events && vnode.child) {
      const config = Generator.getCtorConfig(vnode);
      events = config.events;
    }

    return events;
  }

  /**
   * Resolves the scope for the field.
   * @param {*} el
   * @param {*} binding
   */
  static resolveScope (el, binding, vnode = {}) {
    let scope = null;
    if (isObject(binding.value)) {
      scope = binding.value.scope;
    }

    if (vnode.child && isNullOrUndefined(scope)) {
      scope = vnode.child.$attrs && vnode.child.$attrs['data-vv-scope'];
    }

    return !isNullOrUndefined(scope) ? scope : getScope(el);
  }

  /**
   * Checks if the node directives contains a v-model or a specified arg.
   * Args take priority over models.
   *
   * @return {Object}
   */
  static resolveModel (binding, vnode) {
    if (binding.arg) {
      return binding.arg;
    }

    if (isObject(binding.value) && binding.value.arg) {
      return binding.value.arg;
    }

    const model = vnode.data.model || find(vnode.data.directives, d => d.name === 'model');
    if (!model) {
      return null;
    }

    const watchable = /^[a-z_]+[0-9]*(\w*\.[a-z_]\w*)*$/i.test(model.expression) && hasPath(model.expression, vnode.context);

    if (!watchable) {
      return null;
    }

    return model.expression;
  }

  /**
     * Resolves the field name to trigger validations.
     * @return {String} The field name.
     */
  static resolveName (el, vnode) {
    if (vnode.child) {
      const config = Generator.getCtorConfig(vnode);
      if (config && isCallable(config.name)) {
        const boundGetter = config.name.bind(vnode.child);

        return boundGetter();
      }

      return getDataAttribute(el, 'name') || (vnode.child.$attrs && (vnode.child.$attrs['data-vv-name'] || vnode.child.$attrs['name'])) || vnode.child.name;
    }

    return getDataAttribute(el, 'name') || el.name;
  }

  /**
   * Returns a value getter input type.
   */
  static resolveGetter (el, vnode, model) {
    if (model) {
      return () => {
        return getPath(model, vnode.context);
      };
    }

    if (vnode.child) {
      const config = Generator.getCtorConfig(vnode);
      if (config && isCallable(config.value)) {
        const boundGetter = config.value.bind(vnode.child);

        return () => {
          return boundGetter();
        };
      }

      return () => {
        const path = getDataAttribute(el, 'value-path') || (vnode.child.$attrs && vnode.child.$attrs['data-vv-value-path']);
        if (path) {
          return getPath(path, vnode.child);
        }
        return vnode.child.value;
      };
    }

    switch (el.type) {
    case 'checkbox': return () => {
      let els = document.querySelectorAll(`input[name="${el.name}"]`);

      els = toArray(els).filter(el => el.checked);
      if (!els.length) return undefined;

      return els.map(checkbox => checkbox.value);
    };
    case 'radio': return () => {
      const els = document.querySelectorAll(`input[name="${el.name}"]`);
      const elm = find(els, el => el.checked);

      return elm && elm.value;
    };
    case 'file': return (context) => {
      return toArray(el.files);
    };
    case 'select-multiple': return () => {
      return toArray(el.options).filter(opt => opt.selected).map(opt => opt.value);
    };
    default: return () => {
      return el && el.value;
    };
    }
  }
}
<commit_msg>change name resolution priority<commit_after>import { getScope, getDataAttribute, isObject, toArray, find, getPath, hasPath, isNullOrUndefined, isCallable } from './utils';

/**
 * Generates the options required to construct a field.
 */
export default class Generator {
  static generate (el, binding, vnode, options = {}) {
    const model = Generator.resolveModel(binding, vnode);

    return {
      name: Generator.resolveName(el, vnode),
      el: el,
      listen: !binding.modifiers.disable,
      scope: Generator.resolveScope(el, binding, vnode),
      vm: Generator.makeVM(vnode.context),
      expression: binding.value,
      component: vnode.child,
      classes: options.classes,
      classNames: options.classNames,
      getter: Generator.resolveGetter(el, vnode, model),
      events: Generator.resolveEvents(el, vnode) || options.events,
      model,
      delay: Generator.resolveDelay(el, vnode, options),
      rules: Generator.resolveRules(el, binding),
      initial: !!binding.modifiers.initial,
      alias: Generator.resolveAlias(el, vnode),
      validity: options.validity,
      aria: options.aria,
      initialValue: Generator.resolveInitialValue(vnode)
    };
  }

  static getCtorConfig (vnode) {
    if (!vnode.child) return null;

    const config = getPath('child.$options.$_veeValidate', vnode);

    return config;
  }

  /**
   *
   * @param {*} el
   * @param {*} binding
   */
  static resolveRules (el, binding) {
    if (!binding || !binding.expression) {
      return getDataAttribute(el, 'rules');
    }

    if (typeof binding.value === 'string') {
      return binding.value;
    }

    if (~['string', 'object'].indexOf(typeof binding.value.rules)) {
      return binding.value.rules;
    }

    return binding.value;
  }

  /**
   * @param {*} vnode
   */
  static resolveInitialValue (vnode) {
    const model = vnode.data.model || find(vnode.data.directives, d => d.name === 'model');

    return model && model.value;
  }

  /**
   * Creates a non-circular partial VM instance from a Vue instance.
   * @param {*} vm
   */
  static makeVM (vm) {
    return {
      get $el () {
        return vm.$el;
      },
      get $refs () {
        return vm.$refs;
      },
      $watch: vm.$watch ? vm.$watch.bind(vm) : () => {},
      $validator: vm.$validator ? {
        errors: vm.$validator.errors,
        validate: vm.$validator.validate.bind(vm.$validator),
        update: vm.$validator.update.bind(vm.$validator)
      } : null
    };
  }

  /**
   * Resolves the delay value.
   * @param {*} el
   * @param {*} vnode
   * @param {Object} options
   */
  static resolveDelay (el, vnode, options = {}) {
    return getDataAttribute(el, 'delay') || (vnode.child && vnode.child.$attrs && vnode.child.$attrs['data-vv-delay']) || options.delay;
  }

  /**
   * Resolves the alias for the field.
   * @param {*} el
   * @param {*} vnode
   * @return {Function} alias getter
   */
  static resolveAlias (el, vnode) {
    return () => getDataAttribute(el, 'as') || (vnode.child && vnode.child.$attrs && vnode.child.$attrs['data-vv-as']) || el.title || null;
  }

  /**
   * Resolves the events to validate in response to.
   * @param {*} el
   * @param {*} vnode
   */
  static resolveEvents (el, vnode) {
    let events = getDataAttribute(el, 'validate-on');

    if (!events && vnode.child && vnode.child.$attrs) {
      events = vnode.child.$attrs['data-vv-validate-on'];
    }

    if (!events && vnode.child) {
      const config = Generator.getCtorConfig(vnode);
      events = config.events;
    }

    return events;
  }

  /**
   * Resolves the scope for the field.
   * @param {*} el
   * @param {*} binding
   */
  static resolveScope (el, binding, vnode = {}) {
    let scope = null;
    if (isObject(binding.value)) {
      scope = binding.value.scope;
    }

    if (vnode.child && isNullOrUndefined(scope)) {
      scope = vnode.child.$attrs && vnode.child.$attrs['data-vv-scope'];
    }

    return !isNullOrUndefined(scope) ? scope : getScope(el);
  }

  /**
   * Checks if the node directives contains a v-model or a specified arg.
   * Args take priority over models.
   *
   * @return {Object}
   */
  static resolveModel (binding, vnode) {
    if (binding.arg) {
      return binding.arg;
    }

    if (isObject(binding.value) && binding.value.arg) {
      return binding.value.arg;
    }

    const model = vnode.data.model || find(vnode.data.directives, d => d.name === 'model');
    if (!model) {
      return null;
    }

    const watchable = /^[a-z_]+[0-9]*(\w*\.[a-z_]\w*)*$/i.test(model.expression) && hasPath(model.expression, vnode.context);

    if (!watchable) {
      return null;
    }

    return model.expression;
  }

  /**
     * Resolves the field name to trigger validations.
     * @return {String} The field name.
     */
  static resolveName (el, vnode) {
    let name = getDataAttribute(el, 'name');

    if (!name && !vnode.child) {
      return el.name;
    }

    if (!name && vnode.child && vnode.child.$attrs) {
      name = vnode.child.$attrs['data-vv-name'] || vnode.child.$attrs['name'];
    }

    if (!name && vnode.child) {
      const config = Generator.getCtorConfig(vnode);
      if (config && isCallable(config.name)) {
        const boundGetter = config.name.bind(vnode.child);

        return boundGetter();
      }

      return vnode.child.name;
    }

    return name;
  }

  /**
   * Returns a value getter input type.
   */
  static resolveGetter (el, vnode, model) {
    if (model) {
      return () => {
        return getPath(model, vnode.context);
      };
    }

    if (vnode.child) {
      const config = Generator.getCtorConfig(vnode);
      if (config && isCallable(config.value)) {
        const boundGetter = config.value.bind(vnode.child);

        return () => {
          return boundGetter();
        };
      }

      return () => {
        const path = getDataAttribute(el, 'value-path') || (vnode.child.$attrs && vnode.child.$attrs['data-vv-value-path']);
        if (path) {
          return getPath(path, vnode.child);
        }
        return vnode.child.value;
      };
    }

    switch (el.type) {
    case 'checkbox': return () => {
      let els = document.querySelectorAll(`input[name="${el.name}"]`);

      els = toArray(els).filter(el => el.checked);
      if (!els.length) return undefined;

      return els.map(checkbox => checkbox.value);
    };
    case 'radio': return () => {
      const els = document.querySelectorAll(`input[name="${el.name}"]`);
      const elm = find(els, el => el.checked);

      return elm && elm.value;
    };
    case 'file': return (context) => {
      return toArray(el.files);
    };
    case 'select-multiple': return () => {
      return toArray(el.options).filter(opt => opt.selected).map(opt => opt.value);
    };
    default: return () => {
      return el && el.value;
    };
    }
  }
}
<|endoftext|>


<commit_before>/*

  Lightweight logger, print everything that is send to error, warn
  and messages to stdout (the terminal). If config.debug is set in config
  also print out everything send to debug.

*/

var moment = require('moment');
var fmt = require('util').format;
var _ = require('lodash');
var util = require('./util');
var config = util.getConfig();
var debug = config.debug;
var silent = config.silent;

var sendToParent = function() {
  var send = method => (...args) => {
    process.send({log: method, message: args.join(' ')});
  }

  return {
    error: send('error'),
    warn: send('warn'),
    info: send('info'),
    write: send('write')
  }
}

var Log = function() {
  _.bindAll(this);
  this.env = util.gekkoEnv();

  if(this.env === 'standalone')
    this.output = console;
  else if(this.env === 'child-process')
    this.output = sendToParent();
};

Log.prototype = {
  _write: function(method, args, name) {
    if(!name)
      name = method.toUpperCase();

    var message = moment().format('YYYY-MM-DD HH:mm:ss');
    message += ' (' + name + '):\t';
    message += fmt.apply(null, args);

    this.output[method](message);
  },
  error: function() {
    this._write('error', arguments);
  },
  warn: function() {
    this._write('warn', arguments);
  },
  info: function() {
    this._write('info', arguments);
  },
  write: function() {
    var args = _.toArray(arguments);
    var message = fmt.apply(null, args);
    this.output.info(message);
  }
}

if(debug)
  Log.prototype.debug = function() {
    this._write('info', arguments, 'DEBUG');
  }
else
  Log.prototype.debug = _.noop;

if(silent) {
  Log.prototype.debug = _.noop;
  Log.prototype.info = _.noop;
  Log.prototype.warn = _.noop;
  Log.prototype.error = _.noop;
  Log.prototype.write = _.noop;
}

module.exports = new Log;<commit_msg>never suppress error logs<commit_after>/*

  Lightweight logger, print everything that is send to error, warn
  and messages to stdout (the terminal). If config.debug is set in config
  also print out everything send to debug.

*/

var moment = require('moment');
var fmt = require('util').format;
var _ = require('lodash');
var util = require('./util');
var config = util.getConfig();
var debug = config.debug;
var silent = config.silent;

var sendToParent = function() {
  var send = method => (...args) => {
    process.send({log: method, message: args.join(' ')});
  }

  return {
    error: send('error'),
    warn: send('warn'),
    info: send('info'),
    write: send('write')
  }
}

var Log = function() {
  _.bindAll(this);
  this.env = util.gekkoEnv();

  if(this.env === 'standalone')
    this.output = console;
  else if(this.env === 'child-process')
    this.output = sendToParent();
};

Log.prototype = {
  _write: function(method, args, name) {
    if(!name)
      name = method.toUpperCase();

    var message = moment().format('YYYY-MM-DD HH:mm:ss');
    message += ' (' + name + '):\t';
    message += fmt.apply(null, args);

    this.output[method](message);
  },
  error: function() {
    this._write('error', arguments);
  },
  warn: function() {
    this._write('warn', arguments);
  },
  info: function() {
    this._write('info', arguments);
  },
  write: function() {
    var args = _.toArray(arguments);
    var message = fmt.apply(null, args);
    this.output.info(message);
  }
}

if(debug)
  Log.prototype.debug = function() {
    this._write('info', arguments, 'DEBUG');
  }
else
  Log.prototype.debug = _.noop;

if(silent) {
  Log.prototype.debug = _.noop;
  Log.prototype.info = _.noop;
  Log.prototype.warn = _.noop;
  Log.prototype.write = _.noop;
}

module.exports = new Log;<|endoftext|>


<commit_before>var expect = require('chai').expect;
var runner = require('../../lib/runners/cpp');

describe( 'c++ runner', function(){
    describe( '.run', function(){
        it( 'should handle basic code evaluation', function(done){
            var solution = ['#include <iostream>',
                            'int main()',
                            '{ std::cout << "\\\"Within C++, there is a much smaller and cleaner language struggling to get out.\\\" - Bjarn Stroustrup"; }'
                            ].join('\n');

            runner.run({language: 'c++', solution: solution}, function(buffer) {
                expect(buffer.stdout).to.equal("\"Within C++, there is a much smaller and cleaner language struggling to get out.\" - Bjarn Stroustrup");
                done();
            });
        });
    });
});
<commit_msg>C++11 support & setup code<commit_after>var expect = require('chai').expect;
var runner = require('../../lib/runners/cpp');

describe('c++ runner', function () {
    describe('.run', function () {
        it('should handle basic code evaluation', function (done) {
            var solution = [
                '#include <iostream>',
                'int main()',
                '{ std::cout << "\\\"Within C++, there is a much smaller and cleaner language struggling to get out.\\\" - Bjarn Stroustrup"; }'
            ].join('\n');

            runner.run({language: 'c++', solution: solution}, function (buffer) {
                expect(buffer.stdout).to.equal("\"Within C++, there is a much smaller and cleaner language struggling to get out.\" - Bjarn Stroustrup");
                done();
            });
        });
        it('should handle C++11 nonsense', function (done) {
            var solution = [
                '#include "stdio.h"',
                'int main() {',
                '    auto f = []{ printf("Finally, lambdas in C++.  Now if we had typeclasses, purity and laziness we might have a reasonable functional programming language."); };',
                '    f();',
                '}'
            ].join('\n');

            runner.run({language: 'c++', solution: solution}, function (buffer) {
                expect(buffer.stdout).to.equal("Finally, lambdas in C++.  Now if we had typeclasses, purity and laziness we might have a reasonable functional programming language.");
                done();
            });
        });
        it('should handle setup code and imports', function (done) {
            runner.run({
                language: 'cpp',
                setup: [
                    'int square(int a) { return a * a ; }'
                ].join('\n'),
                solution: [
                    '#include <iostream>',
                    'int square(int);',
                    'int main() {',
                    '    std::cout << square(6);',
                    '}',
                ].join('\n')
            }, function (buffer) {
                expect(buffer.stdout).to.equal('36');
                done();
            });
        });
    });
});
<|endoftext|>


<commit_before>
/**
 * 	@author       Rémi MARTIN <martinremi60@gmail.com>
 * 	@copyright    2014 Rémi MARTIN
 */

 /**
 * 	Creates a new world.
 * 	@class World
 * 	@classdesc yom - World
 * 	@constructor
 *	@param {string} idOfCanvas - The id of the canvas element (without the '#' symbol).
 * 	@param {number} [width=0] - The width of the canvas element.
 * 	@param {number} [height=0] - The height of the canvas element.
 *	@param {Array.<yom.Body>} [bodies] - The bodies engaged in the world
 *	@param {Array} [shapes] - Independant shapes, i.e. not tengible and that don't belong to a body
 * 	@return {yom.World} The point object
 */
yom.World = function (idOfCanvas, width, height, bodies, shapes) {
	/**
     * 	@property {string} idOfCanevas - The id of the canvas element (without the '#' symbol).
     */
	this.idOfCanvas = idOfCanvas || 0;

	/**
     * 	@property {number} width - The width of the canvas element.
     */
	this.width = width || 0;

	/**
     * 	@property {number} height - The height of the canvas element.
     */
	this.height = height || 0;

	/**
     * 	@property {Array.<yom.Body>} bodies - The bodies engaged in the world
     */
	this.bodies = bodies || [];

	/**
     * 	@property {Array} shapes - Independant shapes, i.e. not tengible and don't belong to a body.
     */
	this.shapes = shapes || [];

     /**
     *    @property {function()} stepBehavior - Defines the step behavior
     */
     this.stepBehavior = function() {

     };

     /**
      *   World singleton
      */
     yom.world = this;

     /**
     *    @property {Array.<yom.Vector2>} forces - Forces applied in the world
     *         Only OD are used as others are nonsense
     */
     this.forces = [];
};

// ----- Setter(s) ----- \\
/**
 *   Used to define the behavior of the 'step' function
 *   @method yom.World#setStepBehavior
 *   @param {function()} [stepFunction] - The function to be executed within the step function
 */
yom.World.prototype.setStepBehavior = function(stepFunction) {
     this.stepBehavior = stepFunction;
};

// ----- Method(s) ----- \\
/**
 *   Called before making a movement permanent. Detect colliding after a unit has been moved
 *   @param {number} [numBody=-1] - The index of the body that has been moved
 *   @method yom.doesCollide
 */
yom.World.prototype.doesCollide = function(numBody) {
     if(numBody >= 0 && numBody < this.bodies.length) {
          var body = this.bodies[numBody];
          var i;
          for(i = 0; i < body.shapes.length; ++i) {
               if(body.shapes[i].perimeter) {
                    console.log('voui :)');
               }
          }
     }
};

/**
 *   Called before the render manager in order to apply forces and compute new positions just before rendering
 *   @method yom.World#step
 */
yom.World.prototype.applyForces = function() {
     var i, j, k, l;
     var force;
     var ODvector;
     for(i = 0; i < this.bodies.length; ++i) {
          force = new yom.Vector2();
          for(j = 0; j < this.bodies[i].forces.length; ++j) {
               if(this.bodies[i].forces[j].type == yom.physics.force_type.SE) {
                    force.addVector(this.bodies[i].forces[j].head);
                    force.subVector(this.bodies[i].forces[j].applicationPoint);
               }
          }

          // We apply to the current body, other's "OD" forces
          for(k = 0; k < this.bodies.length; ++k) {
               if(k != i) {
                    for(l = 0; l < this.bodies[k].forces.length; ++l) {
                         if(this.bodies[k].forces[l].type == yom.physics.force_type.OD) {
                              ODvector = new yom.Vector2();
                              // Use centroid instead
                              ODvector.addVector(new yom.Vector2(this.bodies[k].centroid.x, this.bodies[k].centroid.y));
                              ODvector.subVector(new yom.Vector2(this.bodies[i].centroid.x, this.bodies[i].centroid.y));

                              // Scale vector
                              ODvector.norm();

                              // Multiply by intensity
                              ODvector.mulVector(this.bodies[k].forces[l].applicationPoint);
                              force.addVector(ODvector);
                         }
                    }
               }
          }

          // World forces
          for(k = 0; k < this.forces.length; ++k) {
               if(this.forces[k].type === yom.physics.force_type.OD) {
                    force.addVector(this.forces[k].head);
                    force.subVector(this.forces[k].applicationPoint);
               }
          }

          force.div(this.bodies[i].mass); // Acceleration

          // Velocity
          force.mul(yom.display.STEP_INTERVAL);
          force.addVector(this.bodies[i].velocity);
          this.bodies[i].velocity = force.copy();

          // Offset
          force.mul(yom.display.STEP_INTERVAL);

          // for(j = 0; j < this.bodies[i].forces.length; ++j) {
          //      this.bodies[i].forces[j].applicationPoint.addVector(force);
          //      this.bodies[i].forces[j].head.addVector(force);
          // }

          this.bodies[i].move(force.x, force.y);

          // test if collision with new movement
          if(this.doesCollide(i)) {
               console.log("collide");
          }
     }
};

/**
 *   Called before the render manager in order to proceed a new step of the world evolution
 *   BEHAVIOR DEFINED BY THE USER
 *   @method yom.World#step
 */
yom.World.prototype.step = function() {
     this.stepBehavior();
};
<commit_msg>Each normal is now computed from objects perimeters<commit_after>
/**
 * 	@author       Rémi MARTIN <martinremi60@gmail.com>
 * 	@copyright    2014 Rémi MARTIN
 */

 /**
 * 	Creates a new world.
 * 	@class World
 * 	@classdesc yom - World
 * 	@constructor
 *	@param {string} idOfCanvas - The id of the canvas element (without the '#' symbol).
 * 	@param {number} [width=0] - The width of the canvas element.
 * 	@param {number} [height=0] - The height of the canvas element.
 *	@param {Array.<yom.Body>} [bodies] - The bodies engaged in the world
 *	@param {Array} [shapes] - Independant shapes, i.e. not tengible and that don't belong to a body
 * 	@return {yom.World} The point object
 */
yom.World = function (idOfCanvas, width, height, bodies, shapes) {
	/**
     * 	@property {string} idOfCanevas - The id of the canvas element (without the '#' symbol).
     */
	this.idOfCanvas = idOfCanvas || 0;

	/**
     * 	@property {number} width - The width of the canvas element.
     */
	this.width = width || 0;

	/**
     * 	@property {number} height - The height of the canvas element.
     */
	this.height = height || 0;

	/**
     * 	@property {Array.<yom.Body>} bodies - The bodies engaged in the world
     */
	this.bodies = bodies || [];

	/**
     * 	@property {Array} shapes - Independant shapes, i.e. not tengible and don't belong to a body.
     */
	this.shapes = shapes || [];

     /**
     *    @property {function()} stepBehavior - Defines the step behavior
     */
     this.stepBehavior = function() {

     };

     /**
      *   World singleton
      */
     yom.world = this;

     /**
     *    @property {Array.<yom.Vector2>} forces - Forces applied in the world
     *         Only OD are used as others are nonsense
     */
     this.forces = [];
};

// ----- Setter(s) ----- \\
/**
 *   Used to define the behavior of the 'step' function
 *   @method yom.World#setStepBehavior
 *   @param {function()} [stepFunction] - The function to be executed within the step function
 */
yom.World.prototype.setStepBehavior = function(stepFunction) {
     this.stepBehavior = stepFunction;
};

// ----- Method(s) ----- \\
/**
 *   Called before making a movement permanent. Detect colliding after a unit has been moved
 *   @param {number} [numBody=-1] - The index of the body that has been moved
 *   @method yom.doesCollide
 */
yom.World.prototype.doesCollide = function(numBody) {
     if(numBody >= 0 && numBody < this.bodies.length) {
          var body = this.bodies[numBody];
          var i;
          var j;
          var perimeter;
          var normal = new yom.Vector2();
          for(i = 0; i < body.shapes.length; ++i) {
               if(body.shapes[i].perimeter) {
                    lines = body.shapes[i].perimeter.lines;
                    for(j = 0; j < lines.length; ++j) {
                         normal.lineNormal(lines[j]);
                    }
               }
          }
     }
};

/**
 *   Called before the render manager in order to apply forces and compute new positions just before rendering
 *   @method yom.World#step
 */
yom.World.prototype.applyForces = function() {
     var i, j, k, l;
     var force;
     var ODvector;
     for(i = 0; i < this.bodies.length; ++i) {
          force = new yom.Vector2();
          for(j = 0; j < this.bodies[i].forces.length; ++j) {
               if(this.bodies[i].forces[j].type == yom.physics.force_type.SE) {
                    force.addVector(this.bodies[i].forces[j].head);
                    force.subVector(this.bodies[i].forces[j].applicationPoint);
               }
          }

          // We apply to the current body, other's "OD" forces
          for(k = 0; k < this.bodies.length; ++k) {
               if(k != i) {
                    for(l = 0; l < this.bodies[k].forces.length; ++l) {
                         if(this.bodies[k].forces[l].type == yom.physics.force_type.OD) {
                              ODvector = new yom.Vector2();
                              // Use centroid instead
                              ODvector.addVector(new yom.Vector2(this.bodies[k].centroid.x, this.bodies[k].centroid.y));
                              ODvector.subVector(new yom.Vector2(this.bodies[i].centroid.x, this.bodies[i].centroid.y));

                              // Scale vector
                              ODvector.norm();

                              // Multiply by intensity
                              ODvector.mulVector(this.bodies[k].forces[l].applicationPoint);
                              force.addVector(ODvector);
                         }
                    }
               }
          }

          // World forces
          for(k = 0; k < this.forces.length; ++k) {
               if(this.forces[k].type === yom.physics.force_type.OD) {
                    force.addVector(this.forces[k].head);
                    force.subVector(this.forces[k].applicationPoint);
               }
          }

          force.div(this.bodies[i].mass); // Acceleration

          // Velocity
          force.mul(yom.display.STEP_INTERVAL);
          force.addVector(this.bodies[i].velocity);
          this.bodies[i].velocity = force.copy();

          // Offset
          force.mul(yom.display.STEP_INTERVAL);

          // for(j = 0; j < this.bodies[i].forces.length; ++j) {
          //      this.bodies[i].forces[j].applicationPoint.addVector(force);
          //      this.bodies[i].forces[j].head.addVector(force);
          // }

          this.bodies[i].move(force.x, force.y);

          // test if collision with new movement
          if(this.doesCollide(i)) {
               console.log("collide");
          }
     }
};

/**
 *   Called before the render manager in order to proceed a new step of the world evolution
 *   BEHAVIOR DEFINED BY THE USER
 *   @method yom.World#step
 */
yom.World.prototype.step = function() {
     this.stepBehavior();
};
<|endoftext|>


<commit_before>function Map(_game) {
	this.game = _game;
	this.canvas = new Array();
	this.context = new Array();
	this.name = null;
	this.xmlHttp = null;
	this.xmlDoc = null;
	this.tileset = new Array();
    this.layer = new Array();
    this.data = new Array();
    this.width = null;
    this.height = null;
    this.tile = {width: null, height: null};
    this.visible = true;
    this.sprite = new Array();

    return this;
};

Map.prototype.load = function(_name) {
	var self = this;
	this.name = _name;
    this.xmlHttp = new XMLHttpRequest();
    if(this.xmlHttp.overrideMimeType) {
    	this.xmlHttp.overrideMimeType("text/xml");
    }
    this.xmlHttp.open("GET", this.name, false);
	this.xmlHttp.send();
    if(this.xmlHttp.status === 200) {
		this.xmlDoc = this.xmlHttp.responseXML;
    }

    this.width = parseInt(this.xmlDoc.getElementsByTagName("map")[0].getAttribute("width"));
    this.height = parseInt(this.xmlDoc.getElementsByTagName("map")[0].getAttribute("height"));
    this.tile.width = parseInt(this.xmlDoc.getElementsByTagName("map")[0].getAttribute("tilewidth"));
    this.tile.height = parseInt(this.xmlDoc.getElementsByTagName("map")[0].getAttribute("tileheight"));

    this.totalImages = this.xmlDoc.getElementsByTagName("tileset").length;

    for(var i = 0; i < this.xmlDoc.getElementsByTagName("tileset").length; i++) {
        this.tileset.push(self.createTileset(i));
    }

    for(var i = 0; i < this.xmlDoc.getElementsByTagName("layer").length; i++) {
        this.layer.push(self.createLayer(i));
    }

    for(var i = 0; i < this.xmlDoc.getElementsByTagName("object").length; i++) {
    	var _s = {name: this.xmlDoc.getElementsByTagName("object")[i].getAttribute("name"), type: this.xmlDoc.getElementsByTagName("object")[i].getAttribute("type"), x: this.xmlDoc.getElementsByTagName("object")[i].getAttribute("x"), y: this.xmlDoc.getElementsByTagName("object")[i].getAttribute("y")};
    	var _property = new Array();
    	for(var j = 0; j < this.xmlDoc.getElementsByTagName("object")[i].getElementsByTagName("property").length; j++) {
    		var _n = this.xmlDoc.getElementsByTagName("object")[i].getElementsByTagName("property")[j].getAttribute("name");
    		var _v = this.xmlDoc.getElementsByTagName("object")[i].getElementsByTagName("property")[j].getAttribute("value");
    		_property.push({name: _n, value: _v});
    	}
    	this.sprite.push({object: _s, property: _property});
    }

    var interval = setInterval(function(){self.loadResources(interval)}, 100);

    return this;
};

Map.prototype.getTilesetId = function(_tileset, _t) {
    for(var i = _tileset.length - 1; i >= 0 ; i--) {
        if(_t >= _tileset[i].firstGid) {
            return i;
        }
    }
    return -1;
};

Map.prototype.createData = function(_i, _layer, _tileset, _t, _tilesetId, _l) {
    if(_tilesetId >= 0) {
        this.t = _t;
        this.t = this.t - _tileset.firstGid;
        this.x = Math.floor(_i % _layer.width) * _tileset.width;
        this.y = Math.floor(_i / _layer.width) * _tileset.height;
        this.frame = {x: this.t * _tileset.width % _tileset.image.width, y: Math.floor(this.t  * _tileset.width / _tileset.image.width) * _tileset.height};
        this.l = _l;
        this.tilesetId = _tilesetId;
        this.twidth = _tileset.width;
        this.theight = _tileset.height;
        this.tvisible = true;
        this.collide = true;
    } else {
        this.t = null;
        this.x = null;
        this.y = null;
        this.frame = {x: null, y: null};
        this.l = _l;
        this.tilesetId = -1;
        this.twidth = null;
        this.theight = null;
        this.tvisible = false;
        this.collide = false;
    }
    return {t: this.t, position: {x: this.x, y: this.y}, frame: this.frame, layer: this.l, tilesetId: this.tilesetId, width: this.twidth, height: this.theight, visible: this.tvisible, collide: this.collide};
};

Map.prototype.createTileset = function(_i) {
	var self = this;

	var t = this.name.split('/');
	var path = '';

    this.firstGid = parseInt(this.xmlDoc.getElementsByTagName("tileset")[_i].getAttribute("firstgid"));
    this.name = this.xmlDoc.getElementsByTagName("tileset")[_i].getAttribute("name");
    this.twidth = parseInt(this.xmlDoc.getElementsByTagName("tileset")[_i].getAttribute("tilewidth"));
    this.theight = parseInt(this.xmlDoc.getElementsByTagName("tileset")[_i].getAttribute("tileheight"));

    for(var i = 0; i < t.length - 1; i++) {
		path += t[i] + '/';
	}

    this.image = this.game.sprite.loadMap(path + this.xmlDoc.getElementsByTagName("image")[_i].getAttribute("source"));
    return {firstGid: this.firstGid, name: this.name, width: this.twidth, height: this.theight, image: this.image};
};

Map.prototype.loadResources = function(_interval) {
	var self = this;
	if(this.game.sprite.isLoaded()) {
		clearInterval(_interval);
	    var counter = 0;
    	for(var i = 0; i < this.layer.length; i++) {
        	for(var j = 0; j < this.layer[i].width * this.layer[i].height; j++) {
            	var t = parseInt(this.xmlDoc.getElementsByTagName("tile")[counter].getAttribute("gid"));
            	var d = self.getTilesetId(this.tileset, t);
            	this.layer[i].data.push(self.createData(j, this.layer[i], this.tileset[d], t, d, i));
            	counter++;
        	}
        	self.createContext(i);
        }
    }
};

Map.prototype.createContext = function(_i) {
	for(var i = 0; i < this.layer[_i].data.length; i++) {
        var Id = this.layer[_i].data[i].tilesetId;
        if(Id >= 0 && this.layer[_i].data[i].visible) {
            this.context[_i].save();
            this.context[_i].globalAlpha = this.layer[this.layer[_i].data[i].layer].alpha;
            this.context[_i].drawImage(this.tileset[Id].image, this.layer[_i].data[i].frame.x, this.layer[_i].data[i].frame.y, this.tileset[Id].width, this.tileset[Id].height, this.layer[_i].data[i].position.x, this.layer[_i].data[i].position.y, this.tileset[Id].width, this.tileset[Id].height);
            this.context[_i].restore();
        }
    }
};

Map.prototype.createLayer = function(_i) {
    this.name = this.xmlDoc.getElementsByTagName("layer")[_i].getAttribute("name");
    this.width = parseInt(this.xmlDoc.getElementsByTagName("layer")[_i].getAttribute("width"));
    this.height = parseInt(this.xmlDoc.getElementsByTagName("layer")[_i].getAttribute("height"));
    this.alpha = parseFloat(this.xmlDoc.getElementsByTagName("layer")[_i].getAttribute("opacity"));
    if(!this.alpha) {
        this.alpha = 1;
    }

    var _scrollable = true;
    var _scroll = {x: 0, y: 0, speed: 1};
    var _position = {x: 0, y: 0};
    var _visible = true;
    var _collidable = false;
    var _main = false;

    var l = this.xmlDoc.getElementsByTagName("layer")[_i].getElementsByTagName("property");
    for(var i = 0; i < l.length; i++) {
    	switch(l[i].getAttribute("name")) {
    		case 'scrollable':
    			_scrollable = l[i].getAttribute("value") === 'true' ? true : false;
    			break;
    		case 'scroll.x':
    			_scroll.x = l[i].getAttribute("value");
    			_scroll.x = parseInt(_scroll.x);
    			break;
    		case 'scroll.y':
    			_scroll.y = l[i].getAttribute("value");
    			_scroll.y = parseInt(_scroll.y);
    			break;
    		case 'scroll.speed':
    			_scroll.speed = l[i].getAttribute("value");
    			_scroll.speed = parseFloat(_scroll.speed);
    			break;
    		case 'position.x':
    			_position.x = l[i].getAttribute("value");
    			_position.x = parseInt(_position.x);
    			break;
    		case 'position.y':
    			_position.y = l[i].getAttribute("value");
    			_position.y = parseInt(_position.y);
    			break;
    		case 'visible':
    			_visible = l[i].getAttribute("value") === 'true' ? true : false;
    			break;
    		case 'collidable':
    			_collidable = l[i].getAttribute("value") === 'true' ? true : false;
    			break;
    		case 'main.layer':
    			_main = l[i].getAttribute("value") === 'true' ? true : false;
    	}
    }

	this.canvas.push(document.createElement('canvas'));
	this.context.push(this.canvas[_i].getContext('2d'));
    this.canvas[_i].width = this.width * this.tile.width;
    this.canvas[_i].height = this.height * this.tile.height;

    return {name: this.name, width: this.width, height: this.height, alpha: this.alpha, tileset: -1, scrollable: _scrollable, scroll: _scroll, position: _position, visible: _visible, collidable: _collidable, main: _main, data: new Array()};
};

Map.prototype.getMainLayer = function() {
    for(var i = 0; i < this.layer.length; i++) {
        if(this.layer[i].main) {
            return i;
        }
    }
    return -1;
};

Map.prototype.getLayerIdByName = function(_name) {
    for(var i = 0; i < this.layer.length; i++) {
        if(this.layer[i].name === _name) {
            return i;
        }
    }
    return -1;
};

Map.prototype.getTile = function(_layer, _x, _y, _width, _height) {
	var _tile = (Math.floor(_y / this.tile.height) * _layer.width) + Math.floor(_x / this.tile.width);
	if((_tile >= _layer.data.length || _tile < 0 || _x > _layer.width * this.tile.width || _x + _width < 0) || (_y > _layer.height * this.tile.height || _y + _height < 0)) {
		return null;
	} else {
		return _tile;
	}
};

Map.prototype.tileExist = function(_name, _x, _y) {
	var _layerId = this.getLayerIdByName(_name);
	var _tile = this.getTile(this.layer[_layerId], _x + Math.abs(this.layer[_layerId].position.x), _y + Math.abs(this.layer[_layerId].position.y), 1, 1);
	if(_tile === null || this.layer[_layerId].data[_tile].tilesetId === -1) {
		return false;
	} else {
		return true;
	}
};

Map.prototype.update = function() {
	for(var i = 0; i < this.layer.length; i++) {
		this.layer[i].position.x += this.layer[i].scroll.x;
		this.layer[i].position.y += this.layer[i].scroll.y;
		this.layer[i].position.x = parseFloat(this.layer[i].position.x.toFixed(3));
		this.layer[i].position.y = parseFloat(this.layer[i].position.y.toFixed(3));
	}
};

Map.prototype.resetScroll = function() {
	for(var i = 0; i < this.layer.length; i++) {
		this.layer[i].scroll.x = 0;
		this.layer[i].scroll.y = 0;
	}
};

Map.prototype.drawLayer = function(_layer) {
	var i = this.findLayer(_layer);
	if(this.layer[i].visible) {
		var w = this.game.canvas.width > this.canvas[i].width ? this.canvas[i].width : this.game.canvas.width;
		var h = this.game.canvas.height > this.canvas[i].height ? this.canvas[i].height : this.game.canvas.height;
		this.game.context.save();
		this.game.context.drawImage(this.canvas[i], Math.round(-this.layer[i].position.x), Math.round(-this.layer[i].position.y), w, h, 0, 0, w, h);
		this.game.context.restore();
	}
};

Map.prototype.draw = function() {
	for(var i = 0; i < this.canvas.length; i++) {
		if(this.layer[i].visible) {
			var w = this.game.canvas.width > this.canvas[i].width ? this.canvas[i].width : this.game.canvas.width;
			var h = this.game.canvas.height > this.canvas[i].height ? this.canvas[i].height : this.game.canvas.height;
			this.game.contextMap.save();
			this.game.contextMap.drawImage(this.canvas[i], Math.round(-this.layer[i].position.x), Math.round(-this.layer[i].position.y), w, h, 0, 0, w, h);
			this.game.contextMap.restore();
		}
	}
};<commit_msg>Fix bug on loading tiled map with more than one tile set<commit_after>function Map(_game) {
	this.game = _game;
	this.canvas = new Array();
	this.context = new Array();
	this.name = null;
	this.xmlHttp = null;
	this.xmlDoc = null;
	this.tileset = new Array();
    this.layer = new Array();
    this.data = new Array();
    this.width = null;
    this.height = null;
    this.tile = {width: null, height: null};
    this.visible = true;
    this.sprite = new Array();
    this.path = '';

    return this;
};

Map.prototype.load = function(_name) {
	var self = this;
	var t = _name.split('/');
	for(var i = 0; i < t.length - 1; i++) {
		this.path += t[i] + '/';
	}
	this.name = _name;
    this.xmlHttp = new XMLHttpRequest();
    if(this.xmlHttp.overrideMimeType) {
    	this.xmlHttp.overrideMimeType("text/xml");
    }
    this.xmlHttp.open("GET", this.name, false);
	this.xmlHttp.send();
    if(this.xmlHttp.status === 200) {
		this.xmlDoc = this.xmlHttp.responseXML;
    }

    this.width = parseInt(this.xmlDoc.getElementsByTagName("map")[0].getAttribute("width"));
    this.height = parseInt(this.xmlDoc.getElementsByTagName("map")[0].getAttribute("height"));
    this.tile.width = parseInt(this.xmlDoc.getElementsByTagName("map")[0].getAttribute("tilewidth"));
    this.tile.height = parseInt(this.xmlDoc.getElementsByTagName("map")[0].getAttribute("tileheight"));

    this.totalImages = this.xmlDoc.getElementsByTagName("tileset").length;

    for(var i = 0; i < this.xmlDoc.getElementsByTagName("tileset").length; i++) {
        this.tileset.push(self.createTileset(i));
    }

    for(var i = 0; i < this.xmlDoc.getElementsByTagName("layer").length; i++) {
        this.layer.push(self.createLayer(i));
    }

    for(var i = 0; i < this.xmlDoc.getElementsByTagName("object").length; i++) {
    	var _s = {name: this.xmlDoc.getElementsByTagName("object")[i].getAttribute("name"), type: this.xmlDoc.getElementsByTagName("object")[i].getAttribute("type"), x: this.xmlDoc.getElementsByTagName("object")[i].getAttribute("x"), y: this.xmlDoc.getElementsByTagName("object")[i].getAttribute("y")};
    	var _property = new Array();
    	for(var j = 0; j < this.xmlDoc.getElementsByTagName("object")[i].getElementsByTagName("property").length; j++) {
    		var _n = this.xmlDoc.getElementsByTagName("object")[i].getElementsByTagName("property")[j].getAttribute("name");
    		var _v = this.xmlDoc.getElementsByTagName("object")[i].getElementsByTagName("property")[j].getAttribute("value");
    		_property.push({name: _n, value: _v});
    	}
    	this.sprite.push({object: _s, property: _property});
    }

    var interval = setInterval(function(){self.loadResources(interval)}, 100);

    return this;
};

Map.prototype.getTilesetId = function(_tileset, _t) {
    for(var i = _tileset.length - 1; i >= 0 ; i--) {
        if(_t >= _tileset[i].firstGid) {
            return i;
        }
    }
    return -1;
};

Map.prototype.createData = function(_i, _layer, _tileset, _t, _tilesetId, _l) {
    if(_tilesetId >= 0) {
        this.t = _t;
        this.t = this.t - _tileset.firstGid;
        this.x = Math.floor(_i % _layer.width) * _tileset.width;
        this.y = Math.floor(_i / _layer.width) * _tileset.height;
        this.frame = {x: this.t * _tileset.width % _tileset.image.width, y: Math.floor(this.t  * _tileset.width / _tileset.image.width) * _tileset.height};
        this.l = _l;
        this.tilesetId = _tilesetId;
        this.twidth = _tileset.width;
        this.theight = _tileset.height;
        this.tvisible = true;
        this.collide = true;
    } else {
        this.t = null;
        this.x = null;
        this.y = null;
        this.frame = {x: null, y: null};
        this.l = _l;
        this.tilesetId = -1;
        this.twidth = null;
        this.theight = null;
        this.tvisible = false;
        this.collide = false;
    }
    return {t: this.t, position: {x: this.x, y: this.y}, frame: this.frame, layer: this.l, tilesetId: this.tilesetId, width: this.twidth, height: this.theight, visible: this.tvisible, collide: this.collide};
};

Map.prototype.createTileset = function(_i) {
	var self = this;

    this.firstGid = parseInt(this.xmlDoc.getElementsByTagName("tileset")[_i].getAttribute("firstgid"));
    this.name = this.xmlDoc.getElementsByTagName("tileset")[_i].getAttribute("name");
    this.twidth = parseInt(this.xmlDoc.getElementsByTagName("tileset")[_i].getAttribute("tilewidth"));
    this.theight = parseInt(this.xmlDoc.getElementsByTagName("tileset")[_i].getAttribute("tileheight"));

    this.image = this.game.sprite.loadMap(this.path + this.xmlDoc.getElementsByTagName("image")[_i].getAttribute("source"));
    return {firstGid: this.firstGid, name: this.name, width: this.twidth, height: this.theight, image: this.image};
};

Map.prototype.loadResources = function(_interval) {
	var self = this;
	if(this.game.sprite.isLoaded()) {
		clearInterval(_interval);
	    var counter = 0;
    	for(var i = 0; i < this.layer.length; i++) {
        	for(var j = 0; j < this.layer[i].width * this.layer[i].height; j++) {
            	var t = parseInt(this.xmlDoc.getElementsByTagName("tile")[counter].getAttribute("gid"));
            	var d = self.getTilesetId(this.tileset, t);
            	this.layer[i].data.push(self.createData(j, this.layer[i], this.tileset[d], t, d, i));
            	counter++;
        	}
        	self.createContext(i);
        }
    }
};

Map.prototype.createContext = function(_i) {
	for(var i = 0; i < this.layer[_i].data.length; i++) {
        var Id = this.layer[_i].data[i].tilesetId;
        if(Id >= 0 && this.layer[_i].data[i].visible) {
            this.context[_i].save();
            this.context[_i].globalAlpha = this.layer[this.layer[_i].data[i].layer].alpha;
            this.context[_i].drawImage(this.tileset[Id].image, this.layer[_i].data[i].frame.x, this.layer[_i].data[i].frame.y, this.tileset[Id].width, this.tileset[Id].height, this.layer[_i].data[i].position.x, this.layer[_i].data[i].position.y, this.tileset[Id].width, this.tileset[Id].height);
            this.context[_i].restore();
        }
    }
};

Map.prototype.createLayer = function(_i) {
    this.name = this.xmlDoc.getElementsByTagName("layer")[_i].getAttribute("name");
    this.width = parseInt(this.xmlDoc.getElementsByTagName("layer")[_i].getAttribute("width"));
    this.height = parseInt(this.xmlDoc.getElementsByTagName("layer")[_i].getAttribute("height"));
    this.alpha = parseFloat(this.xmlDoc.getElementsByTagName("layer")[_i].getAttribute("opacity"));
    if(!this.alpha) {
        this.alpha = 1;
    }

    var _scrollable = true;
    var _scroll = {x: 0, y: 0, speed: 1};
    var _position = {x: 0, y: 0};
    var _visible = true;
    var _collidable = false;
    var _main = false;

    var l = this.xmlDoc.getElementsByTagName("layer")[_i].getElementsByTagName("property");
    for(var i = 0; i < l.length; i++) {
    	switch(l[i].getAttribute("name")) {
    		case 'scrollable':
    			_scrollable = l[i].getAttribute("value") === 'true' ? true : false;
    			break;
    		case 'scroll.x':
    			_scroll.x = l[i].getAttribute("value");
    			_scroll.x = parseInt(_scroll.x);
    			break;
    		case 'scroll.y':
    			_scroll.y = l[i].getAttribute("value");
    			_scroll.y = parseInt(_scroll.y);
    			break;
    		case 'scroll.speed':
    			_scroll.speed = l[i].getAttribute("value");
    			_scroll.speed = parseFloat(_scroll.speed);
    			break;
    		case 'position.x':
    			_position.x = l[i].getAttribute("value");
    			_position.x = parseInt(_position.x);
    			break;
    		case 'position.y':
    			_position.y = l[i].getAttribute("value");
    			_position.y = parseInt(_position.y);
    			break;
    		case 'visible':
    			_visible = l[i].getAttribute("value") === 'true' ? true : false;
    			break;
    		case 'collidable':
    			_collidable = l[i].getAttribute("value") === 'true' ? true : false;
    			break;
    		case 'main.layer':
    			_main = l[i].getAttribute("value") === 'true' ? true : false;
    	}
    }

	this.canvas.push(document.createElement('canvas'));
	this.context.push(this.canvas[_i].getContext('2d'));
    this.canvas[_i].width = this.width * this.tile.width;
    this.canvas[_i].height = this.height * this.tile.height;

    return {name: this.name, width: this.width, height: this.height, alpha: this.alpha, tileset: -1, scrollable: _scrollable, scroll: _scroll, position: _position, visible: _visible, collidable: _collidable, main: _main, data: new Array()};
};

Map.prototype.getMainLayer = function() {
    for(var i = 0; i < this.layer.length; i++) {
        if(this.layer[i].main) {
            return i;
        }
    }
    return -1;
};

Map.prototype.getLayerIdByName = function(_name) {
    for(var i = 0; i < this.layer.length; i++) {
        if(this.layer[i].name === _name) {
            return i;
        }
    }
    return -1;
};

Map.prototype.getTile = function(_layer, _x, _y, _width, _height) {
	var _tile = (Math.floor(_y / this.tile.height) * _layer.width) + Math.floor(_x / this.tile.width);
	if((_tile >= _layer.data.length || _tile < 0 || _x > _layer.width * this.tile.width || _x + _width < 0) || (_y > _layer.height * this.tile.height || _y + _height < 0)) {
		return null;
	} else {
		return _tile;
	}
};

Map.prototype.tileExist = function(_name, _x, _y) {
	var _layerId = this.getLayerIdByName(_name);
	var _tile = this.getTile(this.layer[_layerId], _x + Math.abs(this.layer[_layerId].position.x), _y + Math.abs(this.layer[_layerId].position.y), 1, 1);
	if(_tile === null || this.layer[_layerId].data[_tile].tilesetId === -1) {
		return false;
	} else {
		return true;
	}
};

Map.prototype.update = function() {
	for(var i = 0; i < this.layer.length; i++) {
		this.layer[i].position.x += this.layer[i].scroll.x;
		this.layer[i].position.y += this.layer[i].scroll.y;
		this.layer[i].position.x = parseFloat(this.layer[i].position.x.toFixed(3));
		this.layer[i].position.y = parseFloat(this.layer[i].position.y.toFixed(3));
	}
};

Map.prototype.resetScroll = function() {
	for(var i = 0; i < this.layer.length; i++) {
		this.layer[i].scroll.x = 0;
		this.layer[i].scroll.y = 0;
	}
};

Map.prototype.drawLayer = function(_layer) {
	var i = this.findLayer(_layer);
	if(this.layer[i].visible) {
		var w = this.game.canvas.width > this.canvas[i].width ? this.canvas[i].width : this.game.canvas.width;
		var h = this.game.canvas.height > this.canvas[i].height ? this.canvas[i].height : this.game.canvas.height;
		this.game.context.save();
		this.game.context.drawImage(this.canvas[i], Math.round(-this.layer[i].position.x), Math.round(-this.layer[i].position.y), w, h, 0, 0, w, h);
		this.game.context.restore();
	}
};

Map.prototype.draw = function() {
	for(var i = 0; i < this.canvas.length; i++) {
		if(this.layer[i].visible) {
			var w = this.game.canvas.width > this.canvas[i].width ? this.canvas[i].width : this.game.canvas.width;
			var h = this.game.canvas.height > this.canvas[i].height ? this.canvas[i].height : this.game.canvas.height;
			this.game.contextMap.save();
			this.game.contextMap.drawImage(this.canvas[i], Math.round(-this.layer[i].position.x), Math.round(-this.layer[i].position.y), w, h, 0, 0, w, h);
			this.game.contextMap.restore();
		}
	}
};<|endoftext|>