<commit_before>function startApp() {
    showHideMenuLinks();
    showHomeView();

    // Bind the navigation menu links
    $("#linkHome").click(showHomeView);
    $("#linkLogin").click(showLoginView);
    $("#linkRegister").click(showRegisterView);
    $("#linkListAds").click(listAdverts);
    $("#linkLogout").click(logoutUser);

    // Bind the form submit buttons
    $("#buttonLoginUser").click(loginUser);
    $("#buttonRegisterUser").click(registerUser);

    const kinveyBaseUrl = "https://mock.api.com/";
    const kinveyAppKey = "kid_rk";
    const kinveyAppSecret = "736804a668";

    function showView(viewName) {
        // Hide all views and show the selected view only
        $('main > section').hide();
        $('#' + viewName).show();
    }

    function showHideMenuLinks() {
        $("#linkHome").show();
        if (sessionStorage.getItem('authToken') === null) {
            // No logged in user
            $("#linkLogin").show();
            $("#linkRegister").show();
            $("#linkListAds").hide();
            $("#linkLogout").hide();
        } else {
            // We have logged in user
            $("#linkLogin").hide();
            $("#linkRegister").hide();
            $("#linkListAds").show();
            $("#linkLogout").show();
        }
    }

    function showHomeView() {
        showView('viewHome');
    }

    function showLoginView() {
        showView('viewLogin');
        $('#formLogin').trigger('reset');
    }

    function showRegisterView() {
        $('#formRegister').trigger('reset');
        showView('viewRegister');
    }

    // user/login
    function loginUser() {
        const kinveyLoginUrl = kinveyBaseUrl + "user/" + kinveyAppKey + "/login";
        const kinveyAuthHeaders = {
            'Authorization': "Basic " + btoa(kinveyAppKey + ":" + kinveyAppSecret),
        };
        let userData = {
            username: $('#formLogin input[name=username]').val(),
            password: $('#formLogin input[name=passwd]').val()
        };

        $.ajax({
            method: "POST",
            url: kinveyLoginUrl,
            headers: kinveyAuthHeaders,
            data: userData,
            success: loginSuccess
        });

        function loginSuccess(userInfo) {
            saveAuthInSession(userInfo);
            showHideMenuLinks();
            listAdverts();
        }
    }

    function saveAuthInSession(userInfo) {
        let userAuth = userInfo._kmd.authtoken;
        sessionStorage.setItem('authToken', userAuth);
        let userId = userInfo._id;
        sessionStorage.setItem('userId', userId);
    }

    // user/register
    function registerUser() {
        const kinveyRegisterUrl = kinveyBaseUrl + "user/" + kinveyAppKey + "/";
        const kinveyAuthHeaders = {
            'Authorization': "Basic " + btoa(kinveyAppKey + ":" + kinveyAppSecret),
        };

        let userData = {
            username: $('#formRegister input[name=username]').val(),
            password: $('#formRegister input[name=passwd]').val()
        };

        $.ajax({
            method: "POST",
            url: kinveyRegisterUrl,
            headers: kinveyAuthHeaders,
            data: userData,
            success: registerSuccess
        });

        function registerSuccess(userInfo) {
            console.log(userInfo);
            saveAuthInSession(userInfo);
            showHideMenuLinks();
            listAdverts();
        }
    }

    // user/logout
    function logoutUser() {
        sessionStorage.clear();
        $('#loggedInUser').text("");
        showHideMenuLinks();
        showHomeView();
    }

    // advertisement/all
    function listAdverts() {
        $('#ads').empty();
        showView('viewAds');

        const kinveyAdvertsUrl = kinveyBaseUrl + "appdata/" + kinveyAppKey + "/adverts";
        const kinveyAuthHeaders = {
            'Authorization': "Kinvey " + sessionStorage.getItem('authToken'),
        };
        $.ajax({
            method: "GET",
            url: kinveyAdvertsUrl,
            headers: kinveyAuthHeaders,
            success: loadAdvertsSuccess
        });

        function loadAdvertsSuccess(adverts) {
            if (adverts.length === 0) {
                $('#ads').text('No advertisements available.');
            } else {
                let advertsTable = $('
')
                    .append($('
').append(
                        'Title	',
                        'Publisher	',
                        'Date Published	',
                        'Price	')
                    );

                for (let advert of adverts) {
                    advertsTable.append($('
').append(
                        $('').text(advert.title),
                        $('').text(advert.publisher),
                        $('').text(advert.datePublished),
                        $('').text(advert.price)
                    ));
                }

                $('#ads').append(advertsTable);
            }
        }
    }
}<commit_msg>Stage 6, Task 2 – Detailed View<commit_after>function startApp() {
    showHideMenuLinks();
    showHomeView();

    // Bind the navigation menu links
    $("#linkHome").click(showHomeView);
    $("#linkLogin").click(showLoginView);
    $("#linkRegister").click(showRegisterView);
    $("#linkListAds").click(listAdverts);
    $("#linkLogout").click(logoutUser);

    // Bind the form submit buttons
    $("#buttonLoginUser").click(loginUser);
    $("#buttonRegisterUser").click(registerUser);

    const kinveyBaseUrl = "https://mock.api.com/";
    const kinveyAppKey = "kid_rk";
    const kinveyAppSecret = "736804a668";

    function showView(viewName) {
        // Hide all views and show the selected view only
        $('main > section').hide();
        $('#' + viewName).show();
    }

    function showHideMenuLinks() {
        $("#linkHome").show();
        if (sessionStorage.getItem('authToken') === null) {
            // No logged in user
            $("#linkLogin").show();
            $("#linkRegister").show();
            $("#linkListAds").hide();
            $("#linkLogout").hide();
        } else {
            // We have logged in user
            $("#linkLogin").hide();
            $("#linkRegister").hide();
            $("#linkListAds").show();
            $("#linkLogout").show();
        }
    }

    function showHomeView() {
        showView('viewHome');
    }

    function showLoginView() {
        showView('viewLogin');
        $('#formLogin').trigger('reset');
    }

    function showRegisterView() {
        $('#formRegister').trigger('reset');
        showView('viewRegister');
    }

    // user/login
    function loginUser() {
        const kinveyLoginUrl = kinveyBaseUrl + "user/" + kinveyAppKey + "/login";
        const kinveyAuthHeaders = {
            'Authorization': "Basic " + btoa(kinveyAppKey + ":" + kinveyAppSecret),
        };
        let userData = {
            username: $('#formLogin input[name=username]').val(),
            password: $('#formLogin input[name=passwd]').val()
        };

        $.ajax({
            method: "POST",
            url: kinveyLoginUrl,
            headers: kinveyAuthHeaders,
            data: userData,
            success: loginSuccess
        });

        function loginSuccess(userInfo) {
            saveAuthInSession(userInfo);
            showHideMenuLinks();
            listAdverts();
        }
    }

    function saveAuthInSession(userInfo) {
        let userAuth = userInfo._kmd.authtoken;
        sessionStorage.setItem('authToken', userAuth);
        let userId = userInfo._id;
        sessionStorage.setItem('userId', userId);
    }

    // user/register
    function registerUser() {
        const kinveyRegisterUrl = kinveyBaseUrl + "user/" + kinveyAppKey + "/";
        const kinveyAuthHeaders = {
            'Authorization': "Basic " + btoa(kinveyAppKey + ":" + kinveyAppSecret),
        };

        let userData = {
            username: $('#formRegister input[name=username]').val(),
            password: $('#formRegister input[name=passwd]').val()
        };

        $.ajax({
            method: "POST",
            url: kinveyRegisterUrl,
            headers: kinveyAuthHeaders,
            data: userData,
            success: registerSuccess
        });

        function registerSuccess(userInfo) {
            console.log(userInfo);
            saveAuthInSession(userInfo);
            showHideMenuLinks();
            listAdverts();
        }
    }

    // user/logout
    function logoutUser() {
        sessionStorage.clear();
        $('#loggedInUser').text("");
        showHideMenuLinks();
        showHomeView();
    }

    // advertisement/all
    function listAdverts() {
        $('#ads').empty();
        showView('viewAds');

        const kinveyAdvertsUrl = kinveyBaseUrl + "appdata/" + kinveyAppKey + "/adverts";
        const kinveyAuthHeaders = {
            'Authorization': "Kinvey " + sessionStorage.getItem('authToken'),
        };
        $.ajax({
            method: "GET",
            url: kinveyAdvertsUrl,
            headers: kinveyAuthHeaders,
            success: loadAdvertsSuccess
        });

        function loadAdvertsSuccess(adverts) {
            if (adverts.length === 0) {
                $('#ads').text('No advertisements available.');
            } else {
                let advertsTable = $('
')
                    .append($('
').append(
                        'Title	',
						   'Description	',
                        'Publisher	',
                        'Date Published	',
                        'Price	',
                        'Actions	')
                    );

                for (let advert of adverts) {

					     let readMoreLink = $(`<a data-id="${advert._id}" href="#">[Read More]</a>`)
                        .click(function() { displayAdvert($(this).attr("data-id")) });

                    advertsTable.append($('
').append(
                        $('').text(advert.title),
						   $('').text(advert.description),
                        $('').text(advert.publisher),
                        $('').text(advert.datePublished),
                        $('').text(advert.price),
                        $('').append(readMoreLink)
                    ));
                }

                $('#ads').append(advertsTable);
            }
        }
    }

	    function displayAdvert(advertId){
        const kinveyAdvertUrl = kinveyBaseUrl + "appdata/" +
            kinveyAppKey + "/adverts/" + advertId;
        const kinveyAuthHeaders = {
            'Authorization': "Kinvey " + sessionStorage.getItem('authToken'),
        };

        $.ajax({
            method: "GET",
            url: kinveyAdvertUrl,
            headers: kinveyAuthHeaders,
            success: displayAdvertSuccess
        });

        $('#viewDetailsAd').empty();

        function displayAdvertSuccess(advert) {
            let advertInfo = $('
').append(
                $('').attr("src", advert.image),
                $('
'),
                $('').text('Title:'),
                $('
').text(advert.title),
                $('').text('Description:'),
                $('
').text(advert.description),
                $('').text('Publisher:'),
                $('
').text(advert.publisher),
                $('').text('Date:'),
                $('
').text(advert.datePublished));

            $('#viewDetailsAd').append(advertInfo);

            showView('viewDetailsAd');
        }
    }

}<|endoftext|>


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

'use strict';

const _ = require('lodash');
const core = require('artillery-core');
const runner = core.runner;
const fs = require('fs');
const path = require('path');
const async = require('async');
const csv = require('csv-parse');
const util = require('util');
const cli = require('cli');
const YAML = require('yamljs');
const defaultOptions = require('rc')('artillery');
const moment = require('moment');
const chalk = require('chalk');

module.exports = run;

function run(scriptPath, options) {

  let logfile;
  if (options.output && options.output !== defaultOptions.output) {
    logfile = options.output;
    if (!logfile.match(/\.json$/)) {
      logfile += '.json';
    }
  } else {
    if (defaultOptions.output) {
      logfile = moment().format(defaultOptions.output);
    } else {
      logfile = moment().format('[artillery_report_]YMMDD_HHmmSS[.json]');
    }
  }

  function log() {
    if (options.quiet) { return; }
    console.log.apply(console, arguments);
  }

  async.waterfall([
    function readScript(callback) {

      fs.readFile(scriptPath, 'utf-8', function(err, data) {

        if (err) {
          const msg = util.format('File not found: %s', scriptPath);
          return callback(new Error(msg), null);
        }

        let script;
        let fileformat;
        try {
          if (/\.ya?ml$/.test(path.extname(scriptPath))) {
            fileformat = 'YAML';
            script = YAML.parse(data);
          } else {
            fileformat = 'JSON';
            script = JSON.parse(data);
          }
        } catch (e) {
          const msg2 = `File ${scriptPath} does not appear to be valid ${fileformat}: (${e.message})`;
          return callback(new Error(msg2), null);
        }

        if (options.target && script.config) {
          script.config.target = options.target;
        }

        if (!script.config.target && !options.environment) {
          const msg4 = 'No target specified and no environment chosen';
          return callback(new Error(msg4), null);
        }

        let validation = core.validate(script);
        if (!validation.valid) {
          log(validation.errors);
          return callback(new Error('Test script validation error'), null);
        }

        return callback(null, {script: script});
      });
    },
    function readPayload(context, callback) {

      if (context.script.config.payload && _.isArray(context.script.config.payload)) {
        async.map(context.script.config.payload,
          function(item, callback2) {
            let absoluteScriptPath = path.resolve(process.cwd(), scriptPath);
            let payloadFile = path.resolve(path.dirname(absoluteScriptPath), item.path);

            let data = fs.readFileSync(payloadFile, 'utf-8');
            csv(data, function(err, parsedData) {
              item.data = parsedData;
              return callback2(err, item);
            });
          },
          function(err, results) {
            if (err) {
              return callback(err, null);
            }
            context.payload = results;
            return callback(null, context);
          });
      } else if (context.script.config.payload &&
                 (_.isObject(context.script.config.payload) ||
                 options.payload)) {
        //use config if path set else use command line
        let csvdata;
        if (context.script.config.payload.path){
           csvdata = fs.readFileSync(context.script.config.payload.path, 'utf-8');
        } else{
           csvdata = fs.readFileSync(options.payload, 'utf-8');
        }

        csv(csvdata, function(err, payload) {

          if (err) {
            const msg3 = util.format(
              'File %s does not appear to be valid CSV', options.payload);
            return callback(new Error(msg3), null);
          }

          context.payload = payload;

          return callback(null, context);
        });
      } else {
        if (context.script.config.payload) {
          log(
            'WARNING: payload file not set, but payload is configured in %s\n',
            scriptPath);
        }

        return callback(null, context);
      }
    },
    function checkIfXPathIsUsed(context, callback) {
      // FIXME: This should probably be in core.
      let xmlInstalled = null;
      try {
        xmlInstalled = require('artillery-xml-capture');
      } catch (e) {
      }

      let usesXPathCapture = false;
      context.script.scenarios.forEach(function(scenario) {
        scenario.flow.forEach(function(step) {
          let params = step[_.keys(step)[0]];
          if ((params.capture && params.capture.xpath) ||
              (params.match && params.match.xpath)) {
            usesXPathCapture = true;
          }
        });
      });
      if (usesXPathCapture && !xmlInstalled) {
        console.log(chalk.bold.red('Warning: '), chalk.bold.yellow('your test script is using XPath capture, but artillery-xml-capture does not seem to be installed.'));
        console.log(chalk.bold.yellow('Install it with: npm install -g artillery-xml-capture'));
      }
      return callback(null, context);
    }
    ],
    function(err, result) {

      if (err) {
        log(err.message);
        process.exit(1);
      }

      if (result.script.config.processor) {
        let absoluteScriptPath = path.resolve(process.cwd(), scriptPath);
        let processorPath = path.resolve(path.dirname(absoluteScriptPath), result.script.config.processor);
        let processor = require(processorPath);
        result.script.config.processor = processor;
      }

      if (options.insecure) {
        if (result.script.config.tls) {
          if (result.script.config.tls.rejectUnauthorized) {
            log('WARNING: TLS certificate validation enabled in the ' +
                        'test script, but explicitly disabled with ' +
                        '-k/--insecure.');
          }
          result.script.config.tls.rejectUnauthorized = false;
        } else {
          result.script.config.tls = {rejectUnauthorized: false};
        }
      }

      var ee = runner(result.script, result.payload, {
        environment: options.environment
      });

      log('Log file: %s', logfile);

      //var bar;
      //var barTimer;
      ee.on('phaseStarted', function(opts) {
        log(
          'Phase %s%s started - duration: %ss',
          opts.index,
          (opts.name ? ' (' + opts.name + ')' : ''),
          opts.duration);
        if (!options.quiet && process.stdout.isTTY) {
          cli.spinner('');
        }
        // bar = new ProgressBar('[ :bar ]', {
        //   total: opts.duration,
        //   width: 79
        // });
        // bar.tick();
        // barTimer = setInterval(function() {
        //   bar.tick();
        // }, 1 * 1000);
      });

      ee.on('phaseCompleted', function(opts) {

        //clearInterval(barTimer);
        if (!options.quiet && process.stdout.isTTY) {
          cli.spinner('', true);
        }
        log(
          'phase %s%s completed',
          opts.index,
          (opts.name ? ' (' + opts.name + ')' : ''));
      });

      ee.on('stats', function(report) {
        if (!options.quiet && process.stdout.isTTY) {
          cli.spinner('', true);
        }

        log('Intermediate report @ %s', report.timestamp);
        if (!options.quiet) {
          humanize(report);
        }

        if (!options.quiet && process.stdout.isTTY) {
          cli.spinner('');
        }
      });

      ee.once('done', function(report) {
        if (!options.quiet && process.stdout.isTTY) {
          cli.spinner('', true);
        }

        if (process.stdout.isTTY) {
          cli.spinner('', true);
        }

        log('all scenarios completed');
        log('Complete report @ %s', report.aggregate.timestamp);
        if (!options.quiet) {
          humanize(report.aggregate);
        }

        report.phases = _.get(result, 'script.config.phases', []);

        fs.writeFileSync(logfile, JSON.stringify(report, null, 2), {flag: 'w'});

        if (result.script.config.ensure) {
          const latency = report.aggregate.latency;
          _.each(result.script.config.ensure, function(max, k) {

            let bucket = k === 'p50' ? 'median' : k;
            if (latency[bucket]) {
              if (latency[bucket] > max) {
                const msg = util.format(
                  'ensure condition failed: ensure.%s < %s', bucket, max);
                log(msg);
                process.exit(1);
              }
            }
          });
        }
      });

      ee.run();
    });
}

function humanize(report) {
  console.log('  Scenarios launched: %s', report.scenariosCreated);
  console.log('  Scenarios completed: %s', report.scenariosCompleted);
  console.log('  Number of requests made: %s', report.requestsCompleted);
  console.log('  RPS: %s', report.rps.mean);
  console.log('  Request latency:');
  console.log('    min: %s', report.latency.min);
  console.log('    max: %s', report.latency.max);
  console.log('    median: %s', report.latency.median);
  console.log('    p95: %s', report.latency.p95);
  console.log('    p99: %s', report.latency.p99);
  console.log('  Scenario duration:');
  console.log('    min: %s', report.scenarioDuration.min);
  console.log('    max: %s', report.scenarioDuration.max);
  console.log('    median: %s', report.scenarioDuration.median);
  console.log('    p95: %s', report.scenarioDuration.p95);
  console.log('    p99: %s', report.scenarioDuration.p99);

  if (_.size(report.customStats) > 0) {
    console.log('Custom stats:');
    _.each(report.customStats, function(r, n) {
      console.log('  %s:', n);
      console.log('    min: %s', r.min);
      console.log('    max: %s', r.max);
      console.log('    median: %s', r.median);
      console.log('    p95: %s', r.p95);
      console.log('    p99: %s', r.p99);
    });
  }

  if (_.keys(report.codes).length !== 0) {
    console.log('  Codes:');
    _.each(report.codes, function(count, code) {
      console.log('    %s: %s', code, count);
    });
  }
  if (_.keys(report.errors).length !== 0) {
    console.log('  Errors:');
    _.each(report.errors, function(count, code) {
      console.log('    %s: %s', code, count);
    });
  }
}
<commit_msg>formatting cleanup<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

'use strict';

const _ = require('lodash');
const core = require('artillery-core');
const runner = core.runner;
const fs = require('fs');
const path = require('path');
const async = require('async');
const csv = require('csv-parse');
const util = require('util');
const cli = require('cli');
const YAML = require('yamljs');
const defaultOptions = require('rc')('artillery');
const moment = require('moment');
const chalk = require('chalk');

module.exports = run;

function run(scriptPath, options) {

  let logfile;
  if (options.output && options.output !== defaultOptions.output) {
    logfile = options.output;
    if (!logfile.match(/\.json$/)) {
      logfile += '.json';
    }
  } else {
    if (defaultOptions.output) {
      logfile = moment().format(defaultOptions.output);
    } else {
      logfile = moment().format('[artillery_report_]YMMDD_HHmmSS[.json]');
    }
  }

  function log() {
    if (options.quiet) { return; }
    console.log.apply(console, arguments);
  }

  async.waterfall([
    function readScript(callback) {

      fs.readFile(scriptPath, 'utf-8', function(err, data) {

        if (err) {
          const msg = util.format('File not found: %s', scriptPath);
          return callback(new Error(msg), null);
        }

        let script;
        let fileformat;
        try {
          if (/\.ya?ml$/.test(path.extname(scriptPath))) {
            fileformat = 'YAML';
            script = YAML.parse(data);
          } else {
            fileformat = 'JSON';
            script = JSON.parse(data);
          }
        } catch (e) {
          const msg2 = `File ${scriptPath} does not appear to be valid ${fileformat}: (${e.message})`;
          return callback(new Error(msg2), null);
        }

        if (options.target && script.config) {
          script.config.target = options.target;
        }

        if (!script.config.target && !options.environment) {
          const msg4 = 'No target specified and no environment chosen';
          return callback(new Error(msg4), null);
        }

        let validation = core.validate(script);
        if (!validation.valid) {
          log(validation.errors);
          return callback(new Error('Test script validation error'), null);
        }

        return callback(null, {script: script});
      });
    },
    function readPayload(context, callback) {

      if (context.script.config.payload && _.isArray(context.script.config.payload)) {
        async.map(context.script.config.payload,
          function(item, callback2) {
            let absoluteScriptPath = path.resolve(process.cwd(), scriptPath);
            let payloadFile = path.resolve(path.dirname(absoluteScriptPath), item.path);

            let data = fs.readFileSync(payloadFile, 'utf-8');
            csv(data, function(err, parsedData) {
              item.data = parsedData;
              return callback2(err, item);
            });
          },
          function(err, results) {
            if (err) {
              return callback(err, null);
            }
            context.payload = results;
            return callback(null, context);
          });
      } else if (context.script.config.payload &&
                 (_.isObject(context.script.config.payload) ||
                 options.payload)) {
        //use config if path set else use command line
        let csvdata;
        if (context.script.config.payload.path) {
          csvdata = fs.readFileSync(context.script.config.payload.path, 'utf-8');
        } else {
          svdata = fs.readFileSync(options.payload, 'utf-8');
        }
        csv(csvdata, function(err, payload) {

          if (err) {
            const msg3 = util.format(
              'File %s does not appear to be valid CSV', options.payload);
            return callback(new Error(msg3), null);
          }

          context.payload = payload;

          return callback(null, context);
        });
      } else {
        if (context.script.config.payload) {
          log(
            'WARNING: payload file not set, but payload is configured in %s\n',
            scriptPath);
        }

        return callback(null, context);
      }
    },
    function checkIfXPathIsUsed(context, callback) {
      // FIXME: This should probably be in core.
      let xmlInstalled = null;
      try {
        xmlInstalled = require('artillery-xml-capture');
      } catch (e) {
      }

      let usesXPathCapture = false;
      context.script.scenarios.forEach(function(scenario) {
        scenario.flow.forEach(function(step) {
          let params = step[_.keys(step)[0]];
          if ((params.capture && params.capture.xpath) ||
              (params.match && params.match.xpath)) {
            usesXPathCapture = true;
          }
        });
      });
      if (usesXPathCapture && !xmlInstalled) {
        console.log(chalk.bold.red('Warning: '), chalk.bold.yellow('your test script is using XPath capture, but artillery-xml-capture does not seem to be installed.'));
        console.log(chalk.bold.yellow('Install it with: npm install -g artillery-xml-capture'));
      }
      return callback(null, context);
    }
    ],
    function(err, result) {

      if (err) {
        log(err.message);
        process.exit(1);
      }

      if (result.script.config.processor) {
        let absoluteScriptPath = path.resolve(process.cwd(), scriptPath);
        let processorPath = path.resolve(path.dirname(absoluteScriptPath), result.script.config.processor);
        let processor = require(processorPath);
        result.script.config.processor = processor;
      }

      if (options.insecure) {
        if (result.script.config.tls) {
          if (result.script.config.tls.rejectUnauthorized) {
            log('WARNING: TLS certificate validation enabled in the ' +
                        'test script, but explicitly disabled with ' +
                        '-k/--insecure.');
          }
          result.script.config.tls.rejectUnauthorized = false;
        } else {
          result.script.config.tls = {rejectUnauthorized: false};
        }
      }

      var ee = runner(result.script, result.payload, {
        environment: options.environment
      });

      log('Log file: %s', logfile);

      //var bar;
      //var barTimer;
      ee.on('phaseStarted', function(opts) {
        log(
          'Phase %s%s started - duration: %ss',
          opts.index,
          (opts.name ? ' (' + opts.name + ')' : ''),
          opts.duration);
        if (!options.quiet && process.stdout.isTTY) {
          cli.spinner('');
        }
        // bar = new ProgressBar('[ :bar ]', {
        //   total: opts.duration,
        //   width: 79
        // });
        // bar.tick();
        // barTimer = setInterval(function() {
        //   bar.tick();
        // }, 1 * 1000);
      });

      ee.on('phaseCompleted', function(opts) {

        //clearInterval(barTimer);
        if (!options.quiet && process.stdout.isTTY) {
          cli.spinner('', true);
        }
        log(
          'phase %s%s completed',
          opts.index,
          (opts.name ? ' (' + opts.name + ')' : ''));
      });

      ee.on('stats', function(report) {
        if (!options.quiet && process.stdout.isTTY) {
          cli.spinner('', true);
        }

        log('Intermediate report @ %s', report.timestamp);
        if (!options.quiet) {
          humanize(report);
        }

        if (!options.quiet && process.stdout.isTTY) {
          cli.spinner('');
        }
      });

      ee.once('done', function(report) {
        if (!options.quiet && process.stdout.isTTY) {
          cli.spinner('', true);
        }

        if (process.stdout.isTTY) {
          cli.spinner('', true);
        }

        log('all scenarios completed');
        log('Complete report @ %s', report.aggregate.timestamp);
        if (!options.quiet) {
          humanize(report.aggregate);
        }

        report.phases = _.get(result, 'script.config.phases', []);

        fs.writeFileSync(logfile, JSON.stringify(report, null, 2), {flag: 'w'});

        if (result.script.config.ensure) {
          const latency = report.aggregate.latency;
          _.each(result.script.config.ensure, function(max, k) {

            let bucket = k === 'p50' ? 'median' : k;
            if (latency[bucket]) {
              if (latency[bucket] > max) {
                const msg = util.format(
                  'ensure condition failed: ensure.%s < %s', bucket, max);
                log(msg);
                process.exit(1);
              }
            }
          });
        }
      });

      ee.run();
    });
}

function humanize(report) {
  console.log('  Scenarios launched: %s', report.scenariosCreated);
  console.log('  Scenarios completed: %s', report.scenariosCompleted);
  console.log('  Number of requests made: %s', report.requestsCompleted);
  console.log('  RPS: %s', report.rps.mean);
  console.log('  Request latency:');
  console.log('    min: %s', report.latency.min);
  console.log('    max: %s', report.latency.max);
  console.log('    median: %s', report.latency.median);
  console.log('    p95: %s', report.latency.p95);
  console.log('    p99: %s', report.latency.p99);
  console.log('  Scenario duration:');
  console.log('    min: %s', report.scenarioDuration.min);
  console.log('    max: %s', report.scenarioDuration.max);
  console.log('    median: %s', report.scenarioDuration.median);
  console.log('    p95: %s', report.scenarioDuration.p95);
  console.log('    p99: %s', report.scenarioDuration.p99);

  if (_.size(report.customStats) > 0) {
    console.log('Custom stats:');
    _.each(report.customStats, function(r, n) {
      console.log('  %s:', n);
      console.log('    min: %s', r.min);
      console.log('    max: %s', r.max);
      console.log('    median: %s', r.median);
      console.log('    p95: %s', r.p95);
      console.log('    p99: %s', r.p99);
    });
  }

  if (_.keys(report.codes).length !== 0) {
    console.log('  Codes:');
    _.each(report.codes, function(count, code) {
      console.log('    %s: %s', code, count);
    });
  }
  if (_.keys(report.errors).length !== 0) {
    console.log('  Errors:');
    _.each(report.errors, function(count, code) {
      console.log('    %s: %s', code, count);
    });
  }
}
<|endoftext|>


<commit_before>const BaseXform = require('../base-xform');

//   <t xml:space="preserve"> is </t>

class TextXform extends BaseXform {
  get tag() {
    return 't';
  }

  render(xmlStream, model) {
    xmlStream.openNode('t');
    if (model[0] === ' ' || model[model.length - 1] === ' ') {
      xmlStream.addAttribute('xml:space', 'preserve');
    }
    xmlStream.writeText(model);
    xmlStream.closeNode();
  }

  get model() {
    return this._text.join('').replace(/_x([0-9A-F]{4})_/g, ($0, $1) => String.fromCharCode(parseInt($1, 16)));
  }

  parseOpen(node) {
    switch (node.name) {
      case 't':
        this._text = [];
        return true;
      default:
        return false;
    }
  }

  parseText(text) {
    this._text.push(text);
  }

  parseClose() {
    return false;
  }
}

module.exports = TextXform;
<commit_msg>add xml:space="preserve" for all whitespaces<commit_after>const BaseXform = require('../base-xform');

//   <t xml:space="preserve"> is </t>

class TextXform extends BaseXform {
  get tag() {
    return 't';
  }

  render(xmlStream, model) {
    xmlStream.openNode('t');
    if (/^\s|\s$/.test(model)) {
      xmlStream.addAttribute('xml:space', 'preserve');
    }
    xmlStream.writeText(model);
    xmlStream.closeNode();
  }

  get model() {
    return this._text.join('').replace(/_x([0-9A-F]{4})_/g, ($0, $1) => String.fromCharCode(parseInt($1, 16)));
  }

  parseOpen(node) {
    switch (node.name) {
      case 't':
        this._text = [];
        return true;
      default:
        return false;
    }
  }

  parseText(text) {
    this._text.push(text);
  }

  parseClose() {
    return false;
  }
}

module.exports = TextXform;
<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict';

/* eslint-disable no-console */
const exec = require('child_process').exec;
const fs = require('fs');
const path = require('path');
const temp = require('temp');
const version = require('../../package.json').version;

const documentationPath = path.join(__dirname, '../../docs/documentation');
const outputPath = temp.mkdirSync('angular-cli-docs');

function execute(command) {
  return new Promise((resolve, reject) => {
    exec(command, (error, stdout) => {
      if(error) {
        reject(error);
      }
      resolve(stdout.trim())
    });
  });
}

function readFiles(directory, filelist) {
  if(directory[directory.length - 1] != '/') {
    directory = directory.concat('/');
  }

  const files = fs.readdirSync(directory);
  filelist = filelist || [];
  files.forEach((file) => {
    if (fs.statSync(directory + file).isDirectory()) {
      filelist = readFiles(directory + file + '/', filelist);
    } else {
      const originalPath = directory + file;
      const newPath = path.join(outputPath, originalPath
        .replace(documentationPath + '/', '')
        .replace('/', '-'));

      filelist.push({ originalPath, newPath });
    }
  });
  return filelist;
}

function copyFile(from, to, linksToReplace) {
  from = path.relative(process.cwd(), from);
  to = path.relative(process.cwd(), to);
  const replaceHyphen = new RegExp('-', 'gi');
  return new Promise((resolve, reject) => {
    fs.readFile(from, (error, data) => {
      if (error) {
        reject(error);
      }
      let fileData = data.toString();
      linksToReplace.forEach((link) => {
        const str = '\\(' + link.oldName.replace(replaceHyphen, '\\-') + '\\)';
        const r = new RegExp(str, 'gi');
        fileData = fileData.replace(r, link.newName);
      });
      fs.writeFile(to, fileData, (error2) => {
        if (error2) {
          reject(error2);
        }
        resolve();
      })
    })
  });
}

function createFiles() {
  const files = readFiles(documentationPath) || [];
  const linksToReplace = checkNameLinks(files);
  const copies = files.map(({ originalPath, newPath }) => {
    return copyFile(originalPath, newPath, linksToReplace)
  });
  return Promise.all(copies);
}

function checkNameLinks(files) {
  return files.reduce((pValue, cValue) => {
    const oldName = cValue.originalPath.split('/').slice(-1).pop().replace('.md', '');
    const newName = '(' + cValue.newPath.split('/').slice(-1).pop().replace('.md', '') + ')';
    if (oldName !== newName) {
      pValue.push({
        oldName,
        newName
      });
    }
    return pValue;
  }, []);
}

Promise.resolve()
  .then(() => console.log(`Documentation Path: ${documentationPath}`))
  .then(() => console.log(`Wiki path: ${outputPath}`))
  .then(() => console.log('Cloning...'))
  .then(() => execute(`git clone "https://github.com/angular/angular-cli.wiki" "${outputPath}"`))
  .then(() => console.log('Copying Files...'))
  .then(() => createFiles())
  .then(() => process.chdir(outputPath))
  .then(() => console.log('Committing...'))
  .then(() => execute('git add .'))
  .then(() => execute(`git commit -m "${version}"`))
  .then(() => execute('git push'))
  .then(() => console.log('Done...'))
  .catch(err => console.error(`Error:\n${err.message}`));
<commit_msg>build: fix docs publish on windows (#5005)<commit_after>#!/usr/bin/env node
'use strict';

/* eslint-disable no-console */
const exec = require('child_process').exec;
const fs = require('fs');
const path = require('path');
const temp = require('temp');
const version = require('../../package.json').version;

const documentationPath = path.join(__dirname, '../../docs/documentation');
const outputPath = temp.mkdirSync('angular-cli-docs');

function execute(command) {
  return new Promise((resolve, reject) => {
    exec(command, (error, stdout) => {
      if(error) {
        reject(error);
      }
      resolve(stdout.trim())
    });
  });
}

function readFiles(directory, filelist) {
  if(directory[directory.length - 1] != `${path.sep}`) {
    directory = directory.concat(`${path.sep}`);
  }

  const files = fs.readdirSync(directory);
  filelist = filelist || [];
  files.forEach((file) => {
    if (fs.statSync(directory + file).isDirectory()) {
      filelist = readFiles(directory + file + `${path.sep}`, filelist);
    } else {
      const originalPath = directory + file;
      const newPath = path.join(outputPath, originalPath
        .replace(documentationPath + `${path.sep}`, '')
        .replace(`${path.sep}`, '-'));

      filelist.push({ originalPath, newPath });
    }
  });
  return filelist;
}

function copyFile(from, to, linksToReplace) {
  from = path.relative(process.cwd(), from);
  to = path.relative(process.cwd(), to);
  const replaceHyphen = new RegExp('-', 'gi');
  return new Promise((resolve, reject) => {
    fs.readFile(from, (error, data) => {
      if (error) {
        reject(error);
      }
      let fileData = data.toString();
      linksToReplace.forEach((link) => {
        const str = '\\(' + link.oldName.replace(replaceHyphen, '\\-') + '\\)';
        const r = new RegExp(str, 'gi');
        fileData = fileData.replace(r, link.newName);
      });
      fs.writeFile(to, fileData, (error2) => {
        if (error2) {
          reject(error2);
        }
        resolve();
      })
    })
  });
}

function createFiles() {
  const files = readFiles(documentationPath) || [];
  const linksToReplace = checkNameLinks(files);
  const copies = files.map(({ originalPath, newPath }) => {
    return copyFile(originalPath, newPath, linksToReplace)
  });
  return Promise.all(copies);
}

function checkNameLinks(files) {
  return files.reduce((pValue, cValue) => {
    const oldName = cValue.originalPath
        .replace(documentationPath + `${path.sep}`, '')
        .replace('.md', '')
        .replace(`${path.sep}`, '/')
    const newName = '(' + cValue.newPath.split(`${path.sep}`).slice(-1).pop().replace('.md', '') + ')';
    if (oldName !== newName) {
      pValue.push({
        oldName,
        newName
      });
    }
    return pValue;
  }, []);
}

Promise.resolve()
  .then(() => console.log(`Documentation Path: ${documentationPath}`))
  .then(() => console.log(`Wiki path: ${outputPath}`))
  .then(() => console.log('Cloning...'))
  .then(() => execute(`git clone "https://github.com/angular/angular-cli.wiki" "${outputPath}"`))
  .then(() => console.log('Copying Files...'))
  .then(() => createFiles())
  .then(() => process.chdir(outputPath))
  .then(() => console.log('Committing...'))
  .then(() => execute('git add .'))
  .then(() => execute(`git commit -m "${version}"`))
  .then(() => execute('git push'))
  .then(() => console.log('Done...'))
  .catch(err => console.error(`Error:\n${err.message}`));
<|endoftext|>


<commit_before>var storedArticleUtils = require("../articles/storedArticleUtils.js");

function propagateError(err) {
    return Promise.reject(err);
}

function getErrorLogger(logId) {
    return function (err) {
        console.log(logId, "Error:", err);
    };
}

if (process.argv.length < 3) {
    console.error("Please provide a username");
    process.exit(1);
}

var username = process.argv[2];

storedArticleUtils.getDB()
    .then(function (db) {
        var collection = db.collection('accessible-articles');

        var results = collection.aggregate([
            {
                $match: {
                    "_meta.username": username
                }
            }, {
                $limit: 1000
            }, {
                $project: {
                    "_timestampIST": {
                        $add: ["$_timestamp", 5.5 * 60 * 60 * 1000]
                    },
                    "_timestamp": 1,
                }
            }, {
                $group: {
                    "_id": {
                        year: { $year : "$_timestampIST" },
                        month: { $month : "$_timestampIST" },
                        day: { $dayOfMonth : "$_timestampIST" }
                    },
                    "count": { $sum: 1 }
                }
            }, {
                $sort: {
                    "_id.year": -1,
                    "_id.month": -1,
                    "_id.day": -1
                }
            }
        ]);

        return results
            .toArray()
            .then(function (res) {
                db.close();
                return res;
            }, function (err) {
                db.close();
                return Promise.reject(err);
            });
    })
    .then(function(res) {
        console.log("");
        res.forEach(function (rec) {
            var date = new Date(rec._id.year, rec._id.month, rec._id.day);
            console.log(date.toDateString(), "\t", rec.count);
        });
    });
<commit_msg>Fix month offset in userProgress.js<commit_after>var storedArticleUtils = require("../articles/storedArticleUtils.js");

function propagateError(err) {
    return Promise.reject(err);
}

function getErrorLogger(logId) {
    return function (err) {
        console.log(logId, "Error:", err);
    };
}

if (process.argv.length < 3) {
    console.error("Please provide a username");
    process.exit(1);
}

var username = process.argv[2];

storedArticleUtils.getDB()
    .then(function (db) {
        var collection = db.collection('accessible-articles');

        var results = collection.aggregate([
            {
                $match: {
                    "_meta.username": username
                }
            }, {
                $limit: 1000
            }, {
                $project: {
                    "_timestampIST": {
                        $add: ["$_timestamp", 5.5 * 60 * 60 * 1000]
                    },
                    "_timestamp": 1,
                }
            }, {
                $group: {
                    "_id": {
                        year: { $year : "$_timestampIST" },
                        month: { $month : "$_timestampIST" },
                        day: { $dayOfMonth : "$_timestampIST" }
                    },
                    "count": { $sum: 1 }
                }
            }, {
                $sort: {
                    "_id.year": -1,
                    "_id.month": -1,
                    "_id.day": -1
                }
            }
        ]);

        return results
            .toArray()
            .then(function (res) {
                db.close();
                return res;
            }, function (err) {
                db.close();
                return Promise.reject(err);
            });
    })
    .then(function(res) {
        console.log("");
        res.forEach(function (rec) {
            var date = new Date(rec._id.year, rec._id.month - 1, rec._id.day);
            console.log(date.toDateString(), "\t", rec.count);
        });
    });
<|endoftext|>


<commit_before>/*
Kuaray Server script v 0.1

http://kuaray.org

   Copyright 2016 Cleuton Sampaio de Melo Junior.

   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 Client = require('../kuarayawsclient/awsClient');
var http = require('http');
var Kuaraymeasure = require('../kuarayawsclient/kuaraymeasure');

var client = new Client();
var lastMeasure = initMeasure();
var stats = {};
var gotTemp = false;
var gotHum = false;

var rpio = require('rpio');
var sleep = require('sleep');
var RaspiSensors = require('raspi-sensors');

var sendBuffer = new Buffer([0x01, (8 + 0 << 4), 0x01]);
var receiveBuffer = new Buffer(sendBuffer.length);

var httpServer = http.createServer(
    function(request,response) {
        response.write(JSON.stringify(stats));
        response.end();
    }
);

var DHT22 = new RaspiSensors.Sensor({
    type: "DHT22",
    pin: 0x7
});

function initMeasure() {
    // Temos que alterar isso depois, quando estivermos usando AWS:
    var obj = new Kuaraymeasure("Kuaray01",
    new Date(), null, null, null, 0,0);
    return obj;
}

var sendToBackend = function(lastMeasure) {

}

var callback = function(err, data) {
    if(err) {
        console.error("An error occured!");
        console.error(err.cause);
		rpio.spiEnd();
        return;
    }
    getData(data);
    // Primeiro vem a temperatura, podemos ver a qualidade do ar em separado,
    // depois vem a umidade. Só depois de termos as 3 medidas é que
    // podemos calcular a média
    if(lastMeasure.temperature != null
       && lastMeasure.humidity != null
       && lastMeasure.quality != null) {
           lastMeasure.date = new Date();
           sendToBackend(lastMeasure);
           stats = lastMeasure;
           lastMeasure = initMeasure();
    }
    if(data.type == "Humididy") {
        lastMeasure.humidity = value;
    }
    else if(data.type == "Temperature") {
        lastMeasure.temperature = value;
    }
    if(data.quality != "undefined" && data.quality != null) {
        lastMeasure.quality = data.quality;
    }

};

var startServices = function() {
    rpio.spiBegin();
    DHT22.fetchInterval(callback,global.config.measureIntervalSeconds);
}

function getData(data) {
    rpio.spiTransfer(sendBuffer, receiveBuffer, sendBuffer.length);
    var junk = receiveBuffer[0],
            MSB = receiveBuffer[1],
            LSB = receiveBuffer[2];
    var value = ((MSB & 3) << 8) + LSB;
    if(value != null && value != 0) {
        data.quality = value;
    }
}

// msg = Kuaraymeasure
var sendMsg = function(msg) {
    client.send(msg);
}

client.start().then(
    function() {
        startServices();
    },
    function(error) {
        console.log('ERROR1: ' + error.message);
    }
);

httpServer.listen(3000, function(){
    console.log("Kuaray server listening on 3000");
});

<commit_msg>Finishing new server<commit_after>/*
Kuaray Server script v 0.1

http://kuaray.org

   Copyright 2016 Cleuton Sampaio de Melo Junior.

   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 Client = require('../kuarayawsclient/awsClient');
var http = require('http');
var Kuaraymeasure = require('../kuarayawsclient/kuaraymeasure');

var client = new Client();
var lastMeasure = initMeasure();
var stats = {};
var gotTemp = false;
var gotHum = false;

var rpio = require('rpio');
var sleep = require('sleep');
var RaspiSensors = require('raspi-sensors');

var sendBuffer = new Buffer([0x01, (8 + 0 << 4), 0x01]);
var receiveBuffer = new Buffer(sendBuffer.length);

var httpServer = http.createServer(
    function(request,response) {
        response.write(JSON.stringify(stats));
        response.end();
    }
);

var DHT22 = new RaspiSensors.Sensor({
    type: "DHT22",
    pin: 0x7
});

function initMeasure() {
    // Temos que alterar isso depois, quando estivermos usando AWS:
    var obj = new Kuaraymeasure("Kuaray01",
    new Date(), null, null, null, 0,0);
    return obj;
}

var sendToBackend = function(lastMeasure) {

}

var callback = function(err, data) {
console.log("#1 callback " + JSON.stringify(data));
    if(err) {
        console.error("An error occured!");
        console.error(err.cause);
		rpio.spiEnd();
        return;
    }
    getData(data);
    // Primeiro vem a temperatura, podemos ver a qualidade do ar em separado,
    // depois vem a umidade. Só depois de termos as 3 medidas é que
    // podemos calcular a média

console.log("#2 callback " + JSON.stringify(data));

    if(lastMeasure.temperature != null
       && lastMeasure.humidity != null
       && lastMeasure.quality != null) {
           lastMeasure.date = new Date();
           sendToBackend(lastMeasure);
           stats = lastMeasure;
           lastMeasure = initMeasure();
    }
    if(data.type == "Humididy") {
        lastMeasure.humidity = value;
console.log("#3 callback " + JSON.stringify(lastMeasure));

    }
    else if(data.type == "Temperature") {
        lastMeasure.temperature = value;
console.log("#4 callback " + JSON.stringify(lastMeasure));
    }
    if(data.quality != "undefined" && data.quality != null) {
        lastMeasure.quality = data.quality;
console.log("#5 callback " + JSON.stringify(lastMeasure));

    }

};

var startServices = function() {
    rpio.spiBegin();
    DHT22.fetchInterval(callback,global.config.measureIntervalSeconds);
}

function getData(data) {
    rpio.spiTransfer(sendBuffer, receiveBuffer, sendBuffer.length);
    var junk = receiveBuffer[0],
            MSB = receiveBuffer[1],
            LSB = receiveBuffer[2];
    var value = ((MSB & 3) << 8) + LSB;
    if(value != null && value != 0) {
        data.quality = value;
    }
}

// msg = Kuaraymeasure
var sendMsg = function(msg) {
    client.send(msg);
}

client.start().then(
    function() {
        startServices();
    },
    function(error) {
        console.log('ERROR1: ' + error.message);
    }
);

httpServer.listen(3000, function(){
    console.log("Kuaray server listening on 3000");
});

<|endoftext|>


<commit_before>// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

// Yacas mode copyright (c) 2015 by Grzegorz Mazur
// Loosely based on mathematica mode by Calin Barbat

(function(mod) {
  if (typeof exports == "object" && typeof module == "object") // CommonJS
    mod(require("../../lib/codemirror"));
  else if (typeof define == "function" && define.amd) // AMD
    define(["../../lib/codemirror"], mod);
  else // Plain browser env
    mod(CodeMirror);
})(function(CodeMirror) {
"use strict";

CodeMirror.defineMode('yacas', function(_config, _parserConfig) {

  function words(str) {
    var obj = {}, words = str.split(" ");
    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
    return obj;
  }

  var bodiedOps = words("Assert BackQuote D Defun Deriv For ForEach FromFile " +
                        "FromString Function Integrate InverseTaylor Limit " +
                        "LocalSymbols Macro MacroRule MacroRulePattern " +
                        "NIntegrate Rule RulePattern Subst TD TExplicitSum " +
                        "TSum Taylor Taylor1 Taylor2 Taylor3 ToFile " +
                        "ToStdout ToString TraceRule Until While");

  // patterns
  var pFloatForm  = "(?:(?:\\.\\d+|\\d+\\.\\d*|\\d+)(?:[eE][+-]?\\d+)?)";
  var pIdentifier = "(?:[a-zA-Z\\$'][a-zA-Z0-9\\$']*)";

  // regular expressions
  var reFloatForm    = new RegExp(pFloatForm);
  var reIdentifier   = new RegExp(pIdentifier);
  var rePattern      = new RegExp(pIdentifier + "?_" + pIdentifier);
  var reFunctionLike = new RegExp(pIdentifier + "\\s*\\(");

  function tokenBase(stream, state) {
    var ch;

    // get next character
    ch = stream.next();

    // string
    if (ch === '"') {
      state.tokenize = tokenString;
      return state.tokenize(stream, state);
    }

    // comment
    if (ch === '/') {
      if (stream.eat('*')) {
        state.tokenize = tokenComment;
        return state.tokenize(stream, state);
      }
      if (stream.eat("/")) {
        stream.skipToEnd();
        return "comment";
      }
    }

    // go back one character
    stream.backUp(1);

    // update scope info
    var m = stream.match(/^(\w+)\s*\(/, false);
    if (m !== null && bodiedOps.hasOwnProperty(m[1]))
      state.scopes.push('bodied');

    var scope = currentScope(state);

    if (scope === 'bodied' && ch === '[')
      state.scopes.pop();

    if (ch === '[' || ch === '{' || ch === '(')
      state.scopes.push(ch);

    scope = currentScope(state);

    if (scope === '[' && ch === ']' ||
        scope === '{' && ch === '}' ||
        scope === '(' && ch === ')')
      state.scopes.pop();

    if (ch === ';') {
      while (scope === 'bodied') {
        state.scopes.pop();
        scope = currentScope(state);
      }
    }

    // look for ordered rules
    if (stream.match(/\d+ *#/, true, false)) {
      return 'qualifier';
    }

    // look for numbers
    if (stream.match(reFloatForm, true, false)) {
      return 'number';
    }

    // look for placeholders
    if (stream.match(rePattern, true, false)) {
      return 'variable-3';
    }

    // match all braces separately
    if (stream.match(/(?:\[|\]|{|}|\(|\))/, true, false)) {
      return 'bracket';
    }

    // literals looking like function calls
    if (stream.match(reFunctionLike, true, false)) {
      stream.backUp(1);
      return 'variable';
    }

    // all other identifiers
    if (stream.match(reIdentifier, true, false)) {
      return 'variable-2';
    }

    // operators; note that operators like @@ or /; are matched separately for each symbol.
    if (stream.match(/(?:\\|\+|\-|\*|\/|,|;|\.|:|@|~|=|>|<|&|\||_|`|'|\^|\?|!|%)/, true, false)) {
      return 'operator';
    }

    // everything else is an error
    return 'error';
  }

  function tokenString(stream, state) {
    var next, end = false, escaped = false;
    while ((next = stream.next()) != null) {
      if (next === '"' && !escaped) {
        end = true;
        break;
      }
      escaped = !escaped && next === '\\';
    }
    if (end && !escaped) {
      state.tokenize = tokenBase;
    }
    return 'string';
  };

  function tokenComment(stream, state) {
    var prev, next;
    while((next = stream.next()) != null) {
      if (prev === '*' && next === '/') {
        state.tokenize = tokenBase;
        break;
      }
      prev = next;
    }
    return 'comment';
  }

  function currentScope(state) {
    var scope = null;
    if (state.scopes.length > 0)
      scope = state.scopes[state.scopes.length - 1];
    return scope;
  }

  return {
    startState: function() {
      return {
        tokenize: tokenBase,
        scopes: []
      };
    },
    token: function(stream, state) {
      if (stream.eatSpace()) return null;
      return state.tokenize(stream, state);
    },
    indent: function(state, textAfter) {
      if (state.tokenize !== tokenBase && state.tokenize !== null)
        return CodeMirror.Pass;

      var delta = 0;
      if (textAfter === ']' || textAfter === '];' ||
          textAfter === '}' || textAfter === '};' ||
          textAfter === ');')
        delta = -1;

      return (state.scopes.length + delta) * _config.indentUnit;
    },
    electricChars: "{}[]();",
    blockCommentStart: "/*",
    blockCommentEnd: "*/",
    lineComment: "//"
  };
});

CodeMirror.defineMIME('text/x-yacas', {
  name: 'yacas'
});

});
<commit_msg>[yacas mode] Tokenize '#' as an operator<commit_after>// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

// Yacas mode copyright (c) 2015 by Grzegorz Mazur
// Loosely based on mathematica mode by Calin Barbat

(function(mod) {
  if (typeof exports == "object" && typeof module == "object") // CommonJS
    mod(require("../../lib/codemirror"));
  else if (typeof define == "function" && define.amd) // AMD
    define(["../../lib/codemirror"], mod);
  else // Plain browser env
    mod(CodeMirror);
})(function(CodeMirror) {
"use strict";

CodeMirror.defineMode('yacas', function(_config, _parserConfig) {

  function words(str) {
    var obj = {}, words = str.split(" ");
    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
    return obj;
  }

  var bodiedOps = words("Assert BackQuote D Defun Deriv For ForEach FromFile " +
                        "FromString Function Integrate InverseTaylor Limit " +
                        "LocalSymbols Macro MacroRule MacroRulePattern " +
                        "NIntegrate Rule RulePattern Subst TD TExplicitSum " +
                        "TSum Taylor Taylor1 Taylor2 Taylor3 ToFile " +
                        "ToStdout ToString TraceRule Until While");

  // patterns
  var pFloatForm  = "(?:(?:\\.\\d+|\\d+\\.\\d*|\\d+)(?:[eE][+-]?\\d+)?)";
  var pIdentifier = "(?:[a-zA-Z\\$'][a-zA-Z0-9\\$']*)";

  // regular expressions
  var reFloatForm    = new RegExp(pFloatForm);
  var reIdentifier   = new RegExp(pIdentifier);
  var rePattern      = new RegExp(pIdentifier + "?_" + pIdentifier);
  var reFunctionLike = new RegExp(pIdentifier + "\\s*\\(");

  function tokenBase(stream, state) {
    var ch;

    // get next character
    ch = stream.next();

    // string
    if (ch === '"') {
      state.tokenize = tokenString;
      return state.tokenize(stream, state);
    }

    // comment
    if (ch === '/') {
      if (stream.eat('*')) {
        state.tokenize = tokenComment;
        return state.tokenize(stream, state);
      }
      if (stream.eat("/")) {
        stream.skipToEnd();
        return "comment";
      }
    }

    // go back one character
    stream.backUp(1);

    // update scope info
    var m = stream.match(/^(\w+)\s*\(/, false);
    if (m !== null && bodiedOps.hasOwnProperty(m[1]))
      state.scopes.push('bodied');

    var scope = currentScope(state);

    if (scope === 'bodied' && ch === '[')
      state.scopes.pop();

    if (ch === '[' || ch === '{' || ch === '(')
      state.scopes.push(ch);

    scope = currentScope(state);

    if (scope === '[' && ch === ']' ||
        scope === '{' && ch === '}' ||
        scope === '(' && ch === ')')
      state.scopes.pop();

    if (ch === ';') {
      while (scope === 'bodied') {
        state.scopes.pop();
        scope = currentScope(state);
      }
    }

    // look for ordered rules
    if (stream.match(/\d+ *#/, true, false)) {
      return 'qualifier';
    }

    // look for numbers
    if (stream.match(reFloatForm, true, false)) {
      return 'number';
    }

    // look for placeholders
    if (stream.match(rePattern, true, false)) {
      return 'variable-3';
    }

    // match all braces separately
    if (stream.match(/(?:\[|\]|{|}|\(|\))/, true, false)) {
      return 'bracket';
    }

    // literals looking like function calls
    if (stream.match(reFunctionLike, true, false)) {
      stream.backUp(1);
      return 'variable';
    }

    // all other identifiers
    if (stream.match(reIdentifier, true, false)) {
      return 'variable-2';
    }

    // operators; note that operators like @@ or /; are matched separately for each symbol.
    if (stream.match(/(?:\\|\+|\-|\*|\/|,|;|\.|:|@|~|=|>|<|&|\||_|`|'|\^|\?|!|%|#)/, true, false)) {
      return 'operator';
    }

    // everything else is an error
    return 'error';
  }

  function tokenString(stream, state) {
    var next, end = false, escaped = false;
    while ((next = stream.next()) != null) {
      if (next === '"' && !escaped) {
        end = true;
        break;
      }
      escaped = !escaped && next === '\\';
    }
    if (end && !escaped) {
      state.tokenize = tokenBase;
    }
    return 'string';
  };

  function tokenComment(stream, state) {
    var prev, next;
    while((next = stream.next()) != null) {
      if (prev === '*' && next === '/') {
        state.tokenize = tokenBase;
        break;
      }
      prev = next;
    }
    return 'comment';
  }

  function currentScope(state) {
    var scope = null;
    if (state.scopes.length > 0)
      scope = state.scopes[state.scopes.length - 1];
    return scope;
  }

  return {
    startState: function() {
      return {
        tokenize: tokenBase,
        scopes: []
      };
    },
    token: function(stream, state) {
      if (stream.eatSpace()) return null;
      return state.tokenize(stream, state);
    },
    indent: function(state, textAfter) {
      if (state.tokenize !== tokenBase && state.tokenize !== null)
        return CodeMirror.Pass;

      var delta = 0;
      if (textAfter === ']' || textAfter === '];' ||
          textAfter === '}' || textAfter === '};' ||
          textAfter === ');')
        delta = -1;

      return (state.scopes.length + delta) * _config.indentUnit;
    },
    electricChars: "{}[]();",
    blockCommentStart: "/*",
    blockCommentEnd: "*/",
    lineComment: "//"
  };
});

CodeMirror.defineMIME('text/x-yacas', {
  name: 'yacas'
});

});
<|endoftext|>


<commit_before>import { $, $$, toKey, getLanguageFromHash } from "~/utils/util"

const stringsToTranslate = [
  '.myself .about',
]

let translate = function(){
  I18n.locale = getLanguageFromHash()

  stringsToTranslate.forEach((queryElement)=>{
    let element        = $(queryElement)
    let keyTranslation = toKey(queryElement)

    element.innerHTML = I18n.t(keyTranslation)
  })
}

let linksToTranslate = $$(".myself a")

Array.prototype.forEach.call(linksToTranslate, (element)=>{
  element.onclick = function(evento){
    translate()
  }
})

translate()
<commit_msg>Fix lazy hash load<commit_after>import { $, $$, toKey, getLanguageFromHash } from "~/utils/util"

const stringsToTranslate = [
  '.myself .about',
]

let translate = function(language=getLanguageFromHash()){
  I18n.locale = language

  stringsToTranslate.forEach((queryElement)=>{
    let element        = $(queryElement)
    let keyTranslation = toKey(queryElement)

    element.innerHTML = I18n.t(keyTranslation)
  })
}

let linksToTranslate = $$(".myself a")

Array.prototype.forEach.call(linksToTranslate, (element)=>{
  element.onclick = function(event){
    let language = event.target.hash.substring(1)
    translate(language)
  }
})

translate()
<|endoftext|>


<commit_before>const mongoose = require('mongoose');
mongoose.Promise = require('bluebird');

const TeamEventSchema = new mongoose.Schema({
    eventId: { type: String, required: true },
    teamId: { type: String, required: true },
    programId: { type: String, required: true },
    registeredOn: {type: Date, required: true }
});

if (!mongoose.models.TeamEvent) {
    mongoose.model('TeamEvent', TeamEventSchema);
}

module.exports = TeamEventSchema;<commit_msg>adding team number<commit_after>const mongoose = require('mongoose');
mongoose.Promise = require('bluebird');

const TeamEventSchema = new mongoose.Schema({
    eventId: { type: String, required: true },
    teamId: { type: String, required: true },
    programId: { type: String, required: true },
    registeredOn: {type: Date, required: true },
    teamNumber: {type:String}
});

if (!mongoose.models.TeamEvent) {
    mongoose.model('TeamEvent', TeamEventSchema);
}

module.exports = TeamEventSchema;<|endoftext|>


<commit_before>// Universal Subtitles, universalsubtitles.org
//
// Copyright (C) 2012 Participatory Culture Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see
// http://www.gnu.org/licenses/agpl-3.0.html.

goog.provide("unisubs.player.BlipTvVideoPlayer");

/**
 * @constructor
 * @param {unisubs.player.BlipTvVideoSource} videoSource
 * @param {boolean=} opt_forDialog
 */
unisubs.player.BlipTvVideoPlayer = function(videoSource, opt_forDialog){
    unisubs.player.AbstractVideoPlayer.call(this, videoSource);

    this.videoSource_ = videoSource;
    this.forDialog_ = !!opt_forDialog;

    this.player_ = null;
    this.playerAPIID_ = [videoSource.getUUID(),
                         '' + new Date().getTime()].join('');

    this.playerElemID_ = videoSource.getUUID() + "_bliptvplayer";

    this.commands_ = [];
    this.playerSize_ = null;
    this.player_ = null;
    this.volume_ = 0.5;
    this.currentTime_ = 0;
    this.ended = false;

    this.swfEmbedded_ = false;
    this.delayer_ = null;

    this.isPlaying_ = false;
}

goog.inherits(unisubs.player.BlipTvVideoPlayer, unisubs.player.AbstractVideoPlayer);

unisubs.player.BlipTvVideoPlayer.DIALOG_SIZE = new goog.math.Size(400, 400);

unisubs.player.BlipTvVideoPlayer.prototype.logger_ =
    goog.debug.Logger.getLogger('unisubs.player.BlipTvVideoPlayer');

unisubs.player.BlipTvVideoPlayer.prototype.createDom = function() {
    // FIXME: this is copied directly from youtube video player.

    this.setElementInternal(this.getDomHelper().createElement('span'));
    goog.dom.classes.add(this.getElement(), 'unisubs-videoplayer');

    var sizeFromConfig = this.sizeFromConfig_();
    if (!this.forDialog_ && sizeFromConfig){
        this.playerSize_ = sizeFromConfig;
    } else {
        this.playerSize_ = this.forDialog_ ?
        unisubs.player.AbstractVideoPlayer.DIALOG_SIZE :
        unisubs.player.AbstractVideoPlayer.DEFAULT_SIZE;
    }

};

unisubs.player.BlipTvVideoPlayer.prototype.enterDocument = function(){
    unisubs.player.BlipTvVideoPlayer.superClass_.enterDocument.call(this);

    if(this.swfEmbedded_){
        return;
    }

    var that = this;

    var jsonp = new goog.net.Jsonp(this.videoSource_.videoURL_ + "?skin=json");
    jsonp.send({}, function(response){
        var post = response[0]['Post'];
        that.duration_ = parseInt(post['media']['duration']);
        that.embedSWF_(post['embedUrl']);
    })

}

unisubs.player.BlipTvVideoPlayer.prototype.embedSWF_ = function(embedUrl){
    if(this.swfEmbedded_){
        return;
    }

    this.swfEmbedded_ = true;
    var videoDiv = this.getDomHelper().createDom("div");
    videoDiv.id = unisubs.randomString();
    this.getElement().appendChild(videoDiv);
    var params = {'allowScriptAccess': 'always', 'enablejs': 'true', "wmode": "opaque"};
    var atts = { 'id': this.playerElemID_,
                 'style': unisubs.style.setSizeInString(
                  '', this.playerSize_) };

    var chromeless = this.forDialog_ ? "true" : "false";
    var url = embedUrl + "?chromeless=" + chromeless + "&captionson=false&backcolor=#00000"

    var callback = goog.bind(this.swfReady_, this);

    window["swfobject"]["embedSWF"](
        url,
        videoDiv.id, this.playerSize_.width + '',
        this.playerSize_.height + '', "8",
        null, null, params, atts, callback);
}

unisubs.player.BlipTvVideoPlayer.prototype.isPausedInternal = function(){
    return !this.isPlaying_;
}

unisubs.player.BlipTvVideoPlayer.prototype.isPlayingInternal = function(){
    return this.isPlaying_;
}

unisubs.player.BlipTvVideoPlayer.prototype.videoEndedInternal = function(){
    return this.ended_;
}

unisubs.player.BlipTvVideoPlayer.prototype.playInternal = function(){
    if(this.player_){
        this.player_['sendEvent']("play");
    } else {
        this.commands_.push(goog.bind(this.playInternal, this));
    }
}

unisubs.player.BlipTvVideoPlayer.prototype.pauseInternal = function(){
    if(this.player_){
        this.player_['sendEvent']("pause");
    } else {
        this.commands_.push(goog.bind(this.pauseInternal, this));
    }
}

unisubs.player.BlipTvVideoPlayer.prototype.stopLoadingInternal = function(){
    this.pause();
}

unisubs.player.BlipTvVideoPlayer.prototype.resumeLoadingInternal = function(playheadTime){
    this.play();
}

unisubs.player.BlipTvVideoPlayer.prototype.getPlayheadTimeInternal = function(){
    return this.currentTime_;
}

unisubs.player.BlipTvVideoPlayer.prototype.setPlayheadTime = function(playheadTime){
    if (this.player_) {
        this.player_['sendEvent']("seek", playheadTime);
        this.sendTimeUpdateInternal();
    } else {
        this.commands_.push(goog.bind(this.setPlayheadTime, this, playheadTime));
    }

}

unisubs.player.BlipTvVideoPlayer.prototype.getDuration = function(){
    return this.duration_;
}

//unisubs.player.BlipTvVideoPlayer.prototype.getBufferedLength = function(){
    //return this.player_ ? 1 : 0;
//}

//unisubs.player.BlipTvVideoPlayer.prototype.getBufferedStart = function(index){
    //return 0;
//}

//unisubs.player.BlipTvVideoPlayer.prototype.getBufferedEnd = function(index){
    //return this.currentTime_ * this.getDuration();
//}

unisubs.player.BlipTvVideoPlayer.prototype.getVolume = function(index){
    return this.volume_;
}

unisubs.player.BlipTvVideoPlayer.prototype.setVolume = function(volume){
    if(this.player_){
        this.player_['sendEvent']("volume", volume);
        this.volume_ = volume;
    } else {
        this.commands_.push(goog.bind(this.setVolume, this));
    }
}

unisubs.player.BlipTvVideoPlayer.prototype.getVideoSize = function(index){
    return this.playerSize_;
}

unisubs.player.BlipTvVideoPlayer.prototype.swfReady_ = function(index){
    this.player_ = goog.dom.$(this.playerElemID_);

    if(!this.player_['addJScallback']){
        this.callback_ = goog.bind(this.swfReady_, this);
        setTimeout(this.callback_, 500)
        return;
    }

    this.swfLoaded_ = true;

    goog.array.forEach(this.commands_, function(cmd) { cmd(); });
    this.commands_ = [];

    var that = this;
    var et = unisubs.player.AbstractVideoPlayer.EventType;
    var randomString = unisubs.randomString();

    var onPlayerStateChange = "onPlayerState" + randomString;

    window[onPlayerStateChange] = function(newState){
        that.logger_.info("new state is " + newState);
        switch(newState) {
            case 'playing':
                that.isPlaying_ = true;
                that.dispatchEvent(et.PLAY);
                break;
            case "paused":
                that.isPlaying_ = false;
                that.dispatchEvent(et.PAUSE);
                break;
        }
    };

    this.player_['addJScallback']("player_state_change", "window." + onPlayerStateChange);

    var onCurrentTimeChange = "onCurrentTimeCha" + randomString;

    window[onCurrentTimeChange] = function(time){
        that.currentTime_ = time;
        that.sendTimeUpdateInternal();
    };

    this.player_['addJScallback']("current_time_change", "window." + onCurrentTimeChange);

    var onVideoEnded = "onVideoEnde" + randomString;

    window[onVideoEnded] = function(){
        that.ended_ = true;
        that.dispatchEndedEvent();
    };
    this.player_['addJScallback']("complete", "window." + onVideoEnded);

    this.player_['sendEvent']("volume", this.volume_);
}

unisubs.player.BlipTvVideoPlayer.prototype.sizeFromConfig_ = function() {
    // FIXME: duplicates same method in youtube player
    var config = this.videoSource_.getVideoConfig();
    if (config && config['width'] && config['height'])
        return new goog.math.Size(
            parseInt(config['width']), parseInt(config['height']));
    else
        return null;
};
<commit_msg>comments comments<commit_after>// Universal Subtitles, universalsubtitles.org
//
// Copyright (C) 2012 Participatory Culture Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see
// http://www.gnu.org/licenses/agpl-3.0.html.

goog.provide("unisubs.player.BlipTvVideoPlayer");

/**
 * @constructor
 * @param {unisubs.player.BlipTvVideoSource} videoSource
 * @param {boolean=} opt_forDialog
 */
unisubs.player.BlipTvVideoPlayer = function(videoSource, opt_forDialog){
    unisubs.player.AbstractVideoPlayer.call(this, videoSource);

    this.videoSource_ = videoSource;
    this.forDialog_ = !!opt_forDialog;

    this.player_ = null;
    this.playerAPIID_ = [videoSource.getUUID(),
                         '' + new Date().getTime()].join('');

    this.playerElemID_ = videoSource.getUUID() + "_bliptvplayer";

    this.commands_ = [];
    this.playerSize_ = null;
    this.player_ = null;
    this.volume_ = 0.5;
    this.currentTime_ = 0;
    this.ended = false;

    this.swfEmbedded_ = false;
    this.delayer_ = null;

    this.isPlaying_ = false;
}

goog.inherits(unisubs.player.BlipTvVideoPlayer, unisubs.player.AbstractVideoPlayer);

unisubs.player.BlipTvVideoPlayer.prototype.logger_ =
    goog.debug.Logger.getLogger('unisubs.player.BlipTvVideoPlayer');

unisubs.player.BlipTvVideoPlayer.prototype.createDom = function() {
    // FIXME: this is copied directly from youtube video player.

    this.setElementInternal(this.getDomHelper().createElement('span'));
    goog.dom.classes.add(this.getElement(), 'unisubs-videoplayer');

    var sizeFromConfig = this.sizeFromConfig_();
    if (!this.forDialog_ && sizeFromConfig){
        this.playerSize_ = sizeFromConfig;
    } else {
        this.playerSize_ = this.forDialog_ ?
        unisubs.player.AbstractVideoPlayer.DIALOG_SIZE :
        unisubs.player.AbstractVideoPlayer.DEFAULT_SIZE;
    }

};

unisubs.player.BlipTvVideoPlayer.prototype.enterDocument = function(){
    unisubs.player.BlipTvVideoPlayer.superClass_.enterDocument.call(this);

    if(this.swfEmbedded_){
        return;
    }

    var that = this;

    // this jsonp calls is needed because we only know the real url of the
    // video and that doesn't provide any way to find the embedUrl
    // (something like http://blip.tv/play/hdljgvKTGAI).
    // We also use this call to find the duration of the video (no method
    // on the player that returns that).
    // It's not clean but it works.
    var jsonp = new goog.net.Jsonp(this.videoSource_.videoURL_ + "?skin=json");
    jsonp.send({}, function(response){
        var post = response[0]['Post'];
        that.duration_ = parseInt(post['media']['duration']);
        that.embedSWF_(post['embedUrl']);
    })

}

unisubs.player.BlipTvVideoPlayer.prototype.embedSWF_ = function(embedUrl){
    if(this.swfEmbedded_){
        return;
    }

    this.swfEmbedded_ = true;
    var videoDiv = this.getDomHelper().createDom("div");
    videoDiv.id = unisubs.randomString();
    this.getElement().appendChild(videoDiv);

    // wmode must be opaque so we can render things on top of the flash player
    var params = {'allowScriptAccess': 'always', 'enablejs': 'true', "wmode": "opaque"};

    var atts = { 'id': this.playerElemID_,
                 'style': unisubs.style.setSizeInString(
                  '', this.playerSize_) };

    var chromeless = this.forDialog_ ? "true" : "false";
    var url = embedUrl + "?chromeless=" + chromeless + "&captionson=false&backcolor=#00000"

    var callback = goog.bind(this.swfReady_, this);

    window["swfobject"]["embedSWF"](
        url,
        videoDiv.id, this.playerSize_.width + '',
        this.playerSize_.height + '', "8",
        null, null, params, atts, callback);
}

unisubs.player.BlipTvVideoPlayer.prototype.isPausedInternal = function(){
    return !this.isPlaying_;
}

unisubs.player.BlipTvVideoPlayer.prototype.isPlayingInternal = function(){
    return this.isPlaying_;
}

unisubs.player.BlipTvVideoPlayer.prototype.videoEndedInternal = function(){
    return this.ended_;
}

unisubs.player.BlipTvVideoPlayer.prototype.playInternal = function(){
    if(this.player_){
        this.player_['sendEvent']("play");
    } else {
        this.commands_.push(goog.bind(this.playInternal, this));
    }
}

unisubs.player.BlipTvVideoPlayer.prototype.pauseInternal = function(){
    if(this.player_){
        this.player_['sendEvent']("pause");
    } else {
        this.commands_.push(goog.bind(this.pauseInternal, this));
    }
}

unisubs.player.BlipTvVideoPlayer.prototype.stopLoadingInternal = function(){
    this.pause();
}

unisubs.player.BlipTvVideoPlayer.prototype.resumeLoadingInternal = function(playheadTime){
    this.play();
}

unisubs.player.BlipTvVideoPlayer.prototype.getPlayheadTimeInternal = function(){
    return this.currentTime_;
}

unisubs.player.BlipTvVideoPlayer.prototype.setPlayheadTime = function(playheadTime){
    if (this.player_) {
        this.player_['sendEvent']("seek", playheadTime);
        this.sendTimeUpdateInternal();
    } else {
        this.commands_.push(goog.bind(this.setPlayheadTime, this, playheadTime));
    }

}

unisubs.player.BlipTvVideoPlayer.prototype.getDuration = function(){
    return this.duration_;
}

// We need to implement those, but i have no idea how, since bliptv
// doesn't have a good method to know who many bytes were buffered.
//
//unisubs.player.BlipTvVideoPlayer.prototype.getBufferedLength = function(){
    //return this.player_ ? 1 : 0;
//}

//unisubs.player.BlipTvVideoPlayer.prototype.getBufferedStart = function(index){
    //return 0;
//}

//unisubs.player.BlipTvVideoPlayer.prototype.getBufferedEnd = function(index){
    //return this.currentTime_ * this.getDuration();
//}

unisubs.player.BlipTvVideoPlayer.prototype.getVolume = function(index){
    return this.volume_;
}

unisubs.player.BlipTvVideoPlayer.prototype.setVolume = function(volume){
    if(this.player_){
        this.player_['sendEvent']("volume", volume);
        this.volume_ = volume;
    } else {
        this.commands_.push(goog.bind(this.setVolume, this));
    }
}

unisubs.player.BlipTvVideoPlayer.prototype.getVideoSize = function(index){
    return this.playerSize_;
}

unisubs.player.BlipTvVideoPlayer.prototype.swfReady_ = function(index){
    this.player_ = goog.dom.$(this.playerElemID_);

    // here we need to wait until the player is ready
    // to accept callbacks. and bliptv player doesn't
    // have an "callback" to know when the player is ready
    if(!this.player_['addJScallback']){
        this.callback_ = goog.bind(this.swfReady_, this);
        setTimeout(this.callback_, 500)
        return;
    }

    this.swfLoaded_ = true;

    goog.array.forEach(this.commands_, function(cmd) { cmd(); });
    this.commands_ = [];

    var that = this;
    var et = unisubs.player.AbstractVideoPlayer.EventType;
    var randomString = unisubs.randomString();

    var onPlayerStateChange = "onPlayerState" + randomString;

    window[onPlayerStateChange] = function(newState){
        that.logger_.info("new state is " + newState);
        switch(newState) {
            case 'playing':
                that.isPlaying_ = true;
                // this is needed so the tab -> play 4s work
                that.dispatchEvent(et.PLAY);
                break;
            case "paused":
                that.isPlaying_ = false;
                that.dispatchEvent(et.PAUSE);
                break;
        }
    };

    this.player_['addJScallback']("player_state_change", "window." + onPlayerStateChange);

    var onCurrentTimeChange = "onCurrentTimeCha" + randomString;

    // FIXME this doesn't work as good as the timer method.
    // maybe we can change.
    window[onCurrentTimeChange] = function(time){
        that.currentTime_ = time;
        that.sendTimeUpdateInternal();
    };

    this.player_['addJScallback']("current_time_change", "window." + onCurrentTimeChange);

    var onVideoEnded = "onVideoEnde" + randomString;

    window[onVideoEnded] = function(){
        that.ended_ = true;
        that.dispatchEndedEvent();
    };
    this.player_['addJScallback']("complete", "window." + onVideoEnded);

    // we also don't have a method to *get* volume
    // so we set to a known value (0.5)
    this.player_['sendEvent']("volume", this.volume_);
}

unisubs.player.BlipTvVideoPlayer.prototype.sizeFromConfig_ = function() {
    // FIXME: duplicates same method in youtube player
    var config = this.videoSource_.getVideoConfig();
    if (config && config['width'] && config['height'])
        return new goog.math.Size(
            parseInt(config['width']), parseInt(config['height']));
    else
        return null;
};
<|endoftext|>