<commit_before>var Module = require('module');
var path = require('path');
var fs = require('fs');

exports.addCoverage = function addCoverage(code, filename) {
    filename = filename.replace(/\\/g, '\\\\');
    if (!~filename.indexOf(addCoverage.subdir)) {
        return code;
    }
    if (process.env.COVERAGE && !~filename.indexOf(process.env.COVERAGE)) {
        return code;
    }
    var lines = code.split('\n');

    if (lines.length > 0) {
        lines[0] = 'if (!__cov["' + filename + '"]) {__cov["' + filename + '"] = { 0: 1}; }' + lines[0];
    }

    for (var i = 0; i < lines.length; i++) {
        if (lines[i].match(/^\s\*\s/)) continue;
        var name = '__cov["' + filename + '"][' + i + ']';
        var covLine = ' ' + name + ' = (' + name + ' || 0) + 1;';
        lines[i] = lines[i]
        .replace(/;$/, ';' + covLine)
        .replace(/^\s*(return|throw|break|continue)/, covLine + ' $1');
    }

    return lines.join('\n');
};

var projectName;

exports.init = function init(subdir, name) {
    projectName = name;
    if (process.env.NOCOV || global.__cov) return;
    if (!subdir) {
        subdir = process.cwd();
    } else if (!subdir.match(/^\//)) {
        subdir = path.join(process.cwd(), subdir);
    }
    global.__cov = {};
    exports.addCoverage.subdir = subdir;
    var compile = Module.prototype._compile;
    Object.keys(Module._cache).forEach(function (path) {
        if (path.match(/node_modules/)) return;
        delete Module._cache[path];
    });
    Module.prototype._compile = function (code, filename) {
        if (~filename.indexOf(subdir)) {
            code = exports.addCoverage(code, filename);
        }
        return compile.call(this, code, filename);
    };
};

exports.report = function () {
    if (process.env.NOCOV) return;
    coverageReport();
};

function coverageReport() {
    var cwd = process.cwd(),
    total_lines = 0,
    total_covered = 0,
    files = [];

    for (file in __cov) {
        if (file.search(cwd) === -1 || file.search(cwd + '/node_modules') !== -1) continue;
        var shortFileName = file.replace(cwd + '/', '');
        var id = shortFileName.replace(/[^a-z]+/gi, '-').replace(/^-|-$/, '');
        var code = syntax(fs.readFileSync(file).toString()).split('\n');
        var cnt = code.filter(function (line) {
            return line.match(/;$/) && !line.match(/^\s\*\s/);
        }).length;
        var covered = Object.keys(__cov[file]).length;
        if (covered > cnt) covered = cnt;
        var coveredPercentage = cnt === 0 ? 100 : Math.round((covered / cnt) * 100);
        total_covered += covered;
        total_lines += cnt;
        var html = '

';
        html += '
';
        html += '' + shortFileName +
            '';
        html += '

';
        var progressClass = 'progress-danger';
        if (coveredPercentage > 30) {
            progressClass = 'progress-warning';
        }
        if (coveredPercentage >= 80) {
            progressClass = 'progress-success';
        }
        html += '

' + coveredPercentage +
            '% [' + covered + '/' + cnt + ']

';
        html += '
';

        html += '

';
        code.forEach(function (line, i) {
            html += '
' + line + '';
            if (__cov[file][i] && i) {
                html += '' + __cov[file][i] + '';
            }
            html += '
';
        });
        html += '

';

        if (cnt > 1) {
            files.push({
                lines: cnt,
                covered: covered,
                id: id,
                name: shortFileName,
                html: html
            });
        }
    }

    var groups = {};
    files.sort(byName).forEach(function (f) {
        var group = f.name.replace(/\/[^\/]+$/, '');
        if (!groups[group]) groups[group] = [];
        groups[group].push(f);
    });

    var groupsListHTML = [];
    var html = Object.keys(groups).map(function (g) {
        var tltc = 0; // total lines to cover
        var tlcd = 0; // total lines covered
        var files = groups[g].sort(bySize).map(function (f) {
            tltc += f.lines;
            tlcd += f.covered;
            return f.html;
        }).join('\n');
        var gid = g.toLowerCase().replace(/[^a-z]/i, '-');
        var percentage = Math.round(100 * tlcd / tltc);
        groupsListHTML.push('
./' + g + ' (' + percentage + '%)
');
        return '

./' + g + '

' + progressBar(tlcd, tltc) + '

' + files;
    }).join('\n');

    function byName(x, y) {
        return x.name > y.name ? -1 : 1;
    }
    function bySize(x, y) {
        return y.lines - x.lines;
    }

    if (!fs.existsSync(cwd + '/coverage')) fs.mkdirSync(cwd + '/coverage');

    fs.writeFileSync(cwd + '/coverage/index.html',
        fs.readFileSync(path.join(__dirname, '/assets/coverage.html'))
        .toString()
        .replace('PROJECT', projectName || '')
        .replace('PROGRESS', progressBar(total_covered, total_lines))
        .replace('CODE', html.replace(/\$'/g, '$\''))
        .replace('GROUPS', groupsListHTML.join(''))
    );

    copy('bootstrap.css');
    copy('style.css');
    copy('coverage.js');
    copy('bootstrap.js');
    copy('jquery.min.js');

    console.log('====================');
    console.log('TOTAL COVERAGE:', Math.round((total_covered / (total_lines)) * 100) + '%');
}

function progressBar(x, total) {
    var percentage = total === 0 ? 100 : Math.round((x / total) * 100);
    var progressClass = 'progress-danger';
    if (percentage > 30) {
        progressClass = 'progress-warning';
    }
    if (percentage >= 80) {
        progressClass = 'progress-success';
    }
    return '

' + percentage +
    '% [' + x + '/' + total + ']

';

}

function copy(file) {
    var source = path.join(__dirname, 'assets', file);
    var destination = path.join(process.cwd(), 'coverage', file);
    var contents = fs.readFileSync(source).toString();
    fs.writeFileSync(destination, contents);
}

function syntax(code) {
    var comments    = [];
    var strings     = [];
    var res         = [];
    var all         = { 'C': comments, 'S': strings, 'R': res };
    var safe        = { '<': '<', '>': '>', '&': '&' };

    return code
        .replace(/[<>&]/g, function (m)
            { return safe[m]; })
        .replace(/\/\/.*$/gm, function (m)
            { var l=comments.length; comments.push(m); return '~~~C'+l+'~~~';   })
        .replace(/\/\*[\s\S]*?\*\//g, function (m)
            { var l=comments.length; comments.push(m); return '~~~C'+l+'~~~';   })
        .replace(/([^\\])((?:'(?:\\'|[^'\n])*')|(?:"(?:\\"|[^"\n])*"))/g, function (m, f, s)
            { var l=strings.length; strings.push(s); return f+'~~~S'+l+'~~~'; })
        // .replace(/\/(\\\/|[^\/\n])*\/[gim]{0,3}/g, function(m)
        //    { var l=res.length; res.push(m); return '~~~R'+l+'~~~';   })
        .replace(/(var|function|typeof|new|return|prototype|if|for|in|while|break|do|continue|switch|case)([^a-z0-9\$_])/gi,
            '$1$2')
        .replace(/(\{|\}|\]|\[|\|)/gi,
            '$1')
        .replace(/([a-z\_\$][a-z0-9_]*)[\s]*\(/gi,
            '$1(')
        .replace(/~~~([CSR])(\d+)~~~/g, replaceCSR)

    function replaceCSR(m, t, i) {
        var openTag = '';
        var closeTag = '';
        return openTag +
            all[t][i].replace(/\n/g, closeTag + '\n' + openTag) +
            closeTag;
    }
}

<commit_msg>Allow multiple sources to track<commit_after>var Module = require('module');
var path = require('path');
var fs = require('fs');

exports.addCoverage = function addCoverage(code, filename) {
    filename = filename.replace(/\\/g, '\\\\');
    if (!eligibleForCoverage(filename)) {
        return code;
    }
    if (process.env.COVERAGE && !~filename.indexOf(process.env.COVERAGE)) {
        return code;
    }
    var lines = code.split('\n');

    if (lines.length > 0) {
        lines[0] = 'if (!__cov["' + filename + '"]) {__cov["' + filename + '"] = { 0: 1}; }' + lines[0];
    }

    for (var i = 0; i < lines.length; i++) {
        if (lines[i].match(/^\s\*\s/)) continue;
        var name = '__cov["' + filename + '"][' + i + ']';
        var covLine = ' ' + name + ' = (' + name + ' || 0) + 1;';
        lines[i] = lines[i]
        .replace(/;$/, ';' + covLine)
        .replace(/^\s*(return|throw|break|continue)/, covLine + ' $1');
    }

    return lines.join('\n');
};

var eligibleForCoverage = exports.eligibleForCoverage = function (filename) {
    var p = exports.addCoverage.paths;
    if (typeof p === 'string') {
        return ~filename.indexOf(p);
    } else if (p instanceof RegExp) {
        return filename.match(p);
    } else if (p instanceof Array) {
        return p.some(function(x) {
            return !!~filename.indexOf(x);
        });
    }
};

var projectName;

exports.init = function init(subdir, name) {
    projectName = name;
    if (process.env.NOCOV || global.__cov) return;
    if (!subdir) {
        subdir = process.cwd();
    } else if (typeof subdir === 'string') {
        if (!subdir.match(/^\//)) {
            subdir = path.join(process.cwd(), subdir);
        }
    } else if (subdir instanceof Array) {
        subdir = subdir.map(function(x) {
            return x.match(/^\//) ? x : path.join(process.cwd(), x);
        });
    }
    global.__cov = {};
    exports.addCoverage.paths = subdir;
    var compile = Module.prototype._compile;
    Object.keys(Module._cache).forEach(function (path) {
        if (path.match(/node_modules/)) return;
        delete Module._cache[path];
    });
    Module.prototype._compile = function (code, filename) {
        if (eligibleForCoverage(filename)) {
            code = exports.addCoverage(code, filename);
        }
        return compile.call(this, code, filename);
    };
};

exports.report = function () {
    if (process.env.NOCOV) return;
    coverageReport();
};

function coverageReport() {
    var cwd = process.cwd(),
    total_lines = 0,
    total_covered = 0,
    files = [];

    for (file in __cov) {
        if (file.search(cwd) === -1 || file.search(cwd + '/node_modules') !== -1) continue;
        var shortFileName = file.replace(cwd + '/', '');
        var id = shortFileName.replace(/[^a-z]+/gi, '-').replace(/^-|-$/, '');
        var code = syntax(fs.readFileSync(file).toString()).split('\n');
        var cnt = code.filter(function (line) {
            return line.match(/;$/) && !line.match(/^\s\*\s/);
        }).length;
        var covered = Object.keys(__cov[file]).length;
        if (covered > cnt) covered = cnt;
        var coveredPercentage = cnt === 0 ? 100 : Math.round((covered / cnt) * 100);
        total_covered += covered;
        total_lines += cnt;
        var html = '

';
        html += '
';
        html += '' + shortFileName +
            '';
        html += '

';
        var progressClass = 'progress-danger';
        if (coveredPercentage > 30) {
            progressClass = 'progress-warning';
        }
        if (coveredPercentage >= 80) {
            progressClass = 'progress-success';
        }
        html += '

' + coveredPercentage +
            '% [' + covered + '/' + cnt + ']

';
        html += '
';

        html += '

';
        code.forEach(function (line, i) {
            html += '
' + line + '';
            if (__cov[file][i] && i) {
                html += '' + __cov[file][i] + '';
            }
            html += '
';
        });
        html += '

';

        if (cnt > 1) {
            files.push({
                lines: cnt,
                covered: covered,
                id: id,
                name: shortFileName,
                html: html
            });
        }
    }

    var groups = {};
    files.sort(byName).forEach(function (f) {
        var group = f.name.replace(/\/[^\/]+$/, '');
        if (!groups[group]) groups[group] = [];
        groups[group].push(f);
    });

    var groupsListHTML = [];
    var html = Object.keys(groups).map(function (g) {
        var tltc = 0; // total lines to cover
        var tlcd = 0; // total lines covered
        var files = groups[g].sort(bySize).map(function (f) {
            tltc += f.lines;
            tlcd += f.covered;
            return f.html;
        }).join('\n');
        var gid = g.toLowerCase().replace(/[^a-z]/i, '-');
        var percentage = Math.round(100 * tlcd / tltc);
        groupsListHTML.push('
./' + g + ' (' + percentage + '%)
');
        return '

./' + g + '

' + progressBar(tlcd, tltc) + '

' + files;
    }).join('\n');

    function byName(x, y) {
        return x.name > y.name ? -1 : 1;
    }
    function bySize(x, y) {
        return y.lines - x.lines;
    }

    if (!fs.existsSync(cwd + '/coverage')) fs.mkdirSync(cwd + '/coverage');

    fs.writeFileSync(cwd + '/coverage/index.html',
        fs.readFileSync(path.join(__dirname, '/assets/coverage.html'))
        .toString()
        .replace('PROJECT', projectName || '')
        .replace('PROGRESS', progressBar(total_covered, total_lines))
        .replace('CODE', html.replace(/\$'/g, '$\''))
        .replace('GROUPS', groupsListHTML.join(''))
    );

    copy('bootstrap.css');
    copy('style.css');
    copy('coverage.js');
    copy('bootstrap.js');
    copy('jquery.min.js');

    console.log('====================');
    console.log('TOTAL COVERAGE:', Math.round((total_covered / (total_lines)) * 100) + '%');
}

function progressBar(x, total) {
    var percentage = total === 0 ? 100 : Math.round((x / total) * 100);
    var progressClass = 'progress-danger';
    if (percentage > 30) {
        progressClass = 'progress-warning';
    }
    if (percentage >= 80) {
        progressClass = 'progress-success';
    }
    return '

' + percentage +
    '% [' + x + '/' + total + ']

';

}

function copy(file) {
    var source = path.join(__dirname, 'assets', file);
    var destination = path.join(process.cwd(), 'coverage', file);
    var contents = fs.readFileSync(source).toString();
    fs.writeFileSync(destination, contents);
}

function syntax(code) {
    var comments    = [];
    var strings     = [];
    var res         = [];
    var all         = { 'C': comments, 'S': strings, 'R': res };
    var safe        = { '<': '<', '>': '>', '&': '&' };

    return code
        .replace(/[<>&]/g, function (m)
            { return safe[m]; })
        .replace(/\/\/.*$/gm, function (m)
            { var l=comments.length; comments.push(m); return '~~~C'+l+'~~~';   })
        .replace(/\/\*[\s\S]*?\*\//g, function (m)
            { var l=comments.length; comments.push(m); return '~~~C'+l+'~~~';   })
        .replace(/([^\\])((?:'(?:\\'|[^'\n])*')|(?:"(?:\\"|[^"\n])*"))/g, function (m, f, s)
            { var l=strings.length; strings.push(s); return f+'~~~S'+l+'~~~'; })
        // .replace(/\/(\\\/|[^\/\n])*\/[gim]{0,3}/g, function(m)
        //    { var l=res.length; res.push(m); return '~~~R'+l+'~~~';   })
        .replace(/(var|function|typeof|new|return|prototype|if|for|in|while|break|do|continue|switch|case)([^a-z0-9\$_])/gi,
            '$1$2')
        .replace(/(\{|\}|\]|\[|\|)/gi,
            '$1')
        .replace(/([a-z\_\$][a-z0-9_]*)[\s]*\(/gi,
            '$1(')
        .replace(/~~~([CSR])(\d+)~~~/g, replaceCSR)

    function replaceCSR(m, t, i) {
        var openTag = '';
        var closeTag = '';
        return openTag +
            all[t][i].replace(/\n/g, closeTag + '\n' + openTag) +
            closeTag;
    }
}

<|endoftext|>


<commit_before>var linestream = require('line-stream')
var through = require('through2')
var pumpify = require('pumpify')

var doneKeywords = ['DONE']
var notDoneKeywords = ['TODO', 'WAITING', 'STARTED']

module.exports = function () {
  var firstLine = true
  var depth = 0
  var transform = through(function(chunk, enc, cb) {
    if (firstLine) {
      this.push('<meta name="viewport" content="width=device-width, initial-scale=1">')
      firstLine = false
    }

    // newlines to br
    var line = chunk.toString()
    line = line.replace(/\n/g, '
\n')

    // done/not-done keywords
    for (var i in notDoneKeywords) {
      line = line.replace(new RegExp(notDoneKeywords[i]), '' + notDoneKeywords[i] + '')
    }
    for (var i in doneKeywords) {
      line = line.replace(new RegExp(doneKeywords[i]), '' + doneKeywords[i] + '')
    }

    // color or indent based on item depth
    if (/^\* /.test(line)) {
      depth = 1
      this.push('')
    }
    else if (/^\*\* /.test(line)) {
      depth = 2
      this.push('')
    }
    else {
      for (var i=0; i < depth + 2; i++) {
        this.push(' ')
      }
    }

    // tags
    var tagRegex = /:(\S+):/g
    line = line.replace(tagRegex, ':$1:')

    // the final line
    this.push(line)

    // close font changes
    this.push('')

    cb()
  },
  function flush(cb) {
    this.push('')
  })

  return pumpify([
    linestream(),
    transform
  ])
}
<commit_msg>better interactive use (newlines for humans)<commit_after>var linestream = require('line-stream')
var through = require('through2')
var pumpify = require('pumpify')

var doneKeywords = ['DONE']
var notDoneKeywords = ['TODO', 'WAITING', 'STARTED']

module.exports = function () {
  var firstLine = true
  var depth = 0
  var transform = through(function(chunk, enc, cb) {
    if (firstLine) {
      this.push('<meta name="viewport" content="width=device-width, initial-scale=1">\n')
      firstLine = false
    }

    // newlines to br
    var line = chunk.toString()
    line = line.replace(/\n/g, '
')

    // done/not-done keywords
    for (var i in notDoneKeywords) {
      line = line.replace(new RegExp(notDoneKeywords[i]), '' + notDoneKeywords[i] + '')
    }
    for (var i in doneKeywords) {
      line = line.replace(new RegExp(doneKeywords[i]), '' + doneKeywords[i] + '')
    }

    // color or indent based on item depth
    if (/^\* /.test(line)) {
      depth = 1
      this.push('')
    }
    else if (/^\*\* /.test(line)) {
      depth = 2
      this.push('')
    }
    else {
      for (var i=0; i < depth + 2; i++) {
        this.push(' ')
      }
    }

    // tags
    var tagRegex = /:(\S+):/g
    line = line.replace(tagRegex, ':$1:')

    // the final line
    this.push(line)

    // close font changes
    this.push('')

    // push a newline. not needed for html, but it makes human interactive use more pleasant.
    this.push('\n')

    cb()
  },
  function flush(cb) {
    this.push('')
  })

  return pumpify([
    linestream(),
    transform
  ])
}
<|endoftext|>


<commit_before>function httpGetAsync(t,e){xmlHttp=new XMLHttpRequest,xmlHttp.onreadystatechange=function(){e(xmlHttp)},xmlHttp.open("GET",t,!0),"undefined"!=typeof authentication&&xmlHttp.setRequestHeader("Authorization","Basic "+btoa(authentication)),xmlHttp.send(null)}function pickrepo(t,e){if(console.log("Inside pickRepo"),4==t.readyState&&200==t.status)if("Not found"==t.responseText)alert("Not found");else{var o=JSON.parse(t.responseText);if(o.length){for(var n=0,a=0;a<o.length;++a)o[a].stargazers_count>n&&(n=a);var s=o[n];console.log("starred element"),console.log(s),window.open(s.url.replace("api.","").replace("/repos/","/"),"_self"),console.log(s.url.replace("api.","").replace("/repos/","/"))}else{console.log("Retry");var r=Math.floor(Math.random()*e.length),s=e[r],p=s.login;httpGetAsync("https://api.github.com/users/"+p+"/starred",function(t){pickrepo(t,e)})}}}function getUserStars(t){if(4==t.readyState&&200==t.status)if("Not found"==t.responseText)alert("Not found");else{var e=JSON.parse(t.responseText);if(e.length){var o=Math.floor(Math.random()*e.length),n=e[o],a=n.login;httpGetAsync("https://api.github.com/users/"+a+"/starred",function(t){pickrepo(t,e)})}}}var authentication=void 0,num=Math.floor(175e5*Math.random()+1);httpGetAsync("https://api.github.com/users?since="+num,getUserStars);<commit_msg>Reformatting the bookmarklet<commit_after>javascript:function httpGetAsync(t,e){xmlHttp=new XMLHttpRequest,xmlHttp.onreadystatechange=function(){e(xmlHttp)},xmlHttp.open("GET",t,!0),"undefined"!=typeof authentication&&xmlHttp.setRequestHeader("Authorization","Basic "+btoa(authentication)),xmlHttp.send(null)}function pickrepo(t,e){if(console.log("Inside pickRepo"),4==t.readyState&&200==t.status)if("Not found"==t.responseText)alert("Not found");else{var o=JSON.parse(t.responseText);if(o.length){for(var n=0,a=0;a<o.length;++a)o[a].stargazers_count>n&&(n=a);var s=o[n];console.log("starred element"),console.log(s),window.open(s.url.replace("api.","").replace("/repos/","/"),"_self"),console.log(s.url.replace("api.","").replace("/repos/","/"))}else{console.log("Retry");var r=Math.floor(Math.random()*e.length),s=e[r],p=s.login;httpGetAsync("https://api.github.com/users/"+p+"/starred",function(t){pickrepo(t,e)})}}}function getUserStars(t){if(4==t.readyState&&200==t.status)if("Not found"==t.responseText)alert("Not found");else{var e=JSON.parse(t.responseText);if(e.length){var o=Math.floor(Math.random()*e.length),n=e[o],a=n.login;httpGetAsync("https://api.github.com/users/"+a+"/starred",function(t){pickrepo(t,e)})}}}var authentication=undefined,num=Math.floor(175e5*Math.random()+1);httpGetAsync("https://api.github.com/users?since="+num,getUserStars);<|endoftext|>


<commit_before>var slugify = require('slugify');

exports.name = "kabamPluginRoom";

exports.extendModel('groups',function(kernel){
  var GroupsSchema = new kabam.mongoose.Schema({
    'name': {
      type: String,
      trim: true,
      unique: true,
      index: true
      },
    'uri': {
      type: String,
      trim: true,
      unique: true,
      index: true,
      default: function(){
        return slugify(this.name);
        }
      },
    'parent':{
      '_id': mongoose.Schema.Types.ObjectId,
      'name': String,
      'uri': String
    },
    'description': String,
    'members':[{
      '_id': mongoose.Schema.Types.ObjectId,
      'username': String,
      'gravatar': String,
      'firstName': String,
      'lastName': String
    }],
    'admins':[{
      '_id': mongoose.Schema.Types.ObjectId,
      'username': String,
      'gravatar': String,
      'firstName': String,
      'lastName': String
    }]
  });

  GroupsSchema.methods.inviteAdmin = function(usernameOrEmailOrUserObject){};
  GroupsSchema.methods.removeAdmin = function(usernameOrEmailOrUserObject){};

  GroupsSchema.methods.inviteUser = function(usernameOrEmailOrUserObject){};
  GroupsSchema.methods.removeUser = function(usernameOrEmailOrUserObject){};

  GroupsSchema.methods.sendMessage = function(usernameOrEmailOrUserObject, message){};

  return kabam.mongoConnection.model('groups', GroupsSchema);
});
<commit_msg>[feature] - messages object<commit_after>var slugify = require('slugify');

exports.name = "kabamPluginRoom";

exports.extendModel({
'groupMessages': function(kernel){
  var GroupMessagesSchema = new kabam.mongoose.Schema({
    'groupId': mongoose.Schema.Types.ObjectId,
    'userId': mongoose.Schema.Types.ObjectId,
    'message': String,
    'user':{
      'username': String,
      'firstName': String,
      'lastName': String,
      'gravatar': String,
    },
    'createdAt': Date
  });

  return kabam.mongoConnection.model('groupMessages', GroupMessagesSchema);
},
'groups': function(kernel){
  var GroupsSchema = new kabam.mongoose.Schema({
    'name': {
      type: String,
      trim: true,
      unique: true,
      index: true
    },
    'uri': {
      type: String,
      trim: true,
      unique: true,
      index: true,
      default: function(){
        return slugify(this.name);
        }
    },
    'parent':{
      '_id': mongoose.Schema.Types.ObjectId,
      'name': String,
      'uri': String
    },
    'description': String,
    'members':[{
      '_id': mongoose.Schema.Types.ObjectId,
      'username': String,
      'gravatar': String,
      'firstName': String,
      'lastName': String
    }],
    'admins':[{
      '_id': mongoose.Schema.Types.ObjectId,
      'username': String,
      'gravatar': String,
      'firstName': String,
      'lastName': String
    }]
  });

  GroupsSchema.methods.inviteAdmin = function(usernameOrEmailOrUserObject){};
  GroupsSchema.methods.removeAdmin = function(usernameOrEmailOrUserObject){};

  GroupsSchema.methods.inviteUser = function(usernameOrEmailOrUserObject){};
  GroupsSchema.methods.removeUser = function(usernameOrEmailOrUserObject){};

  GroupsSchema.methods.sendMessage = function(usernameOrEmailOrUserObject, message){};

  return kabam.mongoConnection.model('groups', GroupsSchema);
}});
<|endoftext|>


<commit_before>/**
 * A Bot for Slack!
 */

/**
 * Define a function for initiating a conversation on installation
 * With custom integrations, we don't have a way to find out who installed us, so we can't message them :(
 */

function onInstallation(bot, installer) {
    if (installer) {
        bot.startPrivateConversation({user: installer}, function (err, convo) {
            if (err) {
                console.log(err);
            } else {
                convo.say('I am a bot that has just joined your team');
                convo.say('You must now /invite me to a channel so that I can be of use!');
            }
        });
    }
}

/**
 * Configure the persistence options
 */

var config = {};
if (process.env.MONGOLAB_URI) {
    var BotkitStorage = require('botkit-storage-mongo');
    config = {
        storage: BotkitStorage({mongoUri: process.env.MONGOLAB_URI}),
    };
} else {
    config = {
        json_file_store: ((process.env.TOKEN)?'./db_slack_bot_ci/':'./db_slack_bot_a/'), //use a different name if an app or CI
    };
}

/**
 * Are being run as an app or a custom integration? The initialization will differ, depending
 */

if (process.env.TOKEN || process.env.SLACK_TOKEN) {
    //Treat this as a custom integration
    var customIntegration = require('./lib/custom_integrations');
    var token = (process.env.TOKEN) ? process.env.TOKEN : process.env.SLACK_TOKEN;
    var controller = customIntegration.configure(token, config, onInstallation);
} else if (process.env.CLIENT_ID && process.env.CLIENT_SECRET && process.env.PORT) {
    //Treat this as an app
    var app = require('./lib/apps');
    var controller = app.configure(process.env.PORT, process.env.CLIENT_ID, process.env.CLIENT_SECRET, config, onInstallation);
} else {
    console.log('Error: If this is a custom integration, please specify TOKEN in the environment. If this is an app, please specify CLIENTID, CLIENTSECRET, and PORT in the environment');
    process.exit(1);
}

/**
 * A demonstration for how to handle websocket events. In this case, just log when we have and have not
 * been disconnected from the websocket. In the future, it would be super awesome to be able to specify
 * a reconnect policy, and do reconnections automatically. In the meantime, we aren't going to attempt reconnects,
 * WHICH IS A B0RKED WAY TO HANDLE BEING DISCONNECTED. So we need to fix this.
 *
 * TODO: fixed b0rked reconnect behavior
 */
// Handle events related to the websocket connection to Slack
controller.on('rtm_open', function (bot) {
    console.log('** The RTM api just connected!');
});

controller.on('rtm_close', function (bot) {
    console.log('** The RTM api just closed');
    // you may want to attempt to re-open
});

/**
 * Core bot logic goes here!
 */
// BEGIN EDITING HERE!

controller.on('bot_channel_join', function (bot, message) {
    bot.reply(message, "I'm here!")
});

controller.hears('hello', 'direct_message', function (bot, message) {
    bot.reply(message, 'Hello!');
});

controller.hears('lunch run', 'direct_message, direct_mention, message_received', function(bot, message) {

        bot.reply(message, "Oooh! I LOVE Pop-a-Top!");

});

/**
 * AN example of what could be:
 * Any un-handled direct mention gets a reaction and a pat response!
 */
//controller.on('direct_message,mention,direct_mention', function (bot, message) {
//    bot.api.reactions.add({
//        timestamp: message.ts,
//        channel: message.channel,
//        name: 'robot_face',
//    }, function (err) {
//        if (err) {
//            console.log(err)
//        }
//        bot.reply(message, 'I heard you loud and clear boss.');
//    });
//});
<commit_msg>remove message_receieved, line 92 index.js because it is for listening to all messages<commit_after>/**
 * A Bot for Slack!
 */

/**
 * Define a function for initiating a conversation on installation
 * With custom integrations, we don't have a way to find out who installed us, so we can't message them :(
 */

function onInstallation(bot, installer) {
    if (installer) {
        bot.startPrivateConversation({user: installer}, function (err, convo) {
            if (err) {
                console.log(err);
            } else {
                convo.say('I am a bot that has just joined your team');
                convo.say('You must now /invite me to a channel so that I can be of use!');
            }
        });
    }
}

/**
 * Configure the persistence options
 */

var config = {};
if (process.env.MONGOLAB_URI) {
    var BotkitStorage = require('botkit-storage-mongo');
    config = {
        storage: BotkitStorage({mongoUri: process.env.MONGOLAB_URI}),
    };
} else {
    config = {
        json_file_store: ((process.env.TOKEN)?'./db_slack_bot_ci/':'./db_slack_bot_a/'), //use a different name if an app or CI
    };
}

/**
 * Are being run as an app or a custom integration? The initialization will differ, depending
 */

if (process.env.TOKEN || process.env.SLACK_TOKEN) {
    //Treat this as a custom integration
    var customIntegration = require('./lib/custom_integrations');
    var token = (process.env.TOKEN) ? process.env.TOKEN : process.env.SLACK_TOKEN;
    var controller = customIntegration.configure(token, config, onInstallation);
} else if (process.env.CLIENT_ID && process.env.CLIENT_SECRET && process.env.PORT) {
    //Treat this as an app
    var app = require('./lib/apps');
    var controller = app.configure(process.env.PORT, process.env.CLIENT_ID, process.env.CLIENT_SECRET, config, onInstallation);
} else {
    console.log('Error: If this is a custom integration, please specify TOKEN in the environment. If this is an app, please specify CLIENTID, CLIENTSECRET, and PORT in the environment');
    process.exit(1);
}

/**
 * A demonstration for how to handle websocket events. In this case, just log when we have and have not
 * been disconnected from the websocket. In the future, it would be super awesome to be able to specify
 * a reconnect policy, and do reconnections automatically. In the meantime, we aren't going to attempt reconnects,
 * WHICH IS A B0RKED WAY TO HANDLE BEING DISCONNECTED. So we need to fix this.
 *
 * TODO: fixed b0rked reconnect behavior
 */
// Handle events related to the websocket connection to Slack
controller.on('rtm_open', function (bot) {
    console.log('** The RTM api just connected!');
});

controller.on('rtm_close', function (bot) {
    console.log('** The RTM api just closed');
    // you may want to attempt to re-open
});

/**
 * Core bot logic goes here!
 */
// BEGIN EDITING HERE!

controller.on('bot_channel_join', function (bot, message) {
    bot.reply(message, "I'm here!")
});

controller.hears('hello', 'direct_message', function (bot, message) {
    bot.reply(message, 'Hello!');
});

controller.hears('lunch run', 'direct_message, direct_mention', function(bot, message) {

        bot.reply(message, "Oooh! I LOVE Pop-a-Top!");

});

/**
 * AN example of what could be:
 * Any un-handled direct mention gets a reaction and a pat response!
 */
//controller.on('direct_message,mention,direct_mention', function (bot, message) {
//    bot.api.reactions.add({
//        timestamp: message.ts,
//        channel: message.channel,
//        name: 'robot_face',
//    }, function (err) {
//        if (err) {
//            console.log(err)
//        }
//        bot.reply(message, 'I heard you loud and clear boss.');
//    });
//});
<|endoftext|>


<commit_before>/**
 * A Bot for Slack!
 */

/**
 * Define a function for initiating a conversation on installation
 * With custom integrations, we don't have a way to find out who installed us, so we can't message them :(
 */

function onInstallation(bot, installer) {
    if (installer) {
        bot.startPrivateConversation({user: installer}, function (err, convo) {
            if (err) {
                console.log(err);
            } else {
                convo.say('I am a bot that has just joined your team');
                convo.say('You must now /invite me to a channel so that I can be of use!');
            }
        });
    }
}

/**
 * Configure the persistence options
 */

var config = {};
if (process.env.MONGOLAB_URI) {
    var BotkitStorage = require('botkit-storage-mongo');
    config = {
        storage: BotkitStorage({mongoUri: process.env.MONGOLAB_URI}),
    };
} else {
    config = {
        json_file_store: ((process.env.TOKEN)?'./db_slack_bot_ci/':'./db_slack_bot_a/'), //use a different name if an app or CI
    };
}

/**
 * Are being run as an app or a custom integration? The initialization will differ, depending
 */

if (process.env.TOKEN || process.env.SLACK_TOKEN) {
    //Treat this as a custom integration
    var customIntegration = require('./lib/custom_integrations');
    var token = (process.env.TOKEN) ? process.env.TOKEN : process.env.SLACK_TOKEN;
    var controller = customIntegration.configure(token, config, onInstallation);
} else if (process.env.CLIENT_ID && process.env.CLIENT_SECRET && process.env.PORT) {
    //Treat this as an app
    var app = require('./lib/apps');
    var controller = app.configure(process.env.PORT, process.env.CLIENT_ID, process.env.CLIENT_SECRET, config, onInstallation);
} else {
    console.log('Error: If this is a custom integration, please specify TOKEN in the environment. If this is an app, please specify CLIENTID, CLIENTSECRET, and PORT in the environment');
    process.exit(1);
}

/**
 * A demonstration for how to handle websocket events. In this case, just log when we have and have not
 * been disconnected from the websocket. In the future, it would be super awesome to be able to specify
 * a reconnect policy, and do reconnections automatically. In the meantime, we aren't going to attempt reconnects,
 * WHICH IS A B0RKED WAY TO HANDLE BEING DISCONNECTED. So we need to fix this.
 *
 * TODO: fixed b0rked reconnect behavior
 */
// Handle events related to the websocket connection to Slack
controller.on('rtm_open', function (bot) {
    console.log('** The RTM api just connected!');
});

controller.on('rtm_close', function (bot) {
    console.log('** The RTM api just closed');
    // you may want to attempt to re-open
});

/**
 * Core bot logic goes here!
 */
// BEGIN EDITING HERE!

var schedule = require('node-schedule');

var message_options = [
        "Let's talk! What did you do last weekend?",
        "Let's talk! What are you excited about today?",
        "Let's talk! What did you have for breakfast?",
        "Let's talk! What is your favorite food?",
        "Let's talk! What TV Shows are you watching right now?",
        "Let's talk! Add Extreme to a random activity, what are the rules to your new sport?",
        "Let's talk! Any vacations coming up?",
        "Let's talk! What was the first time you ever used a computer?",
        "Let's talk! What do you want to do after you retire?",
        "Let's talk! Any plans this weekend?",
        "Let's talk! Who is your favorite entertainer?",
        "Let's talk! Do you have any pets?",
        "Let's talk! What is your favorite fad?",
        "Let's talk! Who is your oldest friend? How did you meet them?",
        "Let's talk! If you could have any animal as a pet, what would you have?",
        "Let's talk! What is the most useful thing you own?",
        "Let's talk! What is the largest group of people you've ever spoken in front of?",
        "Let's talk! What is your favorite subreddit?",
        "Let's talk! What is your Every Day Carry?",
        "Let's talk! Outside of work, how much time do you spend on the internet per day?",
        "Let's talk! What's your favorite SFW joke?"
	]

var j = schedule.scheduleJob('* 1 * * * ', function(

        var random_index = Math.floor(Math.random() * message_options.length)
        var chosen_message = message_options[random_index]
        bot.say(message, chosen_message);

       ){

});
<commit_msg>fixed?<commit_after>/**
 * A Bot for Slack!
 */

/**
 * Define a function for initiating a conversation on installation
 * With custom integrations, we don't have a way to find out who installed us, so we can't message them :(
 */

function onInstallation(bot, installer) {
    if (installer) {
        bot.startPrivateConversation({user: installer}, function (err, convo) {
            if (err) {
                console.log(err);
            } else {
                convo.say('I am a bot that has just joined your team');
                convo.say('You must now /invite me to a channel so that I can be of use!');
            }
        });
    }
}

/**
 * Configure the persistence options
 */

var config = {};
if (process.env.MONGOLAB_URI) {
    var BotkitStorage = require('botkit-storage-mongo');
    config = {
        storage: BotkitStorage({mongoUri: process.env.MONGOLAB_URI}),
    };
} else {
    config = {
        json_file_store: ((process.env.TOKEN)?'./db_slack_bot_ci/':'./db_slack_bot_a/'), //use a different name if an app or CI
    };
}

/**
 * Are being run as an app or a custom integration? The initialization will differ, depending
 */

if (process.env.TOKEN || process.env.SLACK_TOKEN) {
    //Treat this as a custom integration
    var customIntegration = require('./lib/custom_integrations');
    var token = (process.env.TOKEN) ? process.env.TOKEN : process.env.SLACK_TOKEN;
    var controller = customIntegration.configure(token, config, onInstallation);
} else if (process.env.CLIENT_ID && process.env.CLIENT_SECRET && process.env.PORT) {
    //Treat this as an app
    var app = require('./lib/apps');
    var controller = app.configure(process.env.PORT, process.env.CLIENT_ID, process.env.CLIENT_SECRET, config, onInstallation);
} else {
    console.log('Error: If this is a custom integration, please specify TOKEN in the environment. If this is an app, please specify CLIENTID, CLIENTSECRET, and PORT in the environment');
    process.exit(1);
}

/**
 * A demonstration for how to handle websocket events. In this case, just log when we have and have not
 * been disconnected from the websocket. In the future, it would be super awesome to be able to specify
 * a reconnect policy, and do reconnections automatically. In the meantime, we aren't going to attempt reconnects,
 * WHICH IS A B0RKED WAY TO HANDLE BEING DISCONNECTED. So we need to fix this.
 *
 * TODO: fixed b0rked reconnect behavior
 */
// Handle events related to the websocket connection to Slack
controller.on('rtm_open', function (bot) {
    console.log('** The RTM api just connected!');
});

controller.on('rtm_close', function (bot) {
    console.log('** The RTM api just closed');
    // you may want to attempt to re-open
});

/**
 * Core bot logic goes here!
 */
// BEGIN EDITING HERE!

var schedule = require('node-schedule');

var message_options = [
        "Let's talk! What did you do last weekend?",
        "Let's talk! What are you excited about today?",
        "Let's talk! What did you have for breakfast?",
        "Let's talk! What is your favorite food?",
        "Let's talk! What TV Shows are you watching right now?",
        "Let's talk! Add Extreme to a random activity, what are the rules to your new sport?",
        "Let's talk! Any vacations coming up?",
        "Let's talk! What was the first time you ever used a computer?",
        "Let's talk! What do you want to do after you retire?",
        "Let's talk! Any plans this weekend?",
        "Let's talk! Who is your favorite entertainer?",
        "Let's talk! Do you have any pets?",
        "Let's talk! What is your favorite fad?",
        "Let's talk! Who is your oldest friend? How did you meet them?",
        "Let's talk! If you could have any animal as a pet, what would you have?",
        "Let's talk! What is the most useful thing you own?",
        "Let's talk! What is the largest group of people you've ever spoken in front of?",
        "Let's talk! What is your favorite subreddit?",
        "Let's talk! What is your Every Day Carry?",
        "Let's talk! Outside of work, how much time do you spend on the internet per day?",
        "Let's talk! What's your favorite SFW joke?"
	];

var j = schedule.scheduleJob('* 1 * * * ', function () {

        var random_index = Math.floor(Math.random() * message_options.length);
        var chosen_message = message_options[random_index];
        bot.say(message, chosen_message)
        }

       );

<|endoftext|>


<commit_before>/*
 * fis
 * http://web.baidu.com/
 */

'use strict';

var UglifyJS = require('uglify-js');

module.exports = function(content, file, conf, fis){
    conf.fromString = true;
    UglifyJS.AST_Node.warn_function = function(txt){
        fis.log.error(txt)
    };
    return UglifyJS.minify(content, conf).code;
};<commit_msg>fis升级为全局对象<commit_after>/*
 * fis
 * http://web.baidu.com/
 */

'use strict';

var UglifyJS = require('uglify-js');

module.exports = function(content, file, conf){
    conf.fromString = true;
    UglifyJS.AST_Node.warn_function = function(txt){
        fis.log.error(txt)
    };
    return UglifyJS.minify(content, conf).code;
};<|endoftext|>


<commit_before>const Promise = require('bluebird');
const fs = Promise.promisifyAll(require('fs'));
const os = require('os');
if (!os.EOL) {
  os.EOL = (process.platform === 'win32' ? '\r\n' : '\n');
}

const xpath = require('xpath');
const { DOMParser, XMLSerializer } = require('xmldom');
const format = require('xml-formatter');
let fontName;
let ligFontName;

const regEx = /\.liga$/;
const regExBlankLines = /^(?=\n)$|^\s*/gm;
const regExWhitespace = /^\s+$/;
const NodeType = {};
NodeType.TEXT_NODE = 3;

async function main() {
  fontName = process.argv[2];
  ligFontName = fontName.split('-').join('Lig-');

  const srcFileName = `./original/${fontName}.ttx`;
  const dstFileName = `./build/${ligFontName}.ttx`;
  console.log(`Reading original font file ${srcFileName}`);
  const xml = await fs.readFileAsync(srcFileName, 'utf-8');
  const dom = new DOMParser().parseFromString(xml);

  await processPatch('names', patchNames, dom);
  await processPatch('glyphs', patchGlyphs, dom);
  await processPatch('gpos', patchGpos, dom);
  await processPatch('gsub', patchGsub, dom);
  await processPatch('hmtx', patchHmtx, dom);
  await processPatch('lookup', patchLookup, dom);
  await processPatch('charstrings', patchCharStrings, dom);

  console.log(`Writing ligature font file ${dstFileName}`);
  await fs.writeFileAsync(dstFileName, format(serialize(dom)));
  console.log('Done');
}

async function loadConfigAsync(name) {
  const fileName = `./ligature/${ligFontName}/${name}.xml`;
  const xml = await fs.readFileAsync(fileName, 'utf-8');
  return new DOMParser().parseFromString(xml);
}

async function processPatch(name, patchFunc, dom) {
  console.log(`Patching ${name}`);
  await patchFunc(dom);
}

async function patchNames(dom) {
  const configDom = await loadConfigAsync('names');

  const names = xpath.select('/name/namerecord', configDom);
  const targetName = xpath.select('/ttFont/name', dom, true);

  // get font and family name
  const familyName = getTextNode(
    configDom,
    '/name/namerecord[@nameID="1" and @platformID="1"]'
  );
  const fullName = getTextNode(
    configDom,
    '/name/namerecord[@nameID="4" and @platformID="1"]'
  );

  // patch CFFFont
  const cffFont = xpath.select('/ttFont/CFF/CFFFont', dom, true);

  cffFont.setAttribute('name', ligFontName);
  setAttribute(cffFont, 'FullName', 'value', fullName);
  setAttribute(cffFont, 'FamilyName', 'value', familyName);

  // update existing names with new names
  names.forEach(node => {
    const nameId = node.getAttribute('nameID');
    const platformId = node.getAttribute('platformID');

    // search for namerecord in target dom and replace with this one or append node
    const target = xpath.select(
      `/ttFont/name/namerecord[@nameID="${nameId}" and @platformID="${platformId}"]`,
      dom,
      true
    );
    if (target) {
      target.parentNode.replaceChild(node, target);
    } else {
      targetName.appendChild(node);
    }
  });
}

async function patchGlyphs(dom) {
  const configDom = await loadConfigAsync('../glyphs');
  // get number of glyphs in target dom
  const targetGlyphs = xpath.select('/ttFont/GlyphOrder', dom, true);
  const glyphsCount = xpath.select('count(GlyphID)', targetGlyphs, true);

  let n = glyphsCount;
  // get ligature glyphs
  const glyphs = xpath.select('/GlyphOrder/GlyphID', configDom);
  glyphs.forEach(node => {
    node.setAttribute('id', n++);
    targetGlyphs.appendChild(node);
  });

  // update glyph count
  setAttribute(dom, '/ttFont/maxp/numGlyphs', 'value', n);
}

async function patchGpos(dom) {
  const newGpos = await loadConfigAsync('gpos');
  const oldGpos = xpath.select('/ttFont/GPOS', dom, true);
  dom.documentElement.replaceChild(newGpos, oldGpos);
}

async function patchGsub(dom) {
  const newGsub = await loadConfigAsync('gsub');

  // loop through Substituion/Ligature nodes and remap chars
  remap(newGsub, dom, '//Substitution', 'out');
  remap(newGsub, dom, '//Ligature', 'glyph');

  const oldGsub = xpath.select('/ttFont/GSUB', dom, true);
  dom.documentElement.replaceChild(newGsub, oldGsub);
}

const remap = (patchDom, cmapDom, path, attr) => {
  const cmap = [];
  let nodes = xpath.select(path, patchDom);
  nodes.forEach(n => {
    const out = n.getAttribute(attr);
    if (out.startsWith('uni')) {
      // get cmap entry
      const code = '0x' + out.replace(/uni0*/g, '').toLowerCase();
      let name = cmap[code];
      if (!name) {
        const map = xpath.select(`/ttFont/cmap/cmap_format_4/map[@code="${code}"]`, cmapDom, true);
        name = map == null ? out : map.getAttribute('name');
        cmap[code] = name;
      }
      n.setAttribute(attr, name);
    }
  });
}

async function patchHmtx(dom) {
  const hmtxDom = await loadConfigAsync('hmtx');
  const targetHmtx = xpath.select('/ttFont/hmtx', dom, true);

  const mtx = xpath.select('/hmtx/mtx', hmtxDom);
  mtx.forEach(node => targetHmtx.appendChild(node));

  const mtxCount = xpath.select('count(/ttFont/hmtx/mtx)', dom, true);
  setAttribute(dom, '/ttFont/hhea/numberOfHMetrics', 'value', mtxCount);

  const configDom = await loadConfigAsync('config');
  copyConfigAttribute(dom, configDom, '/ttFont/head/xMin', 'value');
  copyConfigAttribute(dom, configDom, '/ttFont/head/yMin', 'value');
  copyConfigAttribute(dom, configDom, '/ttFont/head/xMax', 'value');
  copyConfigAttribute(dom, configDom, '/ttFont/head/yMax', 'value');
  copyConfigAttribute(dom, configDom, '/ttFont/hhea/advanceWidthMax', 'value');
  copyConfigAttribute(dom, configDom, '/ttFont/hhea/xMaxExtent', 'value');
  copyConfigAttribute(dom, configDom, '/ttFont/CFF/CFFFont/FontBBox', 'value');
  copyConfigAttribute(
    dom,
    configDom,
    '/ttFont/CFF/CFFFont/Private/nominalWidthX',
    'value'
  );
}

async function patchLookup(dom) {
  const configDom = await loadConfigAsync('../lookup');
  const featureList = xpath.select('/ttFont/GSUB/FeatureList', dom, true);

  const featuresCount = xpath.select(
    'count(/ttFont/GSUB/FeatureList/FeatureRecord)',
    dom,
    true
  );
  const featureRecord = dom.createElement('FeatureRecord');
  featureRecord.setAttribute('index', featuresCount);
  const featureTag = dom.createElement('FeatureTag');
  featureTag.setAttribute('value', 'liga');
  const feature = dom.createElement('Feature');
  featureRecord.appendChild(featureTag);
  featureRecord.appendChild(feature);
  featureList.appendChild(featureRecord);

  const lookupCount = xpath.select('count(/ttFont/GSUB/LookupList/Lookup)', dom, true);
  const lookupListIndex = dom.createElement('LookupListIndex');
  lookupListIndex.setAttribute('index', '0');
  lookupListIndex.setAttribute('value', lookupCount);
  feature.appendChild(lookupListIndex);

  // helper function for adding feature to ScriptRecord
  const addFeature = (scriptRecord, featureRecord, lang) => {
    if (!lang) return;
    const index = featureRecord.getAttribute('index');
    if (xpath.select(`FeatureIndex[@value="${index}"]`, lang, true)) return;

    const count = xpath.select('count(FeatureIndex)', lang, true);
    const featureIndex = dom.createElement('FeatureIndex');
    featureIndex.setAttribute('index', count);
    featureIndex.setAttribute('value', index);
    lang.appendChild(featureIndex);
  };

  // nead to add feature to ScriptList
  const scriptList = xpath.select('/ttFont/GSUB/ScriptList', dom, true);
  const scriptRecords = xpath.select('ScriptRecord', scriptList);
  scriptRecords.forEach(node => {
    // check for feature in DefaultLangSys
    addFeature(
      node,
      featureRecord,
      xpath.select('Script/DefaultLangSys', node, true)
    );
    // add features to any other languages
    xpath
      .select('Script/LangSysRecord/LangSys', node)
      .forEach(lang => addFeature(node, featureRecord, lang));
  });

  // finally add LigatureSubst to Lookup
  const lookupList = xpath.select('/ttFont/GSUB/LookupList', dom, true);
  const newLookup = xpath.select('/LookupList/Lookup', configDom, true);
  newLookup.setAttribute('index', lookupCount);
  lookupList.appendChild(newLookup);
}

async function patchCharStrings(dom) {
  const configDom = await loadConfigAsync('charstrings');
  const nameDom = await loadConfigAsync('names');

  // get font and family name
  const familyName = getTextNode(nameDom, '/name/namerecord[@nameID="1" and @platformID="1"]');
  const fullName = getTextNode(nameDom, '/name/namerecord[@nameID="4" and @platformID="1"]');

  // patch CFFFont
  const cffFont = xpath.select('/ttFont/CFF/CFFFont', dom, true);

  cffFont.setAttribute('name', ligFontName);
  setAttribute(cffFont, 'FullName', 'value', fullName);
  setAttribute(cffFont, 'FamilyName', 'value', familyName);

  const charStrings = xpath.select('/CharStrings/CharString', configDom);
  const targetCharStrings = xpath.select('CharStrings', cffFont, true);

  const subrs = {
    map: [],
    source: await loadConfigAsync('subrs'),
    target: xpath.select('/ttFont/CFF/CFFFont/Private/Subrs', dom, true)
  };
  const gsubrs = {
    map: [],
    source: await loadConfigAsync('gsubrs'),
    target: xpath.select('/ttFont/CFF/GlobalSubrs', dom, true)
  };

  charStrings.forEach(node => {
    patchCharStringSubrs(node, subrs, gsubrs);
    targetCharStrings.appendChild(node);
  });
}

const patchCharStringSubrs = (node, subrs, gsubrs) => {
  // check for callsubr/callgsubr

  const lines = node.childNodes[0].textContent.split(os.EOL);
  const newLines = [];
  let patched = false;
  lines.forEach(line => {
    const matches = line.match(/(.*?)(-?\d+) (callsubr|callgsubr)$/);
    if (matches != null) {
      const { map, source, target } =
        matches[3] === 'callsubr' ? subrs : gsubrs;
      const index = matches[2];
      let newIndex = 0;
      if (!map[index]) {
        // find subr in source dom and copy to target dom
        const srcIndex = parseInt(index) + 107;
        const srcSubr = xpath.select(
          `//CharString[@index="${srcIndex}"]`,
          source,
          true
        );

        // patch up source in case it also has any callsubrs
        patchCharStringSubrs(srcSubr, subrs, gsubrs);

        // append subr to target dom and get new index
        newIndex = xpath.select('count(CharString)', target, true);
        srcSubr.setAttribute('index', newIndex);
        target.appendChild(srcSubr);

        // add new index to map and rewrite call
        newIndex = newIndex - 107;
        map[index] = newIndex;
      } else {
        newIndex = map[index];
      }

      // rewrite line with new subr index
      line = `${matches[1]}${newIndex} ${matches[3]}`;
      patched = true;
    }
    newLines.push(line);
  });
  if (patched) {
    node.childNodes[0].textContent = newLines.join(os.EOL);
  }
};

const setAttribute = (parent, path, name, value) => {
  var node = xpath.select(path, parent, true);
  node.setAttribute(name, value);
};

const copyConfigAttribute = (dom, configDom, path, name) => {
  const value = xpath.select(path, configDom, true).getAttribute(name);
  setAttribute(dom, path, name, value);
};

const getTextNode = (dom, path) => {
  var node = xpath.select(path, dom, true);
  return node && node.childNodes.length
    ? node.childNodes[0].nodeValue.trim()
    : '';
};

const serialize = dom =>
  new XMLSerializer().serializeToString(dom, false, node => {
    if (node.nodeType === NodeType.TEXT_NODE) {
      if (regExWhitespace.test(node.data)) return null;
      const data = node.data
        .split('\r\n')
        .filter(s => /\S+/.test(s))
        .map(s => s.replace(/^\s+/g, ''))
        .join('\n');

      return node.ownerDocument.createTextNode(data);
    }
    return node;
  });

main();
<commit_msg>Add try/catch and code formatting<commit_after>const Promise = require('bluebird');
const fs = Promise.promisifyAll(require('fs'));
const os = require('os');
if (!os.EOL) {
  os.EOL = process.platform === 'win32' ? '\r\n' : '\n';
}

const xpath = require('xpath');
const { DOMParser, XMLSerializer } = require('xmldom');
const format = require('xml-formatter');
let fontName;
let ligFontName;

const regEx = /\.liga$/;
const regExBlankLines = /^(?=\n)$|^\s*/gm;
const regExWhitespace = /^\s+$/;
const NodeType = {};
NodeType.TEXT_NODE = 3;

async function main() {
  fontName = process.argv[2];
  ligFontName = fontName.split('-').join('Lig-');

  const srcFileName = `./original/${fontName}.ttx`;
  const dstFileName = `./build/${ligFontName}.ttx`;
  console.log(`Reading original font file ${srcFileName}`);
  const xml = await fs.readFileAsync(srcFileName, 'utf-8');
  const dom = new DOMParser().parseFromString(xml);

  try {
    await processPatch('names', patchNames, dom);
    await processPatch('glyphs', patchGlyphs, dom);
    await processPatch('gpos', patchGpos, dom);
    await processPatch('gsub', patchGsub, dom);
    await processPatch('hmtx', patchHmtx, dom);
    //await processPatch('lookup', patchLookup, dom);
    await processPatch('charstrings', patchCharStrings, dom);
  } catch (err) {
    console.log(err);
  }

  console.log(`Writing ligature font file ${dstFileName}`);
  await fs.writeFileAsync(dstFileName, format(serialize(dom)));
  console.log('Done');
}

async function loadConfigAsync(name) {
  const fileName = `./ligature/${ligFontName}/${name}.xml`;
  const xml = await fs.readFileAsync(fileName, 'utf-8');
  return new DOMParser().parseFromString(xml);
}

async function processPatch(name, patchFunc, dom) {
  console.log(`Patching ${name}`);
  await patchFunc(dom);
}

async function patchNames(dom) {
  const configDom = await loadConfigAsync('names');

  const names = xpath.select('/name/namerecord', configDom);
  const targetName = xpath.select('/ttFont/name', dom, true);

  // get font and family name
  const familyName = getTextNode(
    configDom,
    '/name/namerecord[@nameID="1" and @platformID="1"]'
  );
  const fullName = getTextNode(
    configDom,
    '/name/namerecord[@nameID="4" and @platformID="1"]'
  );

  // patch CFFFont
  const cffFont = xpath.select('/ttFont/CFF/CFFFont', dom, true);

  cffFont.setAttribute('name', ligFontName);
  setAttribute(cffFont, 'FullName', 'value', fullName);
  setAttribute(cffFont, 'FamilyName', 'value', familyName);

  // update existing names with new names
  names.forEach(node => {
    const nameId = node.getAttribute('nameID');
    const platformId = node.getAttribute('platformID');

    // search for namerecord in target dom and replace with this one or append node
    const target = xpath.select(
      `/ttFont/name/namerecord[@nameID="${nameId}" and @platformID="${platformId}"]`,
      dom,
      true
    );
    if (target) {
      target.parentNode.replaceChild(node, target);
    } else {
      targetName.appendChild(node);
    }
  });
}

async function patchGlyphs(dom) {
  const configDom = await loadConfigAsync('../glyphs');
  // get number of glyphs in target dom
  const targetGlyphs = xpath.select('/ttFont/GlyphOrder', dom, true);
  const glyphsCount = xpath.select('count(GlyphID)', targetGlyphs, true);

  let n = glyphsCount;
  // get ligature glyphs
  const glyphs = xpath.select('/GlyphOrder/GlyphID', configDom);
  glyphs.forEach(node => {
    node.setAttribute('id', n++);
    targetGlyphs.appendChild(node);
  });

  // update glyph count
  setAttribute(dom, '/ttFont/maxp/numGlyphs', 'value', n);
}

async function patchGpos(dom) {
  const newGpos = await loadConfigAsync('gpos');
  const oldGpos = xpath.select('/ttFont/GPOS', dom, true);
  dom.documentElement.replaceChild(newGpos, oldGpos);
}

async function patchGsub(dom) {
  const newGsub = await loadConfigAsync('gsub');

  // loop through Substituion/Ligature nodes and remap chars
  remap(newGsub, dom, '//Substitution', 'out');
  remap(newGsub, dom, '//Ligature', 'glyph');

  const oldGsub = xpath.select('/ttFont/GSUB', dom, true);
  dom.documentElement.replaceChild(newGsub, oldGsub);
}

const remap = (patchDom, cmapDom, path, attr) => {
  const cmap = [];
  let nodes = xpath.select(path, patchDom);
  nodes.forEach(n => {
    const out = n.getAttribute(attr);
    if (out.startsWith('uni')) {
      // get cmap entry
      const code = '0x' + out.replace(/uni0*/g, '').toLowerCase();
      let name = cmap[code];
      if (!name) {
        const map = xpath.select(
          `/ttFont/cmap/cmap_format_4/map[@code="${code}"]`,
          cmapDom,
          true
        );
        name = map == null ? out : map.getAttribute('name');
        cmap[code] = name;
      }
      n.setAttribute(attr, name);
    }
  });
};

async function patchHmtx(dom) {
  const hmtxDom = await loadConfigAsync('hmtx');
  const targetHmtx = xpath.select('/ttFont/hmtx', dom, true);

  const mtx = xpath.select('/hmtx/mtx', hmtxDom);
  mtx.forEach(node => targetHmtx.appendChild(node));

  const mtxCount = xpath.select('count(/ttFont/hmtx/mtx)', dom, true);
  setAttribute(dom, '/ttFont/hhea/numberOfHMetrics', 'value', mtxCount);

  const configDom = await loadConfigAsync('config');
  copyConfigAttribute(dom, configDom, '/ttFont/head/xMin', 'value');
  copyConfigAttribute(dom, configDom, '/ttFont/head/yMin', 'value');
  copyConfigAttribute(dom, configDom, '/ttFont/head/xMax', 'value');
  copyConfigAttribute(dom, configDom, '/ttFont/head/yMax', 'value');
  copyConfigAttribute(dom, configDom, '/ttFont/hhea/advanceWidthMax', 'value');
  copyConfigAttribute(dom, configDom, '/ttFont/hhea/xMaxExtent', 'value');
  copyConfigAttribute(dom, configDom, '/ttFont/CFF/CFFFont/FontBBox', 'value');
  copyConfigAttribute(
    dom,
    configDom,
    '/ttFont/CFF/CFFFont/Private/nominalWidthX',
    'value'
  );
}

async function patchLookup(dom) {
  const configDom = await loadConfigAsync('../lookup');
  const featureList = xpath.select('/ttFont/GSUB/FeatureList', dom, true);

  const featuresCount = xpath.select(
    'count(/ttFont/GSUB/FeatureList/FeatureRecord)',
    dom,
    true
  );
  const featureRecord = dom.createElement('FeatureRecord');
  featureRecord.setAttribute('index', featuresCount);
  const featureTag = dom.createElement('FeatureTag');
  featureTag.setAttribute('value', 'liga');
  const feature = dom.createElement('Feature');
  featureRecord.appendChild(featureTag);
  featureRecord.appendChild(feature);
  featureList.appendChild(featureRecord);

  const lookupCount = xpath.select(
    'count(/ttFont/GSUB/LookupList/Lookup)',
    dom,
    true
  );
  const lookupListIndex = dom.createElement('LookupListIndex');
  lookupListIndex.setAttribute('index', '0');
  lookupListIndex.setAttribute('value', lookupCount);
  feature.appendChild(lookupListIndex);

  // helper function for adding feature to ScriptRecord
  const addFeature = (scriptRecord, featureRecord, lang) => {
    if (!lang) return;
    const index = featureRecord.getAttribute('index');
    if (xpath.select(`FeatureIndex[@value="${index}"]`, lang, true)) return;

    const count = xpath.select('count(FeatureIndex)', lang, true);
    const featureIndex = dom.createElement('FeatureIndex');
    featureIndex.setAttribute('index', count);
    featureIndex.setAttribute('value', index);
    lang.appendChild(featureIndex);
  };

  // nead to add feature to ScriptList
  const scriptList = xpath.select('/ttFont/GSUB/ScriptList', dom, true);
  const scriptRecords = xpath.select('ScriptRecord', scriptList);
  scriptRecords.forEach(node => {
    // check for feature in DefaultLangSys
    addFeature(
      node,
      featureRecord,
      xpath.select('Script/DefaultLangSys', node, true)
    );
    // add features to any other languages
    xpath
      .select('Script/LangSysRecord/LangSys', node)
      .forEach(lang => addFeature(node, featureRecord, lang));
  });

  // finally add LigatureSubst to Lookup
  const lookupList = xpath.select('/ttFont/GSUB/LookupList', dom, true);
  const newLookup = xpath.select('/LookupList/Lookup', configDom, true);
  newLookup.setAttribute('index', lookupCount);
  lookupList.appendChild(newLookup);
}

async function patchCharStrings(dom) {
  const configDom = await loadConfigAsync('charstrings');
  const nameDom = await loadConfigAsync('names');

  // get font and family name
  const familyName = getTextNode(
    nameDom,
    '/name/namerecord[@nameID="1" and @platformID="1"]'
  );
  const fullName = getTextNode(
    nameDom,
    '/name/namerecord[@nameID="4" and @platformID="1"]'
  );

  // patch CFFFont
  const cffFont = xpath.select('/ttFont/CFF/CFFFont', dom, true);

  cffFont.setAttribute('name', ligFontName);
  setAttribute(cffFont, 'FullName', 'value', fullName);
  setAttribute(cffFont, 'FamilyName', 'value', familyName);

  const charStrings = xpath.select('/CharStrings/CharString', configDom);
  const targetCharStrings = xpath.select('CharStrings', cffFont, true);

  const subrs = {
    map: [],
    source: await loadConfigAsync('subrs'),
    target: xpath.select('/ttFont/CFF/CFFFont/Private/Subrs', dom, true)
  };
  const gsubrs = {
    map: [],
    source: await loadConfigAsync('gsubrs'),
    target: xpath.select('/ttFont/CFF/GlobalSubrs', dom, true)
  };

  charStrings.forEach(node => {
    patchCharStringSubrs(node, subrs, gsubrs);
    targetCharStrings.appendChild(node);
  });
}

const patchCharStringSubrs = (node, subrs, gsubrs) => {
  // check for callsubr/callgsubr

  const lines = node.childNodes[0].textContent.split(os.EOL);
  const newLines = [];
  let patched = false;
  lines.forEach(line => {
    const matches = line.match(/(.*?)(-?\d+) (callsubr|callgsubr)$/);
    if (matches != null) {
      const { map, source, target } =
        matches[3] === 'callsubr' ? subrs : gsubrs;
      const index = matches[2];
      let newIndex = 0;
      if (!map[index]) {
        // find subr in source dom and copy to target dom
        const srcIndex = parseInt(index) + 107;
        const srcSubr = xpath.select(
          `//CharString[@index="${srcIndex}"]`,
          source,
          true
        );

        // patch up source in case it also has any callsubrs
        patchCharStringSubrs(srcSubr, subrs, gsubrs);

        // append subr to target dom and get new index
        newIndex = xpath.select('count(CharString)', target, true);
        srcSubr.setAttribute('index', newIndex);
        target.appendChild(srcSubr);

        // add new index to map and rewrite call
        newIndex = newIndex - 107;
        map[index] = newIndex;
      } else {
        newIndex = map[index];
      }

      // rewrite line with new subr index
      line = `${matches[1]}${newIndex} ${matches[3]}`;
      patched = true;
    }
    newLines.push(line);
  });
  if (patched) {
    node.childNodes[0].textContent = newLines.join(os.EOL);
  }
};

const setAttribute = (parent, path, name, value) => {
  var node = xpath.select(path, parent, true);
  node.setAttribute(name, value);
};

const copyConfigAttribute = (dom, configDom, path, name) => {
  const value = xpath.select(path, configDom, true).getAttribute(name);
  setAttribute(dom, path, name, value);
};

const getTextNode = (dom, path) => {
  var node = xpath.select(path, dom, true);
  return node && node.childNodes.length
    ? node.childNodes[0].nodeValue.trim()
    : '';
};

const serialize = dom =>
  new XMLSerializer().serializeToString(dom, false, node => {
    if (node.nodeType === NodeType.TEXT_NODE) {
      if (regExWhitespace.test(node.data)) return null;
      const data = node.data
        .split('\r\n')
        .filter(s => /\S+/.test(s))
        .map(s => s.replace(/^\s+/g, ''))
        .join('\n');

      return node.ownerDocument.createTextNode(data);
    }
    return node;
  });

main();
<|endoftext|>


<commit_before>/*jslint node: true */
"use strict";

var netdna = require('netdna')

module.exports = function (credentials) {
  if (!credentials.companyAlias) throw(new Error('Missing `companyAlias`!'))
  if (!credentials.consumerKey) throw(new Error('Missing `consumerKey`!'))
  if (!credentials.consumerSecret) throw(new Error('Missing `consumerSecret`!'))
  if (!credentials.zoneId) throw(new Error('Missing `zoneId`!'))

  netdna = netdna({
    companyAlias: credentials.companyAlias,
    consumerKey: credentials.consumerKey,
    consumerSecret: credentials.consumerSecret
  })

  var url = 'zones/pull.json/' + credentials.zoneId + '/cache'
  netdna.delete(url, function (err, response) {
    if (err || response.code !== 200) {
      throw(new Error('Unexpected NetDNA response code: ' + response.code))
    }
  })
}
<commit_msg>accept callback<commit_after>/*jslint node: true */
"use strict";

var netdna = require('netdna')

module.exports = function (credentials, cb) {
  if (!credentials.companyAlias) throw(new Error('Missing `companyAlias`!'))
  if (!credentials.consumerKey) throw(new Error('Missing `consumerKey`!'))
  if (!credentials.consumerSecret) throw(new Error('Missing `consumerSecret`!'))
  if (!credentials.zoneId) throw(new Error('Missing `zoneId`!'))

  netdna = netdna({
    companyAlias: credentials.companyAlias,
    consumerKey: credentials.consumerKey,
    consumerSecret: credentials.consumerSecret
  })

  var url = 'zones/pull.json/' + credentials.zoneId + '/cache'
  netdna.delete(url, function (err, response) {
    if (err || response.code !== 200) {
      cb(new Error('Unexpected NetDNA response code: ' + response.code))
    } else {
      cb(null)
    }
  })
}
<|endoftext|>


<commit_before>var exec = require('child_process').exec
var child

function debug() {
	//console.log.apply(console, arguments)
}

function Sparky(config) {

	if (!config.deviceId) {
		console.log('Device id not found.')
	}

	if (!config.token) {
		console.log('Spark token not found.')
	}

	this.config = config

	this._throttle = 0
}

Sparky.prototype = {
	_command: function(command, params, callback) {

		if (this._throttle > 0 && Date.now() < this._throttle) {
			return false
		}
		this._throttle = 0

		command = command.toLowerCase()
		command = 'curl https://api.spark.io/v1/devices/' + this.config.deviceId + '/' + command + '   -d access_token=' + this.config.token + ' -d params=' + params
		debug('Running command: ', command)
		child = exec(command,
			function (error, stdout, stderr) {
			debug('stdout: ' + stdout)
			debug('stderr: ' + stderr)
			if (error !== null) {
			  debug('exec error: ' + error)
			}
			if (callback) {
				callback(JSON.parse(stdout).return_value)
			}
		})
	},

	/**
	 * Formats values to expected values,
	 * 1, true -> 'HIGH'
	 * 0, false -> 'LOW'
	 */
	formatDigitalValue: function(value) {
		return value ? 'HIGH' : 'LOW'
	},

	digitalWrite: function(pin, value) {
		value = this.formatDigitalValue(value)
		this._command('digitalWrite', pin + ',' + value)
	},

	analogWrite: function(pin, value) {
		this._command('analogWrite', pin + ',' + value)
	},

	digitalRead: function(pin, callback) {
		this._command('digitalRead', pin, callback)
	},

	analogRead: function(pin, callback) {
		this._command('analogRead', pin, callback)
	},

	/**
	 * Runs one a custom spark core command
	 */
	run: function(pin, params, callback) {
		this._command('analogRead', params, callback)
	},

	/**
	 * Only run the next command if we have not written to the same pin based on ms
	 * @param {Integer} Number of seconds to throttle
	 */
	throttle: function(ms) {
		// Set throttle if we don't have one set
		if (this._throttle === 0) {
			this._throttle = Date.now() + ms
		}
		return this
	}
}

exports.Sparky = Sparky
<commit_msg>Use process.env for config values if not passed at creation and allow usage of custom Spark commands<commit_after>var exec = require('child_process').exec;
var child;

function debug() {
	//console.log.apply(console, arguments)
}

function Sparky(config) {

	// If no config obj exists, make one
	if (!config) {
		config = {};
	}

	// Check the process.env if values aren't passed in the config
	if (!config.deviceId && process.env.SPARK_DEVICE_ID) {
		config.deviceId = process.env.SPARK_DEVICE_ID;
	}
	if (!config.token && process.env.SPARK_TOKEN) {
		config.token = process.env.SPARK_TOKEN;
	}

	// Bail if we don't have config values
	if (!config.deviceId) {
		console.log('Device id not found.');
		process.exit(1);
	}
	if (!config.token) {
		console.log('Spark token not found.');
		process.exit(1);
	}

	this.config = config;

	this._throttle = 0;
}

Sparky.prototype = {
	_command: function(command, params, callback) {

		if (this._throttle > 0 && Date.now() < this._throttle) {
			return false;
		}
		this._throttle = 0;

		command = command.toLowerCase();
		command = 'curl https://api.spark.io/v1/devices/' + this.config.deviceId + '/' + command + '   -d access_token=' + this.config.token + ' -d params=' + params;
		debug('Running command: ', command);
		child = exec(command,
			function (error, stdout, stderr) {
			debug('stdout: ' + stdout);
			debug('stderr: ' + stderr);
			if (error !== null) {
				debug('exec error: ' + error);
			}
			if (callback) {
				callback(JSON.parse(stdout).return_value);
			}
		});
	},

	/**
	 * Formats values to expected values,
	 * 1, true -> 'HIGH'
	 * 0, false -> 'LOW'
	 */
	formatDigitalValue: function(value) {
		return value ? 'HIGH' : 'LOW';
	},

	digitalWrite: function(pin, value) {
		value = this.formatDigitalValue(value);
		this._command('digitalWrite', pin + ',' + value);
	},

	analogWrite: function(pin, value) {
		this._command('analogWrite', pin + ',' + value);
	},

	digitalRead: function(pin, callback) {
		this._command('digitalRead', pin, callback);
	},

	analogRead: function(pin, callback) {
		this._command('analogRead', pin, callback);
	},

	/**
	 * Runs a custom spark core command
	 */
	run: function(command, params, callback) {
		this._command(command, params, callback);
	},

	/**
	 * Only run the next command if we have not written to the same pin based on ms
	 * @param {Integer} Number of seconds to throttle
	 */
	throttle: function(ms) {
		// Set throttle if we don't have one set
		if (this._throttle === 0) {
			this._throttle = Date.now() + ms;
		}
		return this;
	}
};

exports.Sparky = Sparky;
<|endoftext|>


<commit_before>'use strict';

var request = require('request');

makeRequest.jar = request.jar;

module.exports = makeRequest;

function makeRequest(server, reqOpts, cb) {
    if (server.address()) {
        onPort();
    } else {
        server.once('listening', onPort);
    }

    function onPort() {
        var port = server.address().port;

        var url = 'http://localhost:' + port;
        reqOpts.url = url + reqOpts.url;

        request(reqOpts, cb);
    }
}
<commit_msg>grab host from address<commit_after>'use strict';

var request = require('request');

makeRequest.jar = request.jar;

module.exports = makeRequest;

function makeRequest(server, reqOpts, cb) {
    if (server.address()) {
        onPort();
    } else {
        server.once('listening', onPort);
    }

    function onPort() {
        var port = server.address().port;
        var host = server.address().address || 'localhost';

        var url = 'http://' + host + ':' + port;
        reqOpts.url = url + reqOpts.url;

        request(reqOpts, cb);
    }
}
<|endoftext|>


<commit_before>(function(_){
    "use strict";
    describe("keph controllers test suite", function(){
        var createController, $scope, $stateParams, $httpBackend, $state, adminApi;
        var formService, SERVER_URL;

        beforeEach(function(){
            module("mflAdminApp");
            inject(["$rootScope", "$controller", "$stateParams", "$httpBackend",
                   "$state", "adminApi","mfl.common.forms.changes","SERVER_URL",
                   function($rootScope, $controller,_$stateParams,
                    _$httpBackend, _$state, _adminApi, frm, _SERVER_URL){
                $scope = $rootScope.$new();
                SERVER_URL = _SERVER_URL;
                $httpBackend = _$httpBackend;
                $stateParams = _$stateParams;
                $state = _$state;
                adminApi = _adminApi;
                formService = frm;
                var data = {
                    $scope: $scope
                };
                createController = function(ctrl, params){
                    return $controller(ctrl, _.extend(data, params));

                };
            }]);
        });

        afterEach(function(){
            $httpBackend.verifyNoOutstandingRequest();
            $httpBackend.verifyNoOutstandingExpectation();
        });

        it("should have `mfl.setup.controller.keph.list` defined", function() {
            var ctrl = createController("mfl.setup.controller.keph.list", {});
            expect(ctrl).toBeDefined();
        });

        it("should create a new KEPH level", function () {
            $httpBackend
                .expectPOST(SERVER_URL+"api/facilities/keph/")
                .respond(201);

            createController("mfl.setup.controller.keph.create");

            $scope.save();
            $httpBackend.flush();
        });

        it("should catch errors on create a new KEPH level", function () {
            $httpBackend
                .expectPOST(SERVER_URL+"api/facilities/keph/")
                .respond(500);

            createController("mfl.setup.controller.keph.create");

            $scope.save();
            $httpBackend.flush();
        });

        it("should delete a KEPH level", function () {
            $httpBackend
                .expectGET(SERVER_URL+"api/facilities/keph/4/")
                .respond(200, {"name": ""});
            $httpBackend
                .expectDELETE(SERVER_URL+"api/facilities/keph/4/")
                .respond(200, {"name": ""});
            createController("mfl.setup.controller.keph.edit", {"$stateParams": {"keph_id": 4}});
            $scope.remove();
            $httpBackend.flush();
            $httpBackend.verifyNoOutstandingExpectation();
            $httpBackend.verifyNoOutstandingRequest();

            expect($scope.keph).toEqual({"name": ""});

            $httpBackend
                .expectPATCH(SERVER_URL+"api/facilities/keph/4/")
                .respond(200);

            $scope.save();
            $httpBackend.flush();
        });

        it("should handle errors on delete a KEPH level", function () {
            $httpBackend
                .expectGET(SERVER_URL+"api/facilities/keph/4/")
                .respond(500, {"name": ""});
            $httpBackend
                .expectDELETE(SERVER_URL+"api/facilities/keph/4/")
                .respond(500, {"name": ""});
            spyOn($state, "go");
            createController("mfl.setup.controller.keph.edit", {"$stateParams": {"keph_id": 4}});
            $scope.remove();
            $scope.cancel();
            $httpBackend.flush();
            $httpBackend.verifyNoOutstandingExpectation();
            $httpBackend.verifyNoOutstandingRequest();
            $scope.keph = {"name": ""};
            $httpBackend
                .expectPATCH(SERVER_URL+"api/facilities/keph/4/")
                .respond(500);
            expect($state.go).toHaveBeenCalledWith("login", { next : "dashboard" });
            expect($state.go).toHaveBeenCalledWith("setup.facility_kephs", { },
                                                   { reload : true });
            $scope.save();
            $httpBackend.flush();
        });

    });
})(window._);
<commit_msg>Fix tests for keph levels editing<commit_after>(function(_){
    "use strict";
    describe("keph controllers test suite", function(){
        var createController, $scope, $stateParams, $httpBackend, $state, adminApi;
        var formService, SERVER_URL;

        beforeEach(function(){
            module("mflAdminApp");
            inject(["$rootScope", "$controller", "$stateParams", "$httpBackend",
                   "$state", "adminApi","mfl.common.forms.changes","SERVER_URL",
                   function($rootScope, $controller,_$stateParams,
                    _$httpBackend, _$state, _adminApi, frm, _SERVER_URL){
                $scope = $rootScope.$new();
                SERVER_URL = _SERVER_URL;
                $httpBackend = _$httpBackend;
                $stateParams = _$stateParams;
                $state = _$state;
                adminApi = _adminApi;
                formService = frm;
                var data = {
                    $scope: $scope
                };
                createController = function(ctrl, params){
                    return $controller(ctrl, _.extend(data, params));

                };
            }]);
        });

        afterEach(function(){
            $httpBackend.verifyNoOutstandingRequest();
            $httpBackend.verifyNoOutstandingExpectation();
        });

        it("should have `mfl.setup.controller.keph.list` defined", function() {
            var ctrl = createController("mfl.setup.controller.keph.list", {});
            expect(ctrl).toBeDefined();
        });

        it("should create a new KEPH level", function () {
            $httpBackend
                .expectPOST(SERVER_URL+"api/facilities/keph/")
                .respond(201);

            createController("mfl.setup.controller.keph.create");

            $scope.save();
            $httpBackend.flush();
        });

        it("should catch errors on create a new KEPH level", function () {
            $httpBackend
                .expectPOST(SERVER_URL+"api/facilities/keph/")
                .respond(500);

            createController("mfl.setup.controller.keph.create");

            $scope.save();
            $httpBackend.flush();
        });

        it("should delete a KEPH level", function () {
            $httpBackend
                .expectGET(SERVER_URL+"api/facilities/keph/4/")
                .respond(200, {"name": "","description":""});
            $httpBackend
                .expectDELETE(SERVER_URL+"api/facilities/keph/4/")
                .respond(200, {"name": "","description":""});
            createController("mfl.setup.controller.keph.edit", {"$stateParams": {"keph_id": 4}});
            $scope.remove();
            $httpBackend.flush();
            $httpBackend.verifyNoOutstandingExpectation();
            $httpBackend.verifyNoOutstandingRequest();
        });

        it("should handle errors on delete a KEPH level", function () {
            $httpBackend
                .expectGET(SERVER_URL+"api/facilities/keph/4/")
                .respond(500, {"name": "","description":""});
            $httpBackend
                .expectDELETE(SERVER_URL+"api/facilities/keph/4/")
                .respond(500, {"name": "","description":""});
            spyOn($state, "go");
            createController("mfl.setup.controller.keph.edit", {"$stateParams": {"keph_id": 4}});
            $scope.remove();
            $scope.cancel();
            $httpBackend.flush();
            $httpBackend.verifyNoOutstandingExpectation();
            $httpBackend.verifyNoOutstandingRequest();
        });

        it("should update keph level: no changes",function(){
                var form = {};
                spyOn($state, "go");
                spyOn(formService, "whatChanged").andReturn(form);
                $httpBackend.expectGET(SERVER_URL+"api/facilities/keph/1/").respond(
                200,{"name": "","description":""});
                createController("mfl.setup.controller.keph.edit",{"$stateParams": {"keph_id": 1}});
                $scope.save(1, form);
                $httpBackend.flush();
                expect($state.go).not.toHaveBeenCalledWith("setup.facility_kephs");
            });
        it("should update keph level: with changes",function(){
                var form = {name:"level 2",description:"level 2 description"};
                var res = {msg: "Ok"};
                spyOn($state, "go");
                spyOn(formService, "whatChanged").andReturn(form);
                $httpBackend.expectGET(SERVER_URL+"api/facilities/keph/1/").respond(
                200,res);
                $httpBackend.expectPATCH(SERVER_URL+"api/facilities/keph/1/").respond(
                200, res);
                createController("mfl.setup.controller.keph.edit",{$stateParams: {keph_id: 1}});
                $scope.save(1, form);
                $httpBackend.flush();
                expect($state.go).toHaveBeenCalledWith("login", { next : "dashboard" });
                expect($state.go).toHaveBeenCalledWith("setup.facility_kephs",{},{reload:true});
            });
        it("should fail to update keph level: with changes",function(){
                var form = {name:"level 2"};
                spyOn($state, "go");
                spyOn(formService, "whatChanged").andReturn(form);
                $httpBackend.expectGET(SERVER_URL+"api/facilities/keph/1/").respond(
                500);
                createController("mfl.setup.controller.keph.edit",{"$stateParams": {"keph_id": 1}});
                $scope.save(1, form);
                $httpBackend.flush();
                expect($state.go).not.toHaveBeenCalledWith("setup.facility_kephs");
            });
    });
})(window._);
<|endoftext|>


<commit_before>/* jshint node: true */
'use strict';

var quotes = [
  {
    text: 'As a tech community, we must treat documentation, marketing, logistics, infrastructure, art, etc. work with as much respect as engineering',
    author: 'Yehuda Katz'
  }, {
    text: 'To maximize your impact in software, empower other developers.',
    author: 'Yehuda Katz'
  }
];

module.exports = {
  name: 'ember-empathy',
  preBuild: function() {
    var quote = quotes[Math.floor(Math.random() * quotes.length)];
    console.log('');
    console.log('"' + quote.text + '"');
    console.log('  — ' + quote.author);
    console.log('');
  }
};
<commit_msg>Use the unified console.<commit_after>/* jshint node: true */
'use strict';

var quotes = [
  {
    text: 'As a tech community, we must treat documentation, marketing, logistics, infrastructure, art, etc. work with as much respect as engineering',
    author: 'Yehuda Katz'
  }, {
    text: 'To maximize your impact in software, empower other developers.',
    author: 'Yehuda Katz'
  }
];

module.exports = {
  name: 'ember-empathy',
  preBuild: function() {
    var quote = quotes[Math.floor(Math.random() * quotes.length)];
    this.project.ui.writeLine('"' + quote.text + '"');
    this.project.ui.writeLine('  — ' + quote.author);
    this.project.ui.spinner.start();
  }
};
<|endoftext|>


<commit_before>function init_SFW_DOM()
{
   set_missing_doc_props();

   // SFW.get_page_xoffset() AND
   // SFW.get_page_yoffset()
   prepare_page_offset_funcs();
   SFW.get_doc_offset       = _get_doc_offset;
   SFW.get_relative_offset  = _get_relative_offset;

   SFW.el_name              = _el_name;
   SFW.find_tagged_children = _find_tagged_children;
   SFW.first_child_element  = _first_child_element;
   SFW.get_page_anchor      = _get_page_anchor;
   SFW.get_ancestor_anchor  = _get_ancestor_anchor;
   SFW.next_sibling_element = _next_sibling_element;

   // Sets SFW.get_page_xoffset and SFW.get_page_yoffset
   function prepare_page_offset_funcs()
   {
      if ('pageXOffset' in window)
      {
         SFW.get_page_xoffset = function() { return window.pageXOffset; };
         SFW.get_page_yoffset = function() { return window.pageYOffset; };
      }
      else if ('body' in document && 'scrollLeft' in document.body)
      {
         SFW.get_page_xoffset = function() { return document.body.scrollLeft; };
         SFW.get_page_yoffset = function() { return document.body.scrollTop;  };
      }
      else
      {
         SFW.get_page_xoffset = void(0);
         SFW.get_page_yoffset = void(0);
      }
   };

   function _get_doc_offset(el)
   {
      if (el===null)
         return {left:0, top:0};

      var os = el.offsetParent ? _get_doc_offset(el.offsetParent) : {left:0,top:0};
      return {left:os.left+el.offsetLeft, top:os.top+el.offsetTop };
   }

   function _get_relative_offset(target, ref)
   {
      var ost = _get_doc_offset(target);
      var osr = _get_doc_offset(ref);
      ost.left -= osr.left;
      ost.top -= ost.top;
      return ost;
   }

   function _el_name(el)
   {
      if ("localName" in el)
         _el_name = function(e) { return e.localName; };
      else if ("baseName" in el)
         _el_name = function(e) { return e.baseName; };
      else
         _el_name = void(0);

      SFW.el_name = _el_name;
      return _el_name(el);
   }

   function _find_tagged_children(parent, tag, first_only)
   {
      var rval = [];
      var node = parent.firstChild;
      while (node)
      {
         if (node.nodeType==1 && node.tagName.toLowerCase()==tag)
         {
            if (first_only)
               return node;
            else
               rval.push(node);
         }
         node = node.nextSibling;
      }
      return rval.length ? rval : null;
   }

   function _first_child_element(el)
   {
      var n = el.firstChild;
      if (n.nodeType==1)
         return n;
      else
         return _next_sibling_element(n);
   }

   function _next_sibling_element(el)
   {
      if ("nextElementSibling" in el)
         _next_sibling_element = function(e) { return e.nextElementSibling; };
      else
      {
         _next_sibling_element = function(e)
         {
            var n = e.nextSibling;
            while (n)
            {
               if (n.nodeType==1)
                  return n;
               else
                  n = n.nextSibling;
            }
            return null;
         };
      }

      // Also reset the member function, now that the function has been reset:
      SFW.next_sibling_element = _next_sibling_element;
      return _next_sibling_element(el);
   }

   function _get_page_anchor(levels, parent)
   {
      if (arguments.length==0)
         levels = 2;

      if (levels==0)
         return null;

      if (arguments.length<2)
         parent = document.getElementById("SFW_Content");

      var subel, el = _first_child_element(parent);
      while (el)
      {
         if (el.getAttribute("data-sfw-class"))
            return el;
         else if ((subel = _get_page_anchor(levels-1, el)))
            return subel;
         else
            el = _next_sibling_element(el);
      }

      return null;
   }

   function _get_ancestor_anchor(el)
   {
      while (el)
      {
         if (el.nodeType==1 && el.getAttribute("data-sfw-class"))
            return el;
         else if (el.nodeType==9)
            break;

         el = el.parentNode;
      }
      return null;
   }

   function set_missing_doc_props()
   {
      var html = document.documentElement;
      if (!("head" in document))
         document.head = _find_tagged_children(html, "head", true);
      if (!("body" in document))
         document.body = _find_tagged_children(html, "body", true);
      if (!("sfwanchor" in document))
      {
         var a = _get_page_anchor();
         if (a)
            document.sfwanchor = a;
      }
   }
}
<commit_msg>Changed find_child_matches to allow recursive searches.<commit_after>function init_SFW_DOM()
{
   set_missing_doc_props();

   // SFW.get_page_xoffset() AND
   // SFW.get_page_yoffset()
   prepare_page_offset_funcs();
   SFW.get_doc_offset       = _get_doc_offset;
   SFW.get_relative_offset  = _get_relative_offset;

   SFW.el_name              = _el_name;
   SFW.find_child_matches   = _find_child_matches;
   SFW.first_child_element  = _first_child_element;
   SFW.get_page_anchor      = _get_page_anchor;
   SFW.get_ancestor_anchor  = _get_ancestor_anchor;
   SFW.next_sibling_element = _next_sibling_element;

   // Sets SFW.get_page_xoffset and SFW.get_page_yoffset
   function prepare_page_offset_funcs()
   {
      if ('pageXOffset' in window)
      {
         SFW.get_page_xoffset = function() { return window.pageXOffset; };
         SFW.get_page_yoffset = function() { return window.pageYOffset; };
      }
      else if ('body' in document && 'scrollLeft' in document.body)
      {
         SFW.get_page_xoffset = function() { return document.body.scrollLeft; };
         SFW.get_page_yoffset = function() { return document.body.scrollTop;  };
      }
      else
      {
         SFW.get_page_xoffset = void(0);
         SFW.get_page_yoffset = void(0);
      }
   };

   function _get_doc_offset(el)
   {
      if (el===null)
         return {left:0, top:0};

      var os = el.offsetParent ? _get_doc_offset(el.offsetParent) : {left:0,top:0};
      return {left:os.left+el.offsetLeft, top:os.top+el.offsetTop };
   }

   function _get_relative_offset(target, ref)
   {
      var ost = _get_doc_offset(target);
      var osr = _get_doc_offset(ref);
      ost.left -= osr.left;
      ost.top -= ost.top;
      return ost;
   }

   function _el_name(el)
   {
      if ("localName" in el)
         _el_name = function(e) { return e.localName; };
      else if ("baseName" in el)
         _el_name = function(e) { return e.baseName; };
      else
         _el_name = void(0);

      SFW.el_name = _el_name;
      return _el_name(el);
   }

   function _find_child_matches(parent, tag_or_func, first_only, recursive)
   {
      var compfunc;
      if (typeof(tag_or_func)=="function")
         compfunc = tag_or_func;
      else
         compfunc = function(el) {
            return el.nodeType==1 && el.tagName.toLowerCase()==tag_or_func;
         };

      var rval = [];
      var node = parent.firstChild;
      while (node)
      {
         if (compfunc(node))
         {
            if (first_only)
               return node;
            else
               rval.push(node);
         }
         else if (recursive)
         {
            var recur =_find_child_matches(node, compfunc, first_only, true);
            if (recur)
            {
               if (first_only)
                  return recur;
               else
                  rval.concat(recur);
            }
         }
         node = node.nextSibling;
      }
      return rval.length ? rval : null;
   }

   function _first_child_element(el)
   {
      var n = el.firstChild;
      if (n)
      {
         if (n.nodeType==1)
            return n;
         else
            return _next_sibling_element(n);
      }
      else
         return null;
   }

   function _next_sibling_element(el)
   {
      if ("nextElementSibling" in el)
         _next_sibling_element = function(e) { return e.nextElementSibling; };
      else
      {
         _next_sibling_element = function(e)
         {
            var n = e.nextSibling;
            while (n)
            {
               if (n.nodeType==1)
                  return n;
               else
                  n = n.nextSibling;
            }
            return null;
         };
      }

      // Also reset the member function, now that the function has been reset:
      SFW.next_sibling_element = _next_sibling_element;
      return _next_sibling_element(el);
   }

   function _get_page_anchor(levels, parent)
   {
      if (arguments.length==0)
         levels = 2;

      if (levels==0)
         return null;

      if (arguments.length<2)
         parent = document.getElementById("SFW_Content");

      var subel, el = _first_child_element(parent);
      while (el)
      {
         if (el.getAttribute("data-sfw-class"))
            return el;
         else if ((subel = _get_page_anchor(levels-1, el)))
            return subel;
         else
            el = _next_sibling_element(el);
      }

      return null;
   }

   function _get_ancestor_anchor(el)
   {
      while (el)
      {
         if (el.nodeType==1 && el.getAttribute("data-sfw-class"))
            return el;
         else if (el.nodeType==9)
            break;

         el = el.parentNode;
      }
      return null;
   }

   function set_missing_doc_props()
   {
      var html = document.documentElement;
      if (!("head" in document))
         document.head = _find_child_matches(html, "head", true);
      if (!("body" in document))
         document.body = _find_child_matches(html, "body", true);
      if (!("sfwanchor" in document))
      {
         var a = _get_page_anchor();
         if (a)
            document.sfwanchor = a;
      }
   }
}
<|endoftext|>