<commit_before>module.exports = function($http, $q) {
    var value = "Hey I'm a value and I'm being returned from a factory!";

    var getEmojis = function() {
        var emojis = ['😄','😃','😀','😊','😉','😍','😘','😚','😗','😙','😜','😝','😛','😳','😁','😔','😌','😒','😞','😣','😢','😂','😭','😪','😥','😰','😅','😓','😩','😫','😨','😱','😠','😡','😤','😖','😆','😋','😷','😎','😴','😵','😲','😟','😦','😧','😈','👿','😮','😬','😐','😕','😯','😶','😇','😏','😑','👲','👳','👮','👷','💂','👶','👦','👧','👨','👩','👴','👵','👱','👼','👸','😺','😸','😻','😽','😼','🙀','😿','😹','😾','👹','👺','🙈','🙉','🙊','💀','👽','💩','🔥','✨','🌟','💫','💥','💢','💦','💧','💤','💨','👂','👀','👃','👅','👄','👍','👎','👌','👊','✊','✌','👋','✋','🖖','👐','👆','👇','👉','👈','🙌','🙏','☝','👏','💪','🚶','🏃','💃','👫','👪','👬','👭','💏','💑','👯','🙆','🙅','💁','🙋','💆','💇','💅','👰','🙎','🙍','🙇','🎩','👑','👒','👟','👞','👡','👠','👢','👕','👔','👚','👗','🎽','👖','👘','👙','💼','👜','👝','👛','👓','🎀','🌂','💄','💛','💙','💜','💚','❤','💔','💗','💓','💕','💖','💞','💘','💌','💋','💍','💎','👤','👥','💬','👣','💭','🐶','🐺','🐱','🐭','🐹','🐰','🐸','🐯','🐨','🐻','🐷','🐽','🐮','🐗','🐵','🐒','🐴','🐑','🐘','🐼','🐧','🐦','🐤','🐥','🐣','🐔','🐍','🐢','🐛','🐝','🐜','🐞','🐌','🐙','🐚','🐠','🐟','🐬','🐳','🐋','🐄','🐏','🐀','🐃','🐅','🐇','🐉','🐎','🐐','🐓','🐕','🐖','🐁','🐂','🐲','🐡','🐊','🐫','🐪','🐆','🐈','🐩','🐾','💐','🌸','🌷','🍀','🌹','🌻','🌺','🍁','🍃','🍂','🌿','🌾','🍄','🌵','🌴','🌲','🌳','🌰','🌱','🌼','🌐','🌞','🌝','🌚','🌑','🌒','🌓','🌔','🌕','🌖','🌗','🌘','🌜','🌛','🌙','🌍','🌎','🌏','🌋','🌌','🌠','⭐','☀','⛅','☁','⚡','☔','❄','⛄','🌀','🌁','🌈','🌊','🎍','💝','🎎','🎒','🎓','🎏','🎆','🎇','🎐','🎑','🎃','👻','🎅','🎄','🎁','🎋','🎉','🎊','🎈','🎌','🔮','🎥','📷','📹','📼','💿','📀','💽','💾','💻','📱','☎','📞','📟','📠','📡','📺','📻','🔊','🔉','🔈','🔇','🔔','🔕','📢','📣','⏳','⌛','⏰','⌚','🔓','🔒','🔏','🔐','🔑','🔎','💡','🔦','🔆','🔅','🔌','🔋','🔍','🛁','🛀','🚿','🚽','🔧','🔩','🔨','🚪','🚬','💣','🔫','🔪','💊','💉','💰','💴','💵','💷','💶','💳','💸','📲','📧','📥','📤','✉','📩','📨','📯','📫','📪','📬','📭','📮','📦','📝','📄','📃','📑','📊','📈','📉','📜','📋','📅','📆','📇','📁','📂','✂','📌','📎','✒','✏','📏','📐','📕','📗','📘','📙','📓','📔','📒','📚','📖','🔖','📛','🔬','🔭','📰','🎨','🎬','🎤','🎧','🎼','🎵','🎶','🎹','🎻','🎺','🎷','🎸','👾','🎮','🃏','🎴','🀄','🎲','🎯','🏈','🏀','⚽','⚾','🎾','🎱','🏉','🎳','⛳','🚵','🚴','🏁','🏇','🏆','🎿','🏂','🏊','🏄','🎣','☕','🍵','🍶','🍼','🍺','🍻','🍸','🍹','🍷','🍴','🍕','🍔','🍟','🍗','🍖','🍝','🍛','🍤','🍱','🍣','🍥','🍙','🍘','🍚','🍜','🍲','🍢','🍡','🍳','🍞','🍩','🍮','🍦','🍨','🍧','🎂','🍰','🍪','🍫','🍬','🍭','🍯','🍎','🍏','🍊','🍋','🍒','🍇','🍉','🍓','🍑','🍈','🍌','🍐','🍍','🍠','🍆','🍅','🌽','🏠','🏡','🏫','🏢','🏣','🏥','🏦','🏪','🏩','🏨','💒','⛪','🏬','🏤','🌇','🌆','🏯','🏰','⛺','🏭','🗼','🗾','🗻','🌄','🌅','🌃','🗽','🌉','🎠','🎡','⛲','🎢','🚢','⛵','🚤','🚣','⚓','🚀','✈','💺','🚁','🚂','🚊','🚉','🚞','🚆','🚄','🚅','🚈','🚇','🚝','🚋','🚃','🚎','🚌','🚍','🚙','🚘','🚗','🚕','🚖','🚛','🚚','🚨','🚓','🚔','🚒','🚑','🚐','🚲','🚡','🚟','🚠','🚜','💈','🚏','🎫','🚦','🚥','⚠','🚧','🔰','⛽','🏮','🎰','♨','🗿','🎪','🎭','📍','🚩'];

        return emojis
    }

    var getBackgrounds = function() {
        var deferred = $q.defer();
        var url = 'http://api.giphy.com/v1/gifs/trending?api_key=dc6zaTOxFJmzC';

        $http.get(url).then(function (res) {
            deferred.resolve(res.data);
        });

        return deferred.promise;

    }

    var getQuotes = function() {
        var quotes = [
            {text: 'Wut'},
            {text: 'HackDisrupt'},
            {text: 'techCrunchDisrupt'},
            {text: 'shipIt'},
            {text: 'mo so lo'},
            {text: '@clintonhalpin'},
            {text: '@iamnickvolpe'},
            {text: '@chrisnager'},
            {text: 'Jaaaavascript'},
            {text: 'Is your machine on'},
            {text: 'Your Face'}
        ];

        return quotes
    }

    var getSongs = function() {
        var songs = [
            {
                title: 'Jeopardy Theme',
                url: 'http://www.youtube.com/embed/0Wi8Fv0AJA4'
            },
            {
                title: 'Journey: Faithfully',
                url: 'http://www.youtube.com/embed/OMD8hBsA-RI'
            },
            {
                title: 'Van Halen: Panama',
                url: 'http://www.youtube.com/embed/w-NshzYK9y0',
            },
            {
                title: 'Jay-Z: Empire State of Mind',
                url: 'http://www.youtube.com/embed/Iv_1LVS3BdE',
            },
            {
                title: 'Gin and juice: Snoop Doggy Dogg',
                url: 'http://www.youtube.com/embed/0Cxr1-b6Xkc',
            },
            {
                title: 'Culture Club: Karma Chameleon',
                url: 'http://www.youtube.com/embed/JmcA9LIIXWw',
            },
            {
                title: 'Nicki Minaj: Starships',
                url: 'http://www.youtube.com/embed/SeIJmciN8mo',
            },
            {
                title: 'K-Ci & JoJo: All My Life',
                url: 'http://www.youtube.com/embed/DXvMT_mVbqw',
            },
            {
                title: 'Blink-182: All the Small Things',
                url: 'http://www.youtube.com/embed/9Ht5RZpzPqw',
            }
        ];

        return songs
    }

    var update = function(req) {
        value = req
        return req
    }

    var get = function(limit) {
        if(limit) {
            console.log('TODO: Request only on of the peices of data')
        }
        return {
            quotes: getQuotes(),
            emojis: getEmojis(),
            backgrounds: getBackgrounds(),
            songs: getSongs()
        }
    }

    return {
        get : get,
        update: update
    }
}
<commit_msg>Update qoutes<commit_after>module.exports = function($http, $q) {
    var value = "Hey I'm a value and I'm being returned from a factory!";

    var getEmojis = function() {
        var emojis = ['😄','😃','😀','😊','😉','😍','😘','😚','😗','😙','😜','😝','😛','😳','😁','😔','😌','😒','😞','😣','😢','😂','😭','😪','😥','😰','😅','😓','😩','😫','😨','😱','😠','😡','😤','😖','😆','😋','😷','😎','😴','😵','😲','😟','😦','😧','😈','👿','😮','😬','😐','😕','😯','😶','😇','😏','😑','👲','👳','👮','👷','💂','👶','👦','👧','👨','👩','👴','👵','👱','👼','👸','😺','😸','😻','😽','😼','🙀','😿','😹','😾','👹','👺','🙈','🙉','🙊','💀','👽','💩','🔥','✨','🌟','💫','💥','💢','💦','💧','💤','💨','👂','👀','👃','👅','👄','👍','👎','👌','👊','✊','✌','👋','✋','🖖','👐','👆','👇','👉','👈','🙌','🙏','☝','👏','💪','🚶','🏃','💃','👫','👪','👬','👭','💏','💑','👯','🙆','🙅','💁','🙋','💆','💇','💅','👰','🙎','🙍','🙇','🎩','👑','👒','👟','👞','👡','👠','👢','👕','👔','👚','👗','🎽','👖','👘','👙','💼','👜','👝','👛','👓','🎀','🌂','💄','💛','💙','💜','💚','❤','💔','💗','💓','💕','💖','💞','💘','💌','💋','💍','💎','👤','👥','💬','👣','💭','🐶','🐺','🐱','🐭','🐹','🐰','🐸','🐯','🐨','🐻','🐷','🐽','🐮','🐗','🐵','🐒','🐴','🐑','🐘','🐼','🐧','🐦','🐤','🐥','🐣','🐔','🐍','🐢','🐛','🐝','🐜','🐞','🐌','🐙','🐚','🐠','🐟','🐬','🐳','🐋','🐄','🐏','🐀','🐃','🐅','🐇','🐉','🐎','🐐','🐓','🐕','🐖','🐁','🐂','🐲','🐡','🐊','🐫','🐪','🐆','🐈','🐩','🐾','💐','🌸','🌷','🍀','🌹','🌻','🌺','🍁','🍃','🍂','🌿','🌾','🍄','🌵','🌴','🌲','🌳','🌰','🌱','🌼','🌐','🌞','🌝','🌚','🌑','🌒','🌓','🌔','🌕','🌖','🌗','🌘','🌜','🌛','🌙','🌍','🌎','🌏','🌋','🌌','🌠','⭐','☀','⛅','☁','⚡','☔','❄','⛄','🌀','🌁','🌈','🌊','🎍','💝','🎎','🎒','🎓','🎏','🎆','🎇','🎐','🎑','🎃','👻','🎅','🎄','🎁','🎋','🎉','🎊','🎈','🎌','🔮','🎥','📷','📹','📼','💿','📀','💽','💾','💻','📱','☎','📞','📟','📠','📡','📺','📻','🔊','🔉','🔈','🔇','🔔','🔕','📢','📣','⏳','⌛','⏰','⌚','🔓','🔒','🔏','🔐','🔑','🔎','💡','🔦','🔆','🔅','🔌','🔋','🔍','🛁','🛀','🚿','🚽','🔧','🔩','🔨','🚪','🚬','💣','🔫','🔪','💊','💉','💰','💴','💵','💷','💶','💳','💸','📲','📧','📥','📤','✉','📩','📨','📯','📫','📪','📬','📭','📮','📦','📝','📄','📃','📑','📊','📈','📉','📜','📋','📅','📆','📇','📁','📂','✂','📌','📎','✒','✏','📏','📐','📕','📗','📘','📙','📓','📔','📒','📚','📖','🔖','📛','🔬','🔭','📰','🎨','🎬','🎤','🎧','🎼','🎵','🎶','🎹','🎻','🎺','🎷','🎸','👾','🎮','🃏','🎴','🀄','🎲','🎯','🏈','🏀','⚽','⚾','🎾','🎱','🏉','🎳','⛳','🚵','🚴','🏁','🏇','🏆','🎿','🏂','🏊','🏄','🎣','☕','🍵','🍶','🍼','🍺','🍻','🍸','🍹','🍷','🍴','🍕','🍔','🍟','🍗','🍖','🍝','🍛','🍤','🍱','🍣','🍥','🍙','🍘','🍚','🍜','🍲','🍢','🍡','🍳','🍞','🍩','🍮','🍦','🍨','🍧','🎂','🍰','🍪','🍫','🍬','🍭','🍯','🍎','🍏','🍊','🍋','🍒','🍇','🍉','🍓','🍑','🍈','🍌','🍐','🍍','🍠','🍆','🍅','🌽','🏠','🏡','🏫','🏢','🏣','🏥','🏦','🏪','🏩','🏨','💒','⛪','🏬','🏤','🌇','🌆','🏯','🏰','⛺','🏭','🗼','🗾','🗻','🌄','🌅','🌃','🗽','🌉','🎠','🎡','⛲','🎢','🚢','⛵','🚤','🚣','⚓','🚀','✈','💺','🚁','🚂','🚊','🚉','🚞','🚆','🚄','🚅','🚈','🚇','🚝','🚋','🚃','🚎','🚌','🚍','🚙','🚘','🚗','🚕','🚖','🚛','🚚','🚨','🚓','🚔','🚒','🚑','🚐','🚲','🚡','🚟','🚠','🚜','💈','🚏','🎫','🚦','🚥','⚠','🚧','🔰','⛽','🏮','🎰','♨','🗿','🎪','🎭','📍','🚩'];

        return emojis
    }

    var getBackgrounds = function() {
        var deferred = $q.defer();
        var url = 'http://api.giphy.com/v1/gifs/trending?api_key=dc6zaTOxFJmzC';

        $http.get(url).then(function (res) {
            deferred.resolve(res.data);
        });

        return deferred.promise;

    }

    var getQuotes = function() {
        var quotes = [
            {text: 'Wut'},
            {text: 'HackDisrupt'},
            {text: 'techCrunchDisrupt'},
            {text: 'shipIt'},
            {text: 'mo so lo'},
            {text: '@clintonhalpin'},
            {text: '@iamnickvolpe'},
            {text: '@chrisnager'},
            {text: 'Jaaaavascript'},
            {text: 'Is your machine on'},
            {text: 'Your Face'}
            { title: "congratulations"},
            { title: "We've made it"},
            { title: "started from the bottom"},
            { title: "Business"},
            { title: "hollatchaboy"},
            { title: "get it"},
            { title: "that's what's up"},
            { title: "aww yiss"},
            { title: "jig"},
            { title: "#tbt"},
            { title: "#nofilter"},
            { title: "thank you"},
            { title: "thx"},
            { title: "congrats"},
            { title: "LOL"},
            { title: "miss you"},
            { title: "XOXOXO"},
            { title: "call me maybe"},
            { title: "yolo"},
            { title: "yup"},
            { title: "love you"},
            { title: "for real"},
            { title: "NO"},
            { title: "this"},
            { title: "me right now"},
            { title: "me irl"},
            { title: "this is so you"}
        ];

        return quotes
    }

    var getSongs = function() {
        var songs = [
            {
                title: 'Jeopardy Theme',
                url: 'http://www.youtube.com/embed/0Wi8Fv0AJA4'
            },
            {
                title: 'Journey: Faithfully',
                url: 'http://www.youtube.com/embed/OMD8hBsA-RI'
            },
            {
                title: 'Van Halen: Panama',
                url: 'http://www.youtube.com/embed/w-NshzYK9y0',
            },
            {
                title: 'Jay-Z: Empire State of Mind',
                url: 'http://www.youtube.com/embed/Iv_1LVS3BdE',
            },
            {
                title: 'Gin and juice: Snoop Doggy Dogg',
                url: 'http://www.youtube.com/embed/0Cxr1-b6Xkc',
            },
            {
                title: 'Culture Club: Karma Chameleon',
                url: 'http://www.youtube.com/embed/JmcA9LIIXWw',
            },
            {
                title: 'Nicki Minaj: Starships',
                url: 'http://www.youtube.com/embed/SeIJmciN8mo',
            },
            {
                title: 'K-Ci & JoJo: All My Life',
                url: 'http://www.youtube.com/embed/DXvMT_mVbqw',
            },
            {
                title: 'Blink-182: All the Small Things',
                url: 'http://www.youtube.com/embed/9Ht5RZpzPqw',
            }
        ];

        return songs
    }

    var update = function(req) {
        value = req
        return req
    }

    var get = function(limit) {
        if(limit) {
            console.log('TODO: Request only on of the peices of data')
        }
        return {
            quotes: getQuotes(),
            emojis: getEmojis(),
            backgrounds: getBackgrounds(),
            songs: getSongs()
        }
    }

    return {
        get : get,
        update: update
    }
}
<|endoftext|>


<commit_before>// use require to avoid errors in showroom webpack

// default sass
require('rc-datepicker/src/style.scss');
require('react-select/dist/default.css');

require('../src/Divider/divider.scss');
require('../src/DropdownMenu/dropdownMenu.scss');
require('../src/DropdownMenu/menu.scss');
require('../src/Panel/tabbedPanel.scss');
require('../src/collapsable-section/collapsableSection.scss');
require('../src/more-or-less/moreOrLess.scss');
require('../src/flex/flexView.scss');
require('../src/loading-spinner/style.scss');
require('../src/dropdown/dropdown.scss');
require('../src/confirmation-input/confirmationInput.scss');
require('../src/badge/badge.scss');
require('../src/toggle/toggle.scss');
require('../src/table/table.scss');
require('../src/Tooltip/tooltip.scss');
require('../src/Panel/panel.scss');
require('../src/Panel/tabbedPanel.scss');
require('../src/modal/modal.scss');
require('../src/ScrollView/scrollView.scss');
require('../src/kitchen-sink/style.scss');

// examples sass
require('../src/button/examples/button.scss');
require('../src/modal/examples/transition.scss');
<commit_msg>add more-or-less example style<commit_after>// use require to avoid errors in showroom webpack

// default sass
require('rc-datepicker/src/style.scss');
require('react-select/dist/default.css');

require('../src/Divider/divider.scss');
require('../src/DropdownMenu/dropdownMenu.scss');
require('../src/DropdownMenu/menu.scss');
require('../src/Panel/tabbedPanel.scss');
require('../src/collapsable-section/collapsableSection.scss');
require('../src/more-or-less/moreOrLess.scss');
require('../src/flex/flexView.scss');
require('../src/loading-spinner/style.scss');
require('../src/dropdown/dropdown.scss');
require('../src/confirmation-input/confirmationInput.scss');
require('../src/badge/badge.scss');
require('../src/toggle/toggle.scss');
require('../src/table/table.scss');
require('../src/Tooltip/tooltip.scss');
require('../src/Panel/panel.scss');
require('../src/Panel/tabbedPanel.scss');
require('../src/modal/modal.scss');
require('../src/ScrollView/scrollView.scss');
require('../src/kitchen-sink/style.scss');

// examples sass
require('../src/button/examples/button.scss');
require('../src/more-or-less/examples/default.scss');
require('../src/modal/examples/transition.scss');
<|endoftext|>


<commit_before>// ==UserScript==
// @match          http://imagecorn.com/img-*.html
// @match          http://imagepicsa.com/img-*.html
// @match          http://imgboo.me/img-*.html
// @match          http://imgcandy.net/img-*.html
// @match          http://imgcloud.co/img-*.html
// @match          http://imgcorn.com/img-*.html
// @match          http://imgmoney.com/img-*.html
// @match          http://imgonion.com/img-*.html
// @match          http://imgpay.me/img-*.html
// @match          http://imgrill.com/img-*.html
// @match          http://imgtube.net/img-*.html
// @match          http://pixup.us/img-*.html
// @match          http://www.imagefolks.com/img-*.html
// ==/UserScript==

$.register({
  rule: {
    host: /^(img(onion|rill|money|corn)|image(corn|picsa)|www\.imagefolks)\.com|img(candy|tube)\.net|imgcloud\.co|pixup\.us|img(boo|pay)\.me$/,
  },
  run: function () {
    'use strict';

    var node = $.$('#continuetoimage > form input');
    if (node) {
      // first pass
      node.click();
      return;
    }

    // second pass
    var o = $('img[alt="image"]');
    $.redirect(o.src);
  },
});

// ex: ts=2 sts=2 sw=2 et
// sublime: tab_size 2; translate_tabs_to_spaces true; detect_indentation false; use_tab_stops true;
// kate: space-indent on; indent-width 2;
<commit_msg>imgboo.me<commit_after>// ==UserScript==
// @match          http://imagecorn.com/img-*.html
// @match          http://imagepicsa.com/img-*.html
// @match          http://imgcandy.net/img-*.html
// @match          http://imgcloud.co/img-*.html
// @match          http://imgcorn.com/img-*.html
// @match          http://imgmoney.com/img-*.html
// @match          http://imgonion.com/img-*.html
// @match          http://imgpay.me/img-*.html
// @match          http://imgrill.com/img-*.html
// @match          http://imgtube.net/img-*.html
// @match          http://pixup.us/img-*.html
// @match          http://www.imagefolks.com/img-*.html
// ==/UserScript==

$.register({
  rule: {
    host: /^(img(onion|rill|money|corn)|image(corn|picsa)|www\.imagefolks)\.com|img(candy|tube)\.net|imgcloud\.co|pixup\.us|imgpay\.me$/,
  },
  run: function () {
    'use strict';

    var node = $.$('#continuetoimage > form input');
    if (node) {
      // first pass
      node.click();
      return;
    }

    // second pass
    var o = $('img[alt="image"]');
    $.redirect(o.src);
  },
});

// ex: ts=2 sts=2 sw=2 et
// sublime: tab_size 2; translate_tabs_to_spaces true; detect_indentation false; use_tab_stops true;
// kate: space-indent on; indent-width 2;
<|endoftext|>


<commit_before>/*global define,QUnit*/
define(function (require) {
    'use strict';
    var $ = require('jquery');
    var TemplateRepo = require('templateRepo');

    QUnit.module('templateRepo', {
        setup: function () {
            // given
            this.document = $('

');
            this.templateRepo = new TemplateRepo(this.document);
        }
    });

    QUnit.test('get', function () {
        // when
        var template = this.templateRepo.get('lemonSpan');
        var templateInstantiation = template({text: 'Lemon'});

        // then
        QUnit.equal(templateInstantiation, 'Lemon', 'templateInstantiation');
    });
});<commit_msg>fixed broken build<commit_after>/*global define,QUnit*/
define(function (require) {
    'use strict';
    var $ = require('jquery');
    var TemplateRepo = require('templateRepo');

    QUnit.module('templateRepo', {
        setup: function () {
            // given
            this.document = $('

');
            this.templateRepo = new TemplateRepo(this.document);
        }
    });

    QUnit.test('get', function () {
        // when
        var template = this.templateRepo.get('lemonSpan');
        var templateInstantiation = template({text: 'Lemon'});

        // then
        QUnit.equal(templateInstantiation, 'Lemon', 'templateInstantiation');
    });

    // ToDo: can we use promises instead of QUnit.throws?
    QUnit.test('get-failsWhenMissing', function () {
        // when + then
        QUnit.throws(function () { this.templateRepo.get('missing'); }, /assertion: template with id "missing" not found/, 'exception message');
    });
});<|endoftext|>


<commit_before>/*
Name:           requestbin
Description:    Node.js package to access the Requestb.in API
Author:         Franklin van de Meent (https://frankl.in)
License:        Unlicence (public domain, see LICENSE file)
Source & docs:  https://github.com/fvdm/nodejs-requestbin
Feedback:       https://github.com/fvdm/nodejs-requestbin/issues
*/

var httpreq = require ('httpreq');
var config = {
  timeout: 5000,
  iface: null,
  baseURL: null,
  userAgent: null
};

/**
 * Communicate with API
 *
 * @callback callback
 * @param method {string} - HTTP method, GET, POST, etc
 * @param path {string} - Request path
 * @param [props] {object} - Send query or POST parameters
 * @param callback {function} - `function (err, data) {}`
 * @return {void}
 */

function talk (method, path, props, callback) {
  var options = {
    url: (config.baseURL || 'http://requestb.in/api/v1/') + path,
    method: method,
    parameters: props,
    timeout: config.timeout || 5000,
    localAddress: config.iface,
    headers: {
      'Accept': 'application/json',
      'User-Agent': (config.userAgent || 'requestbin.js (https://github.com/fvdm/nodejs-requestbin)')
    }
  };

  if (typeof props === 'function') {
    callback = props;
    props = {};
  }

  httpreq.doRequest (options, function (err, res) {
    var data = res && res.body || null;
    var error = null;

    if (err) {
      error = new Error ('request failed');
      error.error = err;
      callback (error);
      return;
    }

    if (res && res.statusCode >= 300) {
      error = new Error ('HTTP error');
      return;
    }

    try {
      data = JSON.parse (data);
    } catch (e) {
      error = new Error ('invalid response');
    }

    if (error) {
      error.httpCode = res.statusCode;
      error.request = options;
      error.response = {
        headers: res.headers,
        body: data
      };
      callback (error);
      return;
    }

    callback (null, data);
  });
}

/**
 * Set configuration
 *
 * @param props {object} - Config parameters
 * @return {void}
 */

function methodConfig (props) (
  var name;

  for (name in props) {
    config [name] = props [name];
  }
}

/**
 * Create request instance
 *
 * @callback callback
 * @param [isPrivate = false] {boolean} - Make instance private
 * @param callback {function} - `function (err, data) {}`
 * @return {void}
 */

function methodCreate (isPrivate, callback) (
  var props = {};

  if (typeof isPrivate === 'function') {
    callback = isPrivate;
  } else if (isPrivate === true) {
    props.private = 'true';
  }

  talk ('POST', 'bins', props, callback);
}

/**
 * Get a request instance
 *
 * @callback callback
 * @param bin {string} - Bin instance ID
 * @param callback {function} - `function (err, data) {}`
 * @return {void}
 */

function methodGet (bin, callback) {
  talk ('GET', 'bins/' + bin, callback);
}

/**
 * Get received requests
 *
 * @callback callback
 * @param bin {string} - Bin instance ID
 * @param callback {function} - `function (err, data) {}`
 * @return {void}
 */

function methodRequests (bin, callback) {
  talk ('GET', 'bins/' + bin + '/requests', callback);
}

/**
 * Get one received request
 *
 * @callback callback
 * @param bin {string} - Bin instance ID
 * @param request {string} - Request ID
 * @param callback {function} - `function (err, data) {}`
 * @return {void}
 */

function methodRequest (bin, request, callback) {
  talk ('GET', 'bins/' + bin + '/requests/' + request, callback);
}

/**
 * Interface methods
 *
 * @return {object} - Methods
 */

module.exports = {
  config: methodConfig,
  create: methodCreate,
  get: methodGet,
  requests: methodRequests,
  request: methodRequest
};
<commit_msg>Refactor(main): Moved response handling to function<commit_after>/*
Name:           requestbin
Description:    Node.js package to access the Requestb.in API
Author:         Franklin van de Meent (https://frankl.in)
License:        Unlicence (public domain, see LICENSE file)
Source & docs:  https://github.com/fvdm/nodejs-requestbin
Feedback:       https://github.com/fvdm/nodejs-requestbin/issues
*/

var httpreq = require ('httpreq');
var config = {
  timeout: 5000,
  iface: null,
  baseURL: null,
  userAgent: null
};

/**
 * Process response
 *
 * argument order is to prevent callback
 * handler detection in code parsers
 *
 * @callback callback
 * @param res {object} - httpreq response
 * @param err {Error|null} - httpreq error
 * @param callback {function} - `function (err, data) {}`
 * @return {void}
 */

function processResponse (res, err, callback) {
  var data = res && res.body || null;
  var error = null;

  if (err) {
    error = new Error ('request failed');
    error.error = err;
    callback (error);
    return;
  }

  if (res && res.statusCode >= 300) {
    error = new Error ('HTTP error');
    return;
  }

  try {
    data = JSON.parse (data);
  } catch (e) {
    error = new Error ('invalid response');
  }

  if (error) {
    error.httpCode = res.statusCode;
    error.request = options;
    error.response = {
      headers: res.headers,
      body: data
    };

    callback (error);
    return;
  }

  callback (null, data);
}

/**
 * Communicate with API
 *
 * @callback callback
 * @param method {string} - HTTP method, GET, POST, etc
 * @param path {string} - Request path
 * @param [props] {object} - Send query or POST parameters
 * @param callback {function} - `function (err, data) {}`
 * @return {void}
 */

function talk (method, path, props, callback) {
  var options = {
    url: (config.baseURL || 'http://requestb.in/api/v1/') + path,
    method: method,
    parameters: props,
    timeout: config.timeout || 5000,
    localAddress: config.iface,
    headers: {
      'Accept': 'application/json',
      'User-Agent': (config.userAgent || 'requestbin.js (https://github.com/fvdm/nodejs-requestbin)')
    }
  };

  if (typeof props === 'function') {
    callback = props;
    props = {};
  }

  httpreq.doRequest (options, function (err, res) {
    processResponse (res, err, callback);
  });
}

/**
 * Set configuration
 *
 * @param props {object} - Config parameters
 * @return {void}
 */

function methodConfig (props) (
  var name;

  for (name in props) {
    config [name] = props [name];
  }
}

/**
 * Create request instance
 *
 * @callback callback
 * @param [isPrivate = false] {boolean} - Make instance private
 * @param callback {function} - `function (err, data) {}`
 * @return {void}
 */

function methodCreate (isPrivate, callback) (
  var props = {};

  if (typeof isPrivate === 'function') {
    callback = isPrivate;
  } else if (isPrivate === true) {
    props.private = 'true';
  }

  talk ('POST', 'bins', props, callback);
}

/**
 * Get a request instance
 *
 * @callback callback
 * @param bin {string} - Bin instance ID
 * @param callback {function} - `function (err, data) {}`
 * @return {void}
 */

function methodGet (bin, callback) {
  talk ('GET', 'bins/' + bin, callback);
}

/**
 * Get received requests
 *
 * @callback callback
 * @param bin {string} - Bin instance ID
 * @param callback {function} - `function (err, data) {}`
 * @return {void}
 */

function methodRequests (bin, callback) {
  talk ('GET', 'bins/' + bin + '/requests', callback);
}

/**
 * Get one received request
 *
 * @callback callback
 * @param bin {string} - Bin instance ID
 * @param request {string} - Request ID
 * @param callback {function} - `function (err, data) {}`
 * @return {void}
 */

function methodRequest (bin, request, callback) {
  talk ('GET', 'bins/' + bin + '/requests/' + request, callback);
}

/**
 * Interface methods
 *
 * @return {object} - Methods
 */

module.exports = {
  config: methodConfig,
  create: methodCreate,
  get: methodGet,
  requests: methodRequests,
  request: methodRequest
};
<|endoftext|>


<commit_before>var _ = require('../../basics/helpers');
var AnnotationIndex = require('../../document/annotation_index');
var Helpers = {};

/**
 * Returns true if given type is a container selection
 * @param {Document} doc
 * @param {string} type
 */

Helpers.isContainerAnnotation = function(doc, type) {
  var schema = doc.getSchema();
  return schema.isInstanceOf(type, "container_annotation");
};

/**
 * For a given selection get all property annotations
 *
 * @method getPropertyAnnotationsForSelection
 * @param {Document} doc
 * @param {Document.Selection} sel
 * @return An array of property annotations
 *
 * WARNING: Returns an empty array when selection is a container selection
 */

Helpers.getPropertyAnnotationsForSelection = function(doc, sel, options) {
  options = options || {};
  var annotations;
  var path, startOffset, endOffset;

  if (sel.isPropertySelection()) {
    path = sel.getPath();
    startOffset = sel.getStartOffset();
    endOffset = sel.getEndOffset();
  } else {
    return [];
  }

  annotations = doc.getIndex('annotations').get(path, startOffset, endOffset);
  if (options.type) {
    annotations = _.filter(annotations, AnnotationIndex.filterByType(options.type));
  }
  return annotations;
};

/**
 * For a given selection get all container annotations
 *
 * @method getContainerAnnotationsForSelection
 * @param {Document} doc
 * @param {Document.Selection} sel
 * @param {Document.Container} container
 * @param {object} options
 * @return An array of container annotations
 *
 * ATTENTION: looking for container annotations is not as efficient as property
 * selections, as we do not have an index that has notion of the spatial extend
 * of an annotation (which would depend on a model-side implementation of
 * Container). Opposed to that, common annotations are bound to properties
 * which make it easy to lookup.
 */

Helpers.getContainerAnnotationsForSelection = function(doc, sel, container, options) {
  if (!container) {
    // Fail more silently
    return [];
    // throw new Error('Container required.');
  }
  var annotations;
  // Also look for container annotations if a Container instance is given
  if (options.type) {
    annotations = doc.getIndex('type').get(options.type);
  } else {
    annotations = doc.getIndex('container-annotation-anchors').byId;
  }
  annotations = _.filter(annotations, function(anno) {
    var annoSel = anno.getSelection();
    return sel.overlaps(annoSel);
  });
  return annotations;
};

/**
 * For a given selection, get annotations of a certain type
 *
 * @method getAnnotationsForSelection
 * @param {Document} doc
 * @param {Document.Selection} sel
 * @param {String} annotationType
 * @param {String} containerId (only needed when type is a container annotation)
 * @return {Array} all matching annotations
 */

Helpers.getAnnotationsForSelection = function(doc, sel, annotationType, containerId) {
  var annos;
  var isContainerAnno = Helpers.isContainerAnnotation(doc, annotationType);

  if (isContainerAnno) {
    var container = doc.get(containerId);
    annos = Helpers.getContainerAnnotationsForSelection(doc, sel, container, {
      type: annotationType
    });
  } else {
    annos = Helpers.getPropertyAnnotationsForSelection(doc, sel, { type: annotationType });
  }
  return annos;
};

/**
 * For a given selection, get the corresponding text string
 *
 * @method getTextForSelection
 * @param {Document} doc
 * @param {Document.Selection} sel
 * @return {String} text enclosed by the annotation
 */

Helpers.getTextForSelection = function(doc, sel) {
  var result = [];
  var text;
  if (!sel || sel.isNull()) {
    return "";
  } else if (sel.isPropertySelection()) {
    text = this.get(sel.start.path);
    result.push(text.substring(sel.start.offset, sel.end.offset));
  } else if (sel.isContainerSelection()) {
    var container = this.get(sel.containerId);
    var range = sel.range;
    var paths = container.getPathRange(range.start.path, range.end.path);
    for (var i = 0; i < paths.length; i++) {
      var path = paths[i];
      text = this.get(path);
      if (paths.length === 1) {
        result.push(text.substring(sel.start.offset, sel.end.offset));
      } else if (i===0) {
        result.push(text.substring(sel.start.offset));
      } else if (i===paths.length-1) {
        result.push(text.substring(0, sel.end.offset));
      } else {
        result.push(text);
      }
    }
  }
  return result.join('');
};

module.exports = Helpers;<commit_msg>Fix regressions.<commit_after>var _ = require('../../basics/helpers');
var AnnotationIndex = require('../../document/annotation_index');
var Helpers = {};

/**
 * Returns true if given type is a container selection
 * @param {Document} doc
 * @param {string} type
 */

Helpers.isContainerAnnotation = function(doc, type) {
  var schema = doc.getSchema();
  return schema.isInstanceOf(type, "container_annotation");
};

/**
 * For a given selection get all property annotations
 *
 * @method getPropertyAnnotationsForSelection
 * @param {Document} doc
 * @param {Document.Selection} sel
 * @return An array of property annotations
 *
 * WARNING: Returns an empty array when selection is a container selection
 */

Helpers.getPropertyAnnotationsForSelection = function(doc, sel, options) {
  options = options || {};
  var annotations;
  var path, startOffset, endOffset;

  if (sel.isPropertySelection()) {
    path = sel.getPath();
    startOffset = sel.getStartOffset();
    endOffset = sel.getEndOffset();
  } else {
    return [];
  }

  annotations = doc.getIndex('annotations').get(path, startOffset, endOffset);
  if (options.type) {
    annotations = _.filter(annotations, AnnotationIndex.filterByType(options.type));
  }
  return annotations;
};

/**
 * For a given selection get all container annotations
 *
 * @method getContainerAnnotationsForSelection
 * @param {Document} doc
 * @param {Document.Selection} sel
 * @param {Document.Container} container
 * @param {object} options
 * @return An array of container annotations
 *
 * ATTENTION: looking for container annotations is not as efficient as property
 * selections, as we do not have an index that has notion of the spatial extend
 * of an annotation (which would depend on a model-side implementation of
 * Container). Opposed to that, common annotations are bound to properties
 * which make it easy to lookup.
 */

Helpers.getContainerAnnotationsForSelection = function(doc, sel, container, options) {
  if (!container) {
    // Fail more silently
    return [];
    // throw new Error('Container required.');
  }
  var annotations;
  // Also look for container annotations if a Container instance is given
  if (options.type) {
    annotations = doc.getIndex('type').get(options.type);
  } else {
    annotations = doc.getIndex('container-annotation-anchors').byId;
  }
  annotations = _.filter(annotations, function(anno) {
    var annoSel = anno.getSelection();
    return sel.overlaps(annoSel);
  });
  return annotations;
};

/**
 * For a given selection, get annotations of a certain type
 *
 * @method getAnnotationsForSelection
 * @param {Document} doc
 * @param {Document.Selection} sel
 * @param {String} annotationType
 * @param {String} containerId (only needed when type is a container annotation)
 * @return {Array} all matching annotations
 */

Helpers.getAnnotationsForSelection = function(doc, sel, annotationType, containerId) {
  var annos;
  var isContainerAnno = Helpers.isContainerAnnotation(doc, annotationType);

  if (isContainerAnno) {
    var container = doc.get(containerId);
    annos = Helpers.getContainerAnnotationsForSelection(doc, sel, container, {
      type: annotationType
    });
  } else {
    annos = Helpers.getPropertyAnnotationsForSelection(doc, sel, { type: annotationType });
  }
  return annos;
};

/**
 * For a given selection, get the corresponding text string
 *
 * @method getTextForSelection
 * @param {Document} doc
 * @param {Document.Selection} sel
 * @return {String} text enclosed by the annotation
 */

Helpers.getTextForSelection = function(doc, sel) {
  var result = [];
  var text;
  if (!sel || sel.isNull()) {
    return "";
  } else if (sel.isPropertySelection()) {
    text = doc.get(sel.start.path);
    result.push(text.substring(sel.start.offset, sel.end.offset));
  } else if (sel.isContainerSelection()) {
    var container = doc.get(sel.containerId);
    var range = sel.range;
    var paths = container.getPathRange(range.start.path, range.end.path);
    for (var i = 0; i < paths.length; i++) {
      var path = paths[i];
      text = doc.get(path);
      if (paths.length === 1) {
        result.push(text.substring(sel.start.offset, sel.end.offset));
      } else if (i===0) {
        result.push(text.substring(sel.start.offset));
      } else if (i===paths.length-1) {
        result.push(text.substring(0, sel.end.offset));
      } else {
        result.push(text);
      }
    }
  }
  return result.join('');
};

module.exports = Helpers;<|endoftext|>


<commit_before>var babel = require( 'babel-core' );
var fs = require( 'fs' );
var assert = require( 'assert' );
var getLocation = require( '../../utils/getLocation' );
var SourceMapConsumer = require( 'source-map' ).SourceMapConsumer;

module.exports = {
	description: 'preserves sourcemap chains when transforming',
	options: {
		plugins: [
			{
				load: function ( id ) {
					if ( id.endsWith( 'main.js' ) ) {
						id = id.replace( /main.js$/, 'foo.js' );
					} else {
						id = id.replace( /foo.js$/, 'main.js' );
					}

					var out = babel.transformFileSync( id, {
						blacklist: [ 'es6.modules' ],
						sourceMap: true
					});

					const sourceRoot = out.map.sources[0].slice( 0, out.map.sources[0].lastIndexOf( '/' ) );
					out.map.sources = out.map.sources.map( source => '../' + source.slice( sourceRoot.length + 1 ) );
					out.map.sourceRoot = 'fake';

					return { code: out.code, map: out.map };
				}
			}
		]
	},
	test: function ( code, map ) {
		var smc = new SourceMapConsumer( map );

		var generatedLoc = getLocation( code, code.indexOf( '42' ) );
		var originalLoc = smc.originalPositionFor( generatedLoc );

		assert.equal( originalLoc.source, '../main.js' );
		assert.equal( originalLoc.line, 1 );
		assert.equal( originalLoc.column, 25 );

		generatedLoc = getLocation( code, code.indexOf( 'log' ) );
		originalLoc = smc.originalPositionFor( generatedLoc );

		assert.equal( originalLoc.source, '../foo.js' );
		assert.equal( originalLoc.line, 3 );
		assert.equal( originalLoc.column, 8 );
	}
};
<commit_msg>Simplify sourcemaps loaders test<commit_after>var babel = require( 'babel-core' );
var fs = require( 'fs' );
var assert = require( 'assert' );
var getLocation = require( '../../utils/getLocation' );
var SourceMapConsumer = require( 'source-map' ).SourceMapConsumer;

module.exports = {
	description: 'preserves sourcemap chains when transforming',
	options: {
		plugins: [
			{
				load: function ( id ) {
					if ( id.endsWith( 'main.js' ) ) {
						id = id.replace( /main.js$/, 'foo.js' );
					} else {
						id = id.replace( /foo.js$/, 'main.js' );
					}

					var out = babel.transformFileSync( id, {
						blacklist: [ 'es6.modules' ],
						sourceMap: true
					});

					const slash = out.map.sources[0].lastIndexOf( '/' ) + 1;
					out.map.sources = out.map.sources.map( source => '../' + source.slice( slash ) );
					out.map.sourceRoot = 'fake';

					return { code: out.code, map: out.map };
				}
			}
		]
	},
	test: function ( code, map ) {
		var smc = new SourceMapConsumer( map );

		var generatedLoc = getLocation( code, code.indexOf( '42' ) );
		var originalLoc = smc.originalPositionFor( generatedLoc );

		assert.equal( originalLoc.source, '../main.js' );
		assert.equal( originalLoc.line, 1 );
		assert.equal( originalLoc.column, 25 );

		generatedLoc = getLocation( code, code.indexOf( 'log' ) );
		originalLoc = smc.originalPositionFor( generatedLoc );

		assert.equal( originalLoc.source, '../foo.js' );
		assert.equal( originalLoc.line, 3 );
		assert.equal( originalLoc.column, 8 );
	}
};
<|endoftext|>


<commit_before>import Phaser from 'phaser'
import Ship from '../sprites/Ship'
import Asteroid from '../sprites/Asteroid'
import Planet, { planets } from '../sprites/Planet'
import Coin from '../sprites/Coin'
export default class extends Phaser.State {
  init () {}
  preload () {}

  create () {
    //Setup physics
    game.physics.startSystem(Phaser.Physics.ARCADE);

    // Set up game input.
    game.cursors = game.input.keyboard.createCursorKeys()
    game.input.keyboard.addKeyCapture([ Phaser.Keyboard.SPACEBAR ])

    var worldWidth = 2000;
    var worldHeight = 2000;

    this.background = new Phaser.TileSprite(game, 0, 0, worldWidth, worldHeight, 'background')

    this.world.setBounds(0,0,worldWidth,worldHeight);
    this.player = new Ship({
      game: this,
      x: this.world.centerX,
      y: this.world.centerY,
      asset: 'ship'
    })
    this.player.body.collideWorldBounds = true;
    game.camera.follow(this.player);

    this.player.body.collideWorldBounds = true;
    this.camera.follow(this.player);

    this.game.add.existing(this.background)
    this.addPlanets()
    this.game.add.existing(this.player);

    this.fuelText = game.add.retroFont('knightHawks', 31, 25, Phaser.RetroFont.TEXT_SET2, 10, 1, 0)
    var fuelTextImage = game.add.image(5, 5, this.fuelText)
    fuelTextImage.tint = 0xFF7766
    fuelTextImage.fixedToCamera = true

    this.healthText = game.add.retroFont('knightHawks', 31, 25, Phaser.RetroFont.TEXT_SET2, 10, 1, 0)
    var healthTextImage = game.add.image(380, 5, this.healthText)
    healthTextImage.tint = 0x28bb35
    healthTextImage.fixedToCamera = true

    this.asteroids = game.add.physicsGroup();
    this.explosions = game.add.group();
    this.explosions.createMultiple(10, 'kaboom');
    this.explosions.forEach(this.setupExplosion, this);

    // Set up a weapon
    this.weapon = game.add.weapon(50, 'bullet')
    this.weapon.bulletKillType = Phaser.Weapon.KILL_WORLD_BOUNDS;
    this.weapon.bulletSpeed = 700;
    this.weapon.fireRate = 100;
    this.weapon.trackSprite(this.player, 0, 0, true);

    this.CoinGroup = this.game.add.physicsGroup();

  }

  setupExplosion(explosion) {
    explosion.anchor.x = 0.5;
    explosion.anchor.y = 0.5;
    explosion.animations.add('kaboom');
  }

  processHandler (player, asteroids) {
    return true;
  }

  update() {
    this.addAsteroid();
	  this.addCoin();

    if(game.input.keyboard.isDown(Phaser.Keyboard.SPACEBAR)) {
      console.log('b');
      this.weapon.fire();
    }

    if (game.physics.arcade.collide(this.player, this.asteroids, this.playerCollideAsteroid, null, this)) {
      console.log("Player got a coin!");
    }
    if (game.physics.arcade.overlap(this.player, this.CoinGroup, this.playerCollideCoin, null, this)) {
      console.log("Player got a coin!");
    }
    if (game.physics.arcade.collide(this.player.bullet, this.asteroids, this.bulletCollideAsteroidHandler, this.processHandler, this)) {
      console.log('Player shot an asteroid');
    }

  }

  bulletCollideAsteroidHandler (bullet, asteroid) {
    var explosion = this.explosions.getFirstExists(false);
    explosion.reset(asteroid.body.x, asteroid.body.y);
    asteroid.destroy();
    explosion.play('kaboom', 30, false, true);
  }

  playerCollideAsteroid (player, asteroid) {
    this.player.health -= player.maxHealth/10;
    var explosion = this.explosions.getFirstExists(false);
    explosion.reset(asteroid.body.x, asteroid.body.y);
    asteroid.destroy();
    explosion.play('kaboom', 30, false, true);
  }

  playerCollideCoin (player, coin) {
    //  If the ship collides with a coin it gets eaten :)
    coin.kill();
  }

  addPlanets() {
    const planetDensity = 0.000004
    const planetCount = this.world.width * this.world.height * planetDensity
    this.game.planets = []

    for (var i = 0; i < planetCount; i++) {
      var planet = new Planet({
        game: this,
        x: this.world.randomX,
        y: this.world.randomY,
        asset: Phaser.ArrayUtils.getRandomItem(planets)
      })
      this.game.planets.push(planet)
      this.game.add.existing(planet)
    }
  }

  addAsteroid() {
    var chanceOfAsteroid = 0.1;

    var asteroidRandom = Math.random();
    if (asteroidRandom < chanceOfAsteroid) {
      var xPos = 0;
      var yPos = 0;
      if (asteroidRandom <= chanceOfAsteroid / 4)
      {
        xPos = this.world.width * Math.random();
        yPos = 0;
      }
      else if (asteroidRandom <= chanceOfAsteroid / 2) {
        xPos = this.world.width * Math.random();
        yPos = this.world.height-1;
      }
      else if (asteroidRandom <= (chanceOfAsteroid*3) /4 ) {
        xPos = 0;
        yPos = this.world.height * Math.random();
      }
      else {
        xPos = this.world.width-1;
        yPos = this.world.height * Math.random();
      }

      var newAsteroid =  this.asteroids.create(xPos, yPos, 'asteroid', 0);

      var baseSpeed = 100
      var speedX = 0
      var speedY = 0
      if (xPos== 0) {
        speedX = baseSpeed * Math.random()
      } else {
        speedX = -baseSpeed * Math.random()
      }
      if (yPos == 0) {
        speedY = baseSpeed * Math.random()
      } else {
        speedY = -baseSpeed * Math.random()
      }

      var randomAngle = Math.atan2(speedY, speedX) / (Math.PI / 180)

      var direction = new Phaser.Point(speedX, speedY)
      newAsteroid.body.velocity = direction

      var randomAngle = 45 + Phaser.Math.radToDeg(
            Phaser.Point.angle(
            newAsteroid.position,
            new Phaser.Point(
              newAsteroid.x + newAsteroid.body.velocity.x,
              newAsteroid.y + newAsteroid.body.velocity.y)
          )
        )
      newAsteroid.angle = randomAngle;
      newAsteroid.outOfBoundsKill = true;
    }
  }

  render () {
    var x = 32
    var y = 32

    this.fuelText.text = 'fuel:' + Math.round(this.player.fuel / this.player.fuelMax * 100) + '%'
    this.healthText.text = 'shields:' + Math.round(this.player.health / this.player.maxHealth * 100) + '%'
  }

  addCoin() {
    var chanceOfCoin = 0.05;

    var coinRandom = Math.random();
    if (coinRandom < chanceOfCoin) {
      var xPos = Math.random();
      var yPos = Math.random();
      xPos = this.world.width * Math.random();
      yPos = this.world.width * Math.random();
	    var newCoin = this.CoinGroup.create(xPos, yPos,'coin');
	    newCoin.width =32;
	    newCoin.height =32;
      newCoin.animations.add('coin');

      //  And this starts the animation playing by using its key ("run")
      //  15 is the frame rate (15fps)
      //  true means it will loop when it finishes
	    newCoin.body.setCircle(10,5,5);//(radius,xoffset,yoffset);
      newCoin.play('coin', 10, true, false);
    }
  }
}
<commit_msg>Fixed asteroids colliding with themselves.<commit_after>import Phaser from 'phaser'
import Ship from '../sprites/Ship'
import Asteroid from '../sprites/Asteroid'
import Planet, { planets } from '../sprites/Planet'
import Coin from '../sprites/Coin'
export default class extends Phaser.State {
  init () {}
  preload () {}

  create () {
    //Setup physics
    game.physics.startSystem(Phaser.Physics.ARCADE);

    // Set up game input.
    game.cursors = game.input.keyboard.createCursorKeys()
    game.input.keyboard.addKeyCapture([ Phaser.Keyboard.SPACEBAR ])

    var worldWidth = 2000;
    var worldHeight = 2000;

    this.background = new Phaser.TileSprite(game, 0, 0, worldWidth, worldHeight, 'background')

    this.world.setBounds(0,0,worldWidth,worldHeight);
    this.player = new Ship({
      game: this,
      x: this.world.centerX,
      y: this.world.centerY,
      asset: 'ship'
    })
    this.player.body.collideWorldBounds = true;
    game.camera.follow(this.player);

    this.player.body.collideWorldBounds = true;
    this.camera.follow(this.player);

    this.game.add.existing(this.background)
    this.addPlanets()
    this.game.add.existing(this.player);

    this.fuelText = game.add.retroFont('knightHawks', 31, 25, Phaser.RetroFont.TEXT_SET2, 10, 1, 0)
    var fuelTextImage = game.add.image(5, 5, this.fuelText)
    fuelTextImage.tint = 0xFF7766
    fuelTextImage.fixedToCamera = true

    this.healthText = game.add.retroFont('knightHawks', 31, 25, Phaser.RetroFont.TEXT_SET2, 10, 1, 0)
    var healthTextImage = game.add.image(380, 5, this.healthText)
    healthTextImage.tint = 0x28bb35
    healthTextImage.fixedToCamera = true

    this.asteroids = game.add.physicsGroup();
    this.explosions = game.add.group();
    this.explosions.createMultiple(30, 'kaboom');
    this.explosions.forEach(this.setupExplosion, this);

    // Set up a weapon
    this.weapon = game.add.weapon(50, 'bullet')
    this.weapon.bulletKillType = Phaser.Weapon.KILL_WORLD_BOUNDS;
    this.weapon.bulletSpeed = 700;
    this.weapon.fireRate = 100;
    this.weapon.trackSprite(this.player, 0, 0, true);

    this.CoinGroup = this.game.add.physicsGroup();

  }

  setupExplosion(explosion) {
    explosion.anchor.x = 0.5;
    explosion.anchor.y = 0.5;
    explosion.animations.add('kaboom');
  }

  processHandler (player, asteroids) {
    return true;
  }

  update() {
    this.addAsteroid();
	  this.addCoin();

    if(game.input.keyboard.isDown(Phaser.Keyboard.SPACEBAR)) {
      console.log('b');
      this.weapon.fire();
    }

    if (game.physics.arcade.collide(this.player, this.asteroids, this.playerCollideAsteroid, null, this)) {
      console.log("Player got a coin!");
    }
    if (game.physics.arcade.overlap(this.player, this.CoinGroup, this.playerCollideCoin, null, this)) {
      console.log("Player got a coin!");
    }
    if (game.physics.arcade.collide(this.player.bullet, this.asteroids, this.bulletCollideAsteroidHandler, this.processHandler, this)) {
      console.log('Player shot an asteroid');
    }
    if (game.physics.arcade.collideGroupVsSelf(this.asteroids, this.asteroidCollideAsteroidHandler,  this.processHandler, this))
    {
      console.log('asteroid hit asteroid!');
    }

  }
  asteroidCollideAsteroidHandler (asteroid1, asteroid2) {
    var explosion = this.explosions.getFirstExists(false);
    explosion.reset((asteroid1.body.x + asteroid2.body.x) / 2,
      (asteroid1.body.y + asteroid2.body.y) / 2);
    asteroid1.destroy();
    asteroid2.destroy();
    explosion.play('kaboom', 30, false, true);
  }

  bulletCollideAsteroidHandler (bullet, asteroid) {
    var explosion = this.explosions.getFirstExists(false);
    explosion.reset(asteroid.body.x, asteroid.body.y);
    asteroid.destroy();
    explosion.play('kaboom', 30, false, true);
  }

  playerCollideAsteroid (player, asteroid) {
    this.player.health -= player.maxHealth/10;
    if (this.player.health <= 0) {
      //TODO:  Kill player and explode ship
    }

    var explosion = this.explosions.getFirstExists(false);
    explosion.reset(asteroid.body.x, asteroid.body.y);
    asteroid.destroy();
    explosion.play('kaboom', 30, false, true);
  }

  playerCollideCoin (player, coin) {
    //  If the ship collides with a coin it gets eaten :)
    coin.kill();
  }

  addPlanets() {
    const planetDensity = 0.000004
    const planetCount = this.world.width * this.world.height * planetDensity
    this.game.planets = []

    for (var i = 0; i < planetCount; i++) {
      var planet = new Planet({
        game: this,
        x: this.world.randomX,
        y: this.world.randomY,
        asset: Phaser.ArrayUtils.getRandomItem(planets)
      })
      this.game.planets.push(planet)
      this.game.add.existing(planet)
    }
  }

  addAsteroid() {
    var chanceOfAsteroid = 0.1;

    var asteroidRandom = Math.random();
    if (asteroidRandom < chanceOfAsteroid) {
      var xPos = 0;
      var yPos = 0;
      if (asteroidRandom <= chanceOfAsteroid / 4)
      {
        xPos = this.world.width * Math.random();
        yPos = 0;
      }
      else if (asteroidRandom <= chanceOfAsteroid / 2) {
        xPos = this.world.width * Math.random();
        yPos = this.world.height-1;
      }
      else if (asteroidRandom <= (chanceOfAsteroid*3) /4 ) {
        xPos = 0;
        yPos = this.world.height * Math.random();
      }
      else {
        xPos = this.world.width-1;
        yPos = this.world.height * Math.random();
      }

      var newAsteroid =  this.asteroids.create(xPos, yPos, 'asteroid', 0);

      var baseSpeed = 100
      var speedX = 0
      var speedY = 0
      if (xPos== 0) {
        speedX = baseSpeed * Math.random()
      } else {
        speedX = -baseSpeed * Math.random()
      }
      if (yPos == 0) {
        speedY = baseSpeed * Math.random()
      } else {
        speedY = -baseSpeed * Math.random()
      }

      var randomAngle = Math.atan2(speedY, speedX) / (Math.PI / 180)

      var direction = new Phaser.Point(speedX, speedY)
      newAsteroid.body.velocity = direction

      var randomAngle = 45 + Phaser.Math.radToDeg(
            Phaser.Point.angle(
            newAsteroid.position,
            new Phaser.Point(
              newAsteroid.x + newAsteroid.body.velocity.x,
              newAsteroid.y + newAsteroid.body.velocity.y)
          )
        )
      newAsteroid.angle = randomAngle;
      newAsteroid.outOfBoundsKill = true;
    }
  }

  render () {
    var x = 32
    var y = 32

    this.fuelText.text = 'fuel:' + Math.round(this.player.fuel / this.player.fuelMax * 100) + '%'
    this.healthText.text = 'shields:' + Math.round(this.player.health / this.player.maxHealth * 100) + '%'
  }

  addCoin() {
    var chanceOfCoin = 0.05;

    var coinRandom = Math.random();
    if (coinRandom < chanceOfCoin) {
      var xPos = Math.random();
      var yPos = Math.random();
      xPos = this.world.width * Math.random();
      yPos = this.world.width * Math.random();
	    var newCoin = this.CoinGroup.create(xPos, yPos,'coin');
	    newCoin.width =32;
	    newCoin.height =32;
      newCoin.animations.add('coin');

      //  And this starts the animation playing by using its key ("run")
      //  15 is the frame rate (15fps)
      //  true means it will loop when it finishes
	    newCoin.body.setCircle(10,5,5);//(radius,xoffset,yoffset);
      newCoin.play('coin', 10, true, false);
    }
  }
}
<|endoftext|>


<commit_before>const faker = require('faker')
const { assign } = require('lodash')

const {
  getSelectorForElementWithText,
  getButtonWithText,
  getLinkWithText,
} = require('../../helpers/selectors')
const { generateFutureDate } = require('../../helpers/date')

const getRadioButtonWithText = (text) =>
  getSelectorForElementWithText(
    text,
    {
      el: '//span',
      className: 'c-multiple-choice__label-text',
    },
  )

module.exports = {
  props: {},
  elements: {
    aStandardInteraction: getRadioButtonWithText('A standard interaction'),
    aServiceThatYouHaveProvided: getRadioButtonWithText('A service that you have provided'),
    continueButton: getButtonWithText('Continue'),
    saveButton: getButtonWithText('Save'),
    subject: '#field-subject',
    notes: '#field-notes',
    dateOfInteractionYear: '#field-date_year',
    dateOfInteractionMonth: '#field-date_month',
    dateOfInteractionDay: '#field-date_day',
    contact: '#field-contact',
    serviceProvider: '#field-dit_team',
    service: '#field-service',
    serviceStatus: '#field-service_delivery_status',
    grantOffered: '#field-grant_amount_offered',
    ditAdviser: '#field-dit_adviser',
    communicationChannel: '#field-communication_channel',
    eventYes: 'label[for=field-is_event-1]',
    eventNo: 'label[for=field-is_event-2]',
    event: '#field-event',
  },
  commands: [
    {
      createInteraction (details = {}, callback) { // TODO feels that some duplication between this and createServiceDelivery can be DRY'd up
        const futureDate = generateFutureDate()
        const interaction = assign({}, {
          subject: faker.lorem.word(),
          notes: faker.lorem.sentence(),
          dateOfInteractionYear: futureDate.year,
          dateOfInteractionMonth: futureDate.month,
          dateOfInteractionDay: futureDate.day,
        }, details)

        this
          .waitForElementVisible('@saveButton')
          .api
          .perform((done) => {
            this.getListOption('@contact', (contact) => {
              interaction.contact = contact
              done()
            })
          })
          .perform((done) => {
            this.getListOption('@serviceProvider', (serviceProvider) => {
              interaction.serviceProvider = serviceProvider
              done()
            })
          })
          .perform((done) => {
            this.getListOption('@service', (service) => {
              interaction.service = service
              done()
            })
          })
          .perform((done) => {
            this.getListOption('@ditAdviser', (ditAdviser) => {
              interaction.ditAdviser = ditAdviser
              done()
            })
          })
          .perform((done) => {
            this.getListOption('@communicationChannel', (communicationChannel) => {
              interaction.communicationChannel = communicationChannel
              done()
            })
          })
          .perform((done) => {
            for (const key in interaction) {
              if (interaction[key]) {
                this.replaceValue(`@${key}`, interaction[key])
              }
            }
            interaction.heading = interaction.subject
            done()
          })

        return this.click('@saveButton', () => {
          callback(interaction)
        })
      },

      createServiceDelivery (details = {}, callback) {
        const futureDate = generateFutureDate()
        const serviceDelivery = assign({}, {
          subject: faker.lorem.word(),
          notes: faker.lorem.sentence(),
          dateOfInteractionYear: futureDate.year,
          dateOfInteractionMonth: futureDate.month,
          dateOfInteractionDay: futureDate.day,
        }, details)
        const serviceDeliveryRadioButtons = {}

        this
          .waitForElementPresent('@eventYes')
          .click('@eventYes')
          .api.perform(async (done) => {
            this
              .api
              .perform((done) => {
                this.getListOption('@contact', (contact) => {
                  serviceDelivery.contact = contact
                  done()
                })
              })
              .perform((done) => {
                this.getListOption('@serviceProvider', (serviceProvider) => {
                  serviceDelivery.serviceProvider = serviceProvider
                  done()
                })
              })
              .perform((done) => {
                this.getListOption('@event', (event) => {
                  serviceDelivery.event = event
                  done()
                })
              })
              .perform((done) => {
                if (serviceDelivery.service) {
                  return done()
                }

                this.getListOption('@service', (service) => {
                  serviceDelivery.service = service
                  done()
                })
              })
              .perform((done) => {
                this.getListOption('@ditAdviser', (ditAdviser) => {
                  serviceDelivery.ditAdviser = ditAdviser
                  done()
                })
              })
              .perform((done) => {
                for (const key in serviceDelivery) {
                  if (serviceDelivery[key]) {
                    this.replaceValue(`@${key}`, serviceDelivery[key])
                  }
                }
                for (const key in serviceDeliveryRadioButtons) {
                  this.api.useCss().click(serviceDeliveryRadioButtons[key].labelSelector)
                  serviceDelivery[key] = serviceDeliveryRadioButtons[key].text
                }

                serviceDelivery.heading = serviceDelivery.subject
                done()
              })
            done()
          })

        return this.click('@saveButton', () => {
          callback(serviceDelivery)
        })
      },
    },
  ],
  sections: {
    details: {
      selector: '.table--key-value',
      elements: {
        documentsLink: getLinkWithText('Documents'),
      },
    },
  },
}
<commit_msg>Remove reference to redundant radio button object<commit_after>const faker = require('faker')
const { assign } = require('lodash')

const {
  getSelectorForElementWithText,
  getButtonWithText,
  getLinkWithText,
} = require('../../helpers/selectors')
const { generateFutureDate } = require('../../helpers/date')

const getRadioButtonWithText = (text) =>
  getSelectorForElementWithText(
    text,
    {
      el: '//span',
      className: 'c-multiple-choice__label-text',
    },
  )

module.exports = {
  props: {},
  elements: {
    aStandardInteraction: getRadioButtonWithText('A standard interaction'),
    aServiceThatYouHaveProvided: getRadioButtonWithText('A service that you have provided'),
    continueButton: getButtonWithText('Continue'),
    saveButton: getButtonWithText('Save'),
    subject: '#field-subject',
    notes: '#field-notes',
    dateOfInteractionYear: '#field-date_year',
    dateOfInteractionMonth: '#field-date_month',
    dateOfInteractionDay: '#field-date_day',
    contact: '#field-contact',
    serviceProvider: '#field-dit_team',
    service: '#field-service',
    serviceStatus: '#field-service_delivery_status',
    grantOffered: '#field-grant_amount_offered',
    ditAdviser: '#field-dit_adviser',
    communicationChannel: '#field-communication_channel',
    eventYes: 'label[for=field-is_event-1]',
    eventNo: 'label[for=field-is_event-2]',
    event: '#field-event',
  },
  commands: [
    {
      createInteraction (details = {}, callback) { // TODO feels that some duplication between this and createServiceDelivery can be DRY'd up
        const futureDate = generateFutureDate()
        const interaction = assign({}, {
          subject: faker.lorem.word(),
          notes: faker.lorem.sentence(),
          dateOfInteractionYear: futureDate.year,
          dateOfInteractionMonth: futureDate.month,
          dateOfInteractionDay: futureDate.day,
        }, details)

        this
          .waitForElementVisible('@saveButton')
          .api
          .perform((done) => {
            this.getListOption('@contact', (contact) => {
              interaction.contact = contact
              done()
            })
          })
          .perform((done) => {
            this.getListOption('@serviceProvider', (serviceProvider) => {
              interaction.serviceProvider = serviceProvider
              done()
            })
          })
          .perform((done) => {
            this.getListOption('@service', (service) => {
              interaction.service = service
              done()
            })
          })
          .perform((done) => {
            this.getListOption('@ditAdviser', (ditAdviser) => {
              interaction.ditAdviser = ditAdviser
              done()
            })
          })
          .perform((done) => {
            this.getListOption('@communicationChannel', (communicationChannel) => {
              interaction.communicationChannel = communicationChannel
              done()
            })
          })
          .perform((done) => {
            for (const key in interaction) {
              if (interaction[key]) {
                this.replaceValue(`@${key}`, interaction[key])
              }
            }
            interaction.heading = interaction.subject
            done()
          })

        return this.click('@saveButton', () => {
          callback(interaction)
        })
      },

      createServiceDelivery (details = {}, callback) {
        const futureDate = generateFutureDate()
        const serviceDelivery = assign({}, {
          subject: faker.lorem.word(),
          notes: faker.lorem.sentence(),
          dateOfInteractionYear: futureDate.year,
          dateOfInteractionMonth: futureDate.month,
          dateOfInteractionDay: futureDate.day,
        }, details)

        this
          .waitForElementPresent('@eventYes')
          .click('@eventYes')
          .api.perform(async (done) => {
            this
              .api
              .perform((done) => {
                this.getListOption('@contact', (contact) => {
                  serviceDelivery.contact = contact
                  done()
                })
              })
              .perform((done) => {
                this.getListOption('@serviceProvider', (serviceProvider) => {
                  serviceDelivery.serviceProvider = serviceProvider
                  done()
                })
              })
              .perform((done) => {
                this.getListOption('@event', (event) => {
                  serviceDelivery.event = event
                  done()
                })
              })
              .perform((done) => {
                if (serviceDelivery.service) {
                  return done()
                }

                this.getListOption('@service', (service) => {
                  serviceDelivery.service = service
                  done()
                })
              })
              .perform((done) => {
                this.getListOption('@ditAdviser', (ditAdviser) => {
                  serviceDelivery.ditAdviser = ditAdviser
                  done()
                })
              })
              .perform((done) => {
                for (const key in serviceDelivery) {
                  if (serviceDelivery[key]) {
                    this.replaceValue(`@${key}`, serviceDelivery[key])
                  }
                }

                serviceDelivery.heading = serviceDelivery.subject
                done()
              })
            done()
          })

        return this.click('@saveButton', () => {
          callback(serviceDelivery)
        })
      },
    },
  ],
  sections: {
    details: {
      selector: '.table--key-value',
      elements: {
        documentsLink: getLinkWithText('Documents'),
      },
    },
  },
}
<|endoftext|>


<commit_before>var TestCheddarFrom = require('../../globals').TestCheddarFrom;
var chai = require('chai');
var expect = chai.expect;
chai.should();

describe('Numbers', function(){
    describe('addition', function(){
        it('should work', TestCheddarFrom.Code(
            'print "2+3=" + String::(2+3)',
            '2+3=5'
        ))
//        it('should break', TestCheddarFrom.Code(
//            'print String::(+)'
//        ))
    })

    describe('subtraction', function(){
        describe('negative number', function(){
            it('should work', TestCheddarFrom.Code(
                'print "-3=" + String::(-3)',
                '-3=-3'
            ))
        })
        it('should work', TestCheddarFrom.Code(
            'print "5-3=" + String::(5-3)',
            '5-3=2'
        ))
//        it('should break', TestCheddarFrom.Code(
//            'print String::(-)'
//        ))
    })
    describe('multiplication', function(){
        it('should work', TestCheddarFrom.Code(
            'print "3*3=" + String::(3*3)',
            '3*3=9'
        ))
    })
    describe('repetition', function(){
        it('should work', TestCheddarFrom.Code(
            'print \'3*"foo"=\' + 3*"foo"',
            '3*"foo"=foofoofoo'
        ))
    })
    describe('division', function(){
        it('should work', TestCheddarFrom.Code(
            'print "10/5=" + String::(10/5)',
            '10/5=2'
        ))
//        it('should break', TestCheddarFrom.Code(
//            'print String::(/)'
//        ))
    })
    describe('powers', function(){
        it('should work', TestCheddarFrom.Code(
            'print "2^2=" + String::(2^2)',
            '2^2=4'
        ))
//        it('should break', TestCheddarFrom.Code(
//            'print String::(^)'
//        ))
    })
    describe('modulo', function(){
        it('should work', TestCheddarFrom.Code(
            'print "10%100=" + String::(10%100)',
            '10%100=10'
        ))
//        it('should break', TestCheddarFrom.Code(
//            'print String::(%)'
//        ))
    })
    describe('less than', function(){
        it('should work', TestCheddarFrom.Code(
            'print "5>4=" + String::(5>4)',
            '5>4=true'
        ))
//        it('should break', TestCheddarFrom.Code(
//            'print String::(>)'
//        ))
    })
    describe('more than', function(){
        it('should work', TestCheddarFrom.Code(
            'print "5<4=" + String::(5<4)',
            '5<4=false'
        ))
//        it('should break', TestCheddarFrom.Code(
//            'print String::(<)'
//        ))
    })
    describe('equal to', function(){
        it('should work', TestCheddarFrom.Code(
            'print "4==4=" + String::(4==4)',
            '4==4=true'
        ))
//        it('should break', TestCheddarFrom.Code(
//            'print String::(==)'
//        ))
    })
    describe('not equal to', function(){
        it('should work', TestCheddarFrom.Code(
            'print "4!=4=" + String::(4!=4)',
            '4!=4=false'
        ))
//        it('should break', TestCheddarFrom.Code(
//            'print String::(!=)'
//        ))
    })
    describe('less than or equal to', function(){
        it('should work', TestCheddarFrom.Code(
            'print "4>=4=" + String::(4>=4)',
            '4>=4=true'
        ))
//        it('should break', TestCheddarFrom.Code(
//            'print String::(>=)'
//        ))
    })
    describe('more than or equal to', function(){
        it('should work', TestCheddarFrom.Code(
            'print "4<=4=" + String::(4<=4)',
            '4<=4=true'
        ))
//        it('should break', TestCheddarFrom.Code(
//            'print String::(<=)'
//        ))
    })
    describe('bitwise and', function(){
        it('should work', TestCheddarFrom.Code(
            'print "4&4=" + String::(4 & 4)',
            '4&4=' + (4 & 4)
        ))
//        it('should break', TestCheddarFrom.Code(
//            'print String::(&)'
//        ))
    })
    describe('bitwise or', function(){
        it('should work', TestCheddarFrom.Code(
            'print "4|4=" + String::(4 | 4)',
            '4|4=' + (4 | 4)
        ))
//        it('should break', TestCheddarFrom.Code(
//            'print String::(|)'
//        ))
    })

    describe('xor', function(){
        it('should work', TestCheddarFrom.Code(
            'print "4 xor 3=" + String::(4 xor 3)',
            '4 xor 3=' + (4 ^ 3)
        ))
//        it('should break', TestCheddarFrom.Code(
//            'print String::(|)'
//        ))
    })

    describe('right shift', function(){
        it('should work', TestCheddarFrom.Code(
            'print "4>>3=" + String::(4>>3)',
            '4>>3=' + (4 >> 3)
        ))
//        it('should break', TestCheddarFrom.Code(
//            'print String::(|)'
//        ))
    })

    describe('left shift', function(){
        it('should work', TestCheddarFrom.Code(
            'print "4<<3=" + String::(4<<3)',
            '4<<3=' + (4<<3)
        ))
//        it('should break', TestCheddarFrom.Code(
//            'print String::(|)'
//        ))
    })

    describe('sign', function(){
        it('unary should work', TestCheddarFrom.Code(
            'print "sign 3=" + String::(sign 3)',
            'sign 3=' + Math.sign(3)
        ))

        it('binary should work', TestCheddarFrom.Code(
            'print "1 sign 3=" + String::(1 sign 3)',
            '1 sign 3=-1'
        ))
//        it('should break', TestCheddarFrom.Code(
//            'print String::(sign)'
//        ))
    })
    describe('square root', function(){
        it('should work', TestCheddarFrom.Code(
            'print "sqrt 9=" + String::(sqrt 9)',
            'sqrt 9=' + Math.sqrt(9)
        ))
//        it('should break', TestCheddarFrom.Code(
//            'print String::(sqrt)'
//        ))
    })
    describe('cube root', function(){
        it('should work', TestCheddarFrom.Code(
            'print "cbrt 8=" + String::(cbrt 8)',
            'cbrt 8=' + Math.cbrt(8)
        ))
//        it('should break', TestCheddarFrom.Code(
//            'print String::(cbrt)'
//        ))
    })
    describe('n root', function(){
        it('should work', TestCheddarFrom.Code(
            'print "8 root 3=" + String::(8 root 3)',
            '8 root 3=2'
        ))
//        it('should break', TestCheddarFrom.Code(
//            'print String::(root)'
//        ))
    })

    describe('log', function(){
        it('unary should work', TestCheddarFrom.Code(
            'print "log Math.E=" + String::(log Math.E)',
            'log Math.E=1'
        ))

        it('binary should work', TestCheddarFrom.Code(
            'print "16 log 2=" + String::(16 log 2)',
            '16 log 2=4'
        ))
    })

    describe('ceil', function(){
        it('should work', TestCheddarFrom.Code(
            'print "ceil 1.6=" + String::(ceil 1.6)',
            'ceil 1.6=2'
        ))
//        it('should break', TestCheddarFrom.Code(
//            'print String::(ceil)'
//        ))
    })
    describe('floor', function(){
        it('should work', TestCheddarFrom.Code(
            'print "floor 1.2=" + String::(floor 1.2)',
            'floor 1.2=1'
        ))
//        it('should break', TestCheddarFrom.Code(
//            'print String::(floor)'
//        ))
    })
    describe('round', function(){
        it('should work', TestCheddarFrom.Code(
            'print "round 1.2=" + String::(round 1.2)',
            'round 1.2=1'
        ))
//        it('should break', TestCheddarFrom.Code(
//            'print String::(round)'
//        ))
    })

    describe('abs', function(){
        it('should work', TestCheddarFrom.Code(
            'print "abs -1=" + String::(abs -1)',
            'abs -1=1'
        ))
    })

    describe('range', function(){
        it('should work', TestCheddarFrom.Code(
            'print "1:5=" + String::(1:5)',
            '1:5=[1, 2, 3, 4, 5]'
        ))

        it('should work reversed', TestCheddarFrom.Code(
            'print "5:1=" + String::(5:1)',
            '5:1=[5, 4, 3, 2, 1]'
        ))
    })

    describe('char', function(){
        it('should work', TestCheddarFrom.Code(
            'print \'@"65=\' + @" 65',
            '@"65=A'
        ))
    })
});
<commit_msg>fix [range]: update tests<commit_after>var TestCheddarFrom = require('../../globals').TestCheddarFrom;
var chai = require('chai');
var expect = chai.expect;
chai.should();

describe('Numbers', function(){
    describe('addition', function(){
        it('should work', TestCheddarFrom.Code(
            'print "2+3=" + String::(2+3)',
            '2+3=5'
        ))
//        it('should break', TestCheddarFrom.Code(
//            'print String::(+)'
//        ))
    })

    describe('subtraction', function(){
        describe('negative number', function(){
            it('should work', TestCheddarFrom.Code(
                'print "-3=" + String::(-3)',
                '-3=-3'
            ))
        })
        it('should work', TestCheddarFrom.Code(
            'print "5-3=" + String::(5-3)',
            '5-3=2'
        ))
//        it('should break', TestCheddarFrom.Code(
//            'print String::(-)'
//        ))
    })
    describe('multiplication', function(){
        it('should work', TestCheddarFrom.Code(
            'print "3*3=" + String::(3*3)',
            '3*3=9'
        ))
    })
    describe('repetition', function(){
        it('should work', TestCheddarFrom.Code(
            'print \'3*"foo"=\' + 3*"foo"',
            '3*"foo"=foofoofoo'
        ))
    })
    describe('division', function(){
        it('should work', TestCheddarFrom.Code(
            'print "10/5=" + String::(10/5)',
            '10/5=2'
        ))
//        it('should break', TestCheddarFrom.Code(
//            'print String::(/)'
//        ))
    })
    describe('powers', function(){
        it('should work', TestCheddarFrom.Code(
            'print "2^2=" + String::(2^2)',
            '2^2=4'
        ))
//        it('should break', TestCheddarFrom.Code(
//            'print String::(^)'
//        ))
    })
    describe('modulo', function(){
        it('should work', TestCheddarFrom.Code(
            'print "10%100=" + String::(10%100)',
            '10%100=10'
        ))
//        it('should break', TestCheddarFrom.Code(
//            'print String::(%)'
//        ))
    })
    describe('less than', function(){
        it('should work', TestCheddarFrom.Code(
            'print "5>4=" + String::(5>4)',
            '5>4=true'
        ))
//        it('should break', TestCheddarFrom.Code(
//            'print String::(>)'
//        ))
    })
    describe('more than', function(){
        it('should work', TestCheddarFrom.Code(
            'print "5<4=" + String::(5<4)',
            '5<4=false'
        ))
//        it('should break', TestCheddarFrom.Code(
//            'print String::(<)'
//        ))
    })
    describe('equal to', function(){
        it('should work', TestCheddarFrom.Code(
            'print "4==4=" + String::(4==4)',
            '4==4=true'
        ))
//        it('should break', TestCheddarFrom.Code(
//            'print String::(==)'
//        ))
    })
    describe('not equal to', function(){
        it('should work', TestCheddarFrom.Code(
            'print "4!=4=" + String::(4!=4)',
            '4!=4=false'
        ))
//        it('should break', TestCheddarFrom.Code(
//            'print String::(!=)'
//        ))
    })
    describe('less than or equal to', function(){
        it('should work', TestCheddarFrom.Code(
            'print "4>=4=" + String::(4>=4)',
            '4>=4=true'
        ))
//        it('should break', TestCheddarFrom.Code(
//            'print String::(>=)'
//        ))
    })
    describe('more than or equal to', function(){
        it('should work', TestCheddarFrom.Code(
            'print "4<=4=" + String::(4<=4)',
            '4<=4=true'
        ))
//        it('should break', TestCheddarFrom.Code(
//            'print String::(<=)'
//        ))
    })
    describe('bitwise and', function(){
        it('should work', TestCheddarFrom.Code(
            'print "4&4=" + String::(4 & 4)',
            '4&4=' + (4 & 4)
        ))
//        it('should break', TestCheddarFrom.Code(
//            'print String::(&)'
//        ))
    })
    describe('bitwise or', function(){
        it('should work', TestCheddarFrom.Code(
            'print "4|4=" + String::(4 | 4)',
            '4|4=' + (4 | 4)
        ))
//        it('should break', TestCheddarFrom.Code(
//            'print String::(|)'
//        ))
    })

    describe('xor', function(){
        it('should work', TestCheddarFrom.Code(
            'print "4 xor 3=" + String::(4 xor 3)',
            '4 xor 3=' + (4 ^ 3)
        ))
//        it('should break', TestCheddarFrom.Code(
//            'print String::(|)'
//        ))
    })

    describe('right shift', function(){
        it('should work', TestCheddarFrom.Code(
            'print "4>>3=" + String::(4>>3)',
            '4>>3=' + (4 >> 3)
        ))
//        it('should break', TestCheddarFrom.Code(
//            'print String::(|)'
//        ))
    })

    describe('left shift', function(){
        it('should work', TestCheddarFrom.Code(
            'print "4<<3=" + String::(4<<3)',
            '4<<3=' + (4<<3)
        ))
//        it('should break', TestCheddarFrom.Code(
//            'print String::(|)'
//        ))
    })

    describe('sign', function(){
        it('unary should work', TestCheddarFrom.Code(
            'print "sign 3=" + String::(sign 3)',
            'sign 3=' + Math.sign(3)
        ))

        it('binary should work', TestCheddarFrom.Code(
            'print "1 sign 3=" + String::(1 sign 3)',
            '1 sign 3=-1'
        ))
//        it('should break', TestCheddarFrom.Code(
//            'print String::(sign)'
//        ))
    })
    describe('square root', function(){
        it('should work', TestCheddarFrom.Code(
            'print "sqrt 9=" + String::(sqrt 9)',
            'sqrt 9=' + Math.sqrt(9)
        ))
//        it('should break', TestCheddarFrom.Code(
//            'print String::(sqrt)'
//        ))
    })
    describe('cube root', function(){
        it('should work', TestCheddarFrom.Code(
            'print "cbrt 8=" + String::(cbrt 8)',
            'cbrt 8=' + Math.cbrt(8)
        ))
//        it('should break', TestCheddarFrom.Code(
//            'print String::(cbrt)'
//        ))
    })
    describe('n root', function(){
        it('should work', TestCheddarFrom.Code(
            'print "8 root 3=" + String::(8 root 3)',
            '8 root 3=2'
        ))
//        it('should break', TestCheddarFrom.Code(
//            'print String::(root)'
//        ))
    })

    describe('log', function(){
        it('unary should work', TestCheddarFrom.Code(
            'print "log Math.E=" + String::(log Math.E)',
            'log Math.E=1'
        ))

        it('binary should work', TestCheddarFrom.Code(
            'print "16 log 2=" + String::(16 log 2)',
            '16 log 2=4'
        ))
    })

    describe('ceil', function(){
        it('should work', TestCheddarFrom.Code(
            'print "ceil 1.6=" + String::(ceil 1.6)',
            'ceil 1.6=2'
        ))
//        it('should break', TestCheddarFrom.Code(
//            'print String::(ceil)'
//        ))
    })
    describe('floor', function(){
        it('should work', TestCheddarFrom.Code(
            'print "floor 1.2=" + String::(floor 1.2)',
            'floor 1.2=1'
        ))
//        it('should break', TestCheddarFrom.Code(
//            'print String::(floor)'
//        ))
    })
    describe('round', function(){
        it('should work', TestCheddarFrom.Code(
            'print "round 1.2=" + String::(round 1.2)',
            'round 1.2=1'
        ))
//        it('should break', TestCheddarFrom.Code(
//            'print String::(round)'
//        ))
    })

    describe('abs', function(){
        it('should work', TestCheddarFrom.Code(
            'print "abs -1=" + String::(abs -1)',
            'abs -1=1'
        ))
    })

    describe('range', function(){
        it('should work', TestCheddarFrom.Code(
            'print "1|>5=" + String::(1:5)',
            '1|>5=[1, 2, 3, 4, 5]'
        ))

        it('should work reversed', TestCheddarFrom.Code(
            'print "5|>1=" + String::(5|>1)',
            '5|>1=[5, 4, 3, 2, 1]'
        ))
    })

    describe('char', function(){
        it('should work', TestCheddarFrom.Code(
            'print \'@"65=\' + @" 65',
            '@"65=A'
        ))
    })
});
<|endoftext|>


<commit_before>import MacroManagerBase from 'substance/ui/MacroManager'

/**
 * A custom `MacroManager` which excludes text in existing annotations
 * from macros regex test strings.
 *
 * @class      MacroManager (name)
 */
function MacroManager () {
  MacroManager.super.apply(this, arguments)
}

MacroManager.Prototype = function () {
  // This function is from `substance/ui/MacroManager` except for the part
  // labelled as "Modification" below
  this.executeMacros = function (update, info) {
    var change = update.change
    if (!change) {
      return
    }

    var doc = this.context.documentSession.getDocument()
    var nodeId, node, text
    var path
    if (info.action === 'type') {
      // HACK: we know that there is only one op when we type something
      var op = change.ops[0]
      path = op.path
      nodeId = path[0]
      node = doc.get(nodeId)
      text = doc.get(path)
    } else {
      return
    }

    // Modification: converts text within existing annotations to spaces so
    // that they are not matched in subsequent macros
    var annos = doc.getIndex('annotations').get(path)
    annos.forEach(function (anno) {
      var length = anno.endOffset - anno.startOffset + 1
      text = text.substring(0, anno.startOffset) + Array(length + 1).join(' ') + text.substring(anno.endOffset + 1)
    })

    var props = {
      action: info.action,
      node: node,
      path: path,
      text: text,
      selection: this.context.documentSession.getSelection()
    }
    for (var i = 0; i < this.macros.length; i++) {
      var macro = this.macros[i]
      var executed = macro.execute(props, this.context)

      if (executed) {
        break
      }
    }
  }
}

MacroManagerBase.extend(MacroManager)

export default MacroManager
<commit_msg>E6ify MacroManager<commit_after>import MacroManagerBase from 'substance/ui/MacroManager'

/**
 * A custom `MacroManager` which excludes text in existing annotations
 * from macros regex test strings.
 *
 * @class      MacroManager (name)
 */
class MacroManager extends MacroManagerBase {
  // This function is from `substance/ui/MacroManager` except for the part
  // labelled as "Modification" below
  executeMacros (update, info) {
    var change = update.change
    if (!change) {
      return
    }

    var doc = this.context.documentSession.getDocument()
    var nodeId, node, text
    var path
    if (info.action === 'type') {
      // HACK: we know that there is only one op when we type something
      var op = change.ops[0]
      path = op.path
      nodeId = path[0]
      node = doc.get(nodeId)
      text = doc.get(path)
    } else {
      return
    }

    // Modification: converts text within existing annotations to spaces so
    // that they are not matched in subsequent macros
    var annos = doc.getIndex('annotations').get(path)
    annos.forEach(function (anno) {
      var length = anno.endOffset - anno.startOffset + 1
      text = text.substring(0, anno.startOffset) + Array(length + 1).join(' ') + text.substring(anno.endOffset + 1)
    })

    var props = {
      action: info.action,
      node: node,
      path: path,
      text: text,
      selection: this.context.documentSession.getSelection()
    }
    for (var i = 0; i < this.macros.length; i++) {
      var macro = this.macros[i]
      var executed = macro.execute(props, this.context)

      if (executed) {
        break
      }
    }
  }
}

export default MacroManager
<|endoftext|>


<commit_before>class Main extends Phaser.State {
	constructor() {
		super();
		this.groundFront;
		this.player;
		this.jumpButton;
		this.doubleJump = 1;
		this.jumpTimer = 0;
		this.timer = 0;
		this.total = 0;
		this.score = 0;
		this.tractor;
		this.weed;
	}

	create() {
		//Enable Arcade Physics
		this.game.physics.startSystem(Phaser.Physics.ARCADE);
		this.game.physics.arcade.gravity.y = 2000;

		//Set the games background colour
		this.game.stage.backgroundColor = '#c8f2fb';
		// this.sky = this.game.add.sprite(0,0,'sky');
		// this.sky.scale.setTo(5,5);

		this.mountainsBack = this.game.add.tileSprite(0,
			this.game.height - this.game.cache.getImage('mountains-back').height,
			this.game.width,
			this.game.cache.getImage('mountains-back').height,
			'mountains-back'
		);

		this.hillsMid1 = this.game.add.tileSprite(0,
			this.game.height - this.game.cache.getImage('hills-mid1').height,
			this.game.width,
			this.game.cache.getImage('hills-mid1').height,
			'hills-mid1'
		);

		this.fenceMid2 = this.game.add.tileSprite(0,
			this.game.height - this.game.cache.getImage('fence-mid2').height,
			this.game.width,
			this.game.cache.getImage('fence-mid2').height,
			'fence-mid2'
		);

		this.groundFront = this.game.add.tileSprite(0,
			this.game.height - this.game.cache.getImage('ground-front').height,
			this.game.width,
			this.game.cache.getImage('ground-front').height,
			'ground-front'
		);

		this.labelScore = this.game.add.text(20, 20, "0", { font: "30px Arial", fill: "#fffff"});

		this.player = this.game.add.sprite(500, 1000, 'dude');
		this.player.scale.setTo(3, 3);

		this.player.animations.add('left', [0, 1, 2, 3], 10, true);
		this.player.animations.add('right', [5, 6, 7, 8], 10, true);

		this.game.physics.arcade.enable([this.player, this.groundFront]);
		this.player.body.collideWorldBounds = true;
		this.player.body.gravity.y = -50;
		// this.player.body.maxVelocity.y = 1000;

		this.groundFront.body.collideWorldBounds = true;
		this.groundFront.body.immovable = true;
		this.groundFront.body.allowGravity = false;

		this.obstacles = this.game.add.group();
		this.stopButton = this.game.add.button(this.game.width - 90, 15, 'stop-game', this.stopGame, this);
	}

	stopGame() {
		this.game.state.start('Stats');
	}

	addTractors() {
		// Generate Obstacles
		// this.tempRock = this.game.add.sprite(0,0, 'rock');
		this.tractor = this.game.add.sprite( 2800 , 1000, 'tractor', );
		this.tractor.scale.setTo(5, 5);
		this.game.physics.arcade.enable(this.tractor);
		console.log(this.tractor.x)

		this.tractor.animations.add('walk')
		this.tractor.animations.play('walk', 200, true);

		this.game.add.tween(this.tractor).to({
			x: this.tractor.x - 50000 }, 110000, Phaser.Easing.Linear.None, true);

		this.obstacles.add(this.tractor);
		this.total++;
		this.timer = this.game.time.now + 6000;
		this.tractor.checkWorldBounds = true;
		this.tractor.outofBoundsKill = true;
		this.score += 1;
		this.labelScore.text = this.score;

	}

	addWeeds() {
		this.weed = this.game.add.sprite( 3500 ,1000, 'weed', );
		console.log(this.weed.x)
		this.weed.scale.setTo(5, 5);
		this.game.physics.arcade.enable(this.weed);

		this.weed.animations.add('waddle')
		this.weed.animations.play('waddle', 1000, true);
		this.weed.animations.getAnimation('waddle').delay = 500

		this.game.add.tween(this.weed).to({
			x: this.weed.x - 300000 }, 110000, Phaser.Easing.Linear.None, true);

		this.obstacles.add(this.weed);
		this.total++;
		this.timer = this.game.time.now + 9000;
		this.weed.checkWorldBounds = true;
		this.weed.outofBoundsKill = true;
		this.score += 1;
		this.labelScore.text = this.score;

	}

	endGame() {
		this.game.state.start('Stats');
	}

	update() {
		this.player.animations.play('right');
		this.game.physics.arcade.collide(this.player, this.groundFront);
		this.game.physics.arcade.collide(this.weed, this.groundFront);
		this.game.physics.arcade.collide(this.tractor, this.groundFront);

		this.mountainsBack.tilePosition.x -= 0.10;
		this.hillsMid1.tilePosition.x -= 0.3;
		this.fenceMid2.tilePosition.x -= 3.0;
		this.groundFront.tilePosition.x -= 6.0;

		if(this.game.input.activePointer.justPressed() && (this.game.time.now > this.jumpTimer) && this.doubleJump < 2) {
			this.player.body.velocity.y = -1250;
			this.player.body.velocity.x = 2;
			this.jumpTimer = this.game.time.now + 200;
			this.doubleJump += 1;
		}

		if(this.player.body.touching.down){
			this.doubleJump = 1;
		}

		if (this.total < 1000 && this.game.time.now > this.timer){
			this.addTractors();
			this.addWeeds();
		}

		this.game.physics.arcade.overlap(
			this.player, this.obstacles, this.endGame, null, this);
		}

}

export default Main;
<commit_msg>delete console log weed value<commit_after>class Main extends Phaser.State {
	constructor() {
		super();
		this.groundFront;
		this.player;
		this.jumpButton;
		this.doubleJump = 1;
		this.jumpTimer = 0;
		this.timer = 0;
		this.total = 0;
		this.score = 0;
		this.tractor;
		this.weed;
	}

	create() {
		//Enable Arcade Physics
		this.game.physics.startSystem(Phaser.Physics.ARCADE);
		this.game.physics.arcade.gravity.y = 2000;

		//Set the games background colour
		this.game.stage.backgroundColor = '#c8f2fb';
		// this.sky = this.game.add.sprite(0,0,'sky');
		// this.sky.scale.setTo(5,5);

		this.mountainsBack = this.game.add.tileSprite(0,
			this.game.height - this.game.cache.getImage('mountains-back').height,
			this.game.width,
			this.game.cache.getImage('mountains-back').height,
			'mountains-back'
		);

		this.hillsMid1 = this.game.add.tileSprite(0,
			this.game.height - this.game.cache.getImage('hills-mid1').height,
			this.game.width,
			this.game.cache.getImage('hills-mid1').height,
			'hills-mid1'
		);

		this.fenceMid2 = this.game.add.tileSprite(0,
			this.game.height - this.game.cache.getImage('fence-mid2').height,
			this.game.width,
			this.game.cache.getImage('fence-mid2').height,
			'fence-mid2'
		);

		this.groundFront = this.game.add.tileSprite(0,
			this.game.height - this.game.cache.getImage('ground-front').height,
			this.game.width,
			this.game.cache.getImage('ground-front').height,
			'ground-front'
		);

		this.labelScore = this.game.add.text(20, 20, "0", { font: "30px Arial", fill: "#fffff"});

		this.player = this.game.add.sprite(500, 1000, 'dude');
		this.player.scale.setTo(3, 3);

		this.player.animations.add('left', [0, 1, 2, 3], 10, true);
		this.player.animations.add('right', [5, 6, 7, 8], 10, true);

		this.game.physics.arcade.enable([this.player, this.groundFront]);
		this.player.body.collideWorldBounds = true;
		this.player.body.gravity.y = -50;
		// this.player.body.maxVelocity.y = 1000;

		this.groundFront.body.collideWorldBounds = true;
		this.groundFront.body.immovable = true;
		this.groundFront.body.allowGravity = false;

		this.obstacles = this.game.add.group();
		this.stopButton = this.game.add.button(this.game.width - 90, 15, 'stop-game', this.stopGame, this);
	}

	stopGame() {
		this.game.state.start('Stats');
	}

	addTractors() {
		// Generate Obstacles
		// this.tempRock = this.game.add.sprite(0,0, 'rock');
		this.tractor = this.game.add.sprite( 2800 , 1000, 'tractor', );
		this.tractor.scale.setTo(5, 5);
		this.game.physics.arcade.enable(this.tractor);
		console.log(this.tractor.x)

		this.tractor.animations.add('walk')
		this.tractor.animations.play('walk', 200, true);

		this.game.add.tween(this.tractor).to({
			x: this.tractor.x - 50000 }, 110000, Phaser.Easing.Linear.None, true);

		this.obstacles.add(this.tractor);
		this.total++;
		this.timer = this.game.time.now + 6000;
		this.tractor.checkWorldBounds = true;
		this.tractor.outofBoundsKill = true;
		this.score += 1;
		this.labelScore.text = this.score;

	}

	addWeeds() {
		this.weed = this.game.add.sprite( 3500 ,1000, 'weed', );
		this.weed.scale.setTo(5, 5);
		this.game.physics.arcade.enable(this.weed);

		this.weed.animations.add('waddle')
		this.weed.animations.play('waddle', 1000, true);
		this.weed.animations.getAnimation('waddle').delay = 500

		this.game.add.tween(this.weed).to({
			x: this.weed.x - 300000 }, 110000, Phaser.Easing.Linear.None, true);

		this.obstacles.add(this.weed);
		this.total++;
		this.timer = this.game.time.now + 9000;
		this.weed.checkWorldBounds = true;
		this.weed.outofBoundsKill = true;
		this.score += 1;
		this.labelScore.text = this.score;

	}

	endGame() {
		this.game.state.start('Stats');
	}

	update() {
		this.player.animations.play('right');
		this.game.physics.arcade.collide(this.player, this.groundFront);
		this.game.physics.arcade.collide(this.weed, this.groundFront);
		this.game.physics.arcade.collide(this.tractor, this.groundFront);

		this.mountainsBack.tilePosition.x -= 0.10;
		this.hillsMid1.tilePosition.x -= 0.3;
		this.fenceMid2.tilePosition.x -= 3.0;
		this.groundFront.tilePosition.x -= 6.0;

		if(this.game.input.activePointer.justPressed() && (this.game.time.now > this.jumpTimer) && this.doubleJump < 2) {
			this.player.body.velocity.y = -1250;
			this.player.body.velocity.x = 2;
			this.jumpTimer = this.game.time.now + 200;
			this.doubleJump += 1;
		}

		if(this.player.body.touching.down){
			this.doubleJump = 1;
		}

		if (this.total < 1000 && this.game.time.now > this.timer){
			this.addTractors();
			this.addWeeds();
		}

		this.game.physics.arcade.overlap(
			this.player, this.obstacles, this.endGame, null, this);
		}

}

export default Main;
<|endoftext|>


<commit_before>describe('Select on Enter', function () {
    'use strict';

    var serviceUrl = '/some/url';

    beforeEach(function(){
        this.input = document.createElement('input');
        this.instance = $(this.input).suggestions({
            serviceUrl: serviceUrl
        }).suggestions();

        this.server = sinon.fakeServer.create();
    });

    afterEach(function () {
        $('.autocomplete-suggestions').remove();
        this.server.restore();
    });

    it('Should trigger suggestion when it equals to query', function () {
        var suggestions = [
                { value: 'Afghanistan', data: 'Af' },
                { value: 'Albania', data: 'Al' },
                { value: 'Andorra', data: 'An' }
            ],
            options = {
                lookup: suggestions,
                onSelect: function(){}
            };
        spyOn(options, 'onSelect');

        this.instance.setOptions(options);
        this.instance.selectedIndex = -1;

        this.input.value = 'Albania';
        this.instance.onValueChange();

        var event = $.Event('keydown');
        event.keyCode = event.which = 13; // code of Enter
        $(this.input).trigger(event);

        expect(options.onSelect).toHaveBeenCalledWith(suggestions[1]);
    });

    it('Should trigger suggestion when it is selected', function () {
        var suggestions = [
            { value: 'Afghanistan', data: 'Af' },
            { value: 'Albania', data: 'Al' },
            { value: 'Andorra', data: 'An' }
        ];
        var options = {
                lookup: suggestions,
                onSelect: function(){}
            };
        spyOn(options, 'onSelect');

        this.instance.setOptions(options);

        this.input.value = 'A';
        this.instance.onValueChange();

        this.instance.selectedIndex = 2;

        var event = $.Event('keydown');
        event.keyCode = event.which = 13; // code of Enter
        $(this.input).trigger(event);

        expect(options.onSelect).toHaveBeenCalledWith(suggestions[2]);
    });

    it('Should NOT trigger when nothing matched', function () {
        var suggestion = { value: 'Jamaica', data: 'J' },
            options = {
                lookup: [suggestion],
                onSelect: function(){}
            };
        spyOn(options, 'onSelect');

        this.instance.setOptions(options);
        this.instance.selectedIndex = -1;

        this.input.value = 'Alg';
        this.instance.onValueChange();

        var event = $.Event('keydown');
        event.keyCode = event.which = 13; // code of Enter
        $(this.input).trigger(event);

        expect(options.onSelect).not.toHaveBeenCalled();
    });
});<commit_msg>sug-108 more specs for select on Enter behavior<commit_after>describe('Select on Enter', function () {
    'use strict';

    var serviceUrl = '/some/url';

    beforeEach(function(){
        this.input = document.createElement('input');
        this.instance = $(this.input).suggestions({
            serviceUrl: serviceUrl
        }).suggestions();

        this.server = sinon.fakeServer.create();
    });

    afterEach(function () {
        $('.autocomplete-suggestions').remove();
        this.server.restore();
    });

    it('Should trigger on full match', function () {
        var suggestions = [
                { value: 'Afghanistan', data: 'Af' },
                { value: 'Albania', data: 'Al' },
                { value: 'Andorra', data: 'An' }
            ],
            options = {
                lookup: suggestions,
                onSelect: function(){}
            };
        spyOn(options, 'onSelect');

        this.instance.setOptions(options);
        this.instance.selectedIndex = -1;

        this.input.value = 'Albania';
        this.instance.onValueChange();

        var event = $.Event('keydown');
        event.keyCode = event.which = 13; // code of Enter
        $(this.input).trigger(event);

        expect(options.onSelect).toHaveBeenCalledWith(suggestions[1]);
    });

    it('Should trigger when suggestion is selected manually', function () {
        var suggestions = [
            { value: 'Afghanistan', data: 'Af' },
            { value: 'Albania', data: 'Al' },
            { value: 'Andorra', data: 'An' }
        ];
        var options = {
                lookup: suggestions,
                onSelect: function(){}
            };
        spyOn(options, 'onSelect');

        this.instance.setOptions(options);

        this.input.value = 'A';
        this.instance.onValueChange();

        this.instance.selectedIndex = 2;

        var event = $.Event('keydown');
        event.keyCode = event.which = 13; // code of Enter
        $(this.input).trigger(event);

        expect(options.onSelect).toHaveBeenCalledWith(suggestions[2]);
    });

    it('Should NOT trigger on partial match', function () {
        var suggestion = { value: 'Jamaica', data: 'J' },
            options = {
                lookup: [suggestion],
                onSelect: function(){}
            };
        spyOn(options, 'onSelect');

        this.instance.setOptions(options);
        this.instance.selectedIndex = -1;

        this.input.value = 'Jam';
        this.instance.onValueChange();

        var event = $.Event('keydown');
        event.keyCode = event.which = 13; // code of Enter
        $(this.input).trigger(event);

        expect(options.onSelect).not.toHaveBeenCalled();
    });

    it('Should NOT trigger when nothing matched', function () {
        var suggestion = { value: 'Jamaica', data: 'J' },
            options = {
                lookup: [suggestion],
                onSelect: function(){}
            };
        spyOn(options, 'onSelect');

        this.instance.setOptions(options);
        this.instance.selectedIndex = -1;

        this.input.value = 'Alg';
        this.instance.onValueChange();

        var event = $.Event('keydown');
        event.keyCode = event.which = 13; // code of Enter
        $(this.input).trigger(event);

        expect(options.onSelect).not.toHaveBeenCalled();
    });
});<|endoftext|>