<commit_before>const gulp   = require('gulp');
const sass   = require('gulp-sass');
const react  = require('gulp-react');
const concat = require('gulp-concat');
const ts     = require('gulp-typescript');
const babel  = require('gulp-babel');

var watching = false;

function onError(err) {
    console.log(err.toString());
    if (watching) {
        this.emit('end');
    } else {
        process.exit(1);
    }
}

var options = {
    react: {
        source: 'views/*.js',
        target: 'compiled/views',
        config: { stage: 0 }
    },
    typeScript: {
        source: 'src/**/*.ts',
        target: 'compiled',
        config: ts.createProject({
            typescript: require('typescript'),
            target: 'ES5',
            module: 'commonjs',
            noImplicitAny: true,
            removeComments: true,
            preserveConstEnums: true,
            sourceMap: true,
            outDir: 'compiled'
        })
    },
    sass: {
        source: ['stylesheets/*.scss', 'decorators/*.scss'],
        target: {
            directory: 'compiled',
            fileName: 'all.css'
        },
        config: {
            errLogToConsole: true
        }
    }
};

gulp.task('typescript', function () {
    return gulp.src(options.typeScript.source)
               .pipe(ts(options.typeScript.config).on("error", onError))
               .pipe(gulp.dest(options.typeScript.target));
});

gulp.task('sass', function () {
    return gulp.src(options.sass.source)
               .pipe(sass(options.sass.config).on("error", onError))
               .pipe(concat(options.sass.target.fileName))
               .pipe(gulp.dest(options.sass.target.directory));
});

gulp.task('react', function () {
    return gulp.src(options.react.source)
               .pipe(babel(options.react.config).on("error", onError))
               .pipe(react().on("error", onError))
               .pipe(gulp.dest(options.react.target));
});

gulp.task('watch', ['default'], function () {
    watching = true;
    gulp.watch(options.sass.source, ['sass']);
    gulp.watch(options.react.source, ['react']);
    gulp.watch(options.typeScript.source, ['typescript']);
});

gulp.task('default', ['typescript', 'sass', 'react']);
<commit_msg>Add a todo.<commit_after>//TODO: Use gulp 4.
const gulp   = require('gulp');
const sass   = require('gulp-sass');
const react  = require('gulp-react');
const concat = require('gulp-concat');
const ts     = require('gulp-typescript');
const babel  = require('gulp-babel');

var watching = false;

function onError(err) {
    console.log(err.toString());
    if (watching) {
        this.emit('end');
    } else {
        process.exit(1);
    }
}

var options = {
    react: {
        source: 'views/*.js',
        target: 'compiled/views',
        config: { stage: 0 }
    },
    typeScript: {
        source: 'src/**/*.ts',
        target: 'compiled',
        config: ts.createProject({
            typescript: require('typescript'),
            target: 'ES5',
            module: 'commonjs',
            noImplicitAny: true,
            removeComments: true,
            preserveConstEnums: true,
            sourceMap: true,
            outDir: 'compiled'
        })
    },
    sass: {
        source: ['stylesheets/*.scss', 'decorators/*.scss'],
        target: {
            directory: 'compiled',
            fileName: 'all.css'
        },
        config: {
            errLogToConsole: true
        }
    }
};

gulp.task('typescript', function () {
    return gulp.src(options.typeScript.source)
               .pipe(ts(options.typeScript.config).on("error", onError))
               .pipe(gulp.dest(options.typeScript.target));
});

gulp.task('sass', function () {
    return gulp.src(options.sass.source)
               .pipe(sass(options.sass.config).on("error", onError))
               .pipe(concat(options.sass.target.fileName))
               .pipe(gulp.dest(options.sass.target.directory));
});

gulp.task('react', function () {
    return gulp.src(options.react.source)
               .pipe(babel(options.react.config).on("error", onError))
               .pipe(react().on("error", onError))
               .pipe(gulp.dest(options.react.target));
});

gulp.task('watch', ['default'], function () {
    watching = true;
    gulp.watch(options.sass.source, ['sass']);
    gulp.watch(options.react.source, ['react']);
    gulp.watch(options.typeScript.source, ['typescript']);
});

gulp.task('default', ['typescript', 'sass', 'react']);
<|endoftext|>


<commit_before>  define(
  'ephox.robin.anteater.Anteater',

  [
    'ephox.compass.Arr',
    'ephox.peanut.Fun',
    'ephox.perhaps.Option',
    'ephox.robin.api.general.Parent',
    'ephox.robin.parent.Subset'
  ],

  function (Arr, Fun, Option, Parent, Subset) {
    // Find the subsection of DIRECT children of parent from [first, last])
    var slice = function (universe, parent, first, last) {
      var children = universe.property().children(parent);

      var finder = function (elem) {
        var index = Arr.findIndex(children, Fun.curry(universe.eq, elem));
        return index > -1 ? Option.some(index) : Option.none();
      };

      // Default to the start of the common parent.
      var firstIndex = first.bind(finder).getOr(0);
      // Default to the end of the common parent.
      var lastIndex = last.bind(finder).getOr(children.length - 1);
      return firstIndex > -1 && lastIndex > -1 ? Option.some(children.slice(firstIndex, lastIndex + 1)) : Option.none();
    };

    var breakPath = function (universe, element, common) {
      var isTop = function (elem) {
        return universe.property().parent(elem).fold(
          Fun.constant(true),
          Fun.curry(universe.eq, common)
        );
      };

      return Parent.breakPath(universe, element, isTop, Parent.breakAt);
    };

    // Break from the first node to the common parent AFTER the second break as the first
    // will impact the second (assuming LEFT to RIGHT) and not vice versa.
    var breakLeft = function (universe, element, common) {
      // If we are the top and we are the left, use default value
      if (universe.eq(common, element)) return Option.none();
      else {
        var breakage = breakPath(universe, element, common);
        // Move the first element into the second section of the split because we want to include element in the formatting.
        if (breakage.splits().length > 0) universe.insert().prepend(breakage.splits()[0].second(), element);
        return Option.some(breakage.second().getOr(element));
      }
    };

    var breakRight = function (universe, element, common) {
      // If we are the top and we are the right, use default value
      if (universe.eq(common, element)) return Option.none();
      else {
        var breakage = breakPath(universe, element, common);
        return Option.some(breakage.first());
      }
    };

    var fossil = function (universe, isRoot, start, finish) {
      if (universe.eq(start, finish)) {
        var children = universe.property().parent(start).fold(Fun.constant([]), function (parent) {
          return universe.property().children(parent);
        });

        var index = Arr.findIndex(children, Fun.curry(universe.eq, start));
        console.log('index: ', children.slice(index, index + 1));
        if (index > -1) return Option.some(children.slice(index, index + 1));
        else return Option.none();
      }

      var subset = Subset.ancestors(universe, start, finish, isRoot);
      var shared = subset.shared().fold(function () {
        return Parent.sharedOne(universe, function (_, elem) {
          return isRoot(elem) ? Option.some(elem) : universe.up().predicate(elem, isRoot);
        }, [ start, finish ]);
      }, function (sh) {
        return Option.some(sh);
      });

      return shared.bind(function (common) {
        // We have the shared parent, we now have to split from the start and finish up
        // to the shared parent.

        var secondBreak = breakRight(universe, finish, common);
        var firstBreak = breakLeft(universe, start, common);
        return slice(universe, common, firstBreak, secondBreak);
      });
    };

    return {
      fossil: fossil
    };
  }
);<commit_msg>TBIO-1766: same vs. diff<commit_after>  define(
  'ephox.robin.anteater.Anteater',

  [
    'ephox.compass.Arr',
    'ephox.peanut.Fun',
    'ephox.perhaps.Option',
    'ephox.robin.api.general.Parent',
    'ephox.robin.parent.Subset'
  ],

  function (Arr, Fun, Option, Parent, Subset) {
    // Find the subsection of DIRECT children of parent from [first, last])
    var slice = function (universe, parent, first, last) {
      var children = universe.property().children(parent);

      var finder = function (elem) {
        var index = Arr.findIndex(children, Fun.curry(universe.eq, elem));
        return index > -1 ? Option.some(index) : Option.none();
      };

      // Default to the start of the common parent.
      var firstIndex = first.bind(finder).getOr(0);
      // Default to the end of the common parent.
      var lastIndex = last.bind(finder).getOr(children.length - 1);
      return firstIndex > -1 && lastIndex > -1 ? Option.some(children.slice(firstIndex, lastIndex + 1)) : Option.none();
    };

    var breakPath = function (universe, element, common) {
      var isTop = function (elem) {
        return universe.property().parent(elem).fold(
          Fun.constant(true),
          Fun.curry(universe.eq, common)
        );
      };

      return Parent.breakPath(universe, element, isTop, Parent.breakAt);
    };

    var breakLeft = function (universe, element, common) {
      // If we are the top and we are the left, use default value
      if (universe.eq(common, element)) return Option.none();
      else {
        var breakage = breakPath(universe, element, common);
        // Move the first element into the second section of the split because we want to include element in the section.
        if (breakage.splits().length > 0) universe.insert().prepend(breakage.splits()[0].second(), element);
        return Option.some(breakage.second().getOr(element));
      }
    };

    var breakRight = function (universe, element, common) {
      // If we are the top and we are the right, use default value
      if (universe.eq(common, element)) return Option.none();
      else {
        var breakage = breakPath(universe, element, common);
        return Option.some(breakage.first());
      }
    };

    var same = function (universe, isRoot, element) {
      var children = universe.property().parent(element).fold(Fun.constant([]), function (parent) {
        return universe.property().children(parent);
      });

      var index = Arr.findIndex(children, Fun.curry(universe.eq, element));
      if (index > -1) return Option.some(children.slice(index, index + 1));
      else return Option.none();
    };

    var diff = function (universe, isRoot, start, finish) {
      var subset = Subset.ancestors(universe, start, finish, isRoot);
      var shared = subset.shared().fold(function () {
        return Parent.sharedOne(universe, function (_, elem) {
          return isRoot(elem) ? Option.some(elem) : universe.up().predicate(elem, isRoot);
        }, [ start, finish ]);
      }, function (sh) {
        return Option.some(sh);
      });

      return shared.bind(function (common) {
        // We have the shared parent, we now have to split from the start and finish up
        // to the shared parent.

        // Break from the first node to the common parent AFTER the second break as the first
        // will impact the second (assuming LEFT to RIGHT) and not vice versa.
        var secondBreak = breakRight(universe, finish, common);
        var firstBreak = breakLeft(universe, start, common);
        return slice(universe, common, firstBreak, secondBreak);
      });
    };

    var fossil = function (universe, isRoot, start, finish) {
      return universe.eq(start, finish) ? same(universe, isRoot, start) : diff(universe, isRoot, start, finish);
    };

    return {
      fossil: fossil
    };
  }
);<|endoftext|>


<commit_before>require('colors');

function log() {
    console.log.apply(null, arguments);
}

var levels = {
    debug: 'grey',
    info: 'blue',
    error: 'red'
};

Object.keys(levels).forEach(function (level) {
    var color = levels[level];
    exports[level] = function () {
        var args = Array.prototype.slice.call(arguments, 0);
        args.unshift(level[color]);
        log.apply(null, args);
    };
});

var logger = {
    log: function (level, id, message) {
        log(level, id, message);
    },
    info: function (id, message, data) {
        this.progress(id, message, data);
    },
    action: function (id, message, data) {
        this.progress(id, message, data);
    },
    progress: function (id, message) {
        var gitParts = message.match(/git:\/\/github.com\/.*\/(.*).git/);
        if(gitParts && gitParts.length > 1) {
            message = gitParts[1];
        }
        var targetParts = message.match(/(.*)#.*/);
        if(targetParts && targetParts.length > 1) {
            message = targetParts[1];
        }

        this.running[message] = this.running[message] || [];
        this.running[message].push(id);
        if (this.stream.isTTY) {
            this.render();
        } else {
            console.log(id, '>'.bold, message);
        }
    },
    render: function () {
        var str = "", nbLines = 0;
        for (var lib in this.running) {
            str += lib + ' - ' + this.running[lib].join(' > ') + '\n';
            nbLines++;
        }
        this.stream.cursorTo(0);
        this.stream.moveCursor(0, -this.progressNbLines || 0);
        this.stream.clearScreenDown();
        this.stream.write(str);
        this.progressNbLines = nbLines;
    },
    geminate: function () {
        return this;
    },
    intercept: function () {}
};

logger.stream = process.stdout;
logger.running = {};

exports.getBowerLogger = function () {
    return logger;
};
<commit_msg>make separators in bold<commit_after>require('colors');

function log() {
    console.log.apply(null, arguments);
}

var levels = {
    debug: 'grey',
    info: 'blue',
    error: 'red'
};

Object.keys(levels).forEach(function (level) {
    var color = levels[level];
    exports[level] = function () {
        var args = Array.prototype.slice.call(arguments, 0);
        args.unshift(level[color]);
        log.apply(null, args);
    };
});

var logger = {
    log: function (level, id, message) {
        log(level, id, message);
    },
    info: function (id, message, data) {
        this.progress(id, message, data);
    },
    action: function (id, message, data) {
        this.progress(id, message, data);
    },
    progress: function (id, message) {
        var gitParts = message.match(/git:\/\/github.com\/.*\/(.*).git/);
        if(gitParts && gitParts.length > 1) {
            message = gitParts[1];
        }
        var targetParts = message.match(/(.*)#.*/);
        if(targetParts && targetParts.length > 1) {
            message = targetParts[1];
        }

        this.running[message] = this.running[message] || [];
        this.running[message].push(id);
        if (this.stream.isTTY) {
            this.render();
        } else {
            console.log(id, '>'.bold, message);
        }
    },
    render: function () {
        var str = "", nbLines = 0;
        for (var lib in this.running) {
            str += lib + ' - ' + this.running[lib].join(' > '.bold) + '\n';
            nbLines++;
        }
        this.stream.cursorTo(0);
        this.stream.moveCursor(0, -this.progressNbLines || 0);
        this.stream.clearScreenDown();
        this.stream.write(str);
        this.progressNbLines = nbLines;
    },
    geminate: function () {
        return this;
    },
    intercept: function () {}
};

logger.stream = process.stdout;
logger.running = {};

exports.getBowerLogger = function () {
    return logger;
};
<|endoftext|>


<commit_before>
var categorySlug = "all";
var places;

var rowHandle = function(evt){
    // Check for all of the possible names that clicksouce
    // can report for the left button/view.

    var placePage = Alloy.createController('place');
    var placemark = evt.rowData.placemark;
    placePage.setPlace( placemark );
	$.win.navGroup.open(placePage.getView());
};

exports.setSlug = function( newCategory ){
	categorySlug = newCategory;
}

exports.setPlaces = function( nplaces ){
	places = nplaces;
}

$.placeTable.setFooterView( Alloy.createController('footerRow', {
	title : 'Powered By: ',
	image : "images/placeling-logo.png"
}).getView() );

$.placeTable.addEventListener('click', rowHandle);

var mapButton = Titanium.UI.createButton({title:"Map"});
$.win.rightNavButton = mapButton;

mapButton.addEventListener('click', function(e){
	Ti.API.info("clicked on Map");
	var mapController = Alloy.createController('map');
	mapController.setPlaces( places );
	mapController.getView().navGroup = $.win.navGroup;
	$.win.navGroup.open( mapController.getView() );
});

function myLoaderCallback(widgetCallback) {
    // DO YOUR LOADING
    loadPlaces();
    widgetCallback(true);
}

function loadPlaces(){

	Titanium.Geolocation.getCurrentPosition(function(e) {
	    if (e.error) {
	        alert('HFL cannot get your current location');
	        return;
	    }

	    var longitude = e.coords.longitude;
	    var latitude = e.coords.latitude;
	    var altitude = e.coords.altitude;
	    var heading = e.coords.heading;
	    var accuracy = e.coords.accuracy;
	    var speed = e.coords.speed;
	    var timestamp = e.coords.timestamp;
	    var altitudeAccuracy = e.coords.altitudeAccuracy;

		var url = Alloy.CFG.serverUrl + "/publishers/" + Alloy.CFG.publisher +  "/publisher_categories/" + categorySlug + "/perspectives.json";

		var xhr = Ti.Network.createHTTPClient({
			onload: function(e) {
				var result = JSON.parse(this.responseText);
				var placemarks = result.perspectives;

				var categoryRaw = result.publisher_category;
				places = placemarks;
				var tableData = [];
				places = placemarks;
				placemarks.forEach( function(placemark) {
					var rowData = {title:placemark.place.name, className:'placeRow', touchEnabled:true, hasDetail:true, placemark: placemark};
					tableData.push( rowData );
				});

				$.placeTable.setData( tableData );

				var collection = Alloy.createCollection("PublisherCategory");
				collection.fetch();

				var categories = collection.where({ slug: categoryRaw.slug});

				var category;
				// open the color info window
				if ( categories[0] ) {
					category = categories[0];
					category.set('lastViewed', new Date());
				} else {
					category = Alloy.createModel('PublisherCategory', {
						name:categoryRaw.name,
						slug:categoryRaw.slug,
						lastViewed:(new Date())
					});
				}
				category.save();

			},
			onerror: function(e) {
				alert("Error:"+JSON.stringify(e));
			},
			timeout: 10000
		});
		xhr.open("GET", url +"?lat="+latitude+"&lng="+longitude);
		xhr.send();

	});
}

$.win.addEventListener('open', function(e){
	loadPlaces();
});

var ptrCtrl = Alloy.createWidget('nl.fokkezb.pullToRefresh');
ptrCtrl.init({
    table: $.placeTable,
    loader: myLoaderCallback
});

<commit_msg>get rid of some old logging<commit_after>
var categorySlug = "all";
var places;

var rowHandle = function(evt){
    // Check for all of the possible names that clicksouce
    // can report for the left button/view.

    var placePage = Alloy.createController('place');
    var placemark = evt.rowData.placemark;
    placePage.setPlace( placemark );
	$.win.navGroup.open(placePage.getView());
};

exports.setSlug = function( newCategory ){
	categorySlug = newCategory;
}

exports.setPlaces = function( nplaces ){
	places = nplaces;
}

$.placeTable.setFooterView( Alloy.createController('footerRow', {
	title : 'Powered By: ',
	image : "images/placeling-logo.png"
}).getView() );

$.placeTable.addEventListener('click', rowHandle);

var mapButton = Titanium.UI.createButton({title:"Map"});
$.win.rightNavButton = mapButton;

mapButton.addEventListener('click', function(e){
	var mapController = Alloy.createController('map');
	mapController.setPlaces( places );
	mapController.getView().navGroup = $.win.navGroup;
	$.win.navGroup.open( mapController.getView() );
});

function myLoaderCallback(widgetCallback) {
    // DO YOUR LOADING
    loadPlaces();
    widgetCallback(true);
}

function loadPlaces(){

	Titanium.Geolocation.getCurrentPosition(function(e) {
	    if (e.error) {
	        alert('HFL cannot get your current location');
	        return;
	    }

	    var longitude = e.coords.longitude;
	    var latitude = e.coords.latitude;
	    var altitude = e.coords.altitude;
	    var heading = e.coords.heading;
	    var accuracy = e.coords.accuracy;
	    var speed = e.coords.speed;
	    var timestamp = e.coords.timestamp;
	    var altitudeAccuracy = e.coords.altitudeAccuracy;

		var url = Alloy.CFG.serverUrl + "/publishers/" + Alloy.CFG.publisher +  "/publisher_categories/" + categorySlug + "/perspectives.json";

		var xhr = Ti.Network.createHTTPClient({
			onload: function(e) {
				var result = JSON.parse(this.responseText);
				var placemarks = result.perspectives;

				var categoryRaw = result.publisher_category;
				places = placemarks;
				var tableData = [];
				places = placemarks;
				placemarks.forEach( function(placemark) {
					var rowData = {title:placemark.place.name, className:'placeRow', touchEnabled:true, hasDetail:true, placemark: placemark};
					tableData.push( rowData );
				});

				$.placeTable.setData( tableData );

				var collection = Alloy.createCollection("PublisherCategory");
				collection.fetch();

				var categories = collection.where({ slug: categoryRaw.slug});

				var category;
				// open the color info window
				if ( categories[0] ) {
					category = categories[0];
					category.set('lastViewed', new Date());
				} else {
					category = Alloy.createModel('PublisherCategory', {
						name:categoryRaw.name,
						slug:categoryRaw.slug,
						lastViewed:(new Date())
					});
				}
				category.save();

			},
			onerror: function(e) {
				alert("Error:"+JSON.stringify(e));
			},
			timeout: 10000
		});
		xhr.open("GET", url +"?lat="+latitude+"&lng="+longitude);
		xhr.send();

	});
}

$.win.addEventListener('open', function(e){
	loadPlaces();
});

var ptrCtrl = Alloy.createWidget('nl.fokkezb.pullToRefresh');
ptrCtrl.init({
    table: $.placeTable,
    loader: myLoaderCallback
});

<|endoftext|>


<commit_before>function FeedbackControl($scope, FeedbackControlService, FeedbackSignal, Template, FeedbackService) {

    var qs = (function(a) {
        if (a == "") return {};
        var b = {};
        for (var i = 0; i < a.length; ++i) {
            var p=a[i].split('=');
            if (p.length != 2) continue;
            b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
        }
        return b;
    })(window.location.search.substr(1).split('&'));

    var is_empty = function(obj) {
        return Object.keys(obj).length === 0;
    }

    var update_selected = function(action, id) {
        if (action == 'add' && $scope.selected.indexOf(id) == -1) {
            $scope.selected.push(id);
        }

        if (action == 'remove' && $scope.selected.indexOf(id) != -1) {
            $scope.selected.splice($scope.selected.indexOf(id), 1);
        }
    }

    var feedback_collect = function(n, mode, collect_type) {
        var me = n;

        var entity = $(".dashboard-feedback[feedback=" + me + "]");
        var entity_parent = entity.parents('.feedback-group');
        var score = entity.attr('score');
        var permission = entity.attr('permission');
        var catid = entity.attr('catid');

        if(
               (score >= 3 && permission == 1)
           || ((score >= 3 && permission == 0) && (mode == 'delete' || mode == 'restore' || mode == 'remove'))
           || ((score == 1 || score == 2) && (mode == 'delete' || mode == 'restore' || mode == 'remove'))
          )  {
            entity.hide();
            var child_count = entity_parent.children('.dashboard-feedback:visible');

            if(child_count.length == 0) {
                entity_parent.hide();
            }

            if(collect_type == 'feedid') {
                return me;
            } else {
                return catid;
            }
        }
    }

    var current_url = window.location.pathname;

    var insert_param = function(key, value) {
        var key = escape(key); value = escape(value);
        var kvp = document.location.search.substr(1).split('&');
        if (kvp == '') {
            var str = '?' + key + '=' + value;
            console.log(str);
            //document.location.search = str;
        } else {
            var i=kvp.length;
            var x;
            while(i--) {
                x = kvp[i].split('=');

                if (x[0]==key) {
                    x[1] = value;
                    kvp[i] = x.join('=');
                    break;
                }
            }

            if (i<0) {
                kvp[kvp.length] = [key,value].join('=');
            }

            console.log(kvp.join('&'));

            //this will reload the page, it's likely better to store this until finished
            //document.location.search = kvp.join('&');
        }
    }

    $scope.selected = [];
    var checkboxes = $(".feed-checkbox");

    $scope.status_select_value = 'none';
    $scope.date_filter     = (!is_empty(qs) && qs['date']) ? qs['date'] : 'none';
    $scope.priority_filter = (!is_empty(qs) && qs['priority']) ? qs['priority'] : 'none';
    $scope.status_filter   = (!is_empty(qs) && qs['status']) ? qs['status'] : 'none';
    $scope.rating_filter   = (!is_empty(qs) && qs['rating']) ? qs['rating'] : 'none';

    $scope.feedback_status = function($event) {
        var target = $($event.target);
        var feed = $.parseJSON(target.attr('data-feed'));

        if(current_url.match(/inbox\/all|deleted/g)) {
            var current = {
                id: feed.id
              , catid: Template.default_category_id
              , status: feed.status
              , origin: Template.current_inbox_state
            }
        }

        if(current_url.match(/published/g)) {
            var current = {
                id: feed.id
              , catid: Template.default_category_id
              , status: feed.status
              , origin: feed.origin
            }
        }

        if(current_url.match(/filed/g)) {
            var current = {
                id: feed.id
              , catid: feed.catid
              , status: feed.status
              , origin: Template.current_inbox_state
            }
            console.log(current);
        }

        if(feed.status != "remove") {
            FeedbackSignal.current_state(current);
            feed.origin = Template.current_inbox_state;
            FeedbackControlService.change_status(feed, true);
        }else {
            if(confirm("Warning! You are about to permanently delete this feedback. There is no undo.")) {
                FeedbackSignal.current_state(current);
                feed.origin = Template.current_inbox_state;
                FeedbackControlService.change_status(feed, true);
            }
        }
    }

    $scope.flag_feedback = function($event) {
        var flag = $($event.target);
        var feed = $.parseJSON(flag.attr('data-feed'));

        var return_policy = flag.attr('return-policy') == true;

        var modfeed = {
            id: feed.id
          , catid: (current_url.match(/filed/g)) ? feed.catid : Template.default_category_id
          , status: (return_policy == true) ? feed.status : 'unflag'
          , origin: Template.current_inbox_state
        }

        FeedbackControlService.flag_feedback(modfeed);
    }

    $scope.update_selection = function($event, id) {
        var checkbox = $event.target;
        var action = (checkbox.checked ? 'add' : 'remove');
        update_selected(action, id);
    }

    $scope.change_value_status = function() {
        if( $('input[type=checkbox].feed-checkbox:checked').length > 0 ) {

            var selected = [];
            var catids = [];
            var ids = $scope.selected;
            var mode = $scope.status_select_value;
            var feed = {};

            if(mode == "remove") {
                if(confirm("Are you sure you want to permanently remove this feedback? There is no undo.")) {
                    for(var i=0; i < ids.length; ++i) {
                        selected.push(feedback_collect(ids[i], mode, 'feedid'));
                        catids.push(feedback_collect(ids[i], mode, 'catid'));
                    }
                } else {
                    $('input[type=checkbox].feed-checkbox:checked, .sorter-checkbox:checked').click();
                }
            } else {
                for(var i=0; i < ids.length; ++i) {
                    selected.push(feedback_collect(ids[i], mode, 'feedid'));
                    catids.push(feedback_collect(ids[i], mode, 'catid'));
                }
            }

            if(selected.length > 0) {
                if(current_url.match(/filed/g)) {
                    var feed = {
                        id: selected
                      , status: $scope.status_select_value
                      , catid:  catids
                      , origin: Template.current_inbox_state
                    }
                } else {
                    var feed = {
                        id: selected
                      , status: $scope.status_select_value
                      , catid: Template.default_category_id
                      , origin: Template.current_inbox_state
                    }
                }

                if(mode == "remove") {
                    FeedbackSignal.current_state(feed);
                    FeedbackControlService.change_status(feed, true);
                } else {
                    FeedbackSignal.current_state(feed);
                    FeedbackControlService.change_status(feed, true);
                }

                $(".checky-box-container").show();

            } else {
                if(mode != "remove") {
                    alert("Action is not allowed!");
                }
            }

            selected = [];
            $scope.selected = [];
            $scope.status_select_value = 'none';

        }
    }

    $scope.select_all = function($event) {

        var checkbox = $event.target;
        var action = (checkbox.checked ? 'add' : 'remove');

        for(var i=0; i < checkboxes.length; i++) {

            var entity = $(checkboxes[i]);
            var myparent = entity.parents('.dashboard-feedback');

            //if action is add then click on checkboxes if not click again to deselect
            if(action == "add") {
                if(!entity.is(":checked")) {
                    entity.click();
                }
            } else {
                entity.click();
            }

            update_selected(action, parseInt(entity.val(), 10));
        }
    }

    $scope.filter = function(filter_type) {
        if(filter_type == 'date') {
            if($scope.date_filter == 'none') {
                window.location = window.location.pathname;
            } else {
                insert_param('date', $scope.date_filter);
            }
        }

        if(filter_type == 'priority') {
            if($scope.priority_filter == 'none') {
                window.location = window.location.pathname;
            } else {
                insert_param('priority', $scope.priority_filter);
            }
        }

        if(filter_type == 'status') {
            if($scope.status_filter == 'none') {
                window.location = window.location.pathname;
            } else {
                insert_param('status', $scope.status_filter);
            }
        }

        if(filter_type == 'rating') {
            if($scope.rating_filter == 'none') {
                window.location = window.location.pathname;
            } else {
                insert_param('rating', $scope.rating_filter);
            }
        }
    }

    $scope.fast_forward = function(email, feedid) {
        FeedbackService.send_fastforward(email, feedid);
    }

    $scope.$on('expungeFeedId', function() {
        FeedbackSignal.data.id = [];
        $scope.selected = [];
    })
}

function CheckyBox($scope, FeedbackSignal, FeedbackControlService) {

    $scope.status_selection;
    $scope.id;
    $scope.data;

    $scope.undo = function() {
        FeedbackControlService.change_status($scope.data);
    }

    $scope.close = function() {
        location.reload();
    }

    $scope.$on('checkFeedbackStatus', function() {
        $scope.status_selection = FeedbackSignal.data.status;
        $scope.id = FeedbackSignal.data.id;
        $scope.data = FeedbackSignal.data;
    });
}
<commit_msg>shityes<commit_after>function FeedbackControl($scope, FeedbackControlService, FeedbackSignal, Template, FeedbackService) {

    var qs = (function(a) {
        if (a == "") return {};
        var b = {};
        for (var i = 0; i < a.length; ++i) {
            var p=a[i].split('=');
            if (p.length != 2) continue;
            b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
        }
        return b;
    })(window.location.search.substr(1).split('&'));

    var is_empty = function(obj) {
        return Object.keys(obj).length === 0;
    }

    var update_selected = function(action, id) {
        if (action == 'add' && $scope.selected.indexOf(id) == -1) {
            $scope.selected.push(id);
        }

        if (action == 'remove' && $scope.selected.indexOf(id) != -1) {
            $scope.selected.splice($scope.selected.indexOf(id), 1);
        }
    }

    var feedback_collect = function(n, mode, collect_type) {
        var me = n;

        var entity = $(".dashboard-feedback[feedback=" + me + "]");
        var entity_parent = entity.parents('.feedback-group');
        var score = entity.attr('score');
        var permission = entity.attr('permission');
        var catid = entity.attr('catid');

        if(
               (score >= 3 && permission == 1)
           || ((score >= 3 && permission == 0) && (mode == 'delete' || mode == 'restore' || mode == 'remove'))
           || ((score == 1 || score == 2) && (mode == 'delete' || mode == 'restore' || mode == 'remove'))
          )  {
            entity.hide();
            var child_count = entity_parent.children('.dashboard-feedback:visible');

            if(child_count.length == 0) {
                entity_parent.hide();
            }

            if(collect_type == 'feedid') {
                return me;
            } else {
                return catid;
            }
        }
    }

    var current_url = window.location.pathname;

    var insert_param = function(key, value) {
        var key = escape(key); value = escape(value);
        var kvp = document.location.search.substr(1).split('&');
        if (kvp == '') {
            var str = '?' + key + '=' + value;
            document.location.search = str;
        } else {
            var i=kvp.length;
            var x;
            while(i--) {
                x = kvp[i].split('=');

                if (x[0]==key) {
                    x[1] = value;
                    kvp[i] = x.join('=');
                    break;
                }
            }

            if (i<0) {
                kvp[kvp.length] = [key,value].join('=');
            }

            //this will reload the page, it's likely better to store this until finished
            document.location.search = kvp.join('&');
        }
    }

    $scope.selected = [];
    var checkboxes = $(".feed-checkbox");

    $scope.status_select_value = 'none';
    $scope.date_filter     = (!is_empty(qs) && qs['date']) ? qs['date'] : 'none';
    $scope.priority_filter = (!is_empty(qs) && qs['priority']) ? qs['priority'] : 'none';
    $scope.status_filter   = (!is_empty(qs) && qs['status']) ? qs['status'] : 'none';
    $scope.rating_filter   = (!is_empty(qs) && qs['rating']) ? qs['rating'] : 'none';

    $scope.feedback_status = function($event) {
        var target = $($event.target);
        var feed = $.parseJSON(target.attr('data-feed'));

        if(current_url.match(/inbox\/all|deleted/g)) {
            var current = {
                id: feed.id
              , catid: Template.default_category_id
              , status: feed.status
              , origin: Template.current_inbox_state
            }
        }

        if(current_url.match(/published/g)) {
            var current = {
                id: feed.id
              , catid: Template.default_category_id
              , status: feed.status
              , origin: feed.origin
            }
        }

        if(current_url.match(/filed/g)) {
            var current = {
                id: feed.id
              , catid: feed.catid
              , status: feed.status
              , origin: Template.current_inbox_state
            }
            console.log(current);
        }

        if(feed.status != "remove") {
            FeedbackSignal.current_state(current);
            feed.origin = Template.current_inbox_state;
            FeedbackControlService.change_status(feed, true);
        }else {
            if(confirm("Warning! You are about to permanently delete this feedback. There is no undo.")) {
                FeedbackSignal.current_state(current);
                feed.origin = Template.current_inbox_state;
                FeedbackControlService.change_status(feed, true);
            }
        }
    }

    $scope.flag_feedback = function($event) {
        var flag = $($event.target);
        var feed = $.parseJSON(flag.attr('data-feed'));

        var return_policy = flag.attr('return-policy') == true;

        var modfeed = {
            id: feed.id
          , catid: (current_url.match(/filed/g)) ? feed.catid : Template.default_category_id
          , status: (return_policy == true) ? feed.status : 'unflag'
          , origin: Template.current_inbox_state
        }

        FeedbackControlService.flag_feedback(modfeed);
    }

    $scope.update_selection = function($event, id) {
        var checkbox = $event.target;
        var action = (checkbox.checked ? 'add' : 'remove');
        update_selected(action, id);
    }

    $scope.change_value_status = function() {
        if( $('input[type=checkbox].feed-checkbox:checked').length > 0 ) {

            var selected = [];
            var catids = [];
            var ids = $scope.selected;
            var mode = $scope.status_select_value;
            var feed = {};

            if(mode == "remove") {
                if(confirm("Are you sure you want to permanently remove this feedback? There is no undo.")) {
                    for(var i=0; i < ids.length; ++i) {
                        selected.push(feedback_collect(ids[i], mode, 'feedid'));
                        catids.push(feedback_collect(ids[i], mode, 'catid'));
                    }
                } else {
                    $('input[type=checkbox].feed-checkbox:checked, .sorter-checkbox:checked').click();
                }
            } else {
                for(var i=0; i < ids.length; ++i) {
                    selected.push(feedback_collect(ids[i], mode, 'feedid'));
                    catids.push(feedback_collect(ids[i], mode, 'catid'));
                }
            }

            if(selected.length > 0) {
                if(current_url.match(/filed/g)) {
                    var feed = {
                        id: selected
                      , status: $scope.status_select_value
                      , catid:  catids
                      , origin: Template.current_inbox_state
                    }
                } else {
                    var feed = {
                        id: selected
                      , status: $scope.status_select_value
                      , catid: Template.default_category_id
                      , origin: Template.current_inbox_state
                    }
                }

                if(mode == "remove") {
                    FeedbackSignal.current_state(feed);
                    FeedbackControlService.change_status(feed, true);
                } else {
                    FeedbackSignal.current_state(feed);
                    FeedbackControlService.change_status(feed, true);
                }

                $(".checky-box-container").show();

            } else {
                if(mode != "remove") {
                    alert("Action is not allowed!");
                }
            }

            selected = [];
            $scope.selected = [];
            $scope.status_select_value = 'none';

        }
    }

    $scope.select_all = function($event) {

        var checkbox = $event.target;
        var action = (checkbox.checked ? 'add' : 'remove');

        for(var i=0; i < checkboxes.length; i++) {

            var entity = $(checkboxes[i]);
            var myparent = entity.parents('.dashboard-feedback');

            //if action is add then click on checkboxes if not click again to deselect
            if(action == "add") {
                if(!entity.is(":checked")) {
                    entity.click();
                }
            } else {
                entity.click();
            }

            update_selected(action, parseInt(entity.val(), 10));
        }
    }

    $scope.filter = function(filter_type) {
        if(filter_type == 'date') {
            insert_param('date', $scope.date_filter);
        }

        if(filter_type == 'priority') {
            insert_param('priority', $scope.priority_filter);
        }

        if(filter_type == 'status') {
            insert_param('status', $scope.status_filter);
        }

        if(filter_type == 'rating') {
            insert_param('rating', $scope.rating_filter);
        }
    }

    $scope.fast_forward = function(email, feedid) {
        FeedbackService.send_fastforward(email, feedid);
    }

    $scope.$on('expungeFeedId', function() {
        FeedbackSignal.data.id = [];
        $scope.selected = [];
    })
}

function CheckyBox($scope, FeedbackSignal, FeedbackControlService) {

    $scope.status_selection;
    $scope.id;
    $scope.data;

    $scope.undo = function() {
        FeedbackControlService.change_status($scope.data);
    }

    $scope.close = function() {
        location.reload();
    }

    $scope.$on('checkFeedbackStatus', function() {
        $scope.status_selection = FeedbackSignal.data.status;
        $scope.id = FeedbackSignal.data.id;
        $scope.data = FeedbackSignal.data;
    });
}
<|endoftext|>


<commit_before>var peopleMgr = require("../../peopleMgr");

var getId = function(object) {
    return object.id;
};

var mapGetId = function (array) {
    return array.map(getId);
};

var suggestions = module.exports = function(text) {
    var regExp = new RegExp(text, "i");
    return peopleMgr.search({
        $or : [ {
            "current.firstName" : regExp
        }, {
            "current.lastName" : regExp
        }, {
            "current.familyName" : regExp
        } ]
    }, {
        limit : 10,
        sort : "current.lastName"
    }).thenSync(mapGetId);
};

suggestions.onComputeSuggestions = function(event) {
    event.returnValue = suggestions(event.text);
};
<commit_msg>Sorting people first by first name then by last name.<commit_after>var peopleMgr = require("../../peopleMgr");

var getId = function(object) {
    return object.id;
};

var mapGetId = function(array) {
    return array.map(getId);
};

var suggestions = module.exports = function(text) {
    var regExp = new RegExp(text, "i");
    return peopleMgr.search({
        $or : [ {
            "current.firstName" : regExp
        }, {
            "current.lastName" : regExp
        }, {
            "current.familyName" : regExp
        } ]
    }, {
        limit : 10,
        sort : [ [ "current.firstName", "asc" ], [ "current.lastName", "asc" ] ]
    }).thenSync(mapGetId);
};

suggestions.onComputeSuggestions = function(event) {
    event.returnValue = suggestions(event.text);
};
<|endoftext|>


<commit_before>var UserView = {
    uploading: false,
    IMAGE_HEIGHT: 168,
    IMAGE_WIDTH: 168,
    showUploadedImage: function( source ) {
        $( ".avatar img" ).remove();
        $image = $( '' );
        $image.load( function() {
            UserView.fixImageSize( $image );
        } );
        $( ".avatar" ).append( $image );
    },
    createImageError: function() {
        $( '.text-center' ).prepend( "
This isn't an image
" )
    },
    removeImageError: function() {
        $( '.text-center .alert.alert-danger' ).remove();
    },
    fixImageSize: function( $image ) {
        var imgWidth = $image.width();
        var imgHeight = $image.height();

        if ( imgWidth > imgHeight ) {
            $image.height( UserView.IMAGE_HEIGHT );
            $image.css( 'top', 0 );
            $image.css( 'left', -Math.floor( ( $image.width() - UserView.IMAGE_WIDTH ) / 2 ) );
        }
        else {
            $image.width( UserView.IMAGE_WIDTH );
            $image.css( 'left', 0 );
            $image.css( 'top', -Math.floor( ( $image.height() - UserView.IMAGE_HEIGHT ) / 2 ) );
        }
    },
    finishUploadAnimation: function() {
        $( ".uploading" ).hide();
        $( ".uploading" ).removeClass( 'animate' );
        UserView.uploading = false;
    },
    startUploadAnimation: function() {
        $( ".upload-link" ).hide();
        $( ".uploading" ).show();
        $( ".uploading" ).addClass( 'animate' );
        UserView.uploading = true;
    },
    ready: function() {
        $( '.avatar img' ).load( function() {
            UserView.fixImageSize( $( '.avatar img' ) );
        } );
        $( ".avatar" ).mouseover( function() {
            if ( $( ".profile-header" ).attr( 'data-sameUser' ) == 'no' || UserView.uploading ) {
                return;
            }
            $( ".upload-link" ).show();
        } );
        $( ".avatar" ).mouseout( function() {
            if ( UserView.uploading ) {
                return;
            }
            $( ".upload-link" ).hide();
        } );
        $( ".upload-link" ).click( function() {
            $( "#image" ).trigger( 'click' );
            return false;
        } );
        $( document ).on( "click", ".follow", function() {
            if ( this.id == 'follow'  ) {
                var now = { 'method': 'create', 'action': 'follow' };
                var next = { 'method': 'delete', 'action': 'unfollow' };
            }
            else {
                var now = { 'method': 'delete', 'action': 'unfollow' };
                var next = { 'method': 'create', 'action': 'follow' };
            }

            var $form = $( "#" + now.action + "-form" );
            var followedid = $( "[name='followedid']", $form ).val();
            var token = $( "[name='token']", $form ).val();
            var formData = new FormData();

            formData.append( "followedid", followedid );
            formData.append( "token", token );

            $.ajax( {
                url: "follow/" + now.method,
                type: "POST",
                data: formData,
                cache: false,
                dataType: "json",
                processData: false,
                contentType: false,
                complete: function() {
                    $( "a#" + now.action ).replaceWith(
                        "<button class='btn btn-primary'>" + next.action + "</button>"
                    );
                    $( 'form#' + now.action + '-form' ).attr( 'action', 'follow/' + next.method );
                    $( 'form#' + now.action + '-form' ).attr( 'id', next.action + '-form' );
                }
            } );
            return false;
        } );
        $( "#image" ).change( function() {
            var image = document.getElementById( "image" ).files[ 0 ];
            var token = $( "input[type=hidden]" ).val();
            var formData = new FormData();

            UserView.removeImageError();

            if ( !image ) {
                return false;
            }

            formData.append( "image", image );
            formData.append( "token", token );

            UserView.startUploadAnimation();

            $.ajax( {
                url: "image/create",
                type: "POST",
                data: formData,
                cache: false,
                dataType: "json",
                processData: false,
                contentType: false,
                success: function( targetPath ) {
                    var reader = new FileReader();

                    UserView.finishUploadAnimation();

                    reader.onloadend = function ( e ) {
                        UserView.showUploadedImage( targetPath );
                    }
                    reader.readAsDataURL( image );
                },
                error: function( jqXHR, textStatus, errorThrown ) {
                    UserView.finishUploadAnimation();

                    UserView.createImageError();
                }
            } );

            return false;
        } );
    }
}
$( document ).ready( UserView.ready );
<commit_msg>capitalize the first letter of the function and make vars assignment in the beggining of the function<commit_after>var UserView = {
    uploading: false,
    IMAGE_HEIGHT: 168,
    IMAGE_WIDTH: 168,
    showUploadedImage: function( source ) {
        $( ".avatar img" ).remove();
        $image = $( '' );
        $image.load( function() {
            UserView.fixImageSize( $image );
        } );
        $( ".avatar" ).append( $image );
    },
    createImageError: function() {
        $( '.text-center' ).prepend( "
This isn't an image
" )
    },
    removeImageError: function() {
        $( '.text-center .alert.alert-danger' ).remove();
    },
    fixImageSize: function( $image ) {
        var imgWidth = $image.width();
        var imgHeight = $image.height();

        if ( imgWidth > imgHeight ) {
            $image.height( UserView.IMAGE_HEIGHT );
            $image.css( 'top', 0 );
            $image.css( 'left', -Math.floor( ( $image.width() - UserView.IMAGE_WIDTH ) / 2 ) );
        }
        else {
            $image.width( UserView.IMAGE_WIDTH );
            $image.css( 'left', 0 );
            $image.css( 'top', -Math.floor( ( $image.height() - UserView.IMAGE_HEIGHT ) / 2 ) );
        }
    },
    finishUploadAnimation: function() {
        $( ".uploading" ).hide();
        $( ".uploading" ).removeClass( 'animate' );
        UserView.uploading = false;
    },
    startUploadAnimation: function() {
        $( ".upload-link" ).hide();
        $( ".uploading" ).show();
        $( ".uploading" ).addClass( 'animate' );
        UserView.uploading = true;
    },
    ready: function() {
        $( '.avatar img' ).load( function() {
            UserView.fixImageSize( $( '.avatar img' ) );
        } );
        $( ".avatar" ).mouseover( function() {
            if ( $( ".profile-header" ).attr( 'data-sameUser' ) == 'no' || UserView.uploading ) {
                return;
            }
            $( ".upload-link" ).show();
        } );
        $( ".avatar" ).mouseout( function() {
            if ( UserView.uploading ) {
                return;
            }
            $( ".upload-link" ).hide();
        } );
        $( ".upload-link" ).click( function() {
            $( "#image" ).trigger( 'click' );
            return false;
        } );
        $( document ).on( "click", ".follow", function() {
            var now = next = {};

            if ( this.id == 'follow'  ) {
                now = { 'method': 'create', 'action': 'follow' };
                next = { 'method': 'delete', 'action': 'unfollow' };
            }
            else {
                now = { 'method': 'delete', 'action': 'unfollow' };
                next = { 'method': 'create', 'action': 'follow' };
            }

            var $form = $( "#" + now.action + "-form" );
            var followedid = $( "[name='followedid']", $form ).val();
            var token = $( "[name='token']", $form ).val();
            var formData = new FormData();

            formData.append( "followedid", followedid );
            formData.append( "token", token );

            $.ajax( {
                url: "follow/" + now.method,
                type: "POST",
                data: formData,
                cache: false,
                dataType: "json",
                processData: false,
                contentType: false,
                complete: function() {
                    var btn_text = next.action.substr(0, 1).toUpperCase() + next.action.substr(1);
                    $( "a#" + now.action ).replaceWith(
                        "<button class='btn btn-primary'>" + btn_text + "</button>"
                    );
                    $( 'form#' + now.action + '-form' ).attr( 'action', 'follow/' + next.method );
                    $( 'form#' + now.action + '-form' ).attr( 'id', next.action + '-form' );
                }
            } );
            return false;
        } );
        $( "#image" ).change( function() {
            var image = document.getElementById( "image" ).files[ 0 ];
            var token = $( "input[type=hidden]" ).val();
            var formData = new FormData();

            UserView.removeImageError();

            if ( !image ) {
                return false;
            }

            formData.append( "image", image );
            formData.append( "token", token );

            UserView.startUploadAnimation();

            $.ajax( {
                url: "image/create",
                type: "POST",
                data: formData,
                cache: false,
                dataType: "json",
                processData: false,
                contentType: false,
                success: function( targetPath ) {
                    var reader = new FileReader();

                    UserView.finishUploadAnimation();

                    reader.onloadend = function ( e ) {
                        UserView.showUploadedImage( targetPath );
                    }
                    reader.readAsDataURL( image );
                },
                error: function( jqXHR, textStatus, errorThrown ) {
                    UserView.finishUploadAnimation();

                    UserView.createImageError();
                }
            } );

            return false;
        } );
    }
}
$( document ).ready( UserView.ready );
<|endoftext|>


<commit_before>var gulp = require('gulp');
var browserSync = require('browser-sync').create();
var pkg = require('./package.json');

// Copy vendor files from /node_modules into /vendor
// NOTE: requires `npm install` before running!
gulp.task('copy', function() {
  gulp.src([
      'node_modules/bootstrap/dist/**/*',
      '!**/npm.js',
      '!**/bootstrap-theme.*',
      '!**/*.map'
    ])
    .pipe(gulp.dest('vendor/bootstrap'))

  gulp.src(['node_modules/jquery/dist/jquery.js', 'node_modules/jquery/dist/jquery.min.js'])
    .pipe(gulp.dest('vendor/jquery'))

  gulp.src(['node_modules/popper.js/dist/umd/popper.js', 'node_modules/popper.js/dist/umd/popper.min.js'])
    .pipe(gulp.dest('vendor/popper'))

  gulp.src(['node_modules/jquery.easing/*.js'])
    .pipe(gulp.dest('vendor/jquery-easing'))
})

// Default task
gulp.task('default', ['copy']);

// Configure the browserSync task
gulp.task('browserSync', function() {
  browserSync.init({
    server: {
      baseDir: ''
    },
  })
})

// Dev task with browserSync
gulp.task('dev', ['browserSync'], function() {
  // Reloads the browser whenever HTML or CSS files change
  gulp.watch('css/*.css', browserSync.reload);
  gulp.watch('js/*.js', browserSync.reload);
  gulp.watch('*.html', browserSync.reload);
});
<commit_msg>remove popper from gulpfile<commit_after>var gulp = require('gulp');
var browserSync = require('browser-sync').create();
var pkg = require('./package.json');

// Copy vendor files from /node_modules into /vendor
// NOTE: requires `npm install` before running!
gulp.task('copy', function() {
  gulp.src([
      'node_modules/bootstrap/dist/**/*',
      '!**/npm.js',
      '!**/bootstrap-theme.*',
      '!**/*.map'
    ])
    .pipe(gulp.dest('vendor/bootstrap'))

  gulp.src(['node_modules/jquery/dist/jquery.js', 'node_modules/jquery/dist/jquery.min.js'])
    .pipe(gulp.dest('vendor/jquery'))

  gulp.src(['node_modules/jquery.easing/*.js'])
    .pipe(gulp.dest('vendor/jquery-easing'))
})

// Default task
gulp.task('default', ['copy']);

// Configure the browserSync task
gulp.task('browserSync', function() {
  browserSync.init({
    server: {
      baseDir: ''
    },
  })
})

// Dev task with browserSync
gulp.task('dev', ['browserSync'], function() {
  // Reloads the browser whenever HTML or CSS files change
  gulp.watch('css/*.css', browserSync.reload);
  gulp.watch('js/*.js', browserSync.reload);
  gulp.watch('*.html', browserSync.reload);
});
<|endoftext|>


<commit_before>var io = require("socket.io-client");
var http = require("http");
var url = require("url");

var socket;
var dataQueue = [];
var newDataAllowed = true;

http.createServer(function(request, response) {
	var params = decodeURI(url.parse(request.url).pathname).split("/");
	params.splice(0, 1);

	if (params[0] !== "poll") {
		console.log(params);
	}

	if (!socket) {
		// We don't have a socket yet we send nothing
		if (params[0] !== "connect") {
			response.end();
			return;
		}

		// Client wants to connect
		socket = io("http://" + params[1]);
		console.log(socket)
	}

	// Scratch wants to send data
	if (params[0] == "emit") {
		socket.emit(params[1], params[2]);
	}

	// Scratch client wants to listen to a new type of event
	if (socket && params[0] == "register") {
		socket.on(params[1], function (event, data) {
			if (typeof data === "object" && data.length === "number") {
				throw "You can only send arrays of strings and integers";
			}

			dataQueue.push({
				event: params[1],
				data: data
			});
		}.bind(this, params[1]));
	}

	if (params[0] == "updatevars") {
		newDataAllowed = true;
	}

	if (params[0] == "poll" && newDataAllowed) {
		var data = "";

		for (var k = 1; k < 4; k++) {
			if (dataQueue[0]) {
				data += "event" + k + " " + dataQueue[0].event + "\n";
				data += "value" + k + " " + dataQueue[0].data.join(",") + "\n";
				dataQueue.splice(0, 1);
			}
		}

		response.write(data);
		newDataAllowed = false;
	}

	// We received your request and acknowledge you
	response.end();
}).listen(12345);

<commit_msg>Update client.js<commit_after>var io = require("socket.io-client");
var http = require("http");
var url = require("url");

var socket;
var dataQueue = [];
var newDataAllowed = true;

http.createServer(function(request, response) {
	var params = decodeURI(url.parse(request.url).pathname).split("/");
	params.splice(0, 1);

	if (params[0] !== "poll") {
		console.log(params);
	}

	if (!socket) {
		// We don't have a socket yet we send nothing
		if (params[0] !== "connect") {
			response.end();
			return;
		}

		// Client wants to connect
		socket = io("http://" + params[1]);
		console.log(socket)
	}

	// Scratch wants to send data
	if (params[0] == "emit") {
		socket.emit(params[1], params[2]);
	}

	// Scratch client wants to listen to a new type of event
	if (socket && params[0] == "register") {
		socket.on(params[1], function (event, data) {
			if (typeof data !== "object" && typeof data.length !== "number") {
				throw "You can only send arrays of strings and integers";
			}

			dataQueue.push({
				event: params[1],
				data: data
			});
		}.bind(this, params[1]));
	}

	if (params[0] == "updatevars") {
		newDataAllowed = true;
	}

	if (params[0] == "poll" && newDataAllowed) {
		var data = "";

		for (var k = 1; k < 4; k++) {
			if (dataQueue[0]) {
				data += "event" + k + " " + dataQueue[0].event + "\n";
				data += "value" + k + " " + dataQueue[0].data.join(",") + "\n";
				dataQueue.splice(0, 1);
			}
		}

		response.write(data);
		newDataAllowed = false;
	}

	// We received your request and acknowledge you
	response.end();
}).listen(12345);

<|endoftext|>


<commit_before>'use strict';

const ajax = require('../common/ajax-functions.js');

/* Client-side book controller which handles communication towards the server,
 * when user wants to add/remove books to/from their profile.
 * */
class BookCtrl {

    constructor(url) {
        this.appUrl = url;
    }

    addBook(bookData, cb) {
        var url = this.appUrl + '/book';
        ajax.post(url, bookData, (err, respText) => {
            if (err) {cb(err);}
            else {
                var respData = JSON.parse(respText);
                cb(null, respData);
            }
        });
    }

    deleteBook(bookData, cb) {
        var url = this.appUrl + '/book';
        ajax.delete(url, bookData, (err, respText) => {
            if (err) {cb(err);}
            else {
                var respData = JSON.parse(respText);
                cb(null, respData);
            }

        });
    }

    /* Gets a list of all books from the server. */
    getAllBooks(cb) {
        var url = this.appUrl + '/book';
        this._ajaxGetBooks(url, cb);
    }

    /* Given username, retrieves all books for that user. This is mainly useful
     * for trade requests. */
    getBooksForUser(username, cb) {
        var url = this.appUrl + '/books/' + username;
        this._ajaxGetBooks(url, cb);
    }

    _ajaxGetBooks(url, cb) {
        ajax.get(url, (err, respText) => {
            if (err) {
                cb(err);
            }
            else {
                try {
                    var books = JSON.parse(respText);
                    cb(null, books);
                }
                catch (e) {
                    var errMsg = 'An error occurred of type: ' + e.toString();
                    cb(errMsg);
                }
            }
        });
    }

}

module.exports = BookCtrl;
<commit_msg>Added searchBook().<commit_after>'use strict';

const ajax = require('../common/ajax-functions.js');

/* Client-side book controller which handles communication towards the server,
 * when user wants to add/remove books to/from their profile.
 * */
class BookCtrl {

    constructor(url) {
        this.appUrl = url;
    }

    addBook(bookData, cb) {
        var url = this.appUrl + '/book';
        ajax.post(url, bookData, (err, respText) => {
            if (err) {cb(err);}
            else {
                var respData = JSON.parse(respText);
                cb(null, respData);
            }
        });
    }

    deleteBook(bookData, cb) {
        var url = this.appUrl + '/book';
        ajax.delete(url, bookData, (err, respText) => {
            if (err) {cb(err);}
            else {
                var respData = JSON.parse(respText);
                cb(null, respData);
            }

        });
    }

    searchBook(search, cb) {
        var url = this.appUrl + '/books/search';
        ajax.post(url, {search: search}, (err, respText) => {
            if (err) {cb(err);}
            else {
                var respData = JSON.parse(respText);
                cb(null, respData);
            }
        });
    }

    /* Gets a list of all books from the server. */
    getAllBooks(cb) {
        var url = this.appUrl + '/book';
        this._ajaxGetBooks(url, cb);
    }

    /* Given username, retrieves all books for that user. This is mainly useful
     * for trade requests. */
    getBooksForUser(username, cb) {
        var url = this.appUrl + '/books/' + username;
        this._ajaxGetBooks(url, cb);
    }

    _ajaxGetBooks(url, cb) {
        ajax.get(url, (err, respText) => {
            if (err) {
                cb(err);
            }
            else {
                try {
                    var books = JSON.parse(respText);
                    cb(null, books);
                }
                catch (e) {
                    var errMsg = 'An error occurred of type: ' + e.toString();
                    cb(errMsg);
                }
            }
        });
    }

}

module.exports = BookCtrl;
<|endoftext|>


<commit_before>var elixir = require('laravel-elixir');

elixir(function(mix) {
    mix
        // Copy webfont files from /vendor directories to /public directory.
        .copy('vendor/fortawesome/font-awesome/fonts', 'public/fonts')
        .copy('vendor/twbs/bootstrap-sass/assets/fonts/bootstrap', 'public/fonts')
        .copy('vendor/twbs/bootstrap/dist/js/bootstrap.min.js', 'public/js/vendor')

        .sass([ // Process front-end stylesheets
                'frontend/main.scss'
            ], 'resources/assets/css/frontend/main.css')
        .styles([  // Combine pre-processed CSS files
                'frontend/main.css'
            ], 'public/css/frontend.css')
        .scripts([ // Combine front-end scripts
                'plugins.js',
                'frontend/main.js'
            ], 'public/js/frontend.js')

        .sass([ // Process back-end stylesheets
            'backend/main.scss',
            'backend/skin.scss'
        ], 'resources/assets/css/backend/main.css')
        .styles([ // Combine pre-processed CSS files
                'bootstrap.css',
                'font-awesome.css',
                'backend/main.css',
                'backend/skin.css'
            ], 'public/css/backend.css')
        .scripts([ // Combine back-end scripts
                'plugins.js',
                'backend/main.js'
            ], 'public/js/backend.js')

        // Apply version control
        .version(["public/css/frontend.css", "public/js/frontend.js", "public/css/backend.css", "public/js/backend.js"]);
});

/**
 * Uncomment for LESS version
 */
/*elixir(function(mix) {
    mix
        // Copy webfont files from /vendor directories to /public directory.
        .copy('vendor/fortawesome/font-awesome/fonts', 'public/fonts')
        .copy('vendor/twbs/bootstrap/fonts', 'public/fonts')
        .copy('vendor/twbs/bootstrap/dist/js/bootstrap.min.js', 'public/js/vendor')

        .less([ // Process front-end stylesheets
            'frontend/main.less'
        ], 'resources/assets/css/frontend/main.less')
        .styles([  // Combine pre-processed CSS files
            'frontend/main.css'
        ], 'public/css/frontend.css')
        .scripts([ // Combine front-end scripts
            'plugins.js',
            'frontend/main.js'
        ], 'public/js/frontend.js')

        .less([ // Process back-end stylesheets
            'backend/AdminLTE.less',
        ], 'resources/assets/css/backend/AdminLTE.less')
        .styles([ // Combine pre-processed CSS files
            'bootstrap.css',
            'font-awesome.css',
            'backend/main.css',
            'backend/skin.css'
        ], 'public/css/backend.css')
        .scripts([ // Combine back-end scripts
            'plugins.js',
            'backend/main.js'
        ], 'public/js/backend.js')

        // Apply version control
        .version(["public/css/frontend.css", "public/js/frontend.js", "public/css/backend.css", "public/js/backend.js"]);
});*/<commit_msg>fix issue #53 gulp less to css output filename<commit_after>var elixir = require('laravel-elixir');

elixir(function(mix) {
    mix
        // Copy webfont files from /vendor directories to /public directory.
        .copy('vendor/fortawesome/font-awesome/fonts', 'public/fonts')
        .copy('vendor/twbs/bootstrap-sass/assets/fonts/bootstrap', 'public/fonts')
        .copy('vendor/twbs/bootstrap/dist/js/bootstrap.min.js', 'public/js/vendor')

        .sass([ // Process front-end stylesheets
                'frontend/main.scss'
            ], 'resources/assets/css/frontend/main.css')
        .styles([  // Combine pre-processed CSS files
                'frontend/main.css'
            ], 'public/css/frontend.css')
        .scripts([ // Combine front-end scripts
                'plugins.js',
                'frontend/main.js'
            ], 'public/js/frontend.js')

        .sass([ // Process back-end stylesheets
            'backend/main.scss',
            'backend/skin.scss'
        ], 'resources/assets/css/backend/main.css')
        .styles([ // Combine pre-processed CSS files
                'bootstrap.css',
                'font-awesome.css',
                'backend/main.css',
                'backend/skin.css'
            ], 'public/css/backend.css')
        .scripts([ // Combine back-end scripts
                'plugins.js',
                'backend/main.js'
            ], 'public/js/backend.js')

        // Apply version control
        .version(["public/css/frontend.css", "public/js/frontend.js", "public/css/backend.css", "public/js/backend.js"]);
});

/**
 * Uncomment for LESS version
 */
/*elixir(function(mix) {
    mix
        // Copy webfont files from /vendor directories to /public directory.
        .copy('vendor/fortawesome/font-awesome/fonts', 'public/fonts')
        .copy('vendor/twbs/bootstrap/fonts', 'public/fonts')
        .copy('vendor/twbs/bootstrap/dist/js/bootstrap.min.js', 'public/js/vendor')

        .less([ // Process front-end stylesheets
            'frontend/main.less'
        ], 'resources/assets/css/frontend/main.css')
        .styles([  // Combine pre-processed CSS files
            'frontend/main.css'
        ], 'public/css/frontend.css')
        .scripts([ // Combine front-end scripts
            'plugins.js',
            'frontend/main.js'
        ], 'public/js/frontend.js')

        .less([ // Process back-end stylesheets
            'backend/AdminLTE.less',
        ], 'resources/assets/css/backend/AdminLTE.less')
        .styles([ // Combine pre-processed CSS files
            'bootstrap.css',
            'font-awesome.css',
            'backend/main.css',
            'backend/skin.css'
        ], 'public/css/backend.css')
        .scripts([ // Combine back-end scripts
            'plugins.js',
            'backend/main.js'
        ], 'public/js/backend.js')

        // Apply version control
        .version(["public/css/frontend.css", "public/js/frontend.js", "public/css/backend.css", "public/js/backend.js"]);
});*/
<|endoftext|>


<commit_before>var chalk = require('chalk');
var util = require('util');

'use strict';

module.exports = {
  Logger: Logger,
  setDebugEnabled: setDebugEnabled,
  _system: new Logger() // system logger, for internal use only
}

var DEBUG_ENABLED = false;

// Turns on debug level logging
function setDebugEnabled(enabled) {
  DEBUG_ENABLED = enabled;
}

// global cache of logger instances by plugin name
var loggerCache = {};

/**
 * Logger class
 */

function Logger(prefix) {
  this.prefix = prefix;
}

Logger.prototype.debug = function(msg) {
  if (DEBUG_ENABLED)
    this.log.apply(this, ['debug'].concat(Array.prototype.slice.call(arguments)));
}

Logger.prototype.info = function(msg) {
  this.log.apply(this, ['info'].concat(Array.prototype.slice.call(arguments)));
}

Logger.prototype.warn = function(msg) {
  this.log.apply(this, ['warn'].concat(Array.prototype.slice.call(arguments)));
}

Logger.prototype.error = function(msg) {
  this.log.apply(this, ['error'].concat(Array.prototype.slice.call(arguments)));
}

Logger.prototype.log = function(level, msg) {

  msg = util.format.apply(util, Array.prototype.slice.call(arguments, 1));
  func = console.log;

  if (level == 'debug') {
    msg = chalk.gray(msg);
  }
  else if (level == 'warn') {
    msg = chalk.yellow(msg);
    func = console.error;
  }
  else if (level == 'error') {
    msg = chalk.bold.red(msg);
    func = console.error;
  }

  // prepend prefix if applicable
  if (this.prefix)
    msg = chalk.cyan("[" + this.prefix +  "]") + " " + msg;

  // prepend timestamp
  var date = new Date();
  msg = chalk.black("[" + date.toLocaleString() + "]") + " " + msg;

  func(msg);
}

Logger.withPrefix = function(prefix) {

  if (!loggerCache[prefix]) {
    // create a class-like logger thing that acts as a function as well
    // as an instance of Logger.
    var logger = new Logger(prefix);
    var log = logger.info.bind(logger);
    log.debug = logger.debug;
    log.info = logger.info;
    log.warn = logger.warn;
    log.error = logger.error;
    log.log = logger.log;
    log.prefix = logger.prefix;
    loggerCache[prefix] = log;
  }

  return loggerCache[prefix];
}
<commit_msg>Changed color for logging timestamp to white.<commit_after>var chalk = require('chalk');
var util = require('util');

'use strict';

module.exports = {
  Logger: Logger,
  setDebugEnabled: setDebugEnabled,
  _system: new Logger() // system logger, for internal use only
}

var DEBUG_ENABLED = false;

// Turns on debug level logging
function setDebugEnabled(enabled) {
  DEBUG_ENABLED = enabled;
}

// global cache of logger instances by plugin name
var loggerCache = {};

/**
 * Logger class
 */

function Logger(prefix) {
  this.prefix = prefix;
}

Logger.prototype.debug = function(msg) {
  if (DEBUG_ENABLED)
    this.log.apply(this, ['debug'].concat(Array.prototype.slice.call(arguments)));
}

Logger.prototype.info = function(msg) {
  this.log.apply(this, ['info'].concat(Array.prototype.slice.call(arguments)));
}

Logger.prototype.warn = function(msg) {
  this.log.apply(this, ['warn'].concat(Array.prototype.slice.call(arguments)));
}

Logger.prototype.error = function(msg) {
  this.log.apply(this, ['error'].concat(Array.prototype.slice.call(arguments)));
}

Logger.prototype.log = function(level, msg) {

  msg = util.format.apply(util, Array.prototype.slice.call(arguments, 1));
  func = console.log;

  if (level == 'debug') {
    msg = chalk.gray(msg);
  }
  else if (level == 'warn') {
    msg = chalk.yellow(msg);
    func = console.error;
  }
  else if (level == 'error') {
    msg = chalk.bold.red(msg);
    func = console.error;
  }

  // prepend prefix if applicable
  if (this.prefix)
    msg = chalk.cyan("[" + this.prefix +  "]") + " " + msg;

  // prepend timestamp
  var date = new Date();
  msg =  chalk.white("[" + date.toLocaleString() + "]") + " " + msg;

  func(msg);
}

Logger.withPrefix = function(prefix) {

  if (!loggerCache[prefix]) {
    // create a class-like logger thing that acts as a function as well
    // as an instance of Logger.
    var logger = new Logger(prefix);
    var log = logger.info.bind(logger);
    log.debug = logger.debug;
    log.info = logger.info;
    log.warn = logger.warn;
    log.error = logger.error;
    log.log = logger.log;
    log.prefix = logger.prefix;
    loggerCache[prefix] = log;
  }

  return loggerCache[prefix];
}
<|endoftext|>


<commit_before>window.testdata = function () {

    var elementsById = {};
    var idCounter = 0;
    var _statistics = null;
    var LEVELS = ['TRACE', 'DEBUG', 'INFO', 'WARN', 'FAIL', 'ERROR'];
    var STATUSES = ['FAIL', 'PASS', 'NOT_RUN'];
    var KEYWORDS = ['KEYWORD', 'SETUP', 'TEARDOWN', 'FOR', 'VAR'];

    function addElement(elem) {
        if (elem.id == undefined)
            elem.id = uniqueId();
        elementsById[elem.id] = elem;
        return elem;
    }

    // TODO: DO we still need this?
    function uniqueId() {
        idCounter++;
        return "elementId_" + idCounter;
    }

    function timestamp(millis) {
        return new Date(window.output.baseMillis + millis);
    }

    function times(stats) {
        var startMillis = stats[1];
        var elapsed = stats[2];
        if (startMillis == null)
            return [null, null, elapsed];
        return [timestamp(startMillis), timestamp(startMillis + elapsed), elapsed];
    }

    function message(element, strings) {
        return addElement(model.Message(LEVELS[element[1]],
                                        timestamp(element[0]),
                                        strings.get(element[2]),
                                        strings.get(element[3])));
    }

    function parseStatus(stats, strings, parentSuiteTeardownFailed) {
        if (parentSuiteTeardownFailed)
            return 'FAIL';
        return STATUSES[stats[0]];
    }

    function last(items) {
        return items[items.length-1];
    }

    function childCreator(parent, childType) {
        return function (elem, strings, index) {
            return addElement(childType(parent, elem, strings, index));
        };
    }

    function createKeyword(parent, element, strings, index) {
        var kw = model.Keyword({
            type: KEYWORDS[element[0]],
            name: strings.get(element[1]),
            timeout: strings.get(element[2]),
            args: strings.get(element[4]),
            doc: function () {
                var doc = strings.get(element[3]);
                this.doc = function () { return doc; };
                return doc;
            },
            status: parseStatus(element[5], strings),
            times: model.Times(times(element[5])),
            parent: parent,
            index: index,
            isChildrenLoaded: typeof(element[6]) !== 'number'
        });
        lazyPopulateKeywordsFromFile(kw, element[6], strings);
        kw.populateMessages(Populator(element[7], strings, message));
        return kw;
    }

    function lazyPopulateKeywordsFromFile(parent, keywordsOrIndex, strings) {
        if (parent.isChildrenLoaded) {
            var keywords = keywordsOrIndex;
            parent.populateKeywords(Populator(keywords, strings, childCreator(parent, createKeyword)));
        } else {
            var index = keywordsOrIndex;
            parent.childFileName = window.settings['splitLogBase'] + '-' + index + '.js';
            parent.populateKeywords(SplitLogPopulator(keywordsOrIndex, childCreator(parent, createKeyword)));
        }
    }

    function tags(taglist, strings) {
        return util.map(taglist, strings.get);
    }

    function createTest(suite, element, strings, index) {
        var statusElement = element[5];
        var test = model.Test({
            parent: suite,
            name: strings.get(element[0]),
            index: index,
            doc: function () {
                var doc = strings.get(element[3]);
                this.doc = function () { return doc; };
                return doc;
            },
            timeout: strings.get(element[1]),
            isCritical: element[2],
            status: parseStatus(statusElement, strings, suite.teardownFailed),
            message:  function () {
                var msg = createMessage(statusElement, strings, suite.teardownFailed);
                this.message = function () { return msg; };
                return msg;
            },
            times: model.Times(times(statusElement)),
            tags: tags(element[4], strings),
            isChildrenLoaded: typeof(element[6]) !== 'number'
        });
        lazyPopulateKeywordsFromFile(test, element[6], strings);
        return test;
    }

    function createMessage(statusElement, strings, suiteTeardownFailed) {
        var message = statusElement.length == 4 ? strings.get(statusElement[3]) : '';
        // output generated by rebot has already teardown messages in place
        if (!suiteTeardownFailed || window.output.generator == 'rebot')
            return message;
        if (message)
            return message + '\n\nAlso teardown of the parent suite failed.';
        return 'Teardown of the parent suite failed.';
    }

    function createSuite(parent, element, strings, index) {
        var statusElement = element[5];
        var parentTeardownFailed = parent && parent.teardownFailed;
        var suite = model.Suite({
            parent: parent,
            name: strings.get(element[0]),
            index: index,
            source: strings.get(element[1]),
            relativeSource: strings.get(element[2]),
            doc: function () {
                var doc = strings.get(element[3]);
                this.doc = function () { return doc; };
                return doc;
            },
            status: parseStatus(statusElement, strings, parentTeardownFailed),
            message: function () {
                var msg = createMessage(statusElement, strings);
                this.message = function () { return msg; };
                return msg;
            },
            times: model.Times(times(statusElement)),
            teardownFailed: element[9] || parentTeardownFailed,
            statistics: suiteStats(last(element)),
            metadata: parseMetadata(element[4], strings)
        });
        suite.populateKeywords(Populator(element[8], strings, childCreator(suite, createKeyword)));
        suite.populateTests(Populator(element[7], strings, childCreator(suite, createTest)));
        suite.populateSuites(Populator(element[6], strings, childCreator(suite, createSuite)));
        return suite;
    }

    function parseMetadata(data, strings) {
        var metadata = [];
        for (var i=0; i<data.length; i+=2) {
            metadata.push([strings.get(data[i]), strings.get(data[i+1])]);
        }
        return metadata;
    }

    function suiteStats(stats) {
        // TODO: Should use 'all' instead of 'total' here for consistency
        return {
            total: stats[0],
            totalPassed: stats[1],
            totalFailed: stats[0] - stats[1],
            critical: stats[2],
            criticalPassed: stats[3],
            criticalFailed: stats[2] - stats[3]
        };
    }

    function Populator(items, strings, creator) {
        return {
            numberOfItems: function () {
                return items.length;
            },
            creator: function (index) {
                return creator(items[index], strings, index);
            }
        };
    }

    function SplitLogPopulator(structureIndex, creator) {
        return {
            numberOfItems: function () {
                return window['keywords'+structureIndex].length;
            },
            creator: function (index) {
                return creator(window['keywords'+structureIndex][index],
                               getStringStore(window['strings'+structureIndex]),
                               index);
            }
        };
    }

    function suite() {
        var elem = window.output.suite;
        if (elementsById[elem.id])
            return elem;
        var main = addElement(createSuite(undefined, elem, getStringStore(window.output.strings)));
        window.output.suite = main;
        return main;
    }

    function findById(id) {
        return elementsById[id];
    }

    function findPathTo(pathId, callback) {
        var ids = pathId.split("-");
        if (ids[0] != "s1") {
            callback([]);
            return;
        }
        var root = suite();
        ids.shift();
        findPathWithId(ids, root, [root.id], callback);
    }

    function findPathWithId(pathId, current, result, callback) {
        if (pathId.length == 0) {
            callback(result);
        } else {
            current.callWhenChildrenReady(function () {
                var item = selectFrom(current, pathId[0][0], parseInt(pathId[0].substring(1))-1);
                result.push(item.id);
                pathId.shift();
                findPathWithId(pathId, item, result, callback);
            });
        }
    }

    function selectFrom(element, selector, index) {
        if (selector == "k") {
            return element.keywords()[index];
        } else if(selector == "t") {
            return element.tests()[index];
        } else if(selector == "s") {
            return element.suites()[index];
        }
    }

    function generated() {
        return timestamp(window.output.generatedMillis);
    }

    function errors() {
        var iterator = new Object();
        iterator.counter = 0;
        iterator.next = function () {
            return message(window.output.errors[iterator.counter++],
                           getStringStore(window.output.strings));
        };
        iterator.hasNext = function () {
            return iterator.counter < window.output.errors.length;
        };
        return iterator;
    }

    function statistics() {
        if (!_statistics) {
            var statData = window.output.stats;
            _statistics = stats.Statistics(statData[0], statData[1], statData[2]);
        }
        return _statistics;
    }

    function getStringStore(strings) {

        function getText(id) {
            var text = strings[id];
            if (!text)
                return '';
            if (text[0] == '*')
                return text.substring(1);
            var extracted = extract(text);
            strings[id] = "*"+extracted;
            return extracted;
        }

        function extract(text) {
            var decoded = JXG.Util.Base64.decodeAsArray(text);
            var extracted = (new JXG.Util.Unzip(decoded)).unzip()[0][0];
            return JXG.Util.utf8Decode(extracted);
        }

        function get(id) {
            if (id == undefined) return undefined;
            if (id == null) return null;
            return getText(id);
        }

        return {get: get};
    }

    return {
        suite: suite,
        errors: errors,
        find: findById,
        findPathTo: findPathTo,
        generated: generated,
        statistics: statistics,
        getStringStore: getStringStore
    };

}();
<commit_msg>cleanup<commit_after>window.testdata = function () {

    var elementsById = {};
    var idCounter = 0;
    var _statistics = null;
    var LEVELS = ['TRACE', 'DEBUG', 'INFO', 'WARN', 'FAIL', 'ERROR'];
    var STATUSES = ['FAIL', 'PASS', 'NOT_RUN'];
    var KEYWORDS = ['KEYWORD', 'SETUP', 'TEARDOWN', 'FOR', 'VAR'];

    function addElement(elem) {
        if (elem.id == undefined)
            elem.id = uniqueId();
        elementsById[elem.id] = elem;
        return elem;
    }

    function uniqueId() {
        idCounter++;
        return "elementId_" + idCounter;
    }

    function timestamp(millis) {
        return new Date(window.output.baseMillis + millis);
    }

    function times(stats) {
        var startMillis = stats[1];
        var elapsed = stats[2];
        if (startMillis == null)
            return [null, null, elapsed];
        return [timestamp(startMillis), timestamp(startMillis + elapsed), elapsed];
    }

    function message(element, strings) {
        return addElement(model.Message(LEVELS[element[1]],
                                        timestamp(element[0]),
                                        strings.get(element[2]),
                                        strings.get(element[3])));
    }

    function parseStatus(stats, strings, parentSuiteTeardownFailed) {
        if (parentSuiteTeardownFailed)
            return 'FAIL';
        return STATUSES[stats[0]];
    }

    function last(items) {
        return items[items.length-1];
    }

    function childCreator(parent, childType) {
        return function (elem, strings, index) {
            return addElement(childType(parent, elem, strings, index));
        };
    }

    function createKeyword(parent, element, strings, index) {
        var kw = model.Keyword({
            type: KEYWORDS[element[0]],
            name: strings.get(element[1]),
            timeout: strings.get(element[2]),
            args: strings.get(element[4]),
            doc: function () {
                var doc = strings.get(element[3]);
                this.doc = function () { return doc; };
                return doc;
            },
            status: parseStatus(element[5], strings),
            times: model.Times(times(element[5])),
            parent: parent,
            index: index,
            isChildrenLoaded: typeof(element[6]) !== 'number'
        });
        lazyPopulateKeywordsFromFile(kw, element[6], strings);
        kw.populateMessages(Populator(element[7], strings, message));
        return kw;
    }

    function lazyPopulateKeywordsFromFile(parent, keywordsOrIndex, strings) {
        if (parent.isChildrenLoaded) {
            var keywords = keywordsOrIndex;
            parent.populateKeywords(Populator(keywords, strings, childCreator(parent, createKeyword)));
        } else {
            var index = keywordsOrIndex;
            parent.childFileName = window.settings['splitLogBase'] + '-' + index + '.js';
            parent.populateKeywords(SplitLogPopulator(keywordsOrIndex, childCreator(parent, createKeyword)));
        }
    }

    function tags(taglist, strings) {
        return util.map(taglist, strings.get);
    }

    function createTest(suite, element, strings, index) {
        var statusElement = element[5];
        var test = model.Test({
            parent: suite,
            name: strings.get(element[0]),
            index: index,
            doc: function () {
                var doc = strings.get(element[3]);
                this.doc = function () { return doc; };
                return doc;
            },
            timeout: strings.get(element[1]),
            isCritical: element[2],
            status: parseStatus(statusElement, strings, suite.teardownFailed),
            message:  function () {
                var msg = createMessage(statusElement, strings, suite.teardownFailed);
                this.message = function () { return msg; };
                return msg;
            },
            times: model.Times(times(statusElement)),
            tags: tags(element[4], strings),
            isChildrenLoaded: typeof(element[6]) !== 'number'
        });
        lazyPopulateKeywordsFromFile(test, element[6], strings);
        return test;
    }

    function createMessage(statusElement, strings, suiteTeardownFailed) {
        var message = statusElement.length == 4 ? strings.get(statusElement[3]) : '';
        // output generated by rebot has already teardown messages in place
        if (!suiteTeardownFailed || window.output.generator == 'rebot')
            return message;
        if (message)
            return message + '\n\nAlso teardown of the parent suite failed.';
        return 'Teardown of the parent suite failed.';
    }

    function createSuite(parent, element, strings, index) {
        var statusElement = element[5];
        var parentTeardownFailed = parent && parent.teardownFailed;
        var suite = model.Suite({
            parent: parent,
            name: strings.get(element[0]),
            index: index,
            source: strings.get(element[1]),
            relativeSource: strings.get(element[2]),
            doc: function () {
                var doc = strings.get(element[3]);
                this.doc = function () { return doc; };
                return doc;
            },
            status: parseStatus(statusElement, strings, parentTeardownFailed),
            message: function () {
                var msg = createMessage(statusElement, strings);
                this.message = function () { return msg; };
                return msg;
            },
            times: model.Times(times(statusElement)),
            teardownFailed: element[9] || parentTeardownFailed,
            statistics: suiteStats(last(element)),
            metadata: parseMetadata(element[4], strings)
        });
        suite.populateKeywords(Populator(element[8], strings, childCreator(suite, createKeyword)));
        suite.populateTests(Populator(element[7], strings, childCreator(suite, createTest)));
        suite.populateSuites(Populator(element[6], strings, childCreator(suite, createSuite)));
        return suite;
    }

    function parseMetadata(data, strings) {
        var metadata = [];
        for (var i=0; i<data.length; i+=2) {
            metadata.push([strings.get(data[i]), strings.get(data[i+1])]);
        }
        return metadata;
    }

    function suiteStats(stats) {
        // TODO: Should use 'all' instead of 'total' here for consistency
        return {
            total: stats[0],
            totalPassed: stats[1],
            totalFailed: stats[0] - stats[1],
            critical: stats[2],
            criticalPassed: stats[3],
            criticalFailed: stats[2] - stats[3]
        };
    }

    function Populator(items, strings, creator) {
        return {
            numberOfItems: function () {
                return items.length;
            },
            creator: function (index) {
                return creator(items[index], strings, index);
            }
        };
    }

    function SplitLogPopulator(structureIndex, creator) {
        return {
            numberOfItems: function () {
                return window['keywords'+structureIndex].length;
            },
            creator: function (index) {
                return creator(window['keywords'+structureIndex][index],
                               getStringStore(window['strings'+structureIndex]),
                               index);
            }
        };
    }

    function suite() {
        var elem = window.output.suite;
        if (elementsById[elem.id])
            return elem;
        var main = addElement(createSuite(undefined, elem, getStringStore(window.output.strings)));
        window.output.suite = main;
        return main;
    }

    function findById(id) {
        return elementsById[id];
    }

    function findPathTo(pathId, callback) {
        var ids = pathId.split("-");
        if (ids[0] != "s1") {
            callback([]);
            return;
        }
        var root = suite();
        ids.shift();
        findPathWithId(ids, root, [root.id], callback);
    }

    function findPathWithId(pathId, current, result, callback) {
        if (pathId.length == 0) {
            callback(result);
        } else {
            current.callWhenChildrenReady(function () {
                var item = selectFrom(current, pathId[0][0], parseInt(pathId[0].substring(1))-1);
                result.push(item.id);
                pathId.shift();
                findPathWithId(pathId, item, result, callback);
            });
        }
    }

    function selectFrom(element, selector, index) {
        if (selector == "k") {
            return element.keywords()[index];
        } else if(selector == "t") {
            return element.tests()[index];
        } else if(selector == "s") {
            return element.suites()[index];
        }
    }

    function generated() {
        return timestamp(window.output.generatedMillis);
    }

    function errors() {
        var iterator = new Object();
        iterator.counter = 0;
        iterator.next = function () {
            return message(window.output.errors[iterator.counter++],
                           getStringStore(window.output.strings));
        };
        iterator.hasNext = function () {
            return iterator.counter < window.output.errors.length;
        };
        return iterator;
    }

    function statistics() {
        if (!_statistics) {
            var statData = window.output.stats;
            _statistics = stats.Statistics(statData[0], statData[1], statData[2]);
        }
        return _statistics;
    }

    function getStringStore(strings) {

        function getText(id) {
            var text = strings[id];
            if (!text)
                return '';
            if (text[0] == '*')
                return text.substring(1);
            var extracted = extract(text);
            strings[id] = "*"+extracted;
            return extracted;
        }

        function extract(text) {
            var decoded = JXG.Util.Base64.decodeAsArray(text);
            var extracted = (new JXG.Util.Unzip(decoded)).unzip()[0][0];
            return JXG.Util.utf8Decode(extracted);
        }

        function get(id) {
            if (id == undefined) return undefined;
            if (id == null) return null;
            return getText(id);
        }

        return {get: get};
    }

    return {
        suite: suite,
        errors: errors,
        find: findById,
        findPathTo: findPathTo,
        generated: generated,
        statistics: statistics,
        getStringStore: getStringStore
    };

}();
<|endoftext|>


<commit_before>const assert = require('assert');
const chai = require('chai');
const chaiHttp = require('chai-http');
const app = require('../../../src/app');
const { API_HOST } = require('../../../config/globals');

chai.use(chaiHttp);

describe('link service', () => {
	const service = app.service('link');
	it('registered the links service', () => {
		assert.ok(service);
	});

	it(`generates a link of length ${service.Model.linkLength} that has the correct target set`, function test() {
		this.timeout(10000);

		const url = `${API_HOST}/`;
		return service.create({ target: url })
			.then((data) => {
				chai.expect(data._id).to.have.lengthOf(service.Model.linkLength);
				chai.expect(data.target).to.equal(url);
				return Promise.resolve(data._id);
			})
			.then((id) => new Promise((resolve, reject) => {
				chai.request(app)
					.get(`/link/${id}`)
					.end((error, result) => {
						if (error) return reject(error);
						chai.expect(result.redirects[0]).to.equal(url);
						return resolve();
					});
			}));
	});
});
<commit_msg>make linktest work on local<commit_after>const assert = require('assert');
const chai = require('chai');
const chaiHttp = require('chai-http');
const app = require('../../../src/app');
const { API_HOST } = require('../../../config/globals');

chai.use(chaiHttp);

describe('link service', () => {
	let server;

	before((done) => {
		server = app.listen(3031, done);
	});

	after((done) => {
		server.close(done);
	});

	const service = app.service('link');
	it('registered the links service', () => {
		assert.ok(service);
	});

	it(`generates a link of length ${service.Model.linkLength} that has the correct target set`, function test() {
		this.timeout(10000);

		const url = 'localhost:3031/';
		return service.create({ target: url })
			.then((data) => {
				chai.expect(data._id).to.have.lengthOf(service.Model.linkLength);
				chai.expect(data.target).to.equal(url);
				return Promise.resolve(data._id);
			})
			.then((id) => new Promise((resolve, reject) => {
				chai.request(app)
					.get(`/link/${id}`)
					.end((error, result) => {
						if (error) return reject(error);
						chai.expect(result.redirects[0]).to.equal(url);
						return resolve();
					});
			}));
	});
});
<|endoftext|>