<commit_before>/*! jQuery B1njPolaroidGallery - v1.0
* https://github.com/b1nj/b1njPolaroidGallery
* Includes: jquery.ui.js
* Copyright (c) 2012 b1nj Licensed MIT */
(function ($)
{
    jQuery.fn.b1njPolaroidGallery = function (options)
    {
        var settings = $.extend( {
            'maxRotation' : 20,
            'randomStacking' : true
        }, options);

        this.each (function (index, value)
        {
            $(this).addClass('b1njPolaroidGallery');
            var galleryW = $(this).width();
            var galleryH = $(this).height();
            var nbPhotos = $('li', this).length;
            var zIndex = new Array();
            for(var i=0; i<nbPhotos; i++) {
                zIndex[i] = i + 1;
            }
            if (settings.randomStacking) {
                var zIndex = zIndex.sort(function() { return 0.5 - Math.random() });
            }

            $('li', this).each (function (index, value)
            {
                var alt = $('img', this).attr('alt');
                if (alt != '') {
                    $(this).append('
'+ alt +'
')
                }

                $(this).width($('img', this).width() + (Number($('img', this).css('margin-left').slice(0,-2)) * 2));

                $('a', this).click(function (e)
                {
                    if (!$(this).parent('li').hasClass('b1njPolaroidGallery-linkOk')) {
                        $(this).parent('li').addClass('b1njPolaroidGallery-linkOk');
                        e.preventDefault();
                        e.stopPropagation();
                        //return false;
                    }
                });

                var photoW = $(this).width();
                var photoH = $(this).height();

                var tempRotDegrees = randomXToY(0, settings.maxRotation);
                var tempVal = Math.round(Math.random());
                if(tempVal == 1) {
                    var rotDegrees = 360 - tempRotDegrees; // rotate left
                } else {
                    var rotDegrees = tempRotDegrees; // rotate right
                }

                var shiftT = shiftAfeterRotate(photoH, photoW, tempRotDegrees);
                var shiftL = shiftAfeterRotate(photoW, photoH, tempRotDegrees);

                if (galleryH - shiftT - photoH > shiftT) {
                    var top = randomXToY(shiftT, galleryH - shiftT - photoH);
                } else {
                    var top = shiftT;
                }
                if (galleryW - shiftL - photoW > shiftL) {
                    var left = randomXToY(shiftL, galleryW - shiftL - photoW);
                } else {
                    var left = shiftL;
                }

                var cssObj = {
                    'left' : '+=' + left,
                    'top' : '+=' + top
                };
                cssObj['z-index'] = zIndex[index];
                $(this).css(cssObj).b1njPolaroidGalleryRotate(rotDegrees).data('rotDegrees', rotDegrees);

                $(this).bind('mousedown', function(e)
                {
                    $(this).parent('ul').find('li').not(this).removeClass('b1njPolaroidGallery-active b1njPolaroidGallery-linkOk');
                    $(this).addClass('b1njPolaroidGallery-active');
                }).
                draggable({
                    containment : 'parent',
                    start: function(event, ui) {
                        if (('a', this).length != 0) {
                            $(this).addClass('b1njPolaroidGallery-LinkOk');
                        }
                    },
                    stop: function(event, ui) {
                        rotDegrees = $(this).data('rotDegrees');
                        $(this).b1njPolaroidGalleryRotate(rotDegrees);
                    }
                });
            });
        });
        return this;
    };
    jQuery.fn.b1njPolaroidGalleryRotate = function (rotation)
    {
        if ($.browser.msie  && parseInt($.browser.version, 10) === 8) {
            if (rotation >= 0) {
                var rotation = Math.PI * rotation / 180;
            } else {
                var rotation = Math.PI * (360 + rotation) / 180;
            }
            var cssObj = {
                'filter' : 'progid:DXImageTransform.Microsoft.Matrix(M11=' + Math.cos(rotation) + ",M12=" + (-Math.sin(rotation)) + ",M21=" + Math.sin(rotation) + ",M22=" + Math.cos(rotation) + ",SizingMethod='auto expand')"
            }
        } else {
            var cssObj = {
                '-webkit-transform' : 'rotate('+ rotation +'deg)',
                '-ms-transform' : 'rotate('+ rotation +'deg)',
                '-moz-transform' : 'rotate('+ rotation +'deg)',
                '-o-transform' : 'rotate('+ rotation +'deg)',
                'tranform' : 'rotate('+ rotation +'deg)'
            };
        }
        $(this).css(cssObj);
        return this;
    }
}) (jQuery);

// Function to get random number upto m
// http://roshanbh.com.np/2008/09/get-random-number-range-two-numbers-javascript.html
function randomXToY(minVal,maxVal,floatVal)
{
    var randVal = minVal+(Math.random()*(maxVal-minVal));
    return typeof floatVal=='undefined'?Math.round(randVal):randVal.toFixed(floatVal);
}

// Fuction get the shift after rotate the photo
// http://www.maths-forum.com/trigonometrie-rotation-d-un-rectangle-129467.php
// //x = (1/V2).V(CD² + AD²) * V(1-cos(alpha)) * sin[(180° - alpha)/2 - arctg(AD/CD)]
function shiftAfeterRotate(height, width, rotate)
{
    if ($.browser.msie  && parseInt($.browser.version, 10) === 8) {
        return 0;
    }
    var x = (1/Math.sqrt(2)) *
    Math.sqrt(Math.pow(width,2) + Math.pow(height,2)) *
    Math.sqrt(1 - Math.cos(rotate * (Math.PI / 180))) *
    Math.sin(((180 - rotate)/2 - (Math.atan2(height, width)  * (180 / Math.PI))) * (Math.PI / 180));
    return x;
}
<commit_msg>do private the function shiftAfeterRotate and randomXToY<commit_after>/*! jQuery B1njPolaroidGallery - v1.0
* https://github.com/b1nj/b1njPolaroidGallery
* Includes: jquery.ui.js
* Copyright (c) 2012 b1nj Licensed MIT */
(function ($)
{
    $.fn.b1njPolaroidGallery = function (options)
    {
        var settings = $.extend( {
            'maxRotation' : 20,
            'randomStacking' : true
        }, options);

        this.each (function (index, value)
        {
            $(this).addClass('b1njPolaroidGallery');
            var galleryW = $(this).width();
            var galleryH = $(this).height();
            var nbPhotos = $('li', this).length;
            var zIndex = new Array();
            for(var i=0; i<nbPhotos; i++) {
                zIndex[i] = i + 1;
            }
            if (settings.randomStacking) {
                var zIndex = zIndex.sort(function() { return 0.5 - Math.random() });
            }

            $('li', this).each (function (index, value)
            {
                var alt = $('img', this).attr('alt');
                if (alt != '') {
                    $(this).append('
'+ alt +'
')
                }

                $(this).width($('img', this).width() + (Number($('img', this).css('margin-left').slice(0,-2)) * 2));

                $('a', this).click(function (e)
                {
                    if (!$(this).parent('li').hasClass('b1njPolaroidGallery-linkOk')) {
                        $(this).parent('li').addClass('b1njPolaroidGallery-linkOk');
                        e.preventDefault();
                        e.stopPropagation();
                        //return false;
                    }
                });

                var photoW = $(this).width();
                var photoH = $(this).height();

                var tempRotDegrees = randomXToY(0, settings.maxRotation);
                var tempVal = Math.round(Math.random());
                if(tempVal == 1) {
                    var rotDegrees = 360 - tempRotDegrees; // rotate left
                } else {
                    var rotDegrees = tempRotDegrees; // rotate right
                }

                var shiftT = shiftAfeterRotate(photoH, photoW, tempRotDegrees);
                var shiftL = shiftAfeterRotate(photoW, photoH, tempRotDegrees);

                if (galleryH - shiftT - photoH > shiftT) {
                    var top = randomXToY(shiftT, galleryH - shiftT - photoH);
                } else {
                    var top = shiftT;
                }
                if (galleryW - shiftL - photoW > shiftL) {
                    var left = randomXToY(shiftL, galleryW - shiftL - photoW);
                } else {
                    var left = shiftL;
                }

                var cssObj = {
                    'left' : '+=' + left,
                    'top' : '+=' + top
                };
                cssObj['z-index'] = zIndex[index];
                $(this).css(cssObj).b1njPolaroidGalleryRotate(rotDegrees).data('rotDegrees', rotDegrees);

                $(this).bind('mousedown', function(e)
                {
                    $(this).parent('ul').find('li').not(this).removeClass('b1njPolaroidGallery-active b1njPolaroidGallery-linkOk');
                    $(this).addClass('b1njPolaroidGallery-active');
                }).
                draggable({
                    containment : 'parent',
                    start: function(event, ui) {
                        if (('a', this).length != 0) {
                            $(this).addClass('b1njPolaroidGallery-LinkOk');
                        }
                    },
                    stop: function(event, ui) {
                        rotDegrees = $(this).data('rotDegrees');
                        $(this).b1njPolaroidGalleryRotate(rotDegrees);
                    }
                });
            });
        });

        // Private functions

        // Function to get random number upto m
        // http://roshanbh.com.np/2008/09/get-random-number-range-two-numbers-javascript.html
        function randomXToY(minVal,maxVal,floatVal)
        {
            var randVal = minVal+(Math.random()*(maxVal-minVal));
            return typeof floatVal=='undefined'?Math.round(randVal):randVal.toFixed(floatVal);
        }

        // Fuction get the shift after rotate the photo
        // http://www.maths-forum.com/trigonometrie-rotation-d-un-rectangle-129467.php
        // //x = (1/V2).V(CD² + AD²) * V(1-cos(alpha)) * sin[(180° - alpha)/2 - arctg(AD/CD)]
        function shiftAfeterRotate(height, width, rotate)
        {
            if ($.browser.msie  && parseInt($.browser.version, 10) === 8) {
                return 0;
            }
            var x = (1/Math.sqrt(2)) *
            Math.sqrt(Math.pow(width,2) + Math.pow(height,2)) *
            Math.sqrt(1 - Math.cos(rotate * (Math.PI / 180))) *
            Math.sin(((180 - rotate)/2 - (Math.atan2(height, width)  * (180 / Math.PI))) * (Math.PI / 180));
            return x;
        }
        return this;
    };
    $.fn.b1njPolaroidGalleryRotate = function (rotation)
    {
        if ($.browser.msie  && parseInt($.browser.version, 10) === 8) {
            if (rotation >= 0) {
                var rotation = Math.PI * rotation / 180;
            } else {
                var rotation = Math.PI * (360 + rotation) / 180;
            }
            var cssObj = {
                'filter' : 'progid:DXImageTransform.Microsoft.Matrix(M11=' + Math.cos(rotation) + ",M12=" + (-Math.sin(rotation)) + ",M21=" + Math.sin(rotation) + ",M22=" + Math.cos(rotation) + ",SizingMethod='auto expand')"
            }
        } else {
            var cssObj = {
                '-webkit-transform' : 'rotate('+ rotation +'deg)',
                '-ms-transform' : 'rotate('+ rotation +'deg)',
                '-moz-transform' : 'rotate('+ rotation +'deg)',
                '-o-transform' : 'rotate('+ rotation +'deg)',
                'tranform' : 'rotate('+ rotation +'deg)'
            };
        }
        $(this).css(cssObj);
        return this;
    }
}) (jQuery);<|endoftext|>


<commit_before>'use strict'

module.exports = function (PromiseArgument) {
  var Promise;
  function throat(size, fn) {
    var queue = []
    function run(fn, self, args) {
      if (size) {
        size--
        var result = new Promise(function (resolve) {
          resolve(fn.apply(self, args))
        })
        result.done(release, release)
        return result
      } else {
        return new Promise(function (resolve) {
          queue.push(new Delayed(resolve, fn, self, args))
        })
      }
    }
    function release() {
      size++
      if (queue.length) {
        var next = queue.shift()
        next.resolve(run(next.fn, next.self, next.args))
      }
    }
    if (typeof size === 'function' && typeof fn === 'number') {
      var temp = fn;
      fn = size;
      size = temp;
    }
    if (typeof fn === 'function') {
      return function () {
        var args = [];
        for (var i = 0; i < arguments.length; i++) {
          args.push(arguments[i]);
        }
        return run(fn, this, args)
      }
    } else {
      return function (fn) {
        var args = [];
        for (var i = 1; i < arguments.length; i++) {
          args.push(arguments[i]);
        }
        return run(fn, this, args)
      }
    }
  }
  if (typeof arguments[0] === 'number' || typeof arguments[1] === 'number') {
    Promise = module.exports.Promise;
    if (typeof Promise !== 'function') {
      throw new Error('You must provide a Promise polyfill for this library to work in older environments');
    }
    return throat(arguments[0], arguments[1]);
  } else {
    Promise = PromiseArgument;
    return throat;
  }
}

/* istanbul ignore next */
if (typeof Promise === 'function') {
  module.exports.Promise = Promise;
}

function Delayed(resolve, fn, self, args) {
  this.resolve = resolve
  this.fn = fn
  this.self = self || null
  this.args = args
}
<commit_msg>Don't use `promise.done`<commit_after>'use strict'

module.exports = function (PromiseArgument) {
  var Promise;
  function throat(size, fn) {
    var queue = []
    function run(fn, self, args) {
      if (size) {
        size--
        var result = new Promise(function (resolve) {
          resolve(fn.apply(self, args))
        })
        result.then(release, release)
        return result
      } else {
        return new Promise(function (resolve) {
          queue.push(new Delayed(resolve, fn, self, args))
        })
      }
    }
    function release() {
      size++
      if (queue.length) {
        var next = queue.shift()
        next.resolve(run(next.fn, next.self, next.args))
      }
    }
    if (typeof size === 'function' && typeof fn === 'number') {
      var temp = fn;
      fn = size;
      size = temp;
    }
    if (typeof fn === 'function') {
      return function () {
        var args = [];
        for (var i = 0; i < arguments.length; i++) {
          args.push(arguments[i]);
        }
        return run(fn, this, args)
      }
    } else {
      return function (fn) {
        var args = [];
        for (var i = 1; i < arguments.length; i++) {
          args.push(arguments[i]);
        }
        return run(fn, this, args)
      }
    }
  }
  if (typeof arguments[0] === 'number' || typeof arguments[1] === 'number') {
    Promise = module.exports.Promise;
    if (typeof Promise !== 'function') {
      throw new Error('You must provide a Promise polyfill for this library to work in older environments');
    }
    return throat(arguments[0], arguments[1]);
  } else {
    Promise = PromiseArgument;
    return throat;
  }
}

/* istanbul ignore next */
if (typeof Promise === 'function') {
  module.exports.Promise = Promise;
}

function Delayed(resolve, fn, self, args) {
  this.resolve = resolve
  this.fn = fn
  this.self = self || null
  this.args = args
}
<|endoftext|>


<commit_before>// Copyright 2002-2015, University of Colorado Boulder

/**
 * Maps an input string to a final string, accommodating tricks like doubleStrings above
 * @param string - the string to be mapped
 * @param stringTest - the value of the stringTest query parameter
 * @returns {*}
 */
(function() {
  var mapString = function( string, stringTest ) {
    return stringTest === null ? string :
           stringTest === 'double' ? string + ':' + string :
           stringTest === 'empty' ? '' :
           stringTest === 'none' ? string :

             //In the fallback case, supply whatever string was given in the query parameter value
           stringTest;
  };
  if ( typeof module !== 'undefined' ) {
    module.exports = mapString;
  }
  else {
    define( function() {
      'use strict';

      return mapString;
    } );
  }
})();
<commit_msg>fix lint error, see #72<commit_after>// Copyright 2002-2015, University of Colorado Boulder

/**
 * Maps an input string to a final string, accommodating tricks like doubleStrings above
 * @param string - the string to be mapped
 * @param stringTest - the value of the stringTest query parameter
 * @returns {*}
 */
(function() {
  'use strict';

  var mapString = function( string, stringTest ) {
    return stringTest === null ? string :
           stringTest === 'double' ? string + ':' + string :
           stringTest === 'empty' ? '' :
           stringTest === 'none' ? string :

             //In the fallback case, supply whatever string was given in the query parameter value
           stringTest;
  };
  if ( typeof module !== 'undefined' ) {
    module.exports = mapString;
  }
  else {
    define( function() {
      return mapString;
    } );
  }
})();
<|endoftext|>


<commit_before>var path = __dirname + '/' + (process.env.TEST_COV_SAML2 ? 'lib-js-cov' : 'lib-js') + '/saml2';
module.exports = require(path);
<commit_msg>Uses path.join to create OS agnostic file paths<commit_after>var path = require('path').join(__dirname, (process.env.TEST_COV_SAML2 ? 'lib-js-cov' : 'lib-js'), 'saml2');
module.exports = require(path);
<|endoftext|>


<commit_before>/*
 *   Copyright 2012 OSBI Ltd
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

/**
 * Dialog for member selections
 */
var SelectionsModal = Modal.extend({
    type: "selections",

    buttons: [
        { text: "OK", method: "save" },
        { text: "Cancel", method: "close" }
    ],

    events: {
        'click a': 'call',
        'click .search_term' : 'search_members',
        'click .clear_search' : 'clear_search',
        'change #show_unique': 'show_unique_action',
        'change #use_result': 'use_result_action',
        'dblclick select option' : 'click_move_selection',
        'click div.selection_buttons a.form_button': 'move_selection',
        'click div.updown_buttons a.form_button': 'updown_selection'
    },

    show_unique_option: false,

    use_result_option: Settings.MEMBERS_FROM_RESULT,
    members_limit: Settings.MEMBERS_LIMIT,
    members_search_limit: Settings.MEMBERS_SEARCH_LIMIT,
    members_search_server: false,

    initialize: function(args) {
        // Initialize properties
        _.extend(this, args);
        this.options.title = "Selections for " + this.name;
        this.message = "Fetching members...";
        this.query = args.workspace.query;
        this.selected_members = [];
        this.available_members = [];

        _.bindAll(this, "fetch_members", "populate", "finished", "get_members", "use_result_action");

        // Determine axis
        this.axis = "undefined";
        if (args.axis) {
            this.axis = args.axis;
            if (args.axis == "FILTER") {
                this.use_result_option = false;
            }
        } else {
            if (args.target.parents('.fields_list_body').hasClass('rows')) {
                this.axis = "ROWS";
            }
            if (args.target.parents('.fields_list_body').hasClass('columns')) {
                this.axis = "COLUMNS";
            }
            if (args.target.parents('.fields_list_body').hasClass('filter')) {
                this.axis = "FILTER";
                this.use_result_option = false;
            }
        }
        // Resize when rendered
        this.bind('open', this.post_render);
        this.render();

        $(this.el).parent().find('.ui-dialog-titlebar-close').bind('click',this.finished);

        // Fetch available members
        this.member = new Member({}, {
            cube: args.workspace.selected_cube,
            dimension: args.key
        });

        // Load template
        $(this.el).find('.dialog_body')
            .html(_.template($("#template-selections").html())(this));

        $(this.el).find('#use_result').attr('checked', this.use_result_option);
        $(this.el).find('.search_limit').text(this.members_search_limit);
        $(this.el).find('.members_limit').text(this.members_limit);

        this.get_members();
    },

    get_members: function() {
            var self = this;
            var path = "/result/metadata/hierarchies/" + encodeURIComponent(this.member.hierarchy) + "/levels/" + encodeURIComponent(this.member.level);
            this.search_path = path;

            var message = '   ' + self.message + ' ';
            self.workspace.block(message);

            this.workspace.query.action.get(path, {
                success: this.fetch_members,
                error: function() {
                    self.workspace.unblock();
                },
                data: {result: this.use_result_option, searchlimit: this.members_limit }});
    },

    clear_search: function() {
        $(this.el).find('.filterbox').val('');
        this.get_members();
    },

    search_members: function() {
        var self = this;
        var search_term = $(this.el).find('.filterbox').val();
        if (!search_term)
            return false;

        var message = '   Searching for members matching: ' + search_term;
        self.workspace.block(message);

        self.workspace.query.action.get(self.search_path, {
                async: false,
                success: function(response, model) {
                                if (model && model.length > 0) {
                                    self.available_members = model;
                                }
                                self.populate();
                            },
                error: function () {
                    self.workspace.unblock();
                },
                data: { search: search_term, searchlimit: self.members_search_limit }
        });

    },

    fetch_members: function(model, response) {
        var self = this;
        if (response && response.length > 0) {
            this.available_members = response;
        }
        this.populate();
    },

    populate: function(model, response) {
            var self = this;
            self.workspace.unblock();
            this.members_search_server = (this.available_members.length >= this.members_limit || this.available_members.length == 0);

            self.show_unique_option = false;
            $(this.el).find('.options #show_unique').attr('checked',false);

            $(this.el).find('.items_size').text(this.available_members.length);
            if (this.members_search_server) {
                $(this.el).find('.warning').text("More items available than listed. Pre-Filter on server.");
            } else {
                $(this.el).find('.warning').text("");
            }

            var hName = self.member.hierarchy;
            var lName = self.member.level;
            var hierarchy = self.workspace.query.helper.getHierarchy(hName);
            if (hierarchy && hierarchy.levels.hasOwnProperty(lName)) {
                this.selected_members = hierarchy.levels[lName].selection ? hierarchy.levels[lName].selection.members : [];
            }
            var used_members = [];

            // Populate both boxes
            $(this.el).find('.used_selections select').removeAttr('disabled');
            var selected_members_opts = "";
            for (var j = 0, len = this.selected_members.length; j < len; j++) {
                var member = this.selected_members[j];
                    selected_members_opts += '<option value="' + encodeURIComponent(member.uniqueName) + '">' + member.caption + "</option>";
                    used_members.push(member.caption);
            }
            if (used_members.length > 0) {
                var selectedMembers = $(this.el).find('.used_selections select');
                selectedMembers.empty();
                $(selected_members_opts).appendTo(selectedMembers);
            }

            // Filter out used members
            this.available_members = _.select(this.available_members, function(obj) {
                return used_members.indexOf(obj.caption) === -1;
            });

            $(this.el).find('.available_selections select').removeAttr('disabled');
            var available_members_opts = "";
            for (var i = 0, len = this.available_members.length; i < len; i++) {
                var member = this.available_members[i];
                available_members_opts += '<option value="' + encodeURIComponent(member.uniqueName) + '">' + member.caption + "</option>";
            }
            if (this.available_members.length > 0) {
                var availableMembersSelect = $(this.el).find('.available_selections select');
                availableMembersSelect.empty();
                $(available_members_opts).appendTo(availableMembersSelect);
            }

            $(this.el).find('.filterbox').autocomplete({
                    minLength: 1, //(self.members_search_server ? 2 : 1),
                    delay: 200, //(self.members_search_server ? 400 : 300),
                    appendTo: ".autocomplete",
                    source: function(request, response ) {
                        var searchlist = self.available_members;
                        /*
                            if (false && self.members_search_server) {
                                self.workspace.query.action.get(self.search_path, { async: false, success: function(response, model) {
                                    searchlist = model;
                                }, data: { search: request.term, searchlimit: self.members_search_limit }});

                                response( $.map( searchlist, function( item ) {
                                    return {
                                                        label: item.caption ,
                                                        value: item.uniqueName
                                    };
                                }));

                            } else {
                            */
                            var search_target = self.show_unique_option == false ? "caption" : "name";
                            var result =  $.map( searchlist, function( item ) {

                                            if (item[search_target].toLowerCase().indexOf(request.term.toLowerCase()) > -1) {
                                                var label = self.show_unique_option == false? item.caption : item.uniqueName;
                                                var value = self.show_unique_option == false? item.uniqueName : item.caption;

                                                return {
                                                    label: label,
                                                    value: value
                                                };
                                            }
                                    });
                            response( result);
                    },
                    select:  function(event, ui) {
                        var value = encodeURIComponent(ui.item.value);
                        var label = ui.item.label;

                        $(self.el).find('.available_selections select option[value="' + value + '"]').remove();
                        $(self.el).find('.used_selections select option[value="' + value + '"]').remove();
                        var option = '<option value="' + value + '">' + label + "</option>";

                        $(option).appendTo($(self.el).find('.used_selections select'));
                        $(self.el).find('.filterbox').val('');
                        ui.item.value = "";

                    }, close: function(event, ui) {
                        //$('#filter_selections').val('');
                        //$(self.el).find('.filterbox').css({ "text-align" : " left"});
                    }, open: function( event, ui ) {
                        //$(self.el).find('.filterbox').css({ "text-align" : " right"});

                    }
                });

        $(this.el).find('.filterbox').autocomplete("enable");

		// Translate
		Saiku.i18n.translate();
        // Show dialog
        Saiku.ui.unblock();
    },

    post_render: function(args) {
        var left = ($(window).width() - 1000)/2;
        $(args.modal.el).parents('.ui-dialog')
            .css({ width: 1040, left: "inherit", margin:"0", height: 465 })
            .offset({ left: left});
    },

    move_selection: function(event) {
        event.preventDefault();
        var action = $(event.target).attr('id');
        var $to = action.indexOf('add') !== -1 ?
            $(this.el).find('.used_selections select') :
            $(this.el).find('.available_selections select');
        var $from = action.indexOf('add') !== -1 ?
            $(this.el).find('.available_selections select') :
            $(this.el).find('.used_selections select');
        var $els = action.indexOf('all') !== -1 ?
            $from.find('option') :$from.find('option:selected');
        $els.detach().appendTo($to);
    },

    updown_selection: function(event) {
        event.preventDefault();
        var action = $(event.target).attr('href').replace('#','');
        if (typeof action != "undefined") {
            if ("up" == action) {
                $(this.el).find('.used_selections option:selected').insertBefore( $('.used_selections option:selected:first').prev());
            } else if ("down" == action) {
                $(this.el).find('.used_selections option:selected').insertAfter( $('.used_selections option:selected:last').next());
            }

        }
    },

    click_move_selection: function(event, ui) {
      var to = ($(event.target).parent().parent().hasClass('used_selections')) ? '.available_selections' : '.used_selections';
      $(event.target).appendTo($(this.el).find(to +' select'));
    },

    show_unique_action: function() {
        $.each($(this.el).find('option'), function(i, option) {
            var text = $(option).text();
            $(option).text(decodeURIComponent($(option).val()));
            $(option).val(encodeURIComponent(text));
        });
        this.show_unique_option= ! this.show_unique_option;
    },

    use_result_action: function() {
        this.use_result_option = !this.use_result_option;
        //console.log(this.use_result_option);
        this.get_members();
    },

    save: function() {
        var self = this;
        // Notify user that updates are in progress
        var $loading = $("
Saving...
");
        $(this.el).find('.dialog_body').children().hide();
        $(this.el).find('.dialog_body').prepend($loading);
        var show_u = this.show_unique_option;

        var hName = decodeURIComponent(self.member.hierarchy);
        var lName = decodeURIComponent(self.member.level)
        var hierarchy = self.workspace.query.helper.getHierarchy(hName);

        // Determine updates
        var updates = [];

        // If no selections are used, add level
        if ($(this.el).find('.used_selections option').length === 0) {
            // nothing to do - include all members of this level
        } else {
            // Loop through selections
            $(this.el).find('.used_selections option')
                .each(function(i, selection) {
                var value = show_u ?
                    encodeURIComponent($(selection).text()) : $(selection).val();
                var caption = show_u ?
                    $(selection).val() : encodeURIComponent($(selection).text());
                updates.push({
                    uniqueName: decodeURIComponent(value),
                    caption: decodeURIComponent(caption)
                });
            });
        }

        if (hierarchy && hierarchy.levels.hasOwnProperty(lName)) {
                hierarchy.levels[lName].selection = { "type": "INCLUSION", "members": updates };
        }

        this.finished();
    },

    finished: function() {
        $('#filter_selections').remove();
        this.available_members = null;
        $(this.el).find('.filterbox').autocomplete('destroy').remove();
        $(this.el).dialog('destroy');
        $(this.el).remove();
        this.query.run();
    }
});
<commit_msg>check max width for selectionsmodal<commit_after>/*
 *   Copyright 2012 OSBI Ltd
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

/**
 * Dialog for member selections
 */
var SelectionsModal = Modal.extend({
    type: "selections",

    buttons: [
        { text: "OK", method: "save" },
        { text: "Cancel", method: "close" }
    ],

    events: {
        'click a': 'call',
        'click .search_term' : 'search_members',
        'click .clear_search' : 'clear_search',
        'change #show_unique': 'show_unique_action',
        'change #use_result': 'use_result_action',
        'dblclick select option' : 'click_move_selection',
        'click div.selection_buttons a.form_button': 'move_selection',
        'click div.updown_buttons a.form_button': 'updown_selection'
    },

    show_unique_option: false,

    use_result_option: Settings.MEMBERS_FROM_RESULT,
    members_limit: Settings.MEMBERS_LIMIT,
    members_search_limit: Settings.MEMBERS_SEARCH_LIMIT,
    members_search_server: false,

    initialize: function(args) {
        // Initialize properties
        _.extend(this, args);
        this.options.title = "Selections for " + this.name;
        this.message = "Fetching members...";
        this.query = args.workspace.query;
        this.selected_members = [];
        this.available_members = [];

        _.bindAll(this, "fetch_members", "populate", "finished", "get_members", "use_result_action");

        // Determine axis
        this.axis = "undefined";
        if (args.axis) {
            this.axis = args.axis;
            if (args.axis == "FILTER") {
                this.use_result_option = false;
            }
        } else {
            if (args.target.parents('.fields_list_body').hasClass('rows')) {
                this.axis = "ROWS";
            }
            if (args.target.parents('.fields_list_body').hasClass('columns')) {
                this.axis = "COLUMNS";
            }
            if (args.target.parents('.fields_list_body').hasClass('filter')) {
                this.axis = "FILTER";
                this.use_result_option = false;
            }
        }
        // Resize when rendered
        this.bind('open', this.post_render);
        this.render();

        $(this.el).parent().find('.ui-dialog-titlebar-close').bind('click',this.finished);

        // Fetch available members
        this.member = new Member({}, {
            cube: args.workspace.selected_cube,
            dimension: args.key
        });

        // Load template
        $(this.el).find('.dialog_body')
            .html(_.template($("#template-selections").html())(this));

        $(this.el).find('#use_result').attr('checked', this.use_result_option);
        $(this.el).find('.search_limit').text(this.members_search_limit);
        $(this.el).find('.members_limit').text(this.members_limit);

        this.get_members();
    },

    get_members: function() {
            var self = this;
            var path = "/result/metadata/hierarchies/" + encodeURIComponent(this.member.hierarchy) + "/levels/" + encodeURIComponent(this.member.level);
            this.search_path = path;

            var message = '   ' + self.message + ' ';
            self.workspace.block(message);

            this.workspace.query.action.get(path, {
                success: this.fetch_members,
                error: function() {
                    self.workspace.unblock();
                },
                data: {result: this.use_result_option, searchlimit: this.members_limit }});
    },

    clear_search: function() {
        $(this.el).find('.filterbox').val('');
        this.get_members();
    },

    search_members: function() {
        var self = this;
        var search_term = $(this.el).find('.filterbox').val();
        if (!search_term)
            return false;

        var message = '   Searching for members matching: ' + search_term;
        self.workspace.block(message);

        self.workspace.query.action.get(self.search_path, {
                async: false,
                success: function(response, model) {
                                if (model && model.length > 0) {
                                    self.available_members = model;
                                }
                                self.populate();
                            },
                error: function () {
                    self.workspace.unblock();
                },
                data: { search: search_term, searchlimit: self.members_search_limit }
        });

    },

    fetch_members: function(model, response) {
        var self = this;
        if (response && response.length > 0) {
            this.available_members = response;
        }
        this.populate();
    },

    populate: function(model, response) {
            var self = this;
            self.workspace.unblock();
            this.members_search_server = (this.available_members.length >= this.members_limit || this.available_members.length == 0);

            self.show_unique_option = false;
            $(this.el).find('.options #show_unique').attr('checked',false);

            $(this.el).find('.items_size').text(this.available_members.length);
            if (this.members_search_server) {
                $(this.el).find('.warning').text("More items available than listed. Pre-Filter on server.");
            } else {
                $(this.el).find('.warning').text("");
            }

            var hName = self.member.hierarchy;
            var lName = self.member.level;
            var hierarchy = self.workspace.query.helper.getHierarchy(hName);
            if (hierarchy && hierarchy.levels.hasOwnProperty(lName)) {
                this.selected_members = hierarchy.levels[lName].selection ? hierarchy.levels[lName].selection.members : [];
            }
            var used_members = [];

            // Populate both boxes
            $(this.el).find('.used_selections select').removeAttr('disabled');
            var selected_members_opts = "";
            for (var j = 0, len = this.selected_members.length; j < len; j++) {
                var member = this.selected_members[j];
                    selected_members_opts += '<option value="' + encodeURIComponent(member.uniqueName) + '">' + member.caption + "</option>";
                    used_members.push(member.caption);
            }
            if (used_members.length > 0) {
                var selectedMembers = $(this.el).find('.used_selections select');
                selectedMembers.empty();
                $(selected_members_opts).appendTo(selectedMembers);
            }

            // Filter out used members
            this.available_members = _.select(this.available_members, function(obj) {
                return used_members.indexOf(obj.caption) === -1;
            });

            $(this.el).find('.available_selections select').removeAttr('disabled');
            var available_members_opts = "";
            for (var i = 0, len = this.available_members.length; i < len; i++) {
                var member = this.available_members[i];
                available_members_opts += '<option value="' + encodeURIComponent(member.uniqueName) + '">' + member.caption + "</option>";
            }
            if (this.available_members.length > 0) {
                var availableMembersSelect = $(this.el).find('.available_selections select');
                availableMembersSelect.empty();
                $(available_members_opts).appendTo(availableMembersSelect);
            }

            $(this.el).find('.filterbox').autocomplete({
                    minLength: 1, //(self.members_search_server ? 2 : 1),
                    delay: 200, //(self.members_search_server ? 400 : 300),
                    appendTo: ".autocomplete",
                    source: function(request, response ) {
                        var searchlist = self.available_members;
                        /*
                            if (false && self.members_search_server) {
                                self.workspace.query.action.get(self.search_path, { async: false, success: function(response, model) {
                                    searchlist = model;
                                }, data: { search: request.term, searchlimit: self.members_search_limit }});

                                response( $.map( searchlist, function( item ) {
                                    return {
                                                        label: item.caption ,
                                                        value: item.uniqueName
                                    };
                                }));

                            } else {
                            */
                            var search_target = self.show_unique_option == false ? "caption" : "name";
                            var result =  $.map( searchlist, function( item ) {

                                            if (item[search_target].toLowerCase().indexOf(request.term.toLowerCase()) > -1) {
                                                var label = self.show_unique_option == false? item.caption : item.uniqueName;
                                                var value = self.show_unique_option == false? item.uniqueName : item.caption;

                                                return {
                                                    label: label,
                                                    value: value
                                                };
                                            }
                                    });
                            response( result);
                    },
                    select:  function(event, ui) {
                        var value = encodeURIComponent(ui.item.value);
                        var label = ui.item.label;

                        $(self.el).find('.available_selections select option[value="' + value + '"]').remove();
                        $(self.el).find('.used_selections select option[value="' + value + '"]').remove();
                        var option = '<option value="' + value + '">' + label + "</option>";

                        $(option).appendTo($(self.el).find('.used_selections select'));
                        $(self.el).find('.filterbox').val('');
                        ui.item.value = "";

                    }, close: function(event, ui) {
                        //$('#filter_selections').val('');
                        //$(self.el).find('.filterbox').css({ "text-align" : " left"});
                    }, open: function( event, ui ) {
                        //$(self.el).find('.filterbox').css({ "text-align" : " right"});

                    }
                });

        $(this.el).find('.filterbox').autocomplete("enable");

		// Translate
		Saiku.i18n.translate();
        // Show dialog
        Saiku.ui.unblock();
    },

    post_render: function(args) {
        var left = ($(window).width() - 1000)/2;
        var width = $(window).width() < 1040 ? $(window).width() : 1040;
        $(args.modal.el).parents('.ui-dialog')
            .css({ width: width, left: "inherit", margin:"0", height: 465 })
            .offset({ left: left});
    },

    move_selection: function(event) {
        event.preventDefault();
        var action = $(event.target).attr('id');
        var $to = action.indexOf('add') !== -1 ?
            $(this.el).find('.used_selections select') :
            $(this.el).find('.available_selections select');
        var $from = action.indexOf('add') !== -1 ?
            $(this.el).find('.available_selections select') :
            $(this.el).find('.used_selections select');
        var $els = action.indexOf('all') !== -1 ?
            $from.find('option') :$from.find('option:selected');
        $els.detach().appendTo($to);
    },

    updown_selection: function(event) {
        event.preventDefault();
        var action = $(event.target).attr('href').replace('#','');
        if (typeof action != "undefined") {
            if ("up" == action) {
                $(this.el).find('.used_selections option:selected').insertBefore( $('.used_selections option:selected:first').prev());
            } else if ("down" == action) {
                $(this.el).find('.used_selections option:selected').insertAfter( $('.used_selections option:selected:last').next());
            }

        }
    },

    click_move_selection: function(event, ui) {
      var to = ($(event.target).parent().parent().hasClass('used_selections')) ? '.available_selections' : '.used_selections';
      $(event.target).appendTo($(this.el).find(to +' select'));
    },

    show_unique_action: function() {
        $.each($(this.el).find('option'), function(i, option) {
            var text = $(option).text();
            $(option).text(decodeURIComponent($(option).val()));
            $(option).val(encodeURIComponent(text));
        });
        this.show_unique_option= ! this.show_unique_option;
    },

    use_result_action: function() {
        this.use_result_option = !this.use_result_option;
        //console.log(this.use_result_option);
        this.get_members();
    },

    save: function() {
        var self = this;
        // Notify user that updates are in progress
        var $loading = $("
Saving...
");
        $(this.el).find('.dialog_body').children().hide();
        $(this.el).find('.dialog_body').prepend($loading);
        var show_u = this.show_unique_option;

        var hName = decodeURIComponent(self.member.hierarchy);
        var lName = decodeURIComponent(self.member.level)
        var hierarchy = self.workspace.query.helper.getHierarchy(hName);

        // Determine updates
        var updates = [];

        // If no selections are used, add level
        if ($(this.el).find('.used_selections option').length === 0) {
            // nothing to do - include all members of this level
        } else {
            // Loop through selections
            $(this.el).find('.used_selections option')
                .each(function(i, selection) {
                var value = show_u ?
                    encodeURIComponent($(selection).text()) : $(selection).val();
                var caption = show_u ?
                    $(selection).val() : encodeURIComponent($(selection).text());
                updates.push({
                    uniqueName: decodeURIComponent(value),
                    caption: decodeURIComponent(caption)
                });
            });
        }

        if (hierarchy && hierarchy.levels.hasOwnProperty(lName)) {
                hierarchy.levels[lName].selection = { "type": "INCLUSION", "members": updates };
        }

        this.finished();
    },

    finished: function() {
        $('#filter_selections').remove();
        this.available_members = null;
        $(this.el).find('.filterbox').autocomplete('destroy').remove();
        $(this.el).dialog('destroy');
        $(this.el).remove();
        this.query.run();
    }
});
<|endoftext|>


<commit_before>'use strict';

module.exports = {
  name: 'Ember CLI ic-ajax',

  init: function(name) {
    var assets_path = require('path').join('ic-ajax','dist','cjs','main.js');
    this.treePaths['vendor'] = require.resolve('ic-ajax').replace(assets_path, '');
  },

  included: function(app) {
    var options = this.app.options.icAjaxOptions || {enabled: true};

    if (options.enabled) {
      this.app.import('vendor/ic-ajax/dist/named-amd/main.js', {
        exports: {
          'ic-ajax': [
            'default',
            'defineFixture',
            'lookupFixture',
            'raw',
            'request',
          ]
        }
      });
    }
  }
};
<commit_msg>CoreObject 1.x and 2.x compat<commit_after>'use strict';

module.exports = {
  name: 'Ember CLI ic-ajax',

  init: function(name) {
    this._super.init && this._super.init.apply(this, arguments);

    var assets_path = require('path').join('ic-ajax','dist','cjs','main.js');
    this.treePaths['vendor'] = require.resolve('ic-ajax').replace(assets_path, '');
  },

  included: function(app) {
    var options = this.app.options.icAjaxOptions || {enabled: true};

    if (options.enabled) {
      this.app.import('vendor/ic-ajax/dist/named-amd/main.js', {
        exports: {
          'ic-ajax': [
            'default',
            'defineFixture',
            'lookupFixture',
            'raw',
            'request',
          ]
        }
      });
    }
  }
};
<|endoftext|>


<commit_before>'use strict';
/*jslint node: true */
/*jslint unparam: true */
/*global which, gulp, tempdir, test, exec, ls */
var gutil = require('gulp-util'),
    shelljs = require('shelljs/global'),
    through = require('through2'),

    stream = through.obj(function (file, enc, callback) {
        this.push(file);
        callback();
    });

var build_arguments = function (opts) {
        var i, args = [], // initialize command array
            keys = Object.keys(opts),
            parameter;
        for (i = 0; i < keys.length; i += 1) {
            if (opts[keys[i]]) { //handle false case if passed in explicitly
                parameter = ((keys[i].length === 1) ? '-' : '--'); // use - for d, w, n, etc.
                parameter += keys[i]; // add parameter name
                if (typeof opts[keys[i]] !== 'boolean') {
                    parameter += ' ' + opts[keys[i]];
                }
                args.push(parameter); // add parameter to command array
            }
        }
        return args.join(' ');
    },
    log_indent = '|   ',
    log_exec = function (output) {
        var output_lines, log_line;
        if (output) {
            output_lines = output.replace(/^\s+|\s+$/, '').split(/[\n\r]+/); // Trims the output and returns it split into an array of lines
            for (log_line = 0; log_line < output_lines.length; log_line += 1) {
                gutil.log(log_indent, output_lines[log_line]);
            }
        }
    };
/*jslint unparam: false*/

if (!which('php')) {
    stream.emit('error', new gutil.PluginError('gulp-composer', "PHP is a composer requirement and therefore it is required to use gulp-composer."));
}
module.exports = function (cmd, opts) {
    var commandToRun, execReturn,
        self_install = true,
        async = true,
        bin, cwd,
        handle_exec = function (code, output) {
            if (code !== 0) {
                stream.emit('error', new gutil.PluginError('gulp-composer', output));
            }

            log_exec(output);

            gutil.log(gutil.colors.cyan.inverse(" Composer completed.                                                       "));

            stream.end();
            stream.emit("end");
        };

    if (cmd === undefined || typeof cmd === 'object') {
        // Looks like this was called with either no parameters
        // or the options were passed through the first parameter
        // In this case, we'll ignore all subsequent params
        opts = cmd || {};
        cmd = 'install';
    } else {
        // Make sure opts is set
        opts = opts || {};
    }

    // optional self-install support
    if (opts['self-install'] !== undefined) {
        self_install = !!opts['self-install'];
        delete opts['self-install']; // avoid sending parameter to composer
    }

    // optional async support
    if (opts.async !== undefined) {
        async = !!opts.async;
        delete opts.async; // avoid sending parameter to composer
    }

    // cwd legacy support
    cwd = opts['working-dir'] || opts.d || opts.cwd || process.cwd();

    // using --working-dir=xxxx instead of -d makes logging clearer
    // and allows us to remove an unneeded `gutil.log` line
    opts['working-dir'] = cwd;

    delete opts.cwd; // avoid sending parameter to composer
    delete opts.d; // avoid sending duplicate -d parameter

    // Ensure opts.quiet is a bool
    opts.quiet = !!opts.quiet;

    if (!opts.quiet) {
        // Turn colors on by default
        if (!opts['no-ansi'] && opts.ansi === undefined) {
            opts.ansi = true;
        }
    }

    if (opts.bin === 'auto') {
        delete opts.bin;
    }

    bin = opts.bin || (function () {
        var self_install_cmd,
            self_install_dir = tempdir(),
            self_install_file = 'gulp-composer.phar',
            self_install_path = self_install_dir + '/' + self_install_file,
            self_install_options = build_arguments({
                'install-dir': self_install_dir,
                'filename': self_install_file,
                'quiet': opts.quiet,
                'ansi': opts.ansi,
                'no-ansi': !opts.ansi
            }),
            self_install_alert = function () {
                gutil.log();
                gutil.log(gutil.colors.yellow.inverse(" Significantly improve performance by installing composer on this machine. "));
                gutil.log(gutil.colors.yellow.inverse(" Installation: ") + gutil.colors.yellow.underline.inverse("https://getcomposer.org/doc/00-intro.md") + gutil.colors.yellow.inverse("                     "));
                gutil.log();
            };

        // Use composer.phar if it exists locally...
        if (test('-e', cwd + '/composer.phar')) {
            gutil.log(gutil.colors.green("Defaulting to locally installed " + cwd + "/composer.phar..."));
            return cwd + '/composer.phar';
        }
        gutil.log(gutil.colors.yellow("Composer is not available locally."));

        // Otherwise use composer if it's installed globally...
        if (which('composer')) {
            gutil.log(gutil.colors.green("Defaulting to globally installed composer..."));
            return 'composer';
        }
        gutil.log(gutil.colors.yellow("Composer is not available globally."));

        if (!self_install) {
            gutil.log(gutil.colors.red.inverse("Failed to load composer and self-install has been disabled."));
            gutil.log(gutil.colors.red.inverse("Installation instructions: ") + gutil.colors.blue.underline.inverse("https://getcomposer.org/doc/00-intro.md"));
            return '';
        }

        if (test('-e', self_install_path)) {
            gutil.log(gutil.colors.yellow("Loading composer from system temp directory..."));
            self_install_alert();
            return self_install_path;
        }

        gutil.log(gutil.colors.yellow("Composer is not available from the system temp, either."));

        // It doesn't exist, so we'll attempt to download it locally and delete it afterward
        if (self_install_options) {
            self_install_options = ' -- ' + self_install_options;
        }

        gutil.log(gutil.colors.magenta.inverse(" Attempting to download composer to system temp directory...               "));
        self_install_cmd = exec('php -r "readfile(\'https://getcomposer.org/installer\');" | php' + self_install_options, {
            async: false,
            silent: true
        });

        if (self_install_cmd.code !== 0) {
            stream.emit('error', new gutil.PluginError('gulp-composer', self_install_cmd.output));
        }
        log_exec(self_install_cmd.output);

        if (ls(self_install_path)[0]) {
            gutil.log(gutil.colors.magenta.inverse(" Successfully downloaded!                                                  "));
            self_install_alert();
            return self_install_path;
        }

        gutil.log(gutil.colors.red.inverse("Failed to download. All options have been exhausted."));
        gutil.log(gutil.colors.red.inverse("Installation instructions: ") + gutil.colors.blue.underline.inverse("https://getcomposer.org/doc/00-intro.md"));

        return '';
    }());
    delete opts.bin; // avoid sending bin parameter

    if (!bin) {
        stream.emit('error', new gutil.PluginError('gulp-composer', "Composer executable does not exist. " + (self_install ? "Self-install was unsuccessful. Please install before continuing." : "Please install or enable the self-install option before continuing.")));
    }

    // build the command array
    commandToRun = [bin, cmd, build_arguments(opts)].join(' ');
    gutil.log(gutil.colors.red(commandToRun));
    gutil.log();
    gutil.log(gutil.colors.cyan.inverse(" Executing composer...                                                     "));

    if (async) {
        exec(commandToRun, {
            silent: true
        }, handle_exec);
    } else {
        execReturn = exec(commandToRun, {
            silent: true,
            async: false
        });
        if(typeof execReturn.output === 'undefined') execReturn.output = execReturn.stderr;
        handle_exec(execReturn.code, execReturn.output);
    }

    return stream;
};
<commit_msg>fix execution of composer.phar in temp folder<commit_after>'use strict';
/*jslint node: true */
/*jslint unparam: true */
/*global which, gulp, tempdir, test, exec, ls */
var gutil = require('gulp-util'),
    shelljs = require('shelljs/global'),
    through = require('through2'),

    stream = through.obj(function (file, enc, callback) {
        this.push(file);
        callback();
    });

var build_arguments = function (opts) {
        var i, args = [], // initialize command array
            keys = Object.keys(opts),
            parameter;
        for (i = 0; i < keys.length; i += 1) {
            if (opts[keys[i]]) { //handle false case if passed in explicitly
                parameter = ((keys[i].length === 1) ? '-' : '--'); // use - for d, w, n, etc.
                parameter += keys[i]; // add parameter name
                if (typeof opts[keys[i]] !== 'boolean') {
                    parameter += ' ' + opts[keys[i]];
                }
                args.push(parameter); // add parameter to command array
            }
        }
        return args.join(' ');
    },
    log_indent = '|   ',
    log_exec = function (output) {
        var output_lines, log_line;
        if (output) {
            output_lines = output.replace(/^\s+|\s+$/, '').split(/[\n\r]+/); // Trims the output and returns it split into an array of lines
            for (log_line = 0; log_line < output_lines.length; log_line += 1) {
                gutil.log(log_indent, output_lines[log_line]);
            }
        }
    };
/*jslint unparam: false*/

if (!which('php')) {
    stream.emit('error', new gutil.PluginError('gulp-composer', "PHP is a composer requirement and therefore it is required to use gulp-composer."));
}
module.exports = function (cmd, opts) {
    var commandToRun, execReturn,
        self_install = true,
        async = true,
        bin, cwd,
        handle_exec = function (code, output) {
            if (code !== 0) {
                stream.emit('error', new gutil.PluginError('gulp-composer', output));
            }

            log_exec(output);

            gutil.log(gutil.colors.cyan.inverse(" Composer completed.                                                       "));

            stream.end();
            stream.emit("end");
        };

    if (cmd === undefined || typeof cmd === 'object') {
        // Looks like this was called with either no parameters
        // or the options were passed through the first parameter
        // In this case, we'll ignore all subsequent params
        opts = cmd || {};
        cmd = 'install';
    } else {
        // Make sure opts is set
        opts = opts || {};
    }

    // optional self-install support
    if (opts['self-install'] !== undefined) {
        self_install = !!opts['self-install'];
        delete opts['self-install']; // avoid sending parameter to composer
    }

    // optional async support
    if (opts.async !== undefined) {
        async = !!opts.async;
        delete opts.async; // avoid sending parameter to composer
    }

    // cwd legacy support
    cwd = opts['working-dir'] || opts.d || opts.cwd || process.cwd();

    // using --working-dir=xxxx instead of -d makes logging clearer
    // and allows us to remove an unneeded `gutil.log` line
    opts['working-dir'] = cwd;

    delete opts.cwd; // avoid sending parameter to composer
    delete opts.d; // avoid sending duplicate -d parameter

    // Ensure opts.quiet is a bool
    opts.quiet = !!opts.quiet;

    if (!opts.quiet) {
        // Turn colors on by default
        if (!opts['no-ansi'] && opts.ansi === undefined) {
            opts.ansi = true;
        }
    }

    if (opts.bin === 'auto') {
        delete opts.bin;
    }

    bin = opts.bin || (function () {
        var self_install_cmd,
            self_install_dir = tempdir(),
            self_install_file = 'gulp-composer.phar',
            self_install_path = self_install_dir + '/' + self_install_file,
            self_install_options = build_arguments({
                'install-dir': self_install_dir,
                'filename': self_install_file,
                'quiet': opts.quiet,
                'ansi': opts.ansi,
                'no-ansi': !opts.ansi
            }),
            self_install_alert = function () {
                gutil.log();
                gutil.log(gutil.colors.yellow.inverse(" Significantly improve performance by installing composer on this machine. "));
                gutil.log(gutil.colors.yellow.inverse(" Installation: ") + gutil.colors.yellow.underline.inverse("https://getcomposer.org/doc/00-intro.md") + gutil.colors.yellow.inverse("                     "));
                gutil.log();
            };

        // Use composer.phar if it exists locally...
        if (test('-e', cwd + '/composer.phar')) {
            gutil.log(gutil.colors.green("Defaulting to locally installed " + cwd + "/composer.phar..."));
            return cwd + '/composer.phar';
        }
        gutil.log(gutil.colors.yellow("Composer is not available locally."));

        // Otherwise use composer if it's installed globally...
        if (which('composer')) {
            gutil.log(gutil.colors.green("Defaulting to globally installed composer..."));
            return 'composer';
        }
        gutil.log(gutil.colors.yellow("Composer is not available globally."));

        if (!self_install) {
            gutil.log(gutil.colors.red.inverse("Failed to load composer and self-install has been disabled."));
            gutil.log(gutil.colors.red.inverse("Installation instructions: ") + gutil.colors.blue.underline.inverse("https://getcomposer.org/doc/00-intro.md"));
            return '';
        }

        if (test('-e', self_install_path)) {
            gutil.log(gutil.colors.yellow("Loading composer from system temp directory..."));
            self_install_alert();
            return self_install_path;
        }

        gutil.log(gutil.colors.yellow("Composer is not available from the system temp, either."));

        // It doesn't exist, so we'll attempt to download it locally and delete it afterward
        if (self_install_options) {
            self_install_options = ' -- ' + self_install_options;
        }

        gutil.log(gutil.colors.magenta.inverse(" Attempting to download composer to system temp directory...               "));
        self_install_cmd = exec('php -r "readfile(\'https://getcomposer.org/installer\');" | php' + self_install_options, {
            async: false,
            silent: true
        });

        if (self_install_cmd.code !== 0) {
            stream.emit('error', new gutil.PluginError('gulp-composer', self_install_cmd.output));
        }
        log_exec(self_install_cmd.output);

        if (ls(self_install_path)[0]) {
            gutil.log(gutil.colors.magenta.inverse(" Successfully downloaded!                                                  "));
            self_install_alert();
            return self_install_path;
        }

        gutil.log(gutil.colors.red.inverse("Failed to download. All options have been exhausted."));
        gutil.log(gutil.colors.red.inverse("Installation instructions: ") + gutil.colors.blue.underline.inverse("https://getcomposer.org/doc/00-intro.md"));

        return '';
    }());
    delete opts.bin; // avoid sending bin parameter

    if (!bin) {
        stream.emit('error', new gutil.PluginError('gulp-composer', "Composer executable does not exist. " + (self_install ? "Self-install was unsuccessful. Please install before continuing." : "Please install or enable the self-install option before continuing.")));
    }

	// fix self install command
	if(self_install) {
        bin = 'php ' + bin;
    }

    // build the command array
    commandToRun = [bin, cmd, build_arguments(opts)].join(' ');
    gutil.log(gutil.colors.red(commandToRun));
    gutil.log();
    gutil.log(gutil.colors.cyan.inverse(" Executing composer...                                                     "));

    if (async) {
        exec(commandToRun, {
            silent: true
        }, handle_exec);
    } else {
        execReturn = exec(commandToRun, {
            silent: true,
            async: false
        });
        if(typeof execReturn.output === 'undefined') execReturn.output = execReturn.stderr;
        handle_exec(execReturn.code, execReturn.output);
    }

    return stream;
};
<|endoftext|>


<commit_before>var app = require("./app");
var port = process.env.PORT || 5000;

app.listen(port, function() {
    console.log("Listening on " + port);
});<commit_msg>Check for users table on app start.<commit_after>var app = require("./app");
var port = process.env.PORT || 5000;

var pg = require("pg");
var fs = require("fs");

pg.connect(process.env.DATABASE_URL, function (err, client) {
    if (err) {
        return console.error("could not connect to postgres", err);
    }
    //TODO: handle registration process, sanitize before doing the insert.
    //TODO: insert query must be run asynch, to get the callback for errors like non-unique values, etc.

    var checkTableQuery = "select * from information_schema.tables where table_name='users'";

    client.query(checkTableQuery, function (err, result){
        if (err) {
            console.log("The users table doesn't exist.", err);

            var createSQL = fs.readFileSync("databases/users.sql", "utf8");

            client.query(createSQL, function (err, result) {
                if (err) {
                    console.log("ERROR on creating users table:", err);
                }
                else {
                    console.log("Created the users table.");
                }
            });
        }
        else {
            console.log("The users table already exists.");
        }
    });
});

app.listen(port, function() {
    console.log("Listening on " + port);
});<|endoftext|>


<commit_before>'use strict';

/* eslint-env node */

const VersionChecker = require('ember-cli-version-checker');

module.exports = {
  name: 'ember-test-selectors',

  _assignOptions(app) {
    let ui = app.project.ui;

    let appOptions = app.options || {};
    let addonOptions = appOptions['ember-test-selectors'] || {};

    if (addonOptions.environments) {
      ui.writeDeprecateLine('The "environments" option in "ember-test-selectors" has been replaced ' +
        'with the "strip" option. Use e.g. "strip: EmberApp.env() === \'production\'" instead to ' +
        'recreate the old behavior.', false);

      this._stripTestSelectors = (addonOptions.environments.indexOf(app.env) !== -1);
    } else if ('strip' in addonOptions) {
      this._stripTestSelectors = addonOptions.strip;
    } else {
      this._stripTestSelectors = !app.tests;
    }
  },

  _setupPreprocessorRegistry(registry) {
    if (this._stripTestSelectors) {
      let StripTestSelectorsTransform = require('./strip-test-selectors');

      registry.add('htmlbars-ast-plugin', {
        name: 'strip-test-selectors',
        plugin: StripTestSelectorsTransform,
        baseDir() { return __dirname; }
      });
    } else {
      let TransformTestSelectorParamsToHashPairs = require('./transform-test-selector-params-to-hash-pairs');

      registry.add('htmlbars-ast-plugin', {
        name: 'transform-test-selector-params-to-hash-pairs',
        plugin: TransformTestSelectorParamsToHashPairs,
        baseDir() { return __dirname; }
      });
    }
  },

  included(app) {
    this._super.included.apply(this, arguments);
    this._ensureFindHost();

    let host = this._findHost();
    this._assignOptions(host);

    // we can't use the setupPreprocessorRegistry() hook as it is called to
    // early and we do not have reliable access to `app.tests` there yet
    this._setupPreprocessorRegistry(app.registry);

    // add the StripDataTestPropertiesPlugin to the list of plugins used by
    // the `ember-cli-babel` addon
    if (this._stripTestSelectors && !this._registeredWithBabel) {
      let checker = new VersionChecker(this).for('ember-cli-babel', 'npm');

      app.options = app.options || {};

      if (checker.satisfies('^5.0.0')) {
        app.options.babel = app.options.babel || {};
        app.options.babel.plugins = app.options.babel.plugins || [];
        app.options.babel.plugins.push(require('./strip-data-test-properties-plugin'));
      } else if (checker.satisfies('^6.0.0-beta.1')) {
        app.options.babel6 = app.options.babel6 || {};
        app.options.babel6.plugins = app.options.babel6.plugins || [];
        app.options.babel6.plugins.push(require('./strip-data-test-properties-plugin6'));
      } else {
        this.ui.writeWarnLine('ember-test-selectors: You are using an unsupported ember-cli-babel version. data-test ' +
          'properties are not automatically stripped from your JS code.');
      }

      this._registeredWithBabel = true;
    }

    if (!this._stripTestSelectors) {
      app.import('vendor/ember-test-selectors/patch-component.js');
    }
  },

  treeForAddon() {
    // remove our "addon" folder from the build if we're stripping test selectors
    if (!this._stripTestSelectors) {
      return this._super.treeForAddon.apply(this, arguments);
    }
  },

  preprocessTree(type, tree) {
    // remove the unit tests if we're testing ourself and are in strip mode.
    // we do this because these tests depend on the "addon" and "app" folders being available,
    // which is not the case if they are stripped out of the build.
    if (type === 'test' && this._stripTestSelectors && this.project.name() === 'ember-test-selectors') {
      tree = require('broccoli-stew').rm(tree, 'dummy/tests/unit/**/*.js');
    }
    return tree;
  },

  _ensureFindHost() {
    if (!this._findHost) {
      this._findHost = function findHostShim() {
        let current = this;
        let app;
        do {
          app = current.app || app;
        } while (current.parent.parent && (current = current.parent));
        return app;
      };
    }
  },
};
<commit_msg>Add cacheKey() methods to template transforms<commit_after>'use strict';

/* eslint-env node */

const VersionChecker = require('ember-cli-version-checker');

module.exports = {
  name: 'ember-test-selectors',

  _assignOptions(app) {
    let ui = app.project.ui;

    let appOptions = app.options || {};
    let addonOptions = appOptions['ember-test-selectors'] || {};

    if (addonOptions.environments) {
      ui.writeDeprecateLine('The "environments" option in "ember-test-selectors" has been replaced ' +
        'with the "strip" option. Use e.g. "strip: EmberApp.env() === \'production\'" instead to ' +
        'recreate the old behavior.', false);

      this._stripTestSelectors = (addonOptions.environments.indexOf(app.env) !== -1);
    } else if ('strip' in addonOptions) {
      this._stripTestSelectors = addonOptions.strip;
    } else {
      this._stripTestSelectors = !app.tests;
    }
  },

  _setupPreprocessorRegistry(registry) {
    if (this._stripTestSelectors) {
      let StripTestSelectorsTransform = require('./strip-test-selectors');

      registry.add('htmlbars-ast-plugin', {
        name: 'strip-test-selectors',
        plugin: StripTestSelectorsTransform,
        baseDir() { return __dirname; },
        cacheKey() { return 'strip-test-selectors'; },
      });
    } else {
      let TransformTestSelectorParamsToHashPairs = require('./transform-test-selector-params-to-hash-pairs');

      registry.add('htmlbars-ast-plugin', {
        name: 'transform-test-selector-params-to-hash-pairs',
        plugin: TransformTestSelectorParamsToHashPairs,
        baseDir() { return __dirname; },
        cacheKey() { return 'transform-test-selector-params-to-hash-pairs'; },
      });
    }
  },

  included(app) {
    this._super.included.apply(this, arguments);
    this._ensureFindHost();

    let host = this._findHost();
    this._assignOptions(host);

    // we can't use the setupPreprocessorRegistry() hook as it is called to
    // early and we do not have reliable access to `app.tests` there yet
    this._setupPreprocessorRegistry(app.registry);

    // add the StripDataTestPropertiesPlugin to the list of plugins used by
    // the `ember-cli-babel` addon
    if (this._stripTestSelectors && !this._registeredWithBabel) {
      let checker = new VersionChecker(this).for('ember-cli-babel', 'npm');

      app.options = app.options || {};

      if (checker.satisfies('^5.0.0')) {
        app.options.babel = app.options.babel || {};
        app.options.babel.plugins = app.options.babel.plugins || [];
        app.options.babel.plugins.push(require('./strip-data-test-properties-plugin'));
      } else if (checker.satisfies('^6.0.0-beta.1')) {
        app.options.babel6 = app.options.babel6 || {};
        app.options.babel6.plugins = app.options.babel6.plugins || [];
        app.options.babel6.plugins.push(require('./strip-data-test-properties-plugin6'));
      } else {
        this.ui.writeWarnLine('ember-test-selectors: You are using an unsupported ember-cli-babel version. data-test ' +
          'properties are not automatically stripped from your JS code.');
      }

      this._registeredWithBabel = true;
    }

    if (!this._stripTestSelectors) {
      app.import('vendor/ember-test-selectors/patch-component.js');
    }
  },

  treeForAddon() {
    // remove our "addon" folder from the build if we're stripping test selectors
    if (!this._stripTestSelectors) {
      return this._super.treeForAddon.apply(this, arguments);
    }
  },

  preprocessTree(type, tree) {
    // remove the unit tests if we're testing ourself and are in strip mode.
    // we do this because these tests depend on the "addon" and "app" folders being available,
    // which is not the case if they are stripped out of the build.
    if (type === 'test' && this._stripTestSelectors && this.project.name() === 'ember-test-selectors') {
      tree = require('broccoli-stew').rm(tree, 'dummy/tests/unit/**/*.js');
    }
    return tree;
  },

  _ensureFindHost() {
    if (!this._findHost) {
      this._findHost = function findHostShim() {
        let current = this;
        let app;
        do {
          app = current.app || app;
        } while (current.parent.parent && (current = current.parent));
        return app;
      };
    }
  },
};
<|endoftext|>


<commit_before>//var display = require("../util/display");
// var eb = require("../eventBus");
var template = require('../tmpl/conversationStats');
var PolisModelView = require("../lib/PolisModelView");
// var Utils = require("../util/utils");
// var Constants = require("../util/constants");

// var isIE8 = Utils.isIE8();

module.exports =  PolisModelView.extend({
  name: "conversationStatsView",
  template: template,
  events: {
  },
  context: function() {
    var ctx = PolisModelView.prototype.context.apply(this, arguments);
    return ctx;
  },
  renderParticipantGraph: function(data, color) {
    var vis = d3.select("#ptptCountsVis");
    var w = 1000;
    var h = 200;
    var margins = {
      top: 20,
      right: 20,
      bottom: 20,
      left: 50
    };
    var strokeWidth = 2;
    var ptpts = data;
    var first = ptpts[0];
    var last = ptpts[ptpts.length-1];
    var xScale = d3.time.scale()
      .range([margins.left, w - margins.right])
      .domain([first.created, last.created]);

    var yScale = d3.scale.linear()
      .range([h - margins.top, margins.bottom])
      .domain([ptpts[0].count, ptpts[ptpts.length-1].count]);

    var xAxis = d3.svg.axis()
      .scale(xScale)
      .orient("bottom")
      .tickSize(-h, 0)
      .tickPadding(6);

    var yAxis = d3.svg.axis()
      .scale(yScale)
      .tickSize(-w, 0)
      .tickPadding(6)
      .orient("left");

    vis.append("clipPath")
        .attr("id", "clip")
      .append("rect")
        .attr("x", xScale(first.created) - strokeWidth)
        // .attr("y", yScale(1))
        .attr("width", w)
        .attr("height", h);

    vis.append("g")
      .classed("x", true)
      .classed("axis", true)
      .attr("transform", "translate(0," + (h - margins.bottom) + ")");

    vis.append("svg:g")
      .classed("y", true)
      .classed("axis", true)
      .attr("transform", "translate(" + (margins.left) + ",0)");

    var lineGen = d3.svg.line()
      .x(function(d) {
        return xScale(d.created);
      })
      .y(function(d) {
        return yScale(d.count);
      });

// var line = d3.svg.line()
//     .interpolate("step-after")
//     .x(function(d) { return x(d.date); })
//     .y(function(d) { return y(d.value); });

    vis.append('path')
      .classed('line', true)
      .attr("clip-path", "url(#clip)")
      .attr('stroke', color)
      .attr('stroke-width', strokeWidth)
      .attr('fill', 'none');

    vis.select('path.line').data([ptpts]);

    var zoom = d3.behavior.zoom()
      .on("zoom", draw);
    zoom.x(xScale);

    vis.append("rect")
      .attr("class", "pane")
      .attr("width", w)
      .attr("height", h)
      .style("cursor", "move")
      .style("fill", "rgba(0,0,0,0)")
      .style("pointer-events", "all")
      .call(zoom);

    function draw() {
      vis.select("g.x.axis").call(xAxis);
      vis.select("g.y.axis").call(yAxis);
      // vis.select("path.area").attr("d", area);
      vis.select("path.line").attr("d", lineGen);
    }

    draw();

  },
  checkForLatestStats: function() {
    var that = this;
    $.get("/api/v3/conversationStats?conversation_id=" + this.model.get("conversation_id")).then(function(stats) {

      // loop over each array, and create objects like {count: ++i, created}, then create a line plot with count as y, and created as x
      var keys = _.keys(stats);
      keys = [keys[0]]; // TODO remove
      _.each(keys, function(key) {
        var vals = stats[key];
        var i = 1;
        var data = _.map(vals, function(created) {
          return {
            count: i++,
            created: created
          };
        });
        var now = _.extend({}, data[data.length-1]);
        now.created = Date.now()+0; // straight line to current time
        data.push(now);
        that.model.set(key, data);

        that.renderParticipantGraph(data, "black");
      });

    }, function(error) {
      console.warn("error fetching stats");
    });
  },
  initialize: function(options) {
    Handlebones.View.prototype.initialize.apply(this, arguments);
    var that = this;

    setInterval(function() {
      that.checkForLatestStats();
    }, 30*1000);
    this.checkForLatestStats();

  } // end initialize
});<commit_msg>prevent polling for stats when not visible<commit_after>//var display = require("../util/display");
// var eb = require("../eventBus");
var template = require('../tmpl/conversationStats');
var PolisModelView = require("../lib/PolisModelView");
var Utils = require("../util/utils");
// var Constants = require("../util/constants");

// var isIE8 = Utils.isIE8();

module.exports =  PolisModelView.extend({
  name: "conversationStatsView",
  template: template,
  events: {
  },
  context: function() {
    var ctx = PolisModelView.prototype.context.apply(this, arguments);
    return ctx;
  },
  renderParticipantGraph: function(data, color) {
    var vis = d3.select("#ptptCountsVis");
    var w = 1000;
    var h = 200;
    var margins = {
      top: 20,
      right: 20,
      bottom: 20,
      left: 50
    };
    var strokeWidth = 2;
    var ptpts = data;
    var first = ptpts[0];
    var last = ptpts[ptpts.length-1];
    var xScale = d3.time.scale()
      .range([margins.left, w - margins.right])
      .domain([first.created, last.created]);

    var yScale = d3.scale.linear()
      .range([h - margins.top, margins.bottom])
      .domain([ptpts[0].count, ptpts[ptpts.length-1].count]);

    var xAxis = d3.svg.axis()
      .scale(xScale)
      .orient("bottom")
      .tickSize(-h, 0)
      .tickPadding(6);

    var yAxis = d3.svg.axis()
      .scale(yScale)
      .tickSize(-w, 0)
      .tickPadding(6)
      .orient("left");

    vis.append("clipPath")
        .attr("id", "clip")
      .append("rect")
        .attr("x", xScale(first.created) - strokeWidth)
        // .attr("y", yScale(1))
        .attr("width", w)
        .attr("height", h);

    vis.append("g")
      .classed("x", true)
      .classed("axis", true)
      .attr("transform", "translate(0," + (h - margins.bottom) + ")");

    vis.append("svg:g")
      .classed("y", true)
      .classed("axis", true)
      .attr("transform", "translate(" + (margins.left) + ",0)");

    var lineGen = d3.svg.line()
      .x(function(d) {
        return xScale(d.created);
      })
      .y(function(d) {
        return yScale(d.count);
      });

// var line = d3.svg.line()
//     .interpolate("step-after")
//     .x(function(d) { return x(d.date); })
//     .y(function(d) { return y(d.value); });

    vis.append('path')
      .classed('line', true)
      .attr("clip-path", "url(#clip)")
      .attr('stroke', color)
      .attr('stroke-width', strokeWidth)
      .attr('fill', 'none');

    vis.select('path.line').data([ptpts]);

    var zoom = d3.behavior.zoom()
      .on("zoom", draw);
    zoom.x(xScale);

    vis.append("rect")
      .attr("class", "pane")
      .attr("width", w)
      .attr("height", h)
      .style("cursor", "move")
      .style("fill", "rgba(0,0,0,0)")
      .style("pointer-events", "all")
      .call(zoom);

    function draw() {
      vis.select("g.x.axis").call(xAxis);
      vis.select("g.y.axis").call(yAxis);
      // vis.select("path.area").attr("d", area);
      vis.select("path.line").attr("d", lineGen);
    }

    draw();

  },
  checkForLatestStats: function() {
    var that = this;
    $.get("/api/v3/conversationStats?conversation_id=" + this.model.get("conversation_id")).then(function(stats) {

      // loop over each array, and create objects like {count: ++i, created}, then create a line plot with count as y, and created as x
      var keys = _.keys(stats);
      keys = [keys[0]]; // TODO remove
      _.each(keys, function(key) {
        var vals = stats[key];
        var i = 1;
        var data = _.map(vals, function(created) {
          return {
            count: i++,
            created: created
          };
        });
        var now = _.extend({}, data[data.length-1]);
        now.created = Date.now()+0; // straight line to current time
        data.push(now);
        that.model.set(key, data);

        that.renderParticipantGraph(data, "black");
      });

    }, function(error) {
      console.warn("error fetching stats");
    });
  },
  initialize: function(options) {
    Handlebones.View.prototype.initialize.apply(this, arguments);
    var that = this;

    setInterval(function() {
      if (!Utils.isHidden()) {
        that.checkForLatestStats();
      }
    }, 60*1000);
    this.checkForLatestStats();

  } // end initialize
});<|endoftext|>


<commit_before>'use strict';

const isFirefoxAndroid = require('is-firefox-android')();
const handleClick = require('./lib/handle-click');
const { PageMod } = require('sdk/page-mod');
const tabs = require('sdk/tabs');
const data = require('sdk/self').data;
const getWindow = require('get-firefox-browser-window');
const { EventTarget } = require('sdk/event/target');
const { Request } = require('sdk/request');
const { emit } = require('sdk/event/core');
const simpleStorage = require('sdk/simple-storage');
const isNumber = require('lodash.isnumber');
const buildHatenaBookmarkJsonLiteUrl = require('./lib/build-hatena-bookmark-json-lite-url');
const target = EventTarget();// eslint-disable-line new-cap
let button;
let menuId;
let page;
let currentUrl;// eslint-disable-line no-unused-vars

/**
  * bookmarks
  * { url -> { updatedAt: time, count: number }}
  */
if (!simpleStorage.storage.bookmarks) {
  simpleStorage.storage.bookmarks = {};
}

target.on('updateBadge', (url, piece) => {
  if (url !== currentUrl) { return; }
  if (isFirefoxAndroid) {
    getWindow().NativeWindow.menu.update(
      menuId,
      {
        name: `Page for Hatebu (${piece})`,
      });
  } else {
    button.badge = piece;
  }
});

function cachedCount(bookmarks, url) {
  if (!bookmarks ||
      !url ||
      !bookmarks[url] ||
      !bookmarks[url].updatedAt ||
      bookmarks[url].updatedAt + 10 * 60 * 1000 < Date.now ||
      !isNumber(bookmarks[url].count)
  ) {
    return null;
  }
  return bookmarks[url].count;
}

target.on('pingUrl', (url) => {
  if (!url || !(/^http/.test(url))) { return; }
  const cached = cachedCount(simpleStorage.storage.bookmarks, url);
  if (isNumber(cached)) {
    emit(target, 'updateBadge', url, cached);
  } else {
    emit(target, 'updateBadge', url, '-');
    Request({// eslint-disable-line new-cap
      url: buildHatenaBookmarkJsonLiteUrl(url),
      onComplete: (response) => {
        if (response.status !== 200 || !response.json) { return; }
        const count = response.json.count;
        simpleStorage.storage.bookmarks[url] = {
          count,
          updatedAt: Date.now(),
        };
        emit(target, 'updateBadge', url, count);
      },
    }).get();
  }
});

if (isFirefoxAndroid) {
  menuId = 0;
  exports.main = (options, callback) => {// eslint-disable-line no-unused-vars
    menuId = getWindow().NativeWindow.menu.add({
      name: 'Page for Hatebu (-)',
      callback: handleClick,
    });
  };
  exports.onUnload = (reason) => {// eslint-disable-line no-unused-vars
    getWindow().NativeWindow.menu.remove(menuId);
  };
} else {
  const { ActionButton } = require('sdk/ui/button/action');
  button = ActionButton({// eslint-disable-line new-cap
    id: 'page-for-hatena-bookmark',
    label: 'Page for Hatebu',
    icon: {
      16: './bookmark42-16.png',
      32: './bookmark42-32.png',
      64: './bookmark42-64.png',
    },
    onClick: handleClick,
    badge: '-',
    badgeColor: '#696969',
  });
}

page = PageMod({// eslint-disable-line new-cap
  include: '*',
  contentScriptFile: [
    data.url('../node_modules/browser-canonical-url/build/browser-canonical-url.js'),
    data.url('content-script.js'),
  ],
  attachTo: ['existing', 'top'],
});

page.on('attach', (worker) => {
  worker.port.on('canonicalUrl', (request) => {
    currentUrl = request;
    emit(target, 'pingUrl', request);
  });
  worker.port.emit('getCanonicalUrl');
});

tabs.on('activate', (tab) => {
  const worker = tab.attach({
    contentScriptFile: [
      data.url('../node_modules/browser-canonical-url/build/browser-canonical-url.js'),
      data.url('content-script.js'),
    ],
  });
  worker.port.on('canonicalUrl', (request) => {
    currentUrl = request;
    emit(target, 'pingUrl', request);
  });
  worker.port.emit('getCanonicalUrl');
});
<commit_msg>chore(storage): convert to number before save<commit_after>'use strict';

const isFirefoxAndroid = require('is-firefox-android')();
const handleClick = require('./lib/handle-click');
const { PageMod } = require('sdk/page-mod');
const tabs = require('sdk/tabs');
const data = require('sdk/self').data;
const getWindow = require('get-firefox-browser-window');
const { EventTarget } = require('sdk/event/target');
const { Request } = require('sdk/request');
const { emit } = require('sdk/event/core');
const simpleStorage = require('sdk/simple-storage');
const isNumber = require('lodash.isnumber');
const buildHatenaBookmarkJsonLiteUrl = require('./lib/build-hatena-bookmark-json-lite-url');
const target = EventTarget();// eslint-disable-line new-cap
let button;
let menuId;
let page;
let currentUrl;// eslint-disable-line no-unused-vars

/**
  * bookmarks
  * { url -> { updatedAt: time, count: number }}
  */
if (!simpleStorage.storage.bookmarks) {
  simpleStorage.storage.bookmarks = {};
}

target.on('updateBadge', (url, piece) => {
  if (url !== currentUrl) { return; }
  if (isFirefoxAndroid) {
    getWindow().NativeWindow.menu.update(
      menuId,
      {
        name: `Page for Hatebu (${piece})`,
      });
  } else {
    button.badge = piece;
  }
});

function cachedCount(bookmarks, url) {
  if (!bookmarks ||
      !url ||
      !bookmarks[url] ||
      !bookmarks[url].updatedAt ||
      bookmarks[url].updatedAt + 10 * 60 * 1000 < Date.now ||
      !isNumber(bookmarks[url].count)
  ) {
    return null;
  }
  return bookmarks[url].count;
}

target.on('pingUrl', (url) => {
  if (!url || !(/^http/.test(url))) { return; }
  const cached = cachedCount(simpleStorage.storage.bookmarks, url);
  if (isNumber(cached)) {
    emit(target, 'updateBadge', url, cached);
  } else {
    emit(target, 'updateBadge', url, '-');
    Request({// eslint-disable-line new-cap
      url: buildHatenaBookmarkJsonLiteUrl(url),
      onComplete: (response) => {
        if (response.status !== 200 || !response.json) { return; }
        const count = Number(response.json.count);
        simpleStorage.storage.bookmarks[url] = {
          count,
          updatedAt: Date.now(),
        };
        emit(target, 'updateBadge', url, count);
      },
    }).get();
  }
});

if (isFirefoxAndroid) {
  menuId = 0;
  exports.main = (options, callback) => {// eslint-disable-line no-unused-vars
    menuId = getWindow().NativeWindow.menu.add({
      name: 'Page for Hatebu (-)',
      callback: handleClick,
    });
  };
  exports.onUnload = (reason) => {// eslint-disable-line no-unused-vars
    getWindow().NativeWindow.menu.remove(menuId);
  };
} else {
  const { ActionButton } = require('sdk/ui/button/action');
  button = ActionButton({// eslint-disable-line new-cap
    id: 'page-for-hatena-bookmark',
    label: 'Page for Hatebu',
    icon: {
      16: './bookmark42-16.png',
      32: './bookmark42-32.png',
      64: './bookmark42-64.png',
    },
    onClick: handleClick,
    badge: '-',
    badgeColor: '#696969',
  });
}

page = PageMod({// eslint-disable-line new-cap
  include: '*',
  contentScriptFile: [
    data.url('../node_modules/browser-canonical-url/build/browser-canonical-url.js'),
    data.url('content-script.js'),
  ],
  attachTo: ['existing', 'top'],
});

page.on('attach', (worker) => {
  worker.port.on('canonicalUrl', (request) => {
    currentUrl = request;
    emit(target, 'pingUrl', request);
  });
  worker.port.emit('getCanonicalUrl');
});

tabs.on('activate', (tab) => {
  const worker = tab.attach({
    contentScriptFile: [
      data.url('../node_modules/browser-canonical-url/build/browser-canonical-url.js'),
      data.url('content-script.js'),
    ],
  });
  worker.port.on('canonicalUrl', (request) => {
    currentUrl = request;
    emit(target, 'pingUrl', request);
  });
  worker.port.emit('getCanonicalUrl');
});
<|endoftext|>