<commit_before>
var fs = require('fs');
var path = require('path');

var moduleOptions = require('./options');
var command = moduleOptions.command;
var replaceTokens = {};

//
// export
//

exports.create = create;
exports.options = moduleOptions;
exports.command = function(args, config){
  return command(args, config, create);
};

//
// if launched directly, run builder
//
if (process.mainModule === module)
  command(null, null, create);

//
// main function
//

function create(options){

  options = moduleOptions.norm(options);

  //
  // init
  //

  var target;
  var output = [];

  console.log('Create file structure:');
  switch (options.topic)
  {
    case 'app':
    case 'module':
      target = options.topic == 'app' ? options.output : path.join(options.output, options.name);
      if (fs.existsSync(target))
      {
        console.warn('Output folder (' + target + ') is already exists. Delete it first or choose another one.')
        process.exit();
      }

      output = output.concat(resolveDirPath(target));

      break;

    case 'type':
      options.instanceName = options.name.charAt(0).toLowerCase() + options.name.substr(1);
      target = options.output;

      if (!fs.existsSync(target))
      {
        console.warn('Destination folder (' + target + ') does not exists.')
        process.exit();
      }

      break;
  }

  //
  // create file structure
  //

  createFiles(options.templateDir, output, {
    name: options.name,
    appName: options.topic == 'app' ? options.name : options.appName,
    appTitle: (options.title || 'My app').replace(/\'/g, '\\\''),
    instanceName: options.instanceName,
    type: options.type,
    l10n: !!options.l10n
  });

  //
  // git
  //

  if (options.topic == 'app' && options.git)
  {
    console.log('\nClone basis.js repo');
    cloneBasis(target + '/lib/basisjs');
  }
}

//
// tools
//

function replaceSpecial(str, values){
  return str
    // cut
    .replace(/\{\s*(!!?)\s*([a-z\d_]+)\s*\}(.*(?:\r\n?|\n\r?|$))/ig, function(m, op, name, rest){
      return (op == '!' ? !values[name] : !!values[name]) ? rest : '';
    })
    // set value
    .replace(/\{\s*=\s*([a-z\d_]+)\s*\}/ig, function(m, name){
      if (name in values == false)
      {
        console.warn('unknown replace token:', name);
        return m;
      }
      else
        return values[name];
    });
}

function indent(level){
  var res = [];
  for (var i = 0; i < level; i++)
    res.push('  ');
  return res.join('');
}

function createFiles(input, output, values){
  var list = fs.readdirSync(input);
  for (var i = 0, fn; fn = list[i]; i++)
  {
    var infn = input + '/' + fn;
    var outputfn = replaceSpecial(fn, values);
    var stat = fs.statSync(infn);

    if (!outputfn)
      continue;

    output.push(outputfn);
    outputfn = output.join('/');

    if (fs.existsSync(outputfn))
    {
      console.warn('[ERROR] '.red + outputfn + ' already exists');
      process.exit();
    }

    if (stat.isDirectory())
    {
      console.log(indent(output.length - 1)/* + 'Create path:'*/ + output.slice(1).join('/'));
      fs.mkdirSync(outputfn);
      createFiles(infn, output, values);
    }
    else
    {
      console.log(indent(output.length - 1)/* + 'Create file:'*/ + output.slice(1).join('/'));
      fs.writeFileSync(outputfn, replaceSpecial(fs.readFileSync(infn, 'utf-8'), values));
    }

    output.pop();
  }
}

function cloneBasis(path){
  require('child_process').spawn(
    'git',
    ['clone', 'http://github.com/basisjs/basisjs', path],
    { stdio: 'inherit' }
  ).on('exit', function (code) {
    if (code)
      console.log('\nSome problems here, git exited with code', code);
  });
}

function resolveDirPath(dir){
  var dirpath = path.normalize(dir + path.sep);
  var output = [];
  if (!fs.existsSync(dirpath))
  {
    var parts = dirpath.split(path.sep);
    var curpath = parts[0] + path.sep;
    for (var i = 1; i < parts.length; i++)
    {
      curpath += parts[i] + path.sep;
      //console.log(curpath, parts[i], fs.existsSync(curpath));
      if (!fs.existsSync(curpath))
      {
        output.push(parts[i]);
        console.log(indent(output.length - 1) + parts[i]);
        fs.mkdirSync(curpath);
      }
    }
  }
  return output;
}<commit_msg>fix special tokens replacing<commit_after>
var fs = require('fs');
var path = require('path');

var moduleOptions = require('./options');
var command = moduleOptions.command;
var replaceTokens = {};

//
// export
//

exports.create = create;
exports.options = moduleOptions;
exports.command = function(args, config){
  return command(args, config, create);
};

//
// if launched directly, run builder
//
if (process.mainModule === module)
  command(null, null, create);

//
// main function
//

function create(options){

  options = moduleOptions.norm(options);

  //
  // init
  //

  var target;
  var output = [];

  console.log('Create file structure:');
  switch (options.topic)
  {
    case 'app':
    case 'module':
      target = options.topic == 'app' ? options.output : path.join(options.output, options.name);
      if (fs.existsSync(target))
      {
        console.warn('Output folder (' + target + ') is already exists. Delete it first or choose another one.')
        process.exit();
      }

      output = output.concat(resolveDirPath(target));

      break;

    case 'type':
      options.instanceName = options.name.charAt(0).toLowerCase() + options.name.substr(1);
      target = options.output;

      if (!fs.existsSync(target))
      {
        console.warn('Destination folder (' + target + ') does not exists.')
        process.exit();
      }

      break;
  }

  //
  // create file structure
  //

  createFiles(options.templateDir, output, {
    name: options.name,
    appName: options.topic == 'app' ? options.name : options.appName,
    appTitle: (options.title || 'My app').replace(/\'/g, '\\\''),
    instanceName: options.instanceName,
    type: options.type,
    l10n: !!options.l10n
  });

  //
  // git
  //

  if (options.topic == 'app' && options.git)
  {
    console.log('\nClone basis.js repo');
    cloneBasis(target + '/lib/basisjs');
  }
}

//
// tools
//

function replaceSpecial(str, values){
  return str
    // cut
    .replace(/\{\s*(!!?)\s*([a-z\d_]+)\s*\}(.*(?:\r\n?|\n\r?|$))/ig, function(m, op, name, rest){
      return (op == '!' ? !values[name] : !!values[name]) ? replaceSpecial(rest, values) : '';
    })
    // set value
    .replace(/\{\s*=\s*([a-z\d_]+)\s*\}/ig, function(m, name){
      if (name in values == false)
      {
        console.warn('unknown replace token:', name);
        return m;
      }
      else
        return values[name];
    });
}

function indent(level){
  var res = [];
  for (var i = 0; i < level; i++)
    res.push('  ');
  return res.join('');
}

function createFiles(input, output, values){
  var list = fs.readdirSync(input);
  for (var i = 0, fn; fn = list[i]; i++)
  {
    var infn = input + '/' + fn;
    var outputfn = replaceSpecial(fn, values);
    var stat = fs.statSync(infn);

    if (!outputfn)
      continue;

    output.push(outputfn);
    outputfn = output.join('/');

    if (fs.existsSync(outputfn))
    {
      console.warn('[ERROR] '.red + outputfn + ' already exists');
      process.exit();
    }

    if (stat.isDirectory())
    {
      console.log(indent(output.length - 1)/* + 'Create path:'*/ + output.slice(1).join('/'));
      fs.mkdirSync(outputfn);
      createFiles(infn, output, values);
    }
    else
    {
      console.log(indent(output.length - 1)/* + 'Create file:'*/ + output.slice(1).join('/'));
      fs.writeFileSync(outputfn, replaceSpecial(fs.readFileSync(infn, 'utf-8'), values));
    }

    output.pop();
  }
}

function cloneBasis(path){
  require('child_process').spawn(
    'git',
    ['clone', 'http://github.com/basisjs/basisjs', path],
    { stdio: 'inherit' }
  ).on('exit', function (code) {
    if (code)
      console.log('\nSome problems here, git exited with code', code);
  });
}

function resolveDirPath(dir){
  var dirpath = path.normalize(dir + path.sep);
  var output = [];
  if (!fs.existsSync(dirpath))
  {
    var parts = dirpath.split(path.sep);
    var curpath = parts[0] + path.sep;
    for (var i = 1; i < parts.length; i++)
    {
      curpath += parts[i] + path.sep;
      //console.log(curpath, parts[i], fs.existsSync(curpath));
      if (!fs.existsSync(curpath))
      {
        output.push(parts[i]);
        console.log(indent(output.length - 1) + parts[i]);
        fs.mkdirSync(curpath);
      }
    }
  }
  return output;
}<|endoftext|>


<commit_before>import {describe, it} from 'mocha';
import assert from 'assert';
import path from 'path';
import sh from 'shelljs';
import {countOccurences, runSSHCommand} from '../../utils';

const servers = require(path.resolve(__rootdir, 'tests/servers'));

describe('module - meteor', function () {
  it('TODO write tests');

  describe('help', function () {
    it('TODO write tests');
  });

  describe('logs', function () {
    it('TODO write tests');
  });

  describe('setup', function () {
    it('TODO write tests');
  });

  describe('push', function () {
    function checkBundle() {
      const serverInfo = servers['mymeteor'];

      return async function(done) {
        this.timeout(60000);
        sh.cd(path.resolve('/tmp','tests/project-1'));

        const out = sh.exec('mup meteor push', {silent: true});
        assert.equal(out.code, 0);

        const num = countOccurences('Pushing Meteor app bundle to the server: SUCCESS', out.output);
        assert.equal(num, 1);

        const sshOut = await runSSHCommand(serverInfo, 'ls -al /opt/myapp/tmp/bundle.tar.gz');
        assert.equal(sshOut.code, 0);

        done();
      };
    }
    it('should push meteor app bundle to "meteor" vm', checkBundle());
  });

  describe('start', function () {
    it('TODO write tests');
  });

  describe('stop', function () {
    it('TODO write tests');
  });
});
<commit_msg>added meteor setup tests<commit_after>import {describe, it} from 'mocha';
import assert from 'assert';
import path from 'path';
import sh from 'shelljs';
import {countOccurences, runSSHCommand} from '../../utils';

const servers = require(path.resolve(__rootdir, 'tests/servers'));

describe('module - meteor', function () {
  it('TODO write tests');

  describe('help', function () {
    it('TODO write tests');
  });

  describe('logs', function () {
    it('TODO write tests');
  });

  describe('setup', function () {
    this.timeout(60000);
    it('should setup enviranment on "meteor" vm', async () => {
      const serverInfo = servers['mymeteor'];

      await runSSHCommand(serverInfo, 'rm -rf /opt/myapp || :');
      await runSSHCommand(serverInfo, 'sudo apt-get -qq install -y tree');

      const out = sh.exec('mup meteor setup');
      assert.equal(out.code, 0);

      const num = countOccurences('setup environment: SUCCESS', out.output);
      assert.equal(num, 1);

      const sshOut = await runSSHCommand(serverInfo, 'tree -pufid /opt');
      assert.equal(countOccurences('/opt/myapp', sshOut.output), 3);
      assert.equal(countOccurences('/opt/myapp/config', sshOut.output), 1);
      assert.equal(countOccurences('/opt/myapp/tmp', sshOut.output), 1);

      //done();
    });
  });

  describe('push', function () {
    function checkBundle() {
      const serverInfo = servers['mymeteor'];

      return async function(done) {
        this.timeout(60000);
        sh.cd(path.resolve('/tmp','tests/project-1'));

        const out = sh.exec('mup meteor push', {silent: true});
        assert.equal(out.code, 0);

        const num = countOccurences('Pushing Meteor app bundle to the server: SUCCESS', out.output);
        assert.equal(num, 1);

        const sshOut = await runSSHCommand(serverInfo, 'ls -al /opt/myapp/tmp/bundle.tar.gz');
        assert.equal(sshOut.code, 0);

        done();
      };
    }
    it('should push meteor app bundle to "meteor" vm', checkBundle());
  });

  describe('start', function () {
    it('TODO write tests');
  });

  describe('stop', function () {
    it('TODO write tests');
  });
});
<|endoftext|>


<commit_before>'use strict'

const assert = require('assert')
const Cucumber = require.main.require('cucumber/lib/cucumber')

module.exports = class CucumberAPI {

  constructor (configuration) {
    this.formatters = configuration.getFormatters()
    this.featuresResult = Cucumber.Runtime.FeaturesResult()
  }

  * broadcastEvent (event) {
    const jobs = this.formatters.map((formatter) => {
      return new Promise((resolve) => {
        formatter.hear(event, resolve)
      })
    })

    yield * this.logLastFailedStep()
    yield jobs
  }

  * logAfterFeatures (features) {
    const event = Cucumber.Runtime.AstTreeWalker.Event(Cucumber.Runtime.AstTreeWalker.FEATURES_EVENT_NAME, { features: features })
    yield * this.broadcastEvent(event.replicateAsPostEvent())
  }

  * logFeaturesResult () {
    const event = Cucumber.Runtime.AstTreeWalker.Event(Cucumber.Runtime.AstTreeWalker.FEATURES_RESULT_EVENT_NAME, { featuresResult: this.featuresResult })
    yield * this.broadcastEvent(event)
  }

  * logBeforeFeature (feature) {
    const event = Cucumber.Runtime.AstTreeWalker.Event(Cucumber.Runtime.AstTreeWalker.FEATURE_EVENT_NAME, { feature: feature })
    yield * this.broadcastEvent(event.replicateAsPreEvent())
    this.prevTime = this.getTime()
  }

  * logBackground (background) {
    const event = Cucumber.Runtime.AstTreeWalker.Event(Cucumber.Runtime.AstTreeWalker.BACKGROUND_EVENT_NAME, { background: background })
    yield * this.broadcastEvent(event.replicateAsPreEvent())
  }

  * logBeforeScenario (scenario) {
    this.scenarioResult = Cucumber.Runtime.ScenarioResult(scenario)
    const event = Cucumber.Runtime.AstTreeWalker.Event(Cucumber.Runtime.AstTreeWalker.SCENARIO_EVENT_NAME, { scenario: scenario })
    yield * this.broadcastEvent(event.replicateAsPreEvent())
    this.attachments = []
  }

  * logScenarioResult () {
    assert(this.scenarioResult)
    this.featuresResult.witnessScenarioResult(this.scenarioResult)
    const event = Cucumber.Runtime.AstTreeWalker.Event(Cucumber.Runtime.AstTreeWalker.SCENARIO_RESULT_EVENT_NAME, { scenarioResult: this.scenarioResult })
    yield * this.broadcastEvent(event)
  }

  * logAmbiguousStep (step) {
    const ambiguousStepResult = Cucumber.Runtime.StepResult({
      ambiguousStepDefinitions: step.stepDefinitions,
      step: step,
      status: Cucumber.Status.AMBIGUOUS
    })
    yield * this.logStepResult(ambiguousStepResult)
  }

  * logUndefinedStep (step) {
    const undefinedStepResult = Cucumber.Runtime.StepResult({ step: step, status: Cucumber.Status.UNDEFINED })
    yield * this.logStepResult(undefinedStepResult)
  }

  * logSkippedStep (step) {
    const undefinedStepResult = Cucumber.Runtime.StepResult({
      step: step,
      stepDefinition: step.stepDefinitions[0],
      status: Cucumber.Status.SKIPPED
    })
    yield * this.logStepResult(undefinedStepResult)
  }

  * logPassedStep (step) {
    if (step.reported) return

    const passedStepResult = Cucumber.Runtime.StepResult({
      step: step,
      stepDefinition: step.stepDefinitions[0],
      duration: this.durationInNanoseconds(this.prevTime),
      attachments: [],
      status: Cucumber.Status.PASSED
    })
    yield * this.logStepResult(passedStepResult)
  }

  * logFailedStep (step, failure, skipRemainingSteps) {
    if (step.reported) return

    yield * this.logLastFailedStep()
    this.lastFailedStepResultData = {
      step: step,
      stepDefinition: step.stepDefinitions[0],
      duration: this.durationInNanoseconds(this.prevTime),
      attachments: [],
      failureException: failure,
      status: Cucumber.Status.FAILED,
      skipRemainingSteps: skipRemainingSteps
    }
    step.reported = true
  }

  * logLastFailedStep () {
    if (this.lastFailedStepResultData) {
      this.lastFailedStepResultData.attachments = this.attachments
      const failedStepResult = Cucumber.Runtime.StepResult(this.lastFailedStepResultData)
      const stepResultData = this.lastFailedStepResultData
      this.lastFailedStepResultData = undefined
      yield * this.logStepResult(failedStepResult)

      if (stepResultData.skipRemainingSteps) {
        const steps = stepResultData.step.getScenario().getSteps()
        let skip = false
        for (let i = 0; i < steps.length(); i++) {
          const step = steps.getAtIndex(i)

          if (skip) {
            yield * this.logSkippedStep(step)
          }

          if (step === stepResultData.step) skip = true
        }
      }
    }
  }

  * logStepResult (stepResult) {
    this.scenarioResult.witnessStepResult(stepResult)
    this.featuresResult.witnessStepResult(stepResult)
    const event = Cucumber.Runtime.AstTreeWalker.Event(Cucumber.Runtime.AstTreeWalker.STEP_RESULT_EVENT_NAME, { stepResult: stepResult })
    yield * this.broadcastEvent(event)
    this.prevTime = this.getTime()
  }

  * addAttachment (data, mimeType) {
    this.attachments.push(Cucumber.Runtime.Attachment({ mimeType: mimeType, data: new VirtualString(data) }))
  }

  getTime () {
    if (typeof process !== 'undefined' && process.hrtime) {
      return process.hrtime()
    } else {
      return new Date().getTime()
    }
  }

  durationInNanoseconds (start) {
    if (typeof process !== 'undefined' && process.hrtime) {
      const duration = process.hrtime(start)
      return duration[0] * 1e9 + duration[1]
    } else {
      return (new Date().getTime() - start) * 1e6
    }
  }
}

class VirtualString {
  constructor (data) {
    this.data = new Buffer(data, 'base64')
    this.length = this.data.length
  }

  charCodeAt (index) {
    return this.data[index]
  }
}
<commit_msg>Fix steps.length is not a function, and remove getAtIndex<commit_after>'use strict'

const assert = require('assert')
const Cucumber = require.main.require('cucumber/lib/cucumber')

module.exports = class CucumberAPI {

  constructor (configuration) {
    this.formatters = configuration.getFormatters()
    this.featuresResult = Cucumber.Runtime.FeaturesResult()
  }

  * broadcastEvent (event) {
    const jobs = this.formatters.map((formatter) => {
      return new Promise((resolve) => {
        formatter.hear(event, resolve)
      })
    })

    yield * this.logLastFailedStep()
    yield jobs
  }

  * logAfterFeatures (features) {
    const event = Cucumber.Runtime.AstTreeWalker.Event(Cucumber.Runtime.AstTreeWalker.FEATURES_EVENT_NAME, { features: features })
    yield * this.broadcastEvent(event.replicateAsPostEvent())
  }

  * logFeaturesResult () {
    const event = Cucumber.Runtime.AstTreeWalker.Event(Cucumber.Runtime.AstTreeWalker.FEATURES_RESULT_EVENT_NAME, { featuresResult: this.featuresResult })
    yield * this.broadcastEvent(event)
  }

  * logBeforeFeature (feature) {
    const event = Cucumber.Runtime.AstTreeWalker.Event(Cucumber.Runtime.AstTreeWalker.FEATURE_EVENT_NAME, { feature: feature })
    yield * this.broadcastEvent(event.replicateAsPreEvent())
    this.prevTime = this.getTime()
  }

  * logBackground (background) {
    const event = Cucumber.Runtime.AstTreeWalker.Event(Cucumber.Runtime.AstTreeWalker.BACKGROUND_EVENT_NAME, { background: background })
    yield * this.broadcastEvent(event.replicateAsPreEvent())
  }

  * logBeforeScenario (scenario) {
    this.scenarioResult = Cucumber.Runtime.ScenarioResult(scenario)
    const event = Cucumber.Runtime.AstTreeWalker.Event(Cucumber.Runtime.AstTreeWalker.SCENARIO_EVENT_NAME, { scenario: scenario })
    yield * this.broadcastEvent(event.replicateAsPreEvent())
    this.attachments = []
  }

  * logScenarioResult () {
    assert(this.scenarioResult)
    this.featuresResult.witnessScenarioResult(this.scenarioResult)
    const event = Cucumber.Runtime.AstTreeWalker.Event(Cucumber.Runtime.AstTreeWalker.SCENARIO_RESULT_EVENT_NAME, { scenarioResult: this.scenarioResult })
    yield * this.broadcastEvent(event)
  }

  * logAmbiguousStep (step) {
    const ambiguousStepResult = Cucumber.Runtime.StepResult({
      ambiguousStepDefinitions: step.stepDefinitions,
      step: step,
      status: Cucumber.Status.AMBIGUOUS
    })
    yield * this.logStepResult(ambiguousStepResult)
  }

  * logUndefinedStep (step) {
    const undefinedStepResult = Cucumber.Runtime.StepResult({ step: step, status: Cucumber.Status.UNDEFINED })
    yield * this.logStepResult(undefinedStepResult)
  }

  * logSkippedStep (step) {
    const undefinedStepResult = Cucumber.Runtime.StepResult({
      step: step,
      stepDefinition: step.stepDefinitions[0],
      status: Cucumber.Status.SKIPPED
    })
    yield * this.logStepResult(undefinedStepResult)
  }

  * logPassedStep (step) {
    if (step.reported) return

    const passedStepResult = Cucumber.Runtime.StepResult({
      step: step,
      stepDefinition: step.stepDefinitions[0],
      duration: this.durationInNanoseconds(this.prevTime),
      attachments: [],
      status: Cucumber.Status.PASSED
    })
    yield * this.logStepResult(passedStepResult)
  }

  * logFailedStep (step, failure, skipRemainingSteps) {
    if (step.reported) return

    yield * this.logLastFailedStep()
    this.lastFailedStepResultData = {
      step: step,
      stepDefinition: step.stepDefinitions[0],
      duration: this.durationInNanoseconds(this.prevTime),
      attachments: [],
      failureException: failure,
      status: Cucumber.Status.FAILED,
      skipRemainingSteps: skipRemainingSteps
    }
    step.reported = true
  }

  * logLastFailedStep () {
    if (this.lastFailedStepResultData) {
      this.lastFailedStepResultData.attachments = this.attachments
      const failedStepResult = Cucumber.Runtime.StepResult(this.lastFailedStepResultData)
      const stepResultData = this.lastFailedStepResultData
      this.lastFailedStepResultData = undefined
      yield * this.logStepResult(failedStepResult)

      if (stepResultData.skipRemainingSteps) {
        const steps = stepResultData.step.getScenario().getSteps()
        let skip = false
        for (let i = 0; i < steps.length; i++) {
          const step = steps[i]

          if (skip) {
            yield * this.logSkippedStep(step)
          }

          if (step === stepResultData.step) skip = true
        }
      }
    }
  }

  * logStepResult (stepResult) {
    this.scenarioResult.witnessStepResult(stepResult)
    this.featuresResult.witnessStepResult(stepResult)
    const event = Cucumber.Runtime.AstTreeWalker.Event(Cucumber.Runtime.AstTreeWalker.STEP_RESULT_EVENT_NAME, { stepResult: stepResult })
    yield * this.broadcastEvent(event)
    this.prevTime = this.getTime()
  }

  * addAttachment (data, mimeType) {
    this.attachments.push(Cucumber.Runtime.Attachment({ mimeType: mimeType, data: new VirtualString(data) }))
  }

  getTime () {
    if (typeof process !== 'undefined' && process.hrtime) {
      return process.hrtime()
    } else {
      return new Date().getTime()
    }
  }

  durationInNanoseconds (start) {
    if (typeof process !== 'undefined' && process.hrtime) {
      const duration = process.hrtime(start)
      return duration[0] * 1e9 + duration[1]
    } else {
      return (new Date().getTime() - start) * 1e6
    }
  }
}

class VirtualString {
  constructor (data) {
    this.data = new Buffer(data, 'base64')
    this.length = this.data.length
  }

  charCodeAt (index) {
    return this.data[index]
  }
}
<|endoftext|>


<commit_before>(function() {
  'use strict';

  exports.init = function(params) {
    var fs = require('fs');
    var path = require('path');
    var shell = require('shelljs');
    var user = params['user'];
    var service = params['service'];
    var pathToFiles = params['pathToFiles'];
    var command = params['command'] || 'node';

    requireParams('service', 'user', 'pathToFiles');
    createUser();
    enableLogging();
    createUpstart();
    enableDaemon();

    function createUser() {
      console.log('creating user ' + service);
    }

    function createUpstart() {
      var format = require('string-template');
      var srcFile = path.join(__dirname, 'template.upstart');
      var _params = {
        command: command,
        service: service,
        user: user
      };

      fs.readFile(srcFile, 'utf8', function(err, data) {
        if (err) {
          throw new Error(err);
        }
        var content = format(data, _params);
        writeUpstart(content);
      });
    }

    function writeUpstart(content) {
      console.log('writing upstart');
      console.log(content);
    }

    function enableLogging() {
      var logPath = path.join(process.env.npm_config_quichean_logging_path, service);
      console.log('log path: ' + logPath);
    }

    function enableDaemon() {
      console.log('enabling daemon');
      console.log('copying files from ' + pathToFiles);
    }

    function requireParams() {
      for (var i = 0; i < arguments.length; i++) {
        if (!params[arguments[i]]) {
          throw new Error('missing required parameter "' + arguments[i] + '"');
        }
      }
    }
  };
})();
<commit_msg>Create user.<commit_after>(function() {
  'use strict';

  exports.init = function(params) {
    var fs = require('fs');
    var path = require('path');
    var shell = require('shelljs');
    var user = params['user'];
    var service = params['service'];
    var pathToFiles = params['pathToFiles'];
    var command = params['command'] || 'node';

    requireParams('service', 'user', 'pathToFiles');
    createUser();
    enableLogging();
    createUpstart();
    enableDaemon();

    function createUser() {
      console.log('creating user "' + user + '"');
      shell.exec(path.join(__dirname, 'createuser.sh') + ' ' + user +
        ' "--shell /bin/bash"');
    }

    function createUpstart() {
      var format = require('string-template');
      var srcFile = path.join(__dirname, 'template.upstart');
      var _params = {
        command: command,
        service: service,
        user: user
      };

      fs.readFile(srcFile, 'utf8', function(err, data) {
        if (err) {
          throw new Error(err);
        }
        var content = format(data, _params);
        writeUpstart(content);
      });
    }

    function writeUpstart(content) {
      console.log('writing upstart');
      console.log(content);
    }

    function enableLogging() {
      var logPath = path.join(process.env.npm_config_quichean_logging_path, service);
      console.log('log path: ' + logPath);
    }

    function enableDaemon() {
      console.log('enabling daemon');
      console.log('copying files from ' + pathToFiles);
    }

    function requireParams() {
      for (var i = 0; i < arguments.length; i++) {
        if (!params[arguments[i]]) {
          throw new Error('missing required parameter "' + arguments[i] + '"');
        }
      }
    }
  };
})();
<|endoftext|>


<commit_before>var util = require('util');
var log = require('../log');

function Daemon(conf) {
  this._components = [];
}

Daemon.prototype.initialize = function(conf) {
  if (conf.verbose) log.setVerbose(conf.verbose);
  log.debug('gearslothd', 'Config parsed:\n',
      util.inspect(conf, { depth: null }));

  if (conf.injector)    this.add('./injector',        conf);
  if (conf.runner)      this.add('./runner',          conf);
  if (conf.controller)  this.add(conf.controllerpath, conf);
  if (conf.ejector)     this.add('./ejector',         conf);
};

Daemon.prototype.add = function(path, conf) {
  var that = this;
  var component = require(path)(conf);
  var id = this._components.length;
  this._components.push({
    component: component,
    connected: false
  });
  if (!component.on)
    return;
  component.on('connect', function() {
    that.setConnected(id, true);
  });
  component.on('disconnect', function() {
    that.setConnected(id, false);
  });
};

Daemon.prototype.allConnected = function() {
  return this._components.reduce(function(acc, component) {
    return acc && component.connected;
  }, true);
};

Daemon.prototype.setConnected = function(id, connected) {
  var prev = this.allConnected();
  this._components[id].connected = connected;
  var next = this.allConnected();
  if (prev && !next)
    log.info('gearslothd', 'Disconnected');
  else if (!prev && next)
    log.info('gearslothd', 'Connected');
};

module.exports = new Daemon();
<commit_msg>Limit recursion depth to avoid huge object dumps<commit_after>var util = require('util');
var log = require('../log');

function Daemon(conf) {
  this._components = [];
}

Daemon.prototype.initialize = function(conf) {
  if (conf.verbose) log.setVerbose(conf.verbose);
  log.debug('gearslothd', 'Config parsed:\n',
      util.inspect(conf, { depth: 3 }));

  if (conf.injector)    this.add('./injector',        conf);
  if (conf.runner)      this.add('./runner',          conf);
  if (conf.controller)  this.add(conf.controllerpath, conf);
  if (conf.ejector)     this.add('./ejector',         conf);
};

Daemon.prototype.add = function(path, conf) {
  var that = this;
  var component = require(path)(conf);
  var id = this._components.length;
  this._components.push({
    component: component,
    connected: false
  });
  if (!component.on)
    return;
  component.on('connect', function() {
    that.setConnected(id, true);
  });
  component.on('disconnect', function() {
    that.setConnected(id, false);
  });
};

Daemon.prototype.allConnected = function() {
  return this._components.reduce(function(acc, component) {
    return acc && component.connected;
  }, true);
};

Daemon.prototype.setConnected = function(id, connected) {
  var prev = this.allConnected();
  this._components[id].connected = connected;
  var next = this.allConnected();
  if (prev && !next)
    log.info('gearslothd', 'Disconnected');
  else if (!prev && next)
    log.info('gearslothd', 'Connected');
};

module.exports = new Daemon();
<|endoftext|>


<commit_before>// Copyright 2013 Joyent, Inc.  All rights reserved.

var uuid = require('node-uuid');

function changelog(req, res, next) {
    if (!req.headers['x-ufds-operation'] || !req.objects) {
        return next();
    }

    var bucket = req.config.changelog.bucket;

    if (!bucket) {
        req.log.warn({
            config: req.config.changelog
        }, 'bucket not provided, skipping');
        return next();
    }

    // Without objects to add/modify/remove we don't need to add nothing
    // to changelog
    if (!req.objects) {
        return next();
    }

    var key = 'change=' + uuid() + ', cn=changelog';
    var value = {
        targetdn: [req.key],
        changetype: [req.headers['x-ufds-operation']],
        objectclass: ['changeLogEntry']
    };

    switch (req.headers['x-ufds-operation']) {
        case 'add':
            value.changes = [JSON.stringify(req._entry)];
            break;
        case 'delete':
            value.changes = [req.headers['x-ufds-deleted-entry']];
            break;
        default:
            // Modify:
            value.changes = [req.headers['x-ufds-changes']];
            value.entry = [JSON.stringify(req.value)];
            break;
    }

    req.objects.push({
        bucket: bucket,
        key: key,
        operation: 'put',
        value: value
    });

    return next();
}

///--- Exports

module.exports = {
    changelog: changelog
};
<commit_msg>CAPI-198: Make sure we save entry into changelog for modify ops<commit_after>// Copyright 2013 Joyent, Inc.  All rights reserved.

var uuid = require('node-uuid');

function changelog(req, res, next) {
    if (!req.headers['x-ufds-operation'] || !req.objects) {
        return next();
    }

    var bucket = req.config.changelog.bucket;

    if (!bucket) {
        req.log.warn({
            config: req.config.changelog
        }, 'bucket not provided, skipping');
        return next();
    }

    // Without objects to add/modify/remove we don't need to add nothing
    // to changelog
    if (!req.objects) {
        return next();
    }

    var key = 'change=' + uuid() + ', cn=changelog';
    var value = {
        targetdn: [req.key],
        changetype: [req.headers['x-ufds-operation']],
        objectclass: ['changeLogEntry']
    };

    switch (req.headers['x-ufds-operation']) {
        case 'add':
            value.changes = [JSON.stringify(req._entry)];
            break;
        case 'delete':
            value.changes = [req.headers['x-ufds-deleted-entry']];
            break;
        default:
            // Modify:
            value.changes = [req.headers['x-ufds-changes']];
            value.entry = [JSON.stringify(req.entry)];
            break;
    }

    req.objects.push({
        bucket: bucket,
        key: key,
        operation: 'put',
        value: value
    });

    return next();
}

///--- Exports

module.exports = {
    changelog: changelog
};
<|endoftext|>


<commit_before>/* Copyright 2013 Gabriel Eugen Vaduva

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
var words = ["abbey", "abruptly", "affix", "apostrophe", "askew", "axiom", "azure", "bagpipes", "bandwagon", "banjo", "bayou", "bikini", "blitz", "bookworm", "boxcar", "boxful", "buckaroo", "buffalo", "buffoon", "chateau", "cobweb", "croquet", "daiquiri", "degenarative", "disavow", "duplex", "dwarf", "equip", "exodus", "fishhook", "fixable", "foxglove", "galaxy", "galvanize", "gazebo", "gizmo", "glowworm", "god", "guffaw", "hangman", "haiku", "haphazard", "hybrid", "hyperbole", "hyphen", "icebox", "injury", "ivory", "ivy", "jaundice", "jawbreaker", "jaywalk", "jazz", "jazzy", "jigsaw", "jiujitsu", "jockey", "jovial", "joyful", "juicy", "jumbo", "kazoo", "kelvin", "keyhole", "khaki", "kilobyte", "kiosk", "kiwifruit", "knapsack", "krypton", "larynx", "lepton", "luxury", "marquis", "megahertz", "metaphor",  "microwave", "muon", "mystify", "nemesis", "neutrino", "neutron", "nightclub", "nowadays", "numbskull", "octogenarian", "osteoporosis", "ovary", "oxidize", "oxygen", "pajama", "peekaboo", "penumbra", "pixel", "physical", "photon", "pneumonia", "polka", "proton", "pseudoscience", "quark", "quartz", "quiz", "quorum", "ray", "radon", "radiation", "rickshaw", "ripple", "schizophrenia", "sphinx", "spritz", "squawk", "subway", "swivel", "symmetry", "talisman", "topaz", "umbrella", "unknown", "unworthy", "unzip", "uptown", "vaporize", "vixen", "void", "vodka", "vortex", "walkway", "waltz", "wavy", "waxy", "weird", "wheezy", "whiskey", "whomever", "wimpy", "wizard", "woozy", "xenon", "xenophobia", "xylophone", "yachtsman", "yippee", "youthful", "zephyr", "zigzag", "zilch", "zodiac", "zombi"];

function drawWord(wo, gu)
{
    var nword = ""; var ok;
    for (var i = 0; i < wo.length; i++) {
        ok = false;
        for (var j = 0; j < gu.length; j++)
        {
            if (gu[j] == wo[i]) {
                nword = nword + wo[i].toUpperCase() + ' ';
                ok = true;
                break;
            }
        }
        if (!ok) nword = nword + '_ ';
    }
    $('#theword').html(nword);
}

function checkWin(p)
{
    for (var i = 0; i < p.length; i++)
        if (p[i] == '_') return false;
    return true;
}

$(document).ready(function(){
    var w = words[Math.floor(Math.random()*words.length)];
    var guess = "";
    var t = 0;
    var c = document.getElementById("display");
    var ctx = c.getContext("2d");
    ctx.font="30px Arial";
    ctx.strokeText("Hangman",235,50);
    drawWord(w, guess);
    $('#letters a').click(function(){
        var vl = $(this).attr('value');
        if (w.indexOf(vl) != -1)
        {
            guess = guess + vl;
            $(this).hide();
            drawWord(w, guess);
            if (checkWin($('#theword').html())) {
                $('#msg').html('Well done! Reload the page to play again.');
                $('#letters').hide();
            }
        } else {
            t++;
            $(this).hide();
            switch(t)
            {
                case 1: {
                    ctx.moveTo(200, 300);
                    ctx.lineTo(200, 100);
                    ctx.stroke();
                } break;
                case 2: {
                    ctx.moveTo(200, 275);
                    ctx.lineTo(225, 300);
                    ctx.stroke();
                } break;
                case 3: {
                    ctx.moveTo(200, 100);
                    ctx.lineTo(325, 100);
                    ctx.stroke();
                } break;
                case 4: {
                    ctx.moveTo(200, 125);
                    ctx.lineTo(225, 100);
                    ctx.stroke();
                } break;
                case 5: {
                    ctx.moveTo(325, 100);
                    ctx.lineTo(325, 130);
                    ctx.stroke();
                } break;
                case 6: {
                    ctx.beginPath();
                    ctx.arc(325,150,20,0,2*Math.PI);
                    ctx.closePath();
                    ctx.stroke();
                } break;
                case 7: {
                    ctx.moveTo(325, 170);
                    ctx.lineTo(325, 230);
                    ctx.stroke();
                } break;
                case 8: {
                    ctx.moveTo(325, 180);
                    ctx.lineTo(300, 215);
                    ctx.stroke();
                } break;
                case 9: {
                    ctx.moveTo(325, 180);
                    ctx.lineTo(350, 215);
                    ctx.stroke();
                } break;
                case 10: {
                    ctx.moveTo(325, 230);
                    ctx.lineTo(300, 265);
                    ctx.stroke();
                } break;
                case 11: {
                    ctx.moveTo(325, 230);
                    ctx.lineTo(350, 265);
                    ctx.stroke();
                } break;
            }

            if (t == 11) {
                $('#msg').html('You are dead! Reload the page to play again.');
                $('#letters').hide();
                $('#theword').html(w.toUpperCase());
            }
        }
    });
});<commit_msg>Nothing special<commit_after>/* Copyright 2013 Gabriel Eugen Vaduva

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
var words = ["abbey", "abruptly", "affix", "apostrophe", "askew", "axiom", "azure", "bagpipes", "bandwagon", "banjo", "bayou", "bikini", "blitz", "bookworm", "boxcar", "boxful", "buckaroo", "buffalo", "buffoon", "chateau", "cobweb", "croquet", "daiquiri", "degenarative", "disavow", "duplex", "dwarf", "equip", "exodus", "fishhook", "fixable", "foxglove", "galaxy", "galvanize", "gazebo", "gizmo", "glowworm", "god", "guffaw", "hangman", "haiku", "haphazard", "hybrid", "hyperbole", "hyphen", "icebox", "injury", "ivory", "ivy", "jaundice", "jawbreaker", "jaywalk", "jazz", "jazzy", "jigsaw", "jiujitsu", "jockey", "jovial", "joyful", "juicy", "jumbo", "kazoo", "kelvin", "keyhole", "khaki", "kilobyte", "kiosk", "kiwifruit", "knapsack", "krypton", "larynx", "lepton", "luxury", "marquis", "megahertz", "metaphor",  "microwave", "muon", "mystify", "nemesis", "neutrino", "neutron", "nightclub", "nowadays", "numbskull", "octogenarian", "osteoporosis", "ovary", "oxidize", "oxygen", "pajama", "peekaboo", "penumbra", "pixel", "physical", "photon", "pneumonia", "polka", "proton", "pseudoscience", "quark", "quartz", "quiz", "quorum", "ray", "radon", "radiation", "rickshaw", "ripple", "schizophrenia", "sphinx", "spritz", "squawk", "subway", "swivel", "symmetry", "talisman", "topaz", "umbrella", "unknown", "unworthy", "unzip", "uptown", "vaporize", "vixen", "void", "vodka", "vortex", "walkway", "waltz", "wavy", "waxy", "weird", "wheezy", "whiskey", "whomever", "wimpy", "wizard", "woozy", "xenon", "xenophobia", "xylophone", "yachtsman", "yippee", "youthful", "zephyr", "zigzag", "zilch", "zodiac", "zombi"];

function drawWord(wo, gu)
{
    var nword = ""; var ok;
    for (var i = 0; i < wo.length; i++) {
        ok = false;
        for (var j = 0; j < gu.length; j++)
        {
            if (gu[j] == wo[i]) {
                nword = nword + wo[i].toUpperCase() + ' ';
                ok = true;
                break;
            }
        }
        if (!ok) nword = nword + '_ ';
    }
    $('#theword').html(nword);
}

function checkWin(p)
{
    for (var i = 0; i < p.length; i++)
        if (p[i] == '_') return false;
    return true;
}

$(document).ready(function(){
    var w = words[Math.floor(Math.random() * words.length)];
    var guess = "";
    var t = 0;
    var c = document.getElementById("display");
    var ctx = c.getContext("2d");
    ctx.font="30px Arial";
    ctx.strokeText("Hangman",235,50);
    drawWord(w, guess);
    $('#letters a').click(function(){
        var vl = $(this).attr('value');
        if (w.indexOf(vl) != -1)
        {
            guess = guess + vl;
            $(this).hide();
            drawWord(w, guess);
            if (checkWin($('#theword').html())) {
                $('#msg').html('Well done! Reload the page to play again.');
                $('#letters').hide();
            }
        } else {
            t++;
            $(this).hide();
            switch(t)
            {
                case 1: {
                    ctx.moveTo(200, 300);
                    ctx.lineTo(200, 100);
                    ctx.stroke();
                } break;
                case 2: {
                    ctx.moveTo(200, 275);
                    ctx.lineTo(225, 300);
                    ctx.stroke();
                } break;
                case 3: {
                    ctx.moveTo(200, 100);
                    ctx.lineTo(325, 100);
                    ctx.stroke();
                } break;
                case 4: {
                    ctx.moveTo(200, 125);
                    ctx.lineTo(225, 100);
                    ctx.stroke();
                } break;
                case 5: {
                    ctx.moveTo(325, 100);
                    ctx.lineTo(325, 130);
                    ctx.stroke();
                } break;
                case 6: {
                    ctx.beginPath();
                    ctx.arc(325,150,20,0,2*Math.PI);
                    ctx.closePath();
                    ctx.stroke();
                } break;
                case 7: {
                    ctx.moveTo(325, 170);
                    ctx.lineTo(325, 230);
                    ctx.stroke();
                } break;
                case 8: {
                    ctx.moveTo(325, 180);
                    ctx.lineTo(300, 215);
                    ctx.stroke();
                } break;
                case 9: {
                    ctx.moveTo(325, 180);
                    ctx.lineTo(350, 215);
                    ctx.stroke();
                } break;
                case 10: {
                    ctx.moveTo(325, 230);
                    ctx.lineTo(300, 265);
                    ctx.stroke();
                } break;
                case 11: {
                    ctx.moveTo(325, 230);
                    ctx.lineTo(350, 265);
                    ctx.stroke();
                } break;
            }

            if (t == 11) {
                $('#msg').html('You are dead! Reload the page to play again.');
                $('#letters').hide();
                $('#theword').html(w.toUpperCase());
            }
        }
    });
});<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

//noinspection JSUnusedGlobalSymbols
function onGet(env) {
    return {petData: {name: null, image: null}};
}
<commit_msg>remove comment in thumbnail.js of thumbnail fragment, pets store sample<commit_after>/*
 *  Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

function onGet(env) {
    return {petData: {name: null, image: null}};
}
<|endoftext|>


<commit_before>import React from 'react';

import TrafficLights from '../traffic-lights';
import VideoPlayer from './video-player';

export default class Editor extends React.Component {
  state = {
    hover: false
  }

  mouseEnter = () => {
    this.setState({hover: true});
  }

  mouseLeave = () => {
    this.setState({hover: false});
  }

  render() {
    const {hover} = this.state;

    return (

            <TrafficLights/>

Editor

        <VideoPlayer hover={hover}/>

    );
  }
}
<commit_msg>Add blur to the editor header (#723)<commit_after>import React from 'react';

import TrafficLights from '../traffic-lights';
import VideoPlayer from './video-player';

export default class Editor extends React.Component {
  state = {
    hover: false
  }

  mouseEnter = () => {
    this.setState({hover: true});
  }

  mouseLeave = () => {
    this.setState({hover: false});
  }

  render() {
    const {hover} = this.state;

    return (

            <TrafficLights/>

Editor

        <VideoPlayer hover={hover}/>

    );
  }
}
<|endoftext|>


<commit_before>/**
 * Get information on matches,
 * generate annotation tables and trees.
 *
 * @author Nils Diewald
 */
/*
 * - Highlight (at least mark as bold) the match
 * - Scroll to match vertically per default
 * - A click on a table field and a tree node should at the field description to the fragments list.
 */
define([
  'match/info',      // rename to anno
  'match/treemenu',
	'util'
], function (infoClass,matchTreeMenuClass) { //, refClass) {

  // Localization values
  const loc   = KorAP.Locale;
  loc.SHOWINFO  = loc.SHOWINFO  || 'Show information';
  loc.ADDTREE   = loc.ADDTREE   || 'Relations';
  loc.SHOWANNO  = loc.SHOWANNO  || 'Tokens';
  loc.CLOSE     = loc.CLOSE     || 'Close';
  loc.SHOW_META = loc.SHOW_META || 'Metadata';

  // 'corpusID', 'docID', 'textID'
  const _matchTerms  = ['textSigle', 'matchID', 'available'];

  const d = document;

  /**
   * Match object
   */
  return {

    /**
     * Create a new annotation object.
     * Expects an array of available foundry/layer=type terms.
     * Supported types are 'spans', 'tokens' and 'rels'.
     */
    create : function (match) {
      return Object.create(this)._init(match);
    },

    /**
     * Initialize match.
     */
    _init : function (match) {
      this._element = null;

      // No match defined
      if (arguments.length < 1 ||
          match === null ||
          match === undefined) {
        throw new Error('Missing parameters');
      }

      // Match defined as a node
      else if (match instanceof Node) {
        this._element  = match;

        // Circular reference !!
        match["_match"] = this;

        /*
          this.corpusID  = match.getAttribute('data-corpus-id'),
          this.docID     = match.getAttribute('data-doc-id'),
          this.textID    = match.getAttribute('data-text-id'),
        */
        if (match.hasAttribute('data-text-sigle')) {
          this.textSigle = match.getAttribute('data-text-sigle')
        }
        else {
          this.textSigle = match.getAttribute('data-corpus-id') +
            '/' +
            match.getAttribute('data-doc-id') +
            '/' +
            match.getAttribute('data-text-id');
        };

        this.matchID   = match.getAttribute('data-match-id');

        // List of available annotations
        this.available = match.getAttribute('data-available-info').split(' ');
      }

      // Match as an object
      else {

        // Iterate over allowed match terms
        for (var i in _matchTerms) {
          var term = _matchTerms[i];
          this[term] = match[term] !== undefined ? match[term] : undefined;
        };
      };

      this._avail = {
        tokens : [],
        spans  : [],
        rels   : []
      };

      // Iterate over info layers
      for (var i = 0; i < this.available.length; i++) {
        var term = this.available[i];

        // Create info layer objects
        try {
          var layer = require('match/infolayer').create(term);
          this._avail[layer.type].push(layer);
        }
        catch (e) {
          continue;
        };
      };

      return this;
    },

    /**
     * Return a list of parseable tree annotations.
     */
    getSpans : function () {
      return this._avail.spans;
    },

    /**
     * Return a list of parseable token annotations.
     */
    getTokens : function () {
      return this._avail.tokens;
    },

    /**
     * Return a list of parseable relation annotations.
     */
    getRels : function () {
      return this._avail.rels;
    },

    /**
     * Open match
     */
    open : function () {

      // Add actions unless it's already activated
      var element = this._element;

      // There is an element to open
      if (this._element === undefined || this._element === null)
        return false;

      // The element is already opened
      if (element.classList.contains('active'))
        return false;

      // Add active class to element
      element.classList.add('active');

      // Already there
      if (element.classList.contains('action'))
        return true;

      // Create action buttons
      var ul = d.createElement('ul');
      ul.classList.add('action', 'right');

      element.appendChild(ul);
      element.classList.add('action');

      // Todo: Open in new frame

      // Add close button
      var close = d.createElement('li');
      close.addE('span').addT(loc.CLOSE);
      close.classList.add('close');
      close.setAttribute('title', loc.CLOSE);

      var that = this;

      // Add meta button
      var refLine = element.querySelector("p.ref");

      // No reference found
      if (!refLine)
        return;

      var ops = d.createElement('div');
      ops.classList.add('action', 'bottom', 'button-group');

      /*
      var meta = ops.addE('span');
      meta.addT('Meta');
      meta.setAttribute('title', loc.SHOW_META);
      meta.classList.add('meta');
      */

      // TODO: Rename anno
      var info = ops.addE('span');
      info.addT(loc.SHOWANNO);
      info.setAttribute('title', loc.SHOWANNO);
      info.classList.add('info');

      var tree = ops.addE('span');
      tree.addT(loc.ADDTREE);
      tree.setAttribute('title', loc.ADDTREE);
      tree.classList.add('tree');

      // Insert before reference line
      refLine.insertBefore(
        ops,
        refLine.firstChild
      );

      // Click on meta - add meta (unless already there)
      /*
      meta.addEventListener(
        'click', function (e) {
          e.halt();
          that.info().showMeta();
        }
      );
      */

      // Click on token annotations - add token annotations (unless already there)
      info.addEventListener(
        'click', function (e) {
          e.halt();
          that.info().showTable();
        }
      );

      // Click to show tree menu
      tree.addEventListener(
        'click', function (e) {
          e.halt();

          if (KorAP.TreeMenu === undefined) {
            KorAP.TreeMenu = matchTreeMenuClass.create([]);
          };

          var tm = KorAP.TreeMenu;

          // Reread list
          tm.info(that.info());
          tm.readItems(that.treeMenuList());

          // Reposition and show menu
          tm.show();
          tm.attachTo(this);
          tm.focus();
        }
      );

      // Close match
      close.addEventListener('click', function (e) {
        e.halt();
        that.close()
      });

      ul.appendChild(close);

      return true;
    },

    // Todo: Test toggle
    toggle : function () {
      if (this._element.classList.contains('active'))
        this.close();
      else
        this.open();
    },

    /**
     * Close info view
     */
    close : function () {
      this._element.classList.remove('active');
      /*
      if (this._info !== undefined) {
        this._info.destroy();
      };
      */
    },

    /**
     * Get and open associated match infos.
     */
    info : function () {

      // Create match info
      if (this._info === undefined)
        this._info = infoClass.create(this);

      // There is an element to append
      if (this._element === undefined ||
          this._element === null)
        return this._info;

      // Info is already activated
      if (this._info._element !== undefined)
        return this._info;

      var refLine = this._element.querySelector("p.ref");
      this._element.insertBefore(
        this._info.element(),
        refLine
      );

      return this._info;
    },

    // Return tree menu list
    treeMenuList : function () {

      if (this._menuList)
        return this._menuList;

      // Join spans and relations
      var treeLayers = []
      var spans = this.getSpans();
      var rels = this.getRels();
      var i;
      for (i in spans) {
        treeLayers.push(spans[i]);
      };
      for (i in rels) {
        treeLayers.push(rels[i]);
      };

      // Get spans
      treeLayers = treeLayers.sort(
        function (a, b) {
          if (a.foundry < b.foundry) {
            return -1;
          }
          else if (a.foundry > b.foundry) {
            return 1;
          }
          else if (a.layer < b.layer) {
            return -1;
          }
          else if (a.layer > b.layer) {
            return 1;
          };
          return 0;
        });

      var menuList = [];

      // Show tree views
      for (var i = 0; i < treeLayers.length; i++) {
        var span = treeLayers[i];

        // Add foundry/layer to menu list
        menuList.push([
          span.foundry + '/' + span.layer,
          span.foundry,
          span.layer,
          span.type
        ]);
      };

      // Create tree menu
      this._menuList = menuList;
      return menuList;
    },

    /**
     * Get match element.
     */
    element : function () {
      return this._element; // May be null
    }
  };
});
<commit_msg>Reenabled meta button<commit_after>/**
 * Get information on matches,
 * generate annotation tables and trees.
 *
 * @author Nils Diewald
 */
/*
 * - Highlight (at least mark as bold) the match
 * - Scroll to match vertically per default
 * - A click on a table field and a tree node should at the field description to the fragments list.
 */
define([
  'match/info',      // rename to anno
  'match/treemenu',
	'util'
], function (infoClass,matchTreeMenuClass) { //, refClass) {

  // Localization values
  const loc   = KorAP.Locale;
  loc.SHOWINFO  = loc.SHOWINFO  || 'Show information';
  loc.ADDTREE   = loc.ADDTREE   || 'Relations';
  loc.SHOWANNO  = loc.SHOWANNO  || 'Tokens';
  loc.CLOSE     = loc.CLOSE     || 'Close';
  loc.SHOW_META = loc.SHOW_META || 'Metadata';

  // 'corpusID', 'docID', 'textID'
  const _matchTerms  = ['textSigle', 'matchID', 'available'];

  const d = document;

  /**
   * Match object
   */
  return {

    /**
     * Create a new annotation object.
     * Expects an array of available foundry/layer=type terms.
     * Supported types are 'spans', 'tokens' and 'rels'.
     */
    create : function (match) {
      return Object.create(this)._init(match);
    },

    /**
     * Initialize match.
     */
    _init : function (match) {
      this._element = null;

      // No match defined
      if (arguments.length < 1 ||
          match === null ||
          match === undefined) {
        throw new Error('Missing parameters');
      }

      // Match defined as a node
      else if (match instanceof Node) {
        this._element  = match;

        // Circular reference !!
        match["_match"] = this;

        /*
          this.corpusID  = match.getAttribute('data-corpus-id'),
          this.docID     = match.getAttribute('data-doc-id'),
          this.textID    = match.getAttribute('data-text-id'),
        */
        if (match.hasAttribute('data-text-sigle')) {
          this.textSigle = match.getAttribute('data-text-sigle')
        }
        else {
          this.textSigle = match.getAttribute('data-corpus-id') +
            '/' +
            match.getAttribute('data-doc-id') +
            '/' +
            match.getAttribute('data-text-id');
        };

        this.matchID   = match.getAttribute('data-match-id');

        // List of available annotations
        this.available = match.getAttribute('data-available-info').split(' ');
      }

      // Match as an object
      else {

        // Iterate over allowed match terms
        for (var i in _matchTerms) {
          var term = _matchTerms[i];
          this[term] = match[term] !== undefined ? match[term] : undefined;
        };
      };

      this._avail = {
        tokens : [],
        spans  : [],
        rels   : []
      };

      // Iterate over info layers
      for (var i = 0; i < this.available.length; i++) {
        var term = this.available[i];

        // Create info layer objects
        try {
          var layer = require('match/infolayer').create(term);
          this._avail[layer.type].push(layer);
        }
        catch (e) {
          continue;
        };
      };

      return this;
    },

    /**
     * Return a list of parseable tree annotations.
     */
    getSpans : function () {
      return this._avail.spans;
    },

    /**
     * Return a list of parseable token annotations.
     */
    getTokens : function () {
      return this._avail.tokens;
    },

    /**
     * Return a list of parseable relation annotations.
     */
    getRels : function () {
      return this._avail.rels;
    },

    /**
     * Open match
     */
    open : function () {

      // Add actions unless it's already activated
      var element = this._element;

      // There is an element to open
      if (this._element === undefined || this._element === null)
        return false;

      // The element is already opened
      if (element.classList.contains('active'))
        return false;

      // Add active class to element
      element.classList.add('active');

      // Already there
      if (element.classList.contains('action'))
        return true;

      // Create action buttons
      var ul = d.createElement('ul');
      ul.classList.add('action', 'right');

      element.appendChild(ul);
      element.classList.add('action');

      // Todo: Open in new frame

      // Add close button
      var close = d.createElement('li');
      close.addE('span').addT(loc.CLOSE);
      close.classList.add('close');
      close.setAttribute('title', loc.CLOSE);

      var that = this;

      // Add meta button
      var refLine = element.querySelector("p.ref");

      // No reference found
      if (!refLine)
        return;

      var ops = d.createElement('div');
      ops.classList.add('action', 'bottom', 'button-group');

      var meta = ops.addE('span');
      meta.addT('Meta');
      meta.setAttribute('title', loc.SHOW_META);
      meta.classList.add('meta');

      // TODO: Rename anno
      var info = ops.addE('span');
      info.addT(loc.SHOWANNO);
      info.setAttribute('title', loc.SHOWANNO);
      info.classList.add('info');

      var tree = ops.addE('span');
      tree.addT(loc.ADDTREE);
      tree.setAttribute('title', loc.ADDTREE);
      tree.classList.add('tree');

      // Insert before reference line
      refLine.insertBefore(
        ops,
        refLine.firstChild
      );

      // Click on meta - add meta (unless already there)
      meta.addEventListener(
        'click', function (e) {
          e.halt();
          that.info().showMeta();
        }
      );

      // Click on token annotations - add token annotations (unless already there)
      info.addEventListener(
        'click', function (e) {
          e.halt();
          that.info().showTable();
        }
      );

      // Click to show tree menu
      tree.addEventListener(
        'click', function (e) {
          e.halt();

          if (KorAP.TreeMenu === undefined) {
            KorAP.TreeMenu = matchTreeMenuClass.create([]);
          };

          var tm = KorAP.TreeMenu;

          // Reread list
          tm.info(that.info());
          tm.readItems(that.treeMenuList());

          // Reposition and show menu
          tm.show();
          tm.attachTo(this);
          tm.focus();
        }
      );

      // Close match
      close.addEventListener('click', function (e) {
        e.halt();
        that.close()
      });

      ul.appendChild(close);

      return true;
    },

    // Todo: Test toggle
    toggle : function () {
      if (this._element.classList.contains('active'))
        this.close();
      else
        this.open();
    },

    /**
     * Close info view
     */
    close : function () {
      this._element.classList.remove('active');
      /*
      if (this._info !== undefined) {
        this._info.destroy();
      };
      */
    },

    /**
     * Get and open associated match infos.
     */
    info : function () {

      // Create match info
      if (this._info === undefined)
        this._info = infoClass.create(this);

      // There is an element to append
      if (this._element === undefined ||
          this._element === null)
        return this._info;

      // Info is already activated
      if (this._info._element !== undefined)
        return this._info;

      var refLine = this._element.querySelector("p.ref");
      this._element.insertBefore(
        this._info.element(),
        refLine
      );

      return this._info;
    },

    // Return tree menu list
    treeMenuList : function () {

      if (this._menuList)
        return this._menuList;

      // Join spans and relations
      var treeLayers = []
      var spans = this.getSpans();
      var rels = this.getRels();
      var i;
      for (i in spans) {
        treeLayers.push(spans[i]);
      };
      for (i in rels) {
        treeLayers.push(rels[i]);
      };

      // Get spans
      treeLayers = treeLayers.sort(
        function (a, b) {
          if (a.foundry < b.foundry) {
            return -1;
          }
          else if (a.foundry > b.foundry) {
            return 1;
          }
          else if (a.layer < b.layer) {
            return -1;
          }
          else if (a.layer > b.layer) {
            return 1;
          };
          return 0;
        });

      var menuList = [];

      // Show tree views
      for (var i = 0; i < treeLayers.length; i++) {
        var span = treeLayers[i];

        // Add foundry/layer to menu list
        menuList.push([
          span.foundry + '/' + span.layer,
          span.foundry,
          span.layer,
          span.type
        ]);
      };

      // Create tree menu
      this._menuList = menuList;
      return menuList;
    },

    /**
     * Get match element.
     */
    element : function () {
      return this._element; // May be null
    }
  };
});
<|endoftext|>


<commit_before>/*
 * == BSD2 LICENSE ==
 * Copyright (c) 2014, Tidepool Project
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the associated License, which is identical to the BSD 2-Clause
 * License as published by the Open Source Initiative at opensource.org.
 *
 * 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 License for more details.
 *
 * You should have received a copy of the License along with this program; if
 * not, you can obtain one from Tidepool Project at tidepool.org.
 * == BSD2 LICENSE ==
 */
'use strict';

var dxcomParser;

var _ = require('lodash');
var es = require('event-stream');
var moment = require('moment');

var misc = require('../misc.js');

var columns = {
  NA_1: 0,
  NA_2: 1,
  GlucoseInternalTime_1: 2,
  GlucoseDisplayTime_1: 3,
  GlucoseValue_1: 4,
  MeterInternalTime_2: 5,
  MeterDisplayTime_2: 6,
  MeterGlucoseValue_2: 7
};

var DEXCOM_TIME = 'YYYY-MM-DD HH:mm:ss';
var OUTPUT_TIME = 'YYYY-MM-DDTHH:mm:ss';

function reformatISO (str) {
  var m = moment.utc(str, DEXCOM_TIME);
  return m.format(OUTPUT_TIME);
}

function validTime (str) {
  return moment(str, OUTPUT_TIME).isValid( );
}

dxcomParser = function(config) {
  var responder, stream;

  stream = es.pipeline(es.split(), es.map(function(data, cb) {

    if(data){
      var sugarsInRow = splitBGRecords(data);

      sugarsInRow.forEach(function(sugar){
        var rec = {
          type: 'cbg',
          data: sugar
        };
        stream.emit('type', rec);
      });
    }
    return cb();
  }));

  responder = function(filter) {
    var tr;
    tr = es.through();
    stream.on('type', function(data) {
      if (data.type.match(filter)) {
        return tr.push(data.data);
      }
    });
    return es.pipeline(stream, tr);
  };

  var toUtcFn = misc.deviceTimeToUtc(config.timezone);

  return es.pipeline(
    responder('cbg'),
    es.map(parse),
    es.map(valid),
    es.map(function(e, cb){ cb(null, toUtcFn(_.assign({}, e, {deviceId: 'dexcom', source: 'csvUpload'}))); })
  );
};

dxcomParser.desalinate = function( ) {
  return dxcomParser().desalinate( );
};

dxcomParser.sugars = function( ) {
  return dxcomParser().sugars( );
};

dxcomParser.cbg = function( ) {
  return dxcomParser().cbg( );
};

dxcomParser.columns = function() {
  return columns;
};

dxcomParser.splitBGRecords =function(rawData){
  return splitBGRecords(rawData);
};

dxcomParser.isValidCbg = function(cbg){
  return isValidCbg(cbg);
};

function parse (rawData, callback) {
  var processedSugar;

  var stringReadingToNum = function(value) {
    if (value.match(/lo./i)) {
      return '39';
    }
    else if (value.match(/hi./i)) {
      return '401';
    }
  };

  if ((rawData.value.match(/lo./i)) || rawData.value.match(/hi./i)) {
    processedSugar = {
      value: stringReadingToNum(rawData.value),
      type: 'cbg',
      deviceTime: reformatISO(rawData.displayTime),
      special: rawData.value
    };
  } else {
    processedSugar = {
      value: rawData.value,
      type: 'cbg',
      deviceTime: reformatISO(rawData.displayTime)
    };
  }

  return callback(null, processedSugar);
}

function valid (data, next) {
  if (isValidCbg(data)) {
    return next(null, data);
  }
  next( );
}

function isValidCbg (cbg) {
  if (isNaN(parseInt(cbg.value))) {
    if (cbg.value.match(/lo./i) || cbg.value.match(/hi./i)) {
      return (cbg.type === 'cbg' && validTime(cbg.deviceTime));
    }
    else {
      return false;
    }
  }
  else {
    return (!isNaN(parseInt(cbg.value)) &&
            cbg.type === 'cbg' && validTime(cbg.deviceTime));
  }
}

var splitBGRecords = function(rawData){
  var records, entryValues, sugarOne;

  entryValues = rawData.split('\t');
  sugarOne = {};

  /* jshint -W069 */
  sugarOne.value = entryValues[columns['GlucoseValue_1']];
  sugarOne.displayTime = entryValues[columns['GlucoseDisplayTime_1']];
  /* jshint +W069 */

  records = [sugarOne];
  return records;
};

module.exports = dxcomParser;

<commit_msg>Submit units along with dexcom data<commit_after>/*
 * == BSD2 LICENSE ==
 * Copyright (c) 2014, Tidepool Project
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the associated License, which is identical to the BSD 2-Clause
 * License as published by the Open Source Initiative at opensource.org.
 *
 * 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 License for more details.
 *
 * You should have received a copy of the License along with this program; if
 * not, you can obtain one from Tidepool Project at tidepool.org.
 * == BSD2 LICENSE ==
 */
'use strict';

var dxcomParser;

var _ = require('lodash');
var es = require('event-stream');
var moment = require('moment');

var misc = require('../misc.js');

var columns = {
  NA_1: 0,
  NA_2: 1,
  GlucoseInternalTime_1: 2,
  GlucoseDisplayTime_1: 3,
  GlucoseValue_1: 4,
  MeterInternalTime_2: 5,
  MeterDisplayTime_2: 6,
  MeterGlucoseValue_2: 7
};

var DEXCOM_TIME = 'YYYY-MM-DD HH:mm:ss';
var OUTPUT_TIME = 'YYYY-MM-DDTHH:mm:ss';

function reformatISO (str) {
  var m = moment.utc(str, DEXCOM_TIME);
  return m.format(OUTPUT_TIME);
}

function validTime (str) {
  return moment(str, OUTPUT_TIME).isValid( );
}

dxcomParser = function(config) {
  var responder, stream;

  stream = es.pipeline(es.split(), es.map(function(data, cb) {

    if(data){
      var sugarsInRow = splitBGRecords(data);

      sugarsInRow.forEach(function(sugar){
        var rec = {
          type: 'cbg',
          data: sugar
        };
        stream.emit('type', rec);
      });
    }
    return cb();
  }));

  responder = function(filter) {
    var tr;
    tr = es.through();
    stream.on('type', function(data) {
      if (data.type.match(filter)) {
        return tr.push(data.data);
      }
    });
    return es.pipeline(stream, tr);
  };

  var toUtcFn = misc.deviceTimeToUtc(config.timezone);

  return es.pipeline(
    responder('cbg'),
    es.map(parse),
    es.map(valid),
    es.map(function(e, cb){ cb(null, toUtcFn(_.assign({}, e, {deviceId: 'dexcom', source: 'csvUpload'}))); })
  );
};

dxcomParser.desalinate = function( ) {
  return dxcomParser().desalinate( );
};

dxcomParser.sugars = function( ) {
  return dxcomParser().sugars( );
};

dxcomParser.cbg = function( ) {
  return dxcomParser().cbg( );
};

dxcomParser.columns = function() {
  return columns;
};

dxcomParser.splitBGRecords =function(rawData){
  return splitBGRecords(rawData);
};

dxcomParser.isValidCbg = function(cbg){
  return isValidCbg(cbg);
};

function parse (rawData, callback) {
  var processedSugar;

  var stringReadingToNum = function(value) {
    if (value.match(/lo./i)) {
      return '39';
    }
    else if (value.match(/hi./i)) {
      return '401';
    }
  };

  if ((rawData.value.match(/lo./i)) || rawData.value.match(/hi./i)) {
    processedSugar = {
      value: stringReadingToNum(rawData.value),
      type: 'cbg',
      deviceTime: reformatISO(rawData.displayTime),
      units: 'mg/dL'
    };
  } else {
    processedSugar = {
      value: rawData.value,
      type: 'cbg',
      deviceTime: reformatISO(rawData.displayTime),
      units: 'mg/dL'
    };
  }

  return callback(null, processedSugar);
}

function valid (data, next) {
  if (isValidCbg(data)) {
    return next(null, data);
  }
  next( );
}

function isValidCbg (cbg) {
  if (isNaN(parseInt(cbg.value))) {
    if (cbg.value.match(/lo./i) || cbg.value.match(/hi./i)) {
      return (cbg.type === 'cbg' && validTime(cbg.deviceTime));
    }
    else {
      return false;
    }
  }
  else {
    return (!isNaN(parseInt(cbg.value)) &&
            cbg.type === 'cbg' && validTime(cbg.deviceTime));
  }
}

var splitBGRecords = function(rawData){
  var records, entryValues, sugarOne;

  entryValues = rawData.split('\t');
  sugarOne = {};

  /* jshint -W069 */
  sugarOne.value = entryValues[columns['GlucoseValue_1']];
  sugarOne.displayTime = entryValues[columns['GlucoseDisplayTime_1']];
  /* jshint +W069 */

  records = [sugarOne];
  return records;
};

module.exports = dxcomParser;

<|endoftext|>


<commit_before>var c;
var ctx;
var enemynum;
var enemycounter;
var score;

var FPS;
var player;
var enemies = [];

function Initialise()
{
  // Reset variables.
  score = 0;
  enemies = [];
  enemynum =0;
  enemycounter=0;

  if(c == null)
  {
    c=document.getElementById("canvas");
    ctx=c.getContext("2d");
    enemynum = 0;
    enemycounter=100;
    FPS = 60;
    canvas.addEventListener('mousemove', MouseMove, false);
    setInterval(function() {
    update();
    draw();
    }, 1000/FPS);
  }
    player = {
    color: "#00A",
    x: 220,
    y: 270,
    width: 32,
    height: 32,
    draw: function() {
    ctx.fillStyle = this.color;
    ctx.fillRect(this.x, this.y, this.width, this.height);
  }
};
}

function draw(){
ctx.clearRect(0, 0, 400, 400);
player.draw();
for(var i = 0; i<enemynum; i++)
  {
    enemies[i].y+=2;
    enemies[i].draw();
    collisions(i);  // Check collisions with current enemy.
  }
}

function collisions(i){

  var e = enemies[i];
  var p = player

  // Top Left

  if(p.x<e.hole && (p.y<(e.y+e.height)&&p.y>e.y))
  {
     //document.getElementById("testout").innerHTML=String("TL Collide");
     Finalise();
  }

  // Top Right

  if((p.x+p.width)>(e.hole+p.width+e.extragap) && ((p.y)<(e.y+e.height)&&p.y>e.y))
  {
     //document.getElementById("testout").innerHTML=String("TR Collide");
     Finalise();
  }

  // Bottom Left

  if(p.x<e.hole && ((p.y+p.height)<(e.y+e.height)&&(p.y+p.height)>e.y))
  {
     //document.getElementById("testout").innerHTML=String("BL Collide");
     Finalise();
  }

  // Bottom Right

  if((p.x+p.width)>(e.hole+p.width+e.extragap) && ((p.y+p.height)<(e.y+e.height)&&(p.y+p.height)>e.y))
  {
     //document.getElementById("testout").innerHTML=String("BR Collide");
     Finalise();
  }
}

function update(){

  score++;
  // Add only 4 enemies to the screen
  if(enemynum<4)
  {
    enemycounter++;
    if(enemycounter > 50)
    // Spacing of enemies
    {
      enemycounter = 0;
      enemynum++;
    }
  }

  for(var i = 0; i<enemynum; i++)
  {
    enemies.push({
    color: "#0F0",
    x: 0,
    y: -20,
    width: 400,
    height: 20,
    extragap: 20,
    hole: Math.floor(Math.random()*380),
    draw: function() {
      if(this.y>400)
      {
        this.hole = Math.floor(Math.random()*this.width-50);
        this.y=-this.height;
      }
      ctx.fillStyle = this.color;
      ctx.fillRect(this.x, this.y, this.hole, this.height);
      ctx.fillRect(this.hole+player.width+this.extragap, this.y, this.width, this.height);
      }
    });
  }
}

function MouseMove(e){

player.x = e.clientX-canvas.offsetLeft-player.height/2;
document.getElementById("testout").innerHTML=String(score);
player.y = e.clientY-canvas.offsetTop-player.height/2+$(document).scrollTop();

}

function Finalise(){

  alert("You lost, but scored " + score);
  Initialise();
}
<commit_msg>Update games.js<commit_after>var c;
var ctx;
var enemynum;
var enemycounter;
var score;

var FPS;
var player;
var enemies = [];

function Initialise()
{
  // Reset variables.
  score = 0;
  enemies = [];
  enemynum =0;
  enemycounter=0;

  if(c == null)
  {
    c=document.getElementById("canvas");
    ctx=c.getContext("2d");
    enemynum = 0;
    enemycounter=100;
    FPS = 60;
    canvas.addEventListener('mousemove', MouseMove, false);
    setInterval(function() {
    update();
    draw();
    }, 1000/FPS);
  }
    player = {
    color: "#00A",
    x: 220,
    y: 270,
    width: 32,
    height: 32,
    draw: function() {
    ctx.fillStyle = this.color;
    ctx.fillRect(this.x, this.y, this.width, this.height);
  }
};
}

function draw(){
ctx.clearRect(0, 0, 400, 400);
player.draw();
for(var i = 0; i<enemynum; i++)
  {
    enemies[i].y+=2;
    enemies[i].draw();
    collisions(i);  // Check collisions with current enemy.
  }
}

function collisions(i){

  var e = enemies[i];
  var p = player

  // Top Left

  if(p.x<e.hole && (p.y<(e.y+e.height)&&p.y>e.y))
  {
     //document.getElementById("testout").innerHTML=String("TL Collide");
     Finalise();
  }

  // Top Right

  if((p.x+p.width)>(e.hole+p.width+e.extragap) && ((p.y)<(e.y+e.height)&&p.y>e.y))
  {
     //document.getElementById("testout").innerHTML=String("TR Collide");
     Finalise();
  }

  // Bottom Left

  if(p.x<e.hole && ((p.y+p.height)<(e.y+e.height)&&(p.y+p.height)>e.y))
  {
     //document.getElementById("testout").innerHTML=String("BL Collide");
     Finalise();
  }

  // Bottom Right

  if((p.x+p.width)>(e.hole+p.width+e.extragap) && ((p.y+p.height)<(e.y+e.height)&&(p.y+p.height)>e.y))
  {
     //document.getElementById("testout").innerHTML=String("BR Collide");
     Finalise();
  }
}

function update(){

  score++;
  // Add only 4 enemies to the screen
  if(enemynum<4)
  {
    enemycounter++;
    if(enemycounter > 50)
    // Spacing of enemies
    {
      enemycounter = 0;
      enemynum++;
    }
  }

  for(var i = 0; i<enemynum; i++)
  {
    enemies.push({
    color: "#0F0",
    x: 0,
    y: -20,
    width: 400,
    height: 20,
    extragap: 20,
    hole: Math.floor(Math.random()*340+20),
    draw: function() {
      if(this.y>400)
      {
        this.hole = Math.floor(Math.random()*this.width-60+20);
        this.y=-this.height;
      }
      ctx.fillStyle = this.color;
      ctx.fillRect(this.x, this.y, this.hole, this.height);
      ctx.fillRect(this.hole+player.width+this.extragap, this.y, this.width, this.height);
      }
    });
  }
}

function MouseMove(e){

player.x = e.clientX-canvas.offsetLeft-player.height/2;
document.getElementById("testout").innerHTML=String(score);
player.y = e.clientY-canvas.offsetTop-player.height/2+$(document).scrollTop();

}

function Finalise(){

  alert("You lost, but scored " + score);
  Initialise();
}
<|endoftext|>


<commit_before>import React from 'react';
import RemoteContent from '~/views/components/RemoteContent';
import { hasProvider } from 'oembed-parser';
import ReactMarkdown from 'react-markdown';
import RemarkDisableTokenizers from 'remark-disable-tokenizers';

import { BaseAnchor, Text } from '@tlon/indigo-react';

const DISABLED_BLOCK_TOKENS = [
  'indentedCode',
  'atxHeading',
  'thematicBreak',
  'list',
  'setextHeading',
  'html',
  'definition',
  'table'
];

const DISABLED_INLINE_TOKENS = [];

const RichText = React.memo(({ remoteContentPolicy, ...props }) => (
  <ReactMarkdown
    {...props}
    renderers={{
      link: (props) => {
        if (hasProvider(props.href)) {
          return <RemoteContent className="mw-100" url={props.href} remoteContentPolicy={remoteContentPolicy} />;
        }
        return <BaseAnchor target='_blank' rel='noreferrer noopener' borderBottom='1px solid' {...props}>{props.children}</BaseAnchor>;
      },
      paragraph: (props) => {
        return <Text display='block' mb='2' {...props}>{props.children}</Text>;
      }
    }}
    plugins={[[
      RemarkDisableTokenizers,
      { block: DISABLED_BLOCK_TOKENS, inline: DISABLED_INLINE_TOKENS }
    ]]}
  />
));

RichText.displayName = 'RichText';

export default RichText;
<commit_msg>RichText: pass props correctly<commit_after>import React from 'react';
import RemoteContent from '~/views/components/RemoteContent';
import { hasProvider } from 'oembed-parser';
import ReactMarkdown from 'react-markdown';
import RemarkDisableTokenizers from 'remark-disable-tokenizers';

import { BaseAnchor, Text } from '@tlon/indigo-react';

const DISABLED_BLOCK_TOKENS = [
  'indentedCode',
  'atxHeading',
  'thematicBreak',
  'list',
  'setextHeading',
  'html',
  'definition',
  'table'
];

const DISABLED_INLINE_TOKENS = [];

const RichText = React.memo(({ remoteContentPolicy, ...props }) => (
  <ReactMarkdown
    {...props}
    renderers={{
      link: (props) => {
        if (hasProvider(props.href)) {
          return <RemoteContent className="mw-100" url={props.href} remoteContentPolicy={remoteContentPolicy} />;
        }
        return <BaseAnchor target='_blank' rel='noreferrer noopener' borderBottom='1px solid' {...props}>{props.children}</BaseAnchor>;
      },
      paragraph: (paraProps) => {
        return <Text display='block' mb='2' {...props} {...paraProps}>{props.children}</Text>;
      }
    }}
    plugins={[[
      RemarkDisableTokenizers,
      { block: DISABLED_BLOCK_TOKENS, inline: DISABLED_INLINE_TOKENS }
    ]]}
  />
));

RichText.displayName = 'RichText';

export default RichText;
<|endoftext|>


<commit_before>/**
 * For some implementation details of Brython, see:
 * https://bitbucket.org/olemis/brython/src/bafb482fb6ad42d6ffd2123905627148e339b5ce/src/py2js.js?at=default
 */

//init brython
brython();

//create observer instance
var mutationObserver = new MutationObserver(function(mutations) {

	//iterate over document changes
    mutations.forEach(function(mutation) {

    	//get new node
        var node = mutation.addedNodes[0];

        //checks if is the type we want
        if(node && node.tagName === 'SCRIPT' && node.type === 'text/pyscript') {

        	//test log
        	console.log('encontrado pyscript')

        	//python source
        	var $src;

            //If `src` is found, do a synchronous ajax to get
        	//the code in order to execute it immediately
            if (node.src!=='') {

                if (window.XMLHttpRequest){
                	// code for IE7+, Firefox, Chrome, Opera, Safari
                    var $xmlhttp = new XMLHttpRequest();
                } else {
                	// code for IE6, IE5
                    var $xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                }
                $xmlhttp.open('GET', node.src, false)
                $xmlhttp.send()
                if ($xmlhttp.readyState === 4 && $xmlhttp.status === 200) {
                    $src = $xmlhttp.responseText
                }
                if ($src === undefined) { // houston, we have a problem!!!
                    console.log('Erro ao carregar script: ' + node.src)
                    return;
                }

            } else {

            	//without src, source is tag content
            	$src = node.textContent || node.innerText;

            }

            //python -> javascript
            __BRYTHON__.$py_module_path['__main__'] = window.location.href;
            var $root = __BRYTHON__.py2js($src, '__main__');
            var $jssrc = $root.to_js();

            //eval in global scope
            if (window.execScript) {
               window.execScript($jssrc);
               return;
            }

            //fix for old browsers
            var fn = function() {
                window.eval.call(window, $jssrc);
            };
            fn();
        }
    });
});

//init observer, monitoring changes in all nodes of any level
mutationObserver.observe(document, { childList: true, subtree: true })

<commit_msg>adjust in pyscript<commit_after>/**
 * For some implementation details of Brython, see:
 * https://bitbucket.org/olemis/brython/src/bafb482fb6ad42d6ffd2123905627148e339b5ce/src/py2js.js?at=default
 */

//init brython
brython();

//create observer instance
var mutationObserver = new MutationObserver(function(mutations) {

	//iterate over document changes
    mutations.forEach(function(mutation) {

    	//get new node
        var node = mutation.addedNodes[0];

        //checks if is the type we want
        if(node && node.tagName === 'SCRIPT' && node.type === 'text/pyscript') {

        	//test log
        	console.log('encontrado pyscript')

        	//python source
        	var $src;

            //If src attribute is found, do a synchronous ajax to get
        	//the code in order to execute it immediately
            if (node.src!=='') {

                if (window.XMLHttpRequest){
                	// code for IE7+, Firefox, Chrome, Opera, Safari
                    var $xmlhttp = new XMLHttpRequest();
                } else {
                	// code for IE6, IE5
                    var $xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                }
                $xmlhttp.open('GET', node.src, false)
                $xmlhttp.send()
                if ($xmlhttp.readyState === 4 && $xmlhttp.status === 200) {
                    $src = $xmlhttp.responseText
                }
                if ($src === undefined) { // houston, we have a problem!!!
                    console.log('Erro ao carregar script: ' + node.src)
                    return;
                }

            } else {

            	//without src, source is tag content
            	$src = node.textContent || node.innerText;

            }

            //python -> javascript
            __BRYTHON__.$py_module_path['__main__'] = window.location.href;
            var $root = __BRYTHON__.py2js($src, '__main__');
            var $jssrc = $root.to_js();

            //eval in global scope
            if (window.execScript) {
               window.execScript($jssrc);
               return;
            }

            //fix for old browsers
            var fn = function() {
                window.eval.call(window, $jssrc);
            };
            fn();
        }
    });
});

//init observer, monitoring changes in all nodes of any level
mutationObserver.observe(document, { childList: true, subtree: true })

<|endoftext|>


<commit_before>#!/usr/bin/env node

/*
  Methods for EC2 instance
*/

var Path = require('path')
  , Optionall = require('optionall')
  , FSTK = require('fstk')
  , Async = require('async')
  , _ = require('underscore')
  , Belt = require('jsbelt')
  , Util = require('util')
  , Winston = require('winston')
  , Events = require('events')
  , Request = require('request')
  , EC2 = require('./ec2.js')
  , S3 = require('./s3.js')
;

module.exports = function(O){
  var Opts = O || new Optionall({
                                  '__dirname': Path.resolve(module.filename + '/../..')
                                , 'file_priority': ['package.json', 'environment.json', 'config.json']
                                });

  var S = new (Events.EventEmitter.bind({}))();
  S.settings = Belt.extend({
    'log_level': 'info'
  }, Opts);

  S['ec2'] = new EC2(S.settings);
  S['s3'] = new S3(S.settings);

  var log = Opts.log || new Winston.Logger();
  if (!Opts.log) log.add(Winston.transports.Console, {'level': S.settings.log_level, 'colorize': true, 'timestamp': false});

  return S;
};

if (require.main === module){
  var M = new module.exports();
}
<commit_msg>adding commenting<commit_after>#!/usr/bin/env node

/*
  Methods for EC2 instance
*/

var Path = require('path')
  , Optionall = require('optionall')
  , FSTK = require('fstk')
  , Async = require('async')
  , _ = require('underscore')
  , Belt = require('jsbelt')
  , Util = require('util')
  , Winston = require('winston')
  , Events = require('events')
  , Request = require('request')
  , EC2 = require('./ec2.js')
  , S3 = require('./s3.js')
;

module.exports = function(O){
  var Opts = O || new Optionall({
                                  '__dirname': Path.resolve(module.filename + '/../..')
                                , 'file_priority': ['package.json', 'environment.json', 'config.json']
                                });

  var S = new (Events.EventEmitter.bind({}))();
  S.settings = Belt.extend({
    'log_level': 'info'
  }, Opts);

  S['ec2'] = new EC2(S.settings);
  S['s3'] = new S3(S.settings);

  var log = Opts.log || new Winston.Logger();
  if (!Opts.log) log.add(Winston.transports.Console, {'level': S.settings.log_level, 'colorize': true, 'timestamp': false});

  /*
    methods
  */

  return S;
};

if (require.main === module){
  var M = new module.exports();
}
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule AssetSourceResolver
 * @flow
 * @format
 */
'use strict';

export type ResolvedAssetSource = {
  __packager_asset: boolean,
  width: ?number,
  height: ?number,
  uri: string,
  scale: number,
};

import type {PackagerAsset} from 'AssetRegistry';

const PixelRatio = require('PixelRatio');
const Platform = require('Platform');

const assetPathUtils = require('../../local-cli/bundle/assetPathUtils');
const invariant = require('fbjs/lib/invariant');

/**
 * Returns a path like 'assets/AwesomeModule/icon@2x.png'
 */
function getScaledAssetPath(asset): string {
  var scale = AssetSourceResolver.pickScale(asset.scales, PixelRatio.get());
  var scaleSuffix = scale === 1 ? '' : '@' + scale + 'x';
  var assetDir = assetPathUtils.getBasePath(asset);
  return assetDir + '/' + asset.name + scaleSuffix + '.' + asset.type;
}

/**
 * Returns a path like 'drawable-mdpi/icon.png'
 */
function getAssetPathInDrawableFolder(asset): string {
  var scale = AssetSourceResolver.pickScale(asset.scales, PixelRatio.get());
  var drawbleFolder = assetPathUtils.getAndroidResourceFolderName(asset, scale);
  var fileName = assetPathUtils.getAndroidResourceIdentifier(asset);
  return drawbleFolder + '/' + fileName + '.' + asset.type;
}

class AssetSourceResolver {
  serverUrl: ?string;
  // where the jsbundle is being run from
  jsbundleUrl: ?string;
  // the asset to resolve
  asset: PackagerAsset;

  constructor(serverUrl: ?string, jsbundleUrl: ?string, asset: PackagerAsset) {
    this.serverUrl = serverUrl;
    this.jsbundleUrl = jsbundleUrl;
    this.asset = asset;
  }

  isLoadedFromServer(): boolean {
    return !!this.serverUrl;
  }

  isLoadedFromFileSystem(): boolean {
    return !!(this.jsbundleUrl && this.jsbundleUrl.startsWith('file://'));
  }

  defaultAsset(): ResolvedAssetSource {
    if (this.isLoadedFromServer()) {
      return this.assetServerURL();
    }

    if (Platform.OS === 'android') {
      return this.isLoadedFromFileSystem()
        ? this.drawableFolderInBundle()
        : this.resourceIdentifierWithoutScale();
    } else {
      return this.scaledAssetURLNearBundle();
    }
  }

  /**
   * Returns an absolute URL which can be used to fetch the asset
   * from the devserver
   */
  assetServerURL(): ResolvedAssetSource {
    invariant(!!this.serverUrl, 'need server to load from');
    return this.fromSource(
      this.serverUrl +
        getScaledAssetPath(this.asset) +
        '?platform=' +
        Platform.OS +
        '&hash=' +
        this.asset.hash,
    );
  }

  /**
   * Resolves to just the scaled asset filename
   * E.g. 'assets/AwesomeModule/icon@2x.png'
   */
  scaledAssetPath(): ResolvedAssetSource {
    return this.fromSource(getScaledAssetPath(this.asset));
  }

  /**
   * Resolves to where the bundle is running from, with a scaled asset filename
   * E.g. 'file:///sdcard/bundle/assets/AwesomeModule/icon@2x.png'
   */
  scaledAssetURLNearBundle(): ResolvedAssetSource {
    const path = this.jsbundleUrl || 'file://';
    return this.fromSource(path + getScaledAssetPath(this.asset));
  }

  /**
   * The default location of assets bundled with the app, located by
   * resource identifier
   * The Android resource system picks the correct scale.
   * E.g. 'assets_awesomemodule_icon'
   */
  resourceIdentifierWithoutScale(): ResolvedAssetSource {
    invariant(
      Platform.OS === 'android',
      'resource identifiers work on Android',
    );
    return this.fromSource(
      assetPathUtils.getAndroidResourceIdentifier(this.asset),
    );
  }

  /**
   * If the jsbundle is running from a sideload location, this resolves assets
   * relative to its location
   * E.g. 'file:///sdcard/AwesomeModule/drawable-mdpi/icon.png'
   */
  drawableFolderInBundle(): ResolvedAssetSource {
    const path = this.jsbundleUrl || 'file://';
    return this.fromSource(path + getAssetPathInDrawableFolder(this.asset));
  }

  fromSource(source: string): ResolvedAssetSource {
    return {
      __packager_asset: true,
      width: this.asset.width,
      height: this.asset.height,
      uri: source,
      scale: AssetSourceResolver.pickScale(this.asset.scales, PixelRatio.get()),
    };
  }

  static pickScale(scales: Array<number>, deviceScale: number): number {
    // Packager guarantees that `scales` array is sorted
    for (var i = 0; i < scales.length; i++) {
      if (scales[i] >= deviceScale) {
        return scales[i];
      }
    }

    // If nothing matches, device scale is larger than any available
    // scales, so we return the biggest one. Unless the array is empty,
    // in which case we default to 1
    return scales[scales.length - 1] || 1;
  }
}

module.exports = AssetSourceResolver;
<commit_msg>Add FDSStoryHeader<commit_after>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule AssetSourceResolver
 * @flow
 * @format
 */
'use strict';

export type ResolvedAssetSource = {|
  +__packager_asset: boolean,
  +width: ?number,
  +height: ?number,
  +uri: string,
  +scale: number,
|};

import type {PackagerAsset} from 'AssetRegistry';

const PixelRatio = require('PixelRatio');
const Platform = require('Platform');

const assetPathUtils = require('../../local-cli/bundle/assetPathUtils');
const invariant = require('fbjs/lib/invariant');

/**
 * Returns a path like 'assets/AwesomeModule/icon@2x.png'
 */
function getScaledAssetPath(asset): string {
  var scale = AssetSourceResolver.pickScale(asset.scales, PixelRatio.get());
  var scaleSuffix = scale === 1 ? '' : '@' + scale + 'x';
  var assetDir = assetPathUtils.getBasePath(asset);
  return assetDir + '/' + asset.name + scaleSuffix + '.' + asset.type;
}

/**
 * Returns a path like 'drawable-mdpi/icon.png'
 */
function getAssetPathInDrawableFolder(asset): string {
  var scale = AssetSourceResolver.pickScale(asset.scales, PixelRatio.get());
  var drawbleFolder = assetPathUtils.getAndroidResourceFolderName(asset, scale);
  var fileName = assetPathUtils.getAndroidResourceIdentifier(asset);
  return drawbleFolder + '/' + fileName + '.' + asset.type;
}

class AssetSourceResolver {
  serverUrl: ?string;
  // where the jsbundle is being run from
  jsbundleUrl: ?string;
  // the asset to resolve
  asset: PackagerAsset;

  constructor(serverUrl: ?string, jsbundleUrl: ?string, asset: PackagerAsset) {
    this.serverUrl = serverUrl;
    this.jsbundleUrl = jsbundleUrl;
    this.asset = asset;
  }

  isLoadedFromServer(): boolean {
    return !!this.serverUrl;
  }

  isLoadedFromFileSystem(): boolean {
    return !!(this.jsbundleUrl && this.jsbundleUrl.startsWith('file://'));
  }

  defaultAsset(): ResolvedAssetSource {
    if (this.isLoadedFromServer()) {
      return this.assetServerURL();
    }

    if (Platform.OS === 'android') {
      return this.isLoadedFromFileSystem()
        ? this.drawableFolderInBundle()
        : this.resourceIdentifierWithoutScale();
    } else {
      return this.scaledAssetURLNearBundle();
    }
  }

  /**
   * Returns an absolute URL which can be used to fetch the asset
   * from the devserver
   */
  assetServerURL(): ResolvedAssetSource {
    invariant(!!this.serverUrl, 'need server to load from');
    return this.fromSource(
      this.serverUrl +
        getScaledAssetPath(this.asset) +
        '?platform=' +
        Platform.OS +
        '&hash=' +
        this.asset.hash,
    );
  }

  /**
   * Resolves to just the scaled asset filename
   * E.g. 'assets/AwesomeModule/icon@2x.png'
   */
  scaledAssetPath(): ResolvedAssetSource {
    return this.fromSource(getScaledAssetPath(this.asset));
  }

  /**
   * Resolves to where the bundle is running from, with a scaled asset filename
   * E.g. 'file:///sdcard/bundle/assets/AwesomeModule/icon@2x.png'
   */
  scaledAssetURLNearBundle(): ResolvedAssetSource {
    const path = this.jsbundleUrl || 'file://';
    return this.fromSource(path + getScaledAssetPath(this.asset));
  }

  /**
   * The default location of assets bundled with the app, located by
   * resource identifier
   * The Android resource system picks the correct scale.
   * E.g. 'assets_awesomemodule_icon'
   */
  resourceIdentifierWithoutScale(): ResolvedAssetSource {
    invariant(
      Platform.OS === 'android',
      'resource identifiers work on Android',
    );
    return this.fromSource(
      assetPathUtils.getAndroidResourceIdentifier(this.asset),
    );
  }

  /**
   * If the jsbundle is running from a sideload location, this resolves assets
   * relative to its location
   * E.g. 'file:///sdcard/AwesomeModule/drawable-mdpi/icon.png'
   */
  drawableFolderInBundle(): ResolvedAssetSource {
    const path = this.jsbundleUrl || 'file://';
    return this.fromSource(path + getAssetPathInDrawableFolder(this.asset));
  }

  fromSource(source: string): ResolvedAssetSource {
    return {
      __packager_asset: true,
      width: this.asset.width,
      height: this.asset.height,
      uri: source,
      scale: AssetSourceResolver.pickScale(this.asset.scales, PixelRatio.get()),
    };
  }

  static pickScale(scales: Array<number>, deviceScale: number): number {
    // Packager guarantees that `scales` array is sorted
    for (var i = 0; i < scales.length; i++) {
      if (scales[i] >= deviceScale) {
        return scales[i];
      }
    }

    // If nothing matches, device scale is larger than any available
    // scales, so we return the biggest one. Unless the array is empty,
    // in which case we default to 1
    return scales[scales.length - 1] || 1;
  }
}

module.exports = AssetSourceResolver;
<|endoftext|>