<commit_before>import React           from 'react';
import TopListChart    from './TopListChart';
import Parties         from '../constants/Parties';
import ImageUtils      from '../utils/ImageUtils';

class ResultStats extends React.Component {
    constructor(props) {
        super(props);

        this.searchStore = this.props.flux.getStore('search');

        this.state = {
            parties: [],
            people: [],
            query: ''
        };
    }

    componentDidMount() {
        this.searchStore.addListener('change', this.handleChange.bind(this));
    }

    componentWillUnmount() {
        this.searchStore.removeListener('change', this.handleChange.bind(this));
    }

    handleChange() {
        let parties = [];
        let people  = [];
        let query   = '';

        let result = this.searchStore.getLastResult();

        if (result) {
            people = result.result.people;
            parties = result.result.parties;
            query = result.query;
        }

        this.setState({
            query: query,
            parties: parties,
            people: people,
            topParties: this.topParties(parties)
        });
    }

    render() {
        return (

                {this.renderPartyStats()}

                {this.renderPeopleStats()}

        );
    }

    renderPartyStats() {
        if (this.state.parties.length) {
            return (

                        <TopListChart
                            subtitle="Partier"
                            orientation={this.props.orientation}
                            unit={this.props.unit}
                            counts={this.state.parties.sort((a, b) => Parties.order(b.key) - Parties.order(a.key))}
                        />

                        {this.renderPartyText()}

            );
        } else {
            return
;
        }
    }

    renderPeopleStats() {
        let people = this.state.people[this.props.unit] || [];

        if (people.length) {
            let topPerson = people[0];
            let num = this.props.unit === 'pct' ? `${topPerson.pct.toFixed(2)} %` : topPerson.count;
            let unitText = this.props.unit === 'pct' ? 'av sine innlegg' : 'innlegg';

            return (

                        <img
                            src={ImageUtils.personImageFor(topPerson.meta.external_id)}
                            alt={`Bilde av ${topPerson.key}`}
                            height="200"
                        />

                        <h2 className={`hdo-party-${topPerson.meta.party.toLowerCase()}`}>
                            {topPerson.key} ({topPerson.meta.party})

                                har nevnt {this.state.query} i

                                {num}

                            {unitText}

                        <TopListChart
                            subtitle="Topp 10 personer"
                            unit={this.props.unit}
                            orientation={this.props.orientation}
                            counts={people}
                            sort={true}
                        />

            );
        } else {
            return
;
        }
    }

    renderPartyText() {
        let topParty  = this.state.topParties[this.props.unit];
        let num       = this.props.unit === 'pct' ? topParty.pct.toFixed(2) + ' %' : topParty.count;
        let unitText  = this.props.unit === 'pct' ? 'av sine innlegg' : 'innlegg';

        return (

                <h2 className={`hdo-party-${topParty.key.toLowerCase()}`}>
                    {Parties.names[topParty.key]}

                        har nevnt {this.state.query} i

                        {num}

                    {unitText}

        );
    }

    topParties(parties) {
        return {
            pct: parties.slice(0).sort((a, b) => b.pct - a.pct)[0],
            count: parties.slice(0).sort((a, b) => b.count - a.count)[0]
        };
    }
}

ResultStats.propTypes = {
};

module.exports = ResultStats;<commit_msg>Hide stats when query is empty<commit_after>import React           from 'react';
import TopListChart    from './TopListChart';
import Parties         from '../constants/Parties';
import ImageUtils      from '../utils/ImageUtils';

class ResultStats extends React.Component {
    constructor(props) {
        super(props);

        this.searchStore = this.props.flux.getStore('search');

        this.state = {
            parties: [],
            people: [],
            query: ''
        };
    }

    componentDidMount() {
        this.searchStore.addListener('change', this.handleChange.bind(this));
    }

    componentWillUnmount() {
        this.searchStore.removeListener('change', this.handleChange.bind(this));
    }

    handleChange() {
        let parties = [];
        let people  = [];
        let query   = '';

        let result = this.searchStore.getLastResult();

        if (result) {
            people = result.result.people;
            parties = result.result.parties;
            query = result.query;
        }

        this.setState({
            query: query,
            parties: parties,
            people: people,
            topParties: this.topParties(parties)
        });
    }

    render() {
        if (this.state.query.length) {
            return (

                    {this.renderPartyStats()}

                    {this.renderPeopleStats()}

            );
        } else {
            return
;
        }
    }

    renderPartyStats() {
        return (

                    <TopListChart
                        subtitle="Partier"
                        orientation={this.props.orientation}
                        unit={this.props.unit}
                        counts={this.state.parties.sort((a, b) => Parties.order(b.key) - Parties.order(a.key))}
                    />

                    {this.renderPartyText()}

        );
    }

    renderPeopleStats() {
        let people = this.state.people[this.props.unit] || [];

        if (people.length) {
            let topPerson = people[0];
            let num = this.props.unit === 'pct' ? `${topPerson.pct.toFixed(2)} %` : topPerson.count;
            let unitText = this.props.unit === 'pct' ? 'av sine innlegg' : 'innlegg';

            return (

                        <img
                            src={ImageUtils.personImageFor(topPerson.meta.external_id)}
                            alt={`Bilde av ${topPerson.key}`}
                            height="200"
                        />

                        <h2 className={`hdo-party-${topPerson.meta.party.toLowerCase()}`}>
                            {topPerson.key} ({topPerson.meta.party})

                                har nevnt {this.state.query} i

                                {num}

                            {unitText}

                        <TopListChart
                            subtitle="Topp 10 personer"
                            unit={this.props.unit}
                            orientation={this.props.orientation}
                            counts={people}
                            sort={true}
                        />

            );
        } else {
            return
;
        }
    }

    renderPartyText() {
        let topParty  = this.state.topParties[this.props.unit];
        let num       = this.props.unit === 'pct' ? topParty.pct.toFixed(2) + ' %' : topParty.count;
        let unitText  = this.props.unit === 'pct' ? 'av sine innlegg' : 'innlegg';

        return (

                <h2 className={`hdo-party-${topParty.key.toLowerCase()}`}>
                    {Parties.names[topParty.key]}

                        har nevnt {this.state.query} i

                        {num}

                    {unitText}

        );
    }

    topParties(parties) {
        return {
            pct: parties.slice(0).sort((a, b) => b.pct - a.pct)[0],
            count: parties.slice(0).sort((a, b) => b.count - a.count)[0]
        };
    }
}

ResultStats.propTypes = {
};

module.exports = ResultStats;<|endoftext|>


<commit_before>/**
 * Copyright 2018-present Facebook.
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 * @format
 */

const Metro = require('../static/node_modules/metro');
const compilePlugins = require('../static/compilePlugins');
const tmp = require('tmp');
const path = require('path');
const fs = require('fs-extra');

function die(err) {
  console.error(err.stack);
  process.exit(1);
}

function compileDefaultPlugins(defaultPluginDir) {
  return compilePlugins(
    null,
    [
      path.join(__dirname, '..', 'src', 'plugins'),
      path.join(__dirname, '..', 'src', 'fb', 'plugins'),
    ],
    defaultPluginDir,
    {force: true, failSilently: false},
  )
    .then(defaultPlugins =>
      fs.writeFileSync(
        path.join(defaultPluginDir, 'index.json'),
        JSON.stringify(
          defaultPlugins.map(plugin => ({
            ...plugin,
            out: path.parse(plugin.out).base,
          })),
        ),
      ),
    )
    .catch(die);
}

function compile(buildFolder, entry) {
  // eslint-disable-next-line no-console
  console.log('Building main bundle', entry);

  const projectRoots = path.join(__dirname, '..');
  return Metro.runBuild(
    {
      reporter: {update: () => {}},
      projectRoot: projectRoots,
      watchFolders: [projectRoots],
      serializer: {},
      transformer: {
        babelTransformerPath: path.join(
          __dirname,
          '..',
          'static',
          'transforms',
          'index.js',
        ),
      },
      resolver: {
        blacklistRE: /\/(sonar|flipper-public)\/dist\//,
      },
    },
    {
      dev: false,
      minify: false,
      resetCache: true,
      sourceMap: true,
      entry,
      out: path.join(buildFolder, 'bundle.js'),
    },
  ).catch(die);
}

function buildFolder() {
  // eslint-disable-next-line no-console
  console.log('Creating build directory');
  return new Promise((resolve, reject) => {
    tmp.dir((err, buildFolder) => {
      if (err) {
        reject(err);
      } else {
        resolve(buildFolder);
      }
    });
  }).catch(die);
}

function getVersionNumber() {
  let {version} = require('../package.json');
  const buildNumber = process.argv.join(' ').match(/--version=(\d+)/);
  if (buildNumber && buildNumber.length > 0) {
    version = [...version.split('.').slice(0, 2), buildNumber[1]].join('.');
  }
  return version;
}

module.exports = {
  buildFolder,
  compile,
  die,
  compileDefaultPlugins,
  getVersionNumber,
};
<commit_msg>removing entry, rootDir from defaultPlugins<commit_after>/**
 * Copyright 2018-present Facebook.
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 * @format
 */

const Metro = require('../static/node_modules/metro');
const compilePlugins = require('../static/compilePlugins');
const tmp = require('tmp');
const path = require('path');
const fs = require('fs-extra');

function die(err) {
  console.error(err.stack);
  process.exit(1);
}

function compileDefaultPlugins(defaultPluginDir) {
  return compilePlugins(
    null,
    [
      path.join(__dirname, '..', 'src', 'plugins'),
      path.join(__dirname, '..', 'src', 'fb', 'plugins'),
    ],
    defaultPluginDir,
    {force: true, failSilently: false},
  )
    .then(defaultPlugins =>
      fs.writeFileSync(
        path.join(defaultPluginDir, 'index.json'),
        JSON.stringify(
          defaultPlugins.map(({entry, rootDir, out, ...plugin}) => ({
            ...plugin,
            out: path.parse(out).base,
          })),
        ),
      ),
    )
    .catch(die);
}

function compile(buildFolder, entry) {
  // eslint-disable-next-line no-console
  console.log('Building main bundle', entry);

  const projectRoots = path.join(__dirname, '..');
  return Metro.runBuild(
    {
      reporter: {update: () => {}},
      projectRoot: projectRoots,
      watchFolders: [projectRoots],
      serializer: {},
      transformer: {
        babelTransformerPath: path.join(
          __dirname,
          '..',
          'static',
          'transforms',
          'index.js',
        ),
      },
      resolver: {
        blacklistRE: /\/(sonar|flipper-public)\/dist\//,
      },
    },
    {
      dev: false,
      minify: false,
      resetCache: true,
      sourceMap: true,
      entry,
      out: path.join(buildFolder, 'bundle.js'),
    },
  ).catch(die);
}

function buildFolder() {
  // eslint-disable-next-line no-console
  console.log('Creating build directory');
  return new Promise((resolve, reject) => {
    tmp.dir((err, buildFolder) => {
      if (err) {
        reject(err);
      } else {
        resolve(buildFolder);
      }
    });
  }).catch(die);
}

function getVersionNumber() {
  let {version} = require('../package.json');
  const buildNumber = process.argv.join(' ').match(/--version=(\d+)/);
  if (buildNumber && buildNumber.length > 0) {
    version = [...version.split('.').slice(0, 2), buildNumber[1]].join('.');
  }
  return version;
}

module.exports = {
  buildFolder,
  compile,
  die,
  compileDefaultPlugins,
  getVersionNumber,
};
<|endoftext|>


<commit_before>'use strict';

if (document.location.pathname != '/' && document.location.pathname.indexOf('code') === -1) {
  document.location.href = '/';
}

const layoutTemplate = `

`;

const Articles = Backbone.Collection.extend({
  url: 'http://www.modelo.mobi:1337/articles',
  initialize() {
    this.listenTo(this, 'search', (query) => {
      this.byQuery(query);
    });
  },
  byQuery(query) {
    if (query) {
      query = query.toLowerCase();
    }
    if (!this.original) {
      this.original = new Articles(this.models);
    }
    const filtered = this.original.filter((item) => {
      let name = item.get('name');
      if (name) {
        name = name.toLowerCase();
      }
      return name.indexOf(query) > -1
    });
    this.reset(filtered);
    this.trigger('searched');
  }
});

const LayoutView = Marionette.LayoutView.extend({
  el: 'main',
  template: _.template(layoutTemplate),
  regions: {
    header: '#header',
    drawer: '#drawer',
    content: '#content',
    footer: '#footer',
    toast: '#toast',
    cart: '#cart'
  },
  onRender() {
    this.getRegion('content').show(new Marionette.Form({
      text: 'Eres mayor de edad?',
      buttons: [
        {
          label: 'SI',
          onClick: function() {
            $('.mdl-layout__drawer-button').css({ display: 'block' });
            Backbone.history.navigate('/order', true);
          }
        },
        {
          label: 'NO',
          onClick: function() {
            document.location.href = 'http://www.google.com';
          }
        }
      ]
    }));
  }
});

const layout = new LayoutView();

layout.render();

const User = Backbone.Model.extend({
  urlRoot: 'http://www.modelo.mobi:1337/users',
  idAttribute: '_id',
});

const user = new User({ _id: '56d28dabb23bf0423c8e12a9' });
user.fetch().then(() => {
  layout.getRegion('drawer').show(new Marionette.Modelo.DrawerView({
    menu: [{
      label: '  Pedir Ahora!',
      href: '/order'
    }, {
      label: '  Historial de Pedidos',
      href: '/orders'
    }, {
      label: '  Mi Perfil',
      href: '/profile'
    }, {
      label: '  Logros',
      href: '/achievments'
    }, {
      label: '  Eventos',
      href: '/events'
    }],
    user: user
  }));
});
//layout.getRegion('header').show(new Marionette.form());
var articles = new Articles();
const searchView = new Marionette.Search({ collection: articles });
layout.getRegion('header').show(searchView);
componentHandler.upgradeDom();

const Order = Backbone.Model.extend({
  urlRoot: 'http://www.modelo.mobi:1337/orders',
  idAttribute: '_id'
});

const Awards = Backbone.Collection.extend({
  url: function(){
    return 'http://www.modelo.mobi:1337/users/'+user.get('_id')+'/awards';
  }
});

const Events = Backbone.Collection.extend({
  url: function(){
    return 'http://www.modelo.mobi:1337/users/'+user.get('_id')+'/events';
  }
});

const Promotion = Backbone.Model.extend({
  urlRoot: 'http://www.modelo.mobi:1337/discounts/',
  idAttribute: 'shortid'
});

const Router = Marionette.AppRouter.extend({
  appRoutes: {
    'order': 'order',
    'orders': 'orders',
    'events': 'events',
    'profile': 'profile',
    'ticket': 'ticket',
    'confirmation': 'confirmation',
    'achievments': 'achievments',
    'code/:_id': 'code'
  },
  controller: {
    code(_id) {
      const promotion = new Promotion({ shortid: _id });
      promotion.fetch().then(() => {
        articles.discount = promotion.get('discount');
        articles.start = new Date();
        Backbone.history.navigate('/order');
      });
    },
    order() {
      layout.getRegion('footer').empty();
      var self = this;
      this.articles = articles;
      this.articles.stopListening(this.articles, 'change', this._showTotalDebounce);
      this._showTotalDebounce = _.debounce(this._showTotal.bind(this), 500);
      this._closeTotalDebounce = _.debounce(this._closeTotal, 1600);
      articles.fetch().done(function(){
        articles.listenTo(articles, 'change', self._showTotalDebounce);
      });

      layout.getRegion('content').show(new Marionette.ArticleList({
        collection: articles
      }))
      var buttonView = new Marionette.Modelo.Button({
        addOrder() {
          Backbone.history.navigate('/ticket', true);
        },
        addSchedule() {
          console.log('):');
        },
      });
      layout.getRegion('cart').show(buttonView);
    },
    orders() {

    },
    events() {
      layout.getRegion('cart').empty();
      layout.getRegion('footer').empty();
      layout.getRegion('toast').empty();
      var eventsList = new Events();
      eventsList.fetch()
      var events = new Marionette.EventsList({
        collection: eventsList
      })
      layout.getRegion('content').show(events)
    },
    profile() {

    },
    achievments() {
      layout.getRegion('cart').empty();
      var awardsList = new Awards();
      awardsList.fetch();
      var awards = new Marionette.Awards({
        collection: awardsList
      });
      layout.getRegion('content').empty();
      layout.getRegion('footer').show(awards);
    },
    confirmation() {
      var confirmationView = new Marionette.Modelo.ConfirmationView({});
      layout.getRegion('footer').empty();
      layout.getRegion('content').show(confirmationView);
    },
    ticket() {
      var self = this;
      this.articles.stopListening(this.articles, 'change', this._showTotalDebounce);
      layout.getRegion('cart').empty();
      layout.getRegion('cart').empty();
      var ticketView = new Marionette.Ticket({
        collection: this.articles
      });
      layout.getRegion('content').show(ticketView);
      var directionView = new Marionette.DirectionView({
        model: new Backbone.Model(),
        onClick() {
          var order = new Order({
            articles: self.articles.toJSON(),
            userId: user.get('_id'),
            direction: this.model.get('direction')
          });
          order.save().done(function(){
            Backbone.history.navigate('/confirmation', true);
          })
        }
      });
      layout.getRegion('footer').show(directionView);
    },
    _showTotal: function() {
      console.log('show total');
      var total = 0;
      this.articles.each(function(article){
        total+= parseFloat(article.get('currentPrice'));
      });
      total = total.toFixed(2);
      var showTotal = new Marionette.ShowTotal({
        total: total
      });
      layout.getRegion('toast').show(showTotal);
      $('#toast').addClass('active');
      this._closeTotalDebounce();
    },
    _closeTotal: function() {
      console.log('close total')
      $('#toast').removeClass('active');
    }
  },
  onRoute: function () {
    if (document.body.querySelector('.mdl-layout__obfuscator.is-visible')) {
      document.body.querySelector('.mdl-layout__obfuscator.is-visible').click();
    }
  }
});

new Router();

Backbone.Intercept.start();
Backbone.history.start({
  pushState: true
});

const userChannel = Backbone.Radio.channel('user');

const saveCurrentPosition = () => {
  navigator.geolocation.getCurrentPosition(function(position) {
      var latitude = position.coords.latitude.toFixed(3);
      var longitude = position.coords.longitude.toFixed(3);
      user.set('location', [longitude, latitude]);
      user.save();
  });
};

setTimeout(saveCurrentPosition, 1000*60*30);
saveCurrentPosition();

<commit_msg>call this order<commit_after>'use strict';

if (document.location.pathname != '/' && document.location.pathname.indexOf('code') === -1) {
  document.location.href = '/';
}

const layoutTemplate = `

`;

const Articles = Backbone.Collection.extend({
  url: 'http://www.modelo.mobi:1337/articles',
  initialize() {
    this.listenTo(this, 'search', (query) => {
      this.byQuery(query);
    });
  },
  byQuery(query) {
    if (query) {
      query = query.toLowerCase();
    }
    if (!this.original) {
      this.original = new Articles(this.models);
    }
    const filtered = this.original.filter((item) => {
      let name = item.get('name');
      if (name) {
        name = name.toLowerCase();
      }
      return name.indexOf(query) > -1
    });
    this.reset(filtered);
    this.trigger('searched');
  }
});

const LayoutView = Marionette.LayoutView.extend({
  el: 'main',
  template: _.template(layoutTemplate),
  regions: {
    header: '#header',
    drawer: '#drawer',
    content: '#content',
    footer: '#footer',
    toast: '#toast',
    cart: '#cart'
  },
  onRender() {
    this.getRegion('content').show(new Marionette.Form({
      text: 'Eres mayor de edad?',
      buttons: [
        {
          label: 'SI',
          onClick: function() {
            $('.mdl-layout__drawer-button').css({ display: 'block' });
            Backbone.history.navigate('/order', true);
          }
        },
        {
          label: 'NO',
          onClick: function() {
            document.location.href = 'http://www.google.com';
          }
        }
      ]
    }));
  }
});

const layout = new LayoutView();

layout.render();

const User = Backbone.Model.extend({
  urlRoot: 'http://www.modelo.mobi:1337/users',
  idAttribute: '_id',
});

const user = new User({ _id: '56d28dabb23bf0423c8e12a9' });
user.fetch().then(() => {
  layout.getRegion('drawer').show(new Marionette.Modelo.DrawerView({
    menu: [{
      label: '  Pedir Ahora!',
      href: '/order'
    }, {
      label: '  Historial de Pedidos',
      href: '/orders'
    }, {
      label: '  Mi Perfil',
      href: '/profile'
    }, {
      label: '  Logros',
      href: '/achievments'
    }, {
      label: '  Eventos',
      href: '/events'
    }],
    user: user
  }));
});
//layout.getRegion('header').show(new Marionette.form());
var articles = new Articles();
const searchView = new Marionette.Search({ collection: articles });
layout.getRegion('header').show(searchView);
componentHandler.upgradeDom();

const Order = Backbone.Model.extend({
  urlRoot: 'http://www.modelo.mobi:1337/orders',
  idAttribute: '_id'
});

const Awards = Backbone.Collection.extend({
  url: function(){
    return 'http://www.modelo.mobi:1337/users/'+user.get('_id')+'/awards';
  }
});

const Events = Backbone.Collection.extend({
  url: function(){
    return 'http://www.modelo.mobi:1337/users/'+user.get('_id')+'/events';
  }
});

const Promotion = Backbone.Model.extend({
  urlRoot: 'http://www.modelo.mobi:1337/discounts/',
  idAttribute: 'shortid'
});

const Router = Marionette.AppRouter.extend({
  appRoutes: {
    'order': 'order',
    'orders': 'orders',
    'events': 'events',
    'profile': 'profile',
    'ticket': 'ticket',
    'confirmation': 'confirmation',
    'achievments': 'achievments',
    'code/:_id': 'code'
  },
  controller: {
    code(_id) {
      const promotion = new Promotion({ shortid: _id });
      promotion.fetch().then(() => {
        articles.discount = promotion.get('discount');
        articles.start = new Date();
        Backbone.history.navigate('/order');
        this.order();
      });
    },
    order() {
      layout.getRegion('footer').empty();
      var self = this;
      this.articles = articles;
      this.articles.stopListening(this.articles, 'change', this._showTotalDebounce);
      this._showTotalDebounce = _.debounce(this._showTotal.bind(this), 500);
      this._closeTotalDebounce = _.debounce(this._closeTotal, 1600);
      articles.fetch().done(function(){
        articles.listenTo(articles, 'change', self._showTotalDebounce);
      });

      layout.getRegion('content').show(new Marionette.ArticleList({
        collection: articles
      }))
      var buttonView = new Marionette.Modelo.Button({
        addOrder() {
          Backbone.history.navigate('/ticket', true);
        },
        addSchedule() {
          console.log('):');
        },
      });
      layout.getRegion('cart').show(buttonView);
    },
    orders() {

    },
    events() {
      layout.getRegion('cart').empty();
      layout.getRegion('footer').empty();
      layout.getRegion('toast').empty();
      var eventsList = new Events();
      eventsList.fetch()
      var events = new Marionette.EventsList({
        collection: eventsList
      })
      layout.getRegion('content').show(events)
    },
    profile() {

    },
    achievments() {
      layout.getRegion('cart').empty();
      var awardsList = new Awards();
      awardsList.fetch();
      var awards = new Marionette.Awards({
        collection: awardsList
      });
      layout.getRegion('content').empty();
      layout.getRegion('footer').show(awards);
    },
    confirmation() {
      var confirmationView = new Marionette.Modelo.ConfirmationView({});
      layout.getRegion('footer').empty();
      layout.getRegion('content').show(confirmationView);
    },
    ticket() {
      var self = this;
      this.articles.stopListening(this.articles, 'change', this._showTotalDebounce);
      layout.getRegion('cart').empty();
      layout.getRegion('cart').empty();
      var ticketView = new Marionette.Ticket({
        collection: this.articles
      });
      layout.getRegion('content').show(ticketView);
      var directionView = new Marionette.DirectionView({
        model: new Backbone.Model(),
        onClick() {
          var order = new Order({
            articles: self.articles.toJSON(),
            userId: user.get('_id'),
            direction: this.model.get('direction')
          });
          order.save().done(function(){
            Backbone.history.navigate('/confirmation', true);
          })
        }
      });
      layout.getRegion('footer').show(directionView);
    },
    _showTotal: function() {
      console.log('show total');
      var total = 0;
      this.articles.each(function(article){
        total+= parseFloat(article.get('currentPrice'));
      });
      total = total.toFixed(2);
      var showTotal = new Marionette.ShowTotal({
        total: total
      });
      layout.getRegion('toast').show(showTotal);
      $('#toast').addClass('active');
      this._closeTotalDebounce();
    },
    _closeTotal: function() {
      console.log('close total')
      $('#toast').removeClass('active');
    }
  },
  onRoute: function () {
    if (document.body.querySelector('.mdl-layout__obfuscator.is-visible')) {
      document.body.querySelector('.mdl-layout__obfuscator.is-visible').click();
    }
  }
});

new Router();

Backbone.Intercept.start();
Backbone.history.start({
  pushState: true
});

const userChannel = Backbone.Radio.channel('user');

const saveCurrentPosition = () => {
  navigator.geolocation.getCurrentPosition(function(position) {
      var latitude = position.coords.latitude.toFixed(3);
      var longitude = position.coords.longitude.toFixed(3);
      user.set('location', [longitude, latitude]);
      user.save();
  });
};

setTimeout(saveCurrentPosition, 1000*60*30);
saveCurrentPosition();

<|endoftext|>


<commit_before>const argv = require("minimist")(process.argv.slice(2))
const ora = require("ora")
const chalk = require("chalk")

const Modules = require("./modules")
const Bundles = require("./bundles")
const Packaging = require("./packaging")
const Stats = require("./stats")
const { asyncCopyTo, asyncRimRaf, asyncExecuteCommand } = require("./utils")

const rollup = require("./rollup")
const babel = require("./babel")
const noop = require("./noop")

const { UNIVERSAL, NODE, NOOP } = Bundles.bundleTypes

const builders = {
  [UNIVERSAL]: rollup,
  [NODE]: babel,
  [NOOP]: noop
}

const requestedEntries = (argv._[0] || "")
  .split(",")
  .map(name => name.toLowerCase())

function shouldSkipBundle(bundle, bundleType) {
  if (requestedEntries.length > 0) {
    const isAskingForDifferentEntries = requestedEntries.every(
      requestedName => bundle.entry.indexOf(requestedName) === -1
    )
    if (isAskingForDifferentEntries) {
      return true
    }
  }
  return false
}

async function copyFlowTypes(name) {
  // Windows isn't supported in flow gen-flow-files
  if (process.platform === "win32") return

  const srcDir = `packages/${name}/src`
  const outDir = `build/packages/${name}`

  const msg = chalk.white.bold(`@lingui/${name}`) + chalk.dim(` (flow types)`)
  const spinner = ora(msg).start()

  await asyncExecuteCommand(
    `yarn flow-copy-source -i *.test.js ${srcDir} ${outDir}`
  )
  spinner.succeed()
}

async function buildEverything() {
  await asyncRimRaf("build")

  // Run them serially for better console output
  // and to avoid any potential race conditions.
  for (const bundle of Bundles.bundles) {
    if (shouldSkipBundle(bundle, bundle.type)) continue

    const builder = builders[bundle.type]
    if (!builder) {
      console.log("Unknown type")
      continue
    }

    await builder(bundle)
    if (bundle.type === UNIVERSAL || bundle.type === NODE) {
      const name = bundle.entry.replace("@lingui/", "")
      await copyFlowTypes(name)
    }
  }

  console.log(Stats.printResults())
  Stats.saveResults()

  await Packaging.prepareNpmPackages()
}

buildEverything()
<commit_msg>chore: don't write bundle stats by defualt<commit_after>const argv = require("minimist")(process.argv.slice(2))
const ora = require("ora")
const chalk = require("chalk")

const Modules = require("./modules")
const Bundles = require("./bundles")
const Packaging = require("./packaging")
const Stats = require("./stats")
const { asyncCopyTo, asyncRimRaf, asyncExecuteCommand } = require("./utils")

const rollup = require("./rollup")
const babel = require("./babel")
const noop = require("./noop")

const { UNIVERSAL, NODE, NOOP } = Bundles.bundleTypes

const builders = {
  [UNIVERSAL]: rollup,
  [NODE]: babel,
  [NOOP]: noop
}

const requestedEntries = (argv._[0] || "")
  .split(",")
  .map(name => name.toLowerCase())

function shouldSkipBundle(bundle, bundleType) {
  if (requestedEntries.length > 0) {
    const isAskingForDifferentEntries = requestedEntries.every(
      requestedName => bundle.entry.indexOf(requestedName) === -1
    )
    if (isAskingForDifferentEntries) {
      return true
    }
  }
  return false
}

async function copyFlowTypes(name) {
  // Windows isn't supported in flow gen-flow-files
  if (process.platform === "win32") return

  const srcDir = `packages/${name}/src`
  const outDir = `build/packages/${name}`

  const msg = chalk.white.bold(`@lingui/${name}`) + chalk.dim(` (flow types)`)
  const spinner = ora(msg).start()

  await asyncExecuteCommand(
    `yarn flow-copy-source -i *.test.js ${srcDir} ${outDir}`
  )
  spinner.succeed()
}

async function buildEverything() {
  await asyncRimRaf("build")

  // Run them serially for better console output
  // and to avoid any potential race conditions.
  for (const bundle of Bundles.bundles) {
    if (shouldSkipBundle(bundle, bundle.type)) continue

    const builder = builders[bundle.type]
    if (!builder) {
      console.log("Unknown type")
      continue
    }

    await builder(bundle)
    if (bundle.type === UNIVERSAL || bundle.type === NODE) {
      const name = bundle.entry.replace("@lingui/", "")
      await copyFlowTypes(name)
    }
  }

  console.log(Stats.printResults())
  if (argv.saveStats) Stats.saveResults()

  await Packaging.prepareNpmPackages()
}

buildEverything()
<|endoftext|>


<commit_before>'use strict';

angular.module('LostPetsApp')
    .controller('DishDetailController', ['$scope', 'petDBFactory', function ($scope, petDBFactory) {

        //Stuff for dealing with no server info
        $scope.showData = false;
        $scope.message = "Processing Data ...";

        //initialize to empty and then try to get data from server -- this is $http method
        /*$scope.petDB = [];
        petDBFactory.getDB()
        .then(
            function(response) {
                $scope.DBofPets = response.data;
                console.log("inside");
                console.log(response.data);
                $scope.showData = true;
            },
            function(response){
                $scope.message = "Error: " + response.status + " " + response.statusText;
            }
        );*/

        $scope.petDB = petDBFactory.getDB().query(
            function (response) {
                $scope.DBofPets = response;
                $scope.showData = true;
                console.log(response[0].entries[0]);//return actual useful data
            },
            function (response) {
                $scope.message = "Error: " + response.status + " " + response.statusText;
            }
        );

        //initially false
        $scope.showDetails = false;

        $scope.entry = { author: "", date: new Date().toISOString(), moreDetails: "" };

        $scope.toggleDetails = function () {
            $scope.showDetails = !$scope.showDetails;
        };

        //$scope.dish = dish;

    }])

    .controller('ModalCtrl', function ($scope, ModalService) {

        //adding modal service
        $scope.show = function () {
            ModalService.showModal({
                templateUrl: "../modalTemplates/complex.html",
                controller: "ModalController"
            }).then(function (modal) {

                //it's a bootstrap element, use 'modal' to show it
                modal.element.modal();
                modal.close.then(function (result) {
                    console.log(result);
                });
            });
        };
    })

    .controller('ContactController', ['$scope', function ($scope) {
        $scope.feedback = {
            mychannel: "",
            firstName: "",
            lastName: "",
            agree: false,
            email: ""
        };
        var channels = [{
            value: "tel",
            label: "Tel."
        }, {
            value: "Email",
            label: "Email"
        }];
        $scope.channels = channels;
        $scope.invalidChannelSelection = false;
    }])

    .controller('FeedbackController', ['$scope', function ($scope) {
        $scope.sendFeedback = function () {
            console.log($scope.feedback);
            if ($scope.feedback.agree && ($scope.feedback.mychannel === "") && !$scope.feedback.mychannel) {
                $scope.invalidChannelSelection = true;
                console.log('incorrect');
            } else {
                $scope.invalidChannelSelection = false;
                $scope.feedback = {
                    mychannel: "",
                    firstName: "",
                    lastName: "",
                    agree: false,
                    email: ""
                };
                $scope.feedback.mychannel = "";

                $scope.feedbackForm.$setPristine();
                console.log($scope.feedback);
            }
        };
    }])

    .controller('PetDetailController', ['$scope', 'petDBFactory', function ($scope) {
        $scope.submitEntry = function () {
            console.log($scope.entry);

            //Step 2: This is how you record the date
            $scope.entry.date = new Date().toISOString();

            // Step 3: Push your comment into the dish's comment array
            $scope.DBofPets.entries.push($scope.entry);

            //Added in to add a new pet to db (sends a 'post' call to the server)

            //Step 4: reset your form to pristine
            $scope.commentForm.$setPristine();

            //Step 5: reset your JavaScript object that holds your comment
            $scope.entry = { author: "", date: new Date().toISOString() };
            console.log($scope.entry);
        };
    }])

    .controller('ModalController', function ($scope, close) {
        $scope.close = function (result) {
                close(result, 500); // close, but give 500ms for bootstrap to animate
                //close("Success!");
        };
    });
<commit_msg>working buttons--removed if-else<commit_after>'use strict';

angular.module('LostPetsApp')
    .controller('DishDetailController', ['$scope', 'petDBFactory', function ($scope, petDBFactory) {

        //Stuff for dealing with no server info
        $scope.showData = false;
        $scope.message = "Processing Data ...";

        //initialize to empty and then try to get data from server -- this is $http method
        /*$scope.petDB = [];
        petDBFactory.getDB()
        .then(
            function(response) {
                $scope.DBofPets = response.data;
                console.log("inside");
                console.log(response.data);
                $scope.showData = true;
            },
            function(response){
                $scope.message = "Error: " + response.status + " " + response.statusText;
            }
        );*/

        $scope.petDB = petDBFactory.getDB().query(
            function (response) {
                $scope.DBofPets = response;
                $scope.showData = true;
                console.log(response[0].entries[0]);//return actual useful data
            },
            function (response) {
                $scope.message = "Error: " + response.status + " " + response.statusText;
            }
        );

        //initially false
        $scope.showDetails = false;

        $scope.entry = { author: "", date: new Date().toISOString(), moreDetails: "" };

        $scope.toggleDetails = function () {
            $scope.showDetails = !$scope.showDetails;
        };

        //$scope.dish = dish;

    }])

    .controller('ModalCtrl', function ($scope, ModalService) {
        //adding modal service
        $scope.show = function () {
            ModalService.showModal({
                templateUrl: "../modalTemplates/complex.html",
                controller: "ModalController"
            }).then(function (modal) {
                //it's a bootstrap element, use 'modal' to show it
                modal.element.modal();
                modal.close.then(function (result) {
                    console.log(result);
                });
            });
        };
    })

    .controller('ContactController', ['$scope', function ($scope) {
        $scope.feedback = {
            mychannel: "",
            firstName: "",
            lastName: "",
            agree: false,
            email: ""
        };
        var channels = [{
            value: "tel",
            label: "Tel."
        }, {
            value: "Email",
            label: "Email"
        }];
        $scope.channels = channels;
        $scope.invalidChannelSelection = false;
    }])

    .controller('FeedbackController', ['$scope', function ($scope) {
        $scope.sendFeedback = function () {
            console.log($scope.feedback);
            if ($scope.feedback.agree && ($scope.feedback.mychannel === "") && !$scope.feedback.mychannel) {
                $scope.invalidChannelSelection = true;
                console.log('incorrect');
            } else {
                $scope.invalidChannelSelection = false;
                $scope.feedback = {
                    mychannel: "",
                    firstName: "",
                    lastName: "",
                    agree: false,
                    email: ""
                };
                $scope.feedback.mychannel = "";

                $scope.feedbackForm.$setPristine();
                console.log($scope.feedback);
            }
        };
    }])

    .controller('PetDetailController', ['$scope', 'petDBFactory', function ($scope) {
        $scope.submitEntry = function () {
            console.log($scope.entry);

            //Step 2: This is how you record the date
            $scope.entry.date = new Date().toISOString();

            // Step 3: Push your comment into the dish's comment array
            $scope.DBofPets.entries.push($scope.entry);

            //Added in to add a new pet to db (sends a 'post' call to the server)

            //Step 4: reset your form to pristine
            $scope.commentForm.$setPristine();

            //Step 5: reset your JavaScript object that holds your comment
            $scope.entry = { author: "", date: new Date().toISOString() };
            console.log($scope.entry);
        };
    }])

    .controller('ModalController', function ($scope, close) {
        $scope.close = function (result) {
                close(result, 500); // close, but give 500ms for bootstrap to animate
                //close("Success!");
        };
    });
<|endoftext|>


<commit_before>var Job = require ('./job');
var spawn = require('child_process').spawn;
var spawnSync = require('child_process').spawnSync;
var _ = require ('underscore');
var utils = require('util');
var events = require('events');
utils.inherits(Printer, events.EventEmitter);

/**
 * Describes the parameter options accepted by lp
 *
 * options array specifies the valid option names for the option
 * if expects is blank '' no option value is required for the option
 *
 * This was written according to lp man page
 * http://unixhelp.ed.ac.uk/CGI/man-cgi?lp
 */
var generalOptions = {
  'E': {
    'options': ['E', 'encryption'],
    'description': 'Forces encryption when connecting to the server',
    'expects': '',
    'default': false
  },
  'U': {
    'options': ['U', 'Username', 'username'],
    'description': 'Specifies the username to use when connecting to the server',
    'expects': 'string'
  },
  'c': {
    'options': ['c', 'backwardsCompatibility'],
    'description': 'This option is provided for backwards-compatibility only. On systems  that	support	 it,  this  option forces the print file to be copied to the spool directory before  printing. In CUPS, print files  are always sent to the scheduler via IPP which has the same effect.',
    'expects': '',
    'default': false
  },
  'd': {
    'options': ['d', 'destination'],
    'description': 'Prints files to the named printer',
    'expects': 'string'
  },
  'h': {
    'options': ['h', 'hostname'],
    'description': 'Chooses an alternate server',
    'expects': 'string'
  },
  'i': {
    'options': ['i', 'job-id'],
    'description': 'Specifies an existing job to modify',
    'expects': 'number'
  },
  'm': {
    'options': ['m'],
    'description': 'Sends an email when the job is completed',
    'expects': ''
  },
  'n': {
    'options': ['n', 'copies', 'numCopies'],
    'description': 'Sets the number of copies to print from 1 to 100',
    'expects': 'number',
    'default': 1
  },
  'o': {
    'options': ['o'],
    'description': '"name=value [name=value ...]" Sets one or more job options',
    'expects': 'string',
    'default': ''
  },
  'q': {
    'options': ['q', 'priority'],
    'description': 'Sets the job priority from	1 (lowest) to 100 (highest). The default priority is 50',
    'expects': 'number',
    'default': 1
  },
  's': {
    'options': ['s'],
    'description': 'Do not report the resulting job IDs (silent mode.)',
    'expects': ''
  },
  't': {
    'options': ['t', 'name'],
    'description': 'Sets the job name',
    'expects': 'string'
  },
  'H': {
    'options': ['H', 'when'],
    'description': 'Specifies  when  the  job  should be printed. A value of immediate will print the file immediately, a value of hold will hold the job indefinitely, and a time value (HH:MM) will hold the job until the specified time. Use a value of resume with the -i option to resume a  held job.  Use a value of restart with the -i option to restart a completed job.',
    'default': 'immediate',
    'expects': 'string'

  },
  'P': {
    'options': ['P', 'page-list'],
    'description': 'page-list Specifies which pages to print in the document. The list can  contain a list of numbers and ranges (#-#) separated by commas (e.g. 1,3-5,16).',
    'expects': 'string'
  }
};

/**
 * Describes the parameter options accepted by lp -o option
 *
 * options array specifies the valid option names for the option
 * if expects is blank '' no option value is required for the option
 *
 * This was written according to lp man page
 * http://unixhelp.ed.ac.uk/CGI/man-cgi?lp
 */
var oOptions = {
  'media': {
    'options': ['media'],
    'description': 'Sets  the  page  size  to size. Most printers support at least the size names "a4", "letter", and "legal".',
    'expects': 'string',
    'default': 'a4'
  },
  'landscape': {
    'options': ['landscape'],
    'description': 'landscape',
    'expects': ''
  },
  'orientation-requested': {
    'options': ['orientation-requested'],
    'description': '',
    'expects': 'number'
  },
  'sides': {
    'options': ['sides'],
    'description': 'Prints on one or two sides of the  paper.  The  value  "two-sided-long-edge" is  normally  used  when printing portrait (unrotated) pages, while "two-sided-short-edge" is used for landscape pages.',
    'expects': 'string'
  },
  'fitplot': {
    'options': ['fitplot'],
    'description': 'Scales the print file to fit on the page',
    'expects': '',
    'default': false
  },
  'scaling': {
    'options': ['scaling'],
    'description': 'Scales image files to use up to number percent of the page. Values greater than 100 cause the image file to be printed across multiple pages',
    'expects': 'number'
  },
  'cpi': {
    'options': ['cpi'],
    'description': 'Sets the number of characters per inch to use when printing a text file. The default is 10',
    'expects': 'number'
  },
  'lpi': {
    'options': ['lpi'],
    'description': 'Sets  the  number  of  lines  per inch to use when printing a text file. The default is 6',
    'expects': 'number'
  },
  'page-bottom': {
    'options': ['page-bottom'],
    'description': 'Sets the page margins when printing text files. The values are in points - there are 72 points to the inch',
    'expects': 'number'
  },
  'page-left': {
    'options': ['page-left'],
    'description': 'Sets the page margins when printing text files. The values are in points - there are 72 points to the inch',
    'expects': 'number'
  },
  'page-right': {
    'options': ['page-right'],
    'description': 'Sets the page margins when printing text files. The values are in points - there are 72 points to the inch',
    'expects': 'number'
  },
  'page-top': {
    'options': ['page-top'],
    'description': 'Sets the page margins when printing text files. The values are in points - there are 72 points to the inch',
    'expects': 'number'
  }
};

var optionsFactory = function (options) {

  var selGeneralOptions = {};

  _.each(generalOptions, function(generalOption, generalOptionId) { // for each of lp available options
    _.each(generalOption.options, function(option) { // for each option possible name
      if(typeof options[option] !== 'undefined') { // check of the method options contains the value
        if(generalOption.expects === '') { // when expects is empty, ommit the options defined value, just add
          if(options[option]) {
            selGeneralOptions[generalOptionId] = true;
          }
        } else {
          selGeneralOptions[generalOptionId] = options[option];
        }
      }
    });
    if(typeof generalOption.default != 'undefined') { // if method options does not contains the value, use default if available
      if(typeof selGeneralOptions[generalOptionId] == 'undefined') {
        selGeneralOptions[generalOptionId] = generalOption.default;
      }
    }
  });

  var selOOptions = {};

  _.each(oOptions, function(oOption, oOptionId) { // for each of lp available options
    _.each(oOption.options, function(option) { // for each option possible name
      if(typeof options[option] !== 'undefined') { // check of the method options contains the value
        if(oOption.expects === '') { // when expects is empty, ommit the options defined value, just add
          if(options[option]) {
            selOOptions[oOptionId] = true;
          }
        } else {
          selOOptions[oOptionId] = options[option];
        }
      } else if(typeof oOption.default != 'undefined') { // if method options does not contains the value, use default if available
        selOOptions[oOptionId] = oOption.default;
      }
    });
    if(typeof oOption.default != 'undefined') { // if method options does not contains the value, use default if available
      if(typeof selOOptions[oOptionId] == 'undefined') {
        selOOptions[oOptionId] = oOption.default;
      }
    }
  });

  if(!_.isEmpty(selOOptions)) {
    var selOoptionsString = '';
    _.each(selOOptions, function(oOption, oOptionId) {
      if(oOptions[oOptionId].expects === '') {
        if(oOption) {
          selOoptionsString = selOoptionsString + ' ' + oOptionId;
        }
      } else {
        selOoptionsString = selOoptionsString + ' ' + oOptionId + '=' + oOption;
      }
    });
    if(typeof selGeneralOptions.o == 'string') {
      selGeneralOptions.o = selGeneralOptions.o + selOoptionsString;
    } else {
      selGeneralOptions.o = selOoptionsString;
    }
  }

  return selGeneralOptions;
};

var argsFactory = function(options) {
  var args = [];
  _.each(options, function(optionValue, optionKey) {
    if(generalOptions[optionKey].expects === '') {
      if(optionValue) {
        args.push('-' + optionKey);
      }
    } else {
      args.push('-' + optionKey + optionValue);
    }

  });
  return args;
};

var buildArgs = function(options) {
  if (!options) return [];
  options = optionsFactory(options);
  return argsFactory(options);
};

var parseStdout = function(data) {
  if (!Buffer.isBuffer(data)) return [];
  return data.toString()
    .replace(/\n$/, '')
    .split('\n');
};

function Printer(name) {
  var self = this;
  if (!Printer.match(name)) {
    console.error(
      name + ' printer does not exist ; installed printers are ' + Printer.list()
      );
  }
  self.name = name;
  self.jobs = [];
  self.watch();
}

Printer.list = function() {
  return parseStdout(spawnSync('lpstat', ['-p']).stdout)
    .filter(function(line) {
      return line.match(/^printer/);
    })
    .map(function(printer) {
      return printer.match(/^printer (\S+)/)[1];
    });
};

Printer.match = function(name) {
  return Boolean(Printer.list().filter(function(printer) {
    return name === printer;
  }).length);
};

Printer.prototype.watch = function() {
  var self = this;
  var args = ['-P', this.name];

  var lpq = spawn('lpq', args);

  lpq.stdout.on('data', function(data) {
    data = parseStdout(data);
    data.shift(2);
    data = data.map(function(line) {
      line = line.split(/[ ]{2,}/);
      return {
        rank: (line[0] === 'active' ? line[0] : parseInt(line[0].slice(0, -2))),
        owner: line[1],
        identifier: parseInt(line[2]),
        files: line[3],
        totalSize: line[4]
      };
    });

    self.jobs.map(function(job) {
      var status = data.filter(function(status) {
        if (status.identifier === job.identifier) return status;
      })[0];

      if (status) {
        job.update(status);
      } else {
        job.unqueue();
      }
    });
  });

  lpq.on('exit', function() {
    self.watch();
  });
};

Printer.prototype.findJob = function(jobId) {
  return this.jobs.filter(function(job) {
    if (job.identifier === jobId) return job;
  })[0];
};

Printer.prototype.printBuffer = function(data, options) {
  var self = this;
  var args = buildArgs(options);
  var lp = spawn('lp', args);

  lp.stdin.write(data);
  lp.stdin.end();

  var job = new Job(lp);
  job.on('sent', function() {
    self.jobs.push(job);
  });

  return job;
};

Printer.prototype.printFile = function(filePath, options) {
  var self = this;
  var args = buildArgs(options);

  args.push('--');
  args.push(file);

  var lp = spawn('lp', args);

  var job = new Job(lp);
  job.on('sent', function() {
    self.jobs.push(job);
  });

  return job;
};

module.exports = Printer;
<commit_msg>remove completed tasks from queue<commit_after>var Job = require ('./job');
var spawn = require('child_process').spawn;
var spawnSync = require('child_process').spawnSync;
var _ = require ('underscore');
var utils = require('util');
var events = require('events');
utils.inherits(Printer, events.EventEmitter);

/**
 * Describes the parameter options accepted by lp
 *
 * options array specifies the valid option names for the option
 * if expects is blank '' no option value is required for the option
 *
 * This was written according to lp man page
 * http://unixhelp.ed.ac.uk/CGI/man-cgi?lp
 */
var generalOptions = {
  'E': {
    'options': ['E', 'encryption'],
    'description': 'Forces encryption when connecting to the server',
    'expects': '',
    'default': false
  },
  'U': {
    'options': ['U', 'Username', 'username'],
    'description': 'Specifies the username to use when connecting to the server',
    'expects': 'string'
  },
  'c': {
    'options': ['c', 'backwardsCompatibility'],
    'description': 'This option is provided for backwards-compatibility only. On systems  that	support	 it,  this  option forces the print file to be copied to the spool directory before  printing. In CUPS, print files  are always sent to the scheduler via IPP which has the same effect.',
    'expects': '',
    'default': false
  },
  'd': {
    'options': ['d', 'destination'],
    'description': 'Prints files to the named printer',
    'expects': 'string'
  },
  'h': {
    'options': ['h', 'hostname'],
    'description': 'Chooses an alternate server',
    'expects': 'string'
  },
  'i': {
    'options': ['i', 'job-id'],
    'description': 'Specifies an existing job to modify',
    'expects': 'number'
  },
  'm': {
    'options': ['m'],
    'description': 'Sends an email when the job is completed',
    'expects': ''
  },
  'n': {
    'options': ['n', 'copies', 'numCopies'],
    'description': 'Sets the number of copies to print from 1 to 100',
    'expects': 'number',
    'default': 1
  },
  'o': {
    'options': ['o'],
    'description': '"name=value [name=value ...]" Sets one or more job options',
    'expects': 'string',
    'default': ''
  },
  'q': {
    'options': ['q', 'priority'],
    'description': 'Sets the job priority from	1 (lowest) to 100 (highest). The default priority is 50',
    'expects': 'number',
    'default': 1
  },
  's': {
    'options': ['s'],
    'description': 'Do not report the resulting job IDs (silent mode.)',
    'expects': ''
  },
  't': {
    'options': ['t', 'name'],
    'description': 'Sets the job name',
    'expects': 'string'
  },
  'H': {
    'options': ['H', 'when'],
    'description': 'Specifies  when  the  job  should be printed. A value of immediate will print the file immediately, a value of hold will hold the job indefinitely, and a time value (HH:MM) will hold the job until the specified time. Use a value of resume with the -i option to resume a  held job.  Use a value of restart with the -i option to restart a completed job.',
    'default': 'immediate',
    'expects': 'string'

  },
  'P': {
    'options': ['P', 'page-list'],
    'description': 'page-list Specifies which pages to print in the document. The list can  contain a list of numbers and ranges (#-#) separated by commas (e.g. 1,3-5,16).',
    'expects': 'string'
  }
};

/**
 * Describes the parameter options accepted by lp -o option
 *
 * options array specifies the valid option names for the option
 * if expects is blank '' no option value is required for the option
 *
 * This was written according to lp man page
 * http://unixhelp.ed.ac.uk/CGI/man-cgi?lp
 */
var oOptions = {
  'media': {
    'options': ['media'],
    'description': 'Sets  the  page  size  to size. Most printers support at least the size names "a4", "letter", and "legal".',
    'expects': 'string',
    'default': 'a4'
  },
  'landscape': {
    'options': ['landscape'],
    'description': 'landscape',
    'expects': ''
  },
  'orientation-requested': {
    'options': ['orientation-requested'],
    'description': '',
    'expects': 'number'
  },
  'sides': {
    'options': ['sides'],
    'description': 'Prints on one or two sides of the  paper.  The  value  "two-sided-long-edge" is  normally  used  when printing portrait (unrotated) pages, while "two-sided-short-edge" is used for landscape pages.',
    'expects': 'string'
  },
  'fitplot': {
    'options': ['fitplot'],
    'description': 'Scales the print file to fit on the page',
    'expects': '',
    'default': false
  },
  'scaling': {
    'options': ['scaling'],
    'description': 'Scales image files to use up to number percent of the page. Values greater than 100 cause the image file to be printed across multiple pages',
    'expects': 'number'
  },
  'cpi': {
    'options': ['cpi'],
    'description': 'Sets the number of characters per inch to use when printing a text file. The default is 10',
    'expects': 'number'
  },
  'lpi': {
    'options': ['lpi'],
    'description': 'Sets  the  number  of  lines  per inch to use when printing a text file. The default is 6',
    'expects': 'number'
  },
  'page-bottom': {
    'options': ['page-bottom'],
    'description': 'Sets the page margins when printing text files. The values are in points - there are 72 points to the inch',
    'expects': 'number'
  },
  'page-left': {
    'options': ['page-left'],
    'description': 'Sets the page margins when printing text files. The values are in points - there are 72 points to the inch',
    'expects': 'number'
  },
  'page-right': {
    'options': ['page-right'],
    'description': 'Sets the page margins when printing text files. The values are in points - there are 72 points to the inch',
    'expects': 'number'
  },
  'page-top': {
    'options': ['page-top'],
    'description': 'Sets the page margins when printing text files. The values are in points - there are 72 points to the inch',
    'expects': 'number'
  }
};

var optionsFactory = function (options) {

  var selGeneralOptions = {};

  _.each(generalOptions, function(generalOption, generalOptionId) { // for each of lp available options
    _.each(generalOption.options, function(option) { // for each option possible name
      if(typeof options[option] !== 'undefined') { // check of the method options contains the value
        if(generalOption.expects === '') { // when expects is empty, ommit the options defined value, just add
          if(options[option]) {
            selGeneralOptions[generalOptionId] = true;
          }
        } else {
          selGeneralOptions[generalOptionId] = options[option];
        }
      }
    });
    if(typeof generalOption.default != 'undefined') { // if method options does not contains the value, use default if available
      if(typeof selGeneralOptions[generalOptionId] == 'undefined') {
        selGeneralOptions[generalOptionId] = generalOption.default;
      }
    }
  });

  var selOOptions = {};

  _.each(oOptions, function(oOption, oOptionId) { // for each of lp available options
    _.each(oOption.options, function(option) { // for each option possible name
      if(typeof options[option] !== 'undefined') { // check of the method options contains the value
        if(oOption.expects === '') { // when expects is empty, ommit the options defined value, just add
          if(options[option]) {
            selOOptions[oOptionId] = true;
          }
        } else {
          selOOptions[oOptionId] = options[option];
        }
      } else if(typeof oOption.default != 'undefined') { // if method options does not contains the value, use default if available
        selOOptions[oOptionId] = oOption.default;
      }
    });
    if(typeof oOption.default != 'undefined') { // if method options does not contains the value, use default if available
      if(typeof selOOptions[oOptionId] == 'undefined') {
        selOOptions[oOptionId] = oOption.default;
      }
    }
  });

  if(!_.isEmpty(selOOptions)) {
    var selOoptionsString = '';
    _.each(selOOptions, function(oOption, oOptionId) {
      if(oOptions[oOptionId].expects === '') {
        if(oOption) {
          selOoptionsString = selOoptionsString + ' ' + oOptionId;
        }
      } else {
        selOoptionsString = selOoptionsString + ' ' + oOptionId + '=' + oOption;
      }
    });
    if(typeof selGeneralOptions.o == 'string') {
      selGeneralOptions.o = selGeneralOptions.o + selOoptionsString;
    } else {
      selGeneralOptions.o = selOoptionsString;
    }
  }

  return selGeneralOptions;
};

var argsFactory = function(options) {
  var args = [];
  _.each(options, function(optionValue, optionKey) {
    if(generalOptions[optionKey].expects === '') {
      if(optionValue) {
        args.push('-' + optionKey);
      }
    } else {
      args.push('-' + optionKey + optionValue);
    }

  });
  return args;
};

var buildArgs = function(options) {
  if (!options) return [];
  options = optionsFactory(options);
  return argsFactory(options);
};

var parseStdout = function(data) {
  if (!Buffer.isBuffer(data)) return [];
  return data.toString()
    .replace(/\n$/, '')
    .split('\n');
};

function Printer(name) {
  var self = this;
  if (!Printer.match(name)) {
    console.error(
      name + ' printer does not exist ; installed printers are ' + Printer.list()
      );
  }
  self.name = name;
  self.jobs = [];
  self.watch();
}

Printer.list = function() {
  return parseStdout(spawnSync('lpstat', ['-p']).stdout)
    .filter(function(line) {
      return line.match(/^printer/);
    })
    .map(function(printer) {
      return printer.match(/^printer (\S+)/)[1];
    });
};

Printer.match = function(name) {
  return Boolean(Printer.list().filter(function(printer) {
    return name === printer;
  }).length);
};

Printer.prototype.watch = function() {
  var self = this;
  var args = ['-P', this.name];

  var lpq = spawn('lpq', args);

  lpq.stdout.on('data', function(data) {
    data = parseStdout(data);
    data.shift(2);
    data = data.map(function(line) {
      line = line.split(/[ ]{2,}/);
      return {
        rank: (line[0] === 'active' ? line[0] : parseInt(line[0].slice(0, -2))),
        owner: line[1],
        identifier: parseInt(line[2]),
        files: line[3],
        totalSize: line[4]
      };
    });

    self.jobs.map(function(job) {
      var status = data.filter(function(status) {
        if (status.identifier === job.identifier) return status;
      })[0];

      if (status) {
        job.update(status);
      } else {
        job.unqueue();
      }
    });
  });

  lpq.on('exit', function() {
    self.watch();
  });
};

Printer.prototype.findJob = function(jobId) {
  return this.jobs.filter(function(job) {
    if (job.identifier === jobId) return job;
  })[0];
};

Printer.prototype.printBuffer = function(data, options) {
  var self = this;
  var args = buildArgs(options);
  var lp = spawn('lp', args);

  lp.stdin.write(data);
  lp.stdin.end();

  var job = new Job(lp);
  job.on('sent', function() {
    self.jobs.push(job);
  });

  job.on('completed', function() {
    self.jobs.splice(self.jobs.indexOf(job), 1);
  });

  return job;
};

Printer.prototype.printFile = function(filePath, options) {
  var self = this;
  var args = buildArgs(options);

  args.push('--');
  args.push(file);

  var lp = spawn('lp', args);

  var job = new Job(lp);
  job.on('sent', function() {
    self.jobs.push(job);
  });

  job.on('completed', function() {
    self.jobs.splice(self.jobs.indexOf(job), 1);
  });

  return job;
};

module.exports = Printer;
<|endoftext|>


<commit_before>module = function (namespace, module) {
    var global = global || window,
        key,
        leaf = global,
        name,
        root,
        tree;

    tree = namespace.split('.');

    while (tree.length) {
        name = tree.shift();

        // is capitalized to conform to best practice of naming modules?
        if (/[^A-Z]/.test(name[0])) {
            console.log('~~~~ namespacejs: Ruh roh. It\'s considered best practice to capitalize your namespace for ' + name +
                        'in namespace ' + namespace + ' to avoid naming collisions.');
        }

        root = leaf;
        leaf = root[name] = root[name] || {};
    }

    // empty object?
    for (key in leaf) {
        console.log('~~~~ namespacejs: Ruh roh. Potential namespace collision on ' + namespace);
        break;
    }

    module.call(leaf, global, root);
};
<commit_msg>Added hasOwnProperty to empty object check.<commit_after>module = function (namespace, module) {
    var global = global || window,
        key,
        leaf = global,
        name,
        root,
        tree;

    tree = namespace.split('.');

    while (tree.length) {
        name = tree.shift();

        // is capitalized to conform to best practice of naming modules?
        if (/[^A-Z]/.test(name[0])) {
            console.log('~~~~ namespacejs: Ruh roh. It\'s considered best practice to capitalize your namespace for ' + name +
                        'in namespace ' + namespace + ' to avoid naming collisions.');
        }

        root = leaf;
        leaf = root[name] = root[name] || {};
    }

    // empty object?
    for (key in leaf) {
        if (leaf.hasOwnProperty(key)) {
            console.log('~~~~ namespacejs: Ruh roh. Potential namespace collision on ' + namespace);
            break;
        }
    }

    module.call(leaf, global, root);
};
<|endoftext|>


<commit_before>const tsc = require('typescript');
const tsConfig = require('./tsconfig.json');

module.exports = {
  process(src, path) {
    if (path.endsWith('.ts')) {
      return tsc.transpile(src, tsConfig.compilerOptions, path, []);
    }
    return src;
  },
};<commit_msg>Add comment to explain preprocessor.js<commit_after>// Teaches jest to read typescript
const tsc = require('typescript');
const tsConfig = require('./tsconfig.json');

module.exports = {
  process(src, path) {
    if (path.endsWith('.ts')) {
      return tsc.transpile(src, tsConfig.compilerOptions, path, []);
    }
    return src;
  },
};<|endoftext|>


<commit_before>/*global google: false */ // This global comment is read by jslint

(function() {

  // The video manager manages a single video element, and all it's commands.
  var VideoManager = this.VideoManager = function(videoElement) {
    this.commandObjects  = {};
    this.manifestObjects = {};
    this.videoElement = videoElement;
    videoElement.videoManager = this;
    VideoManager.addInstance(this);
    videoElement.setAttribute("ontimeupdate", "VideoManager.update(this, this.videoManager);");
  };
  VideoManager.prototype.addCommand = function(command) {
    this.commandObjects[command.id] = command;
  };
  VideoManager.prototype.removeCommand = function(command) {
    delete this.commandObjects[command.id];
  };
  VideoManager.prototype.addManifestObject = function(manifestAttributes) {
    var manifest = {};
    var manifestId = "";
    for (var i = 0, pl = manifestAttributes.length; i < pl; i++) {
      for (var j = 0, nl = manifestAttributes[i].length; j < nl; j++) {
        var key = manifestAttributes[i].item(j).nodeName,
            data = manifestAttributes[i].item(j).nodeValue;
        if (key === "id") {
          manifestId = data;
        } else {
          manifest[key] = data;
        }
      }
    }
    this.manifestObjects[manifestId] = manifest;
  };
  VideoManager.prototype.removeManifestObject = function(itemId) {
    delete this.manifestObjects[itemId];
  };
  // Update is called on the video every time it's time changes.
  VideoManager.update = function(vid, manager) {
    var t = vid.currentTime;
    // Loops through all commands in the manager, preloading data, and calling onIn() or onOut().
    var commandObject = {};
    for (var i in manager.commandObjects) {
      if (manager.commandObjects.hasOwnProperty(i)) {
        commandObject = manager.commandObjects[i];
        if (commandObject.running && (commandObject.params["in"] > t || commandObject.params["out"] < t)) {
          commandObject.running = false;
          commandObject.onOut();
        }
      }
    }
    for (var j in manager.commandObjects) {
      if (manager.commandObjects.hasOwnProperty(j)) {
        commandObject = manager.commandObjects[j];
        if (!commandObject.loaded && (commandObject.params["in"] - 5) < t && commandObject.params["out"] > t) {
          commandObject.loaded = true;
          commandObject.preload();
        }
        if (!commandObject.running && commandObject.params["in"] < t && commandObject.params["out"] > t) {
          commandObject.running = true;
          commandObject.onIn();
        }
      }
    }
  };

  // Store VideoManager instances
  VideoManager.instances = [];
  VideoManager.instanceIds = {};
  VideoManager.addInstance = function(manager) {
    if (typeof manager.videoElement.id === 'undefined' || !manager.videoElement.id.length) {
      manager.videoElement.id = "__video" + VideoManager.instances.length;
    }
    VideoManager.instanceIds[manager.videoElement.id] = VideoManager.instances.length;
    VideoManager.instances.push(manager);
  };
  VideoManager.getInstanceById = function(name) {
    return VideoManager.instances[VideoManager.instanceIds[name]];
  };
  VideoManager.getInstance = function(index) {
    return VideoManager.instances[index];
  };

  // Simple function to convert 0:05 to 0.5 in seconds
  var toSeconds = function(time) {
    var t = time.split(":");
    if (t.length === 1) {
      return parseFloat(t[0], 10);
    } else if (t.length === 2) {
      return parseFloat(t[0], 10) + parseFloat(t[1] / 30, 10);
    } else if (t.length === 3) {
      return parseInt(t[0] * 60, 10) + parseFloat(t[1], 10) + parseFloat(t[2] / 30, 10);
    } else if (t.length === 4) {
      return parseInt(t[0] * 3600, 10) + parseInt(t[1] * 60, 10) + parseFloat(t[2], 10) + parseFloat(t[3] / 30, 10);
    }
  };

  ////////////////////////////////////////////////////////////////////////////
  // Command objects
  ////////////////////////////////////////////////////////////////////////////

  // Base class for all commands, SubtitleCommand, MapCommand, etc.
  var VideoCommand = function(name, params, text, videoManager) {
    this.params = {};
    this.text = text;
    this.videoManager = videoManager;
    this.running = false;
    this.loaded = false;
    this.onIn = function() {};
    this.onOut = function() {};
    this.preload = function() {};
    this.id = name + VideoCommand.count++;
    for (var i = 0, pl = params.length; i < pl; i++) {
      for (var j = 0, nl = params[i].length; j < nl; j++) {
        var key = params[i].item(j).nodeName,
            data = params[i].item(j).nodeValue;
        if (key === "in" || key === "out") {
          this.params[key] = toSeconds(data);
        } else {
          this.params[key] = data;
        }
      }
    }
    // Checkes for a resourceid and gets all the attributes from that resource
    if (this.params.resourceid) {
      for (var attributeName in this.videoManager.manifestObjects[this.params.resourceid]) {
        if (this.videoManager.manifestObjects[this.params.resourceid].hasOwnProperty(attributeName)) {
          this.params[attributeName] = this.videoManager.manifestObjects[this.params.resourceid][attributeName];
        }
      }
    }
  };
  VideoCommand.count = 0;

  ////////////////////////////////////////////////////////////////////////////
  // Subtitle Command
  ////////////////////////////////////////////////////////////////////////////

  var SubtitleCommand = function(name, params, text, videoManager) {
    VideoCommand.call(this, name, params, text, videoManager);
    this.onIn = function() {
      var i = document.getElementById("language").selectedIndex;
      google.language.translate(this.text, '', document.getElementById("language").options[i].getAttribute("val"), function(result) {
        document.getElementById("sub").innerHTML  = result.translation;
      });

    };
    this.onOut = function() {
      document.getElementById("sub").innerHTML  = "";
    };
  };

  ////////////////////////////////////////////////////////////////////////////
  // TagThisPerson Command
  ////////////////////////////////////////////////////////////////////////////

  var TagCommand = function(name, params, text, videoManager) {
    VideoCommand.call(this, name, params, text, videoManager);
    this.onIn = function() {
      TagCommand.people.contains[this.text] = this.text;
      document.getElementById("inthisvideo").innerHTML  = TagCommand.people.toString();
    };
    this.onOut = function() {
      delete TagCommand.people.contains[this.text];
      document.getElementById("inthisvideo").innerHTML  = TagCommand.people.toString();
    };
  };
  TagCommand.people = {
    contains: {},
    toString: function() {
      var r = [];
      for (var i in this.contains) {
        if (this.contains.hasOwnProperty(i)) {
          r.push(" " + this.contains[i]);
        }
      }
      return r.toString();
    }
  };

  ////////////////////////////////////////////////////////////////////////////
  // Map Command
  ////////////////////////////////////////////////////////////////////////////

  var MapCommand = function(name, params, text, videoManager) {
    VideoCommand.call(this, name, params, text, videoManager);
    this.params.zoom = parseInt(this.params.zoom, 10);
    // load the map
    // http://code.google.com/apis/maps/documentation/javascript/reference.html#MapOptions  <-- Map API
    this.location = new google.maps.LatLng(this.params.lat, this.params.long);
    if (!MapCommand.map) {
      MapCommand.map = new google.maps.Map(document.getElementById(this.params.target), {mapTypeId: google.maps.MapTypeId.HYBRID});
      MapCommand.map.setCenter(new google.maps.LatLng(0, 0));
      MapCommand.map.setZoom(0);
    }
    this.onIn = function() {
      MapCommand.map.setCenter(this.location);
      MapCommand.map.setZoom(this.params.zoom);
    };
    this.onOut = function() {
      MapCommand.map.setCenter(new google.maps.LatLng(0, 0));
      MapCommand.map.setZoom(0);
    };
  };

  ////////////////////////////////////////////////////////////////////////////
  // Twitter Command
  ////////////////////////////////////////////////////////////////////////////

  var TwitterCommand = function(name, params, text, videoManager) {}; // http://twitter.com/celinecelines

  ////////////////////////////////////////////////////////////////////////////
  // Footnote Command
  ////////////////////////////////////////////////////////////////////////////

	var FootnoteCommand = function(name, params, text) {
    VideoCommand.call(this, name, params, text);
    this.onIn = function() {
			//if the user specifies a target div for this in the xml use it
			//otherwise make a new div
			if( this.params.target ) {
				document.getElementById( this.params.target ).innerHTML  = this.text;
			} else {
				//this will be done later in ticket #46 (support default div)
				//for this case i would think get the parent div of the <video> and append a new div to it
			}
    };
    this.onOut = function() {
			if( this.params.target ) {
				document.getElementById( this.params.target ).innerHTML  = "";
			} else {
				//this will be done later in ticket #46 (support default div)
			}
    };
  };

  // Wrapper for accessing commands by name
  // commands[name].create() returns a new command of type name
  // Not sure if this is the best way; maybe it's too fancy?
  // I liked it more than a switch, though
  var commands = {
    subtitle: {
      create: function(name, params, text, videoManager) {
        return new SubtitleCommand(name, params, text, videoManager);
      }
    },
    videotag: {
      create: function(name, params, text, videoManager) {
        return new TagCommand(name, params, text, videoManager);
      }
    },
    location: {
      create: function(name, params, text, videoManager) {
        return new MapCommand(name, params, text, videoManager);
      }
    },
	footnote: {
		create: function(name, params, text) {
        return new FootnoteCommand(name, params, text);
      }
    }
  };

  ////////////////////////////////////////////////////////////////////////////
  // XML Parser
  ////////////////////////////////////////////////////////////////////////////

  // Parses xml into command objects and adds them to the video manager
  var parse = function(xmlDoc, videoManager) {

    var parseNode = function(node, attributes, manifest) {
      var allAttributes = attributes.slice(0);
      allAttributes.push(node.attributes);
      var childNodes = node.childNodes;
      if (childNodes.length < 1 || (childNodes.length === 1 && childNodes[0].nodeType === 3)) {
        if (!manifest) {
          videoManager.addCommand(commands[node.nodeName].create(node.nodeName, allAttributes, node.textContent, videoManager));
        } else {
          videoManager.addManifestObject(allAttributes);
        }
      } else {
        for (var i = 0; i < childNodes.length; i++) {
          if (childNodes[i].nodeType === 1) {
            parseNode(childNodes[i], allAttributes, manifest);
          }
        }
      }
    };

    for (var j = 0, dl = xmlDoc.length; j < dl; j++) {
      var x = xmlDoc[j].documentElement.childNodes;
      for (var i = 0, xl = x.length; i < xl; i++) {
        if (x[i].nodeType === 1) {
          if (x[i].nodeName === "manifest") {
            parseNode(x[i], [], true);
          } else {
            parseNode(x[i], [], false);
          }
        }
      }
    }
  };

  // Loads an external xml file, and returns the xml object
  var loadXMLDoc = function(name) {
    var xhttp = new XMLHttpRequest();
    if (xhttp) {
      xhttp.open("GET", name, false);
      xhttp.send();
      return xhttp.responseXML;
    } else {
      return false;
    }
  };

  // Automatic Initialization Method
  var init = function() {
    var video = document.getElementsByTagName('video');
    for (var i = 0, l = video.length; i < l; i++) {
      var videoSources = video[i].getAttribute('data-timeline-sources');
      if (videoSources) {
        var filenames = videoSources.split(' ');
        var xml = [];
        for (var j=0, fl=filenames.length; j<fl; j++) {
          if (filenames[j]) {
            xml.push(loadXMLDoc(filenames[j]));
          }
        }
        var manager = new VideoManager(video[i]);
        parse(xml, manager);
      }
    }
  };
  document.addEventListener('DOMContentLoaded', function() {
    init();
  }, false);

}());

<commit_msg>merging in scotts branch 47 for ticket #47<commit_after>/*global google: false */ // This global comment is read by jslint

(function() {

  // The video manager manages a single video element, and all it's commands.
  var VideoManager = this.VideoManager = function(videoElement) {
    this.commandObjects  = {};
    this.manifestObjects = {};
    this.videoElement = videoElement;
    videoElement.videoManager = this;
    VideoManager.addInstance(this);
    videoElement.setAttribute("ontimeupdate", "VideoManager.update(this, this.videoManager);");
  };
  VideoManager.prototype.addCommand = function(command) {
    this.commandObjects[command.id] = command;
  };
  VideoManager.prototype.removeCommand = function(command) {
    delete this.commandObjects[command.id];
  };
  VideoManager.prototype.addManifestObject = function(manifestAttributes) {
    var manifest = {};
    var manifestId = "";
    for (var i = 0, pl = manifestAttributes.length; i < pl; i++) {
      for (var j = 0, nl = manifestAttributes[i].length; j < nl; j++) {
        var key = manifestAttributes[i].item(j).nodeName,
            data = manifestAttributes[i].item(j).nodeValue;
        if (key === "id") {
          manifestId = data;
        } else {
          manifest[key] = data;
        }
      }
    }
    this.manifestObjects[manifestId] = manifest;
  };
  VideoManager.prototype.removeManifestObject = function(itemId) {
    delete this.manifestObjects[itemId];
  };
  // Update is called on the video every time it's time changes.
  VideoManager.update = function(vid, manager) {
    var t = vid.currentTime;
    // Loops through all commands in the manager, preloading data, and calling onIn() or onOut().
    var commandObject = {};
    for (var i in manager.commandObjects) {
      if (manager.commandObjects.hasOwnProperty(i)) {
        commandObject = manager.commandObjects[i];
        if (commandObject.running && (commandObject.params["in"] > t || commandObject.params["out"] < t)) {
          commandObject.running = false;
          commandObject.onOut();
        }
      }
    }
    for (var j in manager.commandObjects) {
      if (manager.commandObjects.hasOwnProperty(j)) {
        commandObject = manager.commandObjects[j];
        if (!commandObject.loaded && (commandObject.params["in"] - 5) < t && commandObject.params["out"] > t) {
          commandObject.loaded = true;
          commandObject.preload();
        }
        if (!commandObject.running && commandObject.params["in"] < t && commandObject.params["out"] > t) {
          commandObject.running = true;
          commandObject.onIn();
        }
      }
    }
  };

  // Store VideoManager instances
  VideoManager.instances = [];
  VideoManager.instanceIds = {};
  VideoManager.addInstance = function(manager) {
    if (typeof manager.videoElement.id === 'undefined' || !manager.videoElement.id.length) {
      manager.videoElement.id = "__video" + VideoManager.instances.length;
    }
    VideoManager.instanceIds[manager.videoElement.id] = VideoManager.instances.length;
    VideoManager.instances.push(manager);
  };
  VideoManager.getInstanceById = function(name) {
    return VideoManager.instances[VideoManager.instanceIds[name]];
  };
  VideoManager.getInstance = function(index) {
    return VideoManager.instances[index];
  };

  // Simple function to convert 0:05 to 0.5 in seconds
  var toSeconds = function(time) {
    var t = time.split(":");
    if (t.length === 1) {
      return parseFloat(t[0], 10);
    } else if (t.length === 2) {
      return parseFloat(t[0], 10) + parseFloat(t[1] / 30, 10);
    } else if (t.length === 3) {
      return parseInt(t[0] * 60, 10) + parseFloat(t[1], 10) + parseFloat(t[2] / 30, 10);
    } else if (t.length === 4) {
      return parseInt(t[0] * 3600, 10) + parseInt(t[1] * 60, 10) + parseFloat(t[2], 10) + parseFloat(t[3] / 30, 10);
    }
  };

  ////////////////////////////////////////////////////////////////////////////
  // Command objects
  ////////////////////////////////////////////////////////////////////////////

  // Base class for all commands, SubtitleCommand, MapCommand, etc.
  var VideoCommand = function(name, params, text, videoManager) {
    this.params = {};
    this.text = text;
    this.videoManager = videoManager;
    this.running = false;
    this.loaded = false;
    this.onIn = function() {};
    this.onOut = function() {};
    this.preload = function() {};
    this.id = name + VideoCommand.count++;
    this.params["in"] = "0";
    this.params["out"] = this.videoManager.videoElement.duration;
    for (var i = 0, pl = params.length; i < pl; i++) {
      for (var j = 0, nl = params[i].length; j < nl; j++) {
        var key = params[i].item(j).nodeName,
            data = params[i].item(j).nodeValue;
        if (key === "in" || key === "out") {
          this.params[key] = toSeconds(data);
        } else {
          this.params[key] = data;
        }
      }
    }
    // Checkes for a resourceid and gets all the attributes from that resource
    if (this.params.resourceid) {
      for (var attributeName in this.videoManager.manifestObjects[this.params.resourceid]) {
        if (this.videoManager.manifestObjects[this.params.resourceid].hasOwnProperty(attributeName)) {
          this.params[attributeName] = this.videoManager.manifestObjects[this.params.resourceid][attributeName];
        }
      }
    }
  };
  VideoCommand.count = 0;

  ////////////////////////////////////////////////////////////////////////////
  // Subtitle Command
  ////////////////////////////////////////////////////////////////////////////

  // Child commands. Uses onIn() and onOut() to do time based operations
  var SubtitleCommand = function(name, params, text, videoManager) {
    VideoCommand.call(this, name, params, text, videoManager);
    this.onIn = function() {
      var i = document.getElementById("language").selectedIndex;
      google.language.translate(this.text, '', document.getElementById("language").options[i].getAttribute("val"), function(result) {
        document.getElementById("sub").innerHTML  = result.translation;
      });

    };
    this.onOut = function() {
      document.getElementById("sub").innerHTML  = "";
    };
  };

  ////////////////////////////////////////////////////////////////////////////
  // TagThisPerson Command
  ////////////////////////////////////////////////////////////////////////////

  var TagCommand = function(name, params, text, videoManager) {
    VideoCommand.call(this, name, params, text, videoManager);
    this.onIn = function() {
      TagCommand.people.contains[this.text] = this.text;
      document.getElementById("inthisvideo").innerHTML  = TagCommand.people.toString();
    };
    this.onOut = function() {
      delete TagCommand.people.contains[this.text];
      document.getElementById("inthisvideo").innerHTML  = TagCommand.people.toString();
    };
  };
  TagCommand.people = {
    contains: {},
    toString: function() {
      var r = [];
      for (var i in this.contains) {
        if (this.contains.hasOwnProperty(i)) {
          r.push(" " + this.contains[i]);
        }
      }
      return r.toString();
    }
  };

  ////////////////////////////////////////////////////////////////////////////
  // Map Command
  ////////////////////////////////////////////////////////////////////////////

  var MapCommand = function(name, params, text, videoManager) {
    VideoCommand.call(this, name, params, text, videoManager);
    this.params.zoom = parseInt(this.params.zoom, 10);
    // load the map
    // http://code.google.com/apis/maps/documentation/javascript/reference.html#MapOptions  <-- Map API
    this.location = new google.maps.LatLng(this.params.lat, this.params.long);
    if (!MapCommand.map) {
      MapCommand.map = new google.maps.Map(document.getElementById(this.params.target), {mapTypeId: google.maps.MapTypeId.HYBRID});
      MapCommand.map.setCenter(new google.maps.LatLng(0, 0));
      MapCommand.map.setZoom(0);
    }
    this.onIn = function() {
      MapCommand.map.setCenter(this.location);
      MapCommand.map.setZoom(this.params.zoom);
    };
    this.onOut = function() {
      MapCommand.map.setCenter(new google.maps.LatLng(0, 0));
      MapCommand.map.setZoom(0);
    };
  };

  ////////////////////////////////////////////////////////////////////////////
  // Twitter Command
  ////////////////////////////////////////////////////////////////////////////

  var TwitterCommand = function(name, params, text, videoManager) {}; // http://twitter.com/celinecelines

  ////////////////////////////////////////////////////////////////////////////
  // Footnote Command
  ////////////////////////////////////////////////////////////////////////////

	var FootnoteCommand = function(name, params, text) {
    VideoCommand.call(this, name, params, text);
    this.onIn = function() {
			//if the user specifies a target div for this in the xml use it
			//otherwise make a new div
			if( this.params.target ) {
				document.getElementById( this.params.target ).innerHTML  = this.text;
			} else {
				//this will be done later in ticket #46 (support default div)
				//for this case i would think get the parent div of the <video> and append a new div to it
			}
    };
    this.onOut = function() {
			if( this.params.target ) {
				document.getElementById( this.params.target ).innerHTML  = "";
			} else {
				//this will be done later in ticket #46 (support default div)
			}
    };
  };

  // Wrapper for accessing commands by name
  // commands[name].create() returns a new command of type name
  // Not sure if this is the best way; maybe it's too fancy?
  // I liked it more than a switch, though
  var commands = {
    subtitle: {
      create: function(name, params, text, videoManager) {
        return new SubtitleCommand(name, params, text, videoManager);
      }
    },
    videotag: {
      create: function(name, params, text, videoManager) {
        return new TagCommand(name, params, text, videoManager);
      }
    },
    location: {
      create: function(name, params, text, videoManager) {
        return new MapCommand(name, params, text, videoManager);
      }
    },
	footnote: {
		create: function(name, params, text) {
        return new FootnoteCommand(name, params, text);
      }
    }
  };

  ////////////////////////////////////////////////////////////////////////////
  // XML Parser
  ////////////////////////////////////////////////////////////////////////////

  // Parses xml into command objects and adds them to the video manager
  var parse = function(xmlDoc, videoManager) {

    var parseNode = function(node, attributes, manifest) {
      var allAttributes = attributes.slice(0);
      allAttributes.push(node.attributes);
      var childNodes = node.childNodes;
      if (childNodes.length < 1 || (childNodes.length === 1 && childNodes[0].nodeType === 3)) {
        if (!manifest) {
          videoManager.addCommand(commands[node.nodeName].create(node.nodeName, allAttributes, node.textContent, videoManager));
        } else {
          videoManager.addManifestObject(allAttributes);
        }
      } else {
        for (var i = 0; i < childNodes.length; i++) {
          if (childNodes[i].nodeType === 1) {
            parseNode(childNodes[i], allAttributes, manifest);
          }
        }
      }
    };

    for (var j = 0, dl = xmlDoc.length; j < dl; j++) {
      var x = xmlDoc[j].documentElement.childNodes;
      for (var i = 0, xl = x.length; i < xl; i++) {
        if (x[i].nodeType === 1) {
          if (x[i].nodeName === "manifest") {
            parseNode(x[i], [], true);
          } else {
            parseNode(x[i], [], false);
          }
        }
      }
    }
  };

  // Loads an external xml file, and returns the xml object
  var loadXMLDoc = function(name) {
    var xhttp = new XMLHttpRequest();
    if (xhttp) {
      xhttp.open("GET", name, false);
      xhttp.send();
      return xhttp.responseXML;
    } else {
      return false;
    }
  };

  // Automatic Initialization Method
  var init = function() {
    var video = document.getElementsByTagName('video');
    for (var i = 0, l = video.length; i < l; i++) {
      var videoSources = video[i].getAttribute('data-timeline-sources');
      if (videoSources) {
        var filenames = videoSources.split(' ');
        var xml = [];
        for (var j=0, fl=filenames.length; j<fl; j++) {
          if (filenames[j]) {
            xml.push(loadXMLDoc(filenames[j]));
          }
        }
        var manager = new VideoManager(video[i]);
        parse(xml, manager);
      }
    }
  };
  document.addEventListener('DOMContentLoaded', function() {
    init();
  }, false);

}());

<|endoftext|>


<commit_before>var timeoutID1;
var timeoutID2;

/**
 * Prints the given error message.
 * @param {string} msg - The error message to print.
 */
function error(msg) {  // eslint-disable-line no-unused-vars
  if (timeoutID1) {
    window.clearTimeout(timeoutID1);
  }
  if (timeoutID2) {
    window.clearTimeout(timeoutID2);
  }
  var element = document.getElementById('msg');
  element.innerHTML = msg;
  element.className = 'error';
  timeoutID1 = window.setTimeout(function() {
    if (element.className !== 'error') {
      return;
    }
    element.className = 'error-hide';
    timeoutID2 = window.setTimeout(function() {
      element.innerHTML = '';
      element.className = '';
    }, 500);
  }, 10000);
}

/**
 * Prints the given informational message.
 * @param {string} msg - The information message to print.
 */
function info(msg) {
  var element = document.getElementById('msg');
  element.innerHTML = msg;
  element.className = 'info';
}

/**
 * Converts an address object into a dictionary.
 * @param {PaymentAddress} addr - The address to convert.
 * @return {object} The resulting dictionary.
 */
function toDictionary(addr) {  // eslint-disable-line no-unused-vars
  var dict = {};
  if (addr) {
    dict.country = addr.country;
    dict.region = addr.region;
    dict.city = addr.city;
    dict.dependentLocality = addr.dependentLocality;
    dict.addressLine = addr.addressLine;
    dict.postalCode = addr.postalCode;
    dict.sortingCode = addr.sortingCode;
    dict.languageCode = addr.languageCode;
    dict.organization = addr.organization;
    dict.recipient = addr.recipient;
    dict.careOf = addr.careOf;
    dict.phone = addr.phone;
  }
  return dict;
}

/**
 * Called when the payment request is complete.
 * @param {string} message - The human readable message to display.
 * @param {PaymentResponse} respo - The payment response.
 */
function done(message, resp) {  // eslint-disable-line no-unused-vars
  var element = document.getElementById('contents');
  element.innerHTML = message;

  var shippingOption =
      resp.shippingOption ? 'shipping option: ' + shippingOption + '
' : '';

  var shippingAddress = resp.shippingAddress ?
      'shipping address: ' +
      JSON.stringify(toDictionary(shippingAddress), undefined, 2)) +
      '
': '';

  var instrument =
      'instrument:' + JSON.stringify(instrumentDetails, undefined, 2) + '
';

  var method = 'method: ' + methodName + '
';
  var email = resp.payerEmail ? 'email: ' + payerEmail + '
' : '';
  var phone = resp.payerPhone ? 'phone: ' + payerPhone + '
' : '';

  info(email + phone + shippingOption + shippingAddress + method + instrument);
}
<commit_msg>Update contact tests as well<commit_after>var timeoutID1;
var timeoutID2;

/**
 * Prints the given error message.
 * @param {string} msg - The error message to print.
 */
function error(msg) {  // eslint-disable-line no-unused-vars
  if (timeoutID1) {
    window.clearTimeout(timeoutID1);
  }
  if (timeoutID2) {
    window.clearTimeout(timeoutID2);
  }
  var element = document.getElementById('msg');
  element.innerHTML = msg;
  element.className = 'error';
  timeoutID1 = window.setTimeout(function() {
    if (element.className !== 'error') {
      return;
    }
    element.className = 'error-hide';
    timeoutID2 = window.setTimeout(function() {
      element.innerHTML = '';
      element.className = '';
    }, 500);
  }, 10000);
}

/**
 * Prints the given informational message.
 * @param {string} msg - The information message to print.
 */
function info(msg) {
  var element = document.getElementById('msg');
  element.innerHTML = msg;
  element.className = 'info';
}

/**
 * Converts an address object into a dictionary.
 * @param {PaymentAddress} addr - The address to convert.
 * @return {object} The resulting dictionary.
 */
function toDictionary(addr) {  // eslint-disable-line no-unused-vars
  var dict = {};
  if (addr) {
    dict.country = addr.country;
    dict.region = addr.region;
    dict.city = addr.city;
    dict.dependentLocality = addr.dependentLocality;
    dict.addressLine = addr.addressLine;
    dict.postalCode = addr.postalCode;
    dict.sortingCode = addr.sortingCode;
    dict.languageCode = addr.languageCode;
    dict.organization = addr.organization;
    dict.recipient = addr.recipient;
    dict.careOf = addr.careOf;
    dict.phone = addr.phone;
  }
  return dict;
}

/**
 * Called when the payment request is complete.
 * @param {string} message - The human readable message to display.
 * @param {PaymentResponse} respo - The payment response.
 */
function done(message, resp) {  // eslint-disable-line no-unused-vars
  var element = document.getElementById('contents');
  element.innerHTML = message;

  var shippingOption =
      resp.shippingOption ? 'shipping option: ' + shippingOption + '
' : '';

  var shippingAddress = resp.shippingAddress ?
      'shipping address: ' +
          JSON.stringify(toDictionary(shippingAddress), undefined, 2) +
          '
' :
      '';

  var instrument =
      'instrument:' + JSON.stringify(instrumentDetails, undefined, 2) + '
';

  var method = 'method: ' + methodName + '
';
  var email = resp.payerEmail ? 'email: ' + payerEmail + '
' : '';
  var phone = resp.payerPhone ? 'phone: ' + payerPhone + '
' : '';

  info(email + phone + shippingOption + shippingAddress + method + instrument);
}
<|endoftext|>