<commit_before>/*****************************************************************************/
/* Client and Server Routes */
/*****************************************************************************/
// TODO: use these as per the Event Mind CLI tool.
//Router.configure({
//  templateNameConverter: 'upperCamelCase',
//  routeControllerNameConverter: 'upperCamelCase'
//});

Router.configure({
    layoutTemplate: 'devLayout',
    notFoundTemplate: 'devMain',
    loadingTemplate: 'loading'
});

Router.onRun(function () {Session.set("waiting-on", null);this.next(); });
Router.onBeforeAction(function() { Alerts.clearSeen();this.next(); });

var filters = {
    nProgressHook: function () {
        // we're done waiting on all subs
        if (this.ready()) {
            NProgress.done();
            this.next();
        } else {
            NProgress.start();
        }
    }
};

Router.onBeforeAction(filters.nProgressHook);

Meteor.startup(function () {
    Router.map(function () {
        this.route('loading');

        // reset password urls use hash fragments instead of url paths/query
        // strings so that the reset password token is not sent over the wire
        // on the http request

        this.route('reset-password', {
            template: 'devMain',
            layoutTemplate: 'devLayout',
            onRun: function () {
                var token = this.params.hash;
                Meteor.logout(function () {
                    Session.set("viewing-settings", true);
                    Session.set("set-password-token", token);
                    Session.set("settings-set-password", true);
                    // Session.set("enrolling", true) // do something special?
                });

                this.next();
            }
        });

        this.route('verify-email', {
            template: 'devMain',
            layoutTemplate: 'devLayout',
            action: function () {
                var self = this;
                var token = self.params.hash;
                Accounts.verifyEmail(token, function (err) {
                    if (!err) {
                        Alerts.throw({
                            message: "Your email address is now verified!",
                            type: "success", where: "main",
                            autoremove: 3000
                        });
                        Router.go('home');
                    } else {
                        Alerts.throw({
                            message: "Hmm, something went wrong: \""+err.reason +
                                "\". Try again?",
                            type: "danger", where: "main"
                        });
                        Session.set("viewing-settings", true);
                        Router.go('home');
                    }
                });
            }
        });

        this.route('leave-game', {
            template: 'devMain',
            layoutTemplate: 'devLayout',
            action: function () {
                var self = this;
                var token = self.params.hash;
                Meteor.call("leaveGameViaToken", token, function (err, res) {
                    if (!err) {
                        // Idempotently verify user's email,
                        // since they got the token via email.
                        Accounts.verifyEmail(token);
                        if (res.error) {
                            // e.g. "Leave-game link is for unknown game"
                            Alerts.throw({
                                message: res.error.reason, type: "danger", where: "main"
                            });
                            Router.go("home");
                        } else {
                            Alerts.throw({
                                message: "OK, you are no longer in this game.",
                                type: "success", where: res.gameId
                            });
                            Router.go("devDetail", {_id: res.gameId});
                        }
                    } else {
                        Alerts.throw({
                            message: "Hmm, something went wrong: \""+err.reason + "\".",
                            type: "danger", where: "main"
                        });
                        Router.go("home");
                    }
                });
            }
        });

        this.route('game-on', {
            template: 'devMain',
            layoutTemplate: 'devLayout',
            action: function () {
                var self = this;
                var token = self.params.hash;
                Meteor.call("gameOnViaToken", token, function (err, res) {
                  if (err || (res && res.error)) {
                    errorMessage = err ? "Hmm, something went wrong: \"" + err.reason + "\"." : res.error.reason;

                    Alerts.throw({
                      message: errorMessage, type: "danger", where: "main"
                    });

                    Router.go("home");
                  } else {
                    Alerts.throw({
                      message: "Woohoo! Players will be notified.",
                      type: "success", where: res.gameId
                    });

                    Router.go("devDetail", {_id: res.gameId, token: token });
                  }
                });
            }
        });

        this.route('cancel-game', {
            template: 'devMain',
            layoutTemplate: 'devLayout',
            action: function () {
                var self = this;
                var token = self.params.hash;
                Meteor.call("cancelGameViaToken", token, function (err, res) {
                    if (!err) {
                        Accounts.verifyEmail(token);
                        if (res.error) {
                            Alerts.throw({
                                message: res.error.reason, type: "danger", where: "main"
                            });
                            Router.go("home");
                        } else {
                            Alerts.throw({
                                message: "OK, your game is now cancelled, and players "
                                    + "will be notified.",
                                type: "success", where: "main"
                            });
                            Router.go("home");
                        }
                    } else {
                        Alerts.throw({
                            message: "Hmm, something went wrong: \""+err.reason + "\".",
                            type: "danger", where: "main"
                        });
                        Router.go("home");
                    }
                });
            }
        });

        // quite similar to 'leave-game' route
        this.route('unsubscribe-all', {
            template: 'devMain',
            layoutTemplate: 'devLayout',
            action: function () {
                var self = this;
                var token = self.params.hash;
                Meteor.call("unsubscribeAllViaToken", token, function (err, res) {
                    if (!err) {
                        // Idempotently verify user's email,
                        // since they got the token via email.
                        Accounts.verifyEmail(token);
                        if (res.error) {
                            // e.g. "Token provided in link is not an unsubscribe-all token"
                            Alerts.throw({
                                message: res.error.reason, type: "danger", where: "main"
                            });
                            Router.go("home");
                        } else {
                            Alerts.throw({
                                message: "OK, you will no longer receive emails "
                                    + "from Push Pickup.",
                                type: "success", where: "main"
                            });
                            Router.go("home");
                        }
                    } else {
                        Alerts.throw({
                            message: "Hmm, something went wrong: \""+err.reason + "\".",
                            type: "danger", where: "main"
                        });
                        Router.go("home");
                    }
                });
            }
        });

        this.route('enroll-account', {
            template: 'devMain',
            layoutTemplate: 'devLayout',
            onRun: function () {
                var token = this.params.hash;
                Meteor.logout(function () {
                    Session.set("viewing-settings", true);
                    Session.set("set-password-token", token);
                    Session.set("settings-set-password", true);
                    // Session.set("enrolling", true) // do something special?
                });

                this.next();
            }
        });

        // the home page. listing and searching for games
        this.route('home', {
            path: '/',
            template: 'devMain',
            layoutTemplate: 'devLayout'
        });

        // typical user interaction with a single game
        this.route('devDetail', {
            path: '/g/:_id/:token?',
            layoutTemplate: 'devLayout',
            onRun: function () {
                Session.set("joined-game", null);
                this.next();
            },
            waitOn: function () {
                return Meteor.subscribe('game', this.params._id);
            },
            onBeforeAction: function (pause) {
                Session.set("soloGame", this.params._id);
                this.next();
            },
            data: function () {
              var game = Games.findOne(this.params._id);

              if (game) {
                Session.set("gameExists", true);
              }

              return game;
            },
            action: function () {
              var token = this.params.token;

              if (Session.get("gameExists")) {
                this.render();

              } else {
                Router.go('home');

                Alerts.throw({
                  message: "Game not found",
                  type: "warning", where: "top"
                });
              }

              if (token) {
                Meteor.call("sendReminderEmailsViaToken", token, function (err, res) {
                  var errorMessage;

                  Accounts.verifyEmail(token);

                  if (err || (res && res.error)) {
                    errorMessage = err ? "Hmm, something went wrong: \"" + err.reason + "\"." : res.error.reason;

                    Alerts.throw({
                      message: errorMessage, type: "danger", where: "main"
                    });

                    Router.go("home");
                  }
                });
              }
            },
            onStop: function () {
              Session.set("soloGame", null);
              Session.set("gameExists", null);
            }
        });

        this.route('devAddGame', {
            path: '/addGame',
            template: 'devEditableGame',
            layoutTemplate: 'devLayout',
            onRun: function () {
                Session.set("selectedLocationPoint", null);
                Session.set("newGameDay", null);
                Session.set("newGameTime", null);
                InviteList.remove({});
                this.next();
            },
            waitOn: function() {
                Meteor.subscribe('recently-played');
            },
            data: function () {
                return {
                    action: 'add',
                    title: 'Add game',
                    submit: 'Add game'
                };
            }
        });

        this.route('invitePreviousPlayers', {
            path: 'invitePlayers',
            template: 'invitePreviousPlayers',
            layoutTemplate: 'devLayout'
        });

        this.route('devEditGame', {
            path: '/editGame/:_id',
            template: 'devEditableGame',
            layoutTemplate: 'devLayout',
            onRun: function () {
                Session.set("selectedLocationPoint", null);
                this.next();
            },
            waitOn: function () {
                return Meteor.subscribe('game', this.params._id);
            },
            onBeforeAction: function (pause) {
                Session.set("soloGame", this.params._id);
                this.next();
            },
            data: function () {
                return _.extend({
                    action: 'edit',
                    title: 'Edit game',
                    submit: 'Update game'
                }, Games.findOne(this.params._id));
            },
            action: function () {
                var self = this;
                var user = Meteor.user();
                var game = self.data();
                if (user && user._id === game.creator.userId ||
                    user && user.admin) {
                    self.render();
                } else {
                    Router.go('home');
                }
            }
        });

        this.route('adminView', {
            path: '/admin',
            onBeforeAction: function () {
                var user = Meteor.user();
                if (!user || !user.admin) {
                    this.render('home');
                }
                else {
                    this.next();
                }
            }
        });

    });
});<commit_msg>Fixed issue #164.<commit_after>/*****************************************************************************/
/* Client and Server Routes */
/*****************************************************************************/
// TODO: use these as per the Event Mind CLI tool.
//Router.configure({
//  templateNameConverter: 'upperCamelCase',
//  routeControllerNameConverter: 'upperCamelCase'
//});

Router.configure({
    layoutTemplate: 'devLayout',
    notFoundTemplate: 'devMain',
    loadingTemplate: 'loading'
});

Router.onRun(function () {Session.set("waiting-on", null);this.next(); });
Router.onBeforeAction(function() { Alerts.clearSeen();this.next(); });

var filters = {
    nProgressHook: function () {
        // we're done waiting on all subs
        if (this.ready()) {
            NProgress.done();
            this.next();
        } else {
            NProgress.start();
        }
    }
};

Router.onBeforeAction(filters.nProgressHook);

Meteor.startup(function () {
    Router.map(function () {
        this.route('loading');

        // reset password urls use hash fragments instead of url paths/query
        // strings so that the reset password token is not sent over the wire
        // on the http request

        this.route('reset-password', {
            template: 'devMain',
            layoutTemplate: 'devLayout',
            onRun: function () {
                var token = this.params.hash;
                Meteor.logout(function () {
                    Session.set("viewing-settings", true);
                    Session.set("set-password-token", token);
                    Session.set("settings-set-password", true);
                    // Session.set("enrolling", true) // do something special?
                });

                this.next();
            }
        });

        this.route('verify-email', {
            template: 'devMain',
            layoutTemplate: 'devLayout',
            action: function () {
                var self = this;
                var token = self.params.hash;
                Accounts.verifyEmail(token, function (err) {
                    if (!err) {
                        Alerts.throw({
                            message: "Your email address is now verified!",
                            type: "success", where: "main",
                            autoremove: 3000
                        });
                        Router.go('home');
                    } else {
                        Alerts.throw({
                            message: "Hmm, something went wrong: \""+err.reason +
                                "\". Try again?",
                            type: "danger", where: "main"
                        });
                        Session.set("viewing-settings", true);
                        Router.go('home');
                    }
                });
            }
        });

        this.route('leave-game', {
            template: 'devMain',
            layoutTemplate: 'devLayout',
            action: function () {
                var self = this;
                var token = self.params.hash;
                Meteor.call("leaveGameViaToken", token, function (err, res) {
                    if (!err) {
                        // Idempotently verify user's email,
                        // since they got the token via email.
                        Accounts.verifyEmail(token);
                        if (res.error) {
                            // e.g. "Leave-game link is for unknown game"
                            Alerts.throw({
                                message: res.error.reason, type: "danger", where: "main"
                            });
                            Router.go("home");
                        } else {
                            Alerts.throw({
                                message: "OK, you are no longer in this game.",
                                type: "success", where: res.gameId
                            });
                            Router.go("devDetail", {_id: res.gameId});
                        }
                    } else {
                        Alerts.throw({
                            message: "Hmm, something went wrong: \""+err.reason + "\".",
                            type: "danger", where: "main"
                        });
                        Router.go("home");
                    }
                });
            }
        });

        this.route('game-on', {
            template: 'devMain',
            layoutTemplate: 'devLayout',
            action: function () {
                var self = this;
                var token = self.params.hash;
                Meteor.call("gameOnViaToken", token, function (err, res) {
                  if (err || (res && res.error)) {
                    errorMessage = err ? "Hmm, something went wrong: \"" + err.reason + "\"." : res.error.reason;

                    Alerts.throw({
                      message: errorMessage, type: "danger", where: "main"
                    });

                    Router.go("home");
                  } else {
                    Alerts.throw({
                      message: "Woohoo! Players will be notified.",
                      type: "success", where: res.gameId
                    });

                    Router.go("devDetail", {_id: res.gameId, token: token });
                  }
                });
            }
        });

        this.route('cancel-game', {
            template: 'devMain',
            layoutTemplate: 'devLayout',
            action: function () {
                var self = this;
                var token = self.params.hash;
                Meteor.call("cancelGameViaToken", token, function (err, res) {
                    if (!err) {
                        Accounts.verifyEmail(token);
                        if (res.error) {
                            Alerts.throw({
                                message: res.error.reason, type: "danger", where: "main"
                            });
                            Router.go("home");
                        } else {
                            Alerts.throw({
                                message: "OK, your game is now cancelled, and players "
                                    + "will be notified.",
                                type: "success", where: "main"
                            });
                            Router.go("home");
                        }
                    } else {
                        Alerts.throw({
                            message: "Hmm, something went wrong: \""+err.reason + "\".",
                            type: "danger", where: "main"
                        });
                        Router.go("home");
                    }
                });
            }
        });

        // quite similar to 'leave-game' route
        this.route('unsubscribe-all', {
            template: 'devMain',
            layoutTemplate: 'devLayout',
            action: function () {
                var self = this;
                var token = self.params.hash;
                Meteor.call("unsubscribeAllViaToken", token, function (err, res) {
                    if (!err) {
                        // Idempotently verify user's email,
                        // since they got the token via email.
                        Accounts.verifyEmail(token);
                        if (res.error) {
                            // e.g. "Token provided in link is not an unsubscribe-all token"
                            Alerts.throw({
                                message: res.error.reason, type: "danger", where: "main"
                            });
                            Router.go("home");
                        } else {
                            Alerts.throw({
                                message: "OK, you will no longer receive emails "
                                    + "from Push Pickup.",
                                type: "success", where: "main"
                            });
                            Router.go("home");
                        }
                    } else {
                        Alerts.throw({
                            message: "Hmm, something went wrong: \""+err.reason + "\".",
                            type: "danger", where: "main"
                        });
                        Router.go("home");
                    }
                });
            }
        });

        this.route('enroll-account', {
            template: 'devMain',
            layoutTemplate: 'devLayout',
            onRun: function () {
                var token = this.params.hash;
                Meteor.logout(function () {
                    Session.set("viewing-settings", true);
                    Session.set("set-password-token", token);
                    Session.set("settings-set-password", true);
                    // Session.set("enrolling", true) // do something special?
                });

                this.next();
            }
        });

        // the home page. listing and searching for games
        this.route('home', {
            path: '/',
            template: 'devMain',
            layoutTemplate: 'devLayout'
        });

        // typical user interaction with a single game
        this.route('devDetail', {
            path: '/g/:_id/:token?',
            layoutTemplate: 'devLayout',
            onRun: function () {
                Session.set("joined-game", null);
                this.next();
            },
            waitOn: function () {
                return Meteor.subscribe('game', this.params._id);
            },
            onBeforeAction: function (pause) {
                Session.set("soloGame", this.params._id);
                this.next();
            },
            data: function () {
              var game = Games.findOne(this.params._id);

              if (game) {
                Session.set("gameExists", true);
              }

              return game;
            },
            action: function () {
              var token = this.params.token;

              if (Session.get("gameExists")) {
                this.render();

              } else {
                Router.go('home');

                Alerts.throw({
                  message: "Game not found",
                  type: "warning", where: "top"
                });
              }

              if (token) {
                Meteor.call("sendReminderEmailsViaToken", token, function (err, res) {
                  var errorMessage;

                  Accounts.verifyEmail(token);

                  if (err || (res && res.error)) {
                    errorMessage = err ? "Hmm, something went wrong: \"" + err.reason + "\"." : res.error.reason;

                    Alerts.throw({
                      message: errorMessage, type: "danger", where: "main"
                    });

                    Router.go("home");
                  }
                });
              }
            },
            onStop: function () {
              Session.set("soloGame", null);
              Session.set("gameExists", null);
            }
        });

        this.route('devAddGame', {
            path: '/addGame',
            template: 'devEditableGame',
            layoutTemplate: 'devLayout',
            onRun: function () {
                Session.set("selectedLocationPoint", null);
                Session.set("newGameDay", null);
                Session.set("newGameTime", null);
                InviteList.remove({});
                this.next();
            },
            waitOn: function() {
                Meteor.user() !== null && Meteor.subscribe('recently-played');
            },
            data: function () {
                return {
                    action: 'add',
                    title: 'Add game',
                    submit: 'Add game'
                };
            }
        });

        this.route('invitePreviousPlayers', {
            path: 'invitePlayers',
            template: 'invitePreviousPlayers',
            layoutTemplate: 'devLayout'
        });

        this.route('devEditGame', {
            path: '/editGame/:_id',
            template: 'devEditableGame',
            layoutTemplate: 'devLayout',
            onRun: function () {
                Session.set("selectedLocationPoint", null);
                this.next();
            },
            waitOn: function () {
                return Meteor.subscribe('game', this.params._id);
            },
            onBeforeAction: function (pause) {
                Session.set("soloGame", this.params._id);
                this.next();
            },
            data: function () {
                return _.extend({
                    action: 'edit',
                    title: 'Edit game',
                    submit: 'Update game'
                }, Games.findOne(this.params._id));
            },
            action: function () {
                var self = this;
                var user = Meteor.user();
                var game = self.data();
                if (user && user._id === game.creator.userId ||
                    user && user.admin) {
                    self.render();
                } else {
                    Router.go('home');
                }
            }
        });

        this.route('adminView', {
            path: '/admin',
            onBeforeAction: function () {
                var user = Meteor.user();
                if (!user || !user.admin) {
                    this.render('home');
                }
                else {
                    this.next();
                }
            }
        });

    });
});<|endoftext|>


<commit_before>function get(e){var t={Version:.1,Name:"SparrowJS",Author:"RoodyMonster"};if(e){if(window===this){return new get(e)}this.e=document.getElementById(e);return this}else{return t}return this}function extend(e){if(e instanceof get){return get()}else{return new extend(e)}}get.prototype={hide:function(){this.e.style.display="none";return this},show:function(){this.e.style.display="inherit";return this},bgcolor:function(e){this.e.style.background=e;return this},toggle:function(){if(this.e.style.display!=="none"){this.e.style.display="none"}else{this.e.style.display=""}return this},text:function(e){this.e.innerHTML=e;return this},size:function(e,t){this.e.style.height=t+"px";this.e.style.width=e+"px";return this},click:function(e){this.e.addEventListener("click",e,false);return this},color:function(e){this.e.style.color=e;return this},font_array:function(e,t){this.e.style.fontFamily=e;if(t){this.e.style.fontSize=t+"px"}else{return true}return this},isToggle:function(){if(this.e.style.diplay=="none"){return false}else{return true}}};extend.prototype={hide:function(){this.e.style.display="none";return this},show:function(){this.e.style.display="inherit";return this},bgcolor:function(e){this.e.style.background=e;return this},toggle:function(){if(this.e.style.display!=="none"){this.e.style.display="none"}else{this.e.style.display=""}return this},text:function(e){this.e.innerHTML=e;return this},size:function(e,t){this.e.style.height=t+"px";this.e.style.width=e+"px";return this},click:function(e){this.e.addEventListener("click",e,false);return this},color:function(e){this.e.style.color=e;return this},font_array:function(e,t){this.e.style.fontFamily=e;if(t){this.e.style.fontSize=t+"px"}else{return true}return this},isToggle:function(){if(this.e.style.diplay=="none"){return false}else{return true}}}
<commit_msg>Update sparrow.min.js<commit_after>!function(){var t=!1,n=/xyz/.test(function(){})?/\b_super\b/:/.*/;this.$=function(t){return t?window===this?new $(t):(this.e=document.getElementById(t),this):this},$.prototype={start:function(t){return window.onload=t,this},hide:function(){return this.e.style.display="none",this},show:function(){return this.e.style.display="inherit",this},bgcolor:function(t){return this.e.style.background=t,this},toggle:function(){return this.e.style.display="none"!==this.e.style.display?"none":"",this},text:function(t){return this.e.innerHTML=t,this},size:function(t,n){return this.e.style.height=n+"px",this.e.style.width=t+"px",this},click:function(t){return this.e.addEventListener("click",t,!1),this},color:function(t){return this.e.style.color=t,this},font_array:function(t,n,e){return this.e.style.fontFamily=t,n&&e?(this.e.style.fontSize=n+"px",this):!0},hover:function(t,n){return this.e.addEventListener("mouseover",t),this.e.addEventListener("mouseout",n||t),this},trans:function(t,n){return this.e.style.transition=t+" "+n+"s",this},val:function(){return this.e.value},bound:function(t){return this.e.getAttribute(t)},ibound:function(t){return this.e.getAttribute("data-"+t)},bindCustom:function(t,n){return this.e.setAttribute("data-"+t,n),this},change:function(t){return this.e.addEventListener("change",t,!1),this},focus:function(){return this.e===document.activeElement&&document.hasFocus()},submit:function(t){return this.e.addEventListener("submit",t,!1),this}},$.make=function(e){function i(){!t&&this.init&&this.init.apply(this,arguments)}var s=this.prototype;t=!0;var r=new this;t=!1;for(var u in e)r[u]="function"==typeof e[u]&&"function"==typeof s[u]&&n.test(e[u])?function(t,n){return function(){var e=this._super;this._super=s[t];var i=n.apply(this,arguments);return this._super=e,i}}(u,e[u]):e[u];return i.prototype=r,i.prototype.constructor=i,i.extend=arguments.callee,i}}();
<|endoftext|>


<commit_before>// -*- Mode: JavaScript; tab-width: 4 -*- vim:tabstop=4 syntax=javascript:
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/*global Stream: false, module: false */

module.version = 0.6;

module.cmd_g = module.cmd_google =
function cmd_google(dest, msg, nick, ident, host, conn, relay) {
	var data, stream = new Stream("http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=" + encodeURIComponent(msg));
	try {
		data = JSON.parse(decodeUTF8(stream.readFile()));
	} catch (ex) {}
	stream.close();
	if (!data) {
		conn.reply(dest, nick, "Google returned no data.");
		return true;
	}
	if (data.responseStatus != 200) {
		conn.reply(dest, nick, data.responseStatus, data.responseDetails);
		return true;
	}
	var res0 = data.responseData.results[0];
	conn.reply(dest, nick, res0 ? (
			res0.url + " - " + res0.titleNoFormatting + " - " +
			decodeHTML(res0.content).replace(/<\/?b>/g, "\002").replace(/\s+/g, " ")
		) : "No results.");
	return true;
};
<commit_msg>[google] HTML decode titles as well<commit_after>// -*- Mode: JavaScript; tab-width: 4 -*- vim:tabstop=4 syntax=javascript:
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/*global Stream: false, module: false */

module.version = 0.7;

module.cmd_g = module.cmd_google =
function cmd_google(dest, msg, nick, ident, host, conn, relay) {
	var data, stream = new Stream("http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=" + encodeURIComponent(msg));
	try {
		data = JSON.parse(decodeUTF8(stream.readFile()));
	} catch (ex) {}
	stream.close();
	if (!data) {
		conn.reply(dest, nick, "Google returned no data.");
		return true;
	}
	if (data.responseStatus != 200) {
		conn.reply(dest, nick, data.responseStatus, data.responseDetails);
		return true;
	}
	var res0 = data.responseData.results[0];
	conn.reply(dest, nick, res0 ? (
			res0.url + " - " + decodeHTML(res0.titleNoFormatting) + " - " +
			decodeHTML(res0.content).replace(/<\/?b>/g, "\002").replace(/\s+/g, " ")
		) : "No results.");
	return true;
};
<|endoftext|>


<commit_before>jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;

var shell = require('shelljs'),
    path = require('path'),
    fs = require('fs'),
    android_project = path.join(__dirname, 'fixtures', 'projects', 'native', 'android');

var orig_exec = shell.exec;

module.exports = {
    enabled:false,
    enable:function() {
        module.exports.enabled = true;
        require('shelljs').exec = function(cmd, opts) {
            // Match various commands to exec
            if (cmd.match(/android.bin.create/)) {
                var r = new RegExp(/android.bin.create"\s"([\/\\\w-_\.]*)"/);
                var dir = r.exec(cmd)[1];
                shell.cp('-r', android_project, path.join(dir, '..'));
                fs.chmodSync(path.join(dir, 'cordova', 'debug'), '754');
                return {code:0};
            }
            // Fire off to original exec
            return orig_exec.apply(null, arguments);
        }
    },
    disable:function() {
        module.exports.enabled = false;
        require('shelljs').exec = orig_exec;
    }
};

if (!module.exports.enabled) {
    module.exports.enable();
}
<commit_msg>added blackberry shortcut for project creation to speed up specs<commit_after>jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;

var shell = require('shelljs'),
    path = require('path'),
    fs = require('fs'),
    android_project = path.join(__dirname, 'fixtures', 'projects', 'native', 'android'),
    bb_project = path.join(__dirname, 'fixtures', 'projects', 'native', 'blackberry');

var orig_exec = shell.exec;

module.exports = {
    enabled:false,
    enable:function() {
        module.exports.enabled = true;
        require('shelljs').exec = function(cmd, opts) {
            // Match various commands to exec
            if (cmd.match(/android.bin.create/)) {
                var r = new RegExp(/android.bin.create"\s"([\/\\\w-_\.]*)"/);
                var dir = r.exec(cmd)[1];
                shell.cp('-r', android_project, path.join(dir, '..'));
                fs.chmodSync(path.join(dir, 'cordova', 'debug'), '754');
                return {code:0};
            } else if (cmd.match(/blackberry.bin.create/)) {
                var r = new RegExp(/blackberry.bin.create"\s"([\/\\\w-_\.]*)"/);
                var dir = r.exec(cmd)[1];
                var platformsDir = path.join(dir, '..');
                shell.cp('-r', bb_project, platformsDir);
                // TODO: will need to handle bb sub-platforms
                shell.mv(path.join(platformsDir, 'blackberry'), path.join(platformsDir, 'blackberry-10'));
                return {code:0};
            }
            // Fire off to original exec
            return orig_exec.apply(null, arguments);
        }
    },
    disable:function() {
        module.exports.enabled = false;
        require('shelljs').exec = orig_exec;
    }
};

if (!module.exports.enabled) {
    module.exports.enable();
}
<|endoftext|>


<commit_before>var gameTimer,
    startGameButton = document.getElementById('startGameButton'),
    pauseResumeGameButton = document.getElementById('pauseResumeGameButton'),
    canvasElement = document.getElementById('gameFieldCanvas'),
    isGameStarted = false,
    gameFieldCanvas = canvasElement.getContext('2d');

gameFieldCanvas.canvas.width = gameSettings.fieldWidth;
gameFieldCanvas.canvas.height = gameSettings.fieldHeight;

startGameButton.addEventListener('click', startGame, false);

var theBall = new Ball(10, 10, 5);
var p1Racket = new Racket(15, gameFieldCanvas.canvas.height / 2 - gameSettings.p1RacketSize / 2, gameSettings.racketWidth, gameSettings.p1RacketSize, gameSettings.p1RacketFillColor, gameSettings.p1RacketStrokeColor);
var p2Racket = new Racket(gameFieldCanvas.canvas.width - gameSettings.racketWidth - 15, gameFieldCanvas.canvas.height / 2 - gameSettings.p2RacketSize / 2, gameSettings.racketWidth, gameSettings.p2RacketSize, gameSettings.p2RacketFillColor, gameSettings.p2RacketStrokeColor);

document.addEventListener('keydown', function(event) {
    //If 'p' is pressed
    if (event.keyCode == 80) {
        pauseResumeGame();
    } else if (event.keyCode == 38) {
        //Up arrow key pressed
        p1Racket.topLeft_y -= 15;
    } else if (event.keyCode == 40) {
        //Down arrow key pressed
        p1Racket.topLeft_y += 15;
    } else if (event.keyCode == 87) {
        //W key pressed
        p2Racket.topLeft_y -= 15;
    } else if (event.keyCode == 83) {
        //S key pressed
        p2Racket.topLeft_y += 15;
    };
}, false);

function startGame() {
    if (!isGameStarted) {
        initializeSettings();
        $('#startGameButton').hide();
    };

    isGameStarted = true;
    gameTimer = setInterval(playGame, gameSettings.ballSpeed);
    playGame();
}

function playGame() {
    clearGameField();
    applyRandomBonus();
    p1Racket.draw(gameFieldCanvas);
    p2Racket.draw(gameFieldCanvas);
    theBall.draw(gameFieldCanvas);
    theBall.update(gameFieldCanvas);
    //drawBall();
    //moveBall();
}

function clearGameField() {
    gameFieldCanvas.clearRect(0, 0, gameFieldCanvas.canvas.width, gameFieldCanvas.canvas.height);
}

function pauseResumeGame() {
    if (isGameStarted) {
        if (!gameSettings.isGamePaused) {
            clearInterval(gameTimer);
            gameSettings.isGamePaused = true;
        } else {
            startGame();
            gameSettings.isGamePaused = false;
        }
    };
}

function endGame(winner) {
    drawNotificationOnCanvas(gameSettings[winner + 'Name'] + ' WON!!!');
    isGameStarted = false;
    $('#startGameButton').show();
}

//Game Menu
$(document).ready(function() {
    attachSettingsMenuEvents();
});<commit_msg>Rackets moving bug fixed<commit_after>var gameTimer,
    startGameButton = document.getElementById('startGameButton'),
    pauseResumeGameButton = document.getElementById('pauseResumeGameButton'),
    canvasElement = document.getElementById('gameFieldCanvas'),
    isGameStarted = false,
    gameFieldCanvas = canvasElement.getContext('2d');

gameFieldCanvas.canvas.width = gameSettings.fieldWidth;
gameFieldCanvas.canvas.height = gameSettings.fieldHeight;

startGameButton.addEventListener('click', startGame, false);

var theBall = new Ball(10, 10, 5);
var p1Racket = new Racket(15, gameFieldCanvas.canvas.height / 2 - gameSettings.p1RacketSize / 2, gameSettings.racketWidth, gameSettings.p1RacketSize, gameSettings.p1RacketFillColor, gameSettings.p1RacketStrokeColor);
var p2Racket = new Racket(gameFieldCanvas.canvas.width - gameSettings.racketWidth - 15, gameFieldCanvas.canvas.height / 2 - gameSettings.p2RacketSize / 2, gameSettings.racketWidth, gameSettings.p2RacketSize, gameSettings.p2RacketFillColor, gameSettings.p2RacketStrokeColor);

document.addEventListener('keydown', function(event) {
    //If 'p' is pressed
    if (event.keyCode == 80) {
        pauseResumeGame();
    } else if (event.keyCode == 38) {
        //Up arrow key pressed
        if (p1Racket.topLeft_y - 15 >= 0) {
            p1Racket.topLeft_y -= 15;
        };
    } else if (event.keyCode == 40) {
        //Down arrow key pressed
        if (p1Racket.topLeft_y + p1Racket.size_y + 15 <= gameFieldCanvas.canvas.height) {
            p1Racket.topLeft_y += 15;
        };
    } else if (event.keyCode == 87) {
        //W key pressed
        if (p2Racket.topLeft_y - 15 >= 0) {
            p2Racket.topLeft_y -= 15;
        };
    } else if (event.keyCode == 83) {
        //S key pressed
        if (p2Racket.topLeft_y + p2Racket.size_y + 15 <= gameFieldCanvas.canvas.height) {
            p2Racket.topLeft_y += 15;
        };
    };
}, false);

function startGame() {
    if (!isGameStarted) {
        initializeSettings();
        $('#startGameButton').hide();
    };

    isGameStarted = true;
    gameTimer = setInterval(playGame, gameSettings.ballSpeed);
    playGame();
}

function playGame() {
    clearGameField();
    applyRandomBonus();
    p1Racket.draw(gameFieldCanvas);
    p2Racket.draw(gameFieldCanvas);
    theBall.draw(gameFieldCanvas);
    theBall.update(gameFieldCanvas);
    //drawBall();
    //moveBall();
}

function clearGameField() {
    gameFieldCanvas.clearRect(0, 0, gameFieldCanvas.canvas.width, gameFieldCanvas.canvas.height);
}

function pauseResumeGame() {
    if (isGameStarted) {
        if (!gameSettings.isGamePaused) {
            clearInterval(gameTimer);
            gameSettings.isGamePaused = true;
        } else {
            startGame();
            gameSettings.isGamePaused = false;
        }
    };
}

function endGame(winner) {
    drawNotificationOnCanvas(gameSettings[winner + 'Name'] + ' WON!!!');
    isGameStarted = false;
    $('#startGameButton').show();
}

//Game Menu
$(document).ready(function() {
    attachSettingsMenuEvents();
});<|endoftext|>


<commit_before>'use strict';

/* eslint-env mocha */
// This is required before every test to remove boilerplate includes.
const rimraf = require('rimraf');
const config = require('./../lib/config');
const chai = require('chai');
const sinon = require('sinon');
const sinonChai = require('sinon-chai');
const chaiAsPromised = require('chai-as-promised');
const mocha = require('mocha');

// Add sinon assertions to chai
chai.use(sinonChai);

// Add promise helpers to chai
chai.use(chaiAsPromised);

global.expect = chai.expect;
global.sinon = sinon;
global.fixtures = require('./fixtures');
global.locator = require('./../lib/service-locator');

global.cleanupRepo = () => new Promise((resolve) => rimraf(config.tmp, resolve));

// include our inversion of control setups
require('./ioc');
<commit_msg>ensure temp directory for test runs<commit_after>'use strict';

/* eslint-env mocha */
// This is required before every test to remove boilerplate includes.
const rimraf = require('rimraf');
const config = require('./../lib/config');
const chai = require('chai');
const sinon = require('sinon');
const sinonChai = require('sinon-chai');
const chaiAsPromised = require('chai-as-promised');
const mocha = require('mocha');
const mkdirp = require('mkdirp');
const path = require('path');

// Add sinon assertions to chai
chai.use(sinonChai);

// Add promise helpers to chai
chai.use(chaiAsPromised);

global.expect = chai.expect;
global.sinon = sinon;
global.fixtures = require('./fixtures');
global.locator = require('./../lib/service-locator');

global.cleanupRepo = () => new Promise((resolve) => rimraf(config.tmp, resolve));
global.ensureTempDirectory = () => {
  return new Promise((resolve, reject) => {
    mkdirp(path.resolve(__dirname, '../tmp'), (err) => {
      if (err) return reject(err);
      resolve();
    });
  });
};

// include our inversion of control setups
require('./ioc');
<|endoftext|>


<commit_before>let fs = require('fs');
let InvitationRepository = artifacts.require("./InvitationRepository.sol");

if (process.argv.length < 5) {
  throw('usage: truffle exec scripts/invitation.js invitation_codes.txt');
}

let file = process.argv[4];
let invitation_codes = fs.readFileSync(file, 'utf8').trim().split('\n')

module.exports = async function(callback) {
  let invitation = await InvitationRepository.deployed();
  for (var i = 0; i < invitation_codes.length; i++) {
    var invitation_code = invitation_codes[i];
    var registered = await invitation.verify(invitation_code);
    if (registered) {
      var claimed = await invitation.report(invitation_code);
      console.log('invitation_code', invitation_code, ' is already registered. Claimed by ', claimed);
    }else{
      var encrypted_code = await invitation.encrypt.call(invitation_code);
      console.log('Adding', invitation_code, ' as ', encrypted_code);
      await invitation.add([encrypted_code]).catch(function(){});
    }
  }
}
<commit_msg>Handle both invitation and confirmation<commit_after>let fs = require('fs');
let InvitationRepository = artifacts.require("./InvitationRepository.sol");
let ConfirmationRepository = artifacts.require("./ConfirmationRepository.sol");
let repository;
let arg = require('yargs').argv;

console.log('args', arg);
if (!(arg.i && arg.t)) {
  throw('usage: truffle exec scripts/repository.js -t invitation|confirmation -i codes.txt');
}
module.exports = async function(callback) {
  let file = arg.i;
  console.log('file', file)
  switch (arg.t) {
    case 'invitation':
      repository = await InvitationRepository.deployed();
      break;
    case 'confirmation':
      repository = await ConfirmationRepository.deployed();
      break;
    default:
      throw('-t must be either invitation or confirmation');
  }
  console.log(2)
  let codes = fs.readFileSync(file, 'utf8').trim().split('\n');

  for (var i = 0; i < codes.length; i++) {
    console.log('code', codes[i])
    var code = codes[i];
    var registered = await repository.verify(code);
    if (registered) {
      var claimed = await repository.report(code);
      console.log('code', code, ' is already registered. Claimed by ', claimed);
    }else{
      var encrypted_code = await repository.encrypt.call(code);
      console.log('Adding', code, ' as ', encrypted_code);
      await repository.add([encrypted_code]).catch(function(){});
    }
  }
}
<|endoftext|>


<commit_before>const PREC = {
  AND: -1,
  OR: -1,
  NOT: 5,
  DEFINED: 10,
  ASSIGN: 15,
  CONDITIONAL: 20,
  RANGE: 25,
  BOOLEAN_OR: 30,
  BOOLEAN_AND: 35,
  RELATIONAL: 40,
  COMPARISON: 45,
  BITWISE_OR: 50,
  BITWISE_AND: 55,
  SHIFT: 60,
  ADDITIVE: 65,
  MULTIPLICATIVE: 70,
  UNARY_MINUS: 75,
  EXPONENTIAL: 80,
  COMPLEMENT: 85,
};

const unbalancedDelimiters = '!@#$%^&*)]}>|\\=/+-~`\'",.?:;_';
const identifierPattern = /[a-zA-Z_][a-zA-Z0-9_]*/;
const operators = ['..', '|', '^', '&', '<=>', '==', '===', '=~', '>', '>=', '<', '<=', '+', '-', '*', '/', '%', '**', '<<', '>>', '~', '+@', '-@', '[]', '[]='];

module.exports = grammar({
  name: 'ruby',

  extras: $ => [
    $.comment,
    $._line_break,
    /[ \t\r]/
  ],

  rules: {
    program: $ => sep($._statement, $._terminator),

    _statement: $ => choice(
      $._declaration,
      seq($._call, "do", optional("|", commaSep($._block_variable), "|"), sep($._statement, $._terminator), "end"),
      seq("undef", $._function_name),
      seq("alias", $._function_name, $._function_name),
      $.while_statement,
      $.until_statement,
      $.if_statement,
      $.unless_statement,
      $.for_statement,
      $.begin_statement,
      $.return_statement,
      $.if_modifier,
      $.unless_modifier,
      $.while_modifier,
      $.until_modifier,
      $._expression
    ),

    _declaration: $ => choice(
      $.method_declaration,
      $.class_declaration,
      $.module_declaration
    ),

    method_declaration: $ => seq(
      "def", $._function_name, choice(seq("(", optional($.argument_list), ")"), seq(optional($.argument_list), $._terminator)),
      sep($._statement, $._terminator),
      "end"
    ),

    argument_list: $ => commaSep1(seq(optional(choice("*", "&")), $.identifier)),

    class_declaration: $ => seq("class", $.identifier, optional(seq("<", sep1($.identifier, "::"))), $._terminator, sep($._statement, $._terminator), "end"),

    module_declaration: $ => seq("module", $.identifier, $._terminator, sep($._statement, $._terminator), "end"),

    while_statement: $ => seq("while", $.condition, $._statement_block),
    until_statement: $ => seq("until", $.condition, $._statement_block),
    if_statement: $ => seq("if", $.condition, $._then_elsif_else_block),
    unless_statement: $ => seq("unless", $.condition, $._then_else_block),
    for_statement: $ => seq("for", $._lhs, "in", $._expression, $._statement_block),
    begin_statement: $ => seq(
      "begin",
      sep($._statement, $._terminator),
      repeat($.rescue_block),
      optional($.else_block),
      optional($.ensure_block),
      "end"
    ),

    return_statement: $ => seq("return", optional($._expression)),

    if_modifier: $ => seq($._statement, "if", $._expression),
    unless_modifier: $ => seq($._statement, "unless", $._expression),
    while_modifier: $ => seq($._statement, "while", $._expression),
    until_modifier: $ => seq($._statement, "until", $._expression),

    condition: $ => $._expression,

    _statement_block: $ => choice(
      $._do_block,
      seq($._terminator, sep($._statement, $._terminator), "end")
    ),
    _do_block: $ => seq("do", sep($._statement, $._terminator), "end"),

    then_block: $ => seq(choice("then", $._terminator), sep($._statement, $._terminator)),
    else_block: $ => seq("else", sep($._statement, $._terminator)),
    rescue_block: $ => seq("rescue", commaSep($._argument), choice("do", $._terminator), sep($._statement, $._terminator)),
    ensure_block: $ => seq("ensure", sep($._statement, $._terminator)),

    _then_else_block: $ => seq($.then_block, optional($.else_block), "end"),
    _then_elsif_else_block: $ => seq(
      $.then_block,
      repeat(seq(
        "elsif", $.condition,
        $.then_block
      )),
      optional($.else_block),
      "end"
    ),

    _call: $ => choice($._function_call, $._command),

    _call_arguments: $ => choice(
      commaSep1($._argument),
      $._command
    ),

    _command: $ => choice(
      seq("super", $._call_arguments)
    ),
    _function_call: $ => choice("super"),

    _expression: $ => choice(
      $._argument,
      $.yield,
      $.and,
      $.or,
      $.not,
      $.defined,
      $.assignment,
      $.conditional,
      $.range,
      $.boolean_or,
      $.boolean_and,
      $.relational,
      $.comparison,
      $.bitwise_or,
      $.bitwise_and,
      $.shift,
      $.additive,
      $.multiplicative,
      $.unary_minus,
      $.exponential,
      $.complement,
      $._literal
    ),

    _argument: $ => choice($._primary),

    _primary: $ => choice(
      seq("(", sep($._statement, $._terminator), ")"),
      $._lhs
    ),

    scope_resolution_expression: $ => seq(optional($._primary), '::', $.identifier),
    subscript_expression: $ => seq($._primary, "[", commaSep($._argument), "]"),
    member_access: $ => seq($._primary, ".", $.identifier),
    yield: $ => seq("yield", optional($._expression)),

    and: $ => prec.left(PREC.AND, seq($._expression, "and", $._expression)),
    or: $ => prec.left(PREC.OR, seq($._expression, "or", $._expression)),
    not: $ => prec.right(PREC.NOT, seq("not", $._expression)),
    defined: $ => prec(PREC.DEFINED, seq("defined?", $._expression)),
    assignment: $ => prec.right(PREC.ASSIGN, seq($._lhs, '=', $._expression)),
    conditional: $ => prec.right(PREC.CONDITIONAL, seq($._expression, '?', $._expression, ':', $._expression)),
    range: $ => prec.right(PREC.RANGE, seq($._expression, choice('..', '...'), $._expression)),

    boolean_or: $ => prec.left(PREC.BOOLEAN_OR, seq($._expression, '||', $._expression)),
    boolean_and: $ => prec.left(PREC.BOOLEAN_OR, seq($._expression, '&&', $._expression)),

    relational: $ => prec.right(PREC.RELATIONAL, seq($._expression, choice('==', '!=', '===', '<=>', '=~', '!~'), $._expression)),
    comparison: $ => prec.left(PREC.COMPARISON, seq($._expression, choice('<', '<=', '>', '>='), $._expression)),

    bitwise_or: $ => prec.left(PREC.BITWISE_OR, seq($._expression, choice('^', '|'), $._expression)),
    bitwise_and: $ => prec.left(PREC.BITWISE_AND, seq($._expression, '&', $._expression)),
    shift: $ => prec.left(PREC.SHIFT, seq($._expression, choice('<<', '>>'), $._expression)),

    additive: $ => prec.left(PREC.ADDITIVE, seq($._expression, choice('-', '+'), $._expression)),
    multiplicative: $ => prec.left(PREC.MULTIPLICATIVE, seq($._expression, choice('*', '/', '%'), $._expression)),

    unary_minus: $ => prec.right(PREC.UNARY_MINUS, seq('-', $._expression)),

    exponential: $ => prec.right(PREC.EXPONENTIAL, seq($._expression, '**', $._expression)),

    complement: $ => prec.right(PREC.COMPLEMENT, seq(choice('!', '~', '+'), $._expression)),

    _block_variable: $ => choice($._lhs, $._mlhs),
    _mlhs: $ => choice(
      seq(commaSep1($._mlhs_item), optional(seq("*", optional($._lhs)))),
      seq("*", optional($._lhs))
    ),
    _mlhs_item: $ => choice($._lhs, seq("(", $._mlhs, ")")),
    _lhs: $ => choice(
      $._variable,
      $.scope_resolution_expression,
      $.subscript_expression,
      $.member_access
    ),
    _variable: $ => choice($.identifier , 'self'),

    identifier: $ => token(seq(repeat(choice('@', '$')), identifierPattern)),

    comment: $ => token(choice(
      seq('#', /.*/),
      seq(
        '=begin\n',
        repeat(/.*\n/),
        '=end\n'
      )
    )),

    _literal: $ => choice(
      $.symbol,
      $.integer,
      $.float,
      $.boolean,
      $.nil,
      $.string,
      $.subshell,
      $.array,
      $.regex
    ),

    symbol: $ => choice(
      token(seq(':', choice(identifierPattern, choice.apply(null, operators)))),
      seq(":'", $._single_quoted_continuation),
      seq(':"', $._double_quoted_continuation),
      choice.apply(null, unbalancedDelimiters.split('').map(d => stringBody('%s' + d, d))),
      seq(/%s/, $._uninterpolated_angle),
      seq(/%s/, $._uninterpolated_bracket),
      seq(/%s/, $._uninterpolated_paren),
      seq(/%s/, $._uninterpolated_brace)
    ),

    integer: $ => (/0b[01](_?[01])*|0[oO]?[0-7](_?[0-7])*|(0d)?\d(_?\d)*|0x[0-9a-fA-F](_?[0-9a-fA-F])*/),
    float: $ => (/\d(_?\d)*\.\d(_?\d)*([eE]\d(_?\d)*)?/),
    boolean: $ => choice('true', 'false', 'TRUE', 'FALSE'),
    nil: $ => choice('nil', 'NIL'),

    string: $ => choice(
      seq("'", $._single_quoted_continuation),
      seq('"', $._double_quoted_continuation),
      choice.apply(null, unbalancedDelimiters.split('').map(d => stringBody(RegExp('%(Q|)\\' + d), d, $.interpolation))),
      seq(/%Q?/, $._interpolated_angle),
      seq(/%Q?/, $._interpolated_bracket),
      seq(/%Q?/, $._interpolated_paren),
      seq(/%Q?/, $._interpolated_brace),
      choice.apply(null, unbalancedDelimiters.split('').map(d => stringBody('%q' + d, d))),
      seq('%q', $._uninterpolated_angle),
      seq('%q', $._uninterpolated_bracket),
      seq('%q', $._uninterpolated_paren),
      seq('%q', $._uninterpolated_brace)
    ),
    _single_quoted_continuation: $ => stringBody(blank(), "'"),
    _double_quoted_continuation: $ => stringBody(blank(), '"', $.interpolation),

    _interpolated_angle: $ => balancedStringBody($._interpolated_angle, '<', '>', $.interpolation),
    _interpolated_bracket: $ => balancedStringBody($._interpolated_bracket, '[', ']', $.interpolation),
    _interpolated_paren: $ => balancedStringBody($._interpolated_paren, '(', ')', $.interpolation),
    _interpolated_brace: $ => balancedStringBody($._interpolated_brace, '{', '}', $.interpolation),
    _uninterpolated_angle: $ => balancedStringBody($._uninterpolated_angle, '<', '>'),
    _uninterpolated_bracket: $ => balancedStringBody($._uninterpolated_bracket, '[', ']'),
    _uninterpolated_paren: $ => balancedStringBody($._uninterpolated_paren, '(', ')'),
    _uninterpolated_brace: $ => balancedStringBody($._uninterpolated_brace, '{', '}'),
    interpolation: $ => seq(token(prec(20, '#{')), $._expression, '}'),

    subshell: $ => choice(
      stringBody('`', '`'),
      choice.apply(null, unbalancedDelimiters.split('').map(d => stringBody('%x' + d, d, $.interpolation))),
      seq('%x', $._interpolated_angle),
      seq('%x', $._interpolated_bracket),
      seq('%x', $._interpolated_paren),
      seq('%x', $._interpolated_brace)
    ),

    array: $ => choice(
      seq('[', $._array_items, ']'),
      choice.apply(null, unbalancedDelimiters.split('').map(d => stringBody(RegExp('%[wi]\\' + d), d))),
      seq(/%[wi]/, $._uninterpolated_angle),
      seq(/%[wi]/, $._uninterpolated_bracket),
      seq(/%[wi]/, $._uninterpolated_paren),
      seq(/%[wi]/, $._uninterpolated_brace),
      choice.apply(null, unbalancedDelimiters.split('').map(d => stringBody(RegExp('%[WI]\\' + d), d, $.interpolation))),
      seq(/%[WI]/, $._interpolated_angle),
      seq(/%[WI]/, $._interpolated_bracket),
      seq(/%[WI]/, $._interpolated_paren),
      seq(/%[WI]/, $._interpolated_brace)
    ),
    _array_items: $ => optional(seq($._expression, optional(seq(',', $._array_items)))),

    // via https://github.com/tree-sitter/tree-sitter-javascript/blob/31d8b3de9f839057d46c304982b9c245b987bf38/grammar.js#L417-L426
    regex: $ => token(seq(
      '/',
      repeat(choice(
        seq('[', /[^\]\n]*/, ']'), // square-bracket-delimited character class
        seq('\\', /./),            // escaped character
        /[^/\\\[\n]/               // any character besides '[', '\', '/', '\n'
      )),
      '/',
      repeat(/a-z/)
    )),

    _function_name: $ => choice($.identifier, choice.apply(null, operators)),

    _line_break: $ => '\n',
    _terminator: $ => choice($._line_break, ';'),
  }
});

/// Describes the body of a string literal bounded by `open` and `close`, and optionally containing (potentially recursive) references to `insert`.
function stringBody (open, close, insert) {
  var contents = [ /\\./, RegExp('[^\\\\\\' + close + ']') ];
  if (typeof insert !== 'undefined') contents.push(insert);
  return seq(open, repeat(choice.apply(null, contents)), token(prec(20, close)));
}

function balancedStringBody (me, open, close, insert) {
  var contents = [ /\\./, me, RegExp('[^\\\\\\' + open + '\\' + close + ']') ];
  if (typeof insert !== 'undefined') contents.push(insert);
  return seq(open, repeat(choice.apply(null, contents)), close);
}

function sep1 (rule, separator) {
  return seq(rule, repeat(seq(separator, rule)));
}

function sep (rule, separator) {
  return optional(sep1(rule, separator));
}

function commaSep1 (rule) {
  return sep1(rule, ',')
}

function commaSep (rule) {
  return optional(commaSep1(rule));
}
<commit_msg>Add a helper for regexp bodies.<commit_after>const PREC = {
  AND: -1,
  OR: -1,
  NOT: 5,
  DEFINED: 10,
  ASSIGN: 15,
  CONDITIONAL: 20,
  RANGE: 25,
  BOOLEAN_OR: 30,
  BOOLEAN_AND: 35,
  RELATIONAL: 40,
  COMPARISON: 45,
  BITWISE_OR: 50,
  BITWISE_AND: 55,
  SHIFT: 60,
  ADDITIVE: 65,
  MULTIPLICATIVE: 70,
  UNARY_MINUS: 75,
  EXPONENTIAL: 80,
  COMPLEMENT: 85,
};

const unbalancedDelimiters = '!@#$%^&*)]}>|\\=/+-~`\'",.?:;_';
const identifierPattern = /[a-zA-Z_][a-zA-Z0-9_]*/;
const operators = ['..', '|', '^', '&', '<=>', '==', '===', '=~', '>', '>=', '<', '<=', '+', '-', '*', '/', '%', '**', '<<', '>>', '~', '+@', '-@', '[]', '[]='];

module.exports = grammar({
  name: 'ruby',

  extras: $ => [
    $.comment,
    $._line_break,
    /[ \t\r]/
  ],

  rules: {
    program: $ => sep($._statement, $._terminator),

    _statement: $ => choice(
      $._declaration,
      seq($._call, "do", optional("|", commaSep($._block_variable), "|"), sep($._statement, $._terminator), "end"),
      seq("undef", $._function_name),
      seq("alias", $._function_name, $._function_name),
      $.while_statement,
      $.until_statement,
      $.if_statement,
      $.unless_statement,
      $.for_statement,
      $.begin_statement,
      $.return_statement,
      $.if_modifier,
      $.unless_modifier,
      $.while_modifier,
      $.until_modifier,
      $._expression
    ),

    _declaration: $ => choice(
      $.method_declaration,
      $.class_declaration,
      $.module_declaration
    ),

    method_declaration: $ => seq(
      "def", $._function_name, choice(seq("(", optional($.argument_list), ")"), seq(optional($.argument_list), $._terminator)),
      sep($._statement, $._terminator),
      "end"
    ),

    argument_list: $ => commaSep1(seq(optional(choice("*", "&")), $.identifier)),

    class_declaration: $ => seq("class", $.identifier, optional(seq("<", sep1($.identifier, "::"))), $._terminator, sep($._statement, $._terminator), "end"),

    module_declaration: $ => seq("module", $.identifier, $._terminator, sep($._statement, $._terminator), "end"),

    while_statement: $ => seq("while", $.condition, $._statement_block),
    until_statement: $ => seq("until", $.condition, $._statement_block),
    if_statement: $ => seq("if", $.condition, $._then_elsif_else_block),
    unless_statement: $ => seq("unless", $.condition, $._then_else_block),
    for_statement: $ => seq("for", $._lhs, "in", $._expression, $._statement_block),
    begin_statement: $ => seq(
      "begin",
      sep($._statement, $._terminator),
      repeat($.rescue_block),
      optional($.else_block),
      optional($.ensure_block),
      "end"
    ),

    return_statement: $ => seq("return", optional($._expression)),

    if_modifier: $ => seq($._statement, "if", $._expression),
    unless_modifier: $ => seq($._statement, "unless", $._expression),
    while_modifier: $ => seq($._statement, "while", $._expression),
    until_modifier: $ => seq($._statement, "until", $._expression),

    condition: $ => $._expression,

    _statement_block: $ => choice(
      $._do_block,
      seq($._terminator, sep($._statement, $._terminator), "end")
    ),
    _do_block: $ => seq("do", sep($._statement, $._terminator), "end"),

    then_block: $ => seq(choice("then", $._terminator), sep($._statement, $._terminator)),
    else_block: $ => seq("else", sep($._statement, $._terminator)),
    rescue_block: $ => seq("rescue", commaSep($._argument), choice("do", $._terminator), sep($._statement, $._terminator)),
    ensure_block: $ => seq("ensure", sep($._statement, $._terminator)),

    _then_else_block: $ => seq($.then_block, optional($.else_block), "end"),
    _then_elsif_else_block: $ => seq(
      $.then_block,
      repeat(seq(
        "elsif", $.condition,
        $.then_block
      )),
      optional($.else_block),
      "end"
    ),

    _call: $ => choice($._function_call, $._command),

    _call_arguments: $ => choice(
      commaSep1($._argument),
      $._command
    ),

    _command: $ => choice(
      seq("super", $._call_arguments)
    ),
    _function_call: $ => choice("super"),

    _expression: $ => choice(
      $._argument,
      $.yield,
      $.and,
      $.or,
      $.not,
      $.defined,
      $.assignment,
      $.conditional,
      $.range,
      $.boolean_or,
      $.boolean_and,
      $.relational,
      $.comparison,
      $.bitwise_or,
      $.bitwise_and,
      $.shift,
      $.additive,
      $.multiplicative,
      $.unary_minus,
      $.exponential,
      $.complement,
      $._literal
    ),

    _argument: $ => choice($._primary),

    _primary: $ => choice(
      seq("(", sep($._statement, $._terminator), ")"),
      $._lhs
    ),

    scope_resolution_expression: $ => seq(optional($._primary), '::', $.identifier),
    subscript_expression: $ => seq($._primary, "[", commaSep($._argument), "]"),
    member_access: $ => seq($._primary, ".", $.identifier),
    yield: $ => seq("yield", optional($._expression)),

    and: $ => prec.left(PREC.AND, seq($._expression, "and", $._expression)),
    or: $ => prec.left(PREC.OR, seq($._expression, "or", $._expression)),
    not: $ => prec.right(PREC.NOT, seq("not", $._expression)),
    defined: $ => prec(PREC.DEFINED, seq("defined?", $._expression)),
    assignment: $ => prec.right(PREC.ASSIGN, seq($._lhs, '=', $._expression)),
    conditional: $ => prec.right(PREC.CONDITIONAL, seq($._expression, '?', $._expression, ':', $._expression)),
    range: $ => prec.right(PREC.RANGE, seq($._expression, choice('..', '...'), $._expression)),

    boolean_or: $ => prec.left(PREC.BOOLEAN_OR, seq($._expression, '||', $._expression)),
    boolean_and: $ => prec.left(PREC.BOOLEAN_OR, seq($._expression, '&&', $._expression)),

    relational: $ => prec.right(PREC.RELATIONAL, seq($._expression, choice('==', '!=', '===', '<=>', '=~', '!~'), $._expression)),
    comparison: $ => prec.left(PREC.COMPARISON, seq($._expression, choice('<', '<=', '>', '>='), $._expression)),

    bitwise_or: $ => prec.left(PREC.BITWISE_OR, seq($._expression, choice('^', '|'), $._expression)),
    bitwise_and: $ => prec.left(PREC.BITWISE_AND, seq($._expression, '&', $._expression)),
    shift: $ => prec.left(PREC.SHIFT, seq($._expression, choice('<<', '>>'), $._expression)),

    additive: $ => prec.left(PREC.ADDITIVE, seq($._expression, choice('-', '+'), $._expression)),
    multiplicative: $ => prec.left(PREC.MULTIPLICATIVE, seq($._expression, choice('*', '/', '%'), $._expression)),

    unary_minus: $ => prec.right(PREC.UNARY_MINUS, seq('-', $._expression)),

    exponential: $ => prec.right(PREC.EXPONENTIAL, seq($._expression, '**', $._expression)),

    complement: $ => prec.right(PREC.COMPLEMENT, seq(choice('!', '~', '+'), $._expression)),

    _block_variable: $ => choice($._lhs, $._mlhs),
    _mlhs: $ => choice(
      seq(commaSep1($._mlhs_item), optional(seq("*", optional($._lhs)))),
      seq("*", optional($._lhs))
    ),
    _mlhs_item: $ => choice($._lhs, seq("(", $._mlhs, ")")),
    _lhs: $ => choice(
      $._variable,
      $.scope_resolution_expression,
      $.subscript_expression,
      $.member_access
    ),
    _variable: $ => choice($.identifier , 'self'),

    identifier: $ => token(seq(repeat(choice('@', '$')), identifierPattern)),

    comment: $ => token(choice(
      seq('#', /.*/),
      seq(
        '=begin\n',
        repeat(/.*\n/),
        '=end\n'
      )
    )),

    _literal: $ => choice(
      $.symbol,
      $.integer,
      $.float,
      $.boolean,
      $.nil,
      $.string,
      $.subshell,
      $.array,
      $.regex
    ),

    symbol: $ => choice(
      token(seq(':', choice(identifierPattern, choice.apply(null, operators)))),
      seq(":'", $._single_quoted_continuation),
      seq(':"', $._double_quoted_continuation),
      choice.apply(null, unbalancedDelimiters.split('').map(d => stringBody('%s' + d, d))),
      seq(/%s/, $._uninterpolated_angle),
      seq(/%s/, $._uninterpolated_bracket),
      seq(/%s/, $._uninterpolated_paren),
      seq(/%s/, $._uninterpolated_brace)
    ),

    integer: $ => (/0b[01](_?[01])*|0[oO]?[0-7](_?[0-7])*|(0d)?\d(_?\d)*|0x[0-9a-fA-F](_?[0-9a-fA-F])*/),
    float: $ => (/\d(_?\d)*\.\d(_?\d)*([eE]\d(_?\d)*)?/),
    boolean: $ => choice('true', 'false', 'TRUE', 'FALSE'),
    nil: $ => choice('nil', 'NIL'),

    string: $ => choice(
      seq("'", $._single_quoted_continuation),
      seq('"', $._double_quoted_continuation),
      choice.apply(null, unbalancedDelimiters.split('').map(d => stringBody(RegExp('%(Q|)\\' + d), d, $.interpolation))),
      seq(/%Q?/, $._interpolated_angle),
      seq(/%Q?/, $._interpolated_bracket),
      seq(/%Q?/, $._interpolated_paren),
      seq(/%Q?/, $._interpolated_brace),
      choice.apply(null, unbalancedDelimiters.split('').map(d => stringBody('%q' + d, d))),
      seq('%q', $._uninterpolated_angle),
      seq('%q', $._uninterpolated_bracket),
      seq('%q', $._uninterpolated_paren),
      seq('%q', $._uninterpolated_brace)
    ),
    _single_quoted_continuation: $ => stringBody(blank(), "'"),
    _double_quoted_continuation: $ => stringBody(blank(), '"', $.interpolation),

    _interpolated_angle: $ => balancedStringBody($._interpolated_angle, '<', '>', $.interpolation),
    _interpolated_bracket: $ => balancedStringBody($._interpolated_bracket, '[', ']', $.interpolation),
    _interpolated_paren: $ => balancedStringBody($._interpolated_paren, '(', ')', $.interpolation),
    _interpolated_brace: $ => balancedStringBody($._interpolated_brace, '{', '}', $.interpolation),
    _uninterpolated_angle: $ => balancedStringBody($._uninterpolated_angle, '<', '>'),
    _uninterpolated_bracket: $ => balancedStringBody($._uninterpolated_bracket, '[', ']'),
    _uninterpolated_paren: $ => balancedStringBody($._uninterpolated_paren, '(', ')'),
    _uninterpolated_brace: $ => balancedStringBody($._uninterpolated_brace, '{', '}'),
    interpolation: $ => seq(token(prec(20, '#{')), $._expression, '}'),

    subshell: $ => choice(
      stringBody('`', '`'),
      choice.apply(null, unbalancedDelimiters.split('').map(d => stringBody('%x' + d, d, $.interpolation))),
      seq('%x', $._interpolated_angle),
      seq('%x', $._interpolated_bracket),
      seq('%x', $._interpolated_paren),
      seq('%x', $._interpolated_brace)
    ),

    array: $ => choice(
      seq('[', $._array_items, ']'),
      choice.apply(null, unbalancedDelimiters.split('').map(d => stringBody(RegExp('%[wi]\\' + d), d))),
      seq(/%[wi]/, $._uninterpolated_angle),
      seq(/%[wi]/, $._uninterpolated_bracket),
      seq(/%[wi]/, $._uninterpolated_paren),
      seq(/%[wi]/, $._uninterpolated_brace),
      choice.apply(null, unbalancedDelimiters.split('').map(d => stringBody(RegExp('%[WI]\\' + d), d, $.interpolation))),
      seq(/%[WI]/, $._interpolated_angle),
      seq(/%[WI]/, $._interpolated_bracket),
      seq(/%[WI]/, $._interpolated_paren),
      seq(/%[WI]/, $._interpolated_brace)
    ),
    _array_items: $ => optional(seq($._expression, optional(seq(',', $._array_items)))),

    // via https://github.com/tree-sitter/tree-sitter-javascript/blob/31d8b3de9f839057d46c304982b9c245b987bf38/grammar.js#L417-L426
    regex: $ => token(seq(
      '/',
      repeat(choice(
        seq('[', /[^\]\n]*/, ']'), // square-bracket-delimited character class
        seq('\\', /./),            // escaped character
        /[^/\\\[\n]/               // any character besides '[', '\', '/', '\n'
      )),
      '/',
      repeat(/a-z/)
    )),

    _function_name: $ => choice($.identifier, choice.apply(null, operators)),

    _line_break: $ => '\n',
    _terminator: $ => choice($._line_break, ';'),
  }
});

/// Describes the body of a string literal bounded by `open` and `close`, and optionally containing (potentially recursive) references to `insert`.
function stringBody (open, close, insert) {
  var contents = [ /\\./, RegExp('[^\\\\\\' + close + ']') ];
  if (typeof insert !== 'undefined') contents.push(insert);
  return seq(open, repeat(choice.apply(null, contents)), token(prec(20, close)));
}

function balancedStringBody (me, open, close, insert) {
  var contents = [ /\\./, me, RegExp('[^\\\\\\' + open + '\\' + close + ']') ];
  if (typeof insert !== 'undefined') contents.push(insert);
  return seq(open, repeat(choice.apply(null, contents)), close);
}

function regexBody (open, close, insert) {
  var contents = [
    seq('[', /[^\]\n]*/, ']'), // square-bracket-delimited character class
    seq('\\', /./),            // escaped character
    /[^/\\\[\n]/               // any character besides '[', '\', '/', '\n'
  ];
  if (typeof insert !== 'undefined') contents.push(insert);
  return seq(open, repeat(choice.apply(null, contents)), close, repeat(/a-z/));
}

function sep1 (rule, separator) {
  return seq(rule, repeat(seq(separator, rule)));
}

function sep (rule, separator) {
  return optional(sep1(rule, separator));
}

function commaSep1 (rule) {
  return sep1(rule, ',')
}

function commaSep (rule) {
  return optional(commaSep1(rule));
}
<|endoftext|>


<commit_before>$(function() {

  var food_data = loadFoodData();

  var url = chrome.extension.getURL("controls.html");
  $(".col-1 .col-3, .col-1 .col-2").append($('
').load(url, function() {

    $("a.show-hide-user-sub").click(function(e) {
      e.preventDefault();
      var hide = $(this).attr("href") == "#hide";
      $("#hide-user-subbed").val(hide ? 1 : 0);
      $("a.show-hide-user-sub").toggle();

      updateFilteredList();
    });

    $("#filter-by-text").keyup(updateFilteredList);

  }));
});

function updateFilteredList()
{
  var hideUserSubbed = $("#hide-user-subbed").val() == 1;
  var filterKeywords = $("#filter-by-text").val().toLowerCase().trim();

  $("ul#matching li a").each(function() {

    var foodName = $(this).html().toLowerCase();
    var filterMatch = foodName.indexOf(filterKeywords) != -1;

    var isUser = $(this).html().charAt(0) == "*";

    if ( (hideUserSubbed && isUser) || (filterKeywords.length > 0 && !filterMatch) )
    {
      $(this).parent().hide();
    } else {
      $(this).parent().show();
    }

  });
}

function loadFoodData()
{
  foods = new Array();

  $("ul#matching li a").each(function() {

    var url_tokens = $(this).attr("href").split("/");
    var food_id = url_tokens[url_tokens.length - 1];

    $(this).parent().addClass("food-" + food_id);

    $.get($(this).attr("href"), function(html) {
      // TODO
      // parse html, i.e. scrape confirmations, etc.
      // add the confirmation count to the li

      // TODO: .user_submitted doesn't always exist (my foods only?)
      var line = $(html).find(".user_submitted").html().match(/\d+/)[0]
      console.log(confirmations);

    });

  });

  return foods;
}<commit_msg>The confirmation counting doesn't quite work.<commit_after>$(function() {

  var food_data = loadFoodData();

  var url = chrome.extension.getURL("controls.html");
  $(".col-1 .col-3, .col-1 .col-2").append($('
').load(url, function() {

    $("a.show-hide-user-sub").click(function(e) {
      e.preventDefault();
      var hide = $(this).attr("href") == "#hide";
      $("#hide-user-subbed").val(hide ? 1 : 0);
      $("a.show-hide-user-sub").toggle();

      updateFilteredList();
    });

    $("#filter-by-text").keyup(updateFilteredList);

  }));
});

function updateFilteredList()
{
  var hideUserSubbed = $("#hide-user-subbed").val() == 1;
  var filterKeywords = $("#filter-by-text").val().toLowerCase().trim();

  $("ul#matching li a").each(function() {

    var foodName = $(this).html().toLowerCase();
    var filterMatch = foodName.indexOf(filterKeywords) != -1;

    var isUser = $(this).html().charAt(0) == "*";

    if ( (hideUserSubbed && isUser) || (filterKeywords.length > 0 && !filterMatch) )
    {
      $(this).parent().hide();
    } else {
      $(this).parent().show();
    }

  });
}

function loadFoodData()
{
  foods = new Array();

  $("ul#matching li a").each(function() {

    var url_tokens = $(this).attr("href").split("/");
    var food_id = url_tokens[url_tokens.length - 1];

    $(this).parent().addClass("food-" + food_id);

    $.get($(this).attr("href"), function(html) {
      // TODO
      // parse html, i.e. scrape confirmations, etc.
      // add the confirmation count to the li

      var line = $(html).find(".user_submitted").html();
      if (line !== undefined)
      {
        var confirmations = line.match(/\d+/)[0]

        $("ul#matching li.food-" + food_id).parent().append('' + confirmations + '
');
      }

    });

  });

  return foods;
}<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import {
  Animated,
  Image as ImageNative,
  StyleSheet,
  View,
  Platform,
  TouchableOpacity,
  TouchableHighlight,
  TouchableNativeFeedback,
  TouchableWithoutFeedback,
} from 'react-native';

import { nodeType } from '../helpers';
import { withTheme } from '../config';

class Image extends React.Component {
  state = {
    placeholderOpacity: new Animated.Value(1),
  };

  onLoad = (e) => {
    const { transition, onLoad } = this.props;

    if (!transition) {
      this.state.placeholderOpacity.setValue(0);
      return;
    }

    const minimumWait = 100;
    const staggerNonce = 200 * Math.random();

    setTimeout(
      () => {
        Animated.timing(this.state.placeholderOpacity, {
          toValue: 0,
          duration: 350,
          useNativeDriver: Platform.OS === 'android' ? false : true,
        }).start();
      },
      Platform.OS === 'android' ? 0 : Math.floor(minimumWait + staggerNonce)
    );

    onLoad && onLoad(e);
  };

  render() {
    const {
      onPress,
      onLongPress,
      Component = onPress || onLongPress ? TouchableOpacity : View,
      placeholderStyle,
      PlaceholderContent,
      containerStyle,
      style,
      ImageComponent,
      children,
      ...attributes
    } = this.props;
    const hasImage = Boolean(attributes.source);
    const { width, height, ...styleProps } = style;

    return (
      <Component
        onPress={onPress}
        onLongPress={onLongPress}
        accessibilityIgnoresInvertColors={true}
        style={StyleSheet.flatten([styles.container, containerStyle])}
      >
        <ImageComponent
          testID="RNE__Image"
          {...attributes}
          onLoad={this.onLoad}
          style={StyleSheet.flatten([
            StyleSheet.absoluteFill,
            {
              width: width,
              height: height,
            },
            styleProps,
          ])}
        />

        <Animated.View
          pointerEvents={hasImage ? 'none' : 'auto'}
          accessibilityElementsHidden={hasImage}
          importantForAccessibility={hasImage ? 'no-hide-descendants' : 'yes'}
          style={[
            styles.placeholderContainer,
            {
              opacity: hasImage ? this.state.placeholderOpacity : 1,
            },
          ]}
        >
          <View
            testID="RNE__Image__placeholder"
            style={StyleSheet.flatten([
              style,
              styles.placeholder,
              placeholderStyle,
            ])}
          >
            {PlaceholderContent}
          </View>
        </Animated.View>

        <View style={style}>{children}</View>
      </Component>
    );
  }
}

const styles = {
  container: {
    backgroundColor: 'transparent',
    position: 'relative',
    overflow: 'hidden',
  },
  placeholderContainer: {
    ...StyleSheet.absoluteFillObject,
  },
  placeholder: {
    backgroundColor: '#bdbdbd',
    alignItems: 'center',
    justifyContent: 'center',
  },
};

Image.propTypes = {
  ...ImageNative.propTypes,
  Component: PropTypes.oneOf([
    View,
    TouchableOpacity,
    TouchableHighlight,
    TouchableNativeFeedback,
    TouchableWithoutFeedback,
  ]),
  onPress: PropTypes.func,
  onLongPress: PropTypes.func,
  ImageComponent: PropTypes.elementType,
  PlaceholderContent: nodeType,
  containerStyle: PropTypes.oneOfType([PropTypes.object, PropTypes.array]),
  placeholderStyle: PropTypes.oneOfType([PropTypes.object, PropTypes.array]),
  transition: PropTypes.bool,
};

Image.defaultProps = {
  ImageComponent: ImageNative,
  style: {},
  transition: true,
};

Image.getSize = ImageNative.getSize;
Image.getSizeWithHeaders = ImageNative.getSizeWithHeaders;
Image.prefetch = ImageNative.prefetch;
Image.abortPrefetch = ImageNative.abortPrefetch;
Image.queryCache = ImageNative.queryCache;
Image.resolveAssetSource = ImageNative.resolveAssetSource;

export { Image };
export default withTheme(Image, 'Image');
<commit_msg>fix styled-components with Image comp (#2520)<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import {
  Animated,
  Image as ImageNative,
  StyleSheet,
  View,
  Platform,
  TouchableOpacity,
  TouchableHighlight,
  TouchableNativeFeedback,
  TouchableWithoutFeedback,
} from 'react-native';

import { nodeType } from '../helpers';
import { withTheme } from '../config';

class Image extends React.Component {
  state = {
    placeholderOpacity: new Animated.Value(1),
  };

  onLoad = (e) => {
    const { transition, onLoad } = this.props;

    if (!transition) {
      this.state.placeholderOpacity.setValue(0);
      return;
    }

    const minimumWait = 100;
    const staggerNonce = 200 * Math.random();

    setTimeout(
      () => {
        Animated.timing(this.state.placeholderOpacity, {
          toValue: 0,
          duration: 350,
          useNativeDriver: Platform.OS === 'android' ? false : true,
        }).start();
      },
      Platform.OS === 'android' ? 0 : Math.floor(minimumWait + staggerNonce)
    );

    onLoad && onLoad(e);
  };

  render() {
    const {
      onPress,
      onLongPress,
      Component = onPress || onLongPress ? TouchableOpacity : View,
      placeholderStyle,
      PlaceholderContent,
      containerStyle,
      style,
      ImageComponent,
      children,
      ...attributes
    } = this.props;
    const hasImage = Boolean(attributes.source);
    const { width, height, ...styleProps } = StyleSheet.flatten(style);

    return (
      <Component
        onPress={onPress}
        onLongPress={onLongPress}
        accessibilityIgnoresInvertColors={true}
        style={StyleSheet.flatten([styles.container, containerStyle])}
      >
        <ImageComponent
          testID="RNE__Image"
          {...attributes}
          onLoad={this.onLoad}
          style={StyleSheet.flatten([
            StyleSheet.absoluteFill,
            {
              width: width,
              height: height,
            },
            styleProps,
          ])}
        />

        <Animated.View
          pointerEvents={hasImage ? 'none' : 'auto'}
          accessibilityElementsHidden={hasImage}
          importantForAccessibility={hasImage ? 'no-hide-descendants' : 'yes'}
          style={[
            styles.placeholderContainer,
            {
              opacity: hasImage ? this.state.placeholderOpacity : 1,
            },
          ]}
        >
          <View
            testID="RNE__Image__placeholder"
            style={StyleSheet.flatten([
              style,
              styles.placeholder,
              placeholderStyle,
            ])}
          >
            {PlaceholderContent}
          </View>
        </Animated.View>

        <View style={style}>{children}</View>
      </Component>
    );
  }
}

const styles = {
  container: {
    backgroundColor: 'transparent',
    position: 'relative',
    overflow: 'hidden',
  },
  placeholderContainer: {
    ...StyleSheet.absoluteFillObject,
  },
  placeholder: {
    backgroundColor: '#bdbdbd',
    alignItems: 'center',
    justifyContent: 'center',
  },
};

Image.propTypes = {
  ...ImageNative.propTypes,
  Component: PropTypes.oneOf([
    View,
    TouchableOpacity,
    TouchableHighlight,
    TouchableNativeFeedback,
    TouchableWithoutFeedback,
  ]),
  onPress: PropTypes.func,
  onLongPress: PropTypes.func,
  ImageComponent: PropTypes.elementType,
  PlaceholderContent: nodeType,
  containerStyle: PropTypes.oneOfType([PropTypes.object, PropTypes.array]),
  placeholderStyle: PropTypes.oneOfType([PropTypes.object, PropTypes.array]),
  transition: PropTypes.bool,
};

Image.defaultProps = {
  ImageComponent: ImageNative,
  style: {},
  transition: true,
};

Image.getSize = ImageNative.getSize;
Image.getSizeWithHeaders = ImageNative.getSizeWithHeaders;
Image.prefetch = ImageNative.prefetch;
Image.abortPrefetch = ImageNative.abortPrefetch;
Image.queryCache = ImageNative.queryCache;
Image.resolveAssetSource = ImageNative.resolveAssetSource;

export { Image };
export default withTheme(Image, 'Image');
<|endoftext|>


<commit_before>'use strict';

var slateCli = require('slate-cli');
console.log(process.cwd());
slateCli.ensureSlate(process.cwd());
<commit_msg>Update the funciton call now quarry is more defined<commit_after>'use strict';

var slateCli = require('slate-cli');
slateCli.ensureSlateExists();
<|endoftext|>