<commit_before>'use strict';

var request = require("request");
var defaultUserAgent = require("./user_agent");

// @constructor
// @param {string} apiToken the Dialog API token
// @param {string} botId the Dialog bot Id
function Client(apiToken, botId) {
  this.apiEndpoint = "https://api.dialoganalytics.com/v1/";
  this.apiToken = apiToken;
  this.botId = botId;
  this.userAgent = defaultUserAgent;
};
module.exports = Client;

// @param {Object} payload Properties expected by the track API endpoint
// @param {Function} callback
// @returns {Object}
// @see https://docs.dialoganalytics.com/reference/track/
Client.prototype.track = function(payload, callback) {
  var options = {
    url: this.apiEndpoint + "b/" + this.botId + "/track",
    json: payload
  };

  return this.post(options, callback);
};

// @param {String} url
// @returns {String}
// @see https://docs.dialoganalytics.com/reference/click-tracking/
Client.prototype.link = function(url) {
  return this.apiEndpoint + "click/" + this.botId + "?url=" + encodeURIComponent(url);
};

// @param {String} conversationId
// @returns
// @see https://docs.dialoganalytics.com/reference/message#list
Client.prototype.listMessages = function(conversationId) {
  var options = {
    url: this.apiEndpoint + "b/" + this.botId + "/conversations/" + conversationId + "/messages"
  };

  this.get(options);
};

// @param {String} conversationId
// @param {String} messageId
// @returns {Object}
// @see https://docs.dialoganalytics.com/reference/message#retrieve
Client.prototype.retrieveMessage = function(conversationId, messageId) {
  var options = {
    url: this.apiEndpoint + "b/" + this.botId + "/conversations/" + conversationId + "/messages/" + messageId
  };

  this.get(options);
};

// @returns {Object}
// @see https://docs.dialoganalytics.com/reference/conversation#list
Client.prototype.listConversations = function() {
  var options = {
    url: this.apiEndpoint + "b/" + this.botId + "/conversations/"
  };

  this.get(options);
};

// @param {String} conversationId
// @returns {Object}
// @see https://docs.dialoganalytics.com/reference/conversation#retrieve
Client.prototype.retrieveConversation = function(conversationId) {
  var options = {
    url: this.apiEndpoint + "b/" + this.botId + "/conversations/" + conversationId
  };

  this.get(options);
};

// @returns {Object}
// @see https://docs.dialoganalytics.com/reference/interlocutor#list
Client.prototype.listInterlocutors = function() {
  var options = {
    url: this.apiEndpoint + "b/" + this.botId + "/interlocutors/"
  };

  this.get(options);
};

// @param {String} interlocutorId
// @returns {Object}
// @see https://docs.dialoganalytics.com/reference/interlocutor#retrieve
Client.prototype.retrieveInterlocutor = function(interlocutorId) {
  var options = {
    url: this.apiEndpoint + "b/" + this.botId + "/interlocutors/" + interlocutorId
  };

  this.get(options);
};

// @param {Object} params
// @returns {Object}
// @see https://docs.dialoganalytics.com/reference/interlocutor#create
Client.prototype.createInterlocutor = function(params) {
  var options = {
    url: this.apiEndpoint + "b/" + this.botId + "/interlocutors/",
    json: { interlocutor: params }
  };

  this.post(options);
};

// @param {Object} options
// @param {Function} callback
// @returns {Object}
Client.prototype.get = function(options, callback) {
  options.headers = {
    'User-Agent': this.defaultUserAgent,
    'Authorization': 'Api-Key ' + this.apiToken
  };

  var callback = function(error, response, body) {
    // noop
  };

  return request.get(options, callback);
};

// @param {Object} options
// @param {Function} callback
// @returns {Object}
Client.prototype.post = function(options, callback) {
  options.headers = {
    'User-Agent': this.defaultUserAgent,
    'Authorization': 'Api-Key ' + this.apiToken
  };

  var callback = function(error, response, body) {
    // noop
  };

  return request.post(options, callback);
};
<commit_msg>Accept a callback for every client function<commit_after>'use strict';

var request = require("request");
var defaultUserAgent = require("./user_agent");

// @constructor
// @param {string} apiToken the Dialog API token
// @param {string} botId the Dialog bot Id
function Client(apiToken, botId) {
  this.apiEndpoint = "https://api.dialoganalytics.com/v1/";
  this.apiToken = apiToken;
  this.botId = botId;
  this.userAgent = defaultUserAgent;
};
module.exports = Client;

// @param {Object} payload Properties expected by the track API endpoint
// @param {Function} callback
// @returns {Object}
// @see https://docs.dialoganalytics.com/reference/track/
Client.prototype.track = function(payload, callback) {
  var options = {
    url: this.apiEndpoint + "b/" + this.botId + "/track",
    json: payload
  };

  return this.post(options, callback);
};

// @param {String} url
// @returns {String}
// @see https://docs.dialoganalytics.com/reference/click-tracking/
Client.prototype.link = function(url) {
  return this.apiEndpoint + "click/" + this.botId + "?url=" + encodeURIComponent(url);
};

// @param {String} conversationId
// @returns
// @see https://docs.dialoganalytics.com/reference/message#list
Client.prototype.listMessages = function(conversationId, callback) {
  var options = {
    url: this.apiEndpoint + "b/" + this.botId + "/conversations/" + conversationId + "/messages"
  };

  this.get(options, callback);
};

// @param {String} conversationId
// @param {String} messageId
// @returns {Object}
// @see https://docs.dialoganalytics.com/reference/message#retrieve
Client.prototype.retrieveMessage = function(conversationId, messageId, callback) {
  var options = {
    url: this.apiEndpoint + "b/" + this.botId + "/conversations/" + conversationId + "/messages/" + messageId
  };

  this.get(options, callback);
};

// @returns {Object}
// @see https://docs.dialoganalytics.com/reference/conversation#list
Client.prototype.listConversations = function(callback) {
  var options = {
    url: this.apiEndpoint + "b/" + this.botId + "/conversations/"
  };

  this.get(options, callback);
};

// @param {String} conversationId
// @returns {Object}
// @see https://docs.dialoganalytics.com/reference/conversation#retrieve
Client.prototype.retrieveConversation = function(conversationId, callback) {
  var options = {
    url: this.apiEndpoint + "b/" + this.botId + "/conversations/" + conversationId
  };

  this.get(options, callback);
};

// @returns {Object}
// @see https://docs.dialoganalytics.com/reference/interlocutor#list
Client.prototype.listInterlocutors = function(callback) {
  var options = {
    url: this.apiEndpoint + "b/" + this.botId + "/interlocutors/"
  };

  this.get(options, callback);
};

// @param {String} interlocutorId
// @returns {Object}
// @see https://docs.dialoganalytics.com/reference/interlocutor#retrieve
Client.prototype.retrieveInterlocutor = function(interlocutorId, callback) {
  var options = {
    url: this.apiEndpoint + "b/" + this.botId + "/interlocutors/" + interlocutorId
  };

  this.get(options, callback);
};

// @param {Object} params
// @returns {Object}
// @see https://docs.dialoganalytics.com/reference/interlocutor#create
Client.prototype.createInterlocutor = function(params, callback) {
  var options = {
    url: this.apiEndpoint + "b/" + this.botId + "/interlocutors/",
    json: { interlocutor: params }
  };

  this.post(options, callback);
};

// @param {Object} options
// @param {Function} callback
// @returns {Object}
Client.prototype.get = function(options, callback) {
  options.headers = {
    'User-Agent': this.defaultUserAgent,
    'Authorization': 'Api-Key ' + this.apiToken
  };

  var callback = callback || function(error, response, body) {
    // noop
  };

  return request.get(options, callback);
};

// @param {Object} options
// @param {Function} callback
// @returns {Object}
Client.prototype.post = function(options, callback) {
  options.headers = {
    'User-Agent': this.defaultUserAgent,
    'Authorization': 'Api-Key ' + this.apiToken
  };

  var callback = callback || function(error, response, body) {
    // noop
  };

  return request.post(options, callback);
};
<|endoftext|>


<commit_before>import Ember from 'ember';

export default Ember.Component.extend({
  store: Ember.inject.service(),
  actions: {
    saveJudge() {
      var judge = this.get('store').createRecord('judge', {
        session: this.get('model'),
        certification: this.get('certification'),
        kind: "Official",
        category: this.get('certification.category'),
      });
      const flashMessages = Ember.get(this, 'flashMessages');
      judge.save()
      .then(() => {
        flashMessages.success('Judge Added');
        this.set('certification', null);
        this.set('kind', null);
        this.set('category', null);
      })
      .catch(() => {
        flashMessages.danger('Error');
      });
    },
    searchJudge(term) {
      return new Ember.RSVP.Promise((resolve, reject) => {
        Ember.run.debounce(this, this._performSearch, term, resolve, reject, 600);
      });
    },
  },
  judgeKind: [
    'Official',
    'Practice',
  ],
  judgeCategory: [
    'Music',
    'Presentation',
    'Singing',
  ],
  _performSearch(term, resolve, reject) {
    if (Ember.isBlank(term)) { return resolve([]); }
    this.get('store').query('certification', {'name__icontains': term})
      .then(data => resolve(data), reject);
  }
});
<commit_msg>Remove flash<commit_after>import Ember from 'ember';

export default Ember.Component.extend({
  store: Ember.inject.service(),
  actions: {
    saveJudge() {
      var judge = this.get('store').createRecord('judge', {
        session: this.get('model'),
        certification: this.get('certification'),
        kind: "Official",
        category: this.get('certification.category'),
      });
      const flashMessages = Ember.get(this, 'flashMessages');
      judge.save()
      .then(() => {
        this.set('certification', null);
      })
      .catch(() => {
        flashMessages.danger('Error');
      });
    },
    searchJudge(term) {
      return new Ember.RSVP.Promise((resolve, reject) => {
        Ember.run.debounce(this, this._performSearch, term, resolve, reject, 600);
      });
    },
  },
  judgeKind: [
    'Official',
    'Practice',
  ],
  judgeCategory: [
    'Music',
    'Presentation',
    'Singing',
  ],
  _performSearch(term, resolve, reject) {
    if (Ember.isBlank(term)) { return resolve([]); }
    this.get('store').query('certification', {'name__icontains': term})
      .then(data => resolve(data), reject);
  }
});
<|endoftext|>


<commit_before>SearchSource = function SearchSource(source, fields, options) {
  this.source = source;
  this.searchFields = fields;
  this.currentQuery = null;
  this.options = options || {};

  this.status =  new ReactiveVar({loaded: true});
  this.metaData = new ReactiveVar({});
  this.history = {};
  this.store = new Mongo.Collection(null);

  this._storeDep = new Tracker.Dependency();
  this._currentQueryDep = new Tracker.Dependency();
  this._currentVersion = 0;
  this._loadedVersion = 0;
}

SearchSource.prototype._loadData = function(query, options) {
  var self = this;
  var version = 0;
  if(this._canUseHistory(query)) {
    this._updateStore(this.history[query].data);
    this.metaData.set(this.history[query].metadata);
    self._storeDep.changed();
  } else {
    this.status.set({loading: true});
    version = ++this._currentVersion;
    this._fetch(this.source, query, options, handleData);
  }

  function handleData(err, payload) {
    if(err) {
      self.status.set({error: err});
      throw err;
    } else {
      if(payload instanceof Array) {
        var data = payload;
        var metadata = {};
      } else {
        var data = payload.data;
        var metadata = payload.metadata;
        self.metaData.set(payload.metadata || {});
      }

      if(self.options.keepHistory) {
        self.history[query] = {data: data, loaded: new Date(), metadata: metadata};
      }

      if(version > self._loadedVersion) {
        self._updateStore(data);
        self._loadedVersion = version;
      }

      if(version == self._currentVersion) {
        self.status.set({loaded: true});
      }

      self._storeDep.changed();
    }
  }
};

SearchSource.prototype._canUseHistory = function(query) {
  var historyItem = this.history[query];
  if(this.options.keepHistory && historyItem) {
    var diff = Date.now() - historyItem.loaded.getTime();
    return diff < this.options.keepHistory;
  }

  return false;
};

SearchSource.prototype._updateStore = function(data) {
  var self = this;
  var storeIds = _.pluck(this.store.find().fetch(), "_id");
  var currentIds = [];
  data.forEach(function(item) {
    currentIds.push(item._id);
    self.store.update(item._id, item, {upsert: true});
  });

  // Remove items in client DB that we no longer need
  var currentIdStrs = _.map(currentIds, function(currentId){
    return currentId._str;
  });
  var removedItems = _.reject(storeIds, function(storeId) {
    return _.contains(currentIdStrs, storeId._str);
  });
  removedItems.forEach(function(id) {
    self.store.remove(id);
  });
};

SearchSource.prototype.search = function(query, options) {
  this.currentQuery = query;
  this._currentQueryDep.changed();

  this._loadData(query, options);

  if(this.options.localSearch) {
    this._storeDep.changed();
  }
};

SearchSource.prototype.getData = function(options, getCursor) {
  options = options || {};
  var self = this;
  this._storeDep.depend();
  var selector = {$or: []};

  var regExp = this._buildRegExp(self.currentQuery);

  // only do client side searching if we are on the loading state
  // once loaded, we need to send all of them
  if(this.getStatus().loading) {
    self.searchFields.forEach(function(field) {
      var singleQuery = {};
      singleQuery[field] = regExp;
      selector['$or'].push(singleQuery);
    });
  } else {
    selector = {};
  }

  function transform(doc) {
    if(options.transform) {
      self.searchFields.forEach(function(field) {
        if(self.currentQuery && doc[field]) {
          doc[field] = options.transform(doc[field], regExp, field, self.currentQuery);
        }
      });
    }
    if(options.docTransform) {
      return options.docTransform(doc);
    }

    return doc;
  }

  var cursor = this.store.find(selector, {
    sort: options.sort,
    limit: options.limit,
    transform: transform
  });

  if(getCursor) {
    return cursor;
  }

  return cursor.fetch();
};

SearchSource.prototype._fetch = function(source, query, options, callback) {
  if(typeof this.fetchData == 'function') {
    this.fetchData(query, options, callback);
  } else if(Meteor.status().connected) {
    this._fetchDDP.apply(this, arguments);
  } else {
    this._fetchHttp.apply(this, arguments);
  }
};

SearchSource.prototype._fetchDDP = function(source, query, options, callback) {
  Meteor.call("search.source", this.source, query, options, callback);
};

SearchSource.prototype._fetchHttp = function(source, query, options, callback) {
  var payload = {
    source: source,
    query: query,
    options: options
  };

  var headers = {
    "Content-Type": "text/ejson"
  };

  HTTP.post('/_search-source', {
    content: EJSON.stringify(payload),
    headers: headers
  }, function(err, res) {
    if(err) {
      callback(err);
    } else {
      var response = EJSON.parse(res.content);
      if(response.error) {
        callback(response.error);
      } else {
        callback(null, response.data);
      }
    }
  });
};

SearchSource.prototype.getMetadata = function() {
  return this.metaData.get();
};

SearchSource.prototype.getCurrentQuery = function() {
  this._currentQueryDep.depend();
  return this.currentQuery;
}

SearchSource.prototype.getStatus = function() {
  return this.status.get();
};

SearchSource.prototype.cleanHistory = function() {
  this.history = {};
};

SearchSource.prototype._buildRegExp = function(query) {
  query = query || "";

  var afterFilteredRegExpChars = query.replace(this._getRegExpFilterRegExp(), "\\$&");
  var parts = afterFilteredRegExpChars.trim().split(' ');

  return new RegExp("(" + parts.join('|') + ")", "ig");
};

SearchSource.prototype._getRegExpFilterRegExp = _.once(function() {
  var regExpChars = [
    "\\", "^", "$", "*", "+", "?", ".",
     "(", ")", ":", "|", "{", "}", "[", "]",
     "=", "!", ","
  ];
  var regExpCharsReplace = _.map(regExpChars, function(c) {
    return "\\" + c;
  }).join("|");
  return new RegExp("(" + regExpCharsReplace + ")", "g");
});<commit_msg>check if Ids are pure strings for some cases<commit_after>SearchSource = function SearchSource(source, fields, options) {
  this.source = source;
  this.searchFields = fields;
  this.currentQuery = null;
  this.options = options || {};

  this.status =  new ReactiveVar({loaded: true});
  this.metaData = new ReactiveVar({});
  this.history = {};
  this.store = new Mongo.Collection(null);

  this._storeDep = new Tracker.Dependency();
  this._currentQueryDep = new Tracker.Dependency();
  this._currentVersion = 0;
  this._loadedVersion = 0;
}

SearchSource.prototype._loadData = function(query, options) {
  var self = this;
  var version = 0;
  if(this._canUseHistory(query)) {
    this._updateStore(this.history[query].data);
    this.metaData.set(this.history[query].metadata);
    self._storeDep.changed();
  } else {
    this.status.set({loading: true});
    version = ++this._currentVersion;
    this._fetch(this.source, query, options, handleData);
  }

  function handleData(err, payload) {
    if(err) {
      self.status.set({error: err});
      throw err;
    } else {
      if(payload instanceof Array) {
        var data = payload;
        var metadata = {};
      } else {
        var data = payload.data;
        var metadata = payload.metadata;
        self.metaData.set(payload.metadata || {});
      }

      if(self.options.keepHistory) {
        self.history[query] = {data: data, loaded: new Date(), metadata: metadata};
      }

      if(version > self._loadedVersion) {
        self._updateStore(data);
        self._loadedVersion = version;
      }

      if(version == self._currentVersion) {
        self.status.set({loaded: true});
      }

      self._storeDep.changed();
    }
  }
};

SearchSource.prototype._canUseHistory = function(query) {
  var historyItem = this.history[query];
  if(this.options.keepHistory && historyItem) {
    var diff = Date.now() - historyItem.loaded.getTime();
    return diff < this.options.keepHistory;
  }

  return false;
};

SearchSource.prototype._updateStore = function(data) {
  var self = this;
  var storeIds = _.pluck(this.store.find().fetch(), "_id");
  var currentIds = [];
  data.forEach(function(item) {
    currentIds.push(item._id);
    self.store.update(item._id, item, {upsert: true});
  });

  // Remove items in client DB that we no longer need
  var currentIdStrs = _.map(currentIds, function(currentId){
    return (typeof(currentId) == 'string') ? currentId : currentId._str;
  });
  var removedItems = _.reject(storeIds, function(storeId) {
    storeId = (typeof(storeId) == 'string') ? storeId : storeId._str;
    return _.contains(currentIdStrs, storeId);
  });
  removedItems.forEach(function(id) {
    self.store.remove(id);
  });
};

SearchSource.prototype.search = function(query, options) {
  this.currentQuery = query;
  this._currentQueryDep.changed();

  this._loadData(query, options);

  if(this.options.localSearch) {
    this._storeDep.changed();
  }
};

SearchSource.prototype.getData = function(options, getCursor) {
  options = options || {};
  var self = this;
  this._storeDep.depend();
  var selector = {$or: []};

  var regExp = this._buildRegExp(self.currentQuery);

  // only do client side searching if we are on the loading state
  // once loaded, we need to send all of them
  if(this.getStatus().loading) {
    self.searchFields.forEach(function(field) {
      var singleQuery = {};
      singleQuery[field] = regExp;
      selector['$or'].push(singleQuery);
    });
  } else {
    selector = {};
  }

  function transform(doc) {
    if(options.transform) {
      self.searchFields.forEach(function(field) {
        if(self.currentQuery && doc[field]) {
          doc[field] = options.transform(doc[field], regExp, field, self.currentQuery);
        }
      });
    }
    if(options.docTransform) {
      return options.docTransform(doc);
    }

    return doc;
  }

  var cursor = this.store.find(selector, {
    sort: options.sort,
    limit: options.limit,
    transform: transform
  });

  if(getCursor) {
    return cursor;
  }

  return cursor.fetch();
};

SearchSource.prototype._fetch = function(source, query, options, callback) {
  if(typeof this.fetchData == 'function') {
    this.fetchData(query, options, callback);
  } else if(Meteor.status().connected) {
    this._fetchDDP.apply(this, arguments);
  } else {
    this._fetchHttp.apply(this, arguments);
  }
};

SearchSource.prototype._fetchDDP = function(source, query, options, callback) {
  Meteor.call("search.source", this.source, query, options, callback);
};

SearchSource.prototype._fetchHttp = function(source, query, options, callback) {
  var payload = {
    source: source,
    query: query,
    options: options
  };

  var headers = {
    "Content-Type": "text/ejson"
  };

  HTTP.post('/_search-source', {
    content: EJSON.stringify(payload),
    headers: headers
  }, function(err, res) {
    if(err) {
      callback(err);
    } else {
      var response = EJSON.parse(res.content);
      if(response.error) {
        callback(response.error);
      } else {
        callback(null, response.data);
      }
    }
  });
};

SearchSource.prototype.getMetadata = function() {
  return this.metaData.get();
};

SearchSource.prototype.getCurrentQuery = function() {
  this._currentQueryDep.depend();
  return this.currentQuery;
}

SearchSource.prototype.getStatus = function() {
  return this.status.get();
};

SearchSource.prototype.cleanHistory = function() {
  this.history = {};
};

SearchSource.prototype._buildRegExp = function(query) {
  query = query || "";

  var afterFilteredRegExpChars = query.replace(this._getRegExpFilterRegExp(), "\\$&");
  var parts = afterFilteredRegExpChars.trim().split(' ');

  return new RegExp("(" + parts.join('|') + ")", "ig");
};

SearchSource.prototype._getRegExpFilterRegExp = _.once(function() {
  var regExpChars = [
    "\\", "^", "$", "*", "+", "?", ".",
     "(", ")", ":", "|", "{", "}", "[", "]",
     "=", "!", ","
  ];
  var regExpCharsReplace = _.map(regExpChars, function(c) {
    return "\\" + c;
  }).join("|");
  return new RegExp("(" + regExpCharsReplace + ")", "g");
});<|endoftext|>


<commit_before>// Import React
import React, { Component } from 'react';
import axios from 'axios';

import Calendar from './calendar';

// Helper Functions
import Helpers from './utils/helpers.js';

// This is the Main component.
export default class MyGarden extends Component{

  constructor(props){
    super(props)

    this.state = {myVegetablesList: [], gardenData: ""}
  }

  // Will run right before mounting component
  componentWillMount(){
    axios.get('/api/user-veg').then((response) => {
      console.log(response);
      let gardenData = response.data.Garden;

      if(gardenData){

        let vegetables = gardenData.map((vegetable) => {
          let imageUrl = `images/${vegetable.VegName}.jpg`;

          return(

{vegetable.VegName}

          )

        })

        this.setState({ myVegetablesList: vegetables, gardenData: gardenData });
      }
    })

  }

  // Render Component
  render() {

    // IF the user has vegetables in their garden to display
    if(this.state.myVegetablesList.length > 0){
      return (

        < Calendar gardenData={ this.state.gardenData }  />

              {this.state.myVegetablesList}

      );
    }

    return (

View your garden here!

You don't have any plants yet, go add some and track their progress!

    );
  }
};<commit_msg>Garden Formatting<commit_after>// Import React
import React, { Component } from 'react';
import axios from 'axios';

import Calendar from './calendar';

// Helper Functions
import Helpers from './utils/helpers.js';

// This is the Main component.
export default class MyGarden extends Component{

  constructor(props){
    super(props)

    this.state = {myVegetablesList: [], gardenData: ""}
  }

  // Will run right before mounting component
  componentWillMount(){
    axios.get('/api/user-veg').then((response) => {
      console.log(response);
      let gardenData = response.data.Garden;

      if(gardenData){

        let vegetables = gardenData.map((vegetable) => {
          let imageUrl = `images/${vegetable.VegName}.jpg`;

          return(

{vegetable.VegName}

Tips

Spacing: {vegetable.Spacing}

Depth: {vegetable.Depth}

Fertilize: {vegetable.Fertilize}

Water: {vegetable.Water}

Important Dates

                    Indoor Seeding: From {vegetable.IndoorSeedStart} to {vegetable.IndoorSeedEnd}

                    Outdoor Seeding: From {vegetable.OutdoorSeedStart} to {vegetable.OutdoorSeedEnd}

                    Harvest Time: From {vegetable.HarvestStart} to {vegetable.HarvestEnd}

          )

        })

        this.setState({ myVegetablesList: vegetables, gardenData: gardenData });
      }
    })

  }

  // Render Component
  render() {

    // IF the user has vegetables in their garden to display
    if(this.state.myVegetablesList.length > 0){
      return (

        < Calendar gardenData={ this.state.gardenData }  />

              {this.state.myVegetablesList}

      );
    }

    return (

View your garden here!

You don't have any plants yet, go add some and track their progress!

    );
  }
};<|endoftext|>


<commit_before>// Dependencies
var KV = require('./kv.js')
var Sender = require('./http_sender.js')
var proto = require('./proto.js')

// Defaults opts
function Options(opts) {
    this.uri = opts.uri || 'http://localhost:8080/'
    this.host = opts.host
    this.port = opts.port
    this.ssl = opts.ssl ||false
    this.user = opts.user || 'root'
    this.http = opts.http || (this.ssl ? require('https') : require('http'))
    this.clock = opts.clock || require('./clock.js')
}

// Client interface fabricator
function NewClient(_opts) {
    if(!(this instanceof NewClient)) {
        return new NewClient(_opts)
    }

    var opts = new Options(_opts)

    this.sender = new Sender(opts)
    this.clock  = opts.clock

    return new Client(new KV(this.sender, this.clock))
}

// Client.js represents the exported client interface
// This is the API for our end users
function Client(kv) {
    this.kv = kv
    this.Call = this.kv.Call.bind(this.kv) // Default

    return this
}

// Create a new Client
// and Upgrade it to a prepared client.
// This is needed to assure "thread safety"
// Since the kv.Prepare api is expected to be used
// in a sync fashion.
Client.prototype.prepare = function PrepareClient() {
    var client = new Client(this.kv)
    client.Call = client.kv.Prepare.bind(client.kv) // Upgrade
    return client
}

// Get key
Client.prototype.get = function Get(key, callback) {
    this.Call(proto.Get, proto.GetArgs(key), function(err, res) {
        // Extract value from res
        if(!err && res) {
            if(res.value.bytes) {
                var value = res.value.bytes.buffer || null
            }
        }
        callback(err, value, res)
    })
}

// Put key
Client.prototype.put = function Put(key, value, callback) {
    this.Call(proto.Put, proto.PutArgs(key, value), callback)
}

// Conditinal Put key
Client.prototype.conditionalPut = function ConditionalPut(key, value, expectedValue, callback) {
    this.Call(proto.ConditionalPut, proto.ConditionalPutArgs(key, value, expectedValue), function(err, res) {
        if(!err) {
            var actualValue = res.actual_value || null
        }
        callback(err, actualValue, res)
    })
}

// Increment
Client.prototype.increment = function Increment(key, value, callback) {
    this.Call(proto.Increment, proto.IncrementArgs(key, value), function(err, res) {
        if(!err) {
            var newValue = res.new_value || null
        }
        callback(err, newValue, res)
    })
}

// Delete
Client.prototype.delete = function Delete(key, callback) {
    this.Call(proto.Delete, proto.DeleteArgs(key), callback)
}

// Delete Range
Client.prototype.deleteRange = function DeleteRange(start_key, end_key, limit, callback) {
    this.Call(proto.DeleteRange, proto.DeleteRangeArgs(start_key, end_key, limit), function(err, res) {
        if(!err) {
            var deleted = res.num_deleted || null
        }
        callback(err, deleted, res)
    })
}

// Scan
Client.prototype.scan = function Scan(key_start, key_end, limit, callback) {
    this.Call(proto.Scan, proto.ScanArgs(key_start, key_end, limit), function(err, res) {
        if(!err) {
            var rows = res.rows || null
        }
        callback(err, rows, res)
    })
}

// Contains
Client.prototype.contains = function Contains(key, callback) {
    this.Call(proto.Contains, proto.ContainsArgs(key), function(err, res) {
        if(!err) {
            var contains = res.contains || null
        }
        callback(err, contains, res)
    })
}

// Flush prepared buffer
Client.prototype.flush = function Flush(callback) {
    this.kv.Flush(callback)
}

// Request to for a transactional client
Client.prototype.runTransaction = function RunTransaction(opts, txn, callback) {
    this.kv.RunTransaction(opts, function TxnFnc(_kv, commit, abort){
        var client = new Client(_kv)
        txn(client, commit, abort)
    }, callback)
}

// Exports
module.exports = NewClient
<commit_msg>Fix result value type conversion.<commit_after>// Dependencies
var KV = require('./kv.js')
var Sender = require('./http_sender.js')
var proto = require('./proto.js')

// Defaults opts
function Options(opts) {
    this.uri = opts.uri || 'http://localhost:8080/'
    this.host = opts.host
    this.port = opts.port
    this.ssl = opts.ssl ||false
    this.user = opts.user || 'root'
    this.http = opts.http || (this.ssl ? require('https') : require('http'))
    this.clock = opts.clock || require('./clock.js')
}

// Client interface fabricator
function NewClient(_opts) {
    if(!(this instanceof NewClient)) {
        return new NewClient(_opts)
    }

    var opts = new Options(_opts)

    this.sender = new Sender(opts)
    this.clock  = opts.clock

    return new Client(new KV(this.sender, this.clock))
}

// Client.js represents the exported client interface
// This is the API for our end users
function Client(kv) {
    this.kv = kv
    this.Call = this.kv.Call.bind(this.kv) // Default

    return this
}

// Create a new Client
// and Upgrade it to a prepared client.
// This is needed to assure "thread safety"
// Since the kv.Prepare api is expected to be used
// in a sync fashion.
Client.prototype.prepare = function PrepareClient() {
    var client = new Client(this.kv)
    client.Call = client.kv.Prepare.bind(client.kv) // Upgrade
    return client
}

// Get key
Client.prototype.get = function Get(key, callback) {
    this.Call(proto.Get, proto.GetArgs(key), function(err, res) {
        // Extract value from res
        var value
        if(!err && res && res.value && res.value.bytes) {
            value = res.value.bytes.toBuffer() || null
        }
        callback(err, value, res)
    })
}

// Put key
Client.prototype.put = function Put(key, value, callback) {
    this.Call(proto.Put, proto.PutArgs(key, value), callback)
}

// Conditinal Put key
Client.prototype.conditionalPut = function ConditionalPut(key, value, expectedValue, callback) {
    this.Call(proto.ConditionalPut, proto.ConditionalPutArgs(key, value, expectedValue), function(err, res) {
        if(!err) {
            var actualValue = res.actual_value || null
        }
        callback(err, actualValue, res)
    })
}

// Increment
Client.prototype.increment = function Increment(key, value, callback) {
    this.Call(proto.Increment, proto.IncrementArgs(key, value), function(err, res) {
        if(!err) {
            var newValue = res.new_value || null
        }
        callback(err, newValue, res)
    })
}

// Delete
Client.prototype.delete = function Delete(key, callback) {
    this.Call(proto.Delete, proto.DeleteArgs(key), callback)
}

// Delete Range
Client.prototype.deleteRange = function DeleteRange(start_key, end_key, limit, callback) {
    this.Call(proto.DeleteRange, proto.DeleteRangeArgs(start_key, end_key, limit), function(err, res) {
        if(!err) {
            var deleted = res.num_deleted || null
        }
        callback(err, deleted, res)
    })
}

// Scan
Client.prototype.scan = function Scan(key_start, key_end, limit, callback) {
    this.Call(proto.Scan, proto.ScanArgs(key_start, key_end, limit), function(err, res) {
        if(!err) {
            var rows = res.rows || null
        }
        callback(err, rows, res)
    })
}

// Contains
Client.prototype.contains = function Contains(key, callback) {
    this.Call(proto.Contains, proto.ContainsArgs(key), function(err, res) {
        if(!err) {
            var contains = res.contains || null
        }
        callback(err, contains, res)
    })
}

// Flush prepared buffer
Client.prototype.flush = function Flush(callback) {
    this.kv.Flush(callback)
}

// Request to for a transactional client
Client.prototype.runTransaction = function RunTransaction(opts, txn, callback) {
    this.kv.RunTransaction(opts, function TxnFnc(_kv, commit, abort){
        var client = new Client(_kv)
        txn(client, commit, abort)
    }, callback)
}

// Exports
module.exports = NewClient
<|endoftext|>


<commit_before>angular.module('resultsFilters', [])
    .filter('averagePerOption', function() {
        return function (results) {
            if (!results) return;
            var n = results.length;
            var sums = results.reduce(function (memo, result) {
                var votes = result.votes;
                for (var name in votes) {
                    if (votes.hasOwnProperty(name)) {
                        if (!isFinite(memo[name])) {
                            memo[name] = +votes[name] || 0;
                        } else {
                            memo[name] += +votes[name] || 0;
                        }
                    }
                }
                return memo;
            }, {});
            var avgs = {};
            for (var name in sums) {
                if (sums.hasOwnProperty(name)) {
                    avgs[name] = sums[name] / n;
                }
            }
            return avgs;
        }
    });
angular.module('starter.controllers', ['resultsFilters'])

    .controller('AppCtrl', ['$scope', '$ionicModal', '$timeout', function ($scope, $ionicModal, $timeout) {
        // Form data for the login modal
        $scope.loginData = {};

        // Create the login modal that we will use later
        $ionicModal.fromTemplateUrl('client/templates/login.ng.html', {
            scope: $scope
        }).then(function (modal) {
            $scope.modal = modal;
        });

        // Triggered in the login modal to close it
        $scope.closeLogin = function () {
            $scope.modal.hide();
        };

        // Open the login modal
        $scope.login = function () {
            $scope.modal.show();
        };

        // Perform the login action when the user submits the login form
        $scope.doLogin = function () {
            console.log('Doing login', $scope.loginData);

            // Simulate a login delay. Remove this and replace with your login
            // code if using a login system
            $timeout(function () {
                $scope.closeLogin();
            }, 1000);
        };
    }])

    .controller('PropositionsCtrl', ['$scope', '$meteor', function ($scope, $meteor) {
        var vm = this;
        vm.page = 1;
        vm.perPage = 5;
        vm.sort = { createdAt: 1 };
        vm.orderProperty = '1';
        $meteor.autorun($scope, function() {
            var perPage = parseInt($scope.getReactively('vm.perPage'));
            var query = {
                limit: perPage,
                skip: (parseInt($scope.getReactively('vm.page')) - 1) * perPage,
                sort: $scope.getReactively('vm.sort')
            };
            $meteor.subscribe('propositions', query, $scope.getReactively('vm.search')).then(function(){
                vm.propositions = $meteor.collection(function() {
                    return Propositions.find({}, query);
                });
                vm.propositionsCount = $meteor.object(Counts ,'numberOfPropositions', false);
            });
        });
        vm.pageChanged = function(newPage) {
            vm.page = newPage;
        };
        $scope.$watch('vm.orderProperty', function(){
            if (vm.orderProperty)
                vm.sort = {name: parseInt(vm.orderProperty)};
        });
    }])

    .controller('PropositionCtrl', ['$scope', '$stateParams', '$meteor', '$state', function ($scope, $stateParams, $meteor, $state){
        var vm = this;
        var propositionId = $stateParams.propositionId;
        vm.proposition = $meteor.object(Propositions, propositionId, false).subscribe('propositions');
        vm.votes = $meteor.collection(function() {
            return Votes.find({
                propositionId: propositionId
            }, {
                sort : { createdAt: -1 }
            });
        });
        $meteor.subscribe('votes', propositionId).then(function () {
            var options = vm.proposition.options;
            var vote = vm.votes && vm.votes[0];
            if (!vote || !options) {
                return;
            }
            var votes = vote.votes;
            options.forEach(function (option) {
                var name =  option.name;
                if (name in votes) {
                    option.value = votes[name];
                }
            });
        });
        $meteor.subscribe('currentvotes', propositionId).then(function () {
            vm.results = $meteor.collection(function() {
                return CurrentVotes.find({
                    propositionId: propositionId
                });
            });
            vm.currentVote = $meteor.collection(function() {
                return CurrentVotes.find({
                    propositionId: propositionId,
                    userId: Meteor.userId()
                });
            });
            vm.totalUsersVoted = $meteor.object(Counts ,'totalUsersVoted', false);
        });
        vm.vote = function vote() {
            var votes = _.reduce(vm.proposition.options, function (memo, option) {
                memo[option.name] = option.value;
                return memo;
            }, {});
            var vote = {
                propositionId: propositionId,
                userId: Meteor.userId(),
                createdAt: new Date(),
                votes: votes
            };
            vm.votes.save(vote).then(function () {
                if (vm.currentVote[0]) {
                    vm.currentVote[0].votes = votes;
                    vm.currentVote.update(vm.currentVote[0]);
                } else {
                    vm.currentVote.save({
                        propositionId: propositionId,
                        userId: Meteor.userId(),
                        votes: votes
                    });
                }
            });

            $state.go('app.propositions');
        };
    }])

    .controller('NewPropositionCtrl', ['$scope', '$stateParams', '$meteor', '$state', function ($scope, $stateParams, $meteor, $state){
        $scope.proposition = {
            options: []
        };
        $scope.option = {};
        $scope.addOption = function addOption() {
            $scope.proposition.options.push($scope.option);
            $scope.option = {};
        };
        $scope.removeOption = function removeOption(option) {
            if (!option) {
                return;
            }
            var i = $scope.proposition.options.indexOf(option);
            if (i !== -1) {
                $scope.proposition.options.splice(i, 1);
            }
        };
        $scope.propositions = $meteor.collection(Propositions).subscribe('propositions');
        $scope.addProposition = function addProposition() {
            var proposition = $scope.proposition;
            proposition.ownerId = Meteor.userId();
            proposition.owner = Meteor.user();
            proposition.createdAt = new Date();
            $scope.propositions.save(proposition).then(function(){
                $state.go('app.propositions');
            });
            $scope.proposition = {
                options: []
            };
        };
    }]);

<commit_msg>Fix sorting<commit_after>angular.module('resultsFilters', [])
    .filter('averagePerOption', function() {
        return function (results) {
            if (!results) return;
            var n = results.length;
            var sums = results.reduce(function (memo, result) {
                var votes = result.votes;
                for (var name in votes) {
                    if (votes.hasOwnProperty(name)) {
                        if (!isFinite(memo[name])) {
                            memo[name] = +votes[name] || 0;
                        } else {
                            memo[name] += +votes[name] || 0;
                        }
                    }
                }
                return memo;
            }, {});
            var avgs = {};
            for (var name in sums) {
                if (sums.hasOwnProperty(name)) {
                    avgs[name] = sums[name] / n;
                }
            }
            return avgs;
        }
    });
angular.module('starter.controllers', ['resultsFilters'])

    .controller('AppCtrl', ['$scope', '$ionicModal', '$timeout', function ($scope, $ionicModal, $timeout) {
        // Form data for the login modal
        $scope.loginData = {};

        // Create the login modal that we will use later
        $ionicModal.fromTemplateUrl('client/templates/login.ng.html', {
            scope: $scope
        }).then(function (modal) {
            $scope.modal = modal;
        });

        // Triggered in the login modal to close it
        $scope.closeLogin = function () {
            $scope.modal.hide();
        };

        // Open the login modal
        $scope.login = function () {
            $scope.modal.show();
        };

        // Perform the login action when the user submits the login form
        $scope.doLogin = function () {
            console.log('Doing login', $scope.loginData);

            // Simulate a login delay. Remove this and replace with your login
            // code if using a login system
            $timeout(function () {
                $scope.closeLogin();
            }, 1000);
        };
    }])

    .controller('PropositionsCtrl', ['$scope', '$meteor', function ($scope, $meteor) {
        var vm = this;
        vm.page = 1;
        vm.perPage = 5;
        vm.sort = { createdAt: -1 };
        vm.orderProperty = '-1';
        $meteor.autorun($scope, function() {
            var perPage = parseInt($scope.getReactively('vm.perPage'));
            var query = {
                limit: perPage,
                skip: (parseInt($scope.getReactively('vm.page')) - 1) * perPage,
                sort: $scope.getReactively('vm.sort')
            };
            $meteor.subscribe('propositions', query, $scope.getReactively('vm.search')).then(function(){
                vm.propositions = $meteor.collection(function() {
                    return Propositions.find({}, query);
                });
                vm.propositionsCount = $meteor.object(Counts ,'numberOfPropositions', false);
            });
        });
        vm.pageChanged = function(newPage) {
            vm.page = newPage;
        };
        $scope.$watch('vm.orderProperty', function(){
            if (vm.orderProperty)
                vm.sort = {createdAt: parseInt(vm.orderProperty)};
        });
    }])

    .controller('PropositionCtrl', ['$scope', '$stateParams', '$meteor', '$state', function ($scope, $stateParams, $meteor, $state){
        var vm = this;
        var propositionId = $stateParams.propositionId;
        vm.proposition = $meteor.object(Propositions, propositionId, false).subscribe('propositions');
        vm.votes = $meteor.collection(function() {
            return Votes.find({
                propositionId: propositionId
            }, {
                sort : { createdAt: -1 }
            });
        });
        $meteor.subscribe('votes', propositionId).then(function () {
            var options = vm.proposition.options;
            var vote = vm.votes && vm.votes[0];
            if (!vote || !options) {
                return;
            }
            var votes = vote.votes;
            options.forEach(function (option) {
                var name =  option.name;
                if (name in votes) {
                    option.value = votes[name];
                }
            });
        });
        $meteor.subscribe('currentvotes', propositionId).then(function () {
            vm.results = $meteor.collection(function() {
                return CurrentVotes.find({
                    propositionId: propositionId
                });
            });
            vm.currentVote = $meteor.collection(function() {
                return CurrentVotes.find({
                    propositionId: propositionId,
                    userId: Meteor.userId()
                });
            });
            vm.totalUsersVoted = $meteor.object(Counts ,'totalUsersVoted', false);
        });
        vm.vote = function vote() {
            var votes = _.reduce(vm.proposition.options, function (memo, option) {
                memo[option.name] = option.value;
                return memo;
            }, {});
            var vote = {
                propositionId: propositionId,
                userId: Meteor.userId(),
                createdAt: new Date(),
                votes: votes
            };
            vm.votes.save(vote).then(function () {
                if (vm.currentVote[0]) {
                    vm.currentVote[0].votes = votes;
                    vm.currentVote[0].save();
                } else {
                    vm.currentVote.save({
                        propositionId: propositionId,
                        userId: Meteor.userId(),
                        votes: votes
                    });
                }
            });

            $state.go('app.propositions');
        };
    }])

    .controller('NewPropositionCtrl', ['$scope', '$stateParams', '$meteor', '$state', function ($scope, $stateParams, $meteor, $state){
        $scope.proposition = {
            options: []
        };
        $scope.option = {};
        $scope.addOption = function addOption() {
            $scope.proposition.options.push($scope.option);
            $scope.option = {};
        };
        $scope.removeOption = function removeOption(option) {
            if (!option) {
                return;
            }
            var i = $scope.proposition.options.indexOf(option);
            if (i !== -1) {
                $scope.proposition.options.splice(i, 1);
            }
        };
        $scope.propositions = $meteor.collection(Propositions).subscribe('propositions');
        $scope.addProposition = function addProposition() {
            var proposition = $scope.proposition;
            proposition.ownerId = Meteor.userId();
            proposition.owner = Meteor.user();
            proposition.createdAt = new Date();
            $scope.propositions.save(proposition).then(function(){
                $state.go('app.propositions');
            });
            $scope.proposition = {
                options: []
            };
        };
    }]);

<|endoftext|>


<commit_before>define(["dojo/_base/declare", "dojo/Stateful", "ppwcode/oddsAndEnds/bindingChains", "module", "ppwcode/oddsAndEnds/log/logger!"],
  function (declare, Stateful, bindingChains, module, logger) {

    // IDEA note that derivation, delegation and propagation turn out to be 3 separate mechanisms

    var _DerivedMixin = declare([Stateful], {
      // summary:
      //   Mixin that provides support for declarative definition of derived properties.
      // description:
      //   Add a `"-derived-"` property to the prototype of your class with syntax
      //
      //   | "-derived-": {
      //   |   PROPERTYNAME: ["path.to.first.derivationSource", "path.to.second.derivationSource", ...],
      //   |   ...
      //   | },
      //
      //   This will create bindingChains (you can use that complete syntax) for a "virtual" derived property
      //   PROPERTYNAME. Outside users will get events if this derived property changes.
      //
      //   To define the semantics of the derived property, add a regular Stateful `_PROPRETYNAMEGetter`.
      //
      //   Note that derived properties can be based on any other property of any reachable object, also
      //   of this, and also on other derived properties.
      //
      //   Most often, derived properties are read only. This is certainly true for properties that
      //   depend on more than one other property. It is however possible to also add a setter, if this is
      //   appropriate. An example of the latter is when this mechanism is used to alias a property.
      //
      //   "-derived-" definitions for an instance are gathered over the entire inheritance chain.
      //   Deeper definitions for a PROPERTYNAME have precedence.
      //
      //   The events can be temporarily stopped and restarted with `stopDerivedEvents` and `startDerivedEvents`.

      postscript: function() {
        var self = this;
        self.inherited(arguments);

        function dependentPropertyChanged(dependentPropertyName) {
          var previousValue = self.get(dependentPropertyName);
          /* IDEA In general, for more complex, derived properties, we need to store the previousValue
           to be able to send events. Now, we are doing our best NOT to have this "property" data,
           which in simple delegation cases is redundant, in our object. But here we see we have
           it anyway. So, what is the sense in hiding it here. It would probably be much
           simpler to just have it in the object itself, and keep it up-to-date with _set.
           We have it anyway!
           In the case of a read-only property, this is better, since the property cannot be
           set. We should add a defense against that. Most, if not all, complex derived properties are
           read-only: the calculated value based on 2 or more other properties cannot be set
           in a sensible way.
           What is left are read-write properties, of which most, if not all, are simple delegation
           to another property (most often of a nested, owned object). For those, having
           redundant data in this object is less desirable, and not needed. Storing the previousValue
           for them is not necessary, since the sole basis property's value is the one we are
           reflecting too, and the event we receive from the sole basis property contains the previous
           value. So, simple delegation is another mechanism, which could also benefit from bindingChains,
           but has different semantics. Events are just propagated, and both getter and setter just
           delegate to the basis property.
           In some cases, we still might have a redundant copy in this object though. But that seems to
           be bad code.
           */
          return function() {
            if(self._watchCallbacks) {
              var newValue = self.get(dependentPropertyName);
              if (newValue !== previousValue) { // IDEA compare?
                self._watchCallbacks(dependentPropertyName, previousValue, newValue);
                previousValue = newValue;
              }
            }
          }
        }

        self["-derived"] = self.constructor._meta.bases.reduceRight(
          function(acc, base) {
            var dependencies = base.prototype["-derived-"];
            if (dependencies) {
              for (var dependencyPropName in dependencies) {
                acc[dependencyPropName] = dependencies[dependencyPropName];
                acc[dependencyPropName].changed = dependentPropertyChanged(dependencyPropName);
                acc[dependencyPropName].chain = bindingChains(
                  self,
                  acc[dependencyPropName],
                  acc[dependencyPropName].changed
                );
              }
            }
            return acc;
          },
          {}
        );
        logger.debug("derived properties initialized");
      },

      stopDerivedEvents: function() {
        logger.debug("Stopping derived events");
        for (var dependencyPropName in this["-derived-"]) {
          this["-derived-"][dependencyPropName].chain.stop();
        }
      },

      startDerivedEvents: function() {
        logger.debug("Starting derived events");
        for (var dependencyPropName in this["-derived-"]) {
          this["-derived-"][dependencyPropName].changed();
          this["-derived-"][dependencyPropName].chain.start();
        }
      }

      // MUDO add Destroyable

    });

    _DerivedMixin.mid = module.id;
    return _DerivedMixin;
  }
);
<commit_msg>major bug/type: missing "-" at the end of the name<commit_after>define(["dojo/_base/declare", "dojo/Stateful", "ppwcode/oddsAndEnds/bindingChains", "module", "ppwcode/oddsAndEnds/log/logger!"],
  function (declare, Stateful, bindingChains, module, logger) {

    // IDEA note that derivation, delegation and propagation turn out to be 3 separate mechanisms

    var _DerivedMixin = declare([Stateful], {
      // summary:
      //   Mixin that provides support for declarative definition of derived properties.
      // description:
      //   Add a `"-derived-"` property to the prototype of your class with syntax
      //
      //   | "-derived-": {
      //   |   PROPERTYNAME: ["path.to.first.derivationSource", "path.to.second.derivationSource", ...],
      //   |   ...
      //   | },
      //
      //   This will create bindingChains (you can use that complete syntax) for a "virtual" derived property
      //   PROPERTYNAME. Outside users will get events if this derived property changes.
      //
      //   To define the semantics of the derived property, add a regular Stateful `_PROPRETYNAMEGetter`.
      //
      //   Note that derived properties can be based on any other property of any reachable object, also
      //   of this, and also on other derived properties.
      //
      //   Most often, derived properties are read only. This is certainly true for properties that
      //   depend on more than one other property. It is however possible to also add a setter, if this is
      //   appropriate. An example of the latter is when this mechanism is used to alias a property.
      //
      //   "-derived-" definitions for an instance are gathered over the entire inheritance chain.
      //   Deeper definitions for a PROPERTYNAME have precedence.
      //
      //   The events can be temporarily stopped and restarted with `stopDerivedEvents` and `startDerivedEvents`.

      postscript: function() {
        var self = this;
        self.inherited(arguments);

        function dependentPropertyChanged(dependentPropertyName) {
          var previousValue = self.get(dependentPropertyName);
          /* IDEA In general, for more complex, derived properties, we need to store the previousValue
           to be able to send events. Now, we are doing our best NOT to have this "property" data,
           which in simple delegation cases is redundant, in our object. But here we see we have
           it anyway. So, what is the sense in hiding it here. It would probably be much
           simpler to just have it in the object itself, and keep it up-to-date with _set.
           We have it anyway!
           In the case of a read-only property, this is better, since the property cannot be
           set. We should add a defense against that. Most, if not all, complex derived properties are
           read-only: the calculated value based on 2 or more other properties cannot be set
           in a sensible way.
           What is left are read-write properties, of which most, if not all, are simple delegation
           to another property (most often of a nested, owned object). For those, having
           redundant data in this object is less desirable, and not needed. Storing the previousValue
           for them is not necessary, since the sole basis property's value is the one we are
           reflecting too, and the event we receive from the sole basis property contains the previous
           value. So, simple delegation is another mechanism, which could also benefit from bindingChains,
           but has different semantics. Events are just propagated, and both getter and setter just
           delegate to the basis property.
           In some cases, we still might have a redundant copy in this object though. But that seems to
           be bad code.
           */
          return function() {
            if(self._watchCallbacks) {
              var newValue = self.get(dependentPropertyName);
              if (newValue !== previousValue) { // IDEA compare?
                self._watchCallbacks(dependentPropertyName, previousValue, newValue);
                previousValue = newValue;
              }
            }
          }
        }

        self["-derived-"] = self.constructor._meta.bases.reduceRight(
          function(acc, base) {
            var dependencies = base.prototype["-derived-"];
            if (dependencies) {
              for (var dependencyPropName in dependencies) {
                acc[dependencyPropName] = dependencies[dependencyPropName];
                acc[dependencyPropName].changed = dependentPropertyChanged(dependencyPropName);
                acc[dependencyPropName].chain = bindingChains(
                  self,
                  acc[dependencyPropName],
                  acc[dependencyPropName].changed
                );
              }
            }
            return acc;
          },
          {}
        );
        logger.debug("derived properties initialized");
      },

      stopDerivedEvents: function() {
        logger.debug("Stopping derived events");
        for (var dependencyPropName in this["-derived-"]) {
          this["-derived-"][dependencyPropName].chain.stop();
        }
      },

      startDerivedEvents: function() {
        logger.debug("Starting derived events");
        for (var dependencyPropName in this["-derived-"]) {
          this["-derived-"][dependencyPropName].changed();
          this["-derived-"][dependencyPropName].chain.start();
        }
      }

      // MUDO add Destroyable

    });

    _DerivedMixin.mid = module.id;
    return _DerivedMixin;
  }
);
<|endoftext|>


<commit_before>const exec = require('child_process').execSync,

    commandWithPath = (path, args, callback) => {
        args.unshift('git');
        const cmd = args.join(' ');
        try {
            const stdOut = exec(cmd, {cwd:path});
            return callback(null, stdOut.toString());
        }
        catch (error) {
            try {
                return callback(error.stderr.toString(), null);
            }
            catch (error2) {
                throw error;
            }
        }
    },

    command = (args, callback) => {
        commandWithPath(global.__rootPath, args, callback);
    };

exports.pull = (callback) => {
    command(['pull'], callback);
};

exports.pullWithPath = (path, callback) => {
    commandWithPath(path, ['pull'], callback);
};

exports.getSHAOfHead = (callback) => {
    command(['rev-parse', '--verify', 'HEAD'], callback);
};

exports.getSHAOfRemoteMaster = (callback) => {
    command(['rev-parse', '--verify', 'origin/master'], callback);
};

exports.getCurrentBranchName = (callback) => {
    command(['symbolic-ref', '--short', 'HEAD'], callback);
};

exports.clone = (url, dir, callback) => {
    command(['clone', url, dir], callback);
};

exports.submoduleUpdate = (callback) => {
    command(['submodule', 'update', '--init', '--recursive'], callback);
};
<commit_msg>Proposed fix for path with spaces (#233)<commit_after>const exec = require('child_process').execSync,

    commandWithPath = (path, args, callback) => {
        args.unshift('git');
        args.forEach((seg, index, arr) => arr[index] = `"${seg}"`);
        const cmd = args.join(' ');
        try {
            const stdOut = exec(cmd, {cwd:path});
            return callback(null, stdOut.toString());
        }
        catch (error) {
            try {
                return callback(error.stderr.toString(), null);
            }
            catch (error2) {
                throw error;
            }
        }
    },

    command = (args, callback) => {
        commandWithPath(global.__rootPath, args, callback);
    };

exports.pull = (callback) => {
    command(['pull'], callback);
};

exports.pullWithPath = (path, callback) => {
    commandWithPath(path, ['pull'], callback);
};

exports.getSHAOfHead = (callback) => {
    command(['rev-parse', '--verify', 'HEAD'], callback);
};

exports.getSHAOfRemoteMaster = (callback) => {
    command(['rev-parse', '--verify', 'origin/master'], callback);
};

exports.getCurrentBranchName = (callback) => {
    command(['symbolic-ref', '--short', 'HEAD'], callback);
};

exports.clone = (url, dir, callback) => {
    command(['clone', url, dir], callback);
};

exports.submoduleUpdate = (callback) => {
    command(['submodule', 'update', '--init', '--recursive'], callback);
};
<|endoftext|>


<commit_before>

// Listen for on submit click
let formSubmit = document.getElementById("formSubmit");
formSubmit.addEventListener("click", fetchAndShowResponse, false);

/**
 * Grabs response from server
 */
async function fetchAndShowResponse() {
  const response = await fetch('/api/musix');
  const value = await response.json();
  const el = document.getElementById(elId);
  el.innerText = value;
  return value;
}

<commit_msg>resolved reqs<commit_after>// Listen for on submit click
let formSubmit = document.getElementById("formSubmit");
formSubmit.addEventListener("click", fetchAndShowResponse, false);

/**
 * Grabs response from server
 */
async function fetchAndShowResponse() {
  const response = await fetch('/api/musix');
  const value = await response.json();
  const el = document.getElementById(elId);
  el.innerText = value;
  return value;
}

<|endoftext|>


<commit_before>var _ = require("../node_modules/underscore/underscore-min");

module.exports = function(){
	return {
		/**
		 * Add Access-Control-Allow-Headers in HTTP response
		 */
		header : function(req, res, next) {
			res.header('Access-Control-Allow-Origin', '*');
			res.header('Access-Control-Allow-Headers', 'Accept,Content-Type, X-Requested-With');
			res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
			res.header('Access-Control-Allow-Credentials': true);
			next();
		},

		/**
		 * docs return from mongodb is like:
		 * [{"_id":"54a4d108228799901cb889e5","name":"Kayak"},
		 * {"_id":"54a4d108228799901cb889e6","name":"Lifejacket"}]
		 *
		 * chenge _id to id, like:
		 * [{"name":"Kayak","id":"54a4d108228799901cb889e5"},
		 * "name":"Lifejacket","id":"54a4d108228799901cb889e6"}]
		 *
		 * @param docs
		 */
		filterId : function(docs){
			return _.map(docs, function(value) {
				//console.log("v->%j", value._id);
				value['id'] = value._id;
				return _.omit(value, '_id');
			});
		}
	}
}
<commit_msg>add back<commit_after><|endoftext|>


<commit_before>/**
 * @fileoverview High-level view of a Blockly Workspace that allows
 * for programmatically adding, moving, and deleting blocks. Does NOT
 * provide error checking.
 * @author ehernandez4@wisc.edu (Evan Hernandez)
 */
'use strict';

goog.provide('SpeechBlocks.Controller');

goog.require('Blockly.Field');
goog.require('Blockly.FieldColour');
goog.require('Blockly.Workspace');
goog.require('Blockly.constants');
goog.require('Blockly.inject');
goog.require('SpeechBlocks.Blocks');
goog.require('SpeechBlocks.FieldTypes');
goog.require('goog.structs.Map');
goog.require('goog.structs.Set');

/**
 * Inject a Blockly workspace into the given container element.
 * @param {!Element|string} container Containing element, or its ID, or a CSS selector.
 * @param {Object=} opt_options Optional dictionary of options.
 * @constructor
 */
SpeechBlocks.Controller = function(container, opt_options) {
  /** @private @const {!Blockly.Workspace} */
  this.workspace_ = Blockly.inject('blocklyDiv', opt_options);
};

/**
 * Adds and renders a new block to the workspace.
 * @param {string} type Name of the language object containing
 *     type-specific functions for this block.
 * @param {string} blockId ID for the block.
 * @param {!SpeechBlocks.Where} where Location on the workspace
 *     to place the new block.
 * @public
 */
SpeechBlocks.Controller.prototype.addBlock = function(type, blockId, where) {
  var newBlock = this.workspace_.newBlock(type, blockId);
  newBlock.initSvg();
  this.moveBlock(blockId, where);
};

/**
 * Moves the block with the given ID. All child blocks are moved as well.
 * @param {string} blockId ID of the block to move.
 * @param {!SpeechBlocks.Where} where Location on the workspace
 *    to place the new block.
 * @public
 */
SpeechBlocks.Controller.prototype.moveBlock = function(blockId, where) {
  where.place(blockId, this.workspace_);
  this.workspace_.render();
};

/**
 * Removes the block with the given ID from the workspace, along with its children.
 * @param {string} blockId ID of the block to remove.
 * @public
 */
SpeechBlocks.Controller.prototype.removeBlock = function(blockId) {
  var block = SpeechBlocks.Blocks.getBlock(blockId, this.workspace_);
  block.unplug(true /* Heal the stack! */);
  block.dispose();
};

/**
 * Undos the last action.
 * @public
 */
SpeechBlocks.Controller.prototype.undo = function() { this.workspace_.undo(false); };

/**
 * Redos the last undo.
 * @public
 */
SpeechBlocks.Controller.prototype.redo = function() { this.workspace_.undo(true); };

/**
 * Returns the set of IDs for all blocks in the workspace.
 * @return {!goog.structs.Set<string>} The array of all IDs.
 * @public
 */
SpeechBlocks.Controller.prototype.getAllBlockIds = function() {
  var blockIds = new goog.structs.Set();
  this.workspace_.getAllBlocks().forEach(function(block) {
    blockIds.add(block.id);
  });
  return blockIds;
};

/**
 * Checks whether the block with the given ID has a "next block" connection.
 * @param {string} blockId ID of the block.
 * @return {boolean} True if block has next connection, false otherwise.
 * @public
 */
SpeechBlocks.Controller.prototype.hasNextConnection = function(blockId) {
  return !goog.isNull(
      SpeechBlocks.Blocks.getBlock(blockId, this.workspace_).nextConnection);
};

/**
 * Checks whether the block with the given ID has a "previous block" connection.
 * @param {string} blockId ID of the block.
 * @return {boolean} True if block has previous connection, false otherwise.
 * @public
 */
SpeechBlocks.Controller.prototype.hasPreviousConnection = function(blockId) {
  return !goog.isNull(
      SpeechBlocks.Blocks.getBlock(blockId, this.workspace_).previousConnection);
};

/**
 * Checks whether the block with the given ID has a value output connection.
 * @param {string} blockId ID of the block.
 * @return {boolean} True if block has output connection, false otherwise.
 * @public
 */
SpeechBlocks.Controller.prototype.hasOutputConnection = function(blockId) {
  return !goog.isNull(
      SpeechBlocks.Blocks.getBlock(blockId, this.workspace_).outputConnection);
};

/**
 * Returns the list of value input labels for this block.
 * Returns a list of value input labels for the block.
 * @param {string} blockId ID of the block.
 * @return {!Array<string>} List of value input labels for this block.
 * @public
 */
SpeechBlocks.Controller.prototype.getBlockValueInputs = function(blockId) {
  return this.getBlockXInputs_(blockId, Blockly.INPUT_VALUE);
};

/**
 * Returns the list of statement input labels for the block.
 * @param {string} blockId ID of the block.
 * @return {!Array<string>} List of statement input labels for this block.
 * @public
 */
SpeechBlocks.Controller.prototype.getBlockStatementInputs = function(blockId) {
  // Eventually, we might also want to include Blockly.PREVIOUS_STATEMENT
  // input types, but it's not clear where this is used.
  return this.getBlockXInputs_(blockId, Blockly.NEXT_STATEMENT);
};

/**
 * Gets the labels for inputs of the given type from the given block.
 * @param {string} blockId ID of the block.
 * @param {number} type Input type to get.
 * @return {!Array<string>} Array of input labels of the given type.
 * @private
 */
SpeechBlocks.Controller.prototype.getBlockXInputs_ = function (blockId, type) {
  var inputLabels = [];
  SpeechBlocks.Blocks.getBlock(blockId, this.workspace_).inputList.forEach(function(input) {
    if (input.type == type) { inputLabels.push(input.name); }
  });
  return inputLabels;
};

/**
 * Returns a mapping from field names to field types for the given block.
 * Note that all field types are enumerated in SpeechBlocks.FieldTypes.
 * @param {string} blockId The ID of the block.
 * @return {!goog.structs.Map<string, number>} A mapping of field names to field types.
 * @public
 */
SpeechBlocks.Controller.prototype.getFieldsForBlock = function(blockId) {
  var blockFields = new goog.structs.Map();
  SpeechBlocks.Blocks.getBlock(blockId, this.workspace_).inputList.forEach(function(input) {
    input.fieldRow.forEach(function(field) {
      var type = SpeechBlocks.FieldTypes.getFieldType(field);
      if (field.name && type != SpeechBlocks.FieldTypes.IRRELEVANT) {
        blockFields.set(field.name, type);
      }
    });
  });
  return blockFields;
};

/**
 * Sets the field with the given name to the given value.
 *
 * Formatting of the value is very important:
 *
 * _______________________________________
 * FIELD TYPE         | VALUE FORMAT
 * ___________________|___________________
 * Text Input         | '*' (any text)
 * Number Input       | '[0-9]+' (any number)
 * Drop-Down          | existing drop-down value
 * Date Picker        | 'yyyy-mm-dd'
 * Angle Picker       | 'x' where 0 <= x <= 360
 * Colour Picker      | '#HHH' where H is a hex digit
 * Variable Picker    | existing variable name
 *
 * @param {string} blockId ID of the block.
 * @param {string} fieldName Name of the field.
 * @param {string} fieldValue New value for the field.
 * @public
 */
SpeechBlocks.Controller.prototype.setBlockField = function(blockId, fieldName, fieldValue) {
  SpeechBlocks.Blocks.getBlock(blockId, this.workspace_).setFieldValue(fieldValue, fieldName);
};<commit_msg>Add factory method for creating SpeechBlocks.Controller headlessly.<commit_after>/**
 * @fileoverview High-level view of a Blockly Workspace that allows
 * for programmatically adding, moving, and deleting blocks. Does NOT
 * provide error checking.
 * @author ehernandez4@wisc.edu (Evan Hernandez)
 */
'use strict';

goog.provide('SpeechBlocks.Controller');

goog.require('Blockly.Field');
goog.require('Blockly.FieldColour');
goog.require('Blockly.Workspace');
goog.require('Blockly.constants');
goog.require('Blockly.inject');
goog.require('SpeechBlocks.Blocks');
goog.require('SpeechBlocks.FieldTypes');
goog.require('goog.structs.Map');
goog.require('goog.structs.Set');

/**
 * Inject a Blockly workspace into the given container element.
 * @param {!Element|string} container Containing element, or its ID, or a CSS selector.
 * @param {Object=} opt_options Optional dictionary of options.
 * @constructor
 */
SpeechBlocks.Controller = function(container, opt_options) {
  /** @private @const {!Blockly.Workspace} */
  this.workspace_ = Blockly.inject('blocklyDiv', opt_options);
};

/**
 * Parses the headless XML into a Blockly workspace and returns
 * a corresponding SpeechBlocks controller.
 * @param {!Element} xml XML element to convert to workspace.
 * @return {!SpeechBlocks.Controller} Controller for the Blockly workspace.
 */
SpeechBlocks.Controller.fromXml = function(xml) {
  return new SpeechBlocks.Controller(
      Blockly.Xml.domToWorkspace(xml), new Blockly.Workspace());
};

/**
 * Adds and renders a new block to the workspace.
 * @param {string} type Name of the language object containing
 *     type-specific functions for this block.
 * @param {string} blockId ID for the block.
 * @param {!SpeechBlocks.Where} where Location on the workspace
 *     to place the new block.
 * @public
 */
SpeechBlocks.Controller.prototype.addBlock = function(type, blockId, where) {
  var newBlock = this.workspace_.newBlock(type, blockId);
  newBlock.initSvg();
  this.moveBlock(blockId, where);
};

/**
 * Moves the block with the given ID. All child blocks are moved as well.
 * @param {string} blockId ID of the block to move.
 * @param {!SpeechBlocks.Where} where Location on the workspace
 *    to place the new block.
 * @public
 */
SpeechBlocks.Controller.prototype.moveBlock = function(blockId, where) {
  where.place(blockId, this.workspace_);
  this.workspace_.render();
};

/**
 * Removes the block with the given ID from the workspace, along with its children.
 * @param {string} blockId ID of the block to remove.
 * @public
 */
SpeechBlocks.Controller.prototype.removeBlock = function(blockId) {
  var block = SpeechBlocks.Blocks.getBlock(blockId, this.workspace_);
  block.unplug(true /* Heal the stack! */);
  block.dispose();
};

/**
 * Undos the last action.
 * @public
 */
SpeechBlocks.Controller.prototype.undo = function() { this.workspace_.undo(false); };

/**
 * Redos the last undo.
 * @public
 */
SpeechBlocks.Controller.prototype.redo = function() { this.workspace_.undo(true); };

/**
 * Returns the set of IDs for all blocks in the workspace.
 * @return {!goog.structs.Set<string>} The array of all IDs.
 * @public
 */
SpeechBlocks.Controller.prototype.getAllBlockIds = function() {
  var blockIds = new goog.structs.Set();
  this.workspace_.getAllBlocks().forEach(function(block) {
    blockIds.add(block.id);
  });
  return blockIds;
};

/**
 * Checks whether the block with the given ID has a "next block" connection.
 * @param {string} blockId ID of the block.
 * @return {boolean} True if block has next connection, false otherwise.
 * @public
 */
SpeechBlocks.Controller.prototype.hasNextConnection = function(blockId) {
  return !goog.isNull(
      SpeechBlocks.Blocks.getBlock(blockId, this.workspace_).nextConnection);
};

/**
 * Checks whether the block with the given ID has a "previous block" connection.
 * @param {string} blockId ID of the block.
 * @return {boolean} True if block has previous connection, false otherwise.
 * @public
 */
SpeechBlocks.Controller.prototype.hasPreviousConnection = function(blockId) {
  return !goog.isNull(
      SpeechBlocks.Blocks.getBlock(blockId, this.workspace_).previousConnection);
};

/**
 * Checks whether the block with the given ID has a value output connection.
 * @param {string} blockId ID of the block.
 * @return {boolean} True if block has output connection, false otherwise.
 * @public
 */
SpeechBlocks.Controller.prototype.hasOutputConnection = function(blockId) {
  return !goog.isNull(
      SpeechBlocks.Blocks.getBlock(blockId, this.workspace_).outputConnection);
};

/**
 * Returns the list of value input labels for this block.
 * Returns a list of value input labels for the block.
 * @param {string} blockId ID of the block.
 * @return {!Array<string>} List of value input labels for this block.
 * @public
 */
SpeechBlocks.Controller.prototype.getBlockValueInputs = function(blockId) {
  return this.getBlockXInputs_(blockId, Blockly.INPUT_VALUE);
};

/**
 * Returns the list of statement input labels for the block.
 * @param {string} blockId ID of the block.
 * @return {!Array<string>} List of statement input labels for this block.
 * @public
 */
SpeechBlocks.Controller.prototype.getBlockStatementInputs = function(blockId) {
  // Eventually, we might also want to include Blockly.PREVIOUS_STATEMENT
  // input types, but it's not clear where this is used.
  return this.getBlockXInputs_(blockId, Blockly.NEXT_STATEMENT);
};

/**
 * Gets the labels for inputs of the given type from the given block.
 * @param {string} blockId ID of the block.
 * @param {number} type Input type to get.
 * @return {!Array<string>} Array of input labels of the given type.
 * @private
 */
SpeechBlocks.Controller.prototype.getBlockXInputs_ = function (blockId, type) {
  var inputLabels = [];
  SpeechBlocks.Blocks.getBlock(blockId, this.workspace_).inputList.forEach(function(input) {
    if (input.type == type) { inputLabels.push(input.name); }
  });
  return inputLabels;
};

/**
 * Returns a mapping from field names to field types for the given block.
 * Note that all field types are enumerated in SpeechBlocks.FieldTypes.
 * @param {string} blockId The ID of the block.
 * @return {!goog.structs.Map<string, number>} A mapping of field names to field types.
 * @public
 */
SpeechBlocks.Controller.prototype.getFieldsForBlock = function(blockId) {
  var blockFields = new goog.structs.Map();
  SpeechBlocks.Blocks.getBlock(blockId, this.workspace_).inputList.forEach(function(input) {
    input.fieldRow.forEach(function(field) {
      var type = SpeechBlocks.FieldTypes.getFieldType(field);
      if (field.name && type != SpeechBlocks.FieldTypes.IRRELEVANT) {
        blockFields.set(field.name, type);
      }
    });
  });
  return blockFields;
};

/**
 * Sets the field with the given name to the given value.
 *
 * Formatting of the value is very important:
 *
 * _______________________________________
 * FIELD TYPE         | VALUE FORMAT
 * ___________________|___________________
 * Text Input         | '*' (any text)
 * Number Input       | '[0-9]+' (any number)
 * Drop-Down          | existing drop-down value
 * Date Picker        | 'yyyy-mm-dd'
 * Angle Picker       | 'x' where 0 <= x <= 360
 * Colour Picker      | '#HHH' where H is a hex digit
 * Variable Picker    | existing variable name
 *
 * @param {string} blockId ID of the block.
 * @param {string} fieldName Name of the field.
 * @param {string} fieldValue New value for the field.
 * @public
 */
SpeechBlocks.Controller.prototype.setBlockField = function(blockId, fieldName, fieldValue) {
  SpeechBlocks.Blocks.getBlock(blockId, this.workspace_).setFieldValue(fieldValue, fieldName);
};<|endoftext|>


<commit_before>import Domify from 'react-domify';
import React from 'react';
import ReactDOM from 'react-dom';
import { Col, Row } from 'elemental';

import steps from '../../tests/api-react';

const App = React.createClass({
	getInitialState () {
		return {
			log: [],
			step: 1,
			nextStepContext: {},
		};
	},
	log (style, content) {
		if (arguments.length === 1) {
			content = style;
			style = styles.message;
		}
		this.setState({
			log: this.state.log.concat([
				{ style, content },
			]),
		});
	},
	stepReady () {
		this.log(`Step ${this.state.step} ready\n`);
	},
	stepRun () {
		this.log(`Step ${this.state.step} running...\n`);
	},
	stepResult () {
		this.log(`Step ${this.state.step} result:\n`);
		for (var i = 0; i < arguments.length; i++) {
			this.log(arguments[i]);
		}
	},
	stepAssert (msg) {
		this.log(`Step ${this.state.step} asserts:\n`);
		var self = this;
		return {
			truthy (value) {
				if (value) self.log(styles.pass, '[pass] ' + msg);
				else self.log(styles.fail, '[fail] ' + msg);
			}
		};
	},
	stepComplete () {
		this.log(`Step ${this.state.step} complete\n`);
	},
	nextStep (nextStepContext) {
		this.setState({
			step: this.state.step + 1,
			stepContext: nextStepContext,
		});
	},
	renderLog () {
		return this.state.log.map((msg, i) => {
			if (typeof msg.content === 'object') {
				return <Domify style={styles.obj} key={`log${i}`} value={msg.content} />;
			}
			return <div style={msg.style} key={`log${i}`}>{msg.content}
;
		});
	},
	render () {
		const StepComponent = steps[this.state.step - 1];
		return (

				<Row>
					<Col sm="1/2">

							<StepComponent
								assert={this.stepAssert}
								complete={this.stepComplete}
								next={this.nextStep}
								ready={this.stepReady}
								result={this.stepResult}
								run={this.stepRun}
							/>

					</Col>
					<Col sm="1/2">

							{this.renderLog()}

					</Col>
				</Row>

		);
	}
});

const styles = {
	box: {
		backgroundColor: 'white',
		borderRadius: '0.3em',
		boxShadow: '0 2px 3px rgba(0, 0, 0, 0.075), 0 0 0 1px rgba(0,0,0,0.1)',
		margin: '6vh auto',
		padding: '3em',
	},
	obj: {
		border: '1px solid #999',
		fontFamily: 'Monaco',
		fontSize: '0.9em',
		margin: '0.5em -1em',
		padding: '1.2em',
	},
	message: {
		fontSize: '1.2em',
		margin: '0.5em',
	},
	pass: {
		color: 'green',
		fontFamily: 'Monaco',
		margin: '0.5em',
	},
	fail: {
		color: 'red',
		fontFamily: 'Monaco',
		margin: '0.5em',
	},
};

ReactDOM.render(<App />, document.getElementById('app'));
<commit_msg>Cleaning up logging and stepContext framework<commit_after>import Domify from 'react-domify';
import React from 'react';
import ReactDOM from 'react-dom';
import { Col, Row } from 'elemental';

import steps from '../../tests/api-react';

const App = React.createClass({
	getInitialState () {
		return {
			log: [],
			step: 1,
			stepContext: {},
			nextStepContext: {},
		};
	},
	log (style, content) {
		if (arguments.length === 1) {
			content = style;
			style = styles.message;
		}
		this.setState({
			log: [{ style, content }].concat(this.state.log),
		});
	},
	stepReady () {
		this.setState({
			log: [],
		}, () => {
			this.log(`Step ${this.state.step} ready\n`);
		});
	},
	stepRun () {
		this.log(`Step ${this.state.step} running...\n`);
	},
	stepResult () {
		this.log(`Step ${this.state.step} result:\n`);
		for (var i = 0; i < arguments.length; i++) {
			this.log(arguments[i]);
		}
	},
	stepAssert (msg) {
		// this.log(`Step ${this.state.step} asserts:\n`);
		var self = this;
		return {
			truthy (fn) {
				try {
					if (fn()) self.log(styles.pass, '[pass] ' + msg);
					else self.log(styles.fail, '[fail] ' + msg);
				} catch (e) {
					console.log(e);
					self.log(styles.fail, '[error] ' + e.name + ': ' + e.message);
				}
			}
		};
	},
	stepComplete (nextStepContext) {
		this.setState({ nextStepContext });
		this.log(`Step ${this.state.step} complete\n`);
	},
	nextStep () {
		this.setState({
			step: this.state.step + 1,
			stepContext: this.state.nextStepContext,
			nextStepContext: null,
		});
	},
	renderLog () {
		return this.state.log.map((msg, i) => {
			if (typeof msg.content === 'object') {
				return <Domify style={styles.obj} key={`log${i}`} value={msg.content} />;
			}
			return <div style={msg.style} key={`log${i}`}>{msg.content}
;
		});
	},
	render () {
		console.log(this.state.stepContext);
		const StepComponent = steps[this.state.step - 1];
		return (

				<Row>
					<Col sm="1/2">

							<StepComponent
								assert={this.stepAssert}
								complete={this.stepComplete}
								next={this.nextStep}
								ready={this.stepReady}
								result={this.stepResult}
								run={this.stepRun}
								stepContext={this.state.stepContext}
							/>

					</Col>
					<Col sm="1/2">

							{this.renderLog()}

					</Col>
				</Row>

		);
	}
});

const styles = {
	box: {
		backgroundColor: 'white',
		borderRadius: '0.3em',
		boxShadow: '0 2px 3px rgba(0, 0, 0, 0.075), 0 0 0 1px rgba(0,0,0,0.1)',
		margin: '6vh auto',
		padding: '3em',
	},
	obj: {
		border: '1px solid #ccc',
		fontFamily: 'Monaco',
		fontSize: '0.9em',
		margin: '0.3em -1em',
		padding: '0.5em 1.3em',
	},
	message: {
		fontSize: '1.2em',
		margin: '0.2em',
	},
	pass: {
		color: 'green',
		fontFamily: 'Monaco',
		margin: '0.2em',
	},
	fail: {
		color: 'red',
		fontFamily: 'Monaco',
		margin: '0.2em',
	},
};

ReactDOM.render(<App />, document.getElementById('app'));
<|endoftext|>


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

  angular.module('foundation.dynamicRouting.animations', ['ngAnimate', 'foundation.dynamicRouting'])
    .animation('.ui-animation', uiAnimation)
  ;

  uiAnimation.$inject = ['$rootScope', '$state'];

  function uiAnimation($rootScope, $state) {
    var events = ['webkitAnimationEnd', 'mozAnimationEnd', 'MSAnimationEnd', 'oanimationend', 'animationend',
                  'webkitTransitionEnd', 'otransitionend', 'transitionend'];

    var parentStyle = 'position-absolute';

    var animation = {};

    animation.enter = enterAnimation;
    animation.leave = leaveAnimation;

    return animation;

    function enterAnimation(element, done) {
      var scope = element.scope();

      if(scope.vars && scope.vars.animationIn) {
        var animationIn  = scope.vars.animationIn;
        var animationOut = scope.vars.animationOut || '';
        var initial  = 'ng-enter';
        var activate = 'ng-enter-active';
        var timedOut = true;

        //reset possible failed animations and bugs
        element.parent().addClass(parentStyle);
        element.removeClass(activate + ' ' + initial + ' ' + animationIn + ' ' + animationOut);
        element[0].style.transitionDuration = 0;

        //start animation
        element.addClass(animationIn);
        element.addClass(initial);

        $rootScope.$digest();

        element[0].style.transitionDuration = '';
        element.addClass(activate);

        var finishAnimation = function() {
          element.parent().removeClass(parentStyle);
          element.removeClass(activate + ' ' + initial + ' ' + animationIn + ' ' + animationOut);
          timedOut = false;
          done();
        }

        element.one(events.join(' '), function() {
          finishAnimation();
        });

        setTimeout(function() {
          if (timedOut) {
            finishAnimation();
          }
        }, 3000);

      } else {
        done();
      }

      return function(isCancelled) {

      };
    }

    function leaveAnimation(element, done) {
      var scope = element.scope();

      if(scope.vars && scope.vars.animationOut) {
        var animationIn  = scope.vars.animationIn || '';
        var animationOut = scope.vars.animationOut;
        var initial  = 'ng-leave';
        var activate = 'ng-leave-active';
        var timedOut = true;

        element.removeClass(activate + ' ' + initial + ' ' + animationIn + ' ' + animationOut);
        element[0].style.transitionDuration = 0;

        //start animation
        element.addClass(animationOut);
        element.addClass(initial);

        $rootScope.$digest();

        element[0].style.transitionDuration = '';
        element.addClass(activate);

        var finishAnimation = function() {
          element.parent().removeClass(parentStyle);
          element.removeClass(activate + ' ' + initial + ' ' + animationIn + ' ' + animationOut);
          timedOut = false;
          done();
        }

        element.one(events.join(' '), function() {
          finishAnimation();
        });

        setTimeout(function() {
          if (timedOut) {
            finishAnimation();
          }
        }, 3000);

      } else {
        done();
      }

      return function(isCancelled) {

      };
    }
  }

})();
<commit_msg>refactored<commit_after>(function() {
  'use strict';

  angular.module('foundation.dynamicRouting.animations', ['ngAnimate', 'foundation.dynamicRouting'])
    .animation('.ui-animation', uiAnimation)
  ;

  uiAnimation.$inject = ['$animate'];

  function uiAnimation($animate) {
    var parentStyle = 'position-absolute';

    return {
      enter : enterAnimation,
      leave : leaveAnimation
    };

    function enterAnimation(element, done) {
      var scope      = element.scope();
      var enterClass = scope.$eval('vars.animationIn');

      if (! enterClass || element.hasClass(enterClass)) {
        done();
        return angular.noop;
      }

      element.parent().addClass(parentStyle);

      var animation = $animate.addClass(element, enterClass)
        .then(function() {
          element.parent().removeClass(parentStyle);
          done();
        });

      return function () {
        $animate.cancel(animation);
      };
    }

    function leaveAnimation(element, done) {
      var scope      = element.scope();
      var leaveClass = scope.$eval('vars.animationOut');

      if (! leaveClass || element.hasClass(leaveClass)) {
        done();
        return angular.noop;
      }

      element.parent().addClass(parentStyle);

      var animation = $animate.addClass(element, leaveClass)
        .then(function() {
          element.parent().removeClass(parentStyle);
          done();
        });

      return function () {
        $animate.cancel(animation);
      };
    }
  }

})();
<|endoftext|>


<commit_before>import React from 'react';
import * as Paginations from '@trendmicro/react-paginations';
import '@trendmicro/react-paginations/dist/react-paginations.css';
import i18n from '../../lib/i18n';

export const TablePagination = (props) => {
    return (
        <Paginations.TablePagination
            {...props}
            pageRecordsRenderer={({ totalRecords, from, to }) => {
                if (totalRecords > 0) {
                    return i18n._('Records: {{from}} - {{to}} / {{total}}', {
                        from,
                        to,
                        total: total
                    });
                }

                return i18n._('Records: {{total}}', { total: totalRecords });
            }}
            pageLengthRenderer={({ pageLength }) => (

                    {i18n._('{{pageLength}} per page', { pageLength })}

            )}
        />
    );
};
<commit_msg>eslint fixes<commit_after>import React from 'react';
import * as Paginations from '@trendmicro/react-paginations';
import '@trendmicro/react-paginations/dist/react-paginations.css';
import i18n from '../../lib/i18n';

export const TablePagination = (props) => {
    return (
        <Paginations.TablePagination
            {...props}
            pageRecordsRenderer={({ totalRecords, from, to }) => {
                if (totalRecords > 0) {
                    return i18n._('Records: {{from}} - {{to}} / {{total}}', {
                        from,
                        to,
                        total: totalRecords
                    });
                }

                return i18n._('Records: {{total}}', { total: totalRecords });
            }}
            pageLengthRenderer={({ pageLength }) => (

                    {i18n._('{{pageLength}} per page', { pageLength })}

            )}
        />
    );
};
<|endoftext|>


<commit_before>import AudioStats from '../../lib/AudioStats';
import BucketStats from '../../lib/BucketStats';

self.onmessage = function (e) {
  const { token, zoomLevel, start, end, channels } = e.data;
  const startTime = Date.now();
  console.log('working:', startTime, `${startTime - token}ms`);
  let bucketSize = e.data.bucketSize || 1;
  let forceEmitTime = e.data.forceEmitTime || 0;
  let lastEmit = startTime;
  const audioLength = end - start;
  bucketSize = Math.min(audioLength, bucketSize);
  const renderSize = Math.pow(2, 16);
  const itemsPerRender = audioLength / renderSize;
  const numberOfChannels = channels.length;
  let mainStart = start;
  const mainEnd = end;
  const stats = {
    mono: new BucketStats(bucketSize, audioLength, AudioStats),
    channels: []
  };
  for (let channelNum = 0; channelNum < numberOfChannels; channelNum++) {
    stats.channels.push(new BucketStats(bucketSize, audioLength, AudioStats));
  }
  const emit = function (isFinished) {
    if (isFinished || (
      forceEmitTime > 0 &&
      Date.now() - lastEmit > forceEmitTime)) {
      const message = {
        token: token,
        isFinished: isFinished,
        zoomLevel: zoomLevel,
        start: start,
        end: end,
        mono: [],
        channels: []
      };
      message.mono = stats.mono.get(true);
      for (let channelNum = 0; channelNum < numberOfChannels; channelNum++) {
        message.channels[channelNum] = stats.channels[channelNum].get(true);
      }
      message.renderTime = Date.now() - startTime;
      self.postMessage(message);
      lastEmit = Date.now();
    }
  };
  let outerIndex = 0;
  while (mainStart < mainEnd) {
    for (let bucketIndex = 0; bucketIndex < renderSize; bucketIndex++) {
      const audioIndex = Math.floor(itemsPerRender * bucketIndex) + outerIndex;
      //const audioIndex = mainStart; // render in order
      if (audioIndex < channels[0].length) {
        let monoValue = 0;
        for (let channelNum = 0; channelNum < numberOfChannels; channelNum++) {
          const val = channels[channelNum][audioIndex];
          monoValue += val;
          stats.channels[channelNum].processAt(audioIndex, val);
        }
        stats.mono.processAt(audioIndex, monoValue / numberOfChannels);
      }
      mainStart++;
    }
    outerIndex++;
    emit(false);
  }
  emit(true);
  emit(true);
};

self.onerror = function (err) {
  /*eslint-disable */
  console.log('worker error: waveformData', err);
  /*eslint-enable */
};
<commit_msg>remove dupe emit()<commit_after>import AudioStats from '../../lib/AudioStats';
import BucketStats from '../../lib/BucketStats';

self.onmessage = function (e) {
  const { token, zoomLevel, start, end, channels } = e.data;
  const startTime = Date.now();
  console.log('working:', startTime, `${startTime - token}ms`);
  let bucketSize = e.data.bucketSize || 1;
  let forceEmitTime = e.data.forceEmitTime || 0;
  let lastEmit = startTime;
  const audioLength = end - start;
  bucketSize = Math.min(audioLength, bucketSize);
  const renderSize = Math.pow(2, 16);
  const itemsPerRender = audioLength / renderSize;
  const numberOfChannels = channels.length;
  let mainStart = start;
  const mainEnd = end;
  const stats = {
    mono: new BucketStats(bucketSize, audioLength, AudioStats),
    channels: []
  };
  for (let channelNum = 0; channelNum < numberOfChannels; channelNum++) {
    stats.channels.push(new BucketStats(bucketSize, audioLength, AudioStats));
  }
  const emit = function (isFinished) {
    if (isFinished || (
      forceEmitTime > 0 &&
      Date.now() - lastEmit > forceEmitTime)) {
      const message = {
        token: token,
        isFinished: isFinished,
        zoomLevel: zoomLevel,
        start: start,
        end: end,
        mono: [],
        channels: []
      };
      message.mono = stats.mono.get(true);
      for (let channelNum = 0; channelNum < numberOfChannels; channelNum++) {
        message.channels[channelNum] = stats.channels[channelNum].get(true);
      }
      message.renderTime = Date.now() - startTime;
      self.postMessage(message);
      lastEmit = Date.now();
    }
  };
  let outerIndex = 0;
  while (mainStart < mainEnd) {
    for (let bucketIndex = 0; bucketIndex < renderSize; bucketIndex++) {
      const audioIndex = Math.floor(itemsPerRender * bucketIndex) + outerIndex;
      //const audioIndex = mainStart; // render in order
      if (audioIndex < channels[0].length) {
        let monoValue = 0;
        for (let channelNum = 0; channelNum < numberOfChannels; channelNum++) {
          const val = channels[channelNum][audioIndex];
          monoValue += val;
          stats.channels[channelNum].processAt(audioIndex, val);
        }
        stats.mono.processAt(audioIndex, monoValue / numberOfChannels);
      }
      mainStart++;
    }
    outerIndex++;
    emit(false);
  }
  emit(true);
};

self.onerror = function (err) {
  /*eslint-disable */
  console.log('worker error: waveformData', err);
  /*eslint-enable */
};
<|endoftext|>


<commit_before>let Joi = require('joi');

let mutableFields = Joi.object({
  calendarType: Joi.string().valid(['INVENTORY', 'CONFIRMATION_METHOD']).description('Enum value for calendarType'),
  sellMode: Joi.string().valid(['AVAILABLE', 'UNAVAILABLE', 'CALL_AND_REQUEST']).description('Enum value for sellMode')
});

let mutableFieldsStrict = mutableFields.requiredKeys(
  'calendarType',
  'sellMode'
);

let postFields = mutableFieldsStrict.keys({
  calendarId: joiBox.shortId.required()
});

module.exports = {
  mutableFields,
  mutableFieldsStrict,
  postFields
};
<commit_msg>forgot to finish this..<commit_after>import Joi from 'joi';
import shortIdSchema from '../common/shortId';

let mutableFields = Joi.object({
  calendarType: Joi.string().valid(['INVENTORY', 'CONFIRMATION_METHOD']).description('Enum value for calendarType'),
  sellMode: Joi.string().valid(['AVAILABLE', 'UNAVAILABLE', 'CALL_AND_REQUEST']).description('Enum value for sellMode')
});

let mutableFieldsStrict = mutableFields.requiredKeys(
  'calendarType',
  'sellMode'
);

let postFields = mutableFieldsStrict.keys({
  calendarId: shortIdSchema.required()
});

module.exports = {
  mutableFields,
  mutableFieldsStrict,
  postFields
};
<|endoftext|>


<commit_before>(function() {
  function hideAllTabContent() {
    var tabs = document.querySelectorAll('.tab');
    Array.from(tabs).forEach(function(tab) {
      tab.classList.remove('active');
    });

    var tabContents = document.querySelectorAll('.tabContent');
    Array.from(tabContents).forEach(function(content) {
      content.style.display = 'none';
    });
  }

  function showTabContent() {
    this.classList.add('active');
    var tab = this.getAttribute('data-tab');
    var tabContent = document.querySelector('.tabContent[data-tab="{tab}"]'.replace('{tab}', tab));
    tabContent.style.display = 'block';
  }

  hideAllTabContent();
  var tabs = document.querySelectorAll('.tab');
  Array.from(tabs).forEach(function(tab) {
    tab.onclick = function() {
      hideAllTabContent();
      showTabContent.apply(tab);
    };
    if (tab.classList.contains('default')) {
      showTabContent.apply(tab);
    }
  });
})();
<commit_msg>Explicitly pass around references to tab elements<commit_after>(function() {
  var tabs = document.querySelectorAll('.tab');

  function hideAllTabContent(tabs) {
    Array.from(tabs).forEach(function(tab) {
      tab.classList.remove('active');
    });

    var tabContents = document.querySelectorAll('.tabContent');
    Array.from(tabContents).forEach(function(content) {
      content.style.display = 'none';
    });
  }

  function showTabContent(tab) {
    tab.classList.add('active');
    contentRef = tab.getAttribute('data-tab');
    var tabContent = document.querySelector('.tabContent[data-tab="{tab}"]'.replace('{tab}', contentRef));
    tabContent.style.display = 'block';
  }

  hideAllTabContent(tabs);
  Array.from(tabs).forEach(function(tab) {
    tab.onclick = function() {
      hideAllTabContent(tabs);
      showTabContent(tab);
    };
    if (tab.classList.contains('default')) {
      showTabContent(tab);
    }
  });
})();
<|endoftext|>