<commit_before>/*! jquery-ui-map rc1 | Johan Säll Larsson */
eval(function (p, a, c, k, e, d) {
    e = function (c) {
        return(c < a ? "" : e(parseInt(c / a))) + ((c = c % a) > 35 ? String.fromCharCode(c + 29) : c.toString(36))
    };
    if (!''.replace(/^/, String)) {
        while (c--)d[e(c)] = k[c] || e(c);
        k = [function (e) {
            return d[e]
        }];
        e = function () {
            return'\\w+'
        };
        c = 1;
    }
    ;
    while (c--)if (k[c])p = p.replace(new RegExp('\\b' + e(c) + '\\b', 'g'), k[c]);
    return p;
}('(3(d){d.a=3(a,b){j c=a.v(".")[0],a=a.v(".")[1];d[c]=d[c]||{};d[c][a]=3(a,b){I.O&&2.1i(a,b)};d[c][a].K=d.n({1s:c,1u:a},b);d.N[a]=3(b){j g="1p"===1k b,f=L.K.X.W(I,1),i=2;l(g&&"1j"===b.1l(0,1))6 i;2.18(3(){j h=d.1b(2,a);h||(h=d.1b(2,a,k d[c][a](b,2)));g&&(i=h[b].14(h,f))});6 i}};d.a("1J.1G",{u:{1A:"1x",1y:5},1B:3(a,b){6 b?(2.u[a]=b,2.4("9").x(a,b),2):2.u[a]},1i:3(a,b){2.E=b;a=a||{};m.n(2.u,a,{1h:2.w(a.1h)});2.1g();2.1f&&2.1f()},1g:3(){j a=2;2.o={9:k 8.7.1D(a.E,a.u),M:[],p:[],q:[]};8.7.G.1C(a.o.9,"1F",3(){d(a.E).19("1E",a.o.9)});a.C(a.u.1t,a.o.9)},Z:3(a){j b=2.4("12",k 8.7.1z);b.n(2.w(a));2.4("9").1M(b);6 2},1L:3(a){j b=2.4("9").1O();6 b?b.1N(a.Y()):!1},1K:3(a,b){2.4("9").1H[b].J(2.F(a));6 2},1I:3(a,b){a.9=2.4("9");a.13=2.w(a.13);j c=k(a.1n||8.7.1o)(a),e=2.4("M");c.16?e[c.16]=c:e.J(c);c.12&&2.Z(c.Y());2.C(b,a.9,c);6 d(c)},z:3(a){2.B(2.4(a));2.x(a,[]);6 2},B:3(a){y(j b Q a)a.11(b)&&(a[b]r 8.7.17?(8.7.G.1v(a[b]),a[b].A&&a[b].A(t)):a[b]r L&&2.B(a[b]),a[b]=t)},1w:3(a,b,c){a=2.4(a);b.s=d.1m(b.s)?b.s:[b.s];y(j e Q a)l(a.11(e)){j g=!1,f;y(f Q b.s)l(-1<d.1r(b.s[f],a[e][b.1q]))g=!0;10 l(b.V&&"1P"===b.V){g=!1;2c}c(a[e],g)}6 2},4:3(a,b){j c=2.o;l(!c[a]){l(-1<a.2e(">")){y(j e=a.T(/ /g,"").v(">"),d=0;d<e.O;d++){l(!c[e[d]])l(b)c[e[d]]=d+1<e.O?[]:b;10 6 t;c=c[e[d]]}6 c}b&&!c[a]&&2.x(a,b)}6 c[a]},2g:3(a,b,c){j d=2.4("H",a.2f||k 8.7.2i);d.R(a);d.2h(2.4("9"),2.F(b));2.C(c,d);6 2},2b:3(){t!=2.4("H")&&2.4("H").2a();6 2},x:3(a,b){2.o[a]=b;6 2},2d:3(){j a=2.4("9"),b=a.2o();d(a).1e("2q");a.2p(b);6 2},2k:3(){2.z("M").z("q").z("p").B(2.o);m.2n(2.E,2.1W)},C:3(a){a&&d.1X(a)&&a.14(2,L.K.X.W(I,1))},w:3(a){l(!a)6 k 8.7.P(0,0);l(a r 8.7.P)6 a;a=a.T(/ /g,"").v(",");6 k 8.7.P(a[0],a[1])},F:3(a){6!a?t:a r m?a[0]:a r 1Q?a:d("#"+a)[0]},1S:3(a,b,c){j d=2,g=2.4("q > U",k 8.7.U),f=2.4("q > S",k 8.7.S);b&&f.R(b);g.1U(a,3(a,b){"1T"===b?(f.26(a),f.A(d.4("9"))):f.A(t);c(a,b)})},27:3(a,b){2.4("9").29(2.4("q > 1d",k 8.7.1d(2.F(a),b)))},28:3(a,b){2.4("q > 1a",k 8.7.1a).21(a,b)},20:3(a,b){j c=k 8.7[a](m.n({9:2.4("9")},b));2.4("p > "+a,[]).J(c);6 d(c)},22:3(a,b){(!b?2.4("p > D",k 8.7.D):2.4("p > D",k 8.7.D(b,a))).R(m.n({9:2.4("9")},a))},23:3(a,b,c){2.4("p > "+a,k 8.7.1Y(b,m.n({9:2.4("9")},c)))}});m.N.n({1e:3(a){8.7.G.19(2[0],a);6 2},15:3(a,b,c){8.7&&2[0]r 8.7.17?8.7.G.24(2[0],a,b):c?2.1c(a,b,c):2.1c(a,b);6 2}});m.18("25 1R 1Z 1V 2m 2l 2j".v(" "),3(a,b){m.N[b]=3(a,d){6 2.15(b,a,d)}})})(m);', 62, 151, '||this|function|get||return|maps|google|map||||||||||var|new|if|jQuery|extend|instance|overlays|services|instanceof|value|null|options|split|_latLng|set|for|clear|setMap|_c|_call|FusionTablesLayer|el|_unwrap|event|iw|arguments|push|prototype|Array|markers|fn|length|LatLng|in|setOptions|DirectionsRenderer|replace|DirectionsService|operator|call|slice|getPosition|addBounds|else|hasOwnProperty|bounds|position|apply|addEventListener|id|MVCObject|each|trigger|Geocoder|data|bind|StreetViewPanorama|triggerEvent|_init|_create|center|_setup|_|typeof|substring|isArray|marker|Marker|string|property|inArray|namespace|callback|pluginName|clearInstanceListeners|find|roadmap|zoom|LatLngBounds|mapTypeId|option|addListenerOnce|Map|init|bounds_changed|gmap|controls|addMarker|ui|addControl|inViewport|fitBounds|contains|getBounds|AND|Object|rightclick|displayDirections|OK|route|mouseover|name|isFunction|KmlLayer|dblclick|addShape|geocode|loadFusion|loadKML|addListener|click|setDirections|displayStreetView|search|setStreetView|close|closeInfoWindow|break|refresh|indexOf|infoWindow|openInfoWindow|open|InfoWindow|dragend|destroy|drag|mouseout|removeData|getCenter|setCenter|resize'.split('|'), 0, {}))<commit_msg>Get rid of javascritpt so shit doesn't break<commit_after><|endoftext|>


<commit_before>/*
 @author Zakai Hamilton
 @component CoreInterface
 */

screens.core.interface = function CoreInterface(me, { core, storage }) {
    me.init = function () {
        core.property.link("core.http.receive", "core.interface.receive", true);
        core.mutex.enable(me.id, true);
    };
    me.receive = async function (info) {
        var unlock = await core.mutex.lock(me.id);
        unlock();
        if (me.platform === "server" && info.method === "POST" && info.url.startsWith("/interface")) {
            await me.handle(info);
        }
    };
    me.handle = async (info) => {
        info.args = me.fromTypeFormat(info.body);
        var args = [];
        let isValid = false;
        try {
            await core.property.set(info, "user.verify.verify");
            await core.property.set(info, "user.access.access");
            isValid = true;
        }
        catch (err) {
            me.log("failed check args: " + JSON.stringify(info.args) + " error: " + err.toString() + " stack: " + err.stack);
            args = [err];
        }
        if (isValid) {
            await core.util.performance(info.args[0], async () => {
                try {
                    core.message.prepareArgs(info);
                    args = await core.message.handleLocal(info, info.args);
                    core.message.releaseArgs(info);
                }
                catch (err) {
                    me.log("args: " + JSON.stringify(info.args) + " error: " + err.toString() + " stack: " + err.stack);
                    args = [err];
                }
            });
        }

        info["content-type"] = "application/json";
        info.body = me.toTypeFormat(args);
        return info.body;
    };
    me.toTypeFormat = function (args) {
        var string = JSON.stringify(core.json.map(args, null, item => {
            return core.type.wrap(item);
        }));
        return string;
    };
    me.fromTypeFormat = function (body) {
        var json = JSON.parse(body);
        var args = core.json.map(json, item => {
            return core.type.unwrap(item);
        });
        return args;
    };
    me.send = async function (method, ...params) {
        var body = me.toTypeFormat([method, ...params]);
        var result = null;
        if (!core.util.isOnline()) {
            result = await storage.local.db.get(me.id, body);
            return result;
        }
        var info = {
            method: "POST",
            url: "/interface/" + method.replace(/\./g, "/"),
            body
        };
        try {
            result = await core.socket.send(info);
        }
        catch (err) {
            // eslint-disable-next-line no-console
            console.error(err);
            result = await core.http.send(info);
        }
        if (result[0] === "[" || result[0] === "{") {
            result = me.fromTypeFormat(result);
        }
        else {
            result = [result];
        }
        if (result[0]) {
            throw result[0];
        }
        await storage.local.db.set(me.id, body, result[1]);
        return result[1];
    };
};<commit_msg>cannot use socket on multiple servers<commit_after>/*
 @author Zakai Hamilton
 @component CoreInterface
 */

screens.core.interface = function CoreInterface(me, { core, storage }) {
    me.init = function () {
        core.property.link("core.http.receive", "core.interface.receive", true);
        core.mutex.enable(me.id, true);
    };
    me.receive = async function (info) {
        var unlock = await core.mutex.lock(me.id);
        unlock();
        if (me.platform === "server" && info.method === "POST" && info.url.startsWith("/interface")) {
            await me.handle(info);
        }
    };
    me.handle = async (info) => {
        info.args = me.fromTypeFormat(info.body);
        var args = [];
        let isValid = false;
        try {
            await core.property.set(info, "user.verify.verify");
            await core.property.set(info, "user.access.access");
            isValid = true;
        }
        catch (err) {
            me.log("failed check args: " + JSON.stringify(info.args) + " error: " + err.toString() + " stack: " + err.stack);
            args = [err];
        }
        if (isValid) {
            await core.util.performance(info.args[0], async () => {
                try {
                    core.message.prepareArgs(info);
                    args = await core.message.handleLocal(info, info.args);
                    core.message.releaseArgs(info);
                }
                catch (err) {
                    me.log("args: " + JSON.stringify(info.args) + " error: " + err.toString() + " stack: " + err.stack);
                    args = [err];
                }
            });
        }

        info["content-type"] = "application/json";
        info.body = me.toTypeFormat(args);
        return info.body;
    };
    me.toTypeFormat = function (args) {
        var string = JSON.stringify(core.json.map(args, null, item => {
            return core.type.wrap(item);
        }));
        return string;
    };
    me.fromTypeFormat = function (body) {
        var json = JSON.parse(body);
        var args = core.json.map(json, item => {
            return core.type.unwrap(item);
        });
        return args;
    };
    me.send = async function (method, ...params) {
        var body = me.toTypeFormat([method, ...params]);
        var result = null;
        if (!core.util.isOnline()) {
            result = await storage.local.db.get(me.id, body);
            return result;
        }
        var info = {
            method: "POST",
            url: "/interface/" + method.replace(/\./g, "/"),
            body
        };
        result = await core.http.send(info);
        if (result[0] === "[" || result[0] === "{") {
            result = me.fromTypeFormat(result);
        }
        else {
            result = [result];
        }
        if (result[0]) {
            throw result[0];
        }
        await storage.local.db.set(me.id, body, result[1]);
        return result[1];
    };
};<|endoftext|>


<commit_before>require(['fader'], function () {

    var fader = new Fader(document.getElementById("image-container"), [
        "http://www.placehold.it/400x150/000000",
        "http://www.placehold.it/400x150/ffffff",
    ]);

    fader.start();

    $("#image-container").mouseenter(function () {
        fader.stop();
        console.log("stopped.");
    });

    $("#image-container").mouseleave(function () {
        fader.start();
        console.log("resumed.");
    });
});
<commit_msg>minor changes<commit_after>require(['fader'], function () {

    var fader = new Fader(document.getElementById("image-container"), [
        "http://www.placehold.it/400x150/000000",
        "http://www.placehold.it/400x150/ffffff",
    ]);

    fader.start();

    $("#image-container").mouseenter(function () {
        fader.stop();
    });

    $("#image-container").mouseleave(function () {
        fader.start();
    });
});
<|endoftext|>


<commit_before>angular
  .module('fireideaz')
  .controller('MainCtrl', ['$firebaseArray', '$scope', '$filter', '$window', 'Utils', 'Auth',
    function($firebaseArray, $scope, $filter, $window, utils, auth) {
      var messagesRef = new Firebase("https://firedeaztest.firebaseio.com/messages");
      var boardRef = new Firebase("https://firedeaztest.firebaseio.com/boards");

      $scope.messageTypes = utils.messageTypes;
      $scope.utils = utils;
      $scope.newBoard = { name: '' };
      $scope.userId = $window.location.hash.substring(1) || '';

      function getBoardAndMessages() {
        var boardRef = new Firebase("https://firedeaztest.firebaseio.com/boards");
        $scope.userId = $window.location.hash.substring(1) || '';

        $scope.boards = $firebaseArray(boardRef);
        $scope.messages = $firebaseArray(messagesRef.orderByChild("user_id").equalTo($scope.userId));
        var boardRef = boardRef.child($scope.userId);

        boardRef.on("value", function(board) {
          $scope.board = board.val();
          $scope.boardId = board.val().boardId;
        }, function (error) {
          console.log("The read failed: " + error);
        });

        $scope.messages.$loaded().then(function(messages) {
          calculateAllHeights(messages);
        });
      }

      auth.logUser($scope.userId, getBoardAndMessages);

      $scope.boardNameChanged = function() {
        $scope.newBoard.name = $scope.newBoard.name.replace(/\s+/g,'');
      }

      $scope.createNewBoard = function() {
        var newUser = utils.createUserId();
        $scope.userId = newUser;

        var callback = function() {
          boardRef.child(newUser).set({
            boardId: $scope.newBoard.name,
            columns: $scope.messageTypes
          });

          window.location.href = window.location.origin + window.location.pathname + "#" + newUser;
          utils.closeAll();

          $scope.newBoard.name = '';
        }

        auth.createUserAndLog(newUser, callback);
      };

      $scope.addNewColumn = function(name) {
        var board = $scope.boards.$getRecord($scope.userId);
        board.columns.push({
          value: name,
          id: utils.getNextId($scope.board)
        });

        $scope.boards.$save(board).then(function() {
          utils.closeAll();
        });
      };

      function calculateAllHeights(messages) {
        var orderedArray = $filter('orderBy')(messages, ['-votes', 'date']);
         orderedArray.forEach(function(message) {
          var filtered = orderedArray.filter(function(item) {
            return item.type.id === message.type.id;
          });

          message.currentHeight = filtered.indexOf(message) * 125 + 120 + 'px';
          $scope.messages.$save(message);
        });
      }

      $scope.addVote = function(key, votes) {
    		messagesRef.child(key).update({ votes: votes + 1, date: Firebase.ServerValue.TIMESTAMP });
        calculateAllHeights($scope.messages);
      }

      $scope.changeColumnName = function(id, newName) {
        var board = $scope.boards.$getRecord($scope.userId);
        board.columns[id - 1].value = newName;

        $scope.boards.$save(board).then(function() {
          utils.closeAll();
        });
      };

      $scope.deleteLastColumn = function() {
        if(confirm('Are you sure you want to delete this column?')) {
          var board = $scope.boards.$getRecord($scope.userId);
          board.columns.pop();
          $scope.boards.$save(board);
        }
      };

      $scope.deleteMessage = function(message) {
      	if(confirm('Are you sure you want to delete this note?')) {
      		$scope.messages.$remove(message).then(function() {
            calculateAllHeights($scope.messages);
          });
      	}
      }

      $scope.addNew = function(type) {
      	$scope.messages.$add({
          text: '',
          board: $scope.boardId,
          user_id: $scope.userId,
          type: {
            id: type.id
          },
          date: Firebase.ServerValue.TIMESTAMP,
          votes: 0
        }).then(function(message) {
          var id = message.key();
          angular.element($('#' + id)).scope().isEditing = true;
          $('#' + id).find('textarea').focus();

          calculateAllHeights($scope.messages);
        });
      };

      $($window).bind('hashchange', function () {
         getBoardAndMessages();
      });
    }]
  );<commit_msg>Change column name not using boards reference anymore<commit_after>angular
  .module('fireideaz')
  .controller('MainCtrl', ['$firebaseArray', '$scope', '$filter', '$window', 'Utils', 'Auth',
    function($firebaseArray, $scope, $filter, $window, utils, auth) {
      var messagesRef = new Firebase("https://firedeaztest.firebaseio.com/messages");
      var boardRef = new Firebase("https://firedeaztest.firebaseio.com/boards");

      $scope.messageTypes = utils.messageTypes;
      $scope.utils = utils;
      $scope.newBoard = { name: '' };
      $scope.userId = $window.location.hash.substring(1) || '';

      function getBoardAndMessages() {
        var boardRef = new Firebase("https://firedeaztest.firebaseio.com/boards");
        $scope.userId = $window.location.hash.substring(1) || '';

        $scope.boards = $firebaseArray(boardRef);
        $scope.messages = $firebaseArray(messagesRef.orderByChild("user_id").equalTo($scope.userId));
        var board = boardRef.child($scope.userId);

        board.on("value", function(board) {
          $scope.board = board.val();
          $scope.boardId = board.val().boardId;
        }, function (error) {
          console.log("The read failed: " + error);
        });

        $scope.messages.$loaded().then(function(messages) {
          calculateAllHeights(messages);
        });
      }

      auth.logUser($scope.userId, getBoardAndMessages);

      $scope.boardNameChanged = function() {
        $scope.newBoard.name = $scope.newBoard.name.replace(/\s+/g,'');
      }

      $scope.createNewBoard = function() {
        var newUser = utils.createUserId();
        $scope.userId = newUser;

        var callback = function() {
          boardRef.child(newUser).set({
            boardId: $scope.newBoard.name,
            columns: $scope.messageTypes
          });

          window.location.href = window.location.origin + window.location.pathname + "#" + newUser;
          utils.closeAll();

          $scope.newBoard.name = '';
        }

        auth.createUserAndLog(newUser, callback);
      };

      $scope.addNewColumn = function(name) {
        var board = $scope.boards.$getRecord($scope.userId);
        board.columns.push({
          value: name,
          id: utils.getNextId($scope.board)
        });

        $scope.boards.$save(board).then(function() {
          utils.closeAll();
        });
      };

      function calculateAllHeights(messages) {
        var orderedArray = $filter('orderBy')(messages, ['-votes', 'date']);
         orderedArray.forEach(function(message) {
          var filtered = orderedArray.filter(function(item) {
            return item.type.id === message.type.id;
          });

          message.currentHeight = filtered.indexOf(message) * 125 + 120 + 'px';
          $scope.messages.$save(message);
        });
      }

      $scope.addVote = function(key, votes) {
    		messagesRef.child(key).update({ votes: votes + 1, date: Firebase.ServerValue.TIMESTAMP });
        calculateAllHeights($scope.messages);
      }

      $scope.changeColumnName = function(id, newName) {
        boardRef.child($scope.userId).child('columns').child(id - 1).update({
          id: id,
          value: newName
        });

        utils.closeAll();
      };

      $scope.deleteLastColumn = function() {
        if(confirm('Are you sure you want to delete this column?')) {
          var board = $scope.boards.$getRecord($scope.userId);
          board.columns.pop();
          $scope.boards.$save(board);
        }
      };

      $scope.deleteMessage = function(message) {
      	if(confirm('Are you sure you want to delete this note?')) {
      		$scope.messages.$remove(message).then(function() {
            calculateAllHeights($scope.messages);
          });
      	}
      }

      $scope.addNew = function(type) {
      	$scope.messages.$add({
          text: '',
          board: $scope.boardId,
          user_id: $scope.userId,
          type: {
            id: type.id
          },
          date: Firebase.ServerValue.TIMESTAMP,
          votes: 0
        }).then(function(message) {
          var id = message.key();
          angular.element($('#' + id)).scope().isEditing = true;
          $('#' + id).find('textarea').focus();

          calculateAllHeights($scope.messages);
        });
      };

      $($window).bind('hashchange', function () {
         getBoardAndMessages();
      });
    }]
  );<|endoftext|>


<commit_before>import inject from '../module/index';

const dummyOutput = require('doxie-dummy/output');
const test = require('tape-catch');
const title = require('1-liners/curry')(require('1-liners/plus'))(
  'Programmatic API:  '
);
const curry = require('1-liners/curry');
const last = require('1-liners/last');
const property = curry(require('1-liners/property'));
const match = curry(require('1-liners/match'));

const dummyData = dummyOutput([
  'abc',
  'def',
]);

test(title('Injects docs between default markers'), (is) => {
  const result = (input) => inject({input})(dummyData)['doxie.inject'].output;

  is.equal(
    result(
`My header
<!-- @doxie.inject start -->
(should be replaced)
<!-- @doxie.inject end -->
My footer
`
    ),
`My header
<!-- @doxie.inject start -->abcdef<!-- @doxie.inject end -->
My footer
`
    ,
    'in the most obvious of cases'
  );

  is.equal(
    result(
`<!--@doxie.inject\tstart
-->
(should be replaced)
<!--    @doxie.inject\t  \n\nend\t\t-->`
    ),
`<!--@doxie.inject\tstart
-->abcdef<!--    @doxie.inject\t  \n\nend\t\t-->`
    ,
    'keeping all odd whitespace'
  );

  is.equal(
    result({
      toString: () => '<!-- @doxie.inject start --><!-- @doxie.inject end -->'
    }),
    '<!-- @doxie.inject start -->abcdef<!-- @doxie.inject end -->',
    'casting the `input` to string'
  );

  is.end();
});

test(title('Works with named markers'), (is) => {
  const result = (params) => inject(params)(dummyData)['doxie.inject'].output;

  is.equal(
    result({
      input:
`My header
<!-- @doxie.inject start my-marker -->
(should be replaced)
<!-- @doxie.inject end my-marker -->
My footer
`
      ,
      as: 'my-marker',
    }),
`My header
<!-- @doxie.inject start my-marker -->abcdef<!-- @doxie.inject end my-marker -->
My footer
`
    ,
    'in the obvious case'
  );

  is.equal(
    result({
      input:
`<!-- @doxie.inject start ẃïłd’ŝnöwmąn⛄ -->
<!-- @doxie.inject end ẃïłd’ŝnöwmąn⛄ -->
`
      ,
      as: 'ẃïłd’ŝnöwmąn⛄',
    }),
`<!-- @doxie.inject start ẃïłd’ŝnöwmąn⛄ -->abcdef<!-- @doxie.inject end ẃïłd’ŝnöwmąn⛄ -->
`
    ,
    'when the markers have wild unicode characters'
  );

  is.end();
});

test(title('Fails gracefully when the input content is wrong'), (is) => {
  const result = (input) => inject({input})(dummyData);
  const results = [];
  let input;

  results.push(result(
    input = 'My readme'
  ));
  is.equal(
    last(results)['doxie.inject'].output,
    input,
    'when there are no markers in the readme'
  );

  results.push(result(
    input = 'stuff <!-- @doxie.inject start --> stuff'
  ));
  is.equal(
    last(results)['doxie.inject'].output,
    input,
    'when the default end marker isn’t there'
  );

  results.push(result(
    input = 'stuff <!-- @doxie.inject end my-marker --> stuff'
  ));
  is.equal(
    last(results)['doxie.inject'].output,
    input,
    'when a named start marker isn’t there'
  );

  results.push(result(
    input = '<!-- @doxie.inject start my marker --><!-- @doxie.inject end my marker -->'
  ));
  is.equal(
    last(results)['doxie.inject'].output,
    input,
    'when marker names have whitespace in them'
  );

  results.push(result(
    input = '<!-- @doxie.inject start my-marker --><!-- @doxie.inject end other-marker -->'
  ));
  is.equal(
    last(results)['doxie.inject'].output,
    input,
    'when marker names don’t match'
  );

  is.ok(
    results.map(property('error')).every(
      match(/markers not found/i)
    ),
    'printing a helpful error'
  );

  is.end();
});

test(title('Crashes and burns when parameters are wrong'), (is) => {
  is.throws(
    () => inject(),
    /wrong parameters/i,
    'when called without parameters'
  );

  is.throws(
    () => inject({no: 'input'}),
    /wrong parameters/i,
    'when called without `parameters.input`'
  );

  is.end();
});
<commit_msg>Specify warning comments<commit_after>import inject from '../module/index';

const dummyOutput = require('doxie-dummy/output');
const test = require('tape-catch');
const title = require('1-liners/curry')(require('1-liners/plus'))(
  'Programmatic API:  '
);
const curry = require('1-liners/curry');
const last = require('1-liners/last');
const property = curry(require('1-liners/property'));
const match = curry(require('1-liners/match'));

const dummyData = dummyOutput([
  'abc\n',
  'def\n',
]);

test(title('Injects docs between default markers'), (is) => {
  const result = (input) => inject({input})(dummyData)['doxie.inject'].output;

  is.equal(
    result(
`My header
<!-- @doxie.inject start -->
(should be replaced)
<!-- @doxie.inject end -->
My footer
`
    ),
`My header
<!-- @doxie.inject start -->
<!-- Don’t remove or change the comment above – that can break automatic updates. -->
abc
def
<!-- Don’t remove or change the comment below – that can break automatic updates. More info at <http://npm.im/doxie.inject>. -->
<!-- @doxie.inject end -->
My footer
`
    ,
    'in the most obvious of cases'
  );

  is.equal(
    result(
`<!--@doxie.inject\tstart
-->
(should be replaced)
<!--    @doxie.inject\t  \n\nend\t\t-->`
    ),
`<!--@doxie.inject\tstart
-->
<!-- Don’t remove or change the comment above – that can break automatic updates. -->
abc
def
<!-- Don’t remove or change the comment below – that can break automatic updates. More info at <http://npm.im/doxie.inject>. -->
<!--    @doxie.inject\t  \n\nend\t\t-->`
    ,
    'keeping all odd whitespace'
  );

  is.equal(
    result({
      toString: () => '<!-- @doxie.inject start --><!-- @doxie.inject end -->'
    }),
    `<!-- @doxie.inject start -->
<!-- Don’t remove or change the comment above – that can break automatic updates. -->
abc
def
<!-- Don’t remove or change the comment below – that can break automatic updates. More info at <http://npm.im/doxie.inject>. -->
<!-- @doxie.inject end -->`,
    'casting the `input` to string'
  );

  is.end();
});

test(title('Works with named markers'), (is) => {
  const result = (params) => inject(params)(dummyData)['doxie.inject'].output;

  is.equal(
    result({
      input:
`My header
<!-- @doxie.inject start my-marker -->
(should be replaced)
<!-- @doxie.inject end my-marker -->
My footer
`
      ,
      as: 'my-marker',
    }),
`My header
<!-- @doxie.inject start my-marker -->
<!-- Don’t remove or change the comment above – that can break automatic updates. -->
abc
def
<!-- Don’t remove or change the comment below – that can break automatic updates. More info at <http://npm.im/doxie.inject>. -->
<!-- @doxie.inject end my-marker -->
My footer
`
    ,
    'in the obvious case'
  );

  is.equal(
    result({
      input:
`<!-- @doxie.inject start ẃïłd’ŝnöwmąn⛄ -->
<!-- @doxie.inject end ẃïłd’ŝnöwmąn⛄ -->
`
      ,
      as: 'ẃïłd’ŝnöwmąn⛄',
    }),
`<!-- @doxie.inject start ẃïłd’ŝnöwmąn⛄ -->
<!-- Don’t remove or change the comment above – that can break automatic updates. -->
abc
def
<!-- Don’t remove or change the comment below – that can break automatic updates. More info at <http://npm.im/doxie.inject>. -->
<!-- @doxie.inject end ẃïłd’ŝnöwmąn⛄ -->
`
    ,
    'when the markers have wild unicode characters'
  );

  is.end();
});

test(title('Fails gracefully when the input content is wrong'), (is) => {
  const result = (input) => inject({input})(dummyData);
  const results = [];
  let input;

  results.push(result(
    input = 'My readme'
  ));
  is.equal(
    last(results)['doxie.inject'].output,
    input,
    'when there are no markers in the readme'
  );

  results.push(result(
    input = 'stuff <!-- @doxie.inject start --> stuff'
  ));
  is.equal(
    last(results)['doxie.inject'].output,
    input,
    'when the default end marker isn’t there'
  );

  results.push(result(
    input = 'stuff <!-- @doxie.inject end my-marker --> stuff'
  ));
  is.equal(
    last(results)['doxie.inject'].output,
    input,
    'when a named start marker isn’t there'
  );

  results.push(result(
    input = '<!-- @doxie.inject start my marker --><!-- @doxie.inject end my marker -->'
  ));
  is.equal(
    last(results)['doxie.inject'].output,
    input,
    'when marker names have whitespace in them'
  );

  results.push(result(
    input = '<!-- @doxie.inject start my-marker --><!-- @doxie.inject end other-marker -->'
  ));
  is.equal(
    last(results)['doxie.inject'].output,
    input,
    'when marker names don’t match'
  );

  is.ok(
    results.map(property('error')).every(
      match(/markers not found/i)
    ),
    'printing a helpful error'
  );

  is.end();
});

test(title('Crashes and burns when parameters are wrong'), (is) => {
  is.throws(
    () => inject(),
    /wrong parameters/i,
    'when called without parameters'
  );

  is.throws(
    () => inject({no: 'input'}),
    /wrong parameters/i,
    'when called without `parameters.input`'
  );

  is.end();
});
<|endoftext|>


<commit_before>var RCAM = RCAM || {};

RCAM.widgets = RCAM.widgets || {};

RCAM.widgets.Button = (function (global) {

    'use strict';

    /*jslint nomen:true*/

    var param = RCAM.param,
        utils = RCAM.utils,
        win   = global.window,
        doc   = global.document,
        nextFrame = win.requestAnimFrame;

    function Button(el, styles, options) {

        /**
         * Ensure the constructor is new-agnostic
         * Checks the receiver value is a proper instance of Button.
         * This ensures no error if instantiated without 'new' keyword.
         */
        if (!(this instanceof Button)) {
            return new Button(el, options);
        }

        this.hoverStateStyle  = styles.hoverStateStyle;
        this.activeStateStyle = styles.activeStateStyle;

        /**
         * Object containing the default configuration options.
         * (These defults are used when no options are provided on intantiation)
         * @property options
         * @type Object
         */
        this.options = {
            persistActiveState : true,
            onPointerEndCallback : null,
            perimeterDelta : 30
        };

        // Merge/replace the user defined options
        this._extend(this.options, options);

        this.options.persistActiveState = this.activeStateStyle === undefined
            ? false
            : this.options.persistActiveState;

        /**
         * The DOM node.
         * @property el
         * @type Object
         */
        this.el = typeof el === 'string' ? doc.querySelector(el) : el;

        this.bounds = this._getBounds();

        this.pointerIsDown = false;

        this.pointerIsInBounds = false;

        this.el.addEventListener(param.pointerStart, this, false);
        win.addEventListener(param.resizeEvent, this, false);
    }

    Button.prototype = {

        constructor: Button,

        /**
         * Handles events when they are fired.
         * @method handleEvent
         * @private
         */
        handleEvent : function (e) {
            switch (e.type) {
            case param.pointerStart:
                this._onStart(e);
                break;
            case param.pointerMove:
                this._onMove(e);
                break;
            case param.pointerEnd:
            case param.pointerCancel:
                this._onEnd(e);
                break;
            case param.resizeEvent:
                this._resize(e);
                break;
            }
        },

        /**
         * Called when a pointer or touch event starts.
         * @method _onStart
         * @private
         */
        _onStart : function (e) {
            var docOrButton = param.hasTouch ? this.el : doc;

            this.pointerIsDown = true;
            this.pointerIsInBounds = true;

            utils.addClass(this.el, this.hoverStateStyle);

            docOrButton.addEventListener(param.pointerMove, this, false);
            docOrButton.addEventListener(param.pointerEnd, this, false);
            docOrButton.addEventListener(param.pointerCancel, this, false);
            this.el.removeEventListener(param.pointerStart, this, false);

            e.preventDefault();
            e.stopPropagation();
        },

        _onMove : function (e) {
            if (!this.pointerIsDown) { return; }

            var point = param.hasTouch ? e.touches[0] : e;

            this.el.removeEventListener(param.pointerStart, this, false);

            this._handleMove(point.pageX, point.pageY);

            e.preventDefault();
            e.stopPropagation();
        },

        _handleMove : function (x, y) {
            if (x < this.bounds.left      ||
                    x > this.bounds.right ||
                    y < this.bounds.top   ||
                    y > this.bounds.bottom) {

                this.pointerIsInBounds = false;
                utils.removeClass(this.el, this.hoverStateStyle);

            } else {
                this.pointerIsInBounds = true;
                utils.addClass(this.el, this.hoverStateStyle);
            }
        },

        /**
         * Called when a pointer or touch event ends.
         * @method _onEnd
         * @private
         */
        _onEnd : function (e) {

            var docOrButton = param.hasTouch ? this.el : doc;

            this.pointerIsDown = false;

            utils.removeClass(this.el, this.hoverStateStyle);

            this.el.addEventListener(param.pointerStart, this, false);
            docOrButton.removeEventListener(param.pointerEnd, this, false);
            docOrButton.removeEventListener(param.pointerCancel, this, false);
            docOrButton.removeEventListener(param.pointerMove, this, false);

            if (this.options.persistActiveState && this.pointerIsInBounds) {
                utils.addClass(this.el, this.activeStateStyle);
            }

            if (this.options.onPointerEndCallback && this.pointerIsInBounds) {
                this.options.onPointerEndCallback.call(this);
            }

            this.pointerIsInBounds = false;

            e.preventDefault();
            e.stopPropagation();
        },

        /**
         * Enumerate properties of the 'source' object and copy them to the 'target'.
         * @method _extend
         * @private
         */
        _extend : function (target, source) {
            var i;
            if (typeof source === 'object') {
                for (i in source) {
                    if (source.hasOwnProperty(i)) {
                        target[i] = source[i];
                    }
                }
            }
        },

        _getBounds : function () {
            var delta = this.options.perimeterDelta,
                forcePaint = this.el.offsetHeight,
                bounds = this.el.getBoundingClientRect();

            return {
                top    : bounds.top - delta,
                right  : bounds.right + delta,
                bottom : bounds.bottom + delta,
                left   : bounds.left - delta,
                width  : bounds.right - bounds.left,
                height : bounds.bottom - bounds.top
            };
        },

        _resize : function () {
            this.bounds = this._getBounds();
        },

        destroy : function () {
            this.el.removeEventListener(param.pointerStart, this, false);
            win.removeEventListener(param.resizeEvent, this, false);
        }

    };

    return Button;

}(this));
<commit_msg>Add comments for YUIDoc<commit_after>var RCAM = RCAM || {};

RCAM.widgets = RCAM.widgets || {};

/**
 * Constructs a custom interactive Button.
 * @class Button
 * @constructor
 * @namespace RCAM.widgets
 * @requires RCAM.utils, RCAM.param
 * @param {Object} el A reference for the button element in the DOM.
 * @param {Object} styles The css stylenames for hover and active states.
 * @param {Object} options The custom configuration options.
 * @example
        var aButton = new RCAM.widgets.Button('.button', {
            hoverStateStyle  : 'button--hover',
            activeStateStyle : 'button--active'
        }, {
            persistActiveState : true,
            perimeterDelta : 50,
            onPointerEndCallback: function() {
                ...
            }
        });
 */
RCAM.widgets.Button = (function (global) {

    'use strict';

    /*jslint nomen:true*/

    var param = RCAM.param,
        utils = RCAM.utils,
        win   = global.window,
        doc   = global.document,
        nextFrame = win.requestAnimFrame;

    function Button(el, styles, options) {

        /**
         * Ensure the constructor is new-agnostic
         * Checks the receiver value is a proper instance of Button.
         * This ensures no error if instantiated without 'new' keyword.
         */
        if (!(this instanceof Button)) {
            return new Button(el, options);
        }

        this.hoverStateStyle  = styles.hoverStateStyle;
        this.activeStateStyle = styles.activeStateStyle;

        /**
         * Object containing the default configuration options.
         * (These defults are used when no options are provided on intantiation)
         * @property options
         * @type Object
         */
        this.options = {
            persistActiveState : true,
            onPointerEndCallback : null,
            perimeterDelta : 30
        };

        // Merge/replace the user defined options
        this._extend(this.options, options);

        // Normalise 'persistActiveState' state
        this.options.persistActiveState = this.activeStateStyle === undefined
            ? false
            : this.options.persistActiveState;

        /**
         * The DOM node.
         * @property el
         * @type Object
         */
        this.el = typeof el === 'string' ? doc.querySelector(el) : el;

        // Get the button bounds
        this.bounds = this._getBounds();

        this.pointerIsDown = false;

        this.pointerIsInBounds = false;

        this.el.addEventListener(param.pointerStart, this, false);
        win.addEventListener(param.resizeEvent, this, false);
    }

    Button.prototype = {

        constructor: Button,

        /**
         * Handles events when they are fired.
         * @method handleEvent
         * @private
         */
        handleEvent : function (e) {
            switch (e.type) {
            case param.pointerStart:
                this._onStart(e);
                break;
            case param.pointerMove:
                this._onMove(e);
                break;
            case param.pointerEnd:
            case param.pointerCancel:
                this._onEnd(e);
                break;
            case param.resizeEvent:
                this._resize(e);
                break;
            }
        },

        /**
         * Called when a pointer or touch event starts.
         * @method _onStart
         * @private
         */
        _onStart : function (e) {
            var docOrButton = param.hasTouch ? this.el : doc;

            this.pointerIsDown = true;
            this.pointerIsInBounds = true;

            utils.addClass(this.el, this.hoverStateStyle);

            docOrButton.addEventListener(param.pointerMove, this, false);
            docOrButton.addEventListener(param.pointerEnd, this, false);
            docOrButton.addEventListener(param.pointerCancel, this, false);
            this.el.removeEventListener(param.pointerStart, this, false);

            e.preventDefault();
            e.stopPropagation();
        },

        /**
         * Called when a pointer or touch event moves.
         * @method _onMove
         * @private
         */
        _onMove : function (e) {
            if (!this.pointerIsDown) { return; }

            var point = param.hasTouch ? e.touches[0] : e;

            this.el.removeEventListener(param.pointerStart, this, false);

            this._handleMove(point.pageX, point.pageY);

            e.preventDefault();
            e.stopPropagation();
        },

        /**
         * Called when a pointer or touch event moves.
         * @method _handleMove
         * @private
         */
        _handleMove : function (x, y) {
            if (x < this.bounds.left      ||
                    x > this.bounds.right ||
                    y < this.bounds.top   ||
                    y > this.bounds.bottom) {

                this.pointerIsInBounds = false;
                utils.removeClass(this.el, this.hoverStateStyle);

            } else {
                this.pointerIsInBounds = true;
                utils.addClass(this.el, this.hoverStateStyle);
            }
        },

        /**
         * Called when a pointer or touch event ends.
         * @method _onEnd
         * @private
         */
        _onEnd : function (e) {

            var docOrButton = param.hasTouch ? this.el : doc;

            this.pointerIsDown = false;

            utils.removeClass(this.el, this.hoverStateStyle);

            this.el.addEventListener(param.pointerStart, this, false);
            docOrButton.removeEventListener(param.pointerEnd, this, false);
            docOrButton.removeEventListener(param.pointerCancel, this, false);
            docOrButton.removeEventListener(param.pointerMove, this, false);

            if (this.options.persistActiveState && this.pointerIsInBounds) {
                utils.addClass(this.el, this.activeStateStyle);
            }

            if (this.options.onPointerEndCallback && this.pointerIsInBounds) {
                this.options.onPointerEndCallback.call(this);
            }

            this.pointerIsInBounds = false;

            e.preventDefault();
            e.stopPropagation();
        },

        /**
         * Enumerate properties of the 'source' object and copy them to the 'target'.
         * @method _extend
         * @private
         */
        _extend : function (target, source) {
            var i;
            if (typeof source === 'object') {
                for (i in source) {
                    if (source.hasOwnProperty(i)) {
                        target[i] = source[i];
                    }
                }
            }
        },

        _getBounds : function () {
            var delta = this.options.perimeterDelta,
                forcePaint = this.el.offsetHeight,
                bounds = this.el.getBoundingClientRect();

            return {
                top    : bounds.top - delta,
                right  : bounds.right + delta,
                bottom : bounds.bottom + delta,
                left   : bounds.left - delta,
                width  : bounds.right - bounds.left,
                height : bounds.bottom - bounds.top
            };
        },

        _resize : function () {
            this.bounds = this._getBounds();
        },

        destroy : function () {
            this.el.removeEventListener(param.pointerStart, this, false);
            win.removeEventListener(param.resizeEvent, this, false);
        }

    };

    return Button;

}(this));
<|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(fix): 2017-6-14 17:09:53<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>


<commit_before>// vim: ts=2:sw=2:expandtab:
var Whisper = Whisper || {};

(function () {
  'use strict';

  var Thread = Backbone.Model.extend({
    defaults: function() {
      return {
        image: '/images/default.png',
        unreadCount: 0,
        timestamp: new Date().getTime(),
        active: true
      };
    },

    validate: function(attributes, options) {
      var required = ['type', 'timestamp', 'image', 'name'];
      var missing = _.filter(required, function(attr) { return !attributes[attr]; });
      if (missing.length) { return "Thread must have " + missing; }
    },

    sendMessage: function(message) {
      var timestamp = Date.now();

      this.messages().add({ type: 'outgoing',
                            body: message,
                            threadId: this.id,
                            timestamp: timestamp }).save();

      this.save({ timestamp:   timestamp,
                  unreadCount: 0,
                  active:      true});

      if (this.get('type') == 'private') {
        var promise = textsecure.messaging.sendMessageToNumber(this.get('id'), message, []);
      }
      else {
        var promise = textsecure.messaging.sendMessageToGroup(this.get('groupId'), message, []);
      }
      promise.then(
        function(result) {
          console.log(result);
        }
      ).catch(
        function(error) {
          console.log(error);
        }
      );
    },

    messages: function() {
      if (!this.messageCollection) {
        this.messageCollection = new Whisper.MessageCollection([], {threadId: this.id});
      }
      return this.messageCollection;
    },
  });

  Whisper.Threads = new (Backbone.Collection.extend({
    localStorage: new Backbone.LocalStorage("Threads"),
    model: Thread,
    comparator: 'timestamp',
    findOrCreate: function(attributes) {
      var thread = Whisper.Threads.add(attributes, {merge: true});
      thread.save();
      return thread;
    },

    createGroup: function(recipients, name) {
      var attributes = {};
      attributes = {
        name      : name,
        numbers   : recipients,
        type      : 'group',
      };
      var thread = this.findOrCreate(attributes);
      return textsecure.messaging.createGroup(recipients, name).then(function(groupId) {
        thread.set('groupId', groupId);
        thread.save();
        return thread;
      });
    },

    findOrCreateForRecipient: function(recipient) {
      var attributes = {};
      attributes = {
        id        : recipient,
        name      : recipient,
        type      : 'private',
      };
      return this.findOrCreate(attributes);
    },

    findOrCreateForIncomingMessage: function(decrypted) {
      var attributes = {};
      if (decrypted.message.group) {
        attributes = {
          id         : decrypted.message.group.id,
          name       : decrypted.message.group.name,
          type       : 'group',
        };
      } else {
        attributes = {
          id         : decrypted.pushMessage.source,
          name       : decrypted.pushMessage.source,
          type       : 'private'
        };
      }
      return this.findOrCreate(attributes);
    }
  }))();
})();
<commit_msg>Group ids are stored in groupId<commit_after>// vim: ts=2:sw=2:expandtab:
var Whisper = Whisper || {};

(function () {
  'use strict';

  var Thread = Backbone.Model.extend({
    defaults: function() {
      return {
        image: '/images/default.png',
        unreadCount: 0,
        timestamp: new Date().getTime(),
        active: true
      };
    },

    validate: function(attributes, options) {
      var required = ['type', 'timestamp', 'image', 'name'];
      var missing = _.filter(required, function(attr) { return !attributes[attr]; });
      if (missing.length) { return "Thread must have " + missing; }
    },

    sendMessage: function(message) {
      var timestamp = Date.now();

      this.messages().add({ type: 'outgoing',
                            body: message,
                            threadId: this.id,
                            timestamp: timestamp }).save();

      this.save({ timestamp:   timestamp,
                  unreadCount: 0,
                  active:      true});

      if (this.get('type') == 'private') {
        var promise = textsecure.messaging.sendMessageToNumber(this.get('id'), message, []);
      }
      else {
        var promise = textsecure.messaging.sendMessageToGroup(this.get('groupId'), message, []);
      }
      promise.then(
        function(result) {
          console.log(result);
        }
      ).catch(
        function(error) {
          console.log(error);
        }
      );
    },

    messages: function() {
      if (!this.messageCollection) {
        this.messageCollection = new Whisper.MessageCollection([], {threadId: this.id});
      }
      return this.messageCollection;
    },
  });

  Whisper.Threads = new (Backbone.Collection.extend({
    localStorage: new Backbone.LocalStorage("Threads"),
    model: Thread,
    comparator: 'timestamp',
    findOrCreate: function(attributes) {
      var thread = Whisper.Threads.add(attributes, {merge: true});
      thread.save();
      return thread;
    },

    createGroup: function(recipients, name) {
      var attributes = {};
      attributes = {
        name      : name,
        numbers   : recipients,
        type      : 'group',
      };
      var thread = this.findOrCreate(attributes);
      return textsecure.messaging.createGroup(recipients, name).then(function(groupId) {
        thread.set('groupId', groupId);
        thread.save();
        return thread;
      });
    },

    findOrCreateForRecipient: function(recipient) {
      var attributes = {};
      attributes = {
        id        : recipient,
        name      : recipient,
        type      : 'private',
      };
      return this.findOrCreate(attributes);
    },

    findOrCreateForIncomingMessage: function(decrypted) {
      var attributes = {};
      if (decrypted.message.group) {
        attributes = {
          groupId    : decrypted.message.group.id,
          name       : decrypted.message.group.name,
          type       : 'group',
        };
      } else {
        attributes = {
          id         : decrypted.pushMessage.source,
          name       : decrypted.pushMessage.source,
          type       : 'private'
        };
      }
      return this.findOrCreate(attributes);
    }
  }))();
})();
<|endoftext|>


<commit_before>import DS from 'ember-data';

export default DS.Model.extend({
  name: DS.attr('string'),
  permalink: DS.attr('string'),
  prettyName: DS.attr('string'),
  taxons: DS.hasMany('taxon'),
  description: DS.attr('string'),

  root: function() {
    return this.get('taxons').findBy('parentId', undefined);
  }.property('taxons'),

  taxonsExcludingRoot: function() {
    return this.get('taxons').filterBy('parentId');
  }.property('taxons')
});
<commit_msg>find real root taxon, prevously returning nothing<commit_after>import DS from 'ember-data';

export default DS.Model.extend({
  name: DS.attr('string'),
  permalink: DS.attr('string'),
  prettyName: DS.attr('string'),
  taxons: DS.hasMany('taxon'),
  description: DS.attr('string'),

  root: function() {
    return this.get('taxons').findBy('parentId', null);
  }.property('taxons'),

  taxonsExcludingRoot: function() {
    return this.get('taxons').filterBy('parentId');
  }.property('taxons')
});
<|endoftext|>


<commit_before>function buildURL(account) {
    return "://" + account + ".com/";
}

function testMentionify(account) {
    QUnit.test("mentionify." + account, function( assert ) {
        var links = document.getElementById(account).getElementsByClassName("mentionified");
        for (var i = 0; i < links.length; i++) {
            href = links[i].href.slice(links[i].href.indexOf("://"));
            url = buildURL(account) + links[i].innerHTML.slice(1);
            assert.equal(href, url);
        }
    });
}

testMentionify("twitter");
<commit_msg>tested more accounts<commit_after>function buildURL(account) {
    return "://" + account + ".com/";
}

function testMentionify(account) {
    QUnit.test("mentionify." + account, function( assert ) {
        var links = document.getElementById(account).getElementsByClassName("mentionified");
        for (var i = 0; i < links.length; i++) {
            href = links[i].href.slice(links[i].href.indexOf("://"));
            url = buildURL(account) + links[i].innerHTML.slice(1);
            assert.equal(href, url);
        }
    });
}

testMentionify("twitter");
testMentionify("github");
testMentionify("facebook");
testMentionify("portfolium");
testMentionify("soundcloud");
<|endoftext|>


<commit_before>/**
 * @description Game         Configuration object
 * @return {object}  config  Object containing the game settings
 */
var config = (function () {
    'use strict';
    var config = {
        bounds: {
            top: 121,
            right: 780, //808-28
            bottom: 625,
            left: 0
        },
        rowHeight: 101,
        colWidth: 101,
        rows: 8,
        cols: 8,
        tiles: [
            'images/plain-sky-block.png',
            'images/bridge-block.png',
            'images/bridge-block.png',
            'images/bridge-block.png',
            'images/bridge-block.png',
            'images/bridge-block.png',
            'images/ground-block.png',
            'images/plain-ground-block.png'
        ],
        playerStep: {
            x: 25,
            y: 101
        },
        /* Enemies speed ratio to fine-tune the speed*/
        speedRatio: 10,
        collisionTolerance: {
            x: 30,
            y: 30,
        }
    };
    return config;
})();
<commit_msg>add assets to config<commit_after>/**
 * @description Game         Configuration object
 * @return {object}  config  Object containing the game settings
 */
var config = (function () {
    'use strict';
    var config = {
        bounds: {
            top: 121,
            right: 780, //808-28
            bottom: 625,
            left: 0
        },
        rowHeight: 101,
        colWidth: 101,
        rows: 8,
        cols: 8,
        tiles: [
            'images/plain-sky-block.png',
            'images/bridge-block.png',
            'images/bridge-block.png',
            'images/bridge-block.png',
            'images/bridge-block.png',
            'images/bridge-block.png',
            'images/ground-block.png',
            'images/plain-ground-block.png'
        ],
        assets: ['images/plain-sky-block.png',
            'images/sky-block.png',
            'images/bridge-block.png',
            'images/ground-block.png',
            'images/plain-ground-block.png',
            'images/goomba.png',
            'images/mario-right.png',
            'images/mario-left.png',
            'images/small-cloud.png',
            'images/big-cloud.png',
            'images/big-coin.png',
            'images/small-coin.png'
        ],
        playerStep: {
            x: 25,
            y: 101
        },
        /* Enemies speed ratio to fine-tune the speed*/
        speedRatio: 10,
        collisionTolerance: {
            x: 30,
            y: 30,
        }
    };
    return config;
})();
<|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(break): 2017-6-9 17:45:56<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>


<commit_before>define(
  [ 'module', 'jquery', 'domReady', 'obpconfig' ]
, function(module,$,domReady,obpconfig) {
    return {
         name : 'openbibl.event'
       , events: {
             "obp:filter-start"          : {}
           , "obp:filter-change"         : {}
           , "obp:filter-mode-change"    : {}
           , "obp:filter-complete"       : {}
           , "obp:bibliography-added"    : {}
           , "obp:search-term-change"    : {}
           , "obp:browse-term-change"    : {}
       }
       , subscribe : function(ev,obj,cb) {
            if (obpconfig.debug) obpconfig.console.log(obj + ' subscribed ' + ev);
            if (!(ev in this.events)) {
               throw "Unsupported event subscription for '"
                     + ev + "' from object '" + obj + "'";
            }
           this.events[ev][obj] = cb;
       }
       , unsubscribe : function(ev,obj) {
            if (!(ev in this.events)) {
               throw "Unsupported event subscription for '"
                     + ev + "' from object '" + obj + "'";
            }
            delete this.events[ev][obj];
       }
       , raise : function(ev,obj) {
            if (obpconfig.debug) obpconfig.console.log(obj + ' raised ' + ev);
            if (!(ev in this.events)) {
               throw "Unsupported event subscription for '"
                     + ev + "' from object '" + obj + "'";
            }
            var subscribers = this.events[ev] || {};
            for (var obj in subscribers) {
                subscribers[obj]();
            }
       }
    }
});
<commit_msg>removed unneeded field and whitespace<commit_after>define(
  [ 'module', 'jquery', 'domReady', 'obpconfig' ]
, function(module,$,domReady,obpconfig) {
    return {
         events: {
             "obp:filter-start"          : {}
           , "obp:filter-change"         : {}
           , "obp:filter-mode-change"    : {}
           , "obp:filter-complete"       : {}
           , "obp:bibliography-added"    : {}
           , "obp:search-term-change"    : {}
           , "obp:browse-term-change"    : {}
       }
       , subscribe : function(ev,obj,cb) {
            if (obpconfig.debug) obpconfig.console.log(obj + ' subscribed ' + ev);
            if (!(ev in this.events)) {
               throw "Unsupported event subscription for '"
                     + ev + "' from object '" + obj + "'";
            }
           this.events[ev][obj] = cb;
       }
       , unsubscribe : function(ev,obj) {
            if (!(ev in this.events)) {
               throw "Unsupported event subscription for '"
                     + ev + "' from object '" + obj + "'";
            }
            delete this.events[ev][obj];
       }
       , raise : function(ev,obj) {
            if (obpconfig.debug) obpconfig.console.log(obj + ' raised ' + ev);
            if (!(ev in this.events)) {
               throw "Unsupported event subscription for '"
                     + ev + "' from object '" + obj + "'";
            }
            var subscribers = this.events[ev] || {};
            for (var obj in subscribers) {
                subscribers[obj]();
            }
       }
    }
});
<|endoftext|>


<commit_before>/*exported Hungarian*/
var Hungarian = (function() {
  'use strict';

  /**
   * Array minima mutation functions.
   */
  function subtractRowMinima( row ) {
    var min = Math.min.apply( Math, row );

    for ( var i = 0, il = row.length; i < il; i++ ) {
      row[i] -= min;
    }

    return row;
  }

  function subtractRowsMinima( array ) {
    var i, il;
    for ( i = 0, il = array.length; i < il; i++ ) {
      subtractRowMinima( array[i] );
    }
  }

  /**
   * Takes a two-dimensional n by m matrix.
   */
  function subtractColMinima( array, colIndex ) {
    var min = Number.POSITIVE_INFINITY;
    var value;
    var i, il;
    // Create col array and find min.
    for ( i = 0, il = array.length; i < il; i++ ) {
      value = array[i][ colIndex ];
      if ( value < min ) {
        min = value;
      }
    }

    for ( i = 0, il = array.length; i < il; i++ ) {
      array[i][ colIndex ] -= min;
    }

    return array;
  }

  function subtractColsMinima( array ) {
    var i, il;
    for ( i = 0, il = array[0].length; i < il; i++ ) {
      subtractColMinima( array, i );
    }
  }

  function calculate( costMatrix ) {
    var coveredRows = [],
        coveredCols = [];

    subtractRowsMinima( costMatrix );
    subtractColsMinima( costMatrix );

    var marked = [];
    var i, il;
    for ( i = 0, il = costMatrix[0].length; i < il; i++ ) {
      marked.push( [] );
    }

    var j, jl;
    var row;
    for ( i = 0, il = costMatrix.length; i < il; i++ ) {
      row = costMatrix[i];
      for ( j = 0, jl = row.length; j < jl; j++ ) {
        // Mark uncovered zeros.
        if ( !costMatrix && !coveredRows[i] && !coveredCols[j] ) {
          marked[i][j] = true;
          coveredRows[i] = true;
          coveredCols[j] = true;
        }
      }
    }

    // Empty covers.
    coveredRows = [];
    coveredCols = [];

    // Cover each column containing a starred zero.
    for ( i = 0, il = costMatrix.length; i < il; i++ ) {
      for ( j = 0, jl = costMatrix[i].length; j < jl; j++ ) {
        if ( marked[i][j] ) {
          coveredCols[j] = true;
        }
      }
    }

    // Count covered columns.
    var count = 0;
    for ( i = 0, il = coveredCols.length; i < il; i++ ) {
      if ( coveredCols[i] ) {
        count++;
      }
    }

    // Finished.
    if ( count >= costMatrix[0].length ) {
      return;
    }
  }

  return {
    calculate: calculate
  };

}) ();
<commit_msg>registration[points]: Add Hungarian step 4 helper functions.<commit_after>/*exported Hungarian*/
var Hungarian = (function() {
  'use strict';

  /**
   * Array minima mutation functions.
   */
  function subtractRowMinima( row ) {
    var min = Math.min.apply( Math, row );

    for ( var i = 0, il = row.length; i < il; i++ ) {
      row[i] -= min;
    }

    return row;
  }

  function subtractRowsMinima( array ) {
    var i, il;
    for ( i = 0, il = array.length; i < il; i++ ) {
      subtractRowMinima( array[i] );
    }
  }

  /**
   * Takes a two-dimensional n by m matrix.
   */
  function subtractColMinima( array, colIndex ) {
    var min = Number.POSITIVE_INFINITY;
    var value;
    var i, il;
    // Create col array and find min.
    for ( i = 0, il = array.length; i < il; i++ ) {
      value = array[i][ colIndex ];
      if ( value < min ) {
        min = value;
      }
    }

    for ( i = 0, il = array.length; i < il; i++ ) {
      array[i][ colIndex ] -= min;
    }

    return array;
  }

  function subtractColsMinima( array ) {
    var i, il;
    for ( i = 0, il = array[0].length; i < il; i++ ) {
      subtractColMinima( array, i );
    }
  }

  function calculate( costMatrix ) {
    var coveredRows = [],
        coveredCols = [];

    subtractRowsMinima( costMatrix );
    subtractColsMinima( costMatrix );

    var marked = [];
    var i, il;
    for ( i = 0, il = costMatrix[0].length; i < il; i++ ) {
      marked.push( [] );
    }

    var j, jl;
    var row;
    for ( i = 0, il = costMatrix.length; i < il; i++ ) {
      row = costMatrix[i];
      for ( j = 0, jl = row.length; j < jl; j++ ) {
        // Mark uncovered zeros.
        if ( !costMatrix && !coveredRows[i] && !coveredCols[j] ) {
          marked[i][j] = true;
          coveredRows[i] = true;
          coveredCols[j] = true;
        }
      }
    }

    // Empty covers.
    coveredRows = [];
    coveredCols = [];

    // Cover each column containing a starred zero.
    for ( i = 0, il = costMatrix.length; i < il; i++ ) {
      for ( j = 0, jl = costMatrix[i].length; j < jl; j++ ) {
        if ( marked[i][j] ) {
          coveredCols[j] = true;
        }
      }
    }

    // Count covered columns.
    var count = 0;
    for ( i = 0, il = coveredCols.length; i < il; i++ ) {
      if ( coveredCols[i] ) {
        count++;
      }
    }

    // Finished.
    if ( count >= costMatrix[0].length ) {
      return;
    }

    // Step 4 helper functions.
    function findUncoveredZero( costMatrix, coveredRows, coveredCols ) {
      var row, col;
      var i, il;
      var j, jl;
      for ( i = 0, il = costMatrix.length; i < il; i++ ) {
        for ( j = 0, jl = costMatrix[i].length; j < jl; j++ ) {
          if ( !costMatrix[i][j] && !coveredRows[i] && !coveredCols[j] ) {
            // TODO: Out variable these.
            row = i;
            col = j;
            break;
          }
        }
      }

      return {
        row: row,
        col: col
      };
    }

    function isRowStarred( row ) {
      for ( var i = 0, il = row.length; i < il; i++ ) {
        if ( row[i] ) {
          return true;
        }
      }

      return false;
    }

    function starIndex( row ) {
      for ( var i = 0, il = row.length; i < il; i++ ) {
        if ( row[i] ) {
          return i;
        }
      }

      return -1;
    }
  }

  return {
    calculate: calculate
  };

}) ();
<|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(fix): 2017-7-3 09:36:51<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>


<commit_before>var test = require('tape');

// OAuth stub.
function oaStub() {
    var callback = arguments[arguments.length-1];

    var res = JSON.stringify({
        foo: "bar",
        arguments: arguments
    });

    callback(null, res, '');
}

var OAuth = require('oauth').OAuth;
OAuth.prototype.get    = oaStub;
OAuth.prototype.put    = oaStub;
OAuth.prototype.post   = oaStub;
OAuth.prototype.delete = oaStub;

test('maxcdn.create', function(t) {
    var maxcdn = require('../index');

    // setup
    t.throws(function() {
        maxcdn.create();
    });

    t.doesNotThrow(function() {
        maxcdn.create('alias', 'key', 'secret');
    });

    t.end();
});

test('MaxCDN', function(t) {
    var MaxCDN = require('../index');

    // setup
    t.throws(function() {
        new MaxCDN();
    });

    t.doesNotThrow(function() {
        new MaxCDN('alias', 'key', 'secret');
    });

    var m = new MaxCDN('alias', 'key', 'secret');
    t.equal(m.alias  , 'alias',  'setup:: alias');
    t.equal(m.key    , 'key',    'setup:: key');
    t.equal(m.secret , 'secret', 'setup:: secret');

    // _makeUrl
    t.equal(m._makeUrl('foobar'), 'https://rws.maxcdn.com/alias/foobar', '_makeURl');

    // _makeQuerystring
    t.equal(m._makeQuerystring({ foo: 'bar' }), 'foo=bar', '_makeQuerystring:: object');
    t.equal(m._makeQuerystring('{ "foo": "bar" }'), 'foo=bar', '_makeQuerystring:: json');
    t.equal(m._makeQuerystring('foo=bar'), 'foo=bar', '_makeQuerystring:: querystring');

    // _makeObject
    t.equal(m._makeObject({ foo: 'bar' }).foo, 'bar', '_makeObject:: object');
    t.equal(m._makeObject('{ "foo": "bar" }').foo, 'bar', '_makeObject:: json');
    t.equal(m._makeObject('foo=bar').foo, 'bar', '_makeQuery:: querystring');

    // _parse
    m._parse(function(err, data) {
        t.equal('SyntaxError', err.name, '_parse:: parse error');
        t.notOk(data, '_parse:: not data on parse error');
    })(null, 'foobar', '');

    m._parse(function(err, data) {
        t.ok(err, '_parse:: json w/ err');
        t.ok(data, '_parse:: json w/ data');
    })(new Error('connection error'), '{ "foo": "bar" }', '');

    m._parse(function(err, data) {
        t.error(err, '_parse:: no error');
        t.ok(data, '_parse:: json w/ data');
    })(null, '{ "foo": "bar" }', '');

    // get
    m.get('path', function(err, data) {
        t.error(err, 'get w/o error');
        t.equal(data.foo, 'bar', 'get w/ data');
        t.equal(data.arguments[0], 'https://rws.maxcdn.com/alias/path', 'get w/ path');
    });

    // put
    m.put('path', { data: 'data' }, function(err, data) {
        t.error(err, 'put w/o error');
        t.equal(data.foo, 'bar', 'put w/ data');
        t.equal(data.arguments[0], 'https://rws.maxcdn.com/alias/path', 'put w/ path');
        t.deepEqual(data.arguments[3], 'data=data', 'put sends data');
    });

    // post
    m.post('path', { data: 'data' }, function(err, data) {
        t.error(err, 'post w/o error');
        t.equal(data.foo, 'bar', 'post w/ data');
        t.equal(data.arguments[0], 'https://rws.maxcdn.com/alias/path', 'post w/ path');
        t.deepEqual(data.arguments[3], { data: 'data' }, 'post sends data');
    });

    // delete
    m.delete('path', function(err, data) {
        t.error(err, 'delete w/o error');
        t.equal(data.foo, 'bar', 'delete w/ data');
        t.equal(data.arguments[0], 'https://rws.maxcdn.com/alias/path', 'delete w/ path');
        t.notOk(data.arguments[3], 'delete sends data');
    });

    m.delete('path', 'path1', function(err, data) {
        t.error(err, 'delete (via Array) w/o error');
        t.equal(data.foo, 'bar', 'delete (via Array) w/ data');
        t.equal(data.arguments[0],
                'https://rws.maxcdn.com/alias/path?files=path1',
                'delete (via Array) w/ path');
        t.notOk(data.arguments[3], 'delete (via Array) sends data');
    });

    m.delete('path', ['path1','path2'], function(err, data) {
        t.error(err, 'delete (via Array) w/o error');
        t.equal(data.foo, 'bar', 'delete (via Array) w/ data');
        t.equal(data.arguments[0],
                'https://rws.maxcdn.com/alias/path?files[0]=path1&files[1]=path2',
                'delete (via Array) w/ path');
        t.notOk(data.arguments[3], 'delete (via Array) sends data');
    });

    m.delete('path', { files: ['path1','path2'] }, function(err, data) {
        t.error(err, 'delete (via Object) w/o error');
        t.equal(data.foo, 'bar', 'delete (via Object) w/ data');
        t.equal(data.arguments[0],
                'https://rws.maxcdn.com/alias/path?files[0]=path1&files[1]=path2',
                'delete (via Object) w/ path');
        t.notOk(data.arguments[3], 'delete (via Object) sends data');
    });

    m.del('path', function(err, data) {
        t.error(err, 'del w/o error');
        t.equal(data.foo, 'bar', 'del w/ data');
        t.equal(data.arguments[0], 'https://rws.maxcdn.com/alias/path', 'del w/ path');
        t.notOk(data.arguments[3], 'del sends data');
    });

    m.del('path', 'path1', function(err, data) {
        t.error(err, 'delete (via Array) w/o error');
        t.equal(data.foo, 'bar', 'delete (via Array) w/ data');
        t.equal(data.arguments[0],
                'https://rws.maxcdn.com/alias/path?files=path1',
                'delete (via Array) w/ path');
        t.notOk(data.arguments[3], 'delete (via Array) sends data');
    });

    m.del('path', ['path1','path2'], function(err, data) {
        t.error(err, 'del (via Array) w/o error');
        t.equal(data.foo, 'bar', 'del (via Array) w/ data');
        t.equal(data.arguments[0],
                'https://rws.maxcdn.com/alias/path?files[0]=path1&files[1]=path2',
                'del (via Array) w/ path');
        t.notOk(data.arguments[3], 'del (via Array) sends data');
    });

    m.del('path', { files: ['path1','path2'] }, function(err, data) {
        t.error(err, 'del (via Object) w/o error');
        t.equal(data.foo, 'bar', 'del (via Object) w/ data');
        t.equal(data.arguments[0],
                'https://rws.maxcdn.com/alias/path?files[0]=path1&files[1]=path2',
                'del (via Object) w/ path');
        t.notOk(data.arguments[3], 'del (via Object) sends data');
    });

    t.end();
});

// vim: ft=javascript ai sw=4 sts=4 et:
<commit_msg>removing extra unused addtion to test<commit_after>var test = require('tape');

// OAuth stub.
function oaStub() {
    var callback = arguments[arguments.length-1];

    var res = JSON.stringify({
        foo: "bar",
        arguments: arguments
    });

    callback(null, res, '');
}

var OAuth = require('oauth').OAuth;
OAuth.prototype.get    = oaStub;
OAuth.prototype.put    = oaStub;
OAuth.prototype.post   = oaStub;
OAuth.prototype.delete = oaStub;

test('maxcdn.create', function(t) {
    var maxcdn = require('../index');

    // setup
    t.throws(function() {
        maxcdn.create();
    });

    t.doesNotThrow(function() {
        maxcdn.create('alias', 'key', 'secret');
    });

    t.end();
});

test('MaxCDN', function(t) {
    var MaxCDN = require('../index');

    // setup
    t.throws(function() {
        new MaxCDN();
    });

    t.doesNotThrow(function() {
        new MaxCDN('alias', 'key', 'secret');
    });

    var m = new MaxCDN('alias', 'key', 'secret');
    t.equal(m.alias  , 'alias',  'setup:: alias');
    t.equal(m.key    , 'key',    'setup:: key');
    t.equal(m.secret , 'secret', 'setup:: secret');

    // _makeUrl
    t.equal(m._makeUrl('foobar'), 'https://rws.maxcdn.com/alias/foobar', '_makeURl');

    // _makeQuerystring
    t.equal(m._makeQuerystring({ foo: 'bar' }), 'foo=bar', '_makeQuerystring:: object');
    t.equal(m._makeQuerystring('{ "foo": "bar" }'), 'foo=bar', '_makeQuerystring:: json');
    t.equal(m._makeQuerystring('foo=bar'), 'foo=bar', '_makeQuerystring:: querystring');

    // _makeObject
    t.equal(m._makeObject({ foo: 'bar' }).foo, 'bar', '_makeObject:: object');
    t.equal(m._makeObject('{ "foo": "bar" }').foo, 'bar', '_makeObject:: json');
    t.equal(m._makeObject('foo=bar').foo, 'bar', '_makeQuery:: querystring');

    // _parse
    m._parse(function(err, data) {
        t.equal('SyntaxError', err.name, '_parse:: parse error');
        t.notOk(data, '_parse:: not data on parse error');
    })(null, 'foobar', '');

    m._parse(function(err, data) {
        t.ok(err, '_parse:: json w/ err');
        t.ok(data, '_parse:: json w/ data');
    })(new Error(), '{ "foo": "bar" }', '');

    m._parse(function(err, data) {
        t.error(err, '_parse:: no error');
        t.ok(data, '_parse:: json w/ data');
    })(null, '{ "foo": "bar" }', '');

    // get
    m.get('path', function(err, data) {
        t.error(err, 'get w/o error');
        t.equal(data.foo, 'bar', 'get w/ data');
        t.equal(data.arguments[0], 'https://rws.maxcdn.com/alias/path', 'get w/ path');
    });

    // put
    m.put('path', { data: 'data' }, function(err, data) {
        t.error(err, 'put w/o error');
        t.equal(data.foo, 'bar', 'put w/ data');
        t.equal(data.arguments[0], 'https://rws.maxcdn.com/alias/path', 'put w/ path');
        t.deepEqual(data.arguments[3], 'data=data', 'put sends data');
    });

    // post
    m.post('path', { data: 'data' }, function(err, data) {
        t.error(err, 'post w/o error');
        t.equal(data.foo, 'bar', 'post w/ data');
        t.equal(data.arguments[0], 'https://rws.maxcdn.com/alias/path', 'post w/ path');
        t.deepEqual(data.arguments[3], { data: 'data' }, 'post sends data');
    });

    // delete
    m.delete('path', function(err, data) {
        t.error(err, 'delete w/o error');
        t.equal(data.foo, 'bar', 'delete w/ data');
        t.equal(data.arguments[0], 'https://rws.maxcdn.com/alias/path', 'delete w/ path');
        t.notOk(data.arguments[3], 'delete sends data');
    });

    m.delete('path', 'path1', function(err, data) {
        t.error(err, 'delete (via Array) w/o error');
        t.equal(data.foo, 'bar', 'delete (via Array) w/ data');
        t.equal(data.arguments[0],
                'https://rws.maxcdn.com/alias/path?files=path1',
                'delete (via Array) w/ path');
        t.notOk(data.arguments[3], 'delete (via Array) sends data');
    });

    m.delete('path', ['path1','path2'], function(err, data) {
        t.error(err, 'delete (via Array) w/o error');
        t.equal(data.foo, 'bar', 'delete (via Array) w/ data');
        t.equal(data.arguments[0],
                'https://rws.maxcdn.com/alias/path?files[0]=path1&files[1]=path2',
                'delete (via Array) w/ path');
        t.notOk(data.arguments[3], 'delete (via Array) sends data');
    });

    m.delete('path', { files: ['path1','path2'] }, function(err, data) {
        t.error(err, 'delete (via Object) w/o error');
        t.equal(data.foo, 'bar', 'delete (via Object) w/ data');
        t.equal(data.arguments[0],
                'https://rws.maxcdn.com/alias/path?files[0]=path1&files[1]=path2',
                'delete (via Object) w/ path');
        t.notOk(data.arguments[3], 'delete (via Object) sends data');
    });

    m.del('path', function(err, data) {
        t.error(err, 'del w/o error');
        t.equal(data.foo, 'bar', 'del w/ data');
        t.equal(data.arguments[0], 'https://rws.maxcdn.com/alias/path', 'del w/ path');
        t.notOk(data.arguments[3], 'del sends data');
    });

    m.del('path', 'path1', function(err, data) {
        t.error(err, 'delete (via Array) w/o error');
        t.equal(data.foo, 'bar', 'delete (via Array) w/ data');
        t.equal(data.arguments[0],
                'https://rws.maxcdn.com/alias/path?files=path1',
                'delete (via Array) w/ path');
        t.notOk(data.arguments[3], 'delete (via Array) sends data');
    });

    m.del('path', ['path1','path2'], function(err, data) {
        t.error(err, 'del (via Array) w/o error');
        t.equal(data.foo, 'bar', 'del (via Array) w/ data');
        t.equal(data.arguments[0],
                'https://rws.maxcdn.com/alias/path?files[0]=path1&files[1]=path2',
                'del (via Array) w/ path');
        t.notOk(data.arguments[3], 'del (via Array) sends data');
    });

    m.del('path', { files: ['path1','path2'] }, function(err, data) {
        t.error(err, 'del (via Object) w/o error');
        t.equal(data.foo, 'bar', 'del (via Object) w/ data');
        t.equal(data.arguments[0],
                'https://rws.maxcdn.com/alias/path?files[0]=path1&files[1]=path2',
                'del (via Object) w/ path');
        t.notOk(data.arguments[3], 'del (via Object) sends data');
    });

    t.end();
});

// vim: ft=javascript ai sw=4 sts=4 et:
<|endoftext|>


<commit_before>angular.module('asics').controller('AdminCtrl', [
	'$mdToast',
	'$q',
	'$scope',
	'$state',
	'$stateParams',
	'admin',
	function ($mdToast, $q, $scope, $state, $stateParams, admin) {
		$scope.admin = admin;
        $scope.formData = {};

        $scope.$on('$viewContentLoaded', function () {
			updateGuestForm();
            clearForm();
        });

		$scope.guestType = 'athlete';

		$scope.updateForm = function () {
			updateGuestForm();
		};

        $scope.inviteGuest = function () {
            $mdToast.show(
                $mdToast.simple()
                    .textContent("Convite enviado com sucesso!")
                    .position('top right')
                    .hideDelay(3000)
                    .theme('error-toast')
            );
        };

        function clearForm() {
            $scope.formData = {
                guest: {
                    email: '',
                    name: '',
                    occupation: ''
                }
            };

            $scope.adminForm.$setPristine();
            $scope.adminForm.athlete.$touched = false;
            $scope.adminForm.guest.name.$touched = false;
            $scope.adminForm.guest.email.$touched = false;
            $scope.adminForm.guest.occupation.$touched = false;
        }

		function updateGuestForm() {
			if ($scope.guestType === 'athlete') {
				$scope.isAthlete = true;
				$('.other-field').hide();
				$('.athlete-field').show(200);
			} else {
				$scope.isAthlete = false;
				$('.athlete-field').hide();
				$('.other-field').show(200);
			}
		}

	}]);

angular.module('asics').directive('notBizarreAmericanDate', function ($window) {
	return {
		require: '^ngModel',
		restrict: 'A',
		link: function (scope, elm, attrs, ctrl) {

			ctrl.$formatters.unshift(function (modelValue) {
				// console.log(modelValue);
				if (!modelValue) return "";

				var varDate = new Date(modelValue);
				var string = ("0" + varDate.getDate()).slice(-2)
					+ "/" + ("0" + (varDate.getMonth() + 1)).slice(-2)
					+ "/" + varDate.getFullYear();
				// console.log(modelValue);
				// console.log(string);
				return string;
			});

			ctrl.$parsers.unshift(function (viewValue) {
				if (!viewValue) return "";

				viewValue = viewValue.slice(0, 10);
				var transformedInput = viewValue.replace(/[^0-9.]/g, "");

				var newViewString = transformedInput.slice(0, 2);
				if (transformedInput.length > 2)
					newViewString += "/" + transformedInput.slice(2, 4);
				if (transformedInput.length > 4)
					newViewString += "/" + transformedInput.slice(4);

				if (transformedInput != newViewString) {
					ctrl.$setViewValue(newViewString);
					ctrl.$render();
				}

				var m = transformedInput.match(/^(0[1-9]|[12][0-9]|3[01])(0[1-9]|1[012])(19|20)[0-9][0-9]$/g);
				if (m) {
					ctrl.$setValidity("pattern", true);
					var from = viewValue.split("/");
					return new Date(from[2], from[1] - 1, from[0]);
				} else {
					ctrl.$setValidity("pattern", false);
					return null;
				}
			});
		}
	};
});
<commit_msg>organized view controllers.<commit_after>angular.module('asics').controller('AdminCtrl', [
    '$mdToast',
    '$q',
    '$scope',
    '$state',
    '$stateParams',
    'admin',
    function ($mdToast, $q, $scope, $state, $stateParams, admin) {
        $scope.admin = admin;
        $scope.formData = {};

        $scope.$on('$viewContentLoaded', function () {
            updateGuestForm();
            clearForm();
        });

        $scope.guestType = 'athlete';

        $scope.updateForm = function () {
            updateGuestForm();
        };

        $scope.inviteGuest = function () {
            $mdToast.show(
                $mdToast.simple()
                    .textContent("Convite enviado com sucesso!")
                    .position('top right')
                    .hideDelay(3000)
                    .theme('error-toast')
            );
        };

        function clearForm() {
            $scope.formData = {
                guest: {
                    email: '',
                    name: '',
                    occupation: ''
                }
            };

            $scope.adminForm.$setPristine();
            $scope.adminForm.athlete.$touched = false;
            $scope.adminForm.guest.name.$touched = false;
            $scope.adminForm.guest.email.$touched = false;
            $scope.adminForm.guest.occupation.$touched = false;
        }

        function updateGuestForm() {
            if ($scope.guestType === 'athlete') {
                $scope.isAthlete = true;
                $('.other-field').hide();
                $('.athlete-field').show(200);
            } else {
                $scope.isAthlete = false;
                $('.athlete-field').hide();
                $('.other-field').show(200);
            }
        }
    }]);

angular.module('asics').directive('notBizarreAmericanDate', function ($window) {
    return {
        require: '^ngModel',
        restrict: 'A',
        link: function (scope, elm, attrs, ctrl) {

            ctrl.$formatters.unshift(function (modelValue) {
                // console.log(modelValue);
                if (!modelValue) return "";

                var varDate = new Date(modelValue);
                var string = ("0" + varDate.getDate()).slice(-2)
                    + "/" + ("0" + (varDate.getMonth() + 1)).slice(-2)
                    + "/" + varDate.getFullYear();
                // console.log(modelValue);
                // console.log(string);
                return string;
            });

            ctrl.$parsers.unshift(function (viewValue) {
                if (!viewValue) return "";

                viewValue = viewValue.slice(0, 10);
                var transformedInput = viewValue.replace(/[^0-9.]/g, "");

                var newViewString = transformedInput.slice(0, 2);
                if (transformedInput.length > 2)
                    newViewString += "/" + transformedInput.slice(2, 4);
                if (transformedInput.length > 4)
                    newViewString += "/" + transformedInput.slice(4);

                if (transformedInput != newViewString) {
                    ctrl.$setViewValue(newViewString);
                    ctrl.$render();
                }

                var m = transformedInput.match(/^(0[1-9]|[12][0-9]|3[01])(0[1-9]|1[012])(19|20)[0-9][0-9]$/g);
                if (m) {
                    ctrl.$setValidity("pattern", true);
                    var from = viewValue.split("/");
                    return new Date(from[2], from[1] - 1, from[0]);
                } else {
                    ctrl.$setValidity("pattern", false);
                    return null;
                }
            });
        }
    };
});
<|endoftext|>