<commit_before>
/**
 ** Skeleton for new modules
 **/

define(['../remoteStorage', './deps/vcardjs-0.2'], function(remoteStorage, vCardJS) {

  var moduleName = "contacts";

  var VCard = vCardJS.VCard, VCF = vCardJS.VCF;

  remoteStorage.defineModule(moduleName, function(base) {

    var DEBUG = true;

    // Copy over all properties from source to destination.
    // Return destination.
    function extend(destination, source) {
      var keys = Object.keys(source);
      for(var i=0;i<keys.length;i++) {
        var key = keys[i];
        destination[key] = source[key];
      }
      return destination;
    }

    var contacts = {};

    // Copy over all properties from source to destination.
    // Return destination.
    function extend() {
      var destination = arguments[0], source;
      for(var i=1;i<arguments.length;i++) {
        source = arguments[i];
        var keys = Object.keys(source);
        for(var j=0;j<keys.length;j++) {
          var key = keys[j];
          destination[key] = source[key];
        }
      }
      return destination;
    }

    var bindContext = (
      ( (typeof (function() {}).bind === 'function') ?
        // native version
        function(cb, context) { return cb.bind(context); } :
        // custom version
        function(cb, context) {
          return function() { return cb.apply(context, arguments); }
        } )
    );

    var debug = DEBUG ? bindContext(console.log, console) : function() {};

    var nodePrototype = {

      isNew: true,

      markSaved: function() {
        this.isNew = false;
        return this;
      },

      save: function() {
        this.validate();

        if(this.errors && this.errors.length > 0) {
          return false;
        } else {
          base.storeObject('vcard+' + this.kind, this.uid, this.toJCard());
          this.markSaved();
          return true;
        }
      },
    }

    /**
     ** The Contact class.
     **/
    var Contact = function() {
      VCard.apply(this, arguments);
      this.setAttribute('kind', 'individual');
    }

    extend(Contact.prototype, nodePrototype, VCard.prototype, {
    });

    /**
     ** The Group class.
     **/

    var Group = function(name) {
      VCard.apply(this, arguments);
      this.setAttribute('kind', 'group');
    }

    extend(Group.prototype, nodePrototype, {

      getMembers: function() {
        var members = [];
        for(var i=0;i<this.member.length;i++) {
          members.push(this.lookupMember(member[i]));
        }
        return members;
      },

      // resolve a URI to a contact an return it.
      lookupMember: function(uri) {
        var md = uri.match(/^([^:]):(.*)$/), scheme = md[1], rest = md[2];
        var key;
        switch(scheme) {
          // URN and UUID directly resolve to the contact's key.
          // if they don't, there is nothing we can do about it.
        case 'urn':
        case 'uuid':
          return contacts.get(uri);
        case 'mailto':
        case 'xmpp':
        case 'sip':
        case 'tel':
          var query = {};
          query[{
            mailto: 'email',
            xmpp: 'impp',
            sip: 'impp',
            tel: 'tel'
          }[scheme]] = rest;
          var results = contacts.search(query);
          if(results.length > 0) {
            return results[0];
          }
          if(scheme == 'tel') {
            break; // no fallback for TEL
          }
          // fallback for MAILTO, XMPP, SIP schems is webfinger:
        case 'acct':
          console.error("FIXME: implement contact-lookup via webfinger!");
          break;
          // HTTP could resolve to a foaf profile, a vcard, a jcard...
        case 'http':
          console.error("FIXME: implement contact-lookup via HTTP!");
          break;
        default:
          console.error("FIXME: unknown URI scheme " + scheme);
        }
        return undefined;
      }

    });

    /**
     ** THE CONTACTS MODULE
     **/

    extend(contacts, {
      /**
       ** NAMESPACE
       **/

      Contact: Contact,

      /**
       ** PUBLIC METHODS
       **/

      on: function(eventType, callback) {
        base.on(eventType, function(event) {
          if(event.oldValue) {
            event.oldValue = new Contact(event.oldValue);
          }
          if(event.newValue) {
            event.newValue = new Contact(event.newValue);
          }
          callback(event);
        });
      },

      sync: function() {
        debug("contacts.sync()");
        base.sync('/');
      },

      list: function(limit, offset) {
        var list = base.getListing('');
        if(! offset) {
          offset = 0;
        }
        for(var i=0;i<limit;i++) {
          list[i + offset] = this.get(list[i + offset]);
        }
        return list;
      },

      // Get a Contact instance based on it's UID.
      get: function(uid, cb, context) {
        if(cb) {
          base.getObject(uid, function(data) {
            bindContext(cb, context)(this._load(data));
          }, this);
        } else {
          return this._load(base.getObject(uid));
        }
      },

      build: function(attributes) {
        return this._wrap(attributes);
      },

      create: function(attributes) {
        var instance = this.build(attributes);
        instance.save();
        return instance;
      },

      filter: function(cb, context) {
        // this is highly ineffective. go fix it!
        var list = this.list();
        var results = [];
        var item;
        for(var i=0;i<list.length;i++) {
          item = bindContext(cb, context)(list[i]);
          if(item) {
            results.push(item)
          }
        }
        return results;
      },

      search: function(filter) {
        var keys = Object.keys(filter);

        return this.filter(function(item) {
          return this.searchMatch(item, filter, keys);
        }, this);
      },

      searchMatch: function(item, filter, filterKeys) {
        if(! filterKeys) {
          filterKeys = Object.keys(filter);
        }

        var check = function(value, ref) {
          if(value instanceof Array) {
            // multiples, such as MEMBER, EMAIL, TEL
            for(var i=0;i<value.length;i++) {
              check(value[i], ref);
            }
          } else if(typeof value === 'object' && value.value) {
            // compounds, such as EMAIL, TEL, IMPP
            check(value.value, ref);
          } else {
            if(typeof(ref) === 'string' && ref.length === 0) {
              return true; // the empty string always matches
            } else if(ref instanceof RegExp) {
              if(! ref.test(value)) {
                return false;
              }
            } else if(value !== ref) {
              // equality is fallback.
              return false;
            }
          }
        }

        return this.filter(function(item) {
          for(var i=0;i<keys.length;i++) {
            var k = keys[i], v = filter[k];
            if(! check(item[k], v)) {
              return false;
            }
          }
          debug('success');
          return item;
        });
      },

      /**
       ** PRIVATE METHODS
       **/

      // _wrap given data and mark as saved.
      _load: function(data) {
        return this._wrap(data).markSaved();
      },

      // return given data as a Contact instance.
      // do nothing, if it's already a contact.
      _wrap: function(data) {
        return(data instanceof Contact ? data : new Contact(data));
      }

    });

    return {
      name: moduleName,

      dataHints: {
      },

      exports: contacts
    }
  });

  return remoteStorage[moduleName];

});
<commit_msg>fixed dependency for contacts module<commit_after>
/**
 ** Skeleton for new modules
 **/

define(['../remoteStorage', 'modules/deps/vcardjs-0.2'], function(remoteStorage, vCardJS) {
  var moduleName = "contacts";

  var VCard = vCardJS.VCard, VCF = vCardJS.VCF;

  remoteStorage.defineModule(moduleName, function(base) {

    var DEBUG = true;

    // Copy over all properties from source to destination.
    // Return destination.
    function extend(destination, source) {
      var keys = Object.keys(source);
      for(var i=0;i<keys.length;i++) {
        var key = keys[i];
        destination[key] = source[key];
      }
      return destination;
    }

    var contacts = {};

    // Copy over all properties from source to destination.
    // Return destination.
    function extend() {
      var destination = arguments[0], source;
      for(var i=1;i<arguments.length;i++) {
        source = arguments[i];
        var keys = Object.keys(source);
        for(var j=0;j<keys.length;j++) {
          var key = keys[j];
          destination[key] = source[key];
        }
      }
      return destination;
    }

    var bindContext = (
      ( (typeof (function() {}).bind === 'function') ?
        // native version
        function(cb, context) { return cb.bind(context); } :
        // custom version
        function(cb, context) {
          return function() { return cb.apply(context, arguments); }
        } )
    );

    var debug = DEBUG ? bindContext(console.log, console) : function() {};

    var nodePrototype = {

      isNew: true,

      markSaved: function() {
        this.isNew = false;
        return this;
      },

      save: function() {
        this.validate();

        if(this.errors && this.errors.length > 0) {
          return false;
        } else {
          base.storeObject('vcard+' + this.kind, this.uid, this.toJCard());
          this.markSaved();
          return true;
        }
      },
    }

    /**
     ** The Contact class.
     **/
    var Contact = function() {
      VCard.apply(this, arguments);
      this.setAttribute('kind', 'individual');
    }

    extend(Contact.prototype, nodePrototype, VCard.prototype, {
    });

    /**
     ** The Group class.
     **/

    var Group = function(name) {
      VCard.apply(this, arguments);
      this.setAttribute('kind', 'group');
    }

    extend(Group.prototype, nodePrototype, {

      getMembers: function() {
        var members = [];
        for(var i=0;i<this.member.length;i++) {
          members.push(this.lookupMember(member[i]));
        }
        return members;
      },

      // resolve a URI to a contact an return it.
      lookupMember: function(uri) {
        var md = uri.match(/^([^:]):(.*)$/), scheme = md[1], rest = md[2];
        var key;
        switch(scheme) {
          // URN and UUID directly resolve to the contact's key.
          // if they don't, there is nothing we can do about it.
        case 'urn':
        case 'uuid':
          return contacts.get(uri);
        case 'mailto':
        case 'xmpp':
        case 'sip':
        case 'tel':
          var query = {};
          query[{
            mailto: 'email',
            xmpp: 'impp',
            sip: 'impp',
            tel: 'tel'
          }[scheme]] = rest;
          var results = contacts.search(query);
          if(results.length > 0) {
            return results[0];
          }
          if(scheme == 'tel') {
            break; // no fallback for TEL
          }
          // fallback for MAILTO, XMPP, SIP schems is webfinger:
        case 'acct':
          console.error("FIXME: implement contact-lookup via webfinger!");
          break;
          // HTTP could resolve to a foaf profile, a vcard, a jcard...
        case 'http':
          console.error("FIXME: implement contact-lookup via HTTP!");
          break;
        default:
          console.error("FIXME: unknown URI scheme " + scheme);
        }
        return undefined;
      }

    });

    /**
     ** THE CONTACTS MODULE
     **/

    extend(contacts, {
      /**
       ** NAMESPACE
       **/

      Contact: Contact,

      /**
       ** PUBLIC METHODS
       **/

      on: function(eventType, callback) {
        base.on(eventType, function(event) {
          if(event.oldValue) {
            event.oldValue = new Contact(event.oldValue);
          }
          if(event.newValue) {
            event.newValue = new Contact(event.newValue);
          }
          callback(event);
        });
      },

      sync: function() {
        debug("contacts.sync()");
        base.sync('/');
      },

      list: function(limit, offset) {
        var list = base.getListing('');
        if(! offset) {
          offset = 0;
        }
        for(var i=0;i<limit;i++) {
          list[i + offset] = this.get(list[i + offset]);
        }
        return list;
      },

      // Get a Contact instance based on it's UID.
      get: function(uid, cb, context) {
        if(cb) {
          base.getObject(uid, function(data) {
            bindContext(cb, context)(this._load(data));
          }, this);
        } else {
          return this._load(base.getObject(uid));
        }
      },

      build: function(attributes) {
        return this._wrap(attributes);
      },

      create: function(attributes) {
        var instance = this.build(attributes);
        instance.save();
        return instance;
      },

      filter: function(cb, context) {
        // this is highly ineffective. go fix it!
        var list = this.list();
        var results = [];
        var item;
        for(var i=0;i<list.length;i++) {
          item = bindContext(cb, context)(list[i]);
          if(item) {
            results.push(item)
          }
        }
        return results;
      },

      search: function(filter) {
        var keys = Object.keys(filter);

        return this.filter(function(item) {
          return this.searchMatch(item, filter, keys);
        }, this);
      },

      searchMatch: function(item, filter, filterKeys) {
        if(! filterKeys) {
          filterKeys = Object.keys(filter);
        }

        var check = function(value, ref) {
          if(value instanceof Array) {
            // multiples, such as MEMBER, EMAIL, TEL
            for(var i=0;i<value.length;i++) {
              check(value[i], ref);
            }
          } else if(typeof value === 'object' && value.value) {
            // compounds, such as EMAIL, TEL, IMPP
            check(value.value, ref);
          } else {
            if(typeof(ref) === 'string' && ref.length === 0) {
              return true; // the empty string always matches
            } else if(ref instanceof RegExp) {
              if(! ref.test(value)) {
                return false;
              }
            } else if(value !== ref) {
              // equality is fallback.
              return false;
            }
          }
        }

        return this.filter(function(item) {
          for(var i=0;i<keys.length;i++) {
            var k = keys[i], v = filter[k];
            if(! check(item[k], v)) {
              return false;
            }
          }
          debug('success');
          return item;
        });
      },

      /**
       ** PRIVATE METHODS
       **/

      // _wrap given data and mark as saved.
      _load: function(data) {
        return this._wrap(data).markSaved();
      },

      // return given data as a Contact instance.
      // do nothing, if it's already a contact.
      _wrap: function(data) {
        return(data instanceof Contact ? data : new Contact(data));
      }

    });

    return {
      name: moduleName,

      dataHints: {
      },

      exports: contacts
    }
  });

  return remoteStorage[moduleName];

});
<|endoftext|>


<commit_before>// https://en.wikipedia.org/wiki/Null_Island
var latitude = "0";
var longitude = "0";

function reloadNearby() {
  $.ajax({
    url: "/nearby",

    success: function(data) {
      $("#alert").fadeOut(500, function() {
        $("#feed").html(data);
        PkSpr.process_dom();
        $("#feed").fadeIn(500);
      });
    },

    error: function() {
      $("#alert").html("Failed to refresh nearby Pokémon.");
      $("#alert").attr("class", "alert alert-danger");
      $("#alert").fadeIn(250);
    }
  });
}

$("#login-modal").on("shown.bs.modal", function() {
  // Prompt user for location
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(pos) {
      latitude = pos.coords.latitude;
      longitude = pos.coords.longitude;
    });
  }

  // Focus the username field
  $(this).find("[autofocus]").focus();
});

$("#login-form").submit(function(e) {
  e.preventDefault();

  $("#login-alert").html("Logging in…");
  $("#login-alert").attr("class", "alert alert-info");
  $("#login-alert").show();

  var loginData = $(this).serializeArray();
  loginData.push({name: "latitude", value: latitude});
  loginData.push({name: "longitude", value: longitude});

  $.ajax({
    url: "/login",
    type: "POST",
    data: loginData,
    success: function(data) {
      $("#login-alert").html("Success!");
      $("#login-alert").attr("class", "alert alert-success");
      $("#login-alert").show().delay(1000).queue(function() {
        $("#login-modal").modal("toggle");

        $("#alert").html("Locating nearby Pokémon…");
        $("#alert").attr("class", "alert alert-info");
        $("#alert").fadeIn(500);

        reloadNearby();
        setInterval(reloadNearby, 30000);
      });
    },

    error: function(data) {
      $("#login-alert").html(data["responseText"]);
      $("#login-alert").attr("class", "alert alert-danger");
    }
  });
});

$(window).load(function() {
  $.ajax({
    url: "/logged-in",

    statusCode: {
      200: function() {
        // Already logged in, so skip showing login modal
        reloadNearby();
        setInterval(reloadNearby, 5000);
      },

      401: function() {
        $("#login-modal").modal("show");
      }
    }
  });
});
<commit_msg>Begin locating nearby Pokémon immediately<commit_after>// https://en.wikipedia.org/wiki/Null_Island
var latitude = "0";
var longitude = "0";

function reloadNearby() {
  $.ajax({
    url: "/nearby",

    success: function(data) {
      $("#alert").fadeOut(500, function() {
        $("#feed").html(data);
        PkSpr.process_dom();
        $("#feed").fadeIn(500);
      });
    },

    error: function() {
      $("#alert").html("Failed to refresh nearby Pokémon.");
      $("#alert").attr("class", "alert alert-danger");
      $("#alert").fadeIn(250);
    }
  });
}

$("#login-modal").on("shown.bs.modal", function() {
  // Prompt user for location
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(pos) {
      latitude = pos.coords.latitude;
      longitude = pos.coords.longitude;
    });
  }

  // Focus the username field
  $(this).find("[autofocus]").focus();
});

$("#login-form").submit(function(e) {
  e.preventDefault();

  $("#login-alert").html("Logging in…");
  $("#login-alert").attr("class", "alert alert-info");
  $("#login-alert").show();

  var loginData = $(this).serializeArray();
  loginData.push({name: "latitude", value: latitude});
  loginData.push({name: "longitude", value: longitude});

  $.ajax({
    url: "/login",
    type: "POST",
    data: loginData,
    success: function(data) {
      // Begin locating nearby Pokémon immediately
      reloadNearby();
      setInterval(reloadNearby, 30000);

      $("#login-alert").html("Success!");
      $("#login-alert").attr("class", "alert alert-success");
      $("#login-alert").show().delay(1000).queue(function() {
        $("#login-modal").modal("toggle");

        $("#alert").html("Locating nearby Pokémon…");
        $("#alert").attr("class", "alert alert-info");
        $("#alert").fadeIn(500);
      });
    },

    error: function(data) {
      $("#login-alert").html(data["responseText"]);
      $("#login-alert").attr("class", "alert alert-danger");
    }
  });
});

$(window).load(function() {
  $.ajax({
    url: "/logged-in",

    statusCode: {
      200: function() {
        // Already logged in, so skip showing login modal
        reloadNearby();
        setInterval(reloadNearby, 5000);
      },

      401: function() {
        $("#login-modal").modal("show");
      }
    }
  });
});
<|endoftext|>


<commit_before>'use strict';

const Ravel = require('ravel');
const rp = require('request-promise');

class UnscopedPackageError extends Ravel.Error {
  constructor(msg) {
    super(msg, constructor, 308);
  }
}

class UnsubmittedPackageError extends Ravel.Error {
  constructor(msg) {
    super(msg, constructor, 307);
  }
}

class NpmProxyError extends Ravel.Error {
  constructor(msg) {
    super(msg, constructor, 500);
  }
}

/**
 * Logic for listing, retrieving, publishing packages
 */
class Packages extends Ravel.Module {

  isScoped(id) {
    // TODO should we check for the slash as well? This is faster, but maybe not sufficient.
    return id[0] === '@';
  }

  getScope(id) {
    const scope = id.match(/^@([\w\-]+)\/([\w\-]+)$/);
    if (scope === null) {
      throw new UnscopedPackageError(`Package id ${id} is not a scoped package`);
    }
    return scope[1];
  }

  _retrieveInfo(id) { //eslint-disable-line no-unused-vars
    return Promise.reject(new UnsubmittedPackageError({
      error: `nom can't find the package you're looking for.\nPlease encourage the developer to submit it to nom!`
    }));
  }

  /**
   * Re-encode a package id to use urlencoded format for slashes
   */
  encode(id) {
    return id.replace('/','%2f');
  }

  // TODO env var instead of hard coding registry url?
  _retrieveInfoFromNpm(id) {
    let rpOptions = {
      uri: `https://registry.npmjs.org/${this.encode(id)}`,
      json: true
    };

    this.log.debug(`Proxying to npm: ${rpOptions.uri}`);
    return new Promise((resolve, reject) => {
      rp(rpOptions)
        .then((response) => resolve(response))
        .catch((err) => {
          let errMessage = `Unable to retrieve package info for ${id} from npm`;
          this.log.error(errMessage, err);
          reject(new NpmProxyError({error: errMessage}));
        });
    });
  }

  /**
   * Retrieve package information based on a package name
   * @param id {String} the package name (such as @raveljs/ravel).
   * @param query {Object} optional, if specifies proxynpm then will retrieve package info from npm.
   * @return {Promise} resolves if the package is in the nom registry, or if proxynpm is requested
   *                   and the package is found in npm, rejects otherwise.
   */
  info(id, query) {
    const opts = query || {};  // no default parameters in node yet
    this.log.info(`client asked for info on: ${id}`);

    if (this.isScoped(id)) {
      return this._retrieveInfo(id);
    } else if (opts.proxynpm) {
      return this._retrieveInfoFromNpm(id);
    } else {
      return Promise.reject(new UnscopedPackageError({
        error: 'nom does not permit unscoped packages'
      }));
    }
  }

  /**
   * Create or update package info and publish tarballs to blob store
   * @param {Object} args:
   *   @param {String} name
   *   @param {String} description
   *   @param {Object} dist-tags
   *   @param {Object} versions
   *   @param {String} readme
   *   @param {Object} _attachments
   * @return {Promise} resolves when package publish is compmlete, rejects with any errors
   */
  publish(args) { //eslint-disable-line no-unused-vars
    return Promise.reject(new this.ApplicationError.NotImplemented('Not implemented yet :)'));
  }
}

module.exports = Packages;
<commit_msg>Fixing some syntax from merge<commit_after>'use strict';

const Ravel = require('ravel');
const inject = Ravel.inject;

class UnscopedPackageError extends Ravel.Error {
  constructor(msg) {
    super(msg, constructor, 308);
  }
}

class UnsubmittedPackageError extends Ravel.Error {
  constructor(msg) {
    super(msg, constructor, 307);
  }
}

class NpmProxyError extends Ravel.Error {
  constructor(msg) {
    super(msg, constructor, 500);
  }
}

/**
 * Logic for listing, retrieving, publishing packages
 */
@inject('request-promise')
class Packages extends Ravel.Module {

  constructor(rp) {
    super();
    this.rp = rp;
  }

  isScoped(id) {
    // TODO should we check for the slash as well? This is faster, but maybe not sufficient.
    return id[0] === '@';
  }

  getScope(id) {
    const scope = id.match(/^@([\w\-]+)\/([\w\-]+)$/);
    if (scope === null) {
      throw new UnscopedPackageError(`Package id ${id} is not a scoped package`);
    }
    return scope[1];
  }

  _retrieveInfo(id) { //eslint-disable-line no-unused-vars
    return Promise.reject(new UnsubmittedPackageError({
      error: `nom can't find the package you're looking for.\nPlease encourage the developer to submit it to nom!`
    }));
  }

  /**
   * Re-encode a package id to use urlencoded format for slashes
   */
  encode(id) {
    return id.replace('/','%2f');
  }

  // TODO env var instead of hard coding registry url?
  _retrieveInfoFromNpm(id) {
    let rpOptions = {
      uri: `https://registry.npmjs.org/${this.encode(id)}`,
      json: true
    };

    this.log.debug(`Proxying to npm: ${rpOptions.uri}`);
    return new Promise((resolve, reject) => {
      this.rp(rpOptions)
        .then((response) => resolve(response))
        .catch((err) => {
          let errMessage = `Unable to retrieve package info for ${id} from npm`;
          this.log.error(errMessage, err);
          reject(new NpmProxyError({error: errMessage}));
        });
    });
  }

  /**
   * Retrieve package information based on a package name
   * @param id {String} the package name (such as @raveljs/ravel).
   * @param query {Object} optional, if specifies proxynpm then will retrieve package info from npm.
   * @return {Promise} resolves if the package is in the nom registry, or if proxynpm is requested
   *                   and the package is found in npm, rejects otherwise.
   */
  info(id, query) {
    const opts = query || {};  // no default parameters in node yet
    this.log.info(`client asked for info on: ${id}`);

    if (this.isScoped(id)) {
      return this._retrieveInfo(id);
    } else if (opts.proxynpm) {
      return this._retrieveInfoFromNpm(id);
    } else {
      return Promise.reject(new UnscopedPackageError({
        error: 'nom does not permit unscoped packages'
      }));
    }
  }

  /**
   * Create or update package info and publish tarballs to blob store
   * @param {Object} args:
   *   @param {String} name
   *   @param {String} description
   *   @param {Object} dist-tags
   *   @param {Object} versions
   *   @param {String} readme
   *   @param {Object} _attachments
   * @return {Promise} resolves when package publish is compmlete, rejects with any errors
   */
  publish(args) { //eslint-disable-line no-unused-vars
    return Promise.reject(new this.ApplicationError.NotImplemented('Not implemented yet :)'));
  }
}

module.exports = Packages;
<|endoftext|>


<commit_before>'use strict';

(function () {
  function initTreatmentDrawer() {
    $('#eventType').val('BG Check');
    $('#glucoseValue').val('').attr('placeholder', 'Value in ' + browserSettings.units);
    $('#meter').prop('checked', true);
    $('#carbsGiven').val('');
    $('#insulinGiven').val('');
    $('#preBolus').val(0);
    $('#notes').val('');
    $('#enteredBy').val(browserStorage.get('enteredBy') || '');
    $('#nowtime').prop('checked', true);
    $('#eventTimeValue').val(moment().format('HH:mm'));
    $('#eventDateValue').val(moment().format('YYYY-MM-D'));
  }

  function treatmentSubmit(event) {

    var data = {};
    data.enteredBy = $('#enteredBy').val();
    data.eventType = $('#eventType').val();
    data.glucose = $('#glucoseValue').val();
    data.glucoseType = $('#treatment-form input[name=glucoseType]:checked').val();
    data.carbs = $('#carbsGiven').val();
    data.insulin = $('#insulinGiven').val();
    data.preBolus = parseInt($('#preBolus').val());
    data.notes = $('#notes').val();
    data.units = browserSettings.units;

    var errors = [];
    if (isNaN(data.glucose)) {
      errors.push('Blood glucose must be a number');
    }

    if (isNaN(data.carbs)) {
      errors.push('Carbs must be a number');
    }

    if (isNaN(data.insulin)) {
      errors.push('Insulin must be a number');
    }

    if (errors.length > 0) {
      window.alert(errors.join('\n'));
    } else {
      if ($('#othertime').is(':checked')) {
        data.eventTime = Nightscout.utils.mergeInputTime($('#eventTimeValue').val(), $('#eventDateValue').val());
      }
      confirmPost(data);
    }

    if (event) {
      event.preventDefault();
    }
  }

  function confirmPost(data) {
    var confirmtext =
      'Please verify that the data entered is correct: ' +
      '\nEvent type: ' + data.eventType;
    confirmtext += data.glucose ? '\nBlood glucose: ' + data.glucose + '\nMethod: ' + data.glucoseType : '';
    confirmtext += data.carbs ? '\nCarbs Given: ' + data.carbs : '';
    confirmtext += data.insulin ? '\nInsulin Given: ' + data.insulin : '';
    confirmtext += data.preBolus ? '\nPre Bolus: ' + data.preBolus : '';
    confirmtext += data.notes ? '\nNotes: ' + data.notes : '';
    confirmtext += data.enteredBy ? '\nEntered By: ' + data.enteredBy : '';
    confirmtext += data.eventTime ? '\nEvent Time: ' + data.eventTime.format('LLL') : '';

    if (window.confirm(confirmtext)) {
      var dataJson = JSON.stringify(data, null, ' ');
      var xhr = new XMLHttpRequest();
      xhr.open('POST', '/api/v1/treatments/', true);
      xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
      xhr.send(dataJson);

      browserStorage.set('enteredBy', data.enteredBy);

      closeDrawer('#treatmentDrawer');
    }
  }

  $('#treatmentDrawerToggle').click(function (event) {
    toggleDrawer('#treatmentDrawer', initTreatmentDrawer);
    event.preventDefault();
  });

  $('#treatmentDrawer').find('button').click(treatmentSubmit);

  $('#eventTime input:radio').change(function (event) {
    if ($('#othertime').is(':checked')) {
      $('#eventTimeValue').focus();
    }
    event.preventDefault();
  });

  $('.eventinput').focus(function (event) {
    $('#othertime').prop('checked', true);
    var moment = Nightscout.utils.mergeInputTime($('#eventTimeValue').val(), $('#eventDateValue').val());
    $(this).attr('oldminutes', moment.minutes());
    $(this).attr('oldhours', moment.hours());
    event.preventDefault();
  });

  $('.eventinput').change(function (event) {
    $('#othertime').prop('checked', true);
    var moment = Nightscout.utils.mergeInputTime($('#eventTimeValue').val(), $('#eventDateValue').val());
    if ($(this).attr('oldminutes') === ' 59' && moment.minutes() === 0) {
      moment.add(1, 'hours');
    }
    if ($(this).attr('oldminutes') === '0' && moment.minutes() === 59) {
      moment.add(-1, 'hours');
    }
    $('#eventTimeValue').val(moment.format('HH:mm'));
    $('#eventDateValue').val(moment.format('YYYY-MM-D'));
    $(this).attr('oldminutes', moment.minutes());
    $(this).attr('oldhours', moment.hours());
    event.preventDefault();
  });
})();<commit_msg>refactoring to lower complexity; also a little jquery optimization<commit_after>'use strict';

(function () {
  function initTreatmentDrawer() {
    $('#eventType').val('BG Check');
    $('#glucoseValue').val('').attr('placeholder', 'Value in ' + browserSettings.units);
    $('#meter').prop('checked', true);
    $('#carbsGiven').val('');
    $('#insulinGiven').val('');
    $('#preBolus').val(0);
    $('#notes').val('');
    $('#enteredBy').val(browserStorage.get('enteredBy') || '');
    $('#nowtime').prop('checked', true);
    $('#eventTimeValue').val(moment().format('HH:mm'));
    $('#eventDateValue').val(moment().format('YYYY-MM-D'));
  }

  function checkForErrors(data) {
    var errors = [];
    if (isNaN(data.glucose)) {
      errors.push('Blood glucose must be a number');
    }

    if (isNaN(data.carbs)) {
      errors.push('Carbs must be a number');
    }

    if (isNaN(data.insulin)) {
      errors.push('Insulin must be a number');
    }
    return errors;
  }

  function treatmentSubmit(event) {

    var data = {};
    data.enteredBy = $('#enteredBy').val();
    data.eventType = $('#eventType').val();
    data.glucose = $('#glucoseValue').val();
    data.glucoseType = $('#treatment-form').find('input[name=glucoseType]:checked').val();
    data.carbs = $('#carbsGiven').val();
    data.insulin = $('#insulinGiven').val();
    data.preBolus = parseInt($('#preBolus').val());
    data.notes = $('#notes').val();
    data.units = browserSettings.units;

    var errors = checkForErrors(data);

    if (errors.length > 0) {
      window.alert(errors.join('\n'));
    } else {
      if ($('#othertime').is(':checked')) {
        data.eventTime = Nightscout.utils.mergeInputTime($('#eventTimeValue').val(), $('#eventDateValue').val());
      }
      confirmPost(data);
    }

    if (event) {
      event.preventDefault();
    }
  }

  function confirmPost(data) {
    var confirmtext =
      'Please verify that the data entered is correct: ' +
      '\nEvent type: ' + data.eventType;
    confirmtext += data.glucose ? '\nBlood glucose: ' + data.glucose + '\nMethod: ' + data.glucoseType : '';
    confirmtext += data.carbs ? '\nCarbs Given: ' + data.carbs : '';
    confirmtext += data.insulin ? '\nInsulin Given: ' + data.insulin : '';
    confirmtext += data.preBolus ? '\nPre Bolus: ' + data.preBolus : '';
    confirmtext += data.notes ? '\nNotes: ' + data.notes : '';
    confirmtext += data.enteredBy ? '\nEntered By: ' + data.enteredBy : '';
    confirmtext += data.eventTime ? '\nEvent Time: ' + data.eventTime.format('LLL') : '';

    if (window.confirm(confirmtext)) {
      var dataJson = JSON.stringify(data, null, ' ');
      var xhr = new XMLHttpRequest();
      xhr.open('POST', '/api/v1/treatments/', true);
      xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
      xhr.send(dataJson);

      browserStorage.set('enteredBy', data.enteredBy);

      closeDrawer('#treatmentDrawer');
    }
  }

  $('#treatmentDrawerToggle').click(function (event) {
    toggleDrawer('#treatmentDrawer', initTreatmentDrawer);
    event.preventDefault();
  });

  $('#treatmentDrawer').find('button').click(treatmentSubmit);

  $('#eventTime input:radio').change(function (event) {
    if ($('#othertime').is(':checked')) {
      $('#eventTimeValue').focus();
    }
    event.preventDefault();
  });

  $('.eventinput').focus(function (event) {
    $('#othertime').prop('checked', true);
    var moment = Nightscout.utils.mergeInputTime($('#eventTimeValue').val(), $('#eventDateValue').val());
    $(this).attr('oldminutes', moment.minutes());
    $(this).attr('oldhours', moment.hours());
    event.preventDefault();
  });

  $('.eventinput').change(function (event) {
    $('#othertime').prop('checked', true);
    var moment = Nightscout.utils.mergeInputTime($('#eventTimeValue').val(), $('#eventDateValue').val());
    if ($(this).attr('oldminutes') === ' 59' && moment.minutes() === 0) {
      moment.add(1, 'hours');
    }
    if ($(this).attr('oldminutes') === '0' && moment.minutes() === 59) {
      moment.add(-1, 'hours');
    }
    $('#eventTimeValue').val(moment.format('HH:mm'));
    $('#eventDateValue').val(moment.format('YYYY-MM-D'));
    $(this).attr('oldminutes', moment.minutes());
    $(this).attr('oldhours', moment.hours());
    event.preventDefault();
  });
})();<|endoftext|>


<commit_before>import i18next from 'i18next';
import Backend from 'i18next-chained-backend';
import LocalStorageBackend from 'i18next-localstorage-backend'; // primary use cache
import Fetch from 'i18next-fetch-backend'; // fallback xhr load
import pkg from '../../package.json';

const userLanguage = document.querySelector('html').getAttribute('lang');

// mock method. used until language keys are loaded. (not perfect, but at least it works for now)
window.$t = key => key;

i18next
	.use(Backend)
	.init({
		lng: userLanguage,
		fallbackLng: ['de', 'en'].filter(lng => lng !== userLanguage),
		backend: {
			backends: [
				LocalStorageBackend, // primary
				Fetch, // fallback
			],
			backendOptions: [
				{
					prefix: 'i18next_res_',
					defaultVersion: `v${pkg.version}`, // forces a language file reload on version change
				},
				{
					loadPath: '/locales/{{lng}}.json',
				},
			],
		},
	})
	.then(() => {
		window.$t = (...args) => i18next.t(...args);
	});
<commit_msg>fixed bug that i18n sometimes loads too slow on browsers by making in synched<commit_after>import i18next from 'i18next';
import Backend from 'i18next-chained-backend';
import LocalStorageBackend from 'i18next-localstorage-backend'; // primary use cache
import Fetch from 'i18next-fetch-backend'; // fallback xhr load
import pkg from '../../package.json';

const userLanguage = document.querySelector('html').getAttribute('lang');

// mock method. used until language keys are loaded. (not perfect, but at least it works for now)
window.$t = (key) => key;

i18next
	.use(Backend)
	.init({
		initImmediate: false,
		lng: userLanguage,
		fallbackLng: ['de', 'en'].filter((lng) => lng !== userLanguage),
		backend: {
			backends: [
				LocalStorageBackend, // primary
				Fetch, // fallback
			],
			backendOptions: [
				{
					prefix: 'i18next_res_',
					defaultVersion: `v${pkg.version}`, // forces a language file reload on version change
				},
				{
					loadPath: '/locales/{{lng}}.json',
				},
			],
		},
	})
	.then(() => {
		window.$t = (...args) => i18next.t(...args);
	});
<|endoftext|>


<commit_before>let Controller = require('./controller')
let slaves = require('../Models/Slaves')
let rp = require('request-promise')
let AlgoController = class AlgoController {

  constructor (req, res, next) {
    this.req = req
    this.res = res
    this.next = next
    this.controller = new Controller(req, res, next)
  }

  upload () {
    // eval(JSON.parse(this.req.body.algo))
    let slave = slaves.available()[0]
    console.log(slave.port)
    if (slave !== undefined) {
      var options = {
        method: 'POST',
        body: {
          algo: this.req.body.algo
        },
        uri: 'http://' + slave.ip + ':' + slave.port + '/launchAlgo',
        json: true // Automatically stringifies the body to JSON
      }
      rp(options).then(function (parsedBody) {
        console.log(parsedBody)
      }).catch(function (err) {
        if (err) {
          console.log(err)
        }
      })
    }
  }
}

module.exports = AlgoController
<commit_msg>Stockage de l'algo dans le module d'algo<commit_after>let Controller = require('./controller')
let slaves = require('../Models/Slaves')
let algo = require('../Models/Algo')
let rp = require('request-promise')
let AlgoController = class AlgoController {

  constructor (req, res, next) {
    this.req = req
    this.res = res
    this.next = next
    this.controller = new Controller(req, res, next)
  }

  upload () {
    // eval(JSON.parse(this.req.body.algo))
    algo.add(this.req.body.algo)
    console.log(algo.get())
  }

  launch () {
    let slave = slaves.available()[0]
    console.log(slave.port)
    if (slave !== undefined) {
      var options = {
        method: 'POST',
        body: {
          algo: this.req.body.algo
        },
        uri: 'http://' + slave.ip + ':' + slave.port + '/launchAlgo',
        json: true // Automatically stringifies the body to JSON
      }
      rp(options).then(function (parsedBody) {
        console.log(parsedBody)
      }).catch(function (err) {
        if (err) {
          console.log(err)
        }
      })
    }
  }
}

module.exports = AlgoController
<|endoftext|>


<commit_before>"use strict"

const math = require("mathjs")
const sigmoid = require("./sigmoid")
const deriv = require("./deriv")
const multiplyElements = require("./multiply-elements")

// must be vertical matrix
function getAveError(m1) {
    let sum = 0
    m1 = math.transpose(m1)
    let len = (m1.size())[1]

    for (let i = 0; i < len; i++) {
        sum += math.abs(m1.subset(math.index(0,i)))
    }
    return math.abs(sum / len)
}
// TODO: make a function that sets x and y

// Input Data
function train(inputData, inputResults) {
    const x = math.matrix(inputData)
    const y = math.transpose(math.matrix([inputResults]))

    const layer0 = x
    let layer1
    let layer1_error
    let layer1_delta
    let layer2
    let layer2_error
    let layer2_delta
    let hiddenLayerSize
    let error
    let minError = 100
    let synapse0
    let synapse1
    let minSynapse0
    let minSynapse1

    // Gradient descent and dropout optimization variables
    const hlSizes = [(x.size())[1], (x.size())[1] - 1, (x.size())[1] + 1]
    const alphas = [0.1, 1, 10]
    const dropout_percent = 0.2

    for (let alphaIndex = 0; alphaIndex < 3; alphaIndex++) {

        // Iterate over 3 hidden layer sizes to get the best one
        for (let hlSizeIndex = 0; hlSizeIndex < 3; hlSizeIndex++) {

            // Weights
            hiddenLayerSize = hlSizes[hlSizeIndex]
            synapse0 = math.random([(x.size())[1], hiddenLayerSize], -1, 1)
            synapse1 = math.random([hiddenLayerSize, 1], -1, 1)

            for (let i = 0; i < 40000; i++) {
                // forward propagation
                layer1 = math.multiply(layer0, synapse0).map(sigmoid)
                // dropout
                layer1.forEach(function(index) {
                let rand = math.random()
                if(rand < dropout_percent)
                    layer1[index] = 0
                layer1[index] *= 1.0/(1-dropout_percent)
                })
                layer2 = math.multiply(layer1, synapse1).map(sigmoid)
                // compare estimate with actual output
                layer2_error = math.subtract(y, layer2)
                // use slope of sigmoid to update values
                layer2_delta = multiplyElements(layer2_error, layer2.map(deriv))
                // distribute error over synapse 1
                layer1_error = math.multiply(layer2_delta, math.transpose(synapse1))
                // use slope of sigmoid to update values
                layer1_delta = multiplyElements(layer1_error, layer1.map(deriv))
                // compare estimate with actual output
                // update weights
                synapse0 = math.add(synapse0, math.multiply(math.transpose(layer0), layer1_delta))
                synapse1 = math.add(synapse1, math.multiply(math.transpose(layer1), layer2_delta))
            }
            let currentError = getAveError(layer2_error)
            if (currentError < minError) {
                minError = currentError
                minSynapse1 = synapse1
                minSynapse0 = synapse0
            }
        }
    }
    return {
        synapse0: minSynapse0,
        synapse1: minSynapse1
    }
}

function get(input, w0, w1) {
    let synapse0 = math.matrix(w0)
    let synapse1 = math.matrix(w1)
    let x = math.matrix(input)
    let testl1 = math.multiply(x, synapse0).map(sigmoid)
    return math.multiply(testl1, synapse1).map(sigmoid)
}

// // Test Train
// let results = (train([[0, 0, 1],
//                  [0, 1, 1],
//                  [1, 0, 1],
//                  [1, 1, 1]], [0, 0, 1, 1]))
// console.log(get([[0, 1, 0]], results.synapse0, results.synapse1))

module.exports = {train, get}
<commit_msg>indent better<commit_after>"use strict"

const math = require("mathjs")
const sigmoid = require("./sigmoid")
const deriv = require("./deriv")
const multiplyElements = require("./multiply-elements")

// must be vertical matrix
function getAveError(m1) {
    let sum = 0
    m1 = math.transpose(m1)
    let len = (m1.size())[1]

    for (let i = 0; i < len; i++) {
        sum += math.abs(m1.subset(math.index(0,i)))
    }
    return math.abs(sum / len)
}
// TODO: make a function that sets x and y

// Input Data
function train(inputData, inputResults) {
    const x = math.matrix(inputData)
    const y = math.transpose(math.matrix([inputResults]))

    const layer0 = x
    let layer1
    let layer1_error
    let layer1_delta
    let layer2
    let layer2_error
    let layer2_delta
    let hiddenLayerSize
    let error
    let minError = 100
    let synapse0
    let synapse1
    let minSynapse0
    let minSynapse1

    // Gradient descent and dropout optimization variables
    const hlSizes = [(x.size())[1], (x.size())[1] - 1, (x.size())[1] + 1]
    const alphas = [0.1, 1, 10]
    const dropout_percent = 0.2

    for (let alphaIndex = 0; alphaIndex < 3; alphaIndex++) {

        // Iterate over 3 hidden layer sizes to get the best one
        for (let hlSizeIndex = 0; hlSizeIndex < 3; hlSizeIndex++) {

            // Weights
            hiddenLayerSize = hlSizes[hlSizeIndex]
            synapse0 = math.random([(x.size())[1], hiddenLayerSize], -1, 1)
            synapse1 = math.random([hiddenLayerSize, 1], -1, 1)

            for (let i = 0; i < 40000; i++) {
                // forward propagation
                layer1 = math.multiply(layer0, synapse0).map(sigmoid)
                // dropout
                layer1.forEach(function(index) {
                    let rand = math.random()
                    if (rand < dropout_percent) {
                        layer1[index] = 0
                        layer1[index] *= 1.0/(1-dropout_percent)
                    }
                })
                layer2 = math.multiply(layer1, synapse1).map(sigmoid)
                // compare estimate with actual output
                layer2_error = math.subtract(y, layer2)
                // use slope of sigmoid to update values
                layer2_delta = multiplyElements(layer2_error, layer2.map(deriv))
                // distribute error over synapse 1
                layer1_error = math.multiply(layer2_delta, math.transpose(synapse1))
                // use slope of sigmoid to update values
                layer1_delta = multiplyElements(layer1_error, layer1.map(deriv))
                // compare estimate with actual output
                // update weights
                synapse0 = math.add(synapse0, math.multiply(math.transpose(layer0), layer1_delta))
                synapse1 = math.add(synapse1, math.multiply(math.transpose(layer1), layer2_delta))
            }
            let currentError = getAveError(layer2_error)
            if (currentError < minError) {
                minError = currentError
                minSynapse1 = synapse1
                minSynapse0 = synapse0
            }
        }
    }
    return {
        synapse0: minSynapse0,
        synapse1: minSynapse1
    }
}

function get(input, w0, w1) {
    let synapse0 = math.matrix(w0)
    let synapse1 = math.matrix(w1)
    let x = math.matrix(input)
    let testl1 = math.multiply(x, synapse0).map(sigmoid)
    return math.multiply(testl1, synapse1).map(sigmoid)
}

// // Test Train
// let results = (train([[0, 0, 1],
//                  [0, 1, 1],
//                  [1, 0, 1],
//                  [1, 1, 1]], [0, 0, 1, 1]))
// console.log(get([[0, 1, 0]], results.synapse0, results.synapse1))

module.exports = {train, get}
<|endoftext|>


<commit_before>/** File: candy.js
 * Candy - Chats are not dead yet.
 *
 * Authors:
 *   - Troy McCabe <troy.mccabe@geeksquad.com>
 *
 * Copyright:
 *   (c) 2012 Geek Squad. All rights reserved.
 */
var CandyShop = (function(self) { return self; }(CandyShop || {}));

/** Class: CandyShop.StickySubject
 * This plugin makes it so the room subject is always visible
 */
CandyShop.StickySubject = (function(self, Candy, $) {
    /** Function: init
     * Initialize the StickySubject plugin
     */
    self.init = function() {
        // Listen for a subject change in the room
        $(Candy).on('candy:view.room.after-subject-change', function(e, data) {
            // get the current message pane and create the text
            var messagePane = $(Candy.View.Pane.Room.getPane(Candy.View.getCurrent().roomJid)),
                subjectText = $.i18n._('roomSubject') + ' ' + Candy.Util.Parser.linkify(data.subject);

            // if we don't have the subject container yet, add it
            // else just update the content
            if ($('.candy-subject-container').length == 0) {
                messagePane.prepend('
' + subjectText + '
');
                messagePane.find('.message-pane-wrapper').addClass('candy-has-subject');
            } else {
                messagePane.find('.candy-subject-container').html(subjectText);
            }
        });
    };

    return self;
}(CandyShop.StickySubject || {}, Candy, jQuery));<commit_msg>Fixes #69<commit_after>/** File: candy.js
 * Candy - Chats are not dead yet.
 *
 * Authors:
 *   - Troy McCabe <troy.mccabe@geeksquad.com>
 *
 * Copyright:
 *   (c) 2012 Geek Squad. All rights reserved.
 */
var CandyShop = (function(self) { return self; }(CandyShop || {}));

/** Class: CandyShop.StickySubject
 * This plugin makes it so the room subject is always visible
 */
CandyShop.StickySubject = (function(self, Candy, $) {
    /** Function: init
     * Initialize the StickySubject plugin
     */
    self.init = function() {
        // Listen for a subject change in the room
        $(Candy).on('candy:view.room.after-subject-change', function(e, data) {
            // get the current message pane and create the text
            var $messagePane = $(Candy.View.Pane.Room.getPane(Candy.View.getCurrent().roomJid)),
                subjectText = $.i18n._('roomSubject') + ' ' + Candy.Util.Parser.linkify(data.subject);

            // if we don't have the subject container yet, add it
            // else just update the content
            if ($('.candy-subject-container:visible').length == 0) {
                $messagePane.prepend('
' + subjectText + '
');
                $messagePane.find('.message-pane-wrapper').addClass('candy-has-subject');
            } else {
                $messagePane.find('.candy-subject-container').html(subjectText);
            }
        });
    };

    return self;
}(CandyShop.StickySubject || {}, Candy, jQuery));<|endoftext|>


<commit_before>/**
 * @module ol/geom/Geometry
 */
import BaseObject from '../Object.js';
import Units from '../proj/Units.js';
import {abstract} from '../util.js';
import {
  compose as composeTransform,
  create as createTransform,
} from '../transform.js';
import {
  containsExtent,
  createEmpty,
  getHeight,
  returnOrUpdate,
} from '../extent.js';
import {get as getProjection, getTransform} from '../proj.js';
import {memoizeOne} from '../functions.js';
import {transform2D} from './flat/transform.js';

/**
 * @type {import("../transform.js").Transform}
 */
const tmpTransform = createTransform();

/**
 * @classdesc
 * Abstract base class; normally only used for creating subclasses and not
 * instantiated in apps.
 * Base class for vector geometries.
 *
 * To get notified of changes to the geometry, register a listener for the
 * generic `change` event on your geometry instance.
 *
 * @abstract
 * @api
 */
class Geometry extends BaseObject {
  constructor() {
    super();

    /**
     * @private
     * @type {import("../extent.js").Extent}
     */
    this.extent_ = createEmpty();

    /**
     * @private
     * @type {number}
     */
    this.extentRevision_ = -1;

    /**
     * @protected
     * @type {number}
     */
    this.simplifiedGeometryMaxMinSquaredTolerance = 0;

    /**
     * @protected
     * @type {number}
     */
    this.simplifiedGeometryRevision = 0;

    /**
     * Get a transformed and simplified version of the geometry.
     * @abstract
     * @param {number} revision The geometry revision.
     * @param {number} squaredTolerance Squared tolerance.
     * @param {import("../proj.js").TransformFunction} [opt_transform] Optional transform function.
     * @return {Geometry} Simplified geometry.
     */
    this.simplifyTransformedInternal = memoizeOne(function (
      revision,
      squaredTolerance,
      opt_transform
    ) {
      if (!opt_transform) {
        return this.getSimplifiedGeometry(squaredTolerance);
      }
      const clone = this.clone();
      clone.applyTransform(opt_transform);
      return clone.getSimplifiedGeometry(squaredTolerance);
    });
  }

  /**
   * Get a transformed and simplified version of the geometry.
   * @abstract
   * @param {number} squaredTolerance Squared tolerance.
   * @param {import("../proj.js").TransformFunction} [opt_transform] Optional transform function.
   * @return {Geometry} Simplified geometry.
   */
  simplifyTransformed(squaredTolerance, opt_transform) {
    return this.simplifyTransformedInternal(
      this.getRevision(),
      squaredTolerance,
      opt_transform
    );
  }

  /**
   * Make a complete copy of the geometry.
   * @abstract
   * @return {!Geometry} Clone.
   */
  clone() {
    return abstract();
  }

  /**
   * @abstract
   * @param {number} x X.
   * @param {number} y Y.
   * @param {import("../coordinate.js").Coordinate} closestPoint Closest point.
   * @param {number} minSquaredDistance Minimum squared distance.
   * @return {number} Minimum squared distance.
   */
  closestPointXY(x, y, closestPoint, minSquaredDistance) {
    return abstract();
  }

  /**
   * @param {number} x X.
   * @param {number} y Y.
   * @return {boolean} Contains (x, y).
   */
  containsXY(x, y) {
    const coord = this.getClosestPoint([x, y]);
    return coord[0] === x && coord[1] === y;
  }

  /**
   * Return the closest point of the geometry to the passed point as
   * {@link module:ol/coordinate~Coordinate coordinate}.
   * @param {import("../coordinate.js").Coordinate} point Point.
   * @param {import("../coordinate.js").Coordinate=} opt_closestPoint Closest point.
   * @return {import("../coordinate.js").Coordinate} Closest point.
   * @api
   */
  getClosestPoint(point, opt_closestPoint) {
    const closestPoint = opt_closestPoint ? opt_closestPoint : [NaN, NaN];
    this.closestPointXY(point[0], point[1], closestPoint, Infinity);
    return closestPoint;
  }

  /**
   * Returns true if this geometry includes the specified coordinate. If the
   * coordinate is on the boundary of the geometry, returns false.
   * @param {import("../coordinate.js").Coordinate} coordinate Coordinate.
   * @return {boolean} Contains coordinate.
   * @api
   */
  intersectsCoordinate(coordinate) {
    return this.containsXY(coordinate[0], coordinate[1]);
  }

  /**
   * @abstract
   * @param {import("../extent.js").Extent} extent Extent.
   * @protected
   * @return {import("../extent.js").Extent} extent Extent.
   */
  computeExtent(extent) {
    return abstract();
  }

  /**
   * Get the extent of the geometry.
   * @param {import("../extent.js").Extent=} opt_extent Extent.
   * @return {import("../extent.js").Extent} extent Extent.
   * @api
   */
  getExtent(opt_extent) {
    if (this.extentRevision_ != this.getRevision()) {
      this.extent_ = this.computeExtent(this.extent_);
      if (
        !containsExtent([-Infinity, -Infinity, Infinity, Infinity], this.extent_)
      ) {
        this.extent_ = createEmpty();
      }
      this.extentRevision_ = this.getRevision();
    }
    return returnOrUpdate(this.extent_, opt_extent);
  }

  /**
   * Rotate the geometry around a given coordinate. This modifies the geometry
   * coordinates in place.
   * @abstract
   * @param {number} angle Rotation angle in radians.
   * @param {import("../coordinate.js").Coordinate} anchor The rotation center.
   * @api
   */
  rotate(angle, anchor) {
    abstract();
  }

  /**
   * Scale the geometry (with an optional origin).  This modifies the geometry
   * coordinates in place.
   * @abstract
   * @param {number} sx The scaling factor in the x-direction.
   * @param {number=} opt_sy The scaling factor in the y-direction (defaults to sx).
   * @param {import("../coordinate.js").Coordinate=} opt_anchor The scale origin (defaults to the center
   *     of the geometry extent).
   * @api
   */
  scale(sx, opt_sy, opt_anchor) {
    abstract();
  }

  /**
   * Create a simplified version of this geometry.  For linestrings, this uses
   * the [Douglas Peucker](https://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm)
   * algorithm.  For polygons, a quantization-based
   * simplification is used to preserve topology.
   * @param {number} tolerance The tolerance distance for simplification.
   * @return {Geometry} A new, simplified version of the original geometry.
   * @api
   */
  simplify(tolerance) {
    return this.getSimplifiedGeometry(tolerance * tolerance);
  }

  /**
   * Create a simplified version of this geometry using the Douglas Peucker
   * algorithm.
   * See https://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm.
   * @abstract
   * @param {number} squaredTolerance Squared tolerance.
   * @return {Geometry} Simplified geometry.
   */
  getSimplifiedGeometry(squaredTolerance) {
    return abstract();
  }

  /**
   * Get the type of this geometry.
   * @abstract
   * @return {import("./GeometryType.js").default} Geometry type.
   */
  getType() {
    return abstract();
  }

  /**
   * Apply a transform function to the coordinates of the geometry.
   * The geometry is modified in place.
   * If you do not want the geometry modified in place, first `clone()` it and
   * then use this function on the clone.
   * @abstract
   * @param {import("../proj.js").TransformFunction} transformFn Transform function.
   * Called with a flat array of geometry coordinates.
   */
  applyTransform(transformFn) {
    abstract();
  }

  /**
   * Test if the geometry and the passed extent intersect.
   * @abstract
   * @param {import("../extent.js").Extent} extent Extent.
   * @return {boolean} `true` if the geometry and the extent intersect.
   */
  intersectsExtent(extent) {
    return abstract();
  }

  /**
   * Translate the geometry.  This modifies the geometry coordinates in place.  If
   * instead you want a new geometry, first `clone()` this geometry.
   * @abstract
   * @param {number} deltaX Delta X.
   * @param {number} deltaY Delta Y.
   * @api
   */
  translate(deltaX, deltaY) {
    abstract();
  }

  /**
   * Transform each coordinate of the geometry from one coordinate reference
   * system to another. The geometry is modified in place.
   * For example, a line will be transformed to a line and a circle to a circle.
   * If you do not want the geometry modified in place, first `clone()` it and
   * then use this function on the clone.
   *
   * @param {import("../proj.js").ProjectionLike} source The current projection.  Can be a
   *     string identifier or a {@link module:ol/proj/Projection~Projection} object.
   * @param {import("../proj.js").ProjectionLike} destination The desired projection.  Can be a
   *     string identifier or a {@link module:ol/proj/Projection~Projection} object.
   * @return {Geometry} This geometry.  Note that original geometry is
   *     modified in place.
   * @api
   */
  transform(source, destination) {
    /** @type {import("../proj/Projection.js").default} */
    const sourceProj = getProjection(source);
    const transformFn =
      sourceProj.getUnits() == Units.TILE_PIXELS
        ? function (inCoordinates, outCoordinates, stride) {
            const pixelExtent = sourceProj.getExtent();
            const projectedExtent = sourceProj.getWorldExtent();
            const scale = getHeight(projectedExtent) / getHeight(pixelExtent);
            composeTransform(
              tmpTransform,
              projectedExtent[0],
              projectedExtent[3],
              scale,
              -scale,
              0,
              0,
              0
            );
            transform2D(
              inCoordinates,
              0,
              inCoordinates.length,
              stride,
              tmpTransform,
              outCoordinates
            );
            return getTransform(sourceProj, destination)(
              inCoordinates,
              outCoordinates,
              stride
            );
          }
        : getTransform(sourceProj, destination);
    this.applyTransform(transformFn);
    return this;
  }
}

export default Geometry;
<commit_msg>fix pettier<commit_after>/**
 * @module ol/geom/Geometry
 */
import BaseObject from '../Object.js';
import Units from '../proj/Units.js';
import {abstract} from '../util.js';
import {
  compose as composeTransform,
  create as createTransform,
} from '../transform.js';
import {
  containsExtent,
  createEmpty,
  getHeight,
  returnOrUpdate,
} from '../extent.js';
import {get as getProjection, getTransform} from '../proj.js';
import {memoizeOne} from '../functions.js';
import {transform2D} from './flat/transform.js';

/**
 * @type {import("../transform.js").Transform}
 */
const tmpTransform = createTransform();

/**
 * @classdesc
 * Abstract base class; normally only used for creating subclasses and not
 * instantiated in apps.
 * Base class for vector geometries.
 *
 * To get notified of changes to the geometry, register a listener for the
 * generic `change` event on your geometry instance.
 *
 * @abstract
 * @api
 */
class Geometry extends BaseObject {
  constructor() {
    super();

    /**
     * @private
     * @type {import("../extent.js").Extent}
     */
    this.extent_ = createEmpty();

    /**
     * @private
     * @type {number}
     */
    this.extentRevision_ = -1;

    /**
     * @protected
     * @type {number}
     */
    this.simplifiedGeometryMaxMinSquaredTolerance = 0;

    /**
     * @protected
     * @type {number}
     */
    this.simplifiedGeometryRevision = 0;

    /**
     * Get a transformed and simplified version of the geometry.
     * @abstract
     * @param {number} revision The geometry revision.
     * @param {number} squaredTolerance Squared tolerance.
     * @param {import("../proj.js").TransformFunction} [opt_transform] Optional transform function.
     * @return {Geometry} Simplified geometry.
     */
    this.simplifyTransformedInternal = memoizeOne(function (
      revision,
      squaredTolerance,
      opt_transform
    ) {
      if (!opt_transform) {
        return this.getSimplifiedGeometry(squaredTolerance);
      }
      const clone = this.clone();
      clone.applyTransform(opt_transform);
      return clone.getSimplifiedGeometry(squaredTolerance);
    });
  }

  /**
   * Get a transformed and simplified version of the geometry.
   * @abstract
   * @param {number} squaredTolerance Squared tolerance.
   * @param {import("../proj.js").TransformFunction} [opt_transform] Optional transform function.
   * @return {Geometry} Simplified geometry.
   */
  simplifyTransformed(squaredTolerance, opt_transform) {
    return this.simplifyTransformedInternal(
      this.getRevision(),
      squaredTolerance,
      opt_transform
    );
  }

  /**
   * Make a complete copy of the geometry.
   * @abstract
   * @return {!Geometry} Clone.
   */
  clone() {
    return abstract();
  }

  /**
   * @abstract
   * @param {number} x X.
   * @param {number} y Y.
   * @param {import("../coordinate.js").Coordinate} closestPoint Closest point.
   * @param {number} minSquaredDistance Minimum squared distance.
   * @return {number} Minimum squared distance.
   */
  closestPointXY(x, y, closestPoint, minSquaredDistance) {
    return abstract();
  }

  /**
   * @param {number} x X.
   * @param {number} y Y.
   * @return {boolean} Contains (x, y).
   */
  containsXY(x, y) {
    const coord = this.getClosestPoint([x, y]);
    return coord[0] === x && coord[1] === y;
  }

  /**
   * Return the closest point of the geometry to the passed point as
   * {@link module:ol/coordinate~Coordinate coordinate}.
   * @param {import("../coordinate.js").Coordinate} point Point.
   * @param {import("../coordinate.js").Coordinate=} opt_closestPoint Closest point.
   * @return {import("../coordinate.js").Coordinate} Closest point.
   * @api
   */
  getClosestPoint(point, opt_closestPoint) {
    const closestPoint = opt_closestPoint ? opt_closestPoint : [NaN, NaN];
    this.closestPointXY(point[0], point[1], closestPoint, Infinity);
    return closestPoint;
  }

  /**
   * Returns true if this geometry includes the specified coordinate. If the
   * coordinate is on the boundary of the geometry, returns false.
   * @param {import("../coordinate.js").Coordinate} coordinate Coordinate.
   * @return {boolean} Contains coordinate.
   * @api
   */
  intersectsCoordinate(coordinate) {
    return this.containsXY(coordinate[0], coordinate[1]);
  }

  /**
   * @abstract
   * @param {import("../extent.js").Extent} extent Extent.
   * @protected
   * @return {import("../extent.js").Extent} extent Extent.
   */
  computeExtent(extent) {
    return abstract();
  }

  /**
   * Get the extent of the geometry.
   * @param {import("../extent.js").Extent=} opt_extent Extent.
   * @return {import("../extent.js").Extent} extent Extent.
   * @api
   */
  getExtent(opt_extent) {
    if (this.extentRevision_ != this.getRevision()) {
      this.extent_ = this.computeExtent(this.extent_);
      if (
        !containsExtent(
          [-Infinity, -Infinity, Infinity, Infinity],
          this.extent_
        )
      ) {
        this.extent_ = createEmpty();
      }
      this.extentRevision_ = this.getRevision();
    }
    return returnOrUpdate(this.extent_, opt_extent);
  }

  /**
   * Rotate the geometry around a given coordinate. This modifies the geometry
   * coordinates in place.
   * @abstract
   * @param {number} angle Rotation angle in radians.
   * @param {import("../coordinate.js").Coordinate} anchor The rotation center.
   * @api
   */
  rotate(angle, anchor) {
    abstract();
  }

  /**
   * Scale the geometry (with an optional origin).  This modifies the geometry
   * coordinates in place.
   * @abstract
   * @param {number} sx The scaling factor in the x-direction.
   * @param {number=} opt_sy The scaling factor in the y-direction (defaults to sx).
   * @param {import("../coordinate.js").Coordinate=} opt_anchor The scale origin (defaults to the center
   *     of the geometry extent).
   * @api
   */
  scale(sx, opt_sy, opt_anchor) {
    abstract();
  }

  /**
   * Create a simplified version of this geometry.  For linestrings, this uses
   * the [Douglas Peucker](https://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm)
   * algorithm.  For polygons, a quantization-based
   * simplification is used to preserve topology.
   * @param {number} tolerance The tolerance distance for simplification.
   * @return {Geometry} A new, simplified version of the original geometry.
   * @api
   */
  simplify(tolerance) {
    return this.getSimplifiedGeometry(tolerance * tolerance);
  }

  /**
   * Create a simplified version of this geometry using the Douglas Peucker
   * algorithm.
   * See https://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm.
   * @abstract
   * @param {number} squaredTolerance Squared tolerance.
   * @return {Geometry} Simplified geometry.
   */
  getSimplifiedGeometry(squaredTolerance) {
    return abstract();
  }

  /**
   * Get the type of this geometry.
   * @abstract
   * @return {import("./GeometryType.js").default} Geometry type.
   */
  getType() {
    return abstract();
  }

  /**
   * Apply a transform function to the coordinates of the geometry.
   * The geometry is modified in place.
   * If you do not want the geometry modified in place, first `clone()` it and
   * then use this function on the clone.
   * @abstract
   * @param {import("../proj.js").TransformFunction} transformFn Transform function.
   * Called with a flat array of geometry coordinates.
   */
  applyTransform(transformFn) {
    abstract();
  }

  /**
   * Test if the geometry and the passed extent intersect.
   * @abstract
   * @param {import("../extent.js").Extent} extent Extent.
   * @return {boolean} `true` if the geometry and the extent intersect.
   */
  intersectsExtent(extent) {
    return abstract();
  }

  /**
   * Translate the geometry.  This modifies the geometry coordinates in place.  If
   * instead you want a new geometry, first `clone()` this geometry.
   * @abstract
   * @param {number} deltaX Delta X.
   * @param {number} deltaY Delta Y.
   * @api
   */
  translate(deltaX, deltaY) {
    abstract();
  }

  /**
   * Transform each coordinate of the geometry from one coordinate reference
   * system to another. The geometry is modified in place.
   * For example, a line will be transformed to a line and a circle to a circle.
   * If you do not want the geometry modified in place, first `clone()` it and
   * then use this function on the clone.
   *
   * @param {import("../proj.js").ProjectionLike} source The current projection.  Can be a
   *     string identifier or a {@link module:ol/proj/Projection~Projection} object.
   * @param {import("../proj.js").ProjectionLike} destination The desired projection.  Can be a
   *     string identifier or a {@link module:ol/proj/Projection~Projection} object.
   * @return {Geometry} This geometry.  Note that original geometry is
   *     modified in place.
   * @api
   */
  transform(source, destination) {
    /** @type {import("../proj/Projection.js").default} */
    const sourceProj = getProjection(source);
    const transformFn =
      sourceProj.getUnits() == Units.TILE_PIXELS
        ? function (inCoordinates, outCoordinates, stride) {
            const pixelExtent = sourceProj.getExtent();
            const projectedExtent = sourceProj.getWorldExtent();
            const scale = getHeight(projectedExtent) / getHeight(pixelExtent);
            composeTransform(
              tmpTransform,
              projectedExtent[0],
              projectedExtent[3],
              scale,
              -scale,
              0,
              0,
              0
            );
            transform2D(
              inCoordinates,
              0,
              inCoordinates.length,
              stride,
              tmpTransform,
              outCoordinates
            );
            return getTransform(sourceProj, destination)(
              inCoordinates,
              outCoordinates,
              stride
            );
          }
        : getTransform(sourceProj, destination);
    this.applyTransform(transformFn);
    return this;
  }
}

export default Geometry;
<|endoftext|>


<commit_before>import React, { Component, Fragment } from 'react'
import Helmet from 'react-helmet'
import { api } from 'data.json'
import { Heading, Container, LargeButton } from '@hackclub/design-system'
import LoadingAnimation from 'components/LoadingAnimation'
import Footer from 'components/Footer'
import ClubApplicationForm from 'components/apply/ClubApplicationForm'
import ApplyNav from 'components/apply/ApplyNav'
import Login from 'components/apply/Login'
import yup from 'yup'
import fetch from 'unfetch'

export default class extends Component {
  constructor(props) {
    super(props)

    this.state = {
      status: 'loading',
      formFields: undefined,
      id: undefined,
      authToken: undefined
    }
  }

  componentDidMount() {
    var id
    const params = window.location.search.slice(1).split(/&/)
    for (var i = 0; i < params.length; i++) {
      let param = params[i]
      if (param.split('=')[0] === 'id') {
        id = param.split('=')[1]
      }
    }
    const authToken = window.localStorage.getItem('authToken')
    this.setState({ authToken, id })
    const needsToAuth = authToken === null || id === null
    if (needsToAuth) {
      const status = 'needsToAuth'
      this.setState({ status })
    } else {
      fetch(`${api}/v1/new_club_applications/${id}`, {
        method: 'GET',
        headers: { Authorization: `Bearer ${authToken}` }
      })
        .then(res => {
          if (res.ok) {
            return res.json()
          } else {
            throw res
          }
        })
        .then(json => {
          this.setState({
            status: 'loaded',
            formFields: json
          })
        })
        .catch(e => {
          if (e.status === 401) {
            const status = 'needsToAuth'
            this.setState({ status })
          }
          alert(e)
        })
    }
  }

  content() {
    const { status, formFields, id, authToken } = this.state

    if (status === 'needsToAuth') {
      return <Login />
    } else if (status === 'loading') {
      return <LoadingAnimation />
    } else {
      return (
        <Fragment>
          <ApplyNav />
          <ClubApplicationForm
            params={formFields}
            id={id}
            authToken={authToken}
          />
          <Heading.h4 align="center">
            Your form is automatically saved ✨
          </Heading.h4>
          <Container align="center" my={4}>
            <LargeButton.link to="/apply">« Back</LargeButton.link>
          </Container>
          <Footer />
        </Fragment>
      )
    }
  }

  render() {
    return (
      <Fragment>
        <Helmet title="Edit Club Application – Hack Club" />
        {this.content()}
      </Fragment>
    )
  }
}
<commit_msg>Fix API endpoint in club application page<commit_after>import React, { Component, Fragment } from 'react'
import Helmet from 'react-helmet'
import { url as apiUrl } from 'api'
import { Heading, Container, LargeButton } from '@hackclub/design-system'
import LoadingAnimation from 'components/LoadingAnimation'
import Footer from 'components/Footer'
import ClubApplicationForm from 'components/apply/ClubApplicationForm'
import ApplyNav from 'components/apply/ApplyNav'
import Login from 'components/apply/Login'
import yup from 'yup'
import fetch from 'unfetch'

export default class extends Component {
  constructor(props) {
    super(props)

    this.state = {
      status: 'loading',
      formFields: undefined,
      id: undefined,
      authToken: undefined
    }
  }

  componentDidMount() {
    var id
    const params = window.location.search.slice(1).split(/&/)
    for (var i = 0; i < params.length; i++) {
      let param = params[i]
      if (param.split('=')[0] === 'id') {
        id = param.split('=')[1]
      }
    }
    const authToken = window.localStorage.getItem('authToken')
    this.setState({ authToken, id })
    const needsToAuth = authToken === null || id === null
    if (needsToAuth) {
      const status = 'needsToAuth'
      this.setState({ status })
    } else {
      fetch(`${apiUrl}/v1/new_club_applications/${id}`, {
        method: 'GET',
        headers: { Authorization: `Bearer ${authToken}` }
      })
        .then(res => {
          if (res.ok) {
            return res.json()
          } else {
            throw res
          }
        })
        .then(json => {
          this.setState({
            status: 'loaded',
            formFields: json
          })
        })
        .catch(e => {
          if (e.status === 401) {
            const status = 'needsToAuth'
            this.setState({ status })
          }
          alert(e)
        })
    }
  }

  content() {
    const { status, formFields, id, authToken } = this.state

    if (status === 'needsToAuth') {
      return <Login />
    } else if (status === 'loading') {
      return <LoadingAnimation />
    } else {
      return (
        <Fragment>
          <ApplyNav />
          <ClubApplicationForm
            params={formFields}
            id={id}
            authToken={authToken}
          />
          <Heading.h4 align="center">
            Your form is automatically saved ✨
          </Heading.h4>
          <Container align="center" my={4}>
            <LargeButton.link to="/apply">« Back</LargeButton.link>
          </Container>
          <Footer />
        </Fragment>
      )
    }
  }

  render() {
    return (
      <Fragment>
        <Helmet title="Edit Club Application – Hack Club" />
        {this.content()}
      </Fragment>
    )
  }
}
<|endoftext|>


<commit_before>var express = require("express");
var app = express();

const Unmarshaller02 = require("cloudevents-sdk/http/unmarshaller/v02");
var unmarshaller = new Unmarshaller02();

app.use((req, res, next) => {
    var data='';

    req.setEncoding('utf8');
    req.on('data', function(chunk) {
       data += chunk;
    });

    req.on('end', function() {
        req.body = data;
        next();
    });
});

app.post('/', function (req, res) {
  console.log(req.headers);
  console.log(req.body);

  try {
    var event = unmarshaller.unmarshall(req.body, req.headers);

    // pretty print
    console.log("Accepted event:");
    console.log(JSON.stringify(event.format(), null, 2));

    res.status(201)
          .send("Event Accepted");
  }catch(e) {
    console.error(e);

    res.status(400)
          .header("Content-Type", "application/json")
          .send(JSON.stringify(e));
  }
});

app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
});
<commit_msg>Double quotes<commit_after>var express = require("express");
var app = express();

const Unmarshaller02 = require("cloudevents-sdk/http/unmarshaller/v02");
var unmarshaller = new Unmarshaller02();

app.use((req, res, next) => {
    var data='';

    req.setEncoding('utf8');
    req.on('data', function(chunk) {
       data += chunk;
    });

    req.on('end', function() {
        req.body = data;
        next();
    });
});

app.post('/', function (req, res) {
  console.log(req.headers);
  console.log(req.body);

  try {
    var event = unmarshaller.unmarshall(req.body, req.headers);

    // pretty print
    console.log("Accepted event:");
    console.log(JSON.stringify(event.format(), null, 2));

    res.status(201)
          .send("Event Accepted");
  }catch(e) {
    console.error(e);

    res.status(400)
          .header("Content-Type", "application/json")
          .send(JSON.stringify(e));
  }
});

app.listen(3000, function () {
  console.log("Example app listening on port 3000!");
});
<|endoftext|>


<commit_before>'use strict';

var zog = 'zog';

var cmd = {};
var opt = {};

cmd.hello = function (callback, args) {
  console.log (zog + ' tells "Hello, ' + args.join (' ') + '"');
  callback ();
};

cmd.wizard = function (callback) {
  var wizard = [{
    /* Inquirer definition... */
    type: 'input',
    name: 'zog',
    message: 'tell ' + zog
  }];

  callback (wizard, function (answers) {
    /* stuff on answers */
    if (answers.zog === zog) {
      console.log (zog + ' ' + zog);
    } else {
      console.log ('lokthar?');
    }

    /*
    * You can return false if you must provide several wizard with only
    * one call to this command handler.
    * You can call callback () without argument in order to return to the
    * prompt instead of returning true.
    */
    return true;
  });
};

opt.foobar = function (callback, args) {
  if (args) {
    zog = args[0];
  } else {
    zog = 'lokthar';
  }
  callback ();
};

exports.register = function (callback) {
  var commands = [{
    name: 'hello',
    desc: 'print Hello, John',
    options: {
      wizard: false,
      params: {
        required: 'name',
        optional: 'etc...'
      }
    },
    handler: cmd.hello
  }, {
    name: 'wizard',
    desc: 'begins a wizard',
    options: {
      wizard: true
    },
    handler: cmd.wizard
  }];

  var options = [{
    name: '-f, --foobar',
    desc: 'zog is foobar',
    options: {
      params: {
        required: 'who'
      }
    },
    handler: opt.foobar
  }];

  callback (null, commands, options);
};

exports.unregister = function (callback) {
  /* internal stuff */
  callback ();
};
<commit_msg>Fixes the example accordingly to the new API.<commit_after>'use strict';

var zog = 'zog';

var cmd = {};
var opt = {};

cmd.hello = function (callback, args) {
  console.log (zog + ' tells "Hello, ' + args.join (' ') + '"');
  callback ();
};

cmd.wizard = function (callback) {
  var wizard = [{
    /* Inquirer definition... */
    type: 'input',
    name: 'zog',
    message: 'tell ' + zog
  }];

  callback (wizard, function (answers) {
    /* stuff on answers */
    if (answers.zog === zog) {
      console.log (zog + ' ' + zog);
    } else {
      console.log ('lokthar?');
    }

    /*
    * You can return false if you must provide several wizard with only
    * one call to this command handler.
    * You can call callback () without argument in order to return to the
    * prompt instead of returning true.
    */
    return true;
  });
};

opt.foobar = function (callback, args) {
  if (args) {
    zog = args[0];
  } else {
    zog = 'lokthar';
  }
  callback ();
};

exports.register = function (extension, callback) {
  extension
    .command ('hello', 'print Hello, John', {
      wizard: false,
      params: {
        required: 'name',
        optional: 'etc...'
      }
    }, cmd.hello)
    .command ('wizard', 'begins a wizard', {
      wizard: true
    }, cmd.wizard)
    .option ('-f, --foobar', 'zog is foobar', {
      params: {
        required: 'who'
      }
    }, opt.foobar);

  callback ();
};

exports.unregister = function (callback) {
  /* internal stuff */
  callback ();
};
<|endoftext|>


<commit_before>var game = new Game();
var player1 = new Paddle(game, { x: 10, y: game.paper.centerY - 50 });
var player2 = new Paddle(game, { x: game.paper.width - 20, y: game.paper.centerY - 50 });
var ball = new Ball(game);
var score = new Score(game);

$("#canvas").css({"background-color": "#000"});

game.addState('initial', function() {
  this.paper.text("Press 'space' to start", this.paper.centerX, this.paper.centerY, {
    color: 'white',
    font: '40px sans-serif',
    align: 'center'
  });

  if (isKeyPressed('space')) {
    game.changeState('ingame');
  }
});

game.addState('ingame', function() {
  if (ball.isFired()) {
    if (isKeyPressed('up')) {
      player2.moveUp();
    }

    if (isKeyPressed('down')) {
      player2.moveDown();
    }

    if (isKeyPressed('w')) {
      player1.moveUp();
    }

    if (isKeyPressed('s')) {
      player1.moveDown();
    }

    ball.checkCollisionWithPlayers(player1, player2);
  }

  if (isKeyPressed('r')) {
    game.changeState('ingame');
  }

  if (!ball.isFired() && isKeyPressed('space')) {
    ball.fire();
  }

  // Background
  game.paper.draw(function(c) {
    c.globalAlpha = 0.5;

    game.paper.path(function( path ) {
      path.moveTo(game.paper.centerX, -1);
      path.lineTo(game.paper.centerX, game.paper.height);
    });

    c.strokeStyle = "white";
    c.stroke();
  });

  player1.draw();
  player2.draw();
  ball.draw();
  score.draw();
}, {
  before: function() {
    player1.reset();
    player2.reset();
    ball.reset();
    score.reset();
  }
});

game.start();
<commit_msg>removed background color manipulation<commit_after>var game = new Game();
var player1 = new Paddle(game, { x: 10, y: game.paper.centerY - 50 });
var player2 = new Paddle(game, { x: game.paper.width - 20, y: game.paper.centerY - 50 });
var ball = new Ball(game);
var score = new Score(game);

game.addState('initial', function() {
  this.paper.text("Press 'space' to start", this.paper.centerX, this.paper.centerY, {
    color: 'white',
    font: '40px sans-serif',
    align: 'center'
  });

  if (isKeyPressed('space')) {
    game.changeState('ingame');
  }
});

game.addState('ingame', function() {
  if (ball.isFired()) {
    if (isKeyPressed('up')) {
      player2.moveUp();
    }

    if (isKeyPressed('down')) {
      player2.moveDown();
    }

    if (isKeyPressed('w')) {
      player1.moveUp();
    }

    if (isKeyPressed('s')) {
      player1.moveDown();
    }

    ball.checkCollisionWithPlayers(player1, player2);
  }

  if (isKeyPressed('r')) {
    game.changeState('ingame');
  }

  if (!ball.isFired() && isKeyPressed('space')) {
    ball.fire();
  }

  // Background
  game.paper.draw(function(c) {
    c.globalAlpha = 0.5;

    game.paper.path(function( path ) {
      path.moveTo(game.paper.centerX, -1);
      path.lineTo(game.paper.centerX, game.paper.height);
    });

    c.strokeStyle = "white";
    c.stroke();
  });

  player1.draw();
  player2.draw();
  ball.draw();
  score.draw();
}, {
  before: function() {
    player1.reset();
    player2.reset();
    ball.reset();
    score.reset();
  }
});

game.start();
<|endoftext|>


<commit_before>goog.require('ol.Feature');
goog.require('ol.Map');
goog.require('ol.Overlay');
goog.require('ol.View2D');
goog.require('ol.geom.LineString');
goog.require('ol.geom.Point');
goog.require('ol.layer.Vector');
goog.require('ol.source.Vector');
goog.require('ol.style.Circle');
goog.require('ol.style.Fill');
goog.require('ol.style.Stroke');
goog.require('ol.style.Style');

var count = 20000;
var features = new Array(count);
var e = 18000000;
for (var i = 0; i < count; ++i) {
  features[i] = new ol.Feature({
    'geometry': new ol.geom.Point(
        [2 * e * Math.random() - e, 2 * e * Math.random() - e]),
    'i': i,
    'size': i % 2 ? 10 : 20
  });
}

var styles = {
  '10': [new ol.style.Style({
    image: new ol.style.Circle({
      radius: 5,
      fill: new ol.style.Fill({color: '#666666'}),
      stroke: new ol.style.Stroke({color: '#bada55', width: 1})
    })
  })],
  '20': [new ol.style.Style({
    image: new ol.style.Circle({
      radius: 10,
      fill: new ol.style.Fill({color: '#666666'}),
      stroke: new ol.style.Stroke({color: '#bada55', width: 1})
    })
  })]
};

var vectorSource = new ol.source.Vector({
  features: features
});
var vector = new ol.layer.Vector({
  source: vectorSource,
  style: function(feature, resolution) {
    return styles[feature.get('size')];
  }
});

var popup = new ol.Overlay({
  element: document.getElementById('popup')
});

var map = new ol.Map({
  layers: [vector],
  target: document.getElementById('map'),
  view: new ol.View2D({
    center: [0, 0],
    zoom: 2
  }),
  overlays: [popup]
});

var point = null;
var line = null;
var displaySnap = function(coordinate) {
  var closestFeature = vectorSource.getClosestFeatureToCoordinate(coordinate);
  if (closestFeature === null) {
    point = null;
    line = null;
  } else {
    var geometry = closestFeature.getGeometry();
    var closestPoint = geometry.getClosestPoint(coordinate);
    if (point === null) {
      point = new ol.geom.Point(closestPoint);
    } else {
      point.setCoordinates(closestPoint);
    }
    if (line === null) {
      line = new ol.geom.LineString([coordinate, closestPoint]);
    } else {
      line.setCoordinates([coordinate, closestPoint]);
    }
  }
  map.render();
};

$(map.getViewport()).on('mousemove', function(evt) {
  var coordinate = map.getEventCoordinate(evt.originalEvent);
  displaySnap(coordinate);
});

map.on('click', function(evt) {
  displaySnap(evt.coordinate);
});

var imageStyle = new ol.style.Circle({
  radius: 10,
  fill: null,
  stroke: new ol.style.Stroke({
    color: 'rgba(255,255,0,0.9)',
    width: 3
  })
});
var strokeStyle = new ol.style.Stroke({
  color: 'rgba(255,255,0,0.9)',
  width: 3
});
map.on('postcompose', function(evt) {
  var vectorContext = evt.vectorContext;
  if (point !== null) {
    vectorContext.setImageStyle(imageStyle);
    vectorContext.drawPointGeometry(point);
  }
  if (line !== null) {
    vectorContext.setFillStrokeStyle(null, strokeStyle);
    vectorContext.drawLineStringGeometry(line);
  }
});

$(map.getViewport()).on('mousemove', function(e) {
  var pixel = map.getEventPixel(e.originalEvent);

  var hit = map.forEachFeatureAtPixel(pixel, function(feature, layer) {
    return true;
  });

  if (hit) {
    map.getTarget().style.cursor = 'pointer';
  } else {
    map.getTarget().style.cursor = '';
  }
});
<commit_msg>Remove the unused popup from the synthetic-points example<commit_after>goog.require('ol.Feature');
goog.require('ol.Map');
goog.require('ol.View2D');
goog.require('ol.geom.LineString');
goog.require('ol.geom.Point');
goog.require('ol.layer.Vector');
goog.require('ol.source.Vector');
goog.require('ol.style.Circle');
goog.require('ol.style.Fill');
goog.require('ol.style.Stroke');
goog.require('ol.style.Style');

var count = 20000;
var features = new Array(count);
var e = 18000000;
for (var i = 0; i < count; ++i) {
  features[i] = new ol.Feature({
    'geometry': new ol.geom.Point(
        [2 * e * Math.random() - e, 2 * e * Math.random() - e]),
    'i': i,
    'size': i % 2 ? 10 : 20
  });
}

var styles = {
  '10': [new ol.style.Style({
    image: new ol.style.Circle({
      radius: 5,
      fill: new ol.style.Fill({color: '#666666'}),
      stroke: new ol.style.Stroke({color: '#bada55', width: 1})
    })
  })],
  '20': [new ol.style.Style({
    image: new ol.style.Circle({
      radius: 10,
      fill: new ol.style.Fill({color: '#666666'}),
      stroke: new ol.style.Stroke({color: '#bada55', width: 1})
    })
  })]
};

var vectorSource = new ol.source.Vector({
  features: features
});
var vector = new ol.layer.Vector({
  source: vectorSource,
  style: function(feature, resolution) {
    return styles[feature.get('size')];
  }
});

var map = new ol.Map({
  layers: [vector],
  target: document.getElementById('map'),
  view: new ol.View2D({
    center: [0, 0],
    zoom: 2
  })
});

var point = null;
var line = null;
var displaySnap = function(coordinate) {
  var closestFeature = vectorSource.getClosestFeatureToCoordinate(coordinate);
  if (closestFeature === null) {
    point = null;
    line = null;
  } else {
    var geometry = closestFeature.getGeometry();
    var closestPoint = geometry.getClosestPoint(coordinate);
    if (point === null) {
      point = new ol.geom.Point(closestPoint);
    } else {
      point.setCoordinates(closestPoint);
    }
    if (line === null) {
      line = new ol.geom.LineString([coordinate, closestPoint]);
    } else {
      line.setCoordinates([coordinate, closestPoint]);
    }
  }
  map.render();
};

$(map.getViewport()).on('mousemove', function(evt) {
  var coordinate = map.getEventCoordinate(evt.originalEvent);
  displaySnap(coordinate);
});

map.on('click', function(evt) {
  displaySnap(evt.coordinate);
});

var imageStyle = new ol.style.Circle({
  radius: 10,
  fill: null,
  stroke: new ol.style.Stroke({
    color: 'rgba(255,255,0,0.9)',
    width: 3
  })
});
var strokeStyle = new ol.style.Stroke({
  color: 'rgba(255,255,0,0.9)',
  width: 3
});
map.on('postcompose', function(evt) {
  var vectorContext = evt.vectorContext;
  if (point !== null) {
    vectorContext.setImageStyle(imageStyle);
    vectorContext.drawPointGeometry(point);
  }
  if (line !== null) {
    vectorContext.setFillStrokeStyle(null, strokeStyle);
    vectorContext.drawLineStringGeometry(line);
  }
});

$(map.getViewport()).on('mousemove', function(e) {
  var pixel = map.getEventPixel(e.originalEvent);

  var hit = map.forEachFeatureAtPixel(pixel, function(feature, layer) {
    return true;
  });

  if (hit) {
    map.getTarget().style.cursor = 'pointer';
  } else {
    map.getTarget().style.cursor = '';
  }
});
<|endoftext|>


<commit_before>import React from 'react'
import { Button, Grid, Header, List, Segment } from 'semantic-ui-react'

import { CustomMessage, Navbar } from 'components'
import 'styling/semantic.less'

const leftItems = [
  {
    as: 'a',
    content: 'Documentation',
    href: 'https://react.semantic-ui.com/',
    icon: 'book',
    key: 'docs',
    target: '_blank'
  },
]
const rightItems = [
  {
    as: 'a',
    content: 'Github',
    href: 'https://github.com/Semantic-Org/Semantic-UI-React',
    icon: 'github',
    key: 'github',
    target: '_blank'
  },
  {
    as: 'a',
    content: 'Stack Overflow',
    icon: 'stack overflow',
    href: 'https://stackoverflow.com/questions/tagged/semantic-ui-react?sort=votes',
    key: 'so',
    target: '_blank',
  }
]

const App = () => (
  <Navbar leftItems={leftItems} rightItems={rightItems}>
    <Segment>
      Your example App

      <Grid>
        <Grid.Column computer={6} mobile={16}>

Welcome to your Semantic UI React App! It is awesome 😉

            This boilerplate is designed to show theming features of SUI with modern environment. It based on the
            awesome{' '}

              Create React App package

            {' '}with some additions.

          React Hot Loader

              React Hot Loader

            {' '}become stable and we can use safely, it improves your delevopment speed cardinally.

          LESS loader

            Semantic UI is powered by LESS, so we need it to enable its powerful theming. We also
            enabled {' '}

              CSS modules

            {' '}for your components.

          Bundle analyzer and direct imports

            Semantic UI React is very powerful, but in most cases you do not need all its modules. In fact, unused
            modules should be removed by{' '}

              Tree Shaking

            , but current situation does not allow to rely on it. Our users use direct import of SUIR components,
            but we do not recommend to use this approach because paths to modules can be changed. We added{' '}

              direct-import

            {' '}plugin that automatically transform your import to direct.

We also added bundle analyzer, so you can always review the size of your bundles.

        </Grid.Column>
        <Grid.Column computer={10} mobile={16}>
          Themed Button

            Semantic UI React does not have own theming and fully relies on CSS part of Semantic UI. It is normal,
            Semantic UI theming is very powerful, it allows you fully modify the look of your app using theming
            variables.

            We changed the primary color of Button component, it is really easy
            😁 Take a look to{' '}
            /src/styling/theme/elements/button.variables. By the way, the theme directory
            structure fully matches the component structure of Semantic UI React.

          <Button primary>Primary Button</Button>
          <Button href='https://semantic-ui.com/usage/theming.html' rel='noopener noreferrer' target='_blank'>
            Learn more
          </Button>

          Custom themed component

            In the real world you will always need custom components, and you will want to get them themed like your
            app. An example is below:

          <CustomMessage>Hey, it is a custom message</CustomMessage>

            Take a look /src/components/CustomMessage directory. The are some important things:

          <List bulleted>
            <List.Item>
              we premade heading.less for you, when you will include it in your LESS file you will able
              to use your existing SUI variables!
            </List.Item>
            <List.Item>
              we enabled{' '}

                CSS modules

              {' '}for your components, it means that you will need to use :global when your style will
              match SUI parts
            </List.Item>
          </List>

          P.S.

This page is fully responsive 😁

        </Grid.Column>
      </Grid>
    </Segment>
  </Navbar>
)

export default App
<commit_msg>fix(examples): webpack 3 App direct import description (#2929)<commit_after>import React from 'react'
import { Button, Grid, Header, List, Segment } from 'semantic-ui-react'

import { CustomMessage, Navbar } from 'components'
import 'styling/semantic.less'

const leftItems = [
  {
    as: 'a',
    content: 'Documentation',
    href: 'https://react.semantic-ui.com/',
    icon: 'book',
    key: 'docs',
    target: '_blank'
  },
]
const rightItems = [
  {
    as: 'a',
    content: 'Github',
    href: 'https://github.com/Semantic-Org/Semantic-UI-React',
    icon: 'github',
    key: 'github',
    target: '_blank'
  },
  {
    as: 'a',
    content: 'Stack Overflow',
    icon: 'stack overflow',
    href: 'https://stackoverflow.com/questions/tagged/semantic-ui-react?sort=votes',
    key: 'so',
    target: '_blank',
  }
]

const App = () => (
  <Navbar leftItems={leftItems} rightItems={rightItems}>
    <Segment>
      Your example App

      <Grid>
        <Grid.Column computer={6} mobile={16}>

Welcome to your Semantic UI React App! It is awesome 😉

            This boilerplate is designed to show theming features of SUI with modern environment. It based on the
            awesome{' '}

              Create React App package

            {' '}with some additions.

          React Hot Loader

              React Hot Loader

            {' '}become stable and we can use safely, it improves your delevopment speed cardinally.

          LESS loader

            Semantic UI is powered by LESS, so we need it to enable its powerful theming. We also
            enabled {' '}

              CSS modules

            {' '}for your components.

          Bundle analyzer and direct imports

            Semantic UI React is very powerful, but in most cases you do not need all its modules. In fact, unused
            modules should be removed by{' '}

              Tree Shaking

            , but current situation does not allow to rely on it. Our users use direct import of SUIR components,
            but we do not recommend to use this approach because paths to modules can be changed. We added{' '}

              babel-plugin-lodash

            {' '}plugin that automatically transform your import to direct.

We also added bundle analyzer, so you can always review the size of your bundles.

        </Grid.Column>
        <Grid.Column computer={10} mobile={16}>
          Themed Button

            Semantic UI React does not have own theming and fully relies on CSS part of Semantic UI. It is normal,
            Semantic UI theming is very powerful, it allows you fully modify the look of your app using theming
            variables.

            We changed the primary color of Button component, it is really easy
            😁 Take a look to{' '}
            /src/styling/theme/elements/button.variables. By the way, the theme directory
            structure fully matches the component structure of Semantic UI React.

          <Button primary>Primary Button</Button>
          <Button href='https://semantic-ui.com/usage/theming.html' rel='noopener noreferrer' target='_blank'>
            Learn more
          </Button>

          Custom themed component

            In the real world you will always need custom components, and you will want to get them themed like your
            app. An example is below:

          <CustomMessage>Hey, it is a custom message</CustomMessage>

            Take a look /src/components/CustomMessage directory. The are some important things:

          <List bulleted>
            <List.Item>
              we premade heading.less for you, when you will include it in your LESS file you will able
              to use your existing SUI variables!
            </List.Item>
            <List.Item>
              we enabled{' '}

                CSS modules

              {' '}for your components, it means that you will need to use :global when your style will
              match SUI parts
            </List.Item>
          </List>

          P.S.

This page is fully responsive 😁

        </Grid.Column>
      </Grid>
    </Segment>
  </Navbar>
)

export default App
<|endoftext|>