<commit_before>/** @jsx hJSX */
import cuid from 'cuid';
import decorator from './decorator';
import domQuery from './domQuery';
import intent from './intent';
import model from './model';
import props from './props';
import view from './view';
import {clone} from 'ramda';
import {predicateObjectOfObservable} from '@cyclic/util-predicate';
import {Rx} from '@cycle/core';

const COMPONENT_NAME = `molecule-InputContainer`;

function initAddOns({DOM, state$}) {
  return state$.map(
    (state) => {
      const {addOns} = state;

      return addOns.length > 0 ?
        addOns.map(
          (addOnFunc) => {
            if (typeof addOnFunc === `function`) {
              return addOnFunc(
                {DOM, props$: Rx.Observable.just(clone(state))}
              ).DOM;
            }
          }
        ) :
        [];
    }
  );
}

function InputContainer(sources) {
  const {DOM} = sources;
  const props$ = predicateObjectOfObservable(props)(sources.props$);
  const {id = cuid()} = sources;
  const actions = intent({DOM, id});
  const layout = domQuery({componentName: COMPONENT_NAME, DOM, id});
  const state$ = model(
    {actions, componentName: COMPONENT_NAME, layout, props$}
  );
  const decoration$ = decorator({actions, layout, state$});
  const addOn$s$ = initAddOns({DOM, state$});

  return {
    DOM: view({addOn$s$, decoration$, id, state$}),
    id,
    state$: state$.map((state) => clone(state)),
  };
}

export {COMPONENT_NAME};

export default InputContainer;
<commit_msg>refactor(InputContainer): remove redundant type check<commit_after>/** @jsx hJSX */
import cuid from 'cuid';
import decorator from './decorator';
import domQuery from './domQuery';
import intent from './intent';
import model from './model';
import props from './props';
import view from './view';
import {clone} from 'ramda';
import {predicateObjectOfObservable} from '@cyclic/util-predicate';
import {Rx} from '@cycle/core';

const COMPONENT_NAME = `molecule-InputContainer`;

function initAddOns({DOM, state$}) {
  return state$.map(
    (state) => {
      const {addOns} = state;

      return addOns.length > 0 ?
        addOns.map(
          (addOnFunc) => addOnFunc(
            {DOM, props$: Rx.Observable.just(clone(state))}
          ).DOM
        ) :
        [];
    }
  );
}

function InputContainer(sources) {
  const {DOM} = sources;
  const props$ = predicateObjectOfObservable(props)(sources.props$);
  const {id = cuid()} = sources;
  const actions = intent({DOM, id});
  const layout = domQuery({componentName: COMPONENT_NAME, DOM, id});
  const state$ = model(
    {actions, componentName: COMPONENT_NAME, layout, props$}
  );
  const decoration$ = decorator({actions, layout, state$});
  const addOn$s$ = initAddOns({DOM, state$});

  return {
    DOM: view({addOn$s$, decoration$, id, state$}),
    id,
    state$: state$.map((state) => clone(state)),
  };
}

export {COMPONENT_NAME};

export default InputContainer;
<|endoftext|>


<commit_before>Meteor.publish('posts', function () {
  "use strict";
  var result = Posts.find({}, {
    sort: {
      time: -1
    },
    limit: 8
  });
  return result;
});
<commit_msg>Set post limit to 30<commit_after>Meteor.publish('posts', function () {
  "use strict";
  var result = Posts.find({}, {
    sort: {
      time: -1
    },
    limit: 30
  });
  return result;
});
<|endoftext|>


<commit_before>define([
    "text!src/templates/form.html"
], function(templateForm) {
    var hr = codebox.require("hr/hr");
    var commands = codebox.require("core/commands");
    var FormView = codebox.require("views/form");

    var Tab = codebox.tabs.Panel.extend({
        className: "component-settings",
        template: templateForm,
        events: {
            "click .do-submit": "onSubmit",
            "click .do-open-json": "onOpenJson"
        },

        initialize: function() {
            Tab.__super__.initialize.apply(this, arguments);

            this.form = new FormView({
                schema: codebox.settings.toSchema(),
                values: codebox.settings.exportJson()
            });
        },

        render: function() {
            this.form.detach();
            this.form.update();

            return Tab.__super__.render.apply(this, arguments);
        },

        finish: function() {
            this.form.$el.appendTo(this.$(".form-content"));

            return Tab.__super__.finish.apply(this, arguments);
        },

        // Submit form
        onSubmit: function(e) {
            if (e) e.preventDefault();

            var data = this.form.getValues();
            console.log("submit", data);
            codebox.settings.importJSON(data);
        },

        // Open as json
        onOpenJson: function(e) {
            if (e) e.preventDefault();

            return commands.run("file.open", {
                file: codebox.settings.getFile()
            });
        }
    });

    return Tab;
});<commit_msg>Update settings page when values changed<commit_after>define([
    "text!src/templates/form.html"
], function(templateForm) {
    var _ = codebox.require("hr/utils");
    var hr = codebox.require("hr/hr");
    var commands = codebox.require("core/commands");
    var FormView = codebox.require("views/form");

    var Tab = codebox.tabs.Panel.extend({
        className: "component-settings",
        template: templateForm,
        events: {
            "click .do-submit": "onSubmit",
            "click .do-open-json": "onOpenJson"
        },

        initialize: function() {
            Tab.__super__.initialize.apply(this, arguments);

            this.form = new FormView({
                schema: codebox.settings.toSchema(),
                values: codebox.settings.exportJson()
            });

            this.listenTo(codebox.settings, "change", function() {
                _.defer(this.form.setValues.bind(this.form), codebox.settings.exportJson());
            });
        },

        render: function() {
            this.form.detach();
            this.form.update();

            return Tab.__super__.render.apply(this, arguments);
        },

        finish: function() {
            this.form.$el.appendTo(this.$(".form-content"));

            return Tab.__super__.finish.apply(this, arguments);
        },

        // Submit form
        onSubmit: function(e) {
            if (e) e.preventDefault();

            var data = this.form.getValues();
            codebox.settings.importJSON(data);
        },

        // Open as json
        onOpenJson: function(e) {
            if (e) e.preventDefault();

            return commands.run("file.open", {
                file: codebox.settings.getFile()
            });
        }
    });

    return Tab;
});<|endoftext|>


<commit_before>define(['helper'], function (helper) {
  var self = {};

  var ctx;
  var width;
  var height;
  var transform;
  var highlight;

  var NODE_RADIUS = 15;
  var LINE_RADIUS = 12;

  function drawDetailNode(d) {
    if (transform.k > 1 && d.o.is_online) {
      helper.positionClients(ctx, d, Math.PI, d.o, 15);
      ctx.beginPath();
      var name = d.o.node_id;
      if (d.o) {
        name = d.o.hostname;
      }
      ctx.textAlign = 'center';
      ctx.fillStyle = config.forceGraph.labelColor;
      ctx.fillText(name, d.x, d.y + 20);
    }
  }

  function drawHighlightNode(d) {
    if (highlight && highlight.type === 'node' && d.o.node_id === highlight.id) {
      ctx.arc(d.x, d.y, NODE_RADIUS * 1.5, 0, 2 * Math.PI);
      ctx.fillStyle = config.forceGraph.highlightColor;
      ctx.fill();
      ctx.beginPath();
    }
  }

  function drawHighlightLink(d, to) {
    if (highlight && highlight.type === 'link' && d.o.id === highlight.id) {
      ctx.lineTo(to[0], to[1]);
      ctx.strokeStyle = config.forceGraph.highlightColor;
      ctx.lineWidth = LINE_RADIUS * 2;
      ctx.lineCap = 'round';
      ctx.stroke();
      to = [d.source.x, d.source.y];
    }
    return to;
  }

  self.drawNode = function drawNode(d) {
    if (d.x < transform.invertX(0) || d.y < transform.invertY(0) || transform.invertX(width) < d.x || transform.invertY(height) < d.y) {
      return;
    }
    ctx.beginPath();

    drawHighlightNode(d);

    var batmanDomain = 'ffmd';

    if (d.o.is_online) {
      ctx.arc(d.x, d.y, 8, 0, 2 * Math.PI);
      if (d.o.is_gateway) {
        ctx.rect(d.x - 9, d.y - 9, 18, 18);
      }
      if (d.o.domain === batmanDomain) {
        ctx.fillStyle = config.forceGraph.nodeBatmanColor;
      } else if (d.o.gateway_nexthop === d.o.gateway && !d.o.is_gateway) {
        ctx.fillStyle = config.forceGraph.nodeUplinkColor;
      } else {
        ctx.fillStyle = config.forceGraph.nodeColor;
      }
    } else {
      ctx.arc(d.x, d.y, 6, 0, 2 * Math.PI);
      if (d.o.domain === batmanDomain) {
        ctx.fillStyle = config.forceGraph.nodeBatmanOffline;
      } else {
        ctx.fillStyle = config.forceGraph.nodeOfflineColor;
      }
    }

    ctx.fill();

    drawDetailNode(d);
  };

  self.drawLink = function drawLink(d) {
    var zero = transform.invert([0, 0]);
    var area = transform.invert([width, height]);
    if (d.source.x < zero[0] && d.target.x < zero[0] || d.source.y < zero[1] && d.target.y < zero[1] ||
      d.source.x > area[0] && d.target.x > area[0] || d.source.y > area[1] && d.target.y > area[1]) {
      return;
    }
    ctx.beginPath();
    ctx.moveTo(d.source.x, d.source.y);
    var to = [d.target.x, d.target.y];

    to = drawHighlightLink(d, to);

    var grd = ctx.createLinearGradient(d.source.x, d.source.y, d.target.x, d.target.y);
    grd.addColorStop(0.45, d.color);
    grd.addColorStop(0.55, d.color_to);

    ctx.lineTo(to[0], to[1]);
    ctx.strokeStyle = grd;
    if (d.o.type.indexOf('vpn') === 0) {
      ctx.globalAlpha = 0.2;
      ctx.lineWidth = 1.5;
    } else {
      ctx.globalAlpha = 0.8;
      ctx.lineWidth = 2.5;
    }
    ctx.stroke();
    ctx.globalAlpha = 1;
  };

  self.setCTX = function setCTX(newValue) {
    ctx = newValue;
  };

  self.setHighlight = function setHighlight(newValue) {
    highlight = newValue;
  };

  self.setTransform = function setTransform(newValue) {
    transform = newValue;
  };

  self.setMaxArea = function setMaxArea(newWidth, newHeight) {
    width = newWidth;
    height = newHeight;
  };

  return self;
});
<commit_msg>Graph-Ansicht: Batman-Knoten - UpLink-Knoten nun in gelb.<commit_after>define(['helper'], function (helper) {
  var self = {};

  var ctx;
  var width;
  var height;
  var transform;
  var highlight;

  var NODE_RADIUS = 15;
  var LINE_RADIUS = 12;

  function drawDetailNode(d) {
    if (transform.k > 1 && d.o.is_online) {
      helper.positionClients(ctx, d, Math.PI, d.o, 15);
      ctx.beginPath();
      var name = d.o.node_id;
      if (d.o) {
        name = d.o.hostname;
      }
      ctx.textAlign = 'center';
      ctx.fillStyle = config.forceGraph.labelColor;
      ctx.fillText(name, d.x, d.y + 20);
    }
  }

  function drawHighlightNode(d) {
    if (highlight && highlight.type === 'node' && d.o.node_id === highlight.id) {
      ctx.arc(d.x, d.y, NODE_RADIUS * 1.5, 0, 2 * Math.PI);
      ctx.fillStyle = config.forceGraph.highlightColor;
      ctx.fill();
      ctx.beginPath();
    }
  }

  function drawHighlightLink(d, to) {
    if (highlight && highlight.type === 'link' && d.o.id === highlight.id) {
      ctx.lineTo(to[0], to[1]);
      ctx.strokeStyle = config.forceGraph.highlightColor;
      ctx.lineWidth = LINE_RADIUS * 2;
      ctx.lineCap = 'round';
      ctx.stroke();
      to = [d.source.x, d.source.y];
    }
    return to;
  }

  self.drawNode = function drawNode(d) {
    if (d.x < transform.invertX(0) || d.y < transform.invertY(0) || transform.invertX(width) < d.x || transform.invertY(height) < d.y) {
      return;
    }
    ctx.beginPath();

    drawHighlightNode(d);

    var batmanDomain = 'ffmd';

    if (d.o.domain === batmanDomain) {
      if (d.o.is_online) {
        ctx.arc(d.x, d.y, 8, 0, 2 * Math.PI);
        if (d.o.is_gateway) {
          ctx.rect(d.x - 9, d.y - 9, 18, 18);
        }
        if (d.o.gateway_nexthop === d.o.gateway && !d.o.is_gateway) {
          ctx.fillStyle = config.forceGraph.nodeBatmanUplinkColor;
        } else {
          ctx.fillStyle = config.forceGraph.nodeBatmanColor;
        }
      } else {
        ctx.arc(d.x, d.y, 6, 0, 2 * Math.PI);
        ctx.fillStyle = config.forceGraph.nodeBatmanOfflineColor;
      }
    } else {
      if (d.o.is_online) {
        ctx.arc(d.x, d.y, 8, 0, 2 * Math.PI);
        if (d.o.is_gateway) {
          ctx.rect(d.x - 9, d.y - 9, 18, 18);
        }
        if (d.o.gateway_nexthop === d.o.gateway && !d.o.is_gateway) {
          ctx.fillStyle = config.forceGraph.nodeUplinkColor;
        } else {
          ctx.fillStyle = config.forceGraph.nodeColor;
        }
      } else {
        ctx.arc(d.x, d.y, 6, 0, 2 * Math.PI);
        ctx.fillStyle = config.forceGraph.nodeOfflineColor;
      }
    }

    ctx.fill();

    drawDetailNode(d);
  };

  self.drawLink = function drawLink(d) {
    var zero = transform.invert([0, 0]);
    var area = transform.invert([width, height]);
    if (d.source.x < zero[0] && d.target.x < zero[0] || d.source.y < zero[1] && d.target.y < zero[1] ||
      d.source.x > area[0] && d.target.x > area[0] || d.source.y > area[1] && d.target.y > area[1]) {
      return;
    }
    ctx.beginPath();
    ctx.moveTo(d.source.x, d.source.y);
    var to = [d.target.x, d.target.y];

    to = drawHighlightLink(d, to);

    var grd = ctx.createLinearGradient(d.source.x, d.source.y, d.target.x, d.target.y);
    grd.addColorStop(0.45, d.color);
    grd.addColorStop(0.55, d.color_to);

    ctx.lineTo(to[0], to[1]);
    ctx.strokeStyle = grd;
    if (d.o.type.indexOf('vpn') === 0) {
      ctx.globalAlpha = 0.2;
      ctx.lineWidth = 1.5;
    } else {
      ctx.globalAlpha = 0.8;
      ctx.lineWidth = 2.5;
    }
    ctx.stroke();
    ctx.globalAlpha = 1;
  };

  self.setCTX = function setCTX(newValue) {
    ctx = newValue;
  };

  self.setHighlight = function setHighlight(newValue) {
    highlight = newValue;
  };

  self.setTransform = function setTransform(newValue) {
    transform = newValue;
  };

  self.setMaxArea = function setMaxArea(newWidth, newHeight) {
    width = newWidth;
    height = newHeight;
  };

  return self;
});
<|endoftext|>


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

'use strict';

var assert = require('assert');
var async = require('async');
var format = require('string-format-obj');
var googleAuth = require('google-auto-auth');
var is = require('is');
var uuid = require('node-uuid');

var env = require('./env.js');
var BigQuery = require('../lib/bigquery/index.js');
var Logging = require('../lib/logging/index.js');
var PubSub = require('../lib/pubsub/index.js');
var Storage = require('../lib/storage/index.js');

describe('Logging', function() {
  var TESTS_PREFIX = 'gcloud-logging-test';

  var authClient = googleAuth({
    scopes: ['https://www.googleapis.com/auth/cloud-platform']
  });

  var logging = new Logging(env);
  var loggingWithUserAuth;

  var bigQuery = new BigQuery(env);
  var pubsub = new PubSub(env);
  var storage = new Storage(env);

  // Create the possible destinations for sinks that we will create.
  var bucket = storage.bucket(generateName());
  var dataset = bigQuery.dataset(generateName().replace(/-/g, '_'));
  var topic = pubsub.topic(generateName());

  before(function(done) {
    async.parallel([
      checkIfUserAuthIsAvailable,
      createBucket,
      createDataset,
      createTopic
    ], done);

    function checkIfUserAuthIsAvailable(callback) {
      authClient.getToken(function(err) {
        if (!err) {
          loggingWithUserAuth = new Logging({
            projectId: env.projectId
          });
        }

        callback();
      });
    }

    function createBucket(callback) {
      bucket.create(callback);
    }

    function createDataset(callback) {
      dataset.create(callback);
    }

    function createTopic(callback) {
      topic.create(callback);
    }
  });

  after(function(done) {
    async.parallel([
      deleteBuckets,
      deleteDatasets,
      deleteTopics
    ], done);

    function deleteBuckets(callback) {
      storage.getBuckets({
        prefix: TESTS_PREFIX
      }, function(err, buckets) {
        if (err) {
          done(err);
          return;
        }

        function deleteBucket(bucket, callback) {
          bucket.deleteFiles(function(err) {
            if (err) {
              callback(err);
              return;
            }

            bucket.delete(callback);
          });
        }

        async.each(buckets, deleteBucket, callback);
      });
    }

    function deleteDatasets(callback) {
      bigQuery.getDatasets(function(err, datasets) {
        if (err) {
          callback(err);
          return;
        }

        async.each(filterByPrefix(datasets), deleteObject, callback);
      });
    }

    function deleteTopics(callback) {
      pubsub.getTopics(function(err, topics) {
        if (err) {
          callback(err);
          return;
        }

        async.each(filterByPrefix(topics), deleteObject, callback);
      });
    }

    function filterByPrefix(objects) {
      return objects.filter(function(object) {
        return object.id.indexOf(TESTS_PREFIX) === 0;
      });
    }

    function deleteObject(object, callback) {
      object.delete(callback);
    }
  });

  describe('sinks (user auth operations)', function() {
    beforeEach(function() {
      if (!loggingWithUserAuth) {
        this.skip();
      }
    });

    it('should create a sink with a Bucket destination', function(done) {
      var sink = loggingWithUserAuth.sink(generateName());

      sink.create({
        destination: bucket
      }, function(err, sink, apiResponse) {
        assert.ifError(err);

        var destination = 'storage.googleapis.com/' + bucket.name;
        assert.strictEqual(apiResponse.destination, destination);

        sink.delete(done);
      });
    });

    it('should create a sink with a Dataset destination', function(done) {
      var sink = loggingWithUserAuth.sink(generateName());

      sink.create({
        destination: dataset
      }, function(err, sink, apiResponse) {
        assert.ifError(err);

        var destination = format('{baseUrl}/projects/{pId}/datasets/{dId}', {
          baseUrl: 'bigquery.googleapis.com',
          pId: dataset.parent.projectId,
          dId: dataset.id
        });

        assert.strictEqual(apiResponse.destination, destination);

        sink.delete(done);
      });
    });

    it('should create a sink with a Topic destination', function(done) {
      var sink = loggingWithUserAuth.sink(generateName());

      sink.create({
        destination: topic
      }, function(err, sink, apiResponse) {
        assert.ifError(err);

        var destination = 'pubsub.googleapis.com/' + topic.name;
        assert.strictEqual(apiResponse.destination, destination);

        sink.delete(done);
      });
    });

    describe('metadata', function() {
      var sink;
      var FILTER = 'severity = ALERT';

      before(function(done) {
        if (!loggingWithUserAuth) {
          this.skip();
          return;
        }

        sink = loggingWithUserAuth.sink(generateName());

        sink.create({
          destination: topic
        }, done);
      });

      beforeEach(function() {
        if (!loggingWithUserAuth) {
          this.skip();
        }
      });

      after(function(done) {
        if (!loggingWithUserAuth) {
          this.skip();
          return;
        }

        sink.delete(done);
      });

      it('should set metadata', function(done) {
        var metadata = {
          filter: FILTER
        };

        sink.setMetadata(metadata, function(err, apiResponse) {
          assert.ifError(err);
          assert.strictEqual(apiResponse.filter, FILTER);
          done();
        });
      });

      it('should set a filter', function(done) {
        sink.setFilter(FILTER, function(err, apiResponse) {
          assert.ifError(err);
          assert.strictEqual(apiResponse.filter, FILTER);
          done();
        });
      });
    });

    describe('listing sinks', function() {
      var sink;

      before(function(done) {
        if (!loggingWithUserAuth) {
          this.skip();
          return;
        }

        sink = loggingWithUserAuth.sink(generateName());

        sink.create({
          destination: topic
        }, done);
      });

      beforeEach(function() {
        if (!loggingWithUserAuth) {
          this.skip();
        }
      });

      it('should list sinks', function(done) {
        logging.getSinks(function(err, sinks) {
          assert.ifError(err);
          assert(sinks.length > 0);
          done();
        });
      });

      it('should list sinks as a stream', function(done) {
        logging.getSinks({ pageSize: 1 })
          .on('error', done)
          .once('data', function() {
            this.end();
            done();
          });
      });

      it('should get metadata', function(done) {
        logging.getSinks({ pageSize: 1 })
          .on('error', done)
          .once('data', function(sink) {
            sink.getMetadata(function(err, metadata) {
              assert.ifError(err);
              assert.strictEqual(is.object(metadata), true);
              done();
            });
          });
      });
    });
  });

  describe('logs', function() {
    var log = logging.log('syslog');

    var logEntries = [
      log.entry('log entry 1'), // string data
      log.entry({ delegate: process.env.USER }) // object data
    ];

    var options = {
      resource: {
        type: 'gce_instance',
        labels: {
          zone: 'global',
          instance_id: '3'
        }
      }
    };

    it('should list log entries', function(done) {
      logging.getEntries({ pageSize: 1 }, function(err, entries) {
        assert.ifError(err);
        assert.strictEqual(entries.length, 1);
        done();
      });
    });

    it('should list log entries as a stream', function(done) {
      log.getEntries({ pageSize: 1 })
        .on('error', done)
        .once('data', function() {
          this.end();
          done();
        });
    });

    it('should write to a log', function(done) {
      log.write(logEntries, options, done);
    });

    it('should write to a log with alert helper', function(done) {
      log.alert(logEntries, options, done);
    });

    it('should write to a log with critical helper', function(done) {
      log.critical(logEntries, options, done);
    });

    it('should write to a log with debug helper', function(done) {
      log.debug(logEntries, options, done);
    });

    it('should write to a log with emergency helper', function(done) {
      log.emergency(logEntries, options, done);
    });

    it('should write to a log with error helper', function(done) {
      log.error(logEntries, options, done);
    });

    it('should write to a log with info helper', function(done) {
      log.info(logEntries, options, done);
    });

    it('should write to a log with notice helper', function(done) {
      log.notice(logEntries, options, done);
    });

    it('should write to a log with warning helper', function(done) {
      log.warning(logEntries, options, done);
    });

    it('should write from a stream', function(done) {
      log.createWriteStream()
        .on('error', done)
        .on('finish', done)
        .end(logEntries);
    });
  });

  function generateName() {
    return TESTS_PREFIX + uuid.v1();
  }
});
<commit_msg>logging: test fetching log-specific entries<commit_after>/*!
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

var assert = require('assert');
var async = require('async');
var format = require('string-format-obj');
var googleAuth = require('google-auto-auth');
var is = require('is');
var uuid = require('node-uuid');

var env = require('./env.js');
var BigQuery = require('../lib/bigquery/index.js');
var Logging = require('../lib/logging/index.js');
var PubSub = require('../lib/pubsub/index.js');
var Storage = require('../lib/storage/index.js');

describe('Logging', function() {
  var TESTS_PREFIX = 'gcloud-logging-test';

  var authClient = googleAuth({
    scopes: ['https://www.googleapis.com/auth/cloud-platform']
  });

  var logging = new Logging(env);
  var loggingWithUserAuth;

  var bigQuery = new BigQuery(env);
  var pubsub = new PubSub(env);
  var storage = new Storage(env);

  // Create the possible destinations for sinks that we will create.
  var bucket = storage.bucket(generateName());
  var dataset = bigQuery.dataset(generateName().replace(/-/g, '_'));
  var topic = pubsub.topic(generateName());

  before(function(done) {
    async.parallel([
      checkIfUserAuthIsAvailable,
      createBucket,
      createDataset,
      createTopic
    ], done);

    function checkIfUserAuthIsAvailable(callback) {
      authClient.getToken(function(err) {
        if (!err) {
          loggingWithUserAuth = new Logging({
            projectId: env.projectId
          });
        }

        callback();
      });
    }

    function createBucket(callback) {
      bucket.create(callback);
    }

    function createDataset(callback) {
      dataset.create(callback);
    }

    function createTopic(callback) {
      topic.create(callback);
    }
  });

  after(function(done) {
    async.parallel([
      deleteBuckets,
      deleteDatasets,
      deleteTopics
    ], done);

    function deleteBuckets(callback) {
      storage.getBuckets({
        prefix: TESTS_PREFIX
      }, function(err, buckets) {
        if (err) {
          done(err);
          return;
        }

        function deleteBucket(bucket, callback) {
          bucket.deleteFiles(function(err) {
            if (err) {
              callback(err);
              return;
            }

            bucket.delete(callback);
          });
        }

        async.each(buckets, deleteBucket, callback);
      });
    }

    function deleteDatasets(callback) {
      bigQuery.getDatasets(function(err, datasets) {
        if (err) {
          callback(err);
          return;
        }

        async.each(filterByPrefix(datasets), deleteObject, callback);
      });
    }

    function deleteTopics(callback) {
      pubsub.getTopics(function(err, topics) {
        if (err) {
          callback(err);
          return;
        }

        async.each(filterByPrefix(topics), deleteObject, callback);
      });
    }

    function filterByPrefix(objects) {
      return objects.filter(function(object) {
        return object.id.indexOf(TESTS_PREFIX) === 0;
      });
    }

    function deleteObject(object, callback) {
      object.delete(callback);
    }
  });

  describe('sinks (user auth operations)', function() {
    beforeEach(function() {
      if (!loggingWithUserAuth) {
        this.skip();
      }
    });

    it('should create a sink with a Bucket destination', function(done) {
      var sink = loggingWithUserAuth.sink(generateName());

      sink.create({
        destination: bucket
      }, function(err, sink, apiResponse) {
        assert.ifError(err);

        var destination = 'storage.googleapis.com/' + bucket.name;
        assert.strictEqual(apiResponse.destination, destination);

        sink.delete(done);
      });
    });

    it('should create a sink with a Dataset destination', function(done) {
      var sink = loggingWithUserAuth.sink(generateName());

      sink.create({
        destination: dataset
      }, function(err, sink, apiResponse) {
        assert.ifError(err);

        var destination = format('{baseUrl}/projects/{pId}/datasets/{dId}', {
          baseUrl: 'bigquery.googleapis.com',
          pId: dataset.parent.projectId,
          dId: dataset.id
        });

        assert.strictEqual(apiResponse.destination, destination);

        sink.delete(done);
      });
    });

    it('should create a sink with a Topic destination', function(done) {
      var sink = loggingWithUserAuth.sink(generateName());

      sink.create({
        destination: topic
      }, function(err, sink, apiResponse) {
        assert.ifError(err);

        var destination = 'pubsub.googleapis.com/' + topic.name;
        assert.strictEqual(apiResponse.destination, destination);

        sink.delete(done);
      });
    });

    describe('metadata', function() {
      var sink;
      var FILTER = 'severity = ALERT';

      before(function(done) {
        if (!loggingWithUserAuth) {
          this.skip();
          return;
        }

        sink = loggingWithUserAuth.sink(generateName());

        sink.create({
          destination: topic
        }, done);
      });

      beforeEach(function() {
        if (!loggingWithUserAuth) {
          this.skip();
        }
      });

      after(function(done) {
        if (!loggingWithUserAuth) {
          this.skip();
          return;
        }

        sink.delete(done);
      });

      it('should set metadata', function(done) {
        var metadata = {
          filter: FILTER
        };

        sink.setMetadata(metadata, function(err, apiResponse) {
          assert.ifError(err);
          assert.strictEqual(apiResponse.filter, FILTER);
          done();
        });
      });

      it('should set a filter', function(done) {
        sink.setFilter(FILTER, function(err, apiResponse) {
          assert.ifError(err);
          assert.strictEqual(apiResponse.filter, FILTER);
          done();
        });
      });
    });

    describe('listing sinks', function() {
      var sink;

      before(function(done) {
        if (!loggingWithUserAuth) {
          this.skip();
          return;
        }

        sink = loggingWithUserAuth.sink(generateName());

        sink.create({
          destination: topic
        }, done);
      });

      beforeEach(function() {
        if (!loggingWithUserAuth) {
          this.skip();
        }
      });

      it('should list sinks', function(done) {
        logging.getSinks(function(err, sinks) {
          assert.ifError(err);
          assert(sinks.length > 0);
          done();
        });
      });

      it('should list sinks as a stream', function(done) {
        logging.getSinks({ pageSize: 1 })
          .on('error', done)
          .once('data', function() {
            this.end();
            done();
          });
      });

      it('should get metadata', function(done) {
        logging.getSinks({ pageSize: 1 })
          .on('error', done)
          .once('data', function(sink) {
            sink.getMetadata(function(err, metadata) {
              assert.ifError(err);
              assert.strictEqual(is.object(metadata), true);
              done();
            });
          });
      });
    });
  });

  describe('logs', function() {
    var log = logging.log('syslog');

    var logEntries = [
      log.entry('log entry 1'), // string data
      log.entry({ delegate: process.env.USER }) // object data
    ];

    var options = {
      resource: {
        type: 'gce_instance',
        labels: {
          zone: 'global',
          instance_id: '3'
        }
      }
    };

    it('should list log entries', function(done) {
      logging.getEntries({ pageSize: 1 }, function(err, entries) {
        assert.ifError(err);
        assert.strictEqual(entries.length, 1);
        done();
      });
    });

    it('should list log entries as a stream', function(done) {
      logging.getEntries({ pageSize: 1 })
        .on('error', done)
        .once('data', function() {
          this.end();
          done();
        });
    });

    describe('log-specific entries', function() {
      before(function(done) {
        log.write(logEntries, options, done);
      });

      it('should list log entries', function(done) {
        log.getEntries({ pageSize: 1 }, function(err, entries) {
          assert.ifError(err);
          assert.strictEqual(entries.length, 1);
          done();
        });
      });

      it('should list log entries as a stream', function(done) {
        log.getEntries({ pageSize: 1 })
          .on('error', done)
          .once('data', function() {
            this.end();
            done();
          });
      });
    });

    it('should write to a log', function(done) {
      log.write(logEntries, options, done);
    });

    it('should write to a log with alert helper', function(done) {
      log.alert(logEntries, options, done);
    });

    it('should write to a log with critical helper', function(done) {
      log.critical(logEntries, options, done);
    });

    it('should write to a log with debug helper', function(done) {
      log.debug(logEntries, options, done);
    });

    it('should write to a log with emergency helper', function(done) {
      log.emergency(logEntries, options, done);
    });

    it('should write to a log with error helper', function(done) {
      log.error(logEntries, options, done);
    });

    it('should write to a log with info helper', function(done) {
      log.info(logEntries, options, done);
    });

    it('should write to a log with notice helper', function(done) {
      log.notice(logEntries, options, done);
    });

    it('should write to a log with warning helper', function(done) {
      log.warning(logEntries, options, done);
    });

    it('should write from a stream', function(done) {
      log.createWriteStream()
        .on('error', done)
        .on('finish', done)
        .end(logEntries);
    });
  });

  function generateName() {
    return TESTS_PREFIX + uuid.v1();
  }
});
<|endoftext|>


<commit_before>//
//  CanvasCamera.js
//  PhoneGap iOS Cordova Plugin to capture Camera streaming into a HTML5 Canvas or an IMG tag.
//
//  Created by Diego Araos <d@wehack.it> on 12/29/12.
//
//  MIT License

cordova.define("cordova/plugin/CanvasCamera", function(require, exports, module) {
    var exec = require('cordova/exec');
    var CanvasCamera = function(){
        var _orientation = 'landscape';
        var _obj = null;
        var _context = null;
        var _camImage = null;

        var _x = 0;
        var _y = 0;
        var _width = 0;
        var _height = 0;
    };

    CanvasCamera.prototype.initialize = function(obj) {
        var _this = this;
        this._obj = obj;

        this._context = obj.getContext("2d");

        this._camImage = new Image();

        this._camImage.onload = function() {
            console.log("_this._context.clearRect(0, 0, _this._width, _this._height)"+_this._width+","+_this._height);
            _this._context.clearRect(0, 0, _this._width, _this._height);
            if (window.orientation == 90
               || window.orientation == -90)
            {
                _this._context.save();
                // rotate 90
                console.log("_this._context.translate(_this._width/2, _this._height/2)"+(_this._width/2)+","+ (_this._height/2);
                _this._context.translate(_this._width/2, _this._height/2);
                _this._context.rotate((90 - window.orientation) *Math.PI/180);
                _this._context.drawImage(_this._camImage, 0, 0, 352, 288, -_this._width/2, -_this._height/2, _this._width, _this._height);
                //
                _this._context.restore();
            }
            else
            {
                console.log("comes in else");
                _this._context.save();
                // rotate 90
                _this._context.translate(_this._width/2, _this._height/2);
                _this._context.rotate((90 - window.orientation)*Math.PI/180);
                _this._context.drawImage(_this._camImage, 0, 0, 352, 288, -_this._height/2, -_this._width/2, _this._height, _this._width);
                //
                _this._context.restore();
            }
        };

        // register orientation change event
        window.addEventListener('orientationchange', this.doOrientationChange);
        this.doOrientationChange();
    };

    CanvasCamera.prototype.start = function(options) {
        cordova.exec(false, false, "CanvasCamera", "startCapture", [options]);
    };

    CanvasCamera.prototype.capture = function(data) {
        this._camImage.src = data;
    };

    CanvasCamera.prototype.setFlashMode = function(flashMode) {
        cordova.exec(function(){}, function(){}, "CanvasCamera", "setFlashMode", [flashMode]);
    };

    CanvasCamera.prototype.setCameraPosition = function(cameraPosition) {
        cordova.exec(function(){}, function(){}, "CanvasCamera", "setCameraPosition", [cameraPosition]);
    };

    CanvasCamera.prototype.doOrientationChange = function() {
        console.log('doOrientationChange');
        switch(window.orientation)
        {
            case -90:
            case 90:
                this._orientation = 'landscape';
                break;
            default:
                this._orientation = 'portrait';
                break;
        }
        console.log('window.innerWidth'+window.innerWidth);
        console.log('window.innerHeight'+window.innerHeight);

        var windowWidth = window.innerWidth;
        var windowHeight = window.innerHeight;
        var pixelRatio = window.devicePixelRatio || 1; /// get pixel ratio of device

        this._obj.width = windowWidth;// * pixelRatio;   /// resolution of canvas
        this._obj.height = windowHeight;// * pixelRatio;
        console.log('this._obj.width'+this._obj.width);

        this._obj.style.width = windowWidth + 'px';   /// CSS size of canvas
        this._obj.style.height = windowHeight + 'px';
        console.log('this._obj.style.width'+this._obj.style.width);

        this._x = 0;
        this._y = 0;
        this._width = windowWidth;
        this._height = windowHeight;
        console.log('this._width'+this._width+" this._height"+this._height);
    };

    CanvasCamera.prototype.takePicture = function(onsuccess) {
        cordova.exec(onsuccess, function(){}, "CanvasCamera", "captureImage", []);
    };

    var myplugin = new CanvasCamera();
    module.exports = myplugin;
});

var CanvasCamera = cordova.require("cordova/plugin/CanvasCamera");

var DestinationType = {
    DATA_URL : 0,
    FILE_URI : 1
};

var PictureSourceType = {
    PHOTOLIBRARY : 0,
    CAMERA : 1,
    SAVEDPHOTOALBUM : 2
};

var EncodingType = {
    JPEG : 0,
    PNG : 1
};

var CameraPosition = {
    BACK : 0,
    FRONT : 1
};

var CameraPosition = {
    BACK : 1,
    FRONT : 2
};

var FlashMode = {
    OFF : 0,
    ON : 1,
    AUTO : 2
};

CanvasCamera.DestinationType = DestinationType;
CanvasCamera.PictureSourceType = PictureSourceType;
CanvasCamera.EncodingType = EncodingType;
CanvasCamera.CameraPosition = CameraPosition;
CanvasCamera.FlashMode = FlashMode;

module.exports = CanvasCamera;
<commit_msg>Update CanvasCamera.js<commit_after>//
//  CanvasCamera.js
//  PhoneGap iOS Cordova Plugin to capture Camera streaming into a HTML5 Canvas or an IMG tag.
//
//  Created by Diego Araos <d@wehack.it> on 12/29/12.
//
//  MIT License

cordova.define("cordova/plugin/CanvasCamera", function(require, exports, module) {
    var exec = require('cordova/exec');
    var CanvasCamera = function(){
        var _orientation = 'landscape';
        var _obj = null;
        var _context = null;
        var _camImage = null;

        var _x = 0;
        var _y = 0;
        var _width = 0;
        var _height = 0;
    };

    CanvasCamera.prototype.initialize = function(obj) {
        var _this = this;
        this._obj = obj;

        this._context = obj.getContext("2d");

        this._camImage = new Image();

        this._camImage.onload = function() {
            //console.log("_this._context.clearRect(0, 0, _this._width, _this._height)"+_this._width+","+_this._height);
            _this._context.clearRect(0, 0, _this._width, _this._height);
            if (window.orientation == 90
               || window.orientation == -90)
            {
                _this._context.save();
                // rotate 90
                //console.log("_this._context.translate(_this._width/2, _this._height/2)"+(_this._width/2)+","+ (_this._height/2);
                _this._context.translate(_this._width/2, _this._height/2);
                _this._context.rotate((90 - window.orientation) *Math.PI/180);
                _this._context.drawImage(_this._camImage, 0, 0, 352, 288, -_this._width/2, -_this._height/2, _this._width, _this._height);
                //
                _this._context.restore();
            }
            else
            {
                //console.log("comes in else");
                _this._context.save();
                // rotate 90
                _this._context.translate(_this._width/2, _this._height/2);
                _this._context.rotate((90 - window.orientation)*Math.PI/180);
                _this._context.drawImage(_this._camImage, 0, 0, 352, 288, -_this._height/2, -_this._width/2, _this._height, _this._width);
                //
                _this._context.restore();
            }
        };

        // register orientation change event
        window.addEventListener('orientationchange', this.doOrientationChange);
        this.doOrientationChange();
    };

    CanvasCamera.prototype.start = function(options) {
        cordova.exec(false, false, "CanvasCamera", "startCapture", [options]);
    };

    CanvasCamera.prototype.capture = function(data) {
        this._camImage.src = data;
    };

    CanvasCamera.prototype.setFlashMode = function(flashMode) {
        cordova.exec(function(){}, function(){}, "CanvasCamera", "setFlashMode", [flashMode]);
    };

    CanvasCamera.prototype.setCameraPosition = function(cameraPosition) {
        cordova.exec(function(){}, function(){}, "CanvasCamera", "setCameraPosition", [cameraPosition]);
    };

    CanvasCamera.prototype.doOrientationChange = function() {
        //console.log('doOrientationChange');
        switch(window.orientation)
        {
            case -90:
            case 90:
                this._orientation = 'landscape';
                break;
            default:
                this._orientation = 'portrait';
                break;
        }
        //console.log('window.innerWidth'+window.innerWidth);
        //console.log('window.innerHeight'+window.innerHeight);

        var windowWidth = window.innerWidth;
        var windowHeight = window.innerHeight;
        var pixelRatio = window.devicePixelRatio || 1; /// get pixel ratio of device

        this._obj.width = windowWidth;// * pixelRatio;   /// resolution of canvas
        this._obj.height = windowHeight;// * pixelRatio;
        //console.log('this._obj.width'+this._obj.width);

        this._obj.style.width = windowWidth + 'px';   /// CSS size of canvas
        this._obj.style.height = windowHeight + 'px';
        //console.log('this._obj.style.width'+this._obj.style.width);

        this._x = 0;
        this._y = 0;
        this._width = windowWidth;
        this._height = windowHeight;
        //console.log('this._width'+this._width+" this._height"+this._height);
    };

    CanvasCamera.prototype.takePicture = function(onsuccess) {
        cordova.exec(onsuccess, function(){}, "CanvasCamera", "captureImage", []);
    };

    var myplugin = new CanvasCamera();
    module.exports = myplugin;
});

var CanvasCamera = cordova.require("cordova/plugin/CanvasCamera");

var DestinationType = {
    DATA_URL : 0,
    FILE_URI : 1
};

var PictureSourceType = {
    PHOTOLIBRARY : 0,
    CAMERA : 1,
    SAVEDPHOTOALBUM : 2
};

var EncodingType = {
    JPEG : 0,
    PNG : 1
};

var CameraPosition = {
    BACK : 0,
    FRONT : 1
};

var CameraPosition = {
    BACK : 1,
    FRONT : 2
};

var FlashMode = {
    OFF : 0,
    ON : 1,
    AUTO : 2
};

CanvasCamera.DestinationType = DestinationType;
CanvasCamera.PictureSourceType = PictureSourceType;
CanvasCamera.EncodingType = EncodingType;
CanvasCamera.CameraPosition = CameraPosition;
CanvasCamera.FlashMode = FlashMode;

module.exports = CanvasCamera;
<|endoftext|>


<commit_before>import { Util } from './util';
import { English } from './english';
import { Settings } from '../settings';
import { DateTime } from '../datetime';
import { Formatter } from './formatter';

let sysLocaleCache = null;
function systemLocale() {
  if (sysLocaleCache) {
    return sysLocaleCache;
  } else if (Util.hasIntl()) {
    sysLocaleCache = new Intl.DateTimeFormat().resolvedOptions().locale;
    return sysLocaleCache;
  } else {
    sysLocaleCache = 'en-US';
    return sysLocaleCache;
  }
}

function intlConfigString(locale, numberingSystem, outputCalendar) {
  if (Util.hasIntl()) {
    locale = Array.isArray(locale) ? locale : [locale];

    if (outputCalendar || numberingSystem) {
      locale = locale.map(l => {
        l += '-u';

        if (outputCalendar) {
          l += '-ca-' + outputCalendar;
        }

        if (numberingSystem) {
          l += '-nu-' + numberingSystem;
        }
        return l;
      });
    }
    return locale;
  } else {
    return [];
  }
}

function mapMonths(f) {
  const ms = [];
  for (let i = 1; i <= 12; i++) {
    const dt = DateTime.utc(2016, i, 1);
    ms.push(f(dt));
  }
  return ms;
}

function mapWeekdays(f) {
  const ms = [];
  for (let i = 1; i <= 7; i++) {
    const dt = DateTime.utc(2016, 11, 13 + i);
    ms.push(f(dt));
  }
  return ms;
}

function listStuff(loc, length, defaultOK, englishFn, intlFn) {
  const mode = loc.listingMode(defaultOK);

  if (mode === 'error') {
    return null;
  } else if (mode === 'en') {
    return englishFn(length);
  } else {
    return intlFn(length);
  }
}

/**
 * @private
 */

class PolyNumberFormatter {
  constructor(opts) {
    this.padTo = opts.padTo || 0;
    this.round = opts.round || false;
  }

  format(i) {
    const maybeRounded = this.round ? Math.round(i) : i;
    return Util.padStart(maybeRounded.toString(), this.padTo);
  }
}

class PolyDateFormatter {
  constructor(dt, intl, opts) {
    this.opts = opts;
    this.hasIntl = Util.hasIntl();

    let z;
    if (dt.zone.universal && this.hasIntl) {
      // if we have a fixed-offset zone that isn't actually UTC,
      // (like UTC+8), we need to make do with just displaying
      // the time in UTC; the formatter doesn't know how to handle UTC+8
      this.dt = dt.offset === 0 ? dt : DateTime.fromMillis(dt.ts + dt.offset * 60 * 1000);
      z = 'UTC';
    } else if (dt.zone.type === 'local') {
      this.dt = dt;
    } else {
      this.dt = dt;
      z = dt.zone.name;
    }

    if (this.hasIntl) {
      const realIntlOpts = Object.assign({}, this.opts);
      if (z) {
        realIntlOpts.timeZone = z;
      }
      this.dtf = new Intl.DateTimeFormat(intl, realIntlOpts);
    }
  }

  format() {
    if (this.hasIntl) {
      return this.dtf.format(this.dt.toJSDate());
    } else {
      const tokenFormat = English.formatString(this.opts),
        loc = Locale.create('en-US');
      return Formatter.create(loc).formatDateTimeFromString(this.dt, tokenFormat);
    }
  }

  formatToParts() {
    if (this.hasIntl && Util.hasFormatToParts()) {
      return this.dtf.formatToParts(this.dt.toJSDate());
    } else {
      // This is kind of a cop out. We actually could do this for English. However, we couldn't do it for intl strings
      // and IMO it's too weird to have an uncanny valley like that
      return [];
    }
  }

  resolvedOptions() {
    if (this.hasIntl) {
      return this.dtf.resolvedOptions();
    } else {
      return {
        locale: 'en-US',
        numberingSystem: 'latn',
        outputCalendar: 'gregory'
      };
    }
  }
}

/**
 * @private
 */

export class Locale {
  static fromOpts(opts) {
    return Locale.create(opts.locale, opts.numberingSystem, opts.outputCalendar, opts.defaultToEN);
  }

  static create(locale, numberingSystem, outputCalendar, defaultToEN = false) {
    const specifiedLocale = locale || Settings.defaultLocale,
      // the system locale is useful for human readable strings but annoying for parsing/formatting known formats
      localeR = specifiedLocale || (defaultToEN ? 'en-US' : systemLocale()),
      numberingSystemR = numberingSystem || Settings.defaultNumberingSystem,
      outputCalendarR = outputCalendar || Settings.defaultOutputCalendar;
    return new Locale(localeR, numberingSystemR, outputCalendarR, specifiedLocale);
  }

  static resetCache() {
    sysLocaleCache = null;
  }

  static fromObject({ locale, numberingSystem, outputCalendar } = {}) {
    return Locale.create(locale, numberingSystem, outputCalendar);
  }

  constructor(locale, numbering, outputCalendar, specifiedLocale) {
    this.locale = locale;
    this.numberingSystem = numbering;
    this.outputCalendar = outputCalendar;
    this.intl = intlConfigString(this.locale, this.numberingSystem, this.outputCalendar);

    this.weekdaysCache = { format: {}, standalone: {} };
    this.monthsCache = { format: {}, standalone: {} };
    this.meridiemCache = null;
    this.eraCache = {};

    this.specifiedLocale = specifiedLocale;
  }

  // todo: cache me
  listingMode(defaultOk = true) {
    const hasIntl = Util.hasIntl(),
      hasFTP = hasIntl && Util.hasFormatToParts(),
      isActuallyEn =
        this.locale === 'en' ||
        this.locale.toLowerCase() === 'en-us' ||
        (hasIntl &&
          Intl.DateTimeFormat(this.intl)
            .resolvedOptions()
            .locale.startsWith('en-us')),
      hasNoWeirdness =
        (this.numberingSystem === null || this.numberingSystem === 'latn') &&
        (this.outputCalendar === null || this.outputCalendar === 'gregory');

    if (!hasFTP && !(isActuallyEn && hasNoWeirdness) && !defaultOk) {
      return 'error';
    } else if (!hasFTP || (isActuallyEn && hasNoWeirdness)) {
      return 'en';
    } else {
      return 'intl';
    }
  }

  clone(alts) {
    if (!alts || Object.getOwnPropertyNames(alts).length === 0) {
      return this;
    } else {
      return Locale.create(
        alts.locale || this.specifiedLocale,
        alts.numberingSystem || this.numberingSystem,
        alts.outputCalendar || this.outputCalendar,
        alts.defaultToEN || false
      );
    }
  }

  redefaultToEN(alts = {}) {
    return this.clone(Object.assign({}, alts, { defaultToEN: true }));
  }

  redefaultToSystem(alts = {}) {
    return this.clone(Object.assign({}, alts, { defaultToEN: false }));
  }

  months(length, format = false, defaultOK = true) {
    return listStuff(this, length, defaultOK, English.months, () => {
      const intl = format ? { month: length, day: 'numeric' } : { month: length },
        formatStr = format ? 'format' : 'standalone';
      if (!this.monthsCache[formatStr][length]) {
        this.monthsCache[formatStr][length] = mapMonths(dt => this.extract(dt, intl, 'month'));
      }
      return this.monthsCache[formatStr][length];
    });
  }

  weekdays(length, format = false, defaultOK = true) {
    return listStuff(this, length, defaultOK, English.weekdays, () => {
      const intl = format
          ? { weekday: length, year: 'numeric', month: 'long', day: 'numeric' }
          : { weekday: length },
        formatStr = format ? 'format' : 'standalone';
      if (!this.weekdaysCache[formatStr][length]) {
        this.weekdaysCache[formatStr][length] = mapWeekdays(dt =>
          this.extract(dt, intl, 'weekday')
        );
      }
      return this.weekdaysCache[formatStr][length];
    });
  }

  meridiems(defaultOK = true) {
    return listStuff(
      this,
      undefined,
      defaultOK,
      () => English.meridiems,
      () => {
        // In theory there could be aribitrary day periods. We're gonna assume there are exactly two
        // for AM and PM. This is probably wrong, but it's makes parsing way easier.
        if (!this.meridiemCache) {
          const intl = { hour: 'numeric', hour12: true };
          this.meridiemCache = [DateTime.utc(2016, 11, 13, 9), DateTime.utc(2016, 11, 13, 19)].map(
            dt => this.extract(dt, intl, 'dayperiod')
          );
        }

        return this.meridiemCache;
      }
    );
  }

  eras(length, defaultOK = true) {
    return listStuff(this, length, defaultOK, English.eras, () => {
      const intl = { era: length };

      // This is utter bullshit. Different calendars are going to define eras totally differently. What I need is the minimum set of dates
      // to definitely enumerate them.
      if (!this.eraCache[length]) {
        this.eraCache[length] = [DateTime.utc(-40, 1, 1), DateTime.utc(2017, 1, 1)].map(dt =>
          this.extract(dt, intl, 'era')
        );
      }

      return this.eraCache[length];
    });
  }

  extract(dt, intlOpts, field) {
    const df = this.dtFormatter(dt, intlOpts),
      results = df.formatToParts(),
      matching = results.find(m => m.type.toLowerCase() === field);

    return matching ? matching.value : null;
  }

  numberFormatter(opts = {}, intlOpts = {}) {
    if (Util.hasIntl()) {
      const realIntlOpts = Object.assign({ useGrouping: false }, intlOpts);

      if (opts.padTo > 0) {
        realIntlOpts.minimumIntegerDigits = opts.padTo;
      }

      if (opts.round) {
        realIntlOpts.maximumFractionDigits = 0;
      }

      return new Intl.NumberFormat(this.intl, realIntlOpts);
    } else {
      return new PolyNumberFormatter(opts);
    }
  }

  dtFormatter(dt, intlOpts = {}) {
    return new PolyDateFormatter(dt, this.intl, intlOpts);
  }

  equals(other) {
    return (
      this.locale === other.locale &&
      this.numberingSystem === other.numberingSystem &&
      this.outputCalendar === other.outputCalendar
    );
  }
}
<commit_msg>give Node a better default locale<commit_after>import { Util } from './util';
import { English } from './english';
import { Settings } from '../settings';
import { DateTime } from '../datetime';
import { Formatter } from './formatter';

let sysLocaleCache = null;
function systemLocale() {
  if (sysLocaleCache) {
    return sysLocaleCache;
  } else if (Util.hasIntl()) {
    const computedSys = new Intl.DateTimeFormat().resolvedOptions().locale;
    // node sometimes defaults to "und". Override that because that is dumb
    sysLocaleCache = computedSys === 'und' ? 'en-US' : computedSys;
    return sysLocaleCache;
  } else {
    sysLocaleCache = 'en-US';
    return sysLocaleCache;
  }
}

function intlConfigString(locale, numberingSystem, outputCalendar) {
  if (Util.hasIntl()) {
    locale = Array.isArray(locale) ? locale : [locale];

    if (outputCalendar || numberingSystem) {
      locale = locale.map(l => {
        l += '-u';

        if (outputCalendar) {
          l += '-ca-' + outputCalendar;
        }

        if (numberingSystem) {
          l += '-nu-' + numberingSystem;
        }
        return l;
      });
    }
    return locale;
  } else {
    return [];
  }
}

function mapMonths(f) {
  const ms = [];
  for (let i = 1; i <= 12; i++) {
    const dt = DateTime.utc(2016, i, 1);
    ms.push(f(dt));
  }
  return ms;
}

function mapWeekdays(f) {
  const ms = [];
  for (let i = 1; i <= 7; i++) {
    const dt = DateTime.utc(2016, 11, 13 + i);
    ms.push(f(dt));
  }
  return ms;
}

function listStuff(loc, length, defaultOK, englishFn, intlFn) {
  const mode = loc.listingMode(defaultOK);

  if (mode === 'error') {
    return null;
  } else if (mode === 'en') {
    return englishFn(length);
  } else {
    return intlFn(length);
  }
}

/**
 * @private
 */

class PolyNumberFormatter {
  constructor(opts) {
    this.padTo = opts.padTo || 0;
    this.round = opts.round || false;
  }

  format(i) {
    const maybeRounded = this.round ? Math.round(i) : i;
    return Util.padStart(maybeRounded.toString(), this.padTo);
  }
}

class PolyDateFormatter {
  constructor(dt, intl, opts) {
    this.opts = opts;
    this.hasIntl = Util.hasIntl();

    let z;
    if (dt.zone.universal && this.hasIntl) {
      // if we have a fixed-offset zone that isn't actually UTC,
      // (like UTC+8), we need to make do with just displaying
      // the time in UTC; the formatter doesn't know how to handle UTC+8
      this.dt = dt.offset === 0 ? dt : DateTime.fromMillis(dt.ts + dt.offset * 60 * 1000);
      z = 'UTC';
    } else if (dt.zone.type === 'local') {
      this.dt = dt;
    } else {
      this.dt = dt;
      z = dt.zone.name;
    }

    if (this.hasIntl) {
      const realIntlOpts = Object.assign({}, this.opts);
      if (z) {
        realIntlOpts.timeZone = z;
      }
      this.dtf = new Intl.DateTimeFormat(intl, realIntlOpts);
    }
  }

  format() {
    if (this.hasIntl) {
      return this.dtf.format(this.dt.toJSDate());
    } else {
      const tokenFormat = English.formatString(this.opts),
        loc = Locale.create('en-US');
      return Formatter.create(loc).formatDateTimeFromString(this.dt, tokenFormat);
    }
  }

  formatToParts() {
    if (this.hasIntl && Util.hasFormatToParts()) {
      return this.dtf.formatToParts(this.dt.toJSDate());
    } else {
      // This is kind of a cop out. We actually could do this for English. However, we couldn't do it for intl strings
      // and IMO it's too weird to have an uncanny valley like that
      return [];
    }
  }

  resolvedOptions() {
    if (this.hasIntl) {
      return this.dtf.resolvedOptions();
    } else {
      return {
        locale: 'en-US',
        numberingSystem: 'latn',
        outputCalendar: 'gregory'
      };
    }
  }
}

/**
 * @private
 */

export class Locale {
  static fromOpts(opts) {
    return Locale.create(opts.locale, opts.numberingSystem, opts.outputCalendar, opts.defaultToEN);
  }

  static create(locale, numberingSystem, outputCalendar, defaultToEN = false) {
    const specifiedLocale = locale || Settings.defaultLocale,
      // the system locale is useful for human readable strings but annoying for parsing/formatting known formats
      localeR = specifiedLocale || (defaultToEN ? 'en-US' : systemLocale()),
      numberingSystemR = numberingSystem || Settings.defaultNumberingSystem,
      outputCalendarR = outputCalendar || Settings.defaultOutputCalendar;
    return new Locale(localeR, numberingSystemR, outputCalendarR, specifiedLocale);
  }

  static resetCache() {
    sysLocaleCache = null;
  }

  static fromObject({ locale, numberingSystem, outputCalendar } = {}) {
    return Locale.create(locale, numberingSystem, outputCalendar);
  }

  constructor(locale, numbering, outputCalendar, specifiedLocale) {
    this.locale = locale;
    this.numberingSystem = numbering;
    this.outputCalendar = outputCalendar;
    this.intl = intlConfigString(this.locale, this.numberingSystem, this.outputCalendar);

    this.weekdaysCache = { format: {}, standalone: {} };
    this.monthsCache = { format: {}, standalone: {} };
    this.meridiemCache = null;
    this.eraCache = {};

    this.specifiedLocale = specifiedLocale;
  }

  // todo: cache me
  listingMode(defaultOk = true) {
    const hasIntl = Util.hasIntl(),
      hasFTP = hasIntl && Util.hasFormatToParts(),
      isActuallyEn =
        this.locale === 'en' ||
        this.locale.toLowerCase() === 'en-us' ||
        (hasIntl &&
          Intl.DateTimeFormat(this.intl)
            .resolvedOptions()
            .locale.startsWith('en-us')),
      hasNoWeirdness =
        (this.numberingSystem === null || this.numberingSystem === 'latn') &&
        (this.outputCalendar === null || this.outputCalendar === 'gregory');

    if (!hasFTP && !(isActuallyEn && hasNoWeirdness) && !defaultOk) {
      return 'error';
    } else if (!hasFTP || (isActuallyEn && hasNoWeirdness)) {
      return 'en';
    } else {
      return 'intl';
    }
  }

  clone(alts) {
    if (!alts || Object.getOwnPropertyNames(alts).length === 0) {
      return this;
    } else {
      return Locale.create(
        alts.locale || this.specifiedLocale,
        alts.numberingSystem || this.numberingSystem,
        alts.outputCalendar || this.outputCalendar,
        alts.defaultToEN || false
      );
    }
  }

  redefaultToEN(alts = {}) {
    return this.clone(Object.assign({}, alts, { defaultToEN: true }));
  }

  redefaultToSystem(alts = {}) {
    return this.clone(Object.assign({}, alts, { defaultToEN: false }));
  }

  months(length, format = false, defaultOK = true) {
    return listStuff(this, length, defaultOK, English.months, () => {
      const intl = format ? { month: length, day: 'numeric' } : { month: length },
        formatStr = format ? 'format' : 'standalone';
      if (!this.monthsCache[formatStr][length]) {
        this.monthsCache[formatStr][length] = mapMonths(dt => this.extract(dt, intl, 'month'));
      }
      return this.monthsCache[formatStr][length];
    });
  }

  weekdays(length, format = false, defaultOK = true) {
    return listStuff(this, length, defaultOK, English.weekdays, () => {
      const intl = format
          ? { weekday: length, year: 'numeric', month: 'long', day: 'numeric' }
          : { weekday: length },
        formatStr = format ? 'format' : 'standalone';
      if (!this.weekdaysCache[formatStr][length]) {
        this.weekdaysCache[formatStr][length] = mapWeekdays(dt =>
          this.extract(dt, intl, 'weekday')
        );
      }
      return this.weekdaysCache[formatStr][length];
    });
  }

  meridiems(defaultOK = true) {
    return listStuff(
      this,
      undefined,
      defaultOK,
      () => English.meridiems,
      () => {
        // In theory there could be aribitrary day periods. We're gonna assume there are exactly two
        // for AM and PM. This is probably wrong, but it's makes parsing way easier.
        if (!this.meridiemCache) {
          const intl = { hour: 'numeric', hour12: true };
          this.meridiemCache = [DateTime.utc(2016, 11, 13, 9), DateTime.utc(2016, 11, 13, 19)].map(
            dt => this.extract(dt, intl, 'dayperiod')
          );
        }

        return this.meridiemCache;
      }
    );
  }

  eras(length, defaultOK = true) {
    return listStuff(this, length, defaultOK, English.eras, () => {
      const intl = { era: length };

      // This is utter bullshit. Different calendars are going to define eras totally differently. What I need is the minimum set of dates
      // to definitely enumerate them.
      if (!this.eraCache[length]) {
        this.eraCache[length] = [DateTime.utc(-40, 1, 1), DateTime.utc(2017, 1, 1)].map(dt =>
          this.extract(dt, intl, 'era')
        );
      }

      return this.eraCache[length];
    });
  }

  extract(dt, intlOpts, field) {
    const df = this.dtFormatter(dt, intlOpts),
      results = df.formatToParts(),
      matching = results.find(m => m.type.toLowerCase() === field);

    return matching ? matching.value : null;
  }

  numberFormatter(opts = {}, intlOpts = {}) {
    if (Util.hasIntl()) {
      const realIntlOpts = Object.assign({ useGrouping: false }, intlOpts);

      if (opts.padTo > 0) {
        realIntlOpts.minimumIntegerDigits = opts.padTo;
      }

      if (opts.round) {
        realIntlOpts.maximumFractionDigits = 0;
      }

      return new Intl.NumberFormat(this.intl, realIntlOpts);
    } else {
      return new PolyNumberFormatter(opts);
    }
  }

  dtFormatter(dt, intlOpts = {}) {
    return new PolyDateFormatter(dt, this.intl, intlOpts);
  }

  equals(other) {
    return (
      this.locale === other.locale &&
      this.numberingSystem === other.numberingSystem &&
      this.outputCalendar === other.outputCalendar
    );
  }
}
<|endoftext|>


<commit_before>/**
 * Created by nuintun on 2015/4/27.
 */

'use strict';

var path = require('path');
var join = path.join;
var extname = path.extname;
var dirname = path.dirname;
var debug = require('debug')('Transport:util');
var util = require('util');

/**
 * Simple template
 * ```
 * var tpl = '{{name}}/{{version}}';
 * util.template(tpl, {name:'base', version: '1.0.0'});
 * ```
 */

function template(format, data){
  if (!format) return '';
  return format.replace(/{{([a-z]*)}}/g, function (all, match){
    return data[match] || '';
  });
}

/**
 * Set options
 */

function extendOption(options){
  var opt = {
    pkg: null, // The pkg info parsed by father
    ignore: [], // Omit the given dependencies when transport
    idleading: '{{name}}/{{version}}', // The id prefix template that can use pkg as it's data
    rename: null,
    include: 'relative'
  };

  if (!options) return opt;

  for (var key in options) {
    if (options.hasOwnProperty(key)) {
      var val = options[key];

      if (val !== undefined && val !== null) {
        opt[key] = val;
      }
    }
  }

  return opt;
}

/**
 * Hide .js if exists
 */

function hideExt(filepath){
  return extname(filepath) === '.js' ? filepath.replace(/\.js$/, '') : filepath;
}

/**
 * Add .js if not exists
 */

function addExt(filepath){
  return extname(filepath) ? filepath : (filepath + '.js');
}

/**
 * Test filepath is relative path or not
 */

function isRelative(filepath){
  return /^\.{1,2}[\\/]/.test(filepath);
}

/**
 * Test filepath is local path or not
 */

function isLocal(filepath){
  return !/^https?:\/\//.test(filepath) && !/^data:/.test(filepath);
}

/**
 * Resolve a `relative` path base on `base` path
 */

function resolvePath(relative, base){
  if (!isRelative(relative) || !base) return relative;

  debug('transport relative id(%s) of basepath(%s)', relative, base);

  relative = join(dirname(base), relative);

  if (isRelative(relative)) {
    throwError('%s is out of bound of %s', winPath(relative), base);
  }

  return relative;
}

function slashPath(path){
  return path.replace(/\\/g, '/');
}

function throwError(){
  var message = util.format.apply(null, [].slice.call(arguments));

  throw new Error(message);
}

function getRenameOpts(file, opts){
  if (typeof opts === 'function') {
    return opts;
  }

  opts = opts || {};
  var ret = { suffix: '' };

  if (opts.hash) {
    ret.suffix += '-' + file.hash;
  }

  if (opts.debug) {
    ret.suffix += '-debug';
  }

  return ret;
}

/**
 * Exports
 */

exports.template = template;
exports.extendOption = extendOption;
exports.hideExt = hideExt;
exports.addExt = addExt;
exports.isRelative = isRelative;
exports.isLocal = isLocal;
exports.resolvePath = resolvePath;
exports.slashPath = slashPath;
exports.throwError = throwError;
exports.getRenameOpts = getRenameOpts;<commit_msg>add source files<commit_after>/**
 * Created by nuintun on 2015/4/27.
 */

'use strict';

var path = require('path');
var join = path.join;
var extname = path.extname;
var dirname = path.dirname;
var util = require('util');
var debug = require('debug')('Transport:util');

/**
 * Simple template
 * ```
 * var tpl = '{{name}}/{{version}}';
 * util.template(tpl, {name:'base', version: '1.0.0'});
 * ```
 */

function template(format, data){
  if (!format) return '';
  return format.replace(/{{([a-z]*)}}/g, function (all, match){
    return data[match] || '';
  });
}

/**
 * Set options
 */

function extendOption(options){
  var opt = {
    pkg: null, // The pkg info parsed by father
    ignore: [], // Omit the given dependencies when transport
    idleading: '{{name}}/{{version}}', // The id prefix template that can use pkg as it's data
    rename: null,
    include: 'relative'
  };

  if (!options) return opt;

  for (var key in options) {
    if (options.hasOwnProperty(key)) {
      var val = options[key];

      if (val !== undefined && val !== null) {
        opt[key] = val;
      }
    }
  }

  return opt;
}

/**
 * Hide .js if exists
 */

function hideExt(filepath){
  return extname(filepath) === '.js' ? filepath.replace(/\.js$/, '') : filepath;
}

/**
 * Add .js if not exists
 */

function addExt(filepath){
  return extname(filepath) ? filepath : (filepath + '.js');
}

/**
 * Test filepath is relative path or not
 */

function isRelative(filepath){
  return /^\.{1,2}[\\/]/.test(filepath);
}

/**
 * Test filepath is local path or not
 */

function isLocal(filepath){
  return !/^https?:\/\//.test(filepath) && !/^data:/.test(filepath);
}

/**
 * Resolve a `relative` path base on `base` path
 */

function resolvePath(relative, base){
  if (!isRelative(relative) || !base) return relative;

  debug('transport relative id(%s) of basepath(%s)', relative, base);

  relative = join(dirname(base), relative);

  if (isRelative(relative)) {
    throwError('%s is out of bound of %s', winPath(relative), base);
  }

  return relative;
}

function slashPath(path){
  return path.replace(/\\/g, '/');
}

function throwError(){
  var message = util.format.apply(null, [].slice.call(arguments));

  throw new Error(message);
}

function getRenameOpts(file, opts){
  if (typeof opts === 'function') {
    return opts;
  }

  opts = opts || {};
  var ret = { suffix: '' };

  if (opts.hash) {
    ret.suffix += '-' + file.hash;
  }

  if (opts.debug) {
    ret.suffix += '-debug';
  }

  return ret;
}

/**
 * Exports
 */

exports.template = template;
exports.extendOption = extendOption;
exports.hideExt = hideExt;
exports.addExt = addExt;
exports.isRelative = isRelative;
exports.isLocal = isLocal;
exports.resolvePath = resolvePath;
exports.slashPath = slashPath;
exports.throwError = throwError;
exports.getRenameOpts = getRenameOpts;<|endoftext|>


<commit_before>var socket = io.connect('http://localhost:3000')
socket.on('connection', function (data) {
  console.log('connected')
})
socket.on('meeting', function (data) {
  let title = 'Ingen aktiv generalforsamling.';
  console.log('d', data)

  if (data && data.title) {
    title = data.title;
  }
  document.getElementById('meeting-title').innerHTML = title;

  socket.emit('my other event', { my: 'data' })
  const node = document.createElement('p')
  node.innerHTML = title
  document.getElementById('log').appendChild(node)
});
<commit_msg>Eslint most of this dummy script<commit_after>/* global: io */
const socket = io.connect('http://localhost:3000');
socket.on('connection', () => {});
socket.on('meeting', (data) => {
  let title = 'Ingen aktiv generalforsamling.';

  if (data && data.title) {
    title = data.title;
  }
  document.getElementById('meeting-title').innerHTML = title;

  socket.emit('my other event', { my: 'data' });
  const node = document.createElement('p');
  node.innerHTML = title;
  document.getElementById('log').appendChild(node);
});
<|endoftext|>


<commit_before>/*
 * Copyright 2009-2011 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE.txt or:
 * http://opensource.org/licenses/BSD-3-Clause
 */

define(function(require, exports, module) {

var l10n = require('gcli/l10n');
var types = require('gcli/types');
var Type = require('gcli/types').Type;
var Status = require('gcli/types').Status;
var Conversion = require('gcli/types').Conversion;

/**
 * Registration and de-registration.
 */
exports.startup = function() {
  types.registerType(DateType);
};

exports.shutdown = function() {
  types.unregisterType(DateType);
};

function DateType(typeSpec) {
  /* ECMA 5.1 §15.9.1.1
   * @see http://stackoverflow.com/questions/11526504/minimum-and-maximum-date
   */
  if (typeSpec) {
    this._step = typeSpec.step || 1;
    this._min = typeSpec.min || new Date(-8640000000000000);
    this._max = typeSpec.max || new Date(8640000000000000);
  }
  else {
    this._step = 1;
    this._min = new Date(-8640000000000000);
    this._max = new Date(8640000000000000);
  }
}

DateType.prototype = Object.create(Type.prototype);

DateType.prototype.stringify = function(value) {
  if (!this._isValidDate(value)) {
    return '';
  }
  return value.toString();
};

DateType.prototype.getMin = function() {
  if (typeof this._min === 'function') {
    return this._min();
  }
  if (Object.prototype.toString.call(this._min) === '[object Date]') {
    return this._min;
  }
  return undefined;
};

DateType.prototype.getMax = function() {
  if (typeof this._max === 'function') {
    return this._max();
  }
  if (Object.prototype.toString.call(this._max) === '[object Date]') {
    return this._max;
  }
  return undefined;
};

DateType.prototype.parse = function(arg) {
  var value;

  if (arg.text.replace(/\s/g, '').length === 0) {
    return new Conversion(undefined, arg, Status.INCOMPLETE, '');
  }

  // Lots of room for improvement here: 1h ago, in two days, etc.
  // Should "1h ago" dynamically update the step?
  if (arg.text === 'now') {
    value = new Date();
  } else if (arg.text === 'yesterday') {
    value = new Date().setDate(new Date().getDate() - 1);
  } else if (arg.text === 'tomorrow') {
    value = new Date().setDate(new Date().getDate() + 1);
  } else {
    value = Date.parse(arg.text);
    if (isNaN(value)) {
      return new Conversion(undefined, arg, Status.ERROR,
          l10n.lookupFormat('typesDateNan', [ arg.text ]));
    }
  }

  return new Conversion(value, arg);
};

DateType.prototype.decrement = function(value) {
  if (!this._isValidDate(value)) {
    return this._getDefault();
  }
  var newValue = new Date(value);
  newValue.setDate(value.getDate() - this._step);
  if (newValue >= this.getMin()) {
    return newValue;
  } else {
    return this.getMin();
  }
};

DateType.prototype.increment = function(value) {
  console.log('increment!');
  if (!this._isValidDate(value)) {
    console.log('invalid anyway');
    return this._getDefault();
  }
  var newValue = new Date(value);
  newValue.setDate(value.getDate() + this._step);
  if (newValue <= this.getMax()) {
    return newValue;
  } else {
    return this.getMax();
  }
};

/**
 * Is |thing| a valid date?
 * @see http://stackoverflow.com/questions/1353684/detecting-an-invalid-date-date-instance-in-javascript
 */
DateType.prototype._isValidDate = function(thing) {
  return Object.prototype.toString.call(thing) === "[object Date]"
          && !isNaN(thing.getTime());
};

DateType.prototype._getDefault = function() {
  return new Date();
}

DateType.prototype.name = 'date';

exports.DateType = DateType;

});
<commit_msg>date-773271: Remove two console.log used for debugging<commit_after>/*
 * Copyright 2009-2011 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE.txt or:
 * http://opensource.org/licenses/BSD-3-Clause
 */

define(function(require, exports, module) {

var l10n = require('gcli/l10n');
var types = require('gcli/types');
var Type = require('gcli/types').Type;
var Status = require('gcli/types').Status;
var Conversion = require('gcli/types').Conversion;

/**
 * Registration and de-registration.
 */
exports.startup = function() {
  types.registerType(DateType);
};

exports.shutdown = function() {
  types.unregisterType(DateType);
};

function DateType(typeSpec) {
  /* ECMA 5.1 §15.9.1.1
   * @see http://stackoverflow.com/questions/11526504/minimum-and-maximum-date
   */
  if (typeSpec) {
    this._step = typeSpec.step || 1;
    this._min = typeSpec.min || new Date(-8640000000000000);
    this._max = typeSpec.max || new Date(8640000000000000);
  }
  else {
    this._step = 1;
    this._min = new Date(-8640000000000000);
    this._max = new Date(8640000000000000);
  }
}

DateType.prototype = Object.create(Type.prototype);

DateType.prototype.stringify = function(value) {
  if (!this._isValidDate(value)) {
    return '';
  }
  return value.toString();
};

DateType.prototype.getMin = function() {
  if (typeof this._min === 'function') {
    return this._min();
  }
  if (Object.prototype.toString.call(this._min) === '[object Date]') {
    return this._min;
  }
  return undefined;
};

DateType.prototype.getMax = function() {
  if (typeof this._max === 'function') {
    return this._max();
  }
  if (Object.prototype.toString.call(this._max) === '[object Date]') {
    return this._max;
  }
  return undefined;
};

DateType.prototype.parse = function(arg) {
  var value;

  if (arg.text.replace(/\s/g, '').length === 0) {
    return new Conversion(undefined, arg, Status.INCOMPLETE, '');
  }

  // Lots of room for improvement here: 1h ago, in two days, etc.
  // Should "1h ago" dynamically update the step?
  if (arg.text === 'now') {
    value = new Date();
  } else if (arg.text === 'yesterday') {
    value = new Date().setDate(new Date().getDate() - 1);
  } else if (arg.text === 'tomorrow') {
    value = new Date().setDate(new Date().getDate() + 1);
  } else {
    value = Date.parse(arg.text);
    if (isNaN(value)) {
      return new Conversion(undefined, arg, Status.ERROR,
          l10n.lookupFormat('typesDateNan', [ arg.text ]));
    }
  }

  return new Conversion(value, arg);
};

DateType.prototype.decrement = function(value) {
  if (!this._isValidDate(value)) {
    return this._getDefault();
  }
  var newValue = new Date(value);
  newValue.setDate(value.getDate() - this._step);
  if (newValue >= this.getMin()) {
    return newValue;
  } else {
    return this.getMin();
  }
};

DateType.prototype.increment = function(value) {
  if (!this._isValidDate(value)) {
    return this._getDefault();
  }
  var newValue = new Date(value);
  newValue.setDate(value.getDate() + this._step);
  if (newValue <= this.getMax()) {
    return newValue;
  } else {
    return this.getMax();
  }
};

/**
 * Is |thing| a valid date?
 * @see http://stackoverflow.com/questions/1353684/detecting-an-invalid-date-date-instance-in-javascript
 */
DateType.prototype._isValidDate = function(thing) {
  return Object.prototype.toString.call(thing) === "[object Date]"
          && !isNaN(thing.getTime());
};

DateType.prototype._getDefault = function() {
  return new Date();
}

DateType.prototype.name = 'date';

exports.DateType = DateType;

});
<|endoftext|>


<commit_before>var exec = require('cordova/exec');

var Swiper = function() {};

Swiper.initialize = function(success, error) {
	exec(success, error, 'UniMagSwiper', 'initializeSwiper', []);
};

Swiper.activate = function(success, error) {
	exec(success, error, 'UniMagSwiper', 'activateSwiper', []);
};

Swiper.deactivate = function(success, error) {
	exec(success, error, 'UniMagSwiper', 'deactivateSwiper', []);
};

Swiper.swiperDidRecieveData = function (data) {
	alert(data);
};

Swiper.swiperDidRecieveError = function (error) {
    alert('Error:');
    alert(error);
};

Swiper.swiperDidAttach = function (attachStatus) {
    alert(attachStatus);
};

Swiper.swiperDidConnect = function (connectStatus) {
    alert(connectStatus);
};

Swiper.swiperDidStartSwipe = function () {
    alert('Did Start Swipe');
    document.addEventListener('swipeDidStart', unimagIISwiperDidStart('Started'));
};

module.exports = Swiper;
<commit_msg>Minor fix.<commit_after>var exec = require('cordova/exec');

var Swiper = function() {};

Swiper.initialize = function(success, error) {
	exec(success, error, 'UniMagSwiper', 'initializeSwiper', []);
};

Swiper.activate = function(success, error) {
	exec(success, error, 'UniMagSwiper', 'activateSwiper', []);
};

Swiper.deactivate = function(success, error) {
	exec(success, error, 'UniMagSwiper', 'deactivateSwiper', []);
};

Swiper.swiperDidRecieveData = function (data) {
	alert(data);
};

Swiper.swiperDidRecieveError = function (error) {
    alert('Error from js!');
    alert(error);
};

Swiper.swiperDidAttach = function (attachStatus) {
    alert(attachStatus);
};

Swiper.swiperDidConnect = function (connectStatus) {
    alert(connectStatus);
};

Swiper.swiperDidStartSwipe = function () {
    alert('Did Start Swipe');
};

module.exports = Swiper;
<|endoftext|>


<commit_before>/* global: io */
const socket = io.connect('http://localhost:3000');
socket.on('connection', () => {});
socket.on('meeting', (data) => {
  let title = 'Ingen aktiv generalforsamling.';

  if (data && data.title) {
    title = data.title;
  }
  document.getElementById('meeting-title').innerHTML = title;

  socket.emit('my other event', { my: 'data' });
  const node = document.createElement('p');
  node.innerHTML = title;
  document.getElementById('log').appendChild(node);

  console.log('emitting issue thingy');
  socket.emit('issue', { action: 'open', title: 'Mitt spørsmål' });
  setTimeout(() => {
    socket.emit('issue', { action: 'close', title: 'Mitt spørsmål' });
  }, 10000)
});

socket.on('issue', (data) => {
  let question = 'Ingen aktiv sak for øyeblikket.';
  if (data && data.title && data.action !== 'close') {
    question = data.title;
  }
  document.getElementById('question').innerHTML = question;
});
<commit_msg>Update testing frontend a bit<commit_after>/* global: io */
const socket = io.connect('http://localhost:3000');
socket.on('connection', () => {});
socket.on('meeting', (data) => {
  let title = 'Ingen aktiv generalforsamling.';

  if (data && data.title) {
    title = data.title;
  }
  document.getElementById('meeting-title').innerHTML = title;

  socket.emit('my other event', { my: 'data' });
  const node = document.createElement('p');
  node.innerHTML = title;
  document.getElementById('log').appendChild(node);

  console.log('emitting issue thingy');
  socket.emit('issue', { action: 'open', title: 'Mitt spørsmål' });
  setTimeout(() => {
    socket.emit('issue', { action: 'close', title: 'Mitt spørsmål' });
  }, 10000);
});

socket.on('public', (data) => {
  console.log('public', data);
});

socket.on('private', (data) => {
  console.log('priv', data);
});

socket.on('issue', (data) => {
  console.log('issue', data);
  let question = 'Ingen aktiv sak for øyeblikket.';
  if (data && data.title && data.action !== 'close') {
    question = data.title;
  }
  document.getElementById('question').innerHTML = question;
});
<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');
var _ = require('underscore');
var async = require('async');
var Handlebars = require('handlebars');
var documentjs = require('../document');
var utils = require('./generator/utilities');
var beautify = require('js-beautify').js_beautify;

/**
 * Takes a list of files and generates the documentation
 *
 * @param files
 * @param configuration
 * @param callback
 */
module.exports = function (files, options, callback) {
	var configuration = _.extend({
		ignore: function (data) {
			return data.hide || data.type === 'script' ||
				data.type === 'static' ||
				data.type === 'prototype';
		}
	}, options);
	var jsonWriter = function(file, jsonData) {
		return function(callback) {
			var filename = path.join(configuration.out, file);
			fs.writeFile(filename, beautify(JSON.stringify(jsonData)), function(error) {
				callback(error, filename);
			});
		}
	}
	var layout = Handlebars.compile(fs.readFileSync(configuration.layout).toString());
	var renderer = Handlebars.compile(fs.readFileSync(configuration.docs).toString());
	var docFiles = _.filter(files, function(file) {
		return /(\.md)|(\.js)/.test(file);
	});
	var staticFiles = _.difference(files, docFiles);

	if (!fs.existsSync(configuration.out)) {
		fs.mkdirSync(configuration.out);
	}

	utils.handlebarsHelpers(_.extend({}, utils.helpers, options.helpers), Handlebars);
	utils.handlebarsPartials(path.dirname(configuration.docs) + '/', Handlebars);

	documentjs(docFiles, function (error, docData, search) {
		var writers = [];
		var rootItem = utils.menuTree(docData, configuration.parent);

		// Write searchdata only if we have files do document
		if(docFiles.length) {
			writers.push(jsonWriter('searchdata.json', search));

			// Write JSON files for debugging
			if(options.debug) {
				writers.push(jsonWriter('documentjs-debug.json', docData), jsonWriter('rootItem-debug.json', rootItem));
			}
		}

		// Generates static pages
		writers.push.apply(writers, staticFiles.map(function(file) {
			return function(cb) {
				fs.readFile(file, function(error, data) {
					if(error) {
						return cb(error);
					}

					var source = data.toString();
					var renderer = Handlebars.compile(source);
					var page = utils.name(path.basename(file));
					var filename = path.join(configuration.out, page + '.html');
					var source = layout(_.defaults({
						root: configuration.root,
						page: page,
						content: renderer(configuration)
					}, configuration));

					fs.writeFile(filename, source, function (error) {
						cb(error, filename);
					});
				});
			}
		}));

		// Generates DocumentJS pages
		_.each(docData, function (currentData, name) {
			if (!configuration.ignore(currentData, name)) {
				writers.push(function (callback) {
					// Set the active item from the given name
					utils.activateItems(rootItem, name);

					var filename = path.join(configuration.out, (name === configuration.parent ? 'index.html' : utils.docsFilename(name)));
					var data = _.extend({
						menu: rootItem,
						DocumentJS: docData
					}, configuration, currentData);

					if(options.debug) {
						data.debug = beautify(JSON.stringify(currentData));
					}

					var contents = layout(_.extend({
						content: renderer(data)
					}, configuration));

					fs.writeFile(filename, contents, function (error) {
						callback(error, filename);
					});
				});
			}
		});

		// Now let all file writers (a list of callback functions) run in parallel
		async.parallel(writers, callback);
	});
}
<commit_msg>Fixing another reference<commit_after>var fs = require('fs');
var path = require('path');
var _ = require('underscore');
var async = require('async');
var Handlebars = require('handlebars');
var documentjs = require('../document');
var utils = require('./utilities');
var beautify = require('js-beautify').js_beautify;

/**
 * Takes a list of files and generates the documentation
 *
 * @param files
 * @param configuration
 * @param callback
 */
module.exports = function (files, options, callback) {
	var configuration = _.extend({
		ignore: function (data) {
			return data.hide || data.type === 'script' ||
				data.type === 'static' ||
				data.type === 'prototype';
		}
	}, options);
	var jsonWriter = function(file, jsonData) {
		return function(callback) {
			var filename = path.join(configuration.out, file);
			fs.writeFile(filename, beautify(JSON.stringify(jsonData)), function(error) {
				callback(error, filename);
			});
		}
	}
	var layout = Handlebars.compile(fs.readFileSync(configuration.layout).toString());
	var renderer = Handlebars.compile(fs.readFileSync(configuration.docs).toString());
	var docFiles = _.filter(files, function(file) {
		return /(\.md)|(\.js)/.test(file);
	});
	var staticFiles = _.difference(files, docFiles);

	if (!fs.existsSync(configuration.out)) {
		fs.mkdirSync(configuration.out);
	}

	utils.handlebarsHelpers(_.extend({}, utils.helpers, options.helpers), Handlebars);
	utils.handlebarsPartials(path.dirname(configuration.docs) + '/', Handlebars);

	documentjs(docFiles, function (error, docData, search) {
		var writers = [];
		var rootItem = utils.menuTree(docData, configuration.parent);

		// Write searchdata only if we have files do document
		if(docFiles.length) {
			writers.push(jsonWriter('searchdata.json', search));

			// Write JSON files for debugging
			if(options.debug) {
				writers.push(jsonWriter('documentjs-debug.json', docData), jsonWriter('rootItem-debug.json', rootItem));
			}
		}

		// Generates static pages
		writers.push.apply(writers, staticFiles.map(function(file) {
			return function(cb) {
				fs.readFile(file, function(error, data) {
					if(error) {
						return cb(error);
					}

					var source = data.toString();
					var renderer = Handlebars.compile(source);
					var page = utils.name(path.basename(file));
					var filename = path.join(configuration.out, page + '.html');
					var source = layout(_.defaults({
						root: configuration.root,
						page: page,
						content: renderer(configuration)
					}, configuration));

					fs.writeFile(filename, source, function (error) {
						cb(error, filename);
					});
				});
			}
		}));

		// Generates DocumentJS pages
		_.each(docData, function (currentData, name) {
			if (!configuration.ignore(currentData, name)) {
				writers.push(function (callback) {
					// Set the active item from the given name
					utils.activateItems(rootItem, name);

					var filename = path.join(configuration.out, (name === configuration.parent ? 'index.html' : utils.docsFilename(name)));
					var data = _.extend({
						menu: rootItem,
						DocumentJS: docData
					}, configuration, currentData);

					if(options.debug) {
						data.debug = beautify(JSON.stringify(currentData));
					}

					var contents = layout(_.extend({
						content: renderer(data)
					}, configuration));

					fs.writeFile(filename, contents, function (error) {
						callback(error, filename);
					});
				});
			}
		});

		// Now let all file writers (a list of callback functions) run in parallel
		async.parallel(writers, callback);
	});
}
<|endoftext|>


<commit_before>/**
 * @fileoverview 간단한 상속 시뮬레이션
 * @author FE개발팀
 */

(function(ne) {
    'use strict';
    if (!ne) {
        ne = window.ne = {};
    }

    /**
     * 전달된 객체를 prototype으로 사용하는 객체를 만들어 반환하는 메서드
     * @param {Object} obj
     * @return {Object}
     */
    ne.createObject = function(obj) {
        function F() {}
        F.prototype = obj;
        return new F;
    };

    /**
     * 단순 prototype 확장을 응용한 상속 메서드
     *
     * **주의점**
     *
     * 단순 프로토타입 확장 기능만 제공하므로 자식 생성자의 prototype을 덮어쓰면 안된다.
     *
     * @example
     * function Animal(leg) {
     *     this.leg = leg;
     * }
     *
     * Animal.prototype.growl = function() {
     *     // ...
     * };
     *
     * function Person(name) {
     *     this.name = name;
     * }
     *
     * // 상속
     * core.inherit(Person, Animal);
     *
     * // 이 이후부터는 프로퍼티 편집만으로 확장해야 한다.
     * Person.prototype.walk = function(direction) {
     *     // ...
     * };
     * @param {function} subType 자식 생성자 함수
     * @param {function} superType 부모 생성자 함수
     */
    ne.inherit = function(subType, superType) {
        var prototype = ne.createObject(superType.prototype);
        prototype.constructor = subType;
        subType.prototype = prototype;
    };

})(window.ne);
<commit_msg>inheritance 모듈 주석 수정<commit_after>/**
 * @fileoverview 간단한 상속 시뮬레이션
 * @author FE개발팀
 */

(function(ne) {
    'use strict';
    /* istanbul ignore if */
    if (!ne) {
        ne = window.ne = {};
    }

    /**
     * 전달된 객체를 prototype으로 사용하는 객체를 만들어 반환하는 메서드
     * @param {Object} obj
     * @return {Object}
     */
    ne.createObject = function(obj) {
        function F() {}
        F.prototype = obj;
        return new F;
    };

    /**
     * 단순 prototype 확장을 응용한 상속 메서드
     *
     * **주의점**
     *
     * 단순 프로토타입 확장 기능만 제공하므로 자식 생성자의 prototype을 덮어쓰면 안된다.
     *
     * @example
     * function Animal(leg) {
     *     this.leg = leg;
     * }
     *
     * Animal.prototype.growl = function() {
     *     // ...
     * };
     *
     * function Person(name) {
     *     this.name = name;
     * }
     *
     * // 상속
     * core.inherit(Person, Animal);
     *
     * // 이 이후부터는 프로퍼티 편집만으로 확장해야 한다.
     * Person.prototype.walk = function(direction) {
     *     // ...
     * };
     * @param {function} subType 자식 생성자 함수
     * @param {function} superType 부모 생성자 함수
     */
    ne.inherit = function(subType, superType) {
        var prototype = ne.createObject(superType.prototype);
        prototype.constructor = subType;
        subType.prototype = prototype;
    };

})(window.ne);
<|endoftext|>