<commit_before>var childProcess = require('child_process'),
    fs = require('fs'),
    os = require('os');

module.exports = function(grunt) {
  grunt.registerTask('test:bin', function() {
    var done = this.async();

    // On Windows, the executable handlebars.js file cannot be run directly
    var prefix = os.type().match(/^Windows/) ? process.argv[0] : '';
    childProcess.exec(prefix + ' ./bin/handlebars -a spec/artifacts/empty.handlebars', function(err, stdout) {
      if (err) {
        throw err;
      }

      var expected = fs.readFileSync('./spec/expected/empty.amd.js');
      if (stdout.toString() !== expected.toString()) {
        throw new Error('Expected binary output differed:\n\n"' + stdout + '"\n\n"' + expected + '"');
      }

      done();
    });
  });
  grunt.registerTask('test:mocha', function() {
    var done = this.async();

    var runner = childProcess.fork('./spec/env/runner', [], {stdio: 'inherit'});
    runner.on('close', function(code) {
      if (code != 0) {
        grunt.fatal(code + ' tests failed');
      }
      done();
    });
  });
  grunt.registerTask('test:cov', function() {
    var done = this.async();

    var runner = childProcess.fork('node_modules/istanbul/lib/cli.js', ['cover', '--source-map', '--', './spec/env/runner.js'], {stdio: 'inherit'});
    runner.on('close', function(code) {
      if (code != 0) {
        grunt.fatal(code + ' tests failed');
      }
      done();
    });
  });
  grunt.registerTask('test:min', function() {
    var done = this.async();

    var runner = childProcess.fork('./spec/env/runner', ['--min'], {stdio: 'inherit'});
    runner.on('close', function(code) {
      if (code != 0) {
        grunt.fatal(code + ' tests failed');
      }
      done();
    });
  });

  grunt.registerTask('test:check-cov', function() {
    var done = this.async();

    var runner = childProcess.fork('node_modules/istanbul/lib/cli.js', ['check-coverage', '--statements', '100', '--functions', '100', '--branches', '100', '--lines 100'], {stdio: 'inherit'});
    runner.on('close', function(code) {
      if (code != 0) {
        grunt.fatal('Coverage check failed: ' + code);
      }
      done();
    });
  });
  grunt.registerTask('test', ['test:bin', 'test:cov', 'test:check-cov']);
};
<commit_msg>Fix build in windows<commit_after>var childProcess = require('child_process'),
    fs = require('fs'),
    os = require('os');

module.exports = function(grunt) {
  grunt.registerTask('test:bin', function() {
    var done = this.async();

    // On Windows, the executable handlebars.js file cannot be run directly
    var prefix = os.type().match(/^Windows/) ? process.argv[0] : '';
    childProcess.exec(prefix + ' ./bin/handlebars -a spec/artifacts/empty.handlebars', function(err, stdout) {
      if (err) {
        throw err;
      }

      var expected = fs.readFileSync('./spec/expected/empty.amd.js').toString().replace(/\r\n/g, '\n');

      if (stdout.toString() !== expected) {
        throw new Error('Expected binary output differed:\n\n"' + stdout + '"\n\n"' + expected + '"');
      }

      done();
    });
  });
  grunt.registerTask('test:mocha', function() {
    var done = this.async();

    var runner = childProcess.fork('./spec/env/runner', [], {stdio: 'inherit'});
    runner.on('close', function(code) {
      if (code != 0) {
        grunt.fatal(code + ' tests failed');
      }
      done();
    });
  });
  grunt.registerTask('test:cov', function() {
    var done = this.async();

    var runner = childProcess.fork('node_modules/istanbul/lib/cli.js', ['cover', '--source-map', '--', './spec/env/runner.js'], {stdio: 'inherit'});
    runner.on('close', function(code) {
      if (code != 0) {
        grunt.fatal(code + ' tests failed');
      }
      done();
    });
  });
  grunt.registerTask('test:min', function() {
    var done = this.async();

    var runner = childProcess.fork('./spec/env/runner', ['--min'], {stdio: 'inherit'});
    runner.on('close', function(code) {
      if (code != 0) {
        grunt.fatal(code + ' tests failed');
      }
      done();
    });
  });

  grunt.registerTask('test:check-cov', function() {
    var done = this.async();

    var runner = childProcess.fork('node_modules/istanbul/lib/cli.js', ['check-coverage', '--statements', '100', '--functions', '100', '--branches', '100', '--lines 100'], {stdio: 'inherit'});
    runner.on('close', function(code) {
      if (code != 0) {
        grunt.fatal('Coverage check failed: ' + code);
      }
      done();
    });
  });
  grunt.registerTask('test', ['test:bin', 'test:cov', 'test:check-cov']);
};
<|endoftext|>


<commit_before>'use strict';

const Script = require('smooch-bot').Script;

module.exports = new Script({
    processing: {
        prompt: (bot) => bot.say('Beep boop...'),
        receive: () => 'processing'
    },

    start: {
        receive: (bot) => {
            return bot.say('Hi! I\'m Payroll-Bot!')
                .then(() => 'askName');
        }
    },

    askName: {
        prompt: (bot) => bot.say('What\'s your name?'),
        receive: (bot, message) => {
            const name = message.text;
            return bot.setProp('name', name)
                .then(() => bot.say(`Great! I'll call you ${name}
Is that OK? %[Yes](postback:yes) %[No](postback:no)`))
                .then(() => 'askCase');
        }
    },

    askCase: {
      prompt:(bot) => bot.say('Say something - THING, WHATEVER, YO'),
      receive: (bot, message) => {
        const something = message.text;
        return bot.setProp('something', something)
          switch(something){
            case "THING":
              .then(() => bot.say('You said: ${something}'))
            case: "YO":
              .then(() => bot.say('Yo dawg'))
            default:
              .then(() => bot.say('Did not work'))
          }
      }
    },

    finish: {
        receive: (bot, message) => {
            return bot.getProp('name')
                .then((name) => bot.say(`Sorry ${name}, my creator didn't ` +
                        'teach me how to do anything else!'))
                .then(() => 'finish');
        }
    }
});
<commit_msg>Updated Script<commit_after>'use strict';

const Script = require('smooch-bot').Script;

module.exports = new Script({
    processing: {
        prompt: (bot) => bot.say('Beep boop...'),
        receive: () => 'processing'
    },

    start: {
        receive: (bot) => {
            return bot.say('Hi! I\'m Payroll-Bot!')
                .then(() => 'askName');
        }
    },

    askName: {
        prompt: (bot) => bot.say('What\'s your name?'),
        receive: (bot, message) => {
            const name = message.text;
            return bot.setProp('name', name)
                .then(() => bot.say(`Great! I'll call you ${name}
Is that OK? %[Yes](postback:yes) %[No](postback:no)`))
                .then(() => 'askCase');
        }
    },

    askCase: {
        prompt: (bot) => bot.say('Say something - THING, WHATEVER'),
        receive: (bot, message) => {
          const something = message.text;
            return bot.setProp('something', something)
                .then(() => bot.say(`Great! I'll call you ${something}
Is that OK? %[Yes](postback:yes) %[No](postback:no)`))
                .then(() => 'askCase');
        }
    },

    finish: {
        receive: (bot, message) => {
            return bot.getProp('name')
                .then((name) => bot.say(`Sorry ${name}, my creator didn't ` +
                        'teach me how to do anything else!'))
                .then(() => 'finish');
        }
    }
});
<|endoftext|>


<commit_before>/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
define(
    [
        'underscore',
        'Magento_Checkout/js/model/quote',
        'Adyen_Payment/js/model/adyen-method-list',
        'Magento_Customer/js/model/customer',
        'Magento_Checkout/js/model/url-builder',
        'mage/storage'
    ],
    function (_, quote, methodList, customer, urlBuilder, storage) {
        'use strict';

        return {
            /**
             * Populate the list of payment methods
             * @param {Array} methods
             */
            setPaymentMethods: function (methods) {
                methodList(methods);
            },
            /**
             * Get the list of available payment methods.
             * @returns {Array}
             */
            getAvailablePaymentMethods: function () {
                return methodList();
            },
            /**
             * Retrieve the list of available payment methods from the server
             */
            retrieveAvailablePaymentMethods: function (callback = null) {
                var self = this;

                // retrieve payment methods
                var serviceUrl,
                    payload;
                if (customer.isLoggedIn()) {
                    serviceUrl = urlBuilder.createUrl('/carts/mine/retrieve-adyen-payment-methods', {});
                } else {
                    serviceUrl = urlBuilder.createUrl('/guest-carts/:cartId/retrieve-adyen-payment-methods', {
                        cartId: quote.getQuoteId()
                    });
                }

                payload = {
                    cartId: quote.getQuoteId(),
                    shippingAddress: quote.shippingAddress()
                };

                storage.post(
                    serviceUrl, JSON.stringify(payload)
                ).done(
                    function (response) {
                        self.setPaymentMethods(response);
                        if (callback !== null) {
                            callback();
                        }
                    }
                ).fail(
                    function (response) {
                        self.setPaymentMethods([]);
                    }
                )
            }
        };
    }
);
<commit_msg>Fix for IE11 and older browsers (#536)<commit_after>/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
define(
    [
        'underscore',
        'Magento_Checkout/js/model/quote',
        'Adyen_Payment/js/model/adyen-method-list',
        'Magento_Customer/js/model/customer',
        'Magento_Checkout/js/model/url-builder',
        'mage/storage'
    ],
    function (_, quote, methodList, customer, urlBuilder, storage) {
        'use strict';

        return {
            /**
             * Populate the list of payment methods
             * @param {Array} methods
             */
            setPaymentMethods: function (methods) {
                methodList(methods);
            },
            /**
             * Get the list of available payment methods.
             * @returns {Array}
             */
            getAvailablePaymentMethods: function () {
                return methodList();
            },
            /**
             * Retrieve the list of available payment methods from the server
             */
            retrieveAvailablePaymentMethods: function (callback) {
                var self = this;

                // retrieve payment methods
                var serviceUrl,
                    payload;
                if (customer.isLoggedIn()) {
                    serviceUrl = urlBuilder.createUrl('/carts/mine/retrieve-adyen-payment-methods', {});
                } else {
                    serviceUrl = urlBuilder.createUrl('/guest-carts/:cartId/retrieve-adyen-payment-methods', {
                        cartId: quote.getQuoteId()
                    });
                }

                payload = {
                    cartId: quote.getQuoteId(),
                    shippingAddress: quote.shippingAddress()
                };

                storage.post(
                    serviceUrl, JSON.stringify(payload)
                ).done(
                    function (response) {
                        self.setPaymentMethods(response);
                        if (callback) {
                            callback();
                        }
                    }
                ).fail(
                    function (response) {
                        self.setPaymentMethods([]);
                    }
                )
            }
        };
    }
);
<|endoftext|>


<commit_before>define(['vie', 'logger', 'tracker', 'underscore', 'jquery', 'backbone', 'view/detail/DetailView', 'voc'], function(VIE, Logger, tracker, _, $, Backbone, DetailView, Voc){
    return Backbone.View.extend({
        LOG: Logger.get('EntityView'),
        icons: {
            'sss:addPrivateCollectionItem': 'img/sss/addCollectionItem.png',
            'sss:addSharedCollectionItem': 'img/sss/addCollectionItem.png',
            'sss:changeCollectionByAddPrivateCollectionItem': 'img/sss/changeCollection.png', //changeCollectionAddPrivateCollectionItem
            'sss:changeCollectionByAddSharedCollectionItem': 'img/sss/changeCollection.png', //changeCollectionAddSharedCollectionItem
            //'appearsInSearchResult': 'img/sss/.png',
            'sss:subscribeCollection': 'img/sss/subscribeCollection.png',
            'sss:unSubscribeCollection': 'img/sss/unSubscribeCollection.png',
            'sss:createPrivateCollection': 'img/sss/addCollection.png',
            'sss:createSharedCollection': 'img/sss/addCollection.png',
            'sss:createPrivateRecord': 'img/sss/addDocument.png',
            'sss:createSharedRecord': 'img/sss/addDocument.png',
            'sss:rateEntity': 'img/sss/rate.png',
            'sss:discussEntity': 'img/sss/startDiscussion.png', //startDiscussion
            'sss:addDiscussionComment': 'img/sss/discuss.png',
            'sss:addPrivateTag': 'img/sss/addTag.png',
            'sss:addSharedTag': 'img/sss/addTag.png',
            'sss:removePrivateTag': 'img/sss/deleteTag.png',
            'sss:removeSharedTag': 'img/sss/deleteTag.png',
            'sss:renamePrivateCollectionItem': 'img/sss/renameCollectionItem.png',
            'sss:renameSharedCollectionItem': 'img/sss/renameCollectionItem.png',
            'sss:removePrivateCollectionItem': 'img/sss/removeCollectionItem.png',
            'sss:removeSharedCollectionItem': 'img/sss/removeCollectionItem.png',
            'sss:removePrivateCollection': 'img/sss/deleteCollection.png',
            'sss:removeSharedCollection': 'img/sss/deleteCollection.png',
            'sss:removePrivateRecord': 'img/sss/deleteDocument.png',
            'sss:removeSharedRecord': 'img/sss/deleteDocument.png',
            'sss:renameDiscussion': 'img/sss/renameDiscussion.png',
            'sss:changeCollectionByRemovePrivateCollectionItem': 'img/sss/changeCollection.png', //changeCollectionRemovePrivateCollectionItem
            'sss:changeCollectionByRemoveSharedCollectionItem': 'img/sss/changeCollection.png', //changeCollectionRemoveSharedCollectionItem
            //'newDiscussionByDiscussEntity': 'img/sss/.png'
            'sss:renamePrivateCollection':'img/sss/editCollection.png',
            'sss:renameSharedCollection':'img/sss/editCollection.png',
            'sss:renamePrivateRecord':'img/sss/editDocument.png',
            'sss:renameSharedRecord':'img/sss/editDocument.png',
            'sss:shareCollection':'img/sss/shareCollection.png',
            'sss:shareDocument':'img/sss/shareDocument.png',
            'sss:user' : 'img/sss/user1.png',
            'sss:coll' : 'img/sss/collection.png',
            'owl:Thing' : 'img/sss/thing.png',
            'sss:user/peter/' : 'img/sss/user2.png',
            'sss:user/paul/' : 'img/sss/user1.png',
            'sss:entity' : 'img/sss/entityLink.png',
            'sss:disc' : 'img/sss/discuss.png',
            'sss:discEntry' : 'img/sss/discuss.png',
            'sss:file' : 'img/sss/document.png',
            'sss:filePdf' : 'img/sss/entityFilePdf.png',
            'sss:filePng' : 'img/sss/entityImageJpg.png',
            'sss:fileDoc' : 'img/sss/entityFileDoc.png',
            'sss:rating' : 'img/sss/rate.png',
            'sss:tag' : 'img/evernote/tag.png',
            //'sss:userEvent' : 'img/sss/userEvent.png',
            //'sss:learnEp' : 'img/evernote/learnEp.png',
            //'sss:learnEpTimelineState' : 'img/evernote/learnEpTimelineState.png',
            //'sss:learnEpVersion' : 'img/evernote/learnEpVersion.png',
            //'sss:learnEpCircle' : 'img/evernote/learnEpCircle.png',
            //'sss:learnEpEntity' : 'img/evernote/learnEpEntity.png',

            'unknown' : 'img/sss/unknown.png',
            // EVERNOTE STUFF
            'sss:evernoteNotebook' : 'img/sss/collection.png',
            'sss:evernoteNote' : 'img/sss/evernoteNote.png',
            'sss:evernoteResource' : 'img/sss/thing.png',

            'sss:evernoteNotebookCreate' : 'img/sss/addCollection.png',
            'sss:evernoteNotebookUpdate' : 'img/sss/editCollection.png',
            'sss:evernoteNotebookShare' : 'img/sss/shareCollection.png',
            'sss:evernoteNotebookFollow' : 'img/sss/subscribeCollection.png',
            'sss:evernoteNoteCreate' : 'img/sss/addDocument.png',
            'sss:evernoteNoteUpdate' : 'img/sss/editDocument.png',
            'sss:evernoteNoteDelete' : 'img/sss/deleteDocument.png',
            'sss:evernoteNoteShare' : 'img/sss/shareDocument.png',
            'sss:evernoteNoteFollow' : 'img/sss/subscribeDocument.png',
            'sss:evernoteReminderDone' : 'img/sss/reminderDone.png',
            'sss:evernoteReminderCreate' : 'img/sss/reminder.png',
            'sss:evernoteResourceAdd' : 'img/sss/addCollectionItem.png',
            'sss:evernoteResourceFollow' : 'img/sss/subscribeResource.png',
            'sss:evernoteResourceShare' : 'img/sss/shareResource.png'

        },
        events : {
          'click' : '_click'
          //'contextmenu' : 'detailView'
        },
        initialize: function() {
            this.model.on('change', this.render,this );
        },
        click: function(e) {
            this.LOG.error('clicked', e);
            if( e.which === 1 ) {
                this.defer();
            } else if( e.which === 3) {
                this.detailView();
                return false;
            }
        },
        // click function to manage click/dblclick
        _click: function(e) {
            var el=$(this);
            this.LOG.debug('_click');
            if (this.alreadyclicked)
            {
                this.alreadyclicked=false; // reset
                clearTimeout(this.alreadyclickedTimeout); // prevent this from happening
                this.defer();
            }
            else
            {
                this.alreadyclicked=true;
                var view = this;
                //view.detailView(e);
                this.alreadyclickedTimeout=setTimeout(function(){
                    view.alreadyclicked=false; // reset when it happens
                    view.LOG.debug('_click timeOut');
                },400); // <-- dblclick tolerance here
            }
            var ev = $.Event('bnp:clickEntity', {
                originalEvent : e,
                entity : this.model
            });
            this.$el.trigger(ev);
            return false;
        },
        defer: function() {
            this.LOG.debug('defer');
            var resource = this.model.get(Voc.hasResource);
            if( !resource ) resource = this.model.getSubject();
            else resource = resource.getSubject();
            var lastChar = resource[resource.length-1];
            if( lastChar === '/') resource = resource.substring(0, resource.length-1);
            tracker.info(tracker.OPENRESOURCE, resource);
            this.LOG.log('open resource', resource);
            window.open(resource);
        },
        render: function() {
            var label,
                view_class;

            this.$el.attr({
              'class' : 'entity',
              'about' : this.model.getSubject()
            });
            label = this.model.get(Voc.label);
            view_class = 'labelable';

            if( true === this.model.get(Voc.isUsed) ) {
                view_class += ' used';
            }

            if( label && label.isEntity ) label = label.getSubject();
            this.$el.html(//"
"+
                    "
"+
                    ""+
                    (label ?
                        "" +
                        ""+label+"":"no label")+
                        ""+
                    "
");
            this.LOG.debug('rendering ', this.model);
            this.draggable();
            return this;
        },
        detailView: function(e) {
            this.LOG.debug("clicked entity");
            this.LOG.debug("e", e);
            if( !e.currentTarget ) return;
            var id = $(e.currentTarget).attr('about');
            if( !id ) return;
            this.LOG.debug("id", id);
            if( id != this.model.getSubject() ) return;
            tracker.info(tracker.VIEWDETAILS, id);

            // --- ADD THE DETAIL VIEW --- //
            var detailViewId = "detailView" + id.replace(/[\\/:-\\.#]/g, '');
            if( !document.getElementById(detailViewId)) {
                $('body').append("
");
                var detailView = new DetailView({
                    model: this.model,
                    el: '#' + detailViewId
                });
            }
            this.model.trigger('showDetails', e);
            return false;

        },
        draggable: function() {
            var VIEW = this;
            this.$el.draggable({
                zIndex: 10000,
                helper: "clone",
                appendTo: "body",
                drag: function(event, ui) {
                    VIEW.LOG.debug('dragging');
                    var ev = event;
                    while (ev != null) {
                        if (ev.type == "mousemove")
                            ev.stopImmediatePropagation();
                        ev = ev.originalEvent;
                    }
                }
            });

        },
        getIcon: function(type) {
            var name,
                mimeType;
            // TODO: make clear use of URIs
            this.LOG.debug('model', _.clone(this.model.attributes));
            if( !type ) type = this.model.get('@type');
            this.LOG.debug('type', type);
            if( !type ) return this.icons['unknown'];
            name = this.model.vie.namespaces.curie(type.id);
            this.LOG.debug('name', name);
            if( name === 'user' ) {
                name = this.model.vie.namespaces.curie(this.model.getSubject());
                if( !this.icons[name]) name = 'user';
            }

            if ( 'sss:file' === name ) {
                mimeType  = this.model.get(Voc.hasMimeType);
                if ( mimeType ) {
                    switch( mimeType ) {
                        case 'application/pdf':
                            name = 'sss:filePdf';
                            break;
                        case 'image/png':
                            name = 'sss:filePng';
                            break;
                        case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
                        case 'application/msword':
                            name = 'sss:fileDoc';
                            break;
                    }
                }
            }

            if( !this.icons[name]) return this.icons['unknown'];
            return this.icons[name];
        },
        /**
         * Returns the average width of an entity.
         * TODO fix hard-coded width
         */
        getWidth: function() {
            return 40;
        }
    });
});
<commit_msg>LL-350: hiding evernoteResource and evernoteNotebook from app<commit_after>define(['vie', 'logger', 'tracker', 'underscore', 'jquery', 'backbone', 'view/detail/DetailView', 'voc'], function(VIE, Logger, tracker, _, $, Backbone, DetailView, Voc){
    return Backbone.View.extend({
        LOG: Logger.get('EntityView'),
        icons: {
            'sss:addPrivateCollectionItem': 'img/sss/addCollectionItem.png',
            'sss:addSharedCollectionItem': 'img/sss/addCollectionItem.png',
            'sss:changeCollectionByAddPrivateCollectionItem': 'img/sss/changeCollection.png', //changeCollectionAddPrivateCollectionItem
            'sss:changeCollectionByAddSharedCollectionItem': 'img/sss/changeCollection.png', //changeCollectionAddSharedCollectionItem
            //'appearsInSearchResult': 'img/sss/.png',
            'sss:subscribeCollection': 'img/sss/subscribeCollection.png',
            'sss:unSubscribeCollection': 'img/sss/unSubscribeCollection.png',
            'sss:createPrivateCollection': 'img/sss/addCollection.png',
            'sss:createSharedCollection': 'img/sss/addCollection.png',
            'sss:createPrivateRecord': 'img/sss/addDocument.png',
            'sss:createSharedRecord': 'img/sss/addDocument.png',
            'sss:rateEntity': 'img/sss/rate.png',
            'sss:discussEntity': 'img/sss/startDiscussion.png', //startDiscussion
            'sss:addDiscussionComment': 'img/sss/discuss.png',
            'sss:addPrivateTag': 'img/sss/addTag.png',
            'sss:addSharedTag': 'img/sss/addTag.png',
            'sss:removePrivateTag': 'img/sss/deleteTag.png',
            'sss:removeSharedTag': 'img/sss/deleteTag.png',
            'sss:renamePrivateCollectionItem': 'img/sss/renameCollectionItem.png',
            'sss:renameSharedCollectionItem': 'img/sss/renameCollectionItem.png',
            'sss:removePrivateCollectionItem': 'img/sss/removeCollectionItem.png',
            'sss:removeSharedCollectionItem': 'img/sss/removeCollectionItem.png',
            'sss:removePrivateCollection': 'img/sss/deleteCollection.png',
            'sss:removeSharedCollection': 'img/sss/deleteCollection.png',
            'sss:removePrivateRecord': 'img/sss/deleteDocument.png',
            'sss:removeSharedRecord': 'img/sss/deleteDocument.png',
            'sss:renameDiscussion': 'img/sss/renameDiscussion.png',
            'sss:changeCollectionByRemovePrivateCollectionItem': 'img/sss/changeCollection.png', //changeCollectionRemovePrivateCollectionItem
            'sss:changeCollectionByRemoveSharedCollectionItem': 'img/sss/changeCollection.png', //changeCollectionRemoveSharedCollectionItem
            //'newDiscussionByDiscussEntity': 'img/sss/.png'
            'sss:renamePrivateCollection':'img/sss/editCollection.png',
            'sss:renameSharedCollection':'img/sss/editCollection.png',
            'sss:renamePrivateRecord':'img/sss/editDocument.png',
            'sss:renameSharedRecord':'img/sss/editDocument.png',
            'sss:shareCollection':'img/sss/shareCollection.png',
            'sss:shareDocument':'img/sss/shareDocument.png',
            'sss:user' : 'img/sss/user1.png',
            'sss:coll' : 'img/sss/collection.png',
            'owl:Thing' : 'img/sss/thing.png',
            'sss:user/peter/' : 'img/sss/user2.png',
            'sss:user/paul/' : 'img/sss/user1.png',
            'sss:entity' : 'img/sss/entityLink.png',
            'sss:disc' : 'img/sss/discuss.png',
            'sss:discEntry' : 'img/sss/discuss.png',
            'sss:file' : 'img/sss/document.png',
            'sss:filePdf' : 'img/sss/entityFilePdf.png',
            'sss:filePng' : 'img/sss/entityImageJpg.png',
            'sss:fileDoc' : 'img/sss/entityFileDoc.png',
            'sss:rating' : 'img/sss/rate.png',
            'sss:tag' : 'img/evernote/tag.png',
            //'sss:userEvent' : 'img/sss/userEvent.png',
            //'sss:learnEp' : 'img/evernote/learnEp.png',
            //'sss:learnEpTimelineState' : 'img/evernote/learnEpTimelineState.png',
            //'sss:learnEpVersion' : 'img/evernote/learnEpVersion.png',
            //'sss:learnEpCircle' : 'img/evernote/learnEpCircle.png',
            //'sss:learnEpEntity' : 'img/evernote/learnEpEntity.png',

            'unknown' : 'img/sss/unknown.png',
            // EVERNOTE STUFF
            'sss:evernoteNotebook' : 'img/sss/collection.png',
            'sss:evernoteNote' : 'img/sss/evernoteNote.png',
            'sss:evernoteResource' : 'img/sss/thing.png',

            //'sss:evernoteNotebookCreate' : 'img/sss/addCollection.png',
            //'sss:evernoteNotebookUpdate' : 'img/sss/editCollection.png',
            //'sss:evernoteNotebookShare' : 'img/sss/shareCollection.png',
            //'sss:evernoteNotebookFollow' : 'img/sss/subscribeCollection.png',
            'sss:evernoteNoteCreate' : 'img/sss/addDocument.png',
            'sss:evernoteNoteUpdate' : 'img/sss/editDocument.png',
            'sss:evernoteNoteDelete' : 'img/sss/deleteDocument.png',
            'sss:evernoteNoteShare' : 'img/sss/shareDocument.png',
            'sss:evernoteNoteFollow' : 'img/sss/subscribeDocument.png',
            'sss:evernoteReminderDone' : 'img/sss/reminderDone.png',
            'sss:evernoteReminderCreate' : 'img/sss/reminder.png',
            //'sss:evernoteResourceAdd' : 'img/sss/addCollectionItem.png',
            //'sss:evernoteResourceFollow' : 'img/sss/subscribeResource.png',
            //'sss:evernoteResourceShare' : 'img/sss/shareResource.png'

        },
        events : {
          'click' : '_click'
          //'contextmenu' : 'detailView'
        },
        initialize: function() {
            this.model.on('change', this.render,this );
        },
        click: function(e) {
            this.LOG.error('clicked', e);
            if( e.which === 1 ) {
                this.defer();
            } else if( e.which === 3) {
                this.detailView();
                return false;
            }
        },
        // click function to manage click/dblclick
        _click: function(e) {
            var el=$(this);
            this.LOG.debug('_click');
            if (this.alreadyclicked)
            {
                this.alreadyclicked=false; // reset
                clearTimeout(this.alreadyclickedTimeout); // prevent this from happening
                this.defer();
            }
            else
            {
                this.alreadyclicked=true;
                var view = this;
                //view.detailView(e);
                this.alreadyclickedTimeout=setTimeout(function(){
                    view.alreadyclicked=false; // reset when it happens
                    view.LOG.debug('_click timeOut');
                },400); // <-- dblclick tolerance here
            }
            var ev = $.Event('bnp:clickEntity', {
                originalEvent : e,
                entity : this.model
            });
            this.$el.trigger(ev);
            return false;
        },
        defer: function() {
            this.LOG.debug('defer');
            var resource = this.model.get(Voc.hasResource);
            if( !resource ) resource = this.model.getSubject();
            else resource = resource.getSubject();
            var lastChar = resource[resource.length-1];
            if( lastChar === '/') resource = resource.substring(0, resource.length-1);
            tracker.info(tracker.OPENRESOURCE, resource);
            this.LOG.log('open resource', resource);
            window.open(resource);
        },
        render: function() {
            var label,
                view_class;

            this.$el.attr({
              'class' : 'entity',
              'about' : this.model.getSubject()
            });
            label = this.model.get(Voc.label);
            view_class = 'labelable';

            if( true === this.model.get(Voc.isUsed) ) {
                view_class += ' used';
            }

            if( label && label.isEntity ) label = label.getSubject();
            this.$el.html(//"
"+
                    "
"+
                    ""+
                    (label ?
                        "" +
                        ""+label+"":"no label")+
                        ""+
                    "
");
            this.LOG.debug('rendering ', this.model);
            this.draggable();
            return this;
        },
        detailView: function(e) {
            this.LOG.debug("clicked entity");
            this.LOG.debug("e", e);
            if( !e.currentTarget ) return;
            var id = $(e.currentTarget).attr('about');
            if( !id ) return;
            this.LOG.debug("id", id);
            if( id != this.model.getSubject() ) return;
            tracker.info(tracker.VIEWDETAILS, id);

            // --- ADD THE DETAIL VIEW --- //
            var detailViewId = "detailView" + id.replace(/[\\/:-\\.#]/g, '');
            if( !document.getElementById(detailViewId)) {
                $('body').append("
");
                var detailView = new DetailView({
                    model: this.model,
                    el: '#' + detailViewId
                });
            }
            this.model.trigger('showDetails', e);
            return false;

        },
        draggable: function() {
            var VIEW = this;
            this.$el.draggable({
                zIndex: 10000,
                helper: "clone",
                appendTo: "body",
                drag: function(event, ui) {
                    VIEW.LOG.debug('dragging');
                    var ev = event;
                    while (ev != null) {
                        if (ev.type == "mousemove")
                            ev.stopImmediatePropagation();
                        ev = ev.originalEvent;
                    }
                }
            });

        },
        getIcon: function(type) {
            var name,
                mimeType;
            // TODO: make clear use of URIs
            this.LOG.debug('model', _.clone(this.model.attributes));
            if( !type ) type = this.model.get('@type');
            this.LOG.debug('type', type);
            if( !type ) return this.icons['unknown'];
            name = this.model.vie.namespaces.curie(type.id);
            this.LOG.debug('name', name);
            if( name === 'user' ) {
                name = this.model.vie.namespaces.curie(this.model.getSubject());
                if( !this.icons[name]) name = 'user';
            }

            if ( 'sss:file' === name ) {
                mimeType  = this.model.get(Voc.hasMimeType);
                if ( mimeType ) {
                    switch( mimeType ) {
                        case 'application/pdf':
                            name = 'sss:filePdf';
                            break;
                        case 'image/png':
                            name = 'sss:filePng';
                            break;
                        case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
                        case 'application/msword':
                            name = 'sss:fileDoc';
                            break;
                    }
                }
            }

            if( !this.icons[name]) return this.icons['unknown'];
            return this.icons[name];
        },
        /**
         * Returns the average width of an entity.
         * TODO fix hard-coded width
         */
        getWidth: function() {
            return 40;
        }
    });
});
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2014 Romain "Creak" Failliot.
 *
 * This file is part of mesamatrix.
 *
 * mesamatrix is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published
 * by the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * mesamatrix is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with libbench. If not, see <http://www.gnu.org/licenses/>.
 */

function fillZeros(number, size)
{
    var numStrLen = number.toString().length;
    return "0".repeat(size - numStrLen) + number;
}

function getLocalDate(text)
{
    var eventDate = new Date(text);
    var year = eventDate.getFullYear();
    var month = fillZeros(eventDate.getMonth() + 1, 2);
    var day = fillZeros(eventDate.getDate(), 2);
    var hours = fillZeros(eventDate.getHours(), 2);
    var minutes = fillZeros(eventDate.getMinutes(), 2);
    var seconds = fillZeros(eventDate.getSeconds(), 2);
    var timezone = fillZeros(eventDate.getTimezoneOffset() / 60, 3);
    if(timezone >= 0)
        timezone = "+" + timezone;
    return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds + " (GMT " + timezone + ")";
}

function getRelativeDate(text)
{
    var eventDate = new Date(text);
    var relTimeInMin = (Date.now() - eventDate.getTime()) / (1000 * 60);
    if(relTimeInMin <= 5)               // Less than 5 minutes ago
        return "just now";
    if(relTimeInMin <= 60)              // Less than an hour ago
        return Math.round(((relTimeInMin / 60) / 5) * 5) + " minutes ago";
    if(relTimeInMin <= 119)             // Less (strictly) than two hours ago
        return "an hour ago";
    if(relTimeInMin <= 1440)            // Less than a day ago (60 * 24)
        return Math.round(relTimeInMin / 60) + " hours ago";
    if(relTimeInMin <= 2879)            // Less (strictly) than two days ago
        return "a day ago";
    if(relTimeInMin <= 10080)           // Less than a week ago (60 * 24 * 7)
        return Math.round(relTimeInMin / 1440) + " days";
    if(relTimeInMin <= 20159)           // Less (strictly) than two weeks ago (60 * 24 * 7 * 2)
        return "a week ago";
    if(relTimeInMin <= 43200)           // Less than a month ago (60 * 24 * 30)
        return Math.round(relTimeInMin / 10080) + " weeks ago";
    if(relTimeInMin <= 86399)           // Less (strictly) than two months ago (60 * 24 * 30 * 2)
        return "a month ago";
    if(relTimeInMin <= 259200)          // Less than six months ago (60 * 24 * 30 * 6)
        return Math.round(relTimeInMin / 43200) + " months ago";
    var year = eventDate.getFullYear();
    var month = fillZeros(eventDate.getMonth() + 1, 2);
    var day = fillZeros(eventDate.getDate(), 2);
    return year + "-" + month + "-" + day;
}

<commit_msg>Fix: Display the right timezone offset.<commit_after>/*
 * Copyright (C) 2014 Romain "Creak" Failliot.
 *
 * This file is part of mesamatrix.
 *
 * mesamatrix is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published
 * by the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * mesamatrix is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with libbench. If not, see <http://www.gnu.org/licenses/>.
 */

function fillZeros(number, size)
{
    var absNum = Math.abs(number);
    var numZeros = size - absNum.toString().length;
    var res = "";
    if(number < 0)
        res = "-";
    res += "0".repeat(numZeros) + absNum;
    return res;
}

function getLocalDate(text)
{
    var eventDate = new Date(text);
    var year = eventDate.getFullYear();
    var month = fillZeros(eventDate.getMonth() + 1, 2);
    var day = fillZeros(eventDate.getDate(), 2);
    var hours = fillZeros(eventDate.getHours(), 2);
    var minutes = fillZeros(eventDate.getMinutes(), 2);
    var seconds = fillZeros(eventDate.getSeconds(), 2);
    var timezoneOffset = -eventDate.getTimezoneOffset();
    var timezoneMinutes = Math.abs(timezoneOffset);
    var timezoneHours = Math.floor(timezoneMinutes / 60);
    timezoneMinutes -= timezoneHours * 60;
    timezoneHours = fillZeros(timezoneHours, 2);
    timezoneMinutes = fillZeros(timezoneMinutes, 2);
    if(timezoneMinutes >= 0)
        timezoneHours = "+" + timezoneHours;
    return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds + " (GMT " + timezoneHours + timezoneMinutes + ")";
}

function getRelativeDate(text)
{
    var eventDate = new Date(text);
    var relTimeInMin = (Date.now() - eventDate.getTime()) / (1000 * 60);
    if(relTimeInMin <= 5)               // Less than 5 minutes ago
        return "just now";
    if(relTimeInMin <= 60)              // Less than an hour ago
        return Math.round(((relTimeInMin / 60) / 5) * 5) + " minutes ago";
    if(relTimeInMin <= 119)             // Less (strictly) than two hours ago
        return "an hour ago";
    if(relTimeInMin <= 1440)            // Less than a day ago (60 * 24)
        return Math.round(relTimeInMin / 60) + " hours ago";
    if(relTimeInMin <= 2879)            // Less (strictly) than two days ago
        return "a day ago";
    if(relTimeInMin <= 10080)           // Less than a week ago (60 * 24 * 7)
        return Math.round(relTimeInMin / 1440) + " days";
    if(relTimeInMin <= 20159)           // Less (strictly) than two weeks ago (60 * 24 * 7 * 2)
        return "a week ago";
    if(relTimeInMin <= 43200)           // Less than a month ago (60 * 24 * 30)
        return Math.round(relTimeInMin / 10080) + " weeks ago";
    if(relTimeInMin <= 86399)           // Less (strictly) than two months ago (60 * 24 * 30 * 2)
        return "a month ago";
    if(relTimeInMin <= 259200)          // Less than six months ago (60 * 24 * 30 * 6)
        return Math.round(relTimeInMin / 43200) + " months ago";
    var year = eventDate.getFullYear();
    var month = fillZeros(eventDate.getMonth() + 1, 2);
    var day = fillZeros(eventDate.getDate(), 2);
    return year + "-" + month + "-" + day;
}

<|endoftext|>


<commit_before>define([
  'underscore', 'backbone', 'resthub', 'hbs!template/subreddit', 'hbs!template/post-row-small', 'view/post-row-view', 'view/sidebar-view', 'view/base-view', 'collection/subreddit', 'event/channel', 'cookie'],
	function(_, Backbone, Resthub, subredditTmpl, PostViewSmallTpl, PostRowView, SidebarView, BaseView, SubredditCollection, channel, Cookie) {
		var SubredditView = BaseView.extend({

			el: $(".content"),
			template: subredditTmpl,

			events: function() {
				var _events = {
					//'click .tabmenu-right li': 'changeGridOption',
					'click #retry': 'tryAgain'

				};
				//console.log('click .upArrow' + this.options.id)
				_events['click .upArrow' + this.options.id] = "upvote";
				_events['click .downArrow' + this.options.id] = "downvote";
				return _events;
			},

			initialize: function(options) {
				//$(this.el).empty()
				//this.$el.empty()

				_.bindAll(this);
				var self = this;
				this.subName = options.subName
				this.template = subredditTmpl;
				this.sortOrder = options.sortOrder
				this.subID = this.subName + this.sortOrder
				if (typeof this.sortOrder === 'undefined') {
					this.sortOrder = 'hot'
				}

				channel.on("subreddit:changeGridOption", this.changeGridOption, this);
				channel.on("subreddit:remove", this.remove, this);

				this.initGridOption();

				this.render();

				$(this.el).prepend("")
				console.log("window.subs=", window.subs)
				if (typeof window.subs[this.subID] === 'undefined') {
					$(this.el).append("

")
					this.collection = new SubredditCollection({
						subName: this.subName,
						sortOrder: this.sortOrder
					});
					this.fetchMore();
				} else {
					console.log('loading collection from memory')
					this.collection = window.subs[this.subID]
					this.appendPosts(this.collection)

					//this.fetchMore();
				}

				$(window).on("scroll", this.watchScroll);

				//in small thumbnail mode, its sometimes impossible for the infinite scroll event to fire because there is no scrollbar yet
				this.helpFillUpScreen();

				//this.target = $("#siteTable"); //the target to test for infinite scroll
				this.target = $(window); //the target to test for infinite scroll
				this.loading = false;
				this.scrollOffset = 1000;
				this.prevScrollY = 0; //makes sure you are not checking when the user scrolls upwards
				this.errorRetries = 0; //keeps track of how many errors we will retry after

				//$(window).bind("resize.app", _.bind(this.debouncer));
				$(window).resize(this.debouncer(function(e) {
					self.resize()
				}));
				this.resize()

				setTimeout(function() {
					self.changeSortOrderCss()
				}, 100);

			},
			//we have to override the remove event because the window.scroll event will not be removed by the garbage collector
			//cant create infinite scroll without this.
			remove: function() {
				$(window).off("scroll", this.watchScroll);
				$(window).off('resize', this.debouncer);
				channel.off("subreddit:changeGridOption", this.changeGridOption, this);
				channel.off("subreddit:remove", this.remove, this);
				this.undelegateEvents();
				this.$el.empty();
				this.stopListening();
				console.log('**********************removed the view *********************************')

				//call the superclass remove method
				//Backbone.View.prototype.remove.apply(this, arguments);
			},

			/**************Routing functions ****************/
			// clickedInteralLink: function(e) {
			// 	console.log("I clicked a link yo")

			// },
			/**************Grid functions ****************/
			initGridOption: function() {
				/*grid option:
					normal - the default Reddit styling
					small - small thumbnails in the page
					large - full sized images in the page
				*/
				this.gridOption = $.cookie('gridOption');
				if (typeof this.gridOption === 'undefined' || this.gridOption == null || this.gridOption == "") {
					this.gridOption = 'normal'
				} else if (this.gridOption == "large") {
					this.resize()
				}
			},
			changeSortOrderCss: function() {
				channel.trigger("header:updateSortOrder", this.sortOrder);
			},

			resize: function() {
				var mobileWidth = 1000; //when to change to mobile CSS
				if (this.gridOption == "large") {
					//change css of
					var docWidth = $(document).width()
					var newWidth = 0;
					if (docWidth > mobileWidth) {
						newWidth = docWidth - 355;
					} else {
						newWidth = docWidth;
					}
					$('#dynamicWidth').html('');
				}

			},

			changeGridOption: function(data) {
				console.log('changing grid option=', data)
				if (typeof data.gridOption === 'undefined') {
					this.gridOption = $.cookie('gridOption');
				}
				if (this.gridOption == data.gridOption) {
					return; //do nothing if the user already clicked this once
				}
				this.gridOption = data.gridOption
				$.cookie('gridOption', this.gridOption, {
					path: '/'
				});
				//this.changeActiveGrid()
				this.resetPosts()
				if (this.name == "large") {
					this.resize()
				}
				this.appendPosts(this.collection)
				this.helpFillUpScreen()
			},
			resetPosts: function() {
				//this.$('#siteTable').html(" ")
				this.$('#siteTable').empty();
			},
			/**************Fetching functions ****************/
			fetchError: function(response, error) {
				console.log("fetch error, lets retry", this.collection)
				if (this.errorRetries < 10) {
					this.loading = false;
				}

				if (this.collection.length <= 5) {
					this.$('#siteTable').html("

 click here to try again
 ")
				}
				this.errorRetries++;

			},
			tryAgain: function() {
				this.$('#siteTable').html("

 ")
				this.$('#retry').remove()

				this.fetchMore();
			},
			fetchMore: function() {
				this.collection.fetch({
					success: this.gotNewPosts,
					error: this.fetchError,
					remove: false
				});
			},

			appendPosts: function(models) {
				console.log(models)
				models.each(function(model) {
					if (model.get('title') != null) {
						if (this.gridOption == "small") {
							// this.$('#siteTable').append(PostViewSmallTpl({
							// 	model: model.attributes
							// }))
							var postview = new PostRowView({
								root: "#siteTable",
								id: model.get('id'),
								model: model,
								gridOption: this.gridOption
							});
						} else if (this.gridOption == "large") {

							var postview = new PostRowView({
								root: "#siteTable",
								id: model.get('id'),
								model: model,
								gridOption: this.gridOption
							});
						} else {

							var postview = new PostRowView({
								root: "#siteTable",
								model: model,
								id: model.get('id'),
								gridOption: this.gridOption
							});
						}
					}
				}, this);
				this.resize()

			},
			gotNewPosts: function(models, res) {
				this.$('.loading').hide()

				if (typeof res.data.children.length === 'undefined') {
					return; //we might have an undefined length?
				};
				var newCount = res.data.children.length

				var newModels = new Backbone.Collection(models.slice((models.length - newCount), models.length))
				this.appendPosts(newModels)

				//fetch more  posts with the After
				if (this.collection.after == "stop") {
					console.log("AFTER = stop")
					$(window).off("scroll", this.watchScroll);
				}
				this.loading = false; //turn the flag on to go ahead and fetch more!
				this.helpFillUpScreen()
				window.subs[this.subID] = this.collection

			},
			/**************Infinite Scroll functions ****************/
			watchScroll: function(e) {
				var self = this;

				var triggerPoint = 1500; // 1500px from the bottom

				if ((($(window).scrollTop() + $(window).height()) + triggerPoint >= $(document).height()) && this.loading == false) {
					this.loading = true
					console.log('loading MOAR')
					if (this.collection.after != "stop") {
						this.fetchMore()
					}
				}
				//this.prevScrollY = scrollY;
			},
			helpFillUpScreen: function() {
				if (this.collection.length < 301 && this.gridOption == 'small') {
					this.watchScroll()
				}
			}

		});
		return SubredditView;
	});<commit_msg>change single post page image width to be slightly smaller<commit_after>define([
  'underscore', 'backbone', 'resthub', 'hbs!template/subreddit', 'hbs!template/post-row-small', 'view/post-row-view', 'view/sidebar-view', 'view/base-view', 'collection/subreddit', 'event/channel', 'cookie'],
	function(_, Backbone, Resthub, subredditTmpl, PostViewSmallTpl, PostRowView, SidebarView, BaseView, SubredditCollection, channel, Cookie) {
		var SubredditView = BaseView.extend({

			el: $(".content"),
			template: subredditTmpl,

			events: function() {
				var _events = {
					//'click .tabmenu-right li': 'changeGridOption',
					'click #retry': 'tryAgain'

				};
				//console.log('click .upArrow' + this.options.id)
				_events['click .upArrow' + this.options.id] = "upvote";
				_events['click .downArrow' + this.options.id] = "downvote";
				return _events;
			},

			initialize: function(options) {
				//$(this.el).empty()
				//this.$el.empty()
				this.$('#siteTable').empty()
				_.bindAll(this);
				var self = this;
				this.subName = options.subName
				this.template = subredditTmpl;
				this.sortOrder = options.sortOrder
				this.subID = this.subName + this.sortOrder
				if (typeof this.sortOrder === 'undefined') {
					this.sortOrder = 'hot'
				}

				channel.on("subreddit:changeGridOption", this.changeGridOption, this);
				channel.on("subreddit:remove", this.remove, this);

				this.initGridOption();

				this.render();

				$(this.el).prepend("")
				console.log("window.subs=", window.subs)
				if (typeof window.subs[this.subID] === 'undefined') {
					$(this.el).append("

")
					this.collection = new SubredditCollection({
						subName: this.subName,
						sortOrder: this.sortOrder
					});
					this.fetchMore();
				} else {
					console.log('loading collection from memory')
					this.collection = window.subs[this.subID]
					this.appendPosts(this.collection)

					//this.fetchMore();
				}

				$(window).on("scroll", this.watchScroll);

				//in small thumbnail mode, its sometimes impossible for the infinite scroll event to fire because there is no scrollbar yet
				this.helpFillUpScreen();

				//this.target = $("#siteTable"); //the target to test for infinite scroll
				this.target = $(window); //the target to test for infinite scroll
				this.loading = false;
				this.scrollOffset = 1000;
				this.prevScrollY = 0; //makes sure you are not checking when the user scrolls upwards
				this.errorRetries = 0; //keeps track of how many errors we will retry after

				//$(window).bind("resize.app", _.bind(this.debouncer));
				$(window).resize(this.debouncer(function(e) {
					self.resize()
				}));
				this.resize()

				setTimeout(function() {
					self.changeSortOrderCss()
				}, 100);

			},
			//we have to override the remove event because the window.scroll event will not be removed by the garbage collector
			//cant create infinite scroll without this.
			remove: function() {
				$(window).off("scroll", this.watchScroll);
				$(window).off('resize', this.debouncer);
				channel.off("subreddit:changeGridOption", this.changeGridOption, this);
				channel.off("subreddit:remove", this.remove, this);
				this.undelegateEvents();
				this.$el.empty();
				this.stopListening();
				console.log('**********************removed the view *********************************')

				//call the superclass remove method
				//Backbone.View.prototype.remove.apply(this, arguments);
			},

			/**************Routing functions ****************/
			// clickedInteralLink: function(e) {
			// 	console.log("I clicked a link yo")

			// },
			/**************Grid functions ****************/
			initGridOption: function() {
				/*grid option:
					normal - the default Reddit styling
					small - small thumbnails in the page
					large - full sized images in the page
				*/
				this.gridOption = $.cookie('gridOption');
				if (typeof this.gridOption === 'undefined' || this.gridOption == null || this.gridOption == "") {
					this.gridOption = 'normal'
				} else if (this.gridOption == "large") {
					this.resize()
				}
			},
			changeSortOrderCss: function() {
				channel.trigger("header:updateSortOrder", this.sortOrder);
			},

			resize: function() {
				var mobileWidth = 1000; //when to change to mobile CSS
				if (this.gridOption == "large") {
					//change css of
					var docWidth = $(document).width()
					var newWidth = 0;
					if (docWidth > mobileWidth) {
						newWidth = docWidth - 355;
					} else {
						newWidth = docWidth;
					}
					$('#dynamicWidth').html('');
				}

			},

			changeGridOption: function(data) {
				console.log('changing grid option=', data)
				if (typeof data.gridOption === 'undefined') {
					this.gridOption = $.cookie('gridOption');
				}
				if (this.gridOption == data.gridOption) {
					return; //do nothing if the user already clicked this once
				}
				this.gridOption = data.gridOption
				$.cookie('gridOption', this.gridOption, {
					path: '/'
				});
				//this.changeActiveGrid()
				this.resetPosts()
				if (this.name == "large") {
					this.resize()
				}
				this.appendPosts(this.collection)
				this.helpFillUpScreen()
			},
			resetPosts: function() {
				//this.$('#siteTable').html(" ")
				this.$('#siteTable').empty();
			},
			/**************Fetching functions ****************/
			fetchError: function(response, error) {
				console.log("fetch error, lets retry", this.collection)
				if (this.errorRetries < 10) {
					this.loading = false;
				}

				if (this.collection.length <= 5) {
					this.$('#siteTable').html("

 click here to try again
 ")
				}
				this.errorRetries++;

			},
			tryAgain: function() {
				this.$('#siteTable').html("

 ")
				this.$('#retry').remove()

				this.fetchMore();
			},
			fetchMore: function() {
				this.collection.fetch({
					success: this.gotNewPosts,
					error: this.fetchError,
					remove: false
				});
			},

			appendPosts: function(models) {
				console.log(models)
				models.each(function(model) {
					if (model.get('title') != null) {
						if (this.gridOption == "small") {
							// this.$('#siteTable').append(PostViewSmallTpl({
							// 	model: model.attributes
							// }))
							var postview = new PostRowView({
								root: "#siteTable",
								id: model.get('id'),
								model: model,
								gridOption: this.gridOption
							});
						} else if (this.gridOption == "large") {

							var postview = new PostRowView({
								root: "#siteTable",
								id: model.get('id'),
								model: model,
								gridOption: this.gridOption
							});
						} else {

							var postview = new PostRowView({
								root: "#siteTable",
								model: model,
								id: model.get('id'),
								gridOption: this.gridOption
							});
						}
					}
				}, this);
				this.resize()

			},
			gotNewPosts: function(models, res) {
				this.$('.loading').hide()

				if (typeof res.data.children.length === 'undefined') {
					return; //we might have an undefined length?
				};
				var newCount = res.data.children.length

				var newModels = new Backbone.Collection(models.slice((models.length - newCount), models.length))
				this.appendPosts(newModels)

				//fetch more  posts with the After
				if (this.collection.after == "stop") {
					console.log("AFTER = stop")
					$(window).off("scroll", this.watchScroll);
				}
				this.loading = false; //turn the flag on to go ahead and fetch more!
				this.helpFillUpScreen()
				window.subs[this.subID] = this.collection

			},
			/**************Infinite Scroll functions ****************/
			watchScroll: function(e) {
				var self = this;

				var triggerPoint = 1500; // 1500px from the bottom

				if ((($(window).scrollTop() + $(window).height()) + triggerPoint >= $(document).height()) && this.loading == false) {
					this.loading = true
					console.log('loading MOAR')
					if (this.collection.after != "stop") {
						this.fetchMore()
					}
				}
				//this.prevScrollY = scrollY;
			},
			helpFillUpScreen: function() {
				if (this.collection.length < 301 && this.gridOption == 'small') {
					this.watchScroll()
				}
			}

		});
		return SubredditView;
	});<|endoftext|>


<commit_before>/*
  Test module of type 'command'
  Use this as a sort of starting point for your own modules!

  For simplicity's sake, I'll assume that your command character is !. Make sure
  to configure it with the property "command_character".

  The module's 'name' will be this file's name without module- and .js.
  The module can be loaded by adding the module's name to a list under the
  configuration, or by using the builtin `!module.load` functionality.
*/

/*
  This module exposes a command (or many), as well as providing help and a list
  of all the commands it exposes. Both of those are highly recommended.

  The other type of module, 'event', gets a bit more power and the ability to
  hook into all three event streams.
*/
exports.type = 'command';

// Store the 'message' configuration value as a global.
var message;

/*
  Return an array filled with strings, each of which is the name of a subcommand
  you define in this module's listener.

  The listener function is called when '!module' is used, and when '!module.X'
  is used. You can use the X to define different kinds of commands in a single
  module. Here you can list all of the various X-es you define.

  List a * too if your listener works without an X.
*/
exports.listAll = function() {
  return ['*'];
};

/*
  Define a short overview of what your various commands do.
  The format I've used throughout my modules is this:

  `command <mandatory-argument> [optional-argument]` - help here.

  You can also use three dots like <mandatory-argument...> to specify that the
  rest of the line of text is used as the mandatory argument.
*/
exports.getHelp = function() {
  return {
    '*': 'test command! responds with hello and how it was called.'
  };
};

/*

  This function is called every time someone uses !command or !command.X.

  The `this` value is set to the event object passed around by EventEmitter2.
  To obtain the X from the event name, simply cut off your module name from the
  `this.event` property.

  The first argument to the function is a data-structure defining an IRC line.
  It looks approximately like this:

  {  prefix: 'boxmein!~boxmein@unaffiliated/boxmein',
     nick: 'boxmein',
     username: '~boxmein',
     hostname: 'unaffiliated/boxmein',
     hostmask: 'boxmein!~boxmein@unaffiliated/boxmein',
     numeric: 'PRIVMSG',
     command: 'PRIVMSG',
     params: [ '##powder-bots', '\\list system' ]
  }

  The second argument is a list of all words that the user spoke in the IRC line
  including the command.

  [ '\\list', 'system' ]

  The third argument is a function(string) you can call when you want to send a
  response to the caller. It automatically fills in the IRC protocol as well as
  prefixing the caller's username to your string.

*/
exports.listener = function(line, words, respond) {
  respond(message.replace('%cmd', this.event));
};

/*
  This function is called when the module is first loaded. Here's the perfect
  place to set up variables and/or other persistent state.

  The first argument is the global configuration containing the entire data
  structure that configs.yml defines.

  The second argument is a specific section of the global configuration
  dedicated to values you might want to use with a specific module. It's under
  the modules.<module-name> structure.

  This means that config.modules.test == myconfig.

  The third argument is a function(string, string) you can call with two strings
  that will create an alias from the first argument to the second.

  For example, if you want your "!test.do_the_thing" to be available as "!thing"
  then alias("thing", "test.do_the_thing") will accomplish just that.
*/
exports.init = function(config, myconfig, alias) {
  console.log('initialized test with ', myconfig);
  alias('thing', 'test.do_the_thing');
  message = myconfig.message;
};
<commit_msg>added up-to-date commentary, also fixed the init function<commit_after>
// let's inspect everything we come across

/* We'll describe a different `util` later - need to distinguish! */
var nodeutil = require('util');

/* Gotta love underscore */
var _ = require('underscore');

/* This is a logger I wrote with log levels and all sorts of bullcrap. Really
  useful, so using this gets you timestamps, log levels and filtering for free!
  Plus the logs look really neat with timestamps lining the left edge.

  Also, the "concern" property lets every logger instance name what they're
  logging for.
*/
var logger = new require('../toplog')({concern: 'test', loglevel: 'INFO'});

/*
  Hi!

  This is the "test" module, which is meant to be very loud and document every-
  thing that is going on in an average module.

  The module also has a hidden "name" property, which gets assigned according
  to the actual filename of this script. Modules are loaded according to their
  names, and files are loaded by concatenating the module name with a file name
  like "module-" + name + ".js" .

  As the type specifies, this is a "command"-type module, meaning it forfeits
  access to the raw event streams to become better structured and reloadable.

  The other type that exists is "event"-type modules, which you can read about
  in 'module-logging.js'.
*/
exports.type = 'command';

/*
  This is what will be concatenated into a string when a user calls `list` on
  your module. You'll most likely need to put commands here that are accessible
  via this module!

  By convention, list a * command when you don't need to specify a sub-command
  in order to use this module.

  A simple trick is to do `Object.keys(exports.getHelp())` as the return value
  to this, which will keep getHelp and listAll in sync.
*/
exports.listAll = function() {
  return ['*'];
};

/*
  This returns an object with keys as the possible sub-commands and values as
  a documentation on what the subcommands do.

  A convention is to write the documentation like this:

    `command <mandatory-argument> [optional argument]` - description here

  ...or

    `command <mandatory list of arguments...>` - description here.

  The syntax is kind of common and should make sense most of the time. Adapt
  as necessary.

  Also, use backticks to mark out any actual commands  like you would Markdown.
*/
exports.getHelp = function() {
  return {
    '*': '`test` - test command! responds with hello and how it was called.'
  };
};

/*

  This is what will be run every time your module is called, which means all
  events on the `test.*` wildcard, for this module. The module's name is inside
  the filename.

  You get passed four parameters.

  First: the IRC line (a generic object containing everything you'd want to
    know about the message that caused this event).

  This is what an IRC line looks like:

    ":NickServ!NickServ@services. NOTICE boxnode :You gotta identify bro\r\n"
    :<prefix>                     <num>  <params...>                    \r\n

    ==

    {
      "prefix": "NickServ!NickServ@services.",
      // this is the actual command sent from the IRC server
      "numeric": "NOTICE",
      // if the numeric was an actual number, this translates it to text.
      // See constants.json for the mapping.
      "command": "NOTICE",
      "params": [
        "boxnode",
        "You gotta identify bro"
      ],

      // Might not be included.
      "nick": "NickServ",
      "username": "NickServ",
      "hostname": "services."
    }

  Second parameter is a list of all the words the message contained, for example
    ["\\test.potato", "I", "am", "a", "potato"]

  Third parameter is a function you can call to send a response back to the
    user. By default, it mentions the caller too, but you can use the various
    other respond functions attached to the object to change this.

    function respond(channel, name, message) { ... }
    respond.PRIVMSG = function (channel, message) { ... }
    respond.MODE    = function (channel, mode, target) { ... }
    respond.RAW     = function (raw) { ... }

    (however, the "respond" copy you get into this function has the channel and
    name properties prefilled).

  Fourth parameter is a bunch of utility functions: UTIL_OBJECT
    config.get(config_property):
      get a configuration property. (this was changed to allow config
      to be reloaded!)

    parseIRCLine(raw_irc_line):
      parse a string into an IRC line object

    matchesHostname(pattern, hostmask):
      check if the hostmask matches the pattern. Patterns are like regexes, but
      * are automatically changed to (.+?).

    getNames(channel):
      returns a promise that resolves to a list of every user in a channel.

    isChannel(channel):
      returns if the first argument starts with a pound sign.

    respond:
      yes, that's the same respond you already have. Except, not prefilled in.

    addAlias(from, to):
      add a command alias from something to something else. For example,
      "eval" is aliased to "system.evil", meaning \eval == \system.evil

    isOperatorIn(nick, channel):
      returns a promise that resolves to true if the nick is an operator in the
      given channel.

    isVoiceIn(nick, channel):
      returns a promise that resolves to true if the nick is a voice in the
      given channel.

  Another thing:
    Since this listener is (almost) attached to an actual event stream, its
    `this` contains stuff from said event stream. Most important of which is
    probably `this.event`, which is the particular IRC command the listener was
    invoked about. For example, when `\test.potato` is run, the `this.event`
    will be "test.potato".
*/
exports.listener = function(line, words, respond, util) {

  // The log level for these is VERBOSE, while the constructor set the filtered
  // level to INFO, INFO > VERBOSE, therefore VERBOSE is not shown.
  logger.verbose('listener#line:', nodeutil.inspect(line));
  logger.verbose('listener#words:', nodeutil.inspect(words));
  logger.verbose('listener#respond:', nodeutil.inspect(respond));
  logger.verbose('listener#util:', nodeutil.inspect(util));

  // Slicing off the "test." part from this.event.
  var shortEvt = this.event.slice(5);

  if (shortEvt == 'potato') {
    respond(_.sample(util.config.get('modules.test.potatoes')));
  } else {
    var msg = util.config.get('module.test.message', 'hi! you entered %cmd!');
    respond(msg.replace('%cmd', this.event));
  }
};

/*
  This function is called when the module is first loaded. Here's the perfect
  place to set up variables and/or other persistent state.

  Access to the configuration is available via the util object (see above,
  Ctrl+F UTIL_OBJECT). Also, you can attach aliases via the addAlias(from, to)
  function passed right into the scope. It's also available in the util object.
*/
exports.init = function(util, addAlias) {
  logger.verbose('init#util:', nodeutil.inspect(util));
  logger.verbose('init#addAlias:', nodeutil.inspect(addAlias));

  addAlias('potato', 'test.potato');
  addAlias('otatop', 'test.otatop');
  addAlias('asdf', 'test.asdf');
  addAlias('sudo', 'test.sudo');
};
<|endoftext|>


<commit_before>class Branch {

  constructor(branchName, repositoryUrl, apiClients) {
    this.name = branchName;
    this.owner = repositoryUrl.split("/")[0];
    this.repository = repositoryUrl.split("/")[1];
    this.apiClients = apiClients;
    this.branchPattern = /BP[\-|\_](\d{0,4})[\-|\_](.+)/;
    // this.sonarqubeComponentId = this.apiClients["sonarqube"].getComponentIdForProject(this.getSonarqubeKey());
    this.latestCommitTimer = "";
    this.latestCommitter = "unknown";
    this.latestSha = null;
    this.buildStatus = null;
    this.qualityGateStatus = null;
    this.coverage = null;
    this.update();
  }

  /**
  * Fetches information from GitHub-API and parses returned JSON
  * to reset attribute-values.
  *
  */
  update() {
    try {
      const latestInformation = this.apiClients["gitHub"].getDetailsAboutBranch(this.getRepositoryUrl(), this.getName());
      this.latestCommitTimer = new Date(latestInformation["commit"]["commit"]["author"]["date"]);
      this.latestCommitter = latestInformation["commit"]["commit"]["author"]["name"];
      this.latestSha = latestInformation["commit"]["sha"];
    } catch (e) {
      return 1;
    }
    this.updateTravisInformation();
    this.updateSonarqubeInformation();
    this.updateCoverallsInformation();
  }

  getName() {
    return this.name;
  }
  getOwner() {
    return this.owner;
  }
  getRepository() {
    return this.repository;
  }
  getRepositoryUrl() {
    return this.getOwner() + "/" + this.getRepository();
  }
  getLastCommitTime() {
    return this.latestCommitTimer;
  }
  getLastCommitTimeAsString() {
    return this.getLastCommitTime().toLocaleString();
  }
  isDeveloperBranch() {
    return (this.getName() == "dev" || this.getName() == "developer");
  }
  isMasterBranch() {
    return (this.getName() == "master");
  }
  isIssueExtractable() {
    const ret = this.branchPattern.exec(this.getName());
    if(ret) {
      return true;
    }
    return false;
  }
  getIssueNumber() {
    const ret = this.branchPattern.exec(this.getName());
    if(ret){
      return ret[1];
    }
    return "";
  }
  getIssueName() {
    const ret = this.branchPattern.exec(this.getName());
    if(ret){
      var unformattedName = ret[2];
      unformattedName = unformattedName.replace(/\_/g, " ");
      unformattedName = unformattedName.replace(/\-/g, " ");
      return unformattedName;
    }
    return "";
  }
  getJiraLink() {
    return ("https://bpt-lab.org/jira/secure/RapidBoard.jspa?rapidView=8&view=detail&selectedIssue=BP-" + this.getIssueNumber());
  }

  //SONARQUBE FUNCTIONS

  updateSonarqubeInformation() {
    try {
      this.qualityGateStatus = this.apiClients["sonarqube"].getQualityGateStatusForProject(this.getSonarqubeKey());
    } catch (e) {
        this.qualityGateStatus = null;
    }
  }

  getSonarqubeKey() {
    var sonarqubeKey = "de.hpi.bpt:" + this.getRepository();
    if(!this.isMasterBranch())
      sonarqubeKey += ":" + this.getName();
    return sonarqubeKey;
  }
  getQualityGateStatus() {
    return this.qualityGateStatus;
  }
  doesPassQualityGate() {
    return (!(this.getQualityGateStatus() == "ERROR"));
  }
  getNiceSonarqubeString() {
    if(!this.didSonarqubeRun())
      return "no results";
    if(this.doesPassQualityGate()) {
      return "QG passed";
    }
    else {
      return "QG failed";
    }
  }
  didSonarqubeRun() {
    return (this.qualityGateStatus);
  }

  //TRAVIS FUNCTIONS
  updateTravisInformation() {
    try {
      const latestBuildInformation = this.apiClients["travis"].getDetailsAboutLatestBuildOfBranch(this.getRepositoryUrl(), this.getName());
      this.buildStatus = latestBuildInformation["branch"]["state"];
    } catch (e) {
        this.buildStatus = null;
    }
  }

  getBuildStatus() {
    return this.buildStatus;
  }
  didLatestBuildPass() {
    return (this.getBuildStatus() == "passed");
  }
  didTravisRun() {
    return (this.buildStatus);
  }

  //COVERALLS FUNCTIONS
  updateCoverallsInformation() {
    if(!this.latestSha) {
      return;
    }
    try {
      const latestCoverallsInformation = this.apiClients["coveralls"].getCoverageInformationBySha(this.latestSha);
      console.log(latestCoverallsInformation);
      this.coverage = parseFloat(latestCoverallsInformation["covered_percent"]);
    } catch (e) {
      this.coverage = null;
    }
  }
  hasCoverage() {
    return (this.coverage);
  }
  getCoverage() {
    if(this.hasCoverage()) {
      return (Math.round(this.coverage * 10) / 10).toString();
    }
    return "";
  }

}

export default Branch;
<commit_msg>remove logging and return boolean<commit_after>class Branch {

  constructor(branchName, repositoryUrl, apiClients) {
    this.name = branchName;
    this.owner = repositoryUrl.split("/")[0];
    this.repository = repositoryUrl.split("/")[1];
    this.apiClients = apiClients;
    this.branchPattern = /BP[\-|\_](\d{0,4})[\-|\_](.+)/;
    // this.sonarqubeComponentId = this.apiClients["sonarqube"].getComponentIdForProject(this.getSonarqubeKey());
    this.latestCommitTimer = "";
    this.latestCommitter = "unknown";
    this.latestSha = null;
    this.buildStatus = null;
    this.qualityGateStatus = null;
    this.coverage = null;
    this.update();
  }

  /**
  * Fetches information from GitHub-API and parses returned JSON
  * to reset attribute-values.
  *
  */
  update() {
    try {
      const latestInformation = this.apiClients["gitHub"].getDetailsAboutBranch(this.getRepositoryUrl(), this.getName());
      this.latestCommitTimer = new Date(latestInformation["commit"]["commit"]["author"]["date"]);
      this.latestCommitter = latestInformation["commit"]["commit"]["author"]["name"];
      this.latestSha = latestInformation["commit"]["sha"];
    } catch (e) {
      return 1;
    }
    this.updateTravisInformation();
    this.updateSonarqubeInformation();
    this.updateCoverallsInformation();
  }

  getName() {
    return this.name;
  }
  getOwner() {
    return this.owner;
  }
  getRepository() {
    return this.repository;
  }
  getRepositoryUrl() {
    return this.getOwner() + "/" + this.getRepository();
  }
  getLastCommitTime() {
    return this.latestCommitTimer;
  }
  getLastCommitTimeAsString() {
    return this.getLastCommitTime().toLocaleString();
  }
  isDeveloperBranch() {
    return (this.getName() == "dev" || this.getName() == "developer");
  }
  isMasterBranch() {
    return (this.getName() == "master");
  }
  isIssueExtractable() {
    const ret = this.branchPattern.exec(this.getName());
    if(ret) {
      return true;
    }
    return false;
  }
  getIssueNumber() {
    const ret = this.branchPattern.exec(this.getName());
    if(ret){
      return ret[1];
    }
    return "";
  }
  getIssueName() {
    const ret = this.branchPattern.exec(this.getName());
    if(ret){
      var unformattedName = ret[2];
      unformattedName = unformattedName.replace(/\_/g, " ");
      unformattedName = unformattedName.replace(/\-/g, " ");
      return unformattedName;
    }
    return "";
  }
  getJiraLink() {
    return ("https://bpt-lab.org/jira/secure/RapidBoard.jspa?rapidView=8&view=detail&selectedIssue=BP-" + this.getIssueNumber());
  }

  //SONARQUBE FUNCTIONS

  updateSonarqubeInformation() {
    try {
      this.qualityGateStatus = this.apiClients["sonarqube"].getQualityGateStatusForProject(this.getSonarqubeKey());
    } catch (e) {
        this.qualityGateStatus = null;
    }
  }

  getSonarqubeKey() {
    var sonarqubeKey = "de.hpi.bpt:" + this.getRepository();
    if(!this.isMasterBranch())
      sonarqubeKey += ":" + this.getName();
    return sonarqubeKey;
  }
  getQualityGateStatus() {
    return this.qualityGateStatus;
  }
  doesPassQualityGate() {
    return (!(this.getQualityGateStatus() == "ERROR"));
  }
  getNiceSonarqubeString() {
    if(!this.didSonarqubeRun())
      return "no results";
    if(this.doesPassQualityGate()) {
      return "QG passed";
    }
    else {
      return "QG failed";
    }
  }
  didSonarqubeRun() {
    return (this.qualityGateStatus);
  }

  //TRAVIS FUNCTIONS
  updateTravisInformation() {
    try {
      const latestBuildInformation = this.apiClients["travis"].getDetailsAboutLatestBuildOfBranch(this.getRepositoryUrl(), this.getName());
      this.buildStatus = latestBuildInformation["branch"]["state"];
    } catch (e) {
        this.buildStatus = null;
    }
  }

  getBuildStatus() {
    return this.buildStatus;
  }
  didLatestBuildPass() {
    return (this.getBuildStatus() == "passed");
  }
  didTravisRun() {
    return (this.buildStatus);
  }

  //COVERALLS FUNCTIONS
  updateCoverallsInformation() {
    if(!this.latestSha) {
      return;
    }
    try {
      const latestCoverallsInformation = this.apiClients["coveralls"].getCoverageInformationBySha(this.latestSha);
      this.coverage = parseFloat(latestCoverallsInformation["covered_percent"]);
    } catch (e) {
      this.coverage = null;
    }
  }
  hasCoverage() {
    if (this.coverage) {
      return true;
    }
    return false;
  }
  getCoverage() {
    if(this.hasCoverage()) {
      return (Math.round(this.coverage * 10) / 10).toString();
    }
    return "";
  }

}

export default Branch;
<|endoftext|>