<commit_before>'use strict';
var request = require('request'),
    async = require('async');
var error = {
        url: '',
        avatar: '/avatar/ServerCooties',
        author: 'ServerCooties',
        body: '
+++Error At Address: 14, Treacle Mine Road, Ankh-Morpork+++' +
            '
+++Divide By Cucumber Error. Please Reinstall Universe And' +
            ' Reboot +++
',
        name: '',
        authorTitle: ''
    },
    avatars = {},
    definitions = [error],
    users = {},
    host = 'http://what.thedailywtf.com';

function getAvatarPath(username, callback) {
    request(host + '/users/' + username + '.json', function (err, _, body) {
        var letter = '/letter_avatar/' + username +
            '/45/3_af0dc75e546be11ab6c09c8b9d61c787.png';
        if (err) {
            return callback(null, letter);
        }
        try {
            body = JSON.parse(body);
            if (!body.user.avatar_template) {
                return callback(null, letter);
            }

            callback(null, body.user.avatar_template.replace('{size}', '45'));
        } catch (__) {
            callback(null, letter);
        }
    });
}

function getAvatar(username, callback) {
    getAvatarPath(username, function (_, path) {
        var req = request(host + path),
            parts = [],
            res;
        req.on('error', callback);
        req.on('data', function (d) {
            parts.push(d);
        });
        req.on('response', function (resp) {
            res = resp;
        });
        req.on('end', function () {
            callback(null, {
                retrievedAt: Date.now(),
                contentType: res.headers['content-type'],
                lastModified: res.headers['last-modified'],
                data: Buffer.concat(parts)
            });
        });
    });
}

function serve(avatar, response) {
    response.writeHead(200, {
        'Content-Type': avatar.contentType,
        'Last-Modified': avatar.lastModified
    });
    response.write(avatar.data, 'binary');
    response.end();
}

exports.serveAvatar = function serveAvatar(uri, _, response) {
    var username = /[/]([^/]+)$/.exec(uri)[1];
    if (avatars[username]) {
        return serve(avatars[username], response);
    }
    getAvatar(username, function (err, avatar) {
        if (err) {
            response.writeHead(500);
            response.write(err, 'binary');
            return response.end();
        }
        avatars[username] = avatar;
        serve(avatar, response);
    });
};

function getPosts(id, complete) {
    var base = '/t/' + id + '/posts.json?include_raw=1';
    request(host + base + '&post_ids=0', function (err, _, topic) {
        var posts, results = [];
        try {
            posts = JSON.parse(topic).post_stream.stream;
        } catch (e) {
            err = e;
        }
        if (err) {
            return complete([]);
        }
        async.whilst(function () {
            return posts.length > 0;
        }, function (next) {
            var part = [];
            while (part.length < 100 && posts.length > 0) {
                part.push(posts.shift());
            }
            part = part.join('&post_ids[]=');
            request(host + base + '&post_ids[]=' + part,
                function (err2, resp, defs) {
                    if (err2 || resp.statusCode !== 200) {
                        return next();
                    }
                    try {
                        defs = JSON.parse(defs).post_stream.posts;
                    } catch (e) {
                        return next(e);
                    }
                    results = results.concat(defs.filter(function (f) {
                        return f.wiki && f.post_number > 1;
                    }).map(function (post) {
                        return {
                            url: host + '/p/' + post.id,
                            avatar: '/avatar/' + post.username,
                            author: post.username,
                            body: post.cooked,
                            name: post.name,
                            authorTitle: post.user_title
                        };
                    }));
                    next();
                });
        }, function () {
            complete(results);
        });
    });
}

function loadDefinitions(callback) {
    getPosts(3866, function (defs) {
        definitions = defs || [error];
        var usr = definitions.map(function (d) {
            return d.author;
        });
        usr.push('ServerCooties');
        users = {};
        usr.forEach(function (u) {
            users[u] = users[u] ? users[u] + 1 : 1;
        });
        callback();
    });
}

exports.getQuote = function getQuote() {
    var def = definitions[Math.floor(Math.random() * definitions.length)];
    def.body = def.body.replace(/(src|href)="([^"]+)"/g,
        function (_, prefix, value) {
            if (value.substr(0, 2) === '//') {
                value = 'http:' + value;
            }
            if (value[0] === '/') {
                value = host + value;
            }
            return prefix + '="' + value + '"';
        });
    return def;
};

async.forever(function (next) {
    var refresh = 5 * 60 * 60 * 1000;
    loadDefinitions(function () {
        console.log('quotes loaded'); //eslint-disable-line no-console
        var now = Date.now() - refresh;
        async.each(Object.keys(users), function (user, innerNext) {
            if (!avatars[user] || avatars[user].retrievedAt < now) {
                return getAvatar(user, function (err, avatar) {
                    if (!err) {
                        avatars[user] = avatar;
                    }
                    innerNext();
                });
            }
            innerNext();
        });
        setTimeout(next, refresh);
    });
});

async.forever(function (next) {
    var cutoff = Date.now() - 10 * 60 * 1000;
    Object.keys(avatars).forEach(function (key) {
        if (!users[key] && avatars[key].retrievedAt < cutoff) {
            delete users[key];
        }
    });
    setTimeout(next, 60 * 1000);
});
<commit_msg>do not load quotes in devmode unless SOCKQUOTES is truthy<commit_after>'use strict';
var request = require('request'),
    async = require('async');
var error = {
        url: '',
        avatar: '/avatar/ServerCooties',
        author: 'ServerCooties',
        body: '
+++Error At Address: 14, Treacle Mine Road, Ankh-Morpork+++' +
            '
+++Divide By Cucumber Error. Please Reinstall Universe And' +
            ' Reboot +++
',
        name: '',
        authorTitle: ''
    },
    avatars = {},
    definitions = [error],
    users = {},
    host = 'http://what.thedailywtf.com';

function getAvatarPath(username, callback) {
    request(host + '/users/' + username + '.json', function (err, _, body) {
        var letter = '/letter_avatar/' + username +
            '/45/3_af0dc75e546be11ab6c09c8b9d61c787.png';
        if (err) {
            return callback(null, letter);
        }
        try {
            body = JSON.parse(body);
            if (!body.user.avatar_template) {
                return callback(null, letter);
            }

            callback(null, body.user.avatar_template.replace('{size}', '45'));
        } catch (__) {
            callback(null, letter);
        }
    });
}

function getAvatar(username, callback) {
    getAvatarPath(username, function (_, path) {
        var req = request(host + path),
            parts = [],
            res;
        req.on('error', callback);
        req.on('data', function (d) {
            parts.push(d);
        });
        req.on('response', function (resp) {
            res = resp;
        });
        req.on('end', function () {
            callback(null, {
                retrievedAt: Date.now(),
                contentType: res.headers['content-type'],
                lastModified: res.headers['last-modified'],
                data: Buffer.concat(parts)
            });
        });
    });
}

function serve(avatar, response) {
    response.writeHead(200, {
        'Content-Type': avatar.contentType,
        'Last-Modified': avatar.lastModified
    });
    response.write(avatar.data, 'binary');
    response.end();
}

exports.serveAvatar = function serveAvatar(uri, _, response) {
    var username = /[/]([^/]+)$/.exec(uri)[1];
    if (avatars[username]) {
        return serve(avatars[username], response);
    }
    getAvatar(username, function (err, avatar) {
        if (err) {
            response.writeHead(500);
            response.write(err, 'binary');
            return response.end();
        }
        avatars[username] = avatar;
        serve(avatar, response);
    });
};

function getPosts(id, complete) {
    var base = '/t/' + id + '/posts.json?include_raw=1';
    request(host + base + '&post_ids=0', function (err, _, topic) {
        var posts, results = [];
        try {
            posts = JSON.parse(topic).post_stream.stream;
        } catch (e) {
            err = e;
        }
        if (err) {
            return complete([]);
        }
        async.whilst(function () {
            return posts.length > 0;
        }, function (next) {
            var part = [];
            while (part.length < 100 && posts.length > 0) {
                part.push(posts.shift());
            }
            part = part.join('&post_ids[]=');
            request(host + base + '&post_ids[]=' + part,
                function (err2, resp, defs) {
                    if (err2 || resp.statusCode !== 200) {
                        return next();
                    }
                    try {
                        defs = JSON.parse(defs).post_stream.posts;
                    } catch (e) {
                        return next(e);
                    }
                    results = results.concat(defs.filter(function (f) {
                        return f.wiki && f.post_number > 1;
                    }).map(function (post) {
                        return {
                            url: host + '/p/' + post.id,
                            avatar: '/avatar/' + post.username,
                            author: post.username,
                            body: post.cooked,
                            name: post.name,
                            authorTitle: post.user_title
                        };
                    }));
                    next();
                });
        }, function () {
            complete(results);
        });
    });
}

function loadDefinitions(callback) {
    getPosts(3866, function (defs) {
        definitions = defs || [error];
        var usr = definitions.map(function (d) {
            return d.author;
        });
        usr.push('ServerCooties');
        users = {};
        usr.forEach(function (u) {
            users[u] = users[u] ? users[u] + 1 : 1;
        });
        callback();
    });
}

exports.getQuote = function getQuote() {
    var def = definitions[Math.floor(Math.random() * definitions.length)];
    def.body = def.body.replace(/(src|href)="([^"]+)"/g,
        function (_, prefix, value) {
            if (value.substr(0, 2) === '//') {
                value = 'http:' + value;
            }
            if (value[0] === '/') {
                value = host + value;
            }
            return prefix + '="' + value + '"';
        });
    return def;
};

if (process.env.SOCKDEV && !process.env.SOCKQUOTES) {
    async.forever(function (next) {
        var refresh = 5 * 60 * 60 * 1000;
        loadDefinitions(function () {
            console.log('quotes loaded'); //eslint-disable-line no-console
            var now = Date.now() - refresh;
            async.each(Object.keys(users), function (user, innerNext) {
                if (!avatars[user] || avatars[user].retrievedAt < now) {
                    return getAvatar(user, function (err, avatar) {
                        if (!err) {
                            avatars[user] = avatar;
                        }
                        innerNext();
                    });
                }
                innerNext();
            });
            setTimeout(next, refresh);
        });
    });
}

async.forever(function (next) {
    var cutoff = Date.now() - 10 * 60 * 1000;
    Object.keys(avatars).forEach(function (key) {
        if (!users[key] && avatars[key].retrievedAt < cutoff) {
            delete users[key];
        }
    });
    setTimeout(next, 60 * 1000);
});
<|endoftext|>


<commit_before>module.exports = function ($scope, $rootScope, AppService, TechnologyService, UserService, $timeout, API) {

  /**
   * Object context
   * @type {Object}
   */
   var context = this;

  /**
   * Listner to update list when text filter is fired
   * @type {Array}
   */
   $scope.$on('searchChange', function(event, data) {
    context.items = data.technologies;
    $scope.$apply();
  })

  /**
   * List of technologies
   * @type {Array}
   */
   this.getTechnologies = function(){
    TechnologyService.getTechnologies().then(function(){
      context.items = TechnologyService.foundItems;
    });
   }

   this.getTechnologies();

  /**
   * Loading state
   * @type {Boolean}
   */
   this.loading = false;

   this.changeFilters = function(){
    if(context.recommendationFilter == ""){
      context.recommendationFilter = null;
    }
    if(context.lastActivityDateFilter == ""){
      context.lastActivityDateFilter = null;
    }
    TechnologyService.setContentFilters(context.recommendationFilter, context.orderFilter, context.lastActivityDateFilter);
   }

   this.followTechnology = function(idTechnology, $event){
    context.currentElement = $event.currentTarget;
      TechnologyService.followTechnology(idTechnology).then(function(data){
        if(!data.hasOwnProperty('error')){
          changeFollowedClass(context.currentElement);
        }
      });
   }

   function changeFollowedClass(element){
    if(element.className.indexOf('btn-default') > 0){
      element.className = 'btn btn-xs btn-danger';
    }else{
      element.className = 'btn btn-xs btn-default';
    }
    context.currentElement = undefined;
  }

  this.setFollowedClass = function(isFollowedByUser){
    if(isFollowedByUser){
      return 'btn btn-xs btn-danger';
    }
    return 'btn btn-xs btn-default';
  }

  this.deleteTechnology = function(idTechnology){
    if(confirm('Você realmente quer apagar a tecnologia?')) {
      TechnologyService.deleteTechnology(idTechnology).then(function(data){
        if(!data.hasOwnProperty('error')){
          context.getTechnologies();
        }
      });
    }
  }

  /**
   * Page title
   */
   AppService.setPageTitle('Tecnologias');
 }
<commit_msg>[TECG-272]/[TECG-451] Show loading gif<commit_after>module.exports = function ($scope, $rootScope, AppService, TechnologyService, UserService, $timeout, API) {

  /**
   * Object context
   * @type {Object}
   */
   var context = this;

  /**
   * Listner to update list when text filter is fired
   * @type {Array}
   */
   $scope.$on('searchChange', function(event, data) {
    context.items = data.technologies;
    context.loading = false;
    $scope.$apply();
  })

  /**
   * List of technologies
   * @type {Array}
   */
   this.getTechnologies = function(){
    context.loading = true;
    TechnologyService.getTechnologies().then(function(){
      context.items = TechnologyService.foundItems;
      context.loading = false;
    });
   }

   this.getTechnologies();

  /**
   * Loading state
   * @type {Boolean}
   */
   this.loading = true;

   this.changeFilters = function(){
    context.loading = true;
    if(context.recommendationFilter == ""){
      context.recommendationFilter = null;
    }
    if(context.lastActivityDateFilter == ""){
      context.lastActivityDateFilter = null;
    }
    TechnologyService.setContentFilters(context.recommendationFilter, context.orderFilter, context.lastActivityDateFilter);
   }

   this.followTechnology = function(idTechnology, $event){
    context.currentElement = $event.currentTarget;
    TechnologyService.followTechnology(idTechnology).then(function(data){
      if(!data.hasOwnProperty('error')){
        changeFollowedClass(context.currentElement);
      }
    });
   }

   function changeFollowedClass(element){
    if(element.className.indexOf('btn-default') > 0){
      element.className = 'btn btn-xs btn-danger';
    }else{
      element.className = 'btn btn-xs btn-default';
    }
    context.currentElement = undefined;
  }

  this.setFollowedClass = function(isFollowedByUser){
    if(isFollowedByUser){
      return 'btn btn-xs btn-danger';
    }
    return 'btn btn-xs btn-default';
  }

  this.deleteTechnology = function(idTechnology){
    if(confirm('Você realmente quer apagar a tecnologia?')) {
      context.loading = true;
      TechnologyService.deleteTechnology(idTechnology).then(function(data){
        if(!data.hasOwnProperty('error')){
          context.getTechnologies();
        }
      });
    }
  }

  /**
   * Page title
   */
   AppService.setPageTitle('Tecnologias');
 }
<|endoftext|>


<commit_before>$(function() {
	"use strict"
	var target = "p";
	var text = $(target).not(target+" "+target).html();
	var weAreInTag = false;// Means we are beetwen < and >
	var weHaveOpened = false;
	var script = false; // We do not want to do anything beetwen <script> and </script>
	var newText = [];
	for (var i = 0; i <= text.length - 1; i++) {
		if (weAreInTag) {
			if (text[i] == ">") {
				weAreInTag = false;
				var ipt = ""+text[i-1]+text[i-2]+text[i-3];
				if ( ipt == "scr" || ipt == "SCR") {
					script = false;
				};
			};
		}else{
			if (text[i] == "<") {
				weAreInTag = true;
				var scr = ""+text[i+1]+text[i+2]+text[i+3];
				if ( scr == "scr" || scr == "SCR") {
					script = true;
				};
			}else if ( (text[i]=='"'||text[i]=="'") && !script) {

				if (weHaveOpened) {
					newText.push("»");
					weHaveOpened = false;
					continue
				}else{
					newText.push("«");
					weHaveOpened = true;
					continue
				}
			}
		}
		newText.push(text[i]);
	};
	text = newText.join("");
	$(target).empty().html(text);

});<commit_msg>Now we can work on multiple targets;<commit_after>$(function() {
	"use strict"
	var target = "p";
	var elements = $(target).not(target+" "+target);
	elements.each(function(index, elem) {
		var weAreInTag = false;// Means we are beetwen < and >
		var weHaveOpened = false;
		var script = false; // We do not want to do anything beetwen <script> and </script>
		var newText = [];
		var text = $(elem).html();
		for (var i = 0; i <= text.length - 1; i++) {
			if (weAreInTag) {
				if (text[i] == ">") {
					weAreInTag = false;
					var ipt = ""+text[i-1]+text[i-2]+text[i-3];
					if ( ipt == "scr" || ipt == "SCR") {
						script = false;
					};
				};
			}else{
				if (text[i] == "<") {
					weAreInTag = true;
					var scr = ""+text[i+1]+text[i+2]+text[i+3];
					if ( scr == "scr" || scr == "SCR") {
						script = true;
					};
				}else if ( (text[i]=='"'||text[i]=="'") && !script) {

					if (weHaveOpened) {
						newText.push("»");
						weHaveOpened = false;
						continue
					}else{
						newText.push("«");
						weHaveOpened = true;
						continue
					}
				}
			}
			newText.push(text[i]);
		};
		text = newText.join("");
		$(elem).empty().html(text);
	})
});<|endoftext|>


<commit_before>'use strict'

var ObjectId = require("mongodb").ObjectId;
require("mongodb-toolkit");

var DLModels = require('dl-models');
var map = DLModels.map;
var WindingQualitySampling = DLModels.production.spinning.winding.WindingQualitySampling;
var ProductManager = require('../../../master/product-manager');
var MachineManager = require('../../../master/machine-manager');
var UsterManager = require('../../../master/uster-classification-manager');
var BaseManager = require('../../../base-manager');
var i18n = require('dl-i18n');

module.exports = class WindingQualitySamplingManager extends BaseManager {
    constructor(db, user) {
        super(db, user);
        this.collection = this.db.collection(map.production.spinning.winding.collection.WindingQualitySampling);
        this.productManager = new ProductManager(db, user);
        this.machineManager = new MachineManager(db, user);
        this.usterManagerIpiLess = new UsterManager(db, user);
        this.usterManagerIpiGreat = new UsterManager(db, user);
    }

    _getQuery(paging) {
        var deletedFilter = {
            _deleted: false
        }, keywordFilter = {};

        var query = {};
        if (paging.keyword) {
            var regex = new RegExp(paging.keyword, "i");

            var filterSpinning = {
                'spinning': {
                    '$regex': regex
                }
            };
            var filterMachineCode = {
                "machine.code": {
                    '$regex': regex
                }
            };
            var filterMachineName = {
                'machine.name': {
                    '$regex': regex
                }
            };
            var filterThreadCode = {
                "thread.code": {
                    '$regex': regex
                }
            };
            var filterThreadName = {
                "thread.name": {
                    '$regex': regex
                }
            };

            keywordFilter = {
                '$or': [filterSpinning, filterMachineCode, filterMachineName, filterThreadCode, filterThreadName]
            };
        }
        query = { '$and': [deletedFilter, paging.filter, keywordFilter] }
        return query;
    }

    _validate(windingQualitySampling) {
        var errors = {};
        return new Promise((resolve, reject) => {
            var valid = windingQualitySampling;
            var dateNow = new Date();
            var dateProcess = new Date(valid.date);

            var getWindingQuality = this.collection.singleOrDefault({
                "$and" : [{
                        _id : {
                            "$ne" : new ObjectId(valid._id)
                    }
                    },{
                        _deleted : false
                    },{
                        date : dateProcess
                    },{
                        threadName : valid.threadName
                    },{
                        machineId : new ObjectId(valid.machineId)
                    },{
                        spinning : valid.spinning
                }]
            });
            var getMachine = valid.machine && valid.machine._id ? this.machineManager.getSingleByIdOrDefault(valid.machine._id) : Promise.resolve(null);
            var _ipi = (!valid.thin ? 0 : valid.thin) + (!valid.thick ? 0 : valid.thick) + (!valid.neps ? 0 : valid.neps);
            var queryGreat = {
                size : 1,
                page : 1,
                filter : {
                    '$and' : [{
                        threadName : valid.threadName
                    },{
                        ipi : {'$gte' : _ipi}
                    }]
                },
                order : {
                    "ipi" : 1
                }
            };
            var queryLess = {
                size : 1,
                page : 1,
                filter : {
                    '$and' : [{
                        threadName : valid.threadName
                    },{
                        ipi : {'$lt' : _ipi}
                    }]
                },
                order : {
                    "ipi" : -1
                }
            };
            var getUsterGreaterThenIpi = valid.threadName ? this.usterManagerIpiGreat.read(queryGreat) : Promise.resolve(null);
            var getUsterLessThenIpi = valid.threadName ? this.usterManagerIpiLess.read(queryLess) : Promise.resolve(null);

            // 2. begin: Validation.
            Promise.all([getWindingQuality, getMachine, getUsterLessThenIpi, getUsterGreaterThenIpi])
                .then(result =>{
                    var _windingQuality = result[0];
                    var _machine = result[1];
                    var _usterGreatThen = null;
                    var _usterLessThen = null;
                    if(result[2].data.length > 0){
                        for(var a of result[2].data)
                            _usterLessThen = a;
                    }
                    if(result[3].data.length > 0){
                        for(var a of result[3].data)
                            _usterGreatThen = a;
                    }
                    if (!valid.spinning || valid.spinning == '')
                        errors["spinning"] = i18n.__("SpinningProductQuality.spinning.isRequired:%s is required", i18n.__("SpinningProductQuality.spinning._:Spinning")); //"Spinning harus diisi ";
                    else if(_windingQuality)
                        errors["spinning"] = i18n.__(`SpinningProductQuality.spinning.isRequired:%s with same Product, Machine and Date is already exists`, i18n.__("SpinningProductQuality.spinning._:Spinning")); //"Spinning dengan produk, mesin dan tanggal yang sama tidak boleh";

                    if (!valid.date || valid.date == '')
                        errors["date"] = i18n.__("SpinningProductQuality.date.isExists:%s is required", i18n.__("SpinningProductQuality.date._:date")); //"Tanggal tidak boleh kosong";
                    else if (dateProcess > dateNow)
                        errors["date"] = i18n.__("SpinningProductQuality.date.isGreater:%s is greater than today", i18n.__("SpinningProductQuality.date._:Date"));//"Tanggal tidak boleh lebih besar dari tanggal hari ini";

                    if (!valid.machine)
                        errors["machine"] = i18n.__("SpinningProductQuality.machine.name.isRequired:%s is required", i18n.__("SpinningProductQuality.machine.name._:Machine")); //"Nama Mesin tidak boleh kosong";
                    else if(!_machine)
                        errors["machine"] = i18n.__("SpinningProductQuality.machine.name.isRequired:%s is not exists", i18n.__("SpinningProductQuality.machine.name._:Machine")); //"Mesin sudah tidak ada di master mesin";

                    if (!valid.threadName)
                        errors["threadName"] = i18n.__("SpinningProductQuality.threadName.isRequired:%s is required", i18n.__("SpinningProductQuality.threadName._:Thread")); //"Nama Benang tidak boleh kosong";
                    else if(!_usterGreatThen && !_usterLessThen)
                        errors["threadName"] = i18n.__("SpinningProductQuality.threadName.isRequired:%s has no uster classification", i18n.__("SpinningProductQuality.threadName._:Thread")); //"Benang tidak memiliki klassifikasi Uster";

                    if (!valid.U || valid.U == 0)
                        errors["U"] = i18n.__("SpinningProductQuality.U.isRequired:%s is required", i18n.__("SpinningProductQuality.U._:U")); //"U tidak boleh kosong";

                    if (!valid.sys || valid.sys == 0)
                        errors["sys"] = i18n.__("SpinningProductQuality.sys.isRequired:%s is required", i18n.__("SpinningProductQuality.sys._:Sys")); //"Sys tidak boleh kosong";

                    if (!valid.elongation || valid.elongation == 0)
                        errors["elongation"] = i18n.__("SpinningProductQuality.elongation.isRequired:%s is required", i18n.__("SpinningProductQuality.elongation._:Elongation")); //"Elongation tidak boleh kosong";

                    // 2c. begin: check if data has any error, reject if it has.
                     if (Object.getOwnPropertyNames(errors).length > 0) {
                        var ValidationError = require('../../../../validation-error');
                        reject(new ValidationError('data does not pass validation', errors));
                    }
                    valid.machine = _machine;
                    valid.machineId = new ObjectId(_machine._id);
                    if(_usterGreatThen){
                        valid.uster = _usterGreatThen;
                        valid.usterId = new ObjectId(_usterGreatThen._id);
                    }else if(_usterLessThen){
                        valid.uster = _usterLessThen;
                        valid.usterId = new ObjectId(_usterLessThen._id);
                    }
                    if(valid.date)
                        valid.date = dateProcess;
                    valid.ipi = _ipi;

                    if(!valid.stamp)
                        valid = new WindingQualitySampling(valid);
                    valid.stamp(this.user.username, 'manager');
                    resolve(valid);
                })
                .catch(e => {
                    reject(e);
                })
        });
    }

    getWindingQualitySamplingReportByDate(startDate, endDate){
        return new Promise((resolve, reject) => {
            var now = new Date();
            var query = {};
            if(startDate && !endDate){
                query = {
                    "date" : {
                        "$gte" : new Date(startDate)
                    }
                };
            }else if(!startDate && endDate){
                query = {
                    "date" : {
                        "$lte" : new Date(endDate)
                    }
                };
            }else if(startDate && endDate){
                query = {
                    "$and" : [{
                        "date":{
                            "$gte" : new Date(startDate)
                        }
                    },{
                        "date" : {
                            "$lte" : new Date(endDate)
                        }
                    }]
                };
            }else if(!startDate && !endDate){
                query = {
                    "$and" : [{
                        "date":{
                            "$gte" : new Date(1900, 1, 1)
                        }
                    },{
                        "date" : {
                            "$lte" : now
                        }
                    }]
                };
            }
            var order = {
                "date" : -1
            };

            this.collection
                .where(query)
                .order(order)
                .execute()
                .then(Spinning => {
                    resolve(Spinning.data);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

     _createIndexes() {
        var dateIndex = {
            name: `ix_${map.production.spinning.winding.collection.WindingQualitySampling}__updatedDate`,
            key: {
                _updatedDate: -1
            }
        }

        var codeIndex = {
            name: `ix_${map.production.spinning.winding.collection.WindingQualitySampling}_spinning_date_machineId_threadName`,
            key: {
                spinning: 1,
                date: 1,
                machineId: 1,
                threadName: 1
            },
            unique: true
        }

        return this.collection.createIndexes([dateIndex, codeIndex]);
    }
}<commit_msg>update winding quality sampling<commit_after>'use strict'

var ObjectId = require("mongodb").ObjectId;
require("mongodb-toolkit");

var DLModels = require('dl-models');
var map = DLModels.map;
var WindingQualitySampling = DLModels.production.spinning.winding.WindingQualitySampling;
var ProductManager = require('../../../master/product-manager');
var MachineManager = require('../../../master/machine-manager');
var UsterManager = require('../../../master/uster-classification-manager');
var BaseManager = require('../../../base-manager');
var i18n = require('dl-i18n');

module.exports = class WindingQualitySamplingManager extends BaseManager {
    constructor(db, user) {
        super(db, user);
        this.collection = this.db.collection(map.production.spinning.winding.collection.WindingQualitySampling);
        this.productManager = new ProductManager(db, user);
        this.machineManager = new MachineManager(db, user);
        this.usterManagerIpiLess = new UsterManager(db, user);
        this.usterManagerIpiGreat = new UsterManager(db, user);
    }

    _getQuery(paging) {
        var deletedFilter = {
            _deleted: false
        }, keywordFilter = {};

        var query = {};
        if (paging.keyword) {
            var regex = new RegExp(paging.keyword, "i");

            var filterSpinning = {
                'spinning': {
                    '$regex': regex
                }
            };
            var filterMachineCode = {
                "machine.code": {
                    '$regex': regex
                }
            };
            var filterMachineName = {
                'machine.name': {
                    '$regex': regex
                }
            };
            var filterThreadCode = {
                "thread.code": {
                    '$regex': regex
                }
            };
            var filterThreadName = {
                "thread.name": {
                    '$regex': regex
                }
            };

            keywordFilter = {
                '$or': [filterSpinning, filterMachineCode, filterMachineName, filterThreadCode, filterThreadName]
            };
        }
        query = { '$and': [deletedFilter, paging.filter, keywordFilter] }
        return query;
    }

    _validate(windingQualitySampling) {
        var errors = {};
        return new Promise((resolve, reject) => {
            var valid = windingQualitySampling;
            var dateNow = new Date();
            var dateProcess = new Date(valid.date);

            var getWindingQuality = this.collection.singleOrDefault({
                "$and" : [{
                        _id : {
                            "$ne" : new ObjectId(valid._id)
                    }
                    },{
                        _deleted : false
                    },{
                        date : dateProcess
                    },{
                        threadName : valid.threadName
                    },{
                        machineId : new ObjectId(valid.machineId)
                    },{
                        spinning : valid.spinning
                }]
            });
            var getMachine = valid.machine && valid.machine._id ? this.machineManager.getSingleByIdOrDefault(valid.machine._id) : Promise.resolve(null);
            var _ipi = (!valid.thin ? 0 : valid.thin) + (!valid.thick ? 0 : valid.thick) + (!valid.neps ? 0 : valid.neps);
            var queryGreat = {
                size : 1,
                page : 1,
                filter : {
                    '$and' : [{
                        threadName : valid.threadName
                    },{
                        ipi : {'$gte' : _ipi}
                    }]
                },
                order : {
                    "ipi" : 1
                }
            };
            var queryLess = {
                size : 1,
                page : 1,
                filter : {
                    '$and' : [{
                        threadName : valid.threadName
                    },{
                        ipi : {'$lt' : _ipi}
                    }]
                },
                order : {
                    "ipi" : -1
                }
            };
            var getUsterGreaterThenIpi = valid.threadName ? this.usterManagerIpiGreat.read(queryGreat) : Promise.resolve(null);
            var getUsterLessThenIpi = valid.threadName ? this.usterManagerIpiLess.read(queryLess) : Promise.resolve(null);

            // 2. begin: Validation.
            Promise.all([getWindingQuality, getMachine, getUsterLessThenIpi, getUsterGreaterThenIpi])
                .then(result =>{
                    var _windingQuality = result[0];
                    var _machine = result[1];
                    var _usterGreatThen = null;
                    var _usterLessThen = null;
                    if(result[2].data.length > 0){
                        for(var a of result[2].data)
                            _usterLessThen = a;
                    }
                    if(result[3].data.length > 0){
                        for(var a of result[3].data)
                            _usterGreatThen = a;
                    }
                    if (!valid.spinning || valid.spinning == '')
                        errors["spinning"] = i18n.__("WindingQualitySampling.spinning.isRequired:%s is required", i18n.__("WindingQualitySampling.spinning._:Spinning")); //"Spinning harus diisi ";
                    else if(_windingQuality)
                        errors["spinning"] = i18n.__(`WindingQualitySampling.spinning.isRequired:%s with same Product, Machine and Date is already exists`, i18n.__("WindingQualitySampling.spinning._:Spinning")); //"Spinning dengan produk, mesin dan tanggal yang sama tidak boleh";

                    if (!valid.date || valid.date == '')
                        errors["date"] = i18n.__("WindingQualitySampling.date.isExists:%s is required", i18n.__("WindingQualitySampling.date._:date")); //"Tanggal tidak boleh kosong";
                    else if (dateProcess > dateNow)
                        errors["date"] = i18n.__("WindingQualitySampling.date.isGreater:%s is greater than today", i18n.__("WindingQualitySampling.date._:Date"));//"Tanggal tidak boleh lebih besar dari tanggal hari ini";

                    if (!valid.machine)
                        errors["machine"] = i18n.__("WindingQualitySampling.machine.name.isRequired:%s is required", i18n.__("WindingQualitySampling.machine.name._:Machine")); //"Nama Mesin tidak boleh kosong";
                    else if(!_machine)
                        errors["machine"] = i18n.__("WindingQualitySampling.machine.name.isRequired:%s is not exists", i18n.__("WindingQualitySampling.machine.name._:Machine")); //"Mesin sudah tidak ada di master mesin";

                    if (!valid.threadName)
                        errors["threadName"] = i18n.__("WindingQualitySampling.threadName.isRequired:%s is required", i18n.__("WindingQualitySampling.threadName._:Thread")); //"Nama Benang tidak boleh kosong";
                    else if(!_usterGreatThen && !_usterLessThen)
                        errors["threadName"] = i18n.__("WindingQualitySampling.threadName.isRequired:%s has no uster classification", i18n.__("WindingQualitySampling.threadName._:Thread")); //"Benang tidak memiliki klassifikasi Uster";

                    if (!valid.U || valid.U == 0)
                        errors["U"] = i18n.__("WindingQualitySampling.U.isRequired:%s is required", i18n.__("WindingQualitySampling.U._:U")); //"U tidak boleh kosong";

                    if (!valid.sys || valid.sys == 0)
                        errors["sys"] = i18n.__("WindingQualitySampling.sys.isRequired:%s is required", i18n.__("WindingQualitySampling.sys._:Sys")); //"Sys tidak boleh kosong";

                    if (!valid.elongation || valid.elongation == 0)
                        errors["elongation"] = i18n.__("WindingQualitySampling.elongation.isRequired:%s is required", i18n.__("WindingQualitySampling.elongation._:Elongation")); //"Elongation tidak boleh kosong";

                    // 2c. begin: check if data has any error, reject if it has.
                     if (Object.getOwnPropertyNames(errors).length > 0) {
                        var ValidationError = require('../../../../validation-error');
                        reject(new ValidationError('data does not pass validation', errors));
                    }
                    valid.machine = _machine;
                    valid.machineId = new ObjectId(_machine._id);
                    if(_usterGreatThen){
                        valid.uster = _usterGreatThen;
                        valid.usterId = new ObjectId(_usterGreatThen._id);
                    }else if(_usterLessThen){
                        valid.uster = _usterLessThen;
                        valid.usterId = new ObjectId(_usterLessThen._id);
                    }
                    if(valid.date)
                        valid.date = dateProcess;
                    valid.ipi = _ipi;

                    if(!valid.stamp)
                        valid = new WindingQualitySampling(valid);
                    valid.stamp(this.user.username, 'manager');
                    resolve(valid);
                })
                .catch(e => {
                    reject(e);
                })
        });
    }

    getWindingQualitySamplingReportByDate(startDate, endDate){
        return new Promise((resolve, reject) => {
            var now = new Date();
            var query = {};
            if(startDate && !endDate){
                query = {
                    "date" : {
                        "$gte" : new Date(startDate)
                    }
                };
            }else if(!startDate && endDate){
                query = {
                    "date" : {
                        "$lte" : new Date(endDate)
                    }
                };
            }else if(startDate && endDate){
                query = {
                    "$and" : [{
                        "date":{
                            "$gte" : new Date(startDate)
                        }
                    },{
                        "date" : {
                            "$lte" : new Date(endDate)
                        }
                    }]
                };
            }else if(!startDate && !endDate){
                query = {
                    "$and" : [{
                        "date":{
                            "$gte" : new Date(1900, 1, 1)
                        }
                    },{
                        "date" : {
                            "$lte" : now
                        }
                    }]
                };
            }
            var order = {
                "date" : -1
            };

            this.collection
                .where(query)
                .order(order)
                .execute()
                .then(Spinning => {
                    resolve(Spinning.data);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

     _createIndexes() {
        var dateIndex = {
            name: `ix_${map.production.spinning.winding.collection.WindingQualitySampling}__updatedDate`,
            key: {
                _updatedDate: -1
            }
        }

        var codeIndex = {
            name: `ix_${map.production.spinning.winding.collection.WindingQualitySampling}_spinning_date_machineId_threadName`,
            key: {
                spinning: 1,
                date: 1,
                machineId: 1,
                threadName: 1
            },
            unique: true
        }

        return this.collection.createIndexes([dateIndex, codeIndex]);
    }
}<|endoftext|>


<commit_before>import React from 'react'
import { render, unmountComponentAtNode } from 'react-dom'
import { act } from 'react-dom/test-utils'
import { useSelector } from 'react-redux'
import Todos from './Todos'

jest.mock('react-redux')

describe('Should test the sample component', () => {
  let container = null
  const expectedTodos = []

  beforeEach(() => {
    // setup a DOM element as a render target
    container = document.createElement('div')
    document.body.appendChild(container)
  })

  afterEach(() => {
    // cleanup on exiting
    unmountComponentAtNode(container)
    container.remove()
    container = null
  })

  it('show empty text when there is no text', () => {
    useSelector.mockReturnValue(expectedTodos)
    act(() => {
      render(<Todos />, container)
    })
    const listItem = container.querySelectorAll('li')
    expect(container.textContent).toBe('Todo list is empty')
  })

  it('should have on TodoItem when there is one to do', () => {
    let moreTodo = {
      id: 'todoId',
      name: 'Sample todo',
      text: 'This is for testing todos'
    }
    expectedTodos.push(moreTodo)
    useSelector.mockReturnValue(expectedTodos)
    act(() => {
      render(<Todos />, container)
    })
    const listItems = container.querySelectorAll('li')
        // this is not a real id, so only text which can be visible is Delete
    expect(listItems[0].textContent).toBe('Delete')
  })
})
<commit_msg>style(example): change the global variables to local variables<commit_after>import React from 'react'
import { render, unmountComponentAtNode } from 'react-dom'
import { act } from 'react-dom/test-utils'
import { useSelector } from 'react-redux'
import Todos from './Todos'

jest.mock('react-redux')

describe('Should test the Todos Component', () => {
  let container = null

  beforeEach(() => {
    // setup a DOM element as a render target
    container = document.createElement('div')
    document.body.appendChild(container)
  })

  afterEach(() => {
    // cleanup on exiting
    unmountComponentAtNode(container)
    container.remove()
    container = null
  })

  it('show empty text when the todo list is empty', () => {
    let todos = []
    useSelector.mockReturnValue(todos)

    act(() => {
      render(<Todos />, container)
    })

    container.querySelectorAll('li')
    expect(container.textContent).toBe('Todo list is empty')
  })

  it('should have one TodoItem in the list', () => {
    let todos = [
      {
        id: 'todoId',
        name: 'Sample todo',
        text: 'This is for testing todos'
      }
    ]

    useSelector.mockReturnValue(todos)
    act(() => {
      render(<Todos />, container)
    })

    const listItems = container.querySelectorAll('li')

    // this is not a real id, so only text which can be visible is Delete
    expect(listItems[0].textContent).toBe('Delete')
  })
})
<|endoftext|>


<commit_before>jQuery.fn.definePlugin('Upgrade', function($){
	'use strict';

	return {
		init:function(){
			this.markup();
			this.bindEvents();
		},
		getDefaults: function(){
			return {
                class : 'btn-upgrade',
                vendorProductId: '',
				cycle: 'MONTHLY'
			};
		},
		markup: function() {
            var className = "submit uilib-btn " + this.options.class;
			this.$el.append('<button class="' + className + '">' + this.options.text + '</button>');
        },
		bindEvents: function() {
			this.$el.find('.uilib-btn').on('click', this.upgrade.bind(this));
		},
		getValue: function() {
		},
		setValue: function(value) {
		},
        upgrade: function() {
            var vendorProductId = this.options.vendorProductId;
			Wix.Billing.openBillingPageForProduct(vendorProductId, this.options.cycle, function () {
                var popup = Wix.UI.create({ctrl: 'Popup',
                    options: {buttonSet: 'okCancel', fixed:true, title: 'Ooops something when wrong...', content: vendorProductId  + ' was not found.'}});
                popup.getCtrl().open();
            });
		}
	};

});
<commit_msg>cleanup<commit_after>jQuery.fn.definePlugin('Upgrade', function ($) {
    'use strict';

    return {
        init: function () {
            this.markup();
            this.bindEvents();
        },
        getDefaults: function () {
            return {
                class: 'btn-upgrade',
                vendorProductId: '',
                cycle: 'MONTHLY'
            };
        },
        markup: function () {
            var className = "submit uilib-btn " + this.options.class;
            this.$el.append('<button class="' + className + '">' + this.options.text + '</button>');
        },
        bindEvents: function () {
            this.$el.find('.uilib-btn').on('click', this.upgrade.bind(this));
        },
        getValue: function () {
        },
        setValue: function (value) {
        },
        upgrade: function () {
            var vendorProductId = this.options.vendorProductId;
            Wix.Billing.openBillingPageForProduct(vendorProductId, this.options.cycle, function () {
                var popup = Wix.UI.create({ctrl: 'Popup',
                    options: {buttonSet: 'okCancel', fixed: true, title: 'Ooops something when wrong...', content: vendorProductId + ' was not found.'}});
                popup.getCtrl().open();
            });
        }
    };

});
<|endoftext|>


<commit_before>macro .. {
	case infix {
		$start:lit | _ $end:lit
	} => {
		var start = unwrapSyntax(#{$end});
		var end   = unwrapSyntax(#{$start});
		var steps = Math.abs(end - start);
		if (steps > 10) {
			return #{ _range ($start, $end) };
		}

		return #{ _inline ($start, $end) };
	}
}

macro _inline {
	case {
		_ ( $start, $end )
	} => {
		var start = unwrapSyntax(#{$start});
		var end   = unwrapSyntax(#{$end});
		var inline = [];

		for (start; start < end; start++) {
			inline.push(makeValue(start, #{here}));
			inline.push(makePunc(",", #{here}));
		}
		inline.push(makeValue(end, #{here}));
		return [makeDelim("[]",inline, #{here})];
	}
}

macro _range {
	rule  {
		( $start, $end )
	} => {
		(function (start, end) {
			var range = [];

			for (start; start <= end; start++) {
				range.push(start);
		  	}

			return range;
		})($start, $end)
	}
}

var x = 0 .. 9;
3 .. 20

<commit_msg>removes whitespace and examples<commit_after>macro .. {
	case infix {
		$start:lit | _ $end:lit
	} => {
		var start = unwrapSyntax(#{$end});
		var end   = unwrapSyntax(#{$start});
		var steps = Math.abs(end - start);
		if (steps > 10) {
			return #{ _range ($start, $end) };
		}

		return #{ _inline ($start, $end) };
	}
}

macro _inline {
	case {
		_ ( $start, $end )
	} => {
		var start = unwrapSyntax(#{$start});
		var end   = unwrapSyntax(#{$end});
		var inline = [];

		for (start; start < end; start++) {
			inline.push(makeValue(start, #{here}));
			inline.push(makePunc(",", #{here}));
		}
		inline.push(makeValue(end, #{here}));
		return [makeDelim("[]",inline, #{here})];
	}
}

macro _range {
	rule  {
		( $start, $end )
	} => {
		(function (start, end) {
			var range = [];

			for (start; start <= end; start++) {
				range.push(start);
		  	}

			return range;
		})($start, $end)
	}
}
<|endoftext|>


<commit_before>const path = require('path'),

    HappyPack = require('happypack'),
    autoprefixer = require('autoprefixer'),

    config = require('./config.js'),
    utils = require('./utils.js'),

    cssLoaderConfig = ['style-loader', {
        loader: 'css-loader',
        options: {
            importLoaders: 1
        }
    }, {
        loader: 'postcss-loader',
        options: {
            ident: 'postcss',
            plugins: [
                autoprefixer({
                    broswer: 'last 5 versions'
                })
            ]
        }
    }];

function resolve(dir) {
    return path.join(__dirname, '..', dir);
}

module.exports = {

    entry: {
        app: './examples/index.js'
    },

    output: {
        path: config.build.assetsRoot,
        filename: '[name].js',
        publicPath: config.assetsPublicPath
    },

    resolve: {
        extensions: ['.js', '.json'],
        alias: {
            'src': resolve('src'),
            'examples': resolve('examples'),
            'assets': resolve('examples/assets'),
            'scss': resolve('examples/assets/scss'),
            'stylesheets': resolve('examples/assets/stylesheets'),
            'components': resolve('examples/components'),
            'containers': resolve('examples/containers'),
            'modules': resolve('examples/containers/app/modules'),
            'dist': resolve('dist'),
            'vendors': resolve('examples/vendors'),
            'reduxes': resolve('examples/reduxes'),
            'docs': resolve('docs')
        }
    },

    module: {
        rules: [{
            test: /\.js$/,
            use: 'happypack/loader?id=js',
            include: [resolve('examples'), resolve('src')]
        }, {
            test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
            loader: 'url-loader',
            options: {
                limit: 1000,
                name: utils.assetsSubPath('img/[name].[hash:7].[ext]')
            }
        }, {
            test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
            loader: 'url-loader',
            options: {
                limit: 1000,
                name: utils.assetsSubPath('fonts/[name].[hash:7].[ext]')
            }
        }, {
            test: /\.scss$/,
            use: [...cssLoaderConfig, 'fast-sass-loader']
        }, {
            test: /\.css$/,
            use: cssLoaderConfig
        }, {
            test: /\.ht?ml/,
            loader: 'html-loader'
        }]
    },

    plugins: [
        new HappyPack({
            id: 'js',
            loaders: [{
                loader: 'babel-loader?cacheDirectory=true'
            }],
            threads: 4,
            verbose: false
        })
    ]

};
<commit_msg>update postcss<commit_after>const path = require('path'),

    HappyPack = require('happypack'),

    config = require('./config.js'),
    utils = require('./utils.js'),

    cssLoaderConfig = ['style-loader', {
        loader: 'css-loader',
        options: {
            importLoaders: 1
        }
    }, {
        loader: 'postcss-loader',
        options: {
            postcssOptions: {
                plugins: [
                    'postcss-preset-env'
                ]
            }
        }
    }];

function resolve(dir) {
    return path.join(__dirname, '..', dir);
}

module.exports = {

    entry: {
        app: './examples/index.js'
    },

    output: {
        path: config.build.assetsRoot,
        filename: '[name].js',
        publicPath: config.assetsPublicPath
    },

    resolve: {
        extensions: ['.js', '.json'],
        alias: {
            'src': resolve('src'),
            'examples': resolve('examples'),
            'assets': resolve('examples/assets'),
            'scss': resolve('examples/assets/scss'),
            'stylesheets': resolve('examples/assets/stylesheets'),
            'components': resolve('examples/components'),
            'containers': resolve('examples/containers'),
            'modules': resolve('examples/containers/app/modules'),
            'dist': resolve('dist'),
            'vendors': resolve('examples/vendors'),
            'reduxes': resolve('examples/reduxes'),
            'docs': resolve('docs')
        }
    },

    module: {
        rules: [{
            test: /\.js$/,
            use: 'happypack/loader?id=js',
            include: [resolve('examples'), resolve('src')]
        }, {
            test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
            loader: 'url-loader',
            options: {
                limit: 1000,
                name: utils.assetsSubPath('img/[name].[hash:7].[ext]')
            }
        }, {
            test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
            loader: 'url-loader',
            options: {
                limit: 1000,
                name: utils.assetsSubPath('fonts/[name].[hash:7].[ext]')
            }
        }, {
            test: /\.scss$/,
            use: [...cssLoaderConfig, 'fast-sass-loader']
        }, {
            test: /\.css$/,
            use: cssLoaderConfig
        }, {
            test: /\.ht?ml/,
            loader: 'html-loader'
        }]
    },

    plugins: [
        new HappyPack({
            id: 'js',
            loaders: [{
                loader: 'babel-loader?cacheDirectory=true'
            }],
            threads: 4,
            verbose: false
        })
    ]

};
<|endoftext|>


<commit_before>'use strict';

var GLClient = angular.module('GLClient', [
    'ngAria',
    'ngRoute',
    'ui.bootstrap',
    'flow',
    'monospaced.elastic',
    'pascalprecht.translate',
    'GLServices',
    'GLDirectives',
    'GLFilters'
  ]).
  config(['$compileProvider', '$routeProvider', '$translateProvider', '$tooltipProvider',
    function($compileProvider, $routeProvider, $translateProvider, $tooltipProvider) {

    $compileProvider.debugInfoEnabled(false);

    $routeProvider.
      when('/wizard', {
        templateUrl: 'views/wizard/main.html',
        controller: 'WizardCtrl',
        header_title: 'Platform Wizard',
        header_subtitle: 'Step-by-step setup'
      }).
      when('/submission', {
        templateUrl: 'views/submission/main.html',
        controller: 'SubmissionCtrl',
        header_title: '',
        header_subtitle: ''
      }).
      when('/receipt', {
        templateUrl: 'views/receipt.html',
        controller: 'ReceiptController',
        header_title: '',
        header_subtitle: ''
      }).
      when('/status/:tip_id', {
        templateUrl: 'views/receiver/tip.html',
        controller: 'TipCtrl',
        header_title: 'Receiver Interface',
        header_subtitle: 'Tip Status Page'
      }).
      when('/status', {
        templateUrl: 'views/whistleblower/tip.html',
        controller: 'TipCtrl',
        header_title: 'Whistleblower Interface',
        header_title: '',
        header_subtitle: ''
      }).
      when('/forcedpasswordchange', {
        templateUrl: 'views/forced_password_change.html',
        controller: 'ForcedPasswordChangeCtrl',
        header_title: 'Change your password',
        header_subtitle: ''
      }).
      when('/receiver/preferences', {
        templateUrl: 'views/receiver/preferences.html',
        controller: 'PreferencesCtrl',
        header_title: 'Receiver Interface',
        header_subtitle: 'Preferences'
      }).
      when('/receiver/tips', {
        templateUrl: 'views/receiver/tips.html',
        controller: 'ReceiverTipsCtrl',
        header_title: 'Receiver Interface',
        header_subtitle: 'List of submissions'
      }).
      when('/admin/landing', {
        templateUrl: 'views/admin/landing.html',
        controller: 'AdminCtrl',
        header_title: 'Administration Interface',
        header_subtitle: 'Landing Page'
      }).
      when('/admin/content', {
        templateUrl: 'views/admin/content.html',
        controller: 'AdminCtrl',
        header_title: 'Administration Interface',
        header_subtitle: 'Content Settings'
      }).
      when('/admin/contexts', {
        templateUrl: 'views/admin/contexts.html',
        controller: 'AdminCtrl',
        header_title: 'Administration Interface',
        header_subtitle: 'Contexts Configuration'
      }).
      when('/admin/fields', {
        templateUrl: 'views/admin/field_templates.html',
        controller: 'AdminCtrl',
        header_title: 'Administration Interface',
        header_subtitle: 'Fields Configuration'
      }).
      when('/admin/users', {
        templateUrl: 'views/admin/users.html',
        controller: 'AdminCtrl',
        header_title: 'Administration Interface',
        header_subtitle: 'Users Configuration'
      }).
      when('/admin/receivers', {
        templateUrl: 'views/admin/receivers.html',
        controller: 'AdminCtrl',
        header_title: 'Administration Interface',
        header_subtitle: 'Receivers Configuration'
      }).
      when('/admin/mail', {
        templateUrl: 'views/admin/mail.html',
        controller: 'AdminCtrl',
        header_title: 'Administration Interface',
        header_subtitle: 'Email Configuration'
      }).
      when('/admin/advanced_settings', {
        templateUrl: 'views/admin/advanced.html',
        controller: 'AdminCtrl',
        header_title: 'Administration Interface',
        header_subtitle: 'Advanced Settings'
      }).
      when('/user/preferences', {
        templateUrl: 'views/user/preferences.html',
        controller: 'PreferencesCtrl',
        header_title: 'User Preferences',
        header_subtitle: ''
      }).
      when('/admin/overview/users', {
        templateUrl: 'views/admin/users_overview.html',
        controller: 'OverviewCtrl',
        header_title: 'Administration Interface',
        header_subtitle: 'Users Overview'
      }).
      when('/admin/overview/tips', {
        templateUrl: 'views/admin/tips_overview.html',
        controller: 'OverviewCtrl',
        header_title: 'Administration Interface',
        header_subtitle: 'Tips Overview'
      }).
      when('/admin/overview/files', {
        templateUrl: 'views/admin/files_overview.html',
        controller: 'OverviewCtrl',
        header_title: 'Administration Interface',
        header_subtitle: 'Files Overview'
      }).
      when('/admin/anomalies', {
        templateUrl: 'views/admin/anomalies.html',
        controller: 'AnomaliesCtrl',
        header_title: 'Administration Interface',
        header_subtitle: 'Anomalies'
      }).
      when('/admin/stats', {
        templateUrl: 'views/admin/stats.html',
        controller: 'StatisticsCtrl',
        header_title: 'Administration Interface',
        header_subtitle: 'System Stats'
      }).
      when('/admin/activities', {
        templateUrl: 'views/admin/activities.html',
        controller: 'ActivitiesCtrl',
        header_title: 'Administration Interface',
        header_subtitle: 'Recent Activities'
      }).
      when('/admin', {
        templateUrl: 'views/login.html',
        controller: 'LoginCtrl',
        header_title: 'Login',
        header_subtitle: ''
      }).
      when('/custodian', {
        templateUrl: 'views/login.html',
        controller: 'LoginCtrl',
        header_title: 'Login',
        header_subtitle: ''
      }).
      when('/login', {
        templateUrl: 'views/login.html',
        controller: 'LoginCtrl',
        header_title: 'Login',
        header_subtitle: ''
      }).
      when('/start', {
        templateUrl: 'views/home.html',
        controller: 'HomeCtrl',
        header_title: '',
        header_subtitle: ''
      }).
      when('/', {
        templateUrl: 'views/home.html',
        controller: 'HomeCtrl',
        header_title: '',
        header_subtitle: ''
      }).
      otherwise({
        redirectTo: '/'
      });

      $translateProvider.useStaticFilesLoader({
        prefix: 'l10n/',
        suffix: '.json'
      });

      $translateProvider.useSanitizeValueStrategy('escape');

      $tooltipProvider.options({appendToBody: true});
}]).
  config(['flowFactoryProvider', function (flowFactoryProvider) {
    flowFactoryProvider.defaults = {
        chunkSize: 1 * 1024 * 1024,
        forceChunkSize: true,
        testChunks: false,
        simultaneousUploads: 1,
        generateUniqueIdentifier: function (file) {
          return Math.random() * 1000000 + 1000000;
        }
    };
}]).
  factory("stacktraceService", function() {
    return({
      print: StackTrace.get()
    });
}).
  config(exceptionConfig).
  run(['$http', '$rootScope', '$location', function ($http, $rootScope, $location) {
     $rootScope.successes = [];
     $rootScope.errors = [];
     $rootScope.loginInProgress = false;

     var globaleaksRequestInterceptor = function(data, headers) {
        headers = angular.extend(headers(), $rootScope.get_auth_headers());
        return data;
    };

    $http.defaults.transformRequest.push(globaleaksRequestInterceptor);

    // register listener to watch route changes
    $rootScope.$on("$routeChangeStart", function(event, next, current) {
      var path = $location.path();
      var embedded = '/embedded/';

      if (path.substr(0, embedded.length) === embedded) {
        $rootScope.embedded = true;
        var search = $location.search();
        if (Object.keys(search).length === 0) {
          $location.path(path.replace("/embedded/", "/"));
          $location.search("embedded=true");
        } else {
          $location.url($location.url().replace("/embedded/", "/") + "&embedded=true");
        }
      }
    });

    $rootScope.$on('$routeChangeSuccess', function (event, current, previous) {
        if (current.$$route) {
          $rootScope.successes = [];
          $rootScope.errors = [];
          $rootScope.header_title = current.$$route.header_title;
          $rootScope.header_subtitle = current.$$route.header_subtitle;
        }
    });

    $rootScope.anonymous = false;
    $rootScope.embedded = false;
}]);

exceptionConfig.$inject = ['$provide'];

function exceptionConfig($provide) {
    $provide.decorator('$exceptionHandler', extendExceptionHandler);
}

extendExceptionHandler.$inject = ['$delegate', '$injector', '$window', 'stacktraceService'];

function extendExceptionHandler($delegate, $injector, $window, stacktraceService) {
    return function(exception, cause) {

        var $rootScope = $injector.get('$rootScope');

        if ($rootScope.exceptions_count === undefined) {
          $rootScope.exceptions_count = 0;
        }

        $rootScope.exceptions_count += 1;

        if ($rootScope.exceptions_count >= 3) {
          // Give each client the ability to forward only the first 3 exceptions
          // scattered; this is also important to avoid looping exceptions to
          // cause looping POST requests.
          return;
        }

        $delegate(exception, cause);

        var errorMessage = exception.toString();
        var stackTrace = stacktraceService.print({e: exception});

        var errorData = angular.toJson({
          errorUrl: $window.location.href,
          errorMessage: errorMessage,
          stackTrace: stackTrace,
          agent: navigator.userAgent
        });

        var $http = $injector.get('$http');

        $http.post('exception', errorData);
    };
}
<commit_msg>Align usage of StackTrack.js to latest version<commit_after>'use strict';

var GLClient = angular.module('GLClient', [
    'ngAria',
    'ngRoute',
    'ui.bootstrap',
    'flow',
    'monospaced.elastic',
    'pascalprecht.translate',
    'GLServices',
    'GLDirectives',
    'GLFilters'
  ]).
  config(['$compileProvider', '$routeProvider', '$translateProvider', '$tooltipProvider',
    function($compileProvider, $routeProvider, $translateProvider, $tooltipProvider) {

    $compileProvider.debugInfoEnabled(false);

    $routeProvider.
      when('/wizard', {
        templateUrl: 'views/wizard/main.html',
        controller: 'WizardCtrl',
        header_title: 'Platform Wizard',
        header_subtitle: 'Step-by-step setup'
      }).
      when('/submission', {
        templateUrl: 'views/submission/main.html',
        controller: 'SubmissionCtrl',
        header_title: '',
        header_subtitle: ''
      }).
      when('/receipt', {
        templateUrl: 'views/receipt.html',
        controller: 'ReceiptController',
        header_title: '',
        header_subtitle: ''
      }).
      when('/status/:tip_id', {
        templateUrl: 'views/receiver/tip.html',
        controller: 'TipCtrl',
        header_title: 'Receiver Interface',
        header_subtitle: 'Tip Status Page'
      }).
      when('/status', {
        templateUrl: 'views/whistleblower/tip.html',
        controller: 'TipCtrl',
        header_title: 'Whistleblower Interface',
        header_title: '',
        header_subtitle: ''
      }).
      when('/forcedpasswordchange', {
        templateUrl: 'views/forced_password_change.html',
        controller: 'ForcedPasswordChangeCtrl',
        header_title: 'Change your password',
        header_subtitle: ''
      }).
      when('/receiver/preferences', {
        templateUrl: 'views/receiver/preferences.html',
        controller: 'PreferencesCtrl',
        header_title: 'Receiver Interface',
        header_subtitle: 'Preferences'
      }).
      when('/receiver/tips', {
        templateUrl: 'views/receiver/tips.html',
        controller: 'ReceiverTipsCtrl',
        header_title: 'Receiver Interface',
        header_subtitle: 'List of submissions'
      }).
      when('/admin/landing', {
        templateUrl: 'views/admin/landing.html',
        controller: 'AdminCtrl',
        header_title: 'Administration Interface',
        header_subtitle: 'Landing Page'
      }).
      when('/admin/content', {
        templateUrl: 'views/admin/content.html',
        controller: 'AdminCtrl',
        header_title: 'Administration Interface',
        header_subtitle: 'Content Settings'
      }).
      when('/admin/contexts', {
        templateUrl: 'views/admin/contexts.html',
        controller: 'AdminCtrl',
        header_title: 'Administration Interface',
        header_subtitle: 'Contexts Configuration'
      }).
      when('/admin/fields', {
        templateUrl: 'views/admin/field_templates.html',
        controller: 'AdminCtrl',
        header_title: 'Administration Interface',
        header_subtitle: 'Fields Configuration'
      }).
      when('/admin/users', {
        templateUrl: 'views/admin/users.html',
        controller: 'AdminCtrl',
        header_title: 'Administration Interface',
        header_subtitle: 'Users Configuration'
      }).
      when('/admin/receivers', {
        templateUrl: 'views/admin/receivers.html',
        controller: 'AdminCtrl',
        header_title: 'Administration Interface',
        header_subtitle: 'Receivers Configuration'
      }).
      when('/admin/mail', {
        templateUrl: 'views/admin/mail.html',
        controller: 'AdminCtrl',
        header_title: 'Administration Interface',
        header_subtitle: 'Email Configuration'
      }).
      when('/admin/advanced_settings', {
        templateUrl: 'views/admin/advanced.html',
        controller: 'AdminCtrl',
        header_title: 'Administration Interface',
        header_subtitle: 'Advanced Settings'
      }).
      when('/user/preferences', {
        templateUrl: 'views/user/preferences.html',
        controller: 'PreferencesCtrl',
        header_title: 'User Preferences',
        header_subtitle: ''
      }).
      when('/admin/overview/users', {
        templateUrl: 'views/admin/users_overview.html',
        controller: 'OverviewCtrl',
        header_title: 'Administration Interface',
        header_subtitle: 'Users Overview'
      }).
      when('/admin/overview/tips', {
        templateUrl: 'views/admin/tips_overview.html',
        controller: 'OverviewCtrl',
        header_title: 'Administration Interface',
        header_subtitle: 'Tips Overview'
      }).
      when('/admin/overview/files', {
        templateUrl: 'views/admin/files_overview.html',
        controller: 'OverviewCtrl',
        header_title: 'Administration Interface',
        header_subtitle: 'Files Overview'
      }).
      when('/admin/anomalies', {
        templateUrl: 'views/admin/anomalies.html',
        controller: 'AnomaliesCtrl',
        header_title: 'Administration Interface',
        header_subtitle: 'Anomalies'
      }).
      when('/admin/stats', {
        templateUrl: 'views/admin/stats.html',
        controller: 'StatisticsCtrl',
        header_title: 'Administration Interface',
        header_subtitle: 'System Stats'
      }).
      when('/admin/activities', {
        templateUrl: 'views/admin/activities.html',
        controller: 'ActivitiesCtrl',
        header_title: 'Administration Interface',
        header_subtitle: 'Recent Activities'
      }).
      when('/admin', {
        templateUrl: 'views/login.html',
        controller: 'LoginCtrl',
        header_title: 'Login',
        header_subtitle: ''
      }).
      when('/custodian', {
        templateUrl: 'views/login.html',
        controller: 'LoginCtrl',
        header_title: 'Login',
        header_subtitle: ''
      }).
      when('/login', {
        templateUrl: 'views/login.html',
        controller: 'LoginCtrl',
        header_title: 'Login',
        header_subtitle: ''
      }).
      when('/start', {
        templateUrl: 'views/home.html',
        controller: 'HomeCtrl',
        header_title: '',
        header_subtitle: ''
      }).
      when('/', {
        templateUrl: 'views/home.html',
        controller: 'HomeCtrl',
        header_title: '',
        header_subtitle: ''
      }).
      otherwise({
        redirectTo: '/'
      });

      $translateProvider.useStaticFilesLoader({
        prefix: 'l10n/',
        suffix: '.json'
      });

      $translateProvider.useSanitizeValueStrategy('escape');

      $tooltipProvider.options({appendToBody: true});
}]).
  config(['flowFactoryProvider', function (flowFactoryProvider) {
    flowFactoryProvider.defaults = {
        chunkSize: 1 * 1024 * 1024,
        forceChunkSize: true,
        testChunks: false,
        simultaneousUploads: 1,
        generateUniqueIdentifier: function (file) {
          return Math.random() * 1000000 + 1000000;
        }
    };
}]).
  factory("stacktraceService", function() {
    return({
      fromError: StackTrace.fromError
    });
}).
  config(exceptionConfig).
  run(['$http', '$rootScope', '$location', function ($http, $rootScope, $location) {
     $rootScope.successes = [];
     $rootScope.errors = [];
     $rootScope.loginInProgress = false;

     var globaleaksRequestInterceptor = function(data, headers) {
        headers = angular.extend(headers(), $rootScope.get_auth_headers());
        return data;
    };

    $http.defaults.transformRequest.push(globaleaksRequestInterceptor);

    // register listener to watch route changes
    $rootScope.$on("$routeChangeStart", function(event, next, current) {
      var path = $location.path();
      var embedded = '/embedded/';

      if (path.substr(0, embedded.length) === embedded) {
        $rootScope.embedded = true;
        var search = $location.search();
        if (Object.keys(search).length === 0) {
          $location.path(path.replace("/embedded/", "/"));
          $location.search("embedded=true");
        } else {
          $location.url($location.url().replace("/embedded/", "/") + "&embedded=true");
        }
      }
    });

    $rootScope.$on('$routeChangeSuccess', function (event, current, previous) {
        if (current.$$route) {
          $rootScope.successes = [];
          $rootScope.errors = [];
          $rootScope.header_title = current.$$route.header_title;
          $rootScope.header_subtitle = current.$$route.header_subtitle;
        }
    });

    $rootScope.anonymous = false;
    $rootScope.embedded = false;
}]);

exceptionConfig.$inject = ['$provide'];

function exceptionConfig($provide) {
    $provide.decorator('$exceptionHandler', extendExceptionHandler);
}

extendExceptionHandler.$inject = ['$delegate', '$injector', '$window', 'stacktraceService'];

function extendExceptionHandler($delegate, $injector, $window, stacktraceService) {
    return function(exception, cause) {

        var $rootScope = $injector.get('$rootScope');

        if ($rootScope.exceptions_count === undefined) {
          $rootScope.exceptions_count = 0;
        }

        $rootScope.exceptions_count += 1;

        if ($rootScope.exceptions_count >= 3) {
          // Give each client the ability to forward only the first 3 exceptions
          // scattered; this is also important to avoid looping exceptions to
          // cause looping POST requests.
          return;
        }

        $delegate(exception, cause);

        var errorMessage = exception.toString();
        stacktraceService.fromError(exception).then(function(result) {
          var errorData = angular.toJson({
            errorUrl: $window.location.href,
            errorMessage: errorMessage,
            stackTrace: result,
            agent: navigator.userAgent
          });

          var $http = $injector.get('$http');

          $http.post('exception', errorData);
        });
    };
}
<|endoftext|>


<commit_before>const {readFileSync} = require('fs')
const {join} = require('path')

const replace = require('replace-in-file')
const chokidar = require('chokidar')

const postcss = require('postcss')
const autoprefixer = require('autoprefixer')
const cssnano = require('cssnano');

const postcssPlugins = [
  autoprefixer,
  cssnano()
]
// const postcssOptions = {}
// const filterType = /^text\/css$/

// Initialize watcher.
const watcher = chokidar.watch('./src/components/**/*.postcss', {
  persistent: true
})

// Something to use when events are received.
const log = console.log.bind(console)

const replaceHtml = (path, css) => {
  return replace({
    files: path,
    from: /<style>((.|\n)*)<\/style>/,
    to: `<style>
        ${css}
      </style>`
  }).then(changedFiles => changedFiles)
}

const compile = sourcePath => {
  const css = readFileSync(sourcePath, 'utf8')
  const splittedPath = sourcePath.split('/')
  const normalizedPath = splittedPath.splice(0, splittedPath.length - 1).join('/')
  const htmlPath = join(normalizedPath, 'style-module.html')

  postcss(postcssPlugins)
    .process(css)
    .then(cssRes => replaceHtml(htmlPath, cssRes))
		.then(compileFiles => log(`>> Compiled: ${sourcePath} -> ${compileFiles}`))
    .catch(err => console.error(`! ERR: ${err}`))
}

// Add event listeners.
watcher
  .on('add', sourcePath => log(`File ${sourcePath} has been added`))
  .on('change', sourcePath => compile(sourcePath))
  .on('unlink', sourcePath => log(`File ${sourcePath} has been removed`))

<commit_msg>Test fixed<commit_after>const {readFileSync} = require('fs')
const {join} = require('path')

const replace = require('replace-in-file')
const chokidar = require('chokidar')

const postcss = require('postcss')
const autoprefixer = require('autoprefixer')
const cssnano = require('cssnano')

const postcssPlugins = [
  autoprefixer,
  cssnano()
]
// const postcssOptions = {}
// const filterType = /^text\/css$/

// Initialize watcher.
const watcher = chokidar.watch('./src/components/**/*.postcss', {
  persistent: true
})

// Something to use when events are received.
const log = console.log.bind(console)

const replaceHtml = (path, css) => {
  return replace({
    files: path,
    from: /<style>((.|\n)*)<\/style>/,
    to: `<style>
        ${css}
      </style>`
  }).then(changedFiles => changedFiles)
}

const compile = sourcePath => {
  const css = readFileSync(sourcePath, 'utf8')
  const splittedPath = sourcePath.split('/')
  const normalizedPath = splittedPath.splice(0, splittedPath.length - 1).join('/')
  const htmlPath = join(normalizedPath, 'style-module.html')

  postcss(postcssPlugins)
    .process(css)
    .then(cssRes => replaceHtml(htmlPath, cssRes))
		.then(compileFiles => log(`>> Compiled: ${sourcePath} -> ${compileFiles}`))
    .catch(err => console.error(`! ERR: ${err}`))
}

// Add event listeners.
watcher
  .on('add', sourcePath => log(`File ${sourcePath} has been added`))
  .on('change', sourcePath => compile(sourcePath))
  .on('unlink', sourcePath => log(`File ${sourcePath} has been removed`))

<|endoftext|>


<commit_before>'use strict';

require('dotenv').config({path: __dirname + '/../.env'});

const NEXMO_API_KEY = process.env.NEXMO_API_KEY;
const NEXMO_API_SECRET = process.env.NEXMO_API_SECRET;
const NEXMO_PRIVATE_KEY = __dirname +"/../"+ process.env.NEXMO_PRIVATE_KEY;
const NEXMO_APPLICATION_ID = process.env.NEXMO_APPLICATION_ID;

const Nexmo = require('nexmo');

const nexmo = new Nexmo({
  apiKey: NEXMO_API_KEY,
  apiSecret: NEXMO_API_SECRET,
  applicationId: NEXMO_APPLICATION_ID,
  privateKey: NEXMO_PRIVATE_KEY
});

nexmo.calls.get({}, (err, res) => {
  if(err) { console.error(err); }
  else {
    res._embedded.calls.forEach((call) => {
      console.log(call);
    });
  }
});
<commit_msg>Add get calls example<commit_after>'use strict';

require('dotenv').config({path: __dirname + '/../.env'});

const NEXMO_API_KEY = process.env.NEXMO_API_KEY;
const NEXMO_API_SECRET = process.env.NEXMO_API_SECRET;
const NEXMO_PRIVATE_KEY = __dirname +"/../"+ process.env.NEXMO_PRIVATE_KEY;
const NEXMO_APPLICATION_ID = process.env.NEXMO_APPLICATION_ID;

const Nexmo = require('nexmo');

const nexmo = new Nexmo({
  apiKey: NEXMO_API_KEY,
  apiSecret: NEXMO_API_SECRET,
  applicationId: NEXMO_APPLICATION_ID,
  privateKey: NEXMO_PRIVATE_KEY
}, {debug: true});

nexmo.calls.get({}, (err, res) => {
  if(err) { console.error(err); }
  else {
    res._embedded.calls.forEach((call) => {
      console.log(call);
    });
  }
});
<|endoftext|>


<commit_before>import React, {useState} from 'react';
import {Platform} from 'react-native';
import {StateNavigator} from 'navigation';
import {NavigationHandler} from 'navigation-react';
import {NavigationStack, TabBar, TabBarItem} from 'navigation-react-native';
import createStateNavigator from './createStateNavigator';
import {getFollows} from './data';

var stateNavigator = createStateNavigator();

const notificationsNavigator = new StateNavigator(stateNavigator);
  stateNavigator.navigate('home');
  if (Platform.OS !== 'web')
    notificationsNavigator.navigate('notifications');

const Stack = ({navigator}) => (
  <NavigationHandler stateNavigator={navigator}>
    <NavigationStack
      crumbStyle={from => from ? 'scale_in' : 'scale_out'}
      unmountStyle={from => from ? 'slide_in' : 'slide_out'} />
  </NavigationHandler>
);

const App = () => {
  const [notified, setNotified] = useState(false);
  return Platform.OS === 'ios' ? (
    <TabBar>
      <TabBarItem title="Home" image={require('./home.png')}>
        <Stack navigator={stateNavigator} />
      </TabBarItem>
      <TabBarItem
        title="Notifications"
        image={require('./notifications.png')}
        badge={!notified ? '' + getFollows().length : null}
        onPress={() => {setNotified(true)}}>
        <Stack navigator={notificationsNavigator} />
      </TabBarItem>
    </TabBar>
  ) : (
    <Stack navigator={stateNavigator} />
  );
};

export default App;
<commit_msg>Disabled other navigator history manager<commit_after>import React, {useState} from 'react';
import {Platform} from 'react-native';
import {StateNavigator} from 'navigation';
import {NavigationHandler} from 'navigation-react';
import {NavigationStack, TabBar, TabBarItem} from 'navigation-react-native';
import createStateNavigator from './createStateNavigator';
import {getFollows} from './data';

var stateNavigator = createStateNavigator();

const notificationsNavigator = new StateNavigator(stateNavigator);
  stateNavigator.navigate('home');
  notificationsNavigator.historyManager.disabled = true;
  notificationsNavigator.historyManager.stop();
  notificationsNavigator.navigate('notifications');

const Stack = ({navigator}) => (
  <NavigationHandler stateNavigator={navigator}>
    <NavigationStack
      crumbStyle={from => from ? 'scale_in' : 'scale_out'}
      unmountStyle={from => from ? 'slide_in' : 'slide_out'} />
  </NavigationHandler>
);

const App = () => {
  const [notified, setNotified] = useState(false);
  return Platform.OS === 'ios' ? (
    <TabBar>
      <TabBarItem title="Home" image={require('./home.png')}>
        <Stack navigator={stateNavigator} />
      </TabBarItem>
      <TabBarItem
        title="Notifications"
        image={require('./notifications.png')}
        badge={!notified ? '' + getFollows().length : null}
        onPress={() => {setNotified(true)}}>
        <Stack navigator={notificationsNavigator} />
      </TabBarItem>
    </TabBar>
  ) : (
    <Stack navigator={stateNavigator} />
  );
};

export default App;
<|endoftext|>


<commit_before>asynctest(
  'Browser Test: ui.ListTest',

  [
    'ephox.agar.api.Assertions',
    'ephox.agar.api.Chain',
    'ephox.agar.api.GeneralSteps',
    'ephox.agar.api.Mouse',
    'ephox.agar.api.Pipeline',
    'ephox.agar.api.Step',
    'ephox.agar.api.Waiter',
    'ephox.alloy.api.behaviour.Behaviour',
    'ephox.alloy.api.behaviour.Replacing',
    'ephox.alloy.api.behaviour.Toggling',
    'ephox.alloy.api.component.GuiFactory',
    'ephox.alloy.api.component.Memento',
    'ephox.alloy.api.system.Attachment',
    'ephox.alloy.api.system.Gui',
    'ephox.alloy.test.GuiSetup',
    'ephox.katamari.api.Fun',
    'ephox.mcagar.api.TinyApis',
    'ephox.mcagar.api.TinyLoader',
    'ephox.sugar.api.node.Body',
    'ephox.sugar.api.properties.Attr',
    'ephox.sugar.api.search.Traverse',
    'tinymce.themes.mobile.features.Features',
    'tinymce.themes.mobile.test.theme.TestTheme',
    'tinymce.themes.mobile.util.FormatChangers'
  ],

  function (
    Assertions, Chain, GeneralSteps, Mouse, Pipeline, Step, Waiter, Behaviour, Replacing, Toggling, GuiFactory, Memento, Attachment, Gui, GuiSetup, Fun, TinyApis,
    TinyLoader, Body, Attr, Traverse, Features, TestTheme, FormatChangers
  ) {
    var success = arguments[arguments.length - 2];
    var failure = arguments[arguments.length - 1];

    /* This test is going to create a toolbar with both list items on it */
    var alloy = Gui.create();

    var body = Body.body();
    Attachment.attachSystem(body, alloy);

    var toolbar = GuiFactory.build({
      dom: {
        tag: 'div',
        classes: [ 'test-toolbar' ]
      },
      behaviours: Behaviour.derive([
        Replacing.config({ })
      ])
    });

    var socket = GuiFactory.build({
      dom: {
        tag: 'div',
        classes: [ 'test-socket' ]
      }
    });

    alloy.add(toolbar);
    alloy.add(socket);

    TestTheme.setup(alloy, socket);

    var realm = {
      system: Fun.constant(alloy)
    };

    TinyLoader.setup(function (editor, onSuccess, onFailure) {
      var features = Features.setup(realm, editor);

      FormatChangers.init(realm, editor);

      var apis = TinyApis(editor);

      var memBullist = Memento.record(
        features.bullist.spec()
      );

      var memNumlist = Memento.record(
        features.numlist.spec()
      );

      Replacing.set(toolbar, [
        memBullist.asSpec(),
        memNumlist.asSpec()
      ]);

      var sSetP1 = apis.sSetSelection([ 0, 0, 0 ], 'Thi'.length, [ 0, 0, 0 ], 'Thi'.length);
      var sSetP2 = apis.sSetSelection([ 1, 0 ], 'Norma'.length, [ 1, 0 ], 'Norma'.length);
      var sSetP3 = apis.sSetSelection([ 2, 0, 0 ], 'Bu'.length, [ 2, 0, 0 ], 'Bu'.length);

      var sAssertListIs = function (label, mem, state) {
        return Waiter.sTryUntil(
            label,
            Step.sync(function () {
              var button = mem.get(socket);
              Assertions.assertEq('Selected/Pressed state of button:\n' +
                '      (' + Attr.get(button.element(), 'class') + ')', state, Toggling.isOn(button));
            }),
            100,
            1000
        );
      };

      var sCheckInNumlist = function (situation) {
        return GeneralSteps.sequence([
          sAssertListIs('checking numlist: ' + situation, memNumlist, true),
          sAssertListIs('checking bullist: ' + situation, memBullist, false)
        ]);
      };

      var sCheckInBullist = function (situation) {
        return GeneralSteps.sequence([
          sAssertListIs('checking numlist: ' + situation, memNumlist, false),
          sAssertListIs('checking bullist: ' + situation, memBullist, true)
        ]);
      };

      var sCheckInNoList = function (situation) {
        return GeneralSteps.sequence([
          sAssertListIs('checking numlist: ' + situation, memNumlist, false),
          sAssertListIs('checking bullist: ' + situation, memBullist, false)
        ]);
      };

      var sCheckP1 = function (situation) {
        return GeneralSteps.sequence([
          sSetP1,
          sCheckInNumlist(situation)
        ]);
      };

      var sCheckP2 = function (situation) {
        return GeneralSteps.sequence([
          sSetP2,
          sCheckInNoList(situation)
        ]);
      };

      var sCheckP3 = function (situation) {
        return GeneralSteps.sequence([
          sSetP3,
          sCheckInBullist(situation)
        ]);
      };

      var sClickButton = function (mem) {
        return Chain.asStep(alloy.element(), [
          Chain.mapper(function () {
            return mem.get(socket).element();
          }),
          Mouse.cClick
        ]);
      };

      Pipeline.async({}, [
        GuiSetup.mAddStyles(Traverse.owner(body), [
          '.tinymce-mobile-toolbar-button { padding: 2px; border: 1px solid black; background: white; }',
          '.tinymce-mobile-toolbar-button.tinymce-mobile-toolbar-button-selected { background: #cadbee; }',
          '.tinymce-mobile-icon-unordered-list:before { content: "ul"; }',
          '.tinymce-mobile-icon-ordered-list:before { content: "ol"; }'
        ]),
        apis.sFocus,
        apis.sSetContent(
          '

This is an ordered list

Normal paragraph

Bullet list

'
        ),
        sCheckP1('initial selection in ol'),
        sCheckP2('ol >>> p'),
        sCheckP3('p >>> ul'),
        sCheckP1('ul >>> ol'),

        sClickButton(memBullist),
        sCheckInBullist('ol converted to ul'),
        sClickButton(memNumlist),
        sCheckInNumlist('ul converted back to ol'),
        sClickButton(memNumlist),
        sCheckInNoList('ol converted to p'),
        GuiSetup.mRemoveStyles
      ], onSuccess, onFailure);
    }, {
      theme: TestTheme.name()
    }, function () {
      success();
    }, failure);

  }
);
<commit_msg>TM-93: using general testing methods<commit_after>asynctest(
  'Browser Test: ui.ListTest',

  [
    'ephox.agar.api.GeneralSteps',
    'ephox.agar.api.Pipeline',
    'ephox.alloy.api.behaviour.Behaviour',
    'ephox.alloy.api.behaviour.Replacing',
    'ephox.alloy.api.component.GuiFactory',
    'ephox.alloy.api.component.Memento',
    'ephox.alloy.api.system.Attachment',
    'ephox.alloy.api.system.Gui',
    'ephox.alloy.test.GuiSetup',
    'ephox.katamari.api.Fun',
    'ephox.mcagar.api.TinyApis',
    'ephox.mcagar.api.TinyLoader',
    'ephox.sugar.api.node.Body',
    'ephox.sugar.api.search.Traverse',
    'tinymce.themes.mobile.features.Features',
    'tinymce.themes.mobile.test.theme.TestTheme',
    'tinymce.themes.mobile.test.ui.TestUi',
    'tinymce.themes.mobile.util.FormatChangers'
  ],

  function (
    GeneralSteps, Pipeline, Behaviour, Replacing, GuiFactory, Memento, Attachment, Gui, GuiSetup, Fun, TinyApis, TinyLoader, Body, Traverse, Features, TestTheme,
    TestUi, FormatChangers
  ) {
    var success = arguments[arguments.length - 2];
    var failure = arguments[arguments.length - 1];

    /* This test is going to create a toolbar with both list items on it */
    var alloy = Gui.create();

    var body = Body.body();
    Attachment.attachSystem(body, alloy);

    var toolbar = GuiFactory.build({
      dom: {
        tag: 'div',
        classes: [ 'test-toolbar' ]
      },
      behaviours: Behaviour.derive([
        Replacing.config({ })
      ])
    });

    var socket = GuiFactory.build({
      dom: {
        tag: 'div',
        classes: [ 'test-socket' ]
      }
    });

    alloy.add(toolbar);
    alloy.add(socket);

    TestTheme.setup(alloy, socket);

    var realm = {
      system: Fun.constant(alloy),
      socket: Fun.constant(socket)
    };

    TinyLoader.setup(function (editor, onSuccess, onFailure) {
      var features = Features.setup(realm, editor);

      FormatChangers.init(realm, editor);

      var apis = TinyApis(editor);

      var memBullist = Memento.record(
        features.bullist.spec()
      );

      var memNumlist = Memento.record(
        features.numlist.spec()
      );

      Replacing.set(toolbar, [
        memBullist.asSpec(),
        memNumlist.asSpec()
      ]);

      var sSetP1 = apis.sSetSelection([ 0, 0, 0 ], 'Thi'.length, [ 0, 0, 0 ], 'Thi'.length);
      var sSetP2 = apis.sSetSelection([ 1, 0 ], 'Norma'.length, [ 1, 0 ], 'Norma'.length);
      var sSetP3 = apis.sSetSelection([ 2, 0, 0 ], 'Bu'.length, [ 2, 0, 0 ], 'Bu'.length);

      var sCheckComponent = function (label, state) {
        return function (memento) {
          return TestUi.sWaitForToggledState(label, state, realm, memento);
        };
      };

      var sCheckLists = function (situation, stateOfNumlist, stateOfBullist) {
        return GeneralSteps.sequence([
          sCheckComponent('checking numlist: ' + situation, stateOfNumlist)(memNumlist),
          sCheckComponent('checking bullist: ' + situation, stateOfBullist)(memBullist)
        ]);
      };

      var sCheckInNumlist = function (situation) {
        return sCheckLists(situation, true, false);
      };

      var sCheckInBullist = function (situation) {
        return sCheckLists(situation, false, true);
      };

      var sCheckInNoList = function (situation) {
        return sCheckLists(situation, false, false);
      };

      var sCheckP1 = function (situation) {
        return GeneralSteps.sequence([
          sSetP1,
          sCheckInNumlist(situation)
        ]);
      };

      var sCheckP2 = function (situation) {
        return GeneralSteps.sequence([
          sSetP2,
          sCheckInNoList(situation)
        ]);
      };

      var sCheckP3 = function (situation) {
        return GeneralSteps.sequence([
          sSetP3,
          sCheckInBullist(situation)
        ]);
      };

      Pipeline.async({}, [
        GuiSetup.mAddStyles(Traverse.owner(body), [
          '.tinymce-mobile-toolbar-button { padding: 2px; border: 1px solid black; background: white; }',
          '.tinymce-mobile-toolbar-button.tinymce-mobile-toolbar-button-selected { background: #cadbee; }',
          '.tinymce-mobile-icon-unordered-list:before { content: "ul"; }',
          '.tinymce-mobile-icon-ordered-list:before { content: "ol"; }'
        ]),
        apis.sFocus,
        apis.sSetContent(
          '

This is an ordered list

Normal paragraph

Bullet list

'
        ),
        sCheckP1('initial selection in ol'),
        sCheckP2('ol >>> p'),
        sCheckP3('p >>> ul'),
        sCheckP1('ul >>> ol'),

        TestUi.sClickComponent(realm, memBullist),
        sCheckInBullist('ol converted to ul'),
        TestUi.sClickComponent(realm, memNumlist),
        sCheckInNumlist('ul converted back to ol'),
        TestUi.sClickComponent(realm, memNumlist),
        sCheckInNoList('ol converted to p'),
        GuiSetup.mRemoveStyles
      ], onSuccess, onFailure);
    }, {
      theme: TestTheme.name()
    }, function () {
      success();
    }, failure);

  }
);
<|endoftext|>


<commit_before>defineAttr(OpenClassOrInterfaceType$meta$declaration.$$.prototype,'typeArguments',function(){
  var tps=this.declaration.typeParameterDeclarations;
  if (tps && tps.length > 0) {
    var targs=[];
    for (var i=0; i < tps.length; i++) {
      var targ = FreeClass(typeLiteral$meta({Type:Anything})); //TODO find this shit for real
      targs.push(Entry(tps[i], targ, {Key:{t:TypeParameter$meta$declaration},Item:{t:OpenType$meta$declaration}}));
    }
    return LazyMap(targs.reifyCeylonType({Absent:{t:Null},Element:{t:Entry,a:{Key:{t:TypeParameter$meta$declaration},Item:{t:OpenType$meta$declaration}}}}),{Key:{t:TypeParameter$meta$declaration},Item:{t:OpenType$meta$declaration}});
  }
  return getEmpty();
},undefined,function(){return{mod:$$METAMODEL$$,$t:{t:Map,a:{Key:{t:TypeParameter$meta$declaration},Item:{t:OpenType$meta$declaration}}},$cont:OpenClassOrInterfaceType,$an:function(){return[shared(),actual()];},d:['ceylon.language.meta.declaration','OpenClassOrInterfaceType','$at','typeArguments']};});
defineAttr(OpenClassOrInterfaceType$meta$declaration.$$.prototype,'extendedType',function(){
  return this.declaration.extendedType;
},undefined,function(){return{mod:$$METAMODEL$$,$t:{ t:'u', l:[{t:Null},{t:OpenClassType$meta$declaration}]},$cont:OpenClassOrInterfaceType,$an:function(){return[shared(),actual()];},d:['ceylon.language.meta.declaration','OpenClassOrInterfaceType','$at','extendedType']};});
defineAttr(OpenClassOrInterfaceType$meta$declaration.$$.prototype,'declaration',function(){return this._decl;},undefined,function(){return{mod:$$METAMODEL$$,$t:{t:ClassDeclaration$meta$declaration},$cont:OpenClassOrInterfaceType,$an:function(){return[shared(),actual()];},d:['ceylon.language.meta.declaration','OpenClassOrInterfaceType','$at','declaration']};});
defineAttr(OpenClassOrInterfaceType$meta$declaration.$$.prototype,'satisfiedTypes',function(){
  return this.declaration.satisfiedTypes;
},undefined,function(){return{mod:$$METAMODEL$$,$t:{t:Sequential,a:{Element:{t:OpenInterfaceType$meta$declaration}}},$cont:OpenClassOrInterfaceType$meta$declaration,$an:function(){return[shared(),actual()];},d:['ceylon.language.meta.declaration','OpenClassOrInterfaceType','$at','satisfiedTypes']};});
<commit_msg>use OpenTvar for now<commit_after>defineAttr(OpenClassOrInterfaceType$meta$declaration.$$.prototype,'typeArguments',function(){
  var tps=this.declaration.typeParameterDeclarations;
  if (tps && tps.length > 0) {
    var targs=[];
    for (var i=0; i < tps.length; i++) {
      var targ = OpenTvar(tps[i]); //TODO dig deeper
      targs.push(Entry(tps[i], targ, {Key:{t:TypeParameter$meta$declaration},Item:{t:OpenType$meta$declaration}}));
    }
    return LazyMap(targs.reifyCeylonType({Absent:{t:Null},Element:{t:Entry,a:{Key:{t:TypeParameter$meta$declaration},Item:{t:OpenType$meta$declaration}}}}),{Key:{t:TypeParameter$meta$declaration},Item:{t:OpenType$meta$declaration}});
  }
  return getEmpty();
},undefined,function(){return{mod:$$METAMODEL$$,$t:{t:Map,a:{Key:{t:TypeParameter$meta$declaration},Item:{t:OpenType$meta$declaration}}},$cont:OpenClassOrInterfaceType,$an:function(){return[shared(),actual()];},d:['ceylon.language.meta.declaration','OpenClassOrInterfaceType','$at','typeArguments']};});
defineAttr(OpenClassOrInterfaceType$meta$declaration.$$.prototype,'extendedType',function(){
  return this.declaration.extendedType;
},undefined,function(){return{mod:$$METAMODEL$$,$t:{ t:'u', l:[{t:Null},{t:OpenClassType$meta$declaration}]},$cont:OpenClassOrInterfaceType,$an:function(){return[shared(),actual()];},d:['ceylon.language.meta.declaration','OpenClassOrInterfaceType','$at','extendedType']};});
defineAttr(OpenClassOrInterfaceType$meta$declaration.$$.prototype,'declaration',function(){return this._decl;},undefined,function(){return{mod:$$METAMODEL$$,$t:{t:ClassDeclaration$meta$declaration},$cont:OpenClassOrInterfaceType,$an:function(){return[shared(),actual()];},d:['ceylon.language.meta.declaration','OpenClassOrInterfaceType','$at','declaration']};});
defineAttr(OpenClassOrInterfaceType$meta$declaration.$$.prototype,'satisfiedTypes',function(){
  return this.declaration.satisfiedTypes;
},undefined,function(){return{mod:$$METAMODEL$$,$t:{t:Sequential,a:{Element:{t:OpenInterfaceType$meta$declaration}}},$cont:OpenClassOrInterfaceType$meta$declaration,$an:function(){return[shared(),actual()];},d:['ceylon.language.meta.declaration','OpenClassOrInterfaceType','$at','satisfiedTypes']};});
<|endoftext|>