<commit_before>var Promise = require('promise');
var shexjs = require("shex");
var n3 = require("n3");

var DefaultBase = "";

function Validator(schemaText, dataText, callbacks, options) {
    this.callbacks = callbacks;
    this.options = options;

    this.updateSchema(location.origin + '/schema.shex', schemaText);
    this.updateData(dataText);
}

Validator.prototype = {
    updateSchema: function (base, schemaText) {
        this.schema = parseSchema(base ,schemaText);
        this.schema.done(this.callbacks.schemaParsed, this.callbacks.schemaParseError);
    },
    updateData: function (dataText) {
        this.data = parseData(dataText);
        this.data.done(this.callbacks.dataParsed, this.callbacks.dataParseError);
    },
    findShapes: function () {
        var _this = this;
        return Promise.all([this.schema, this.data]).then(function (a) {
            console.log('showing shapes');
            console.log(this.schema);
            console.log(this.data);
        });
    },
    validate: function(startingNodes) {
        var _this = this;
        console.log('validate function',_this);
        return Promise.all([this.schema, this.data, this.options]).then(function (a) {
            console.log(a);
            var node = Object.keys(a[2].resourceShapeMap)[0];
            var result = shexjs.Validator.construct(a[0].schema).validate(a[1].db, node, a[2].resourceShapeMap[node]);
            console.log('callbacks in validator',_this.callbacks);
            console.log('db to validate',a[1].db)
            // console.log('validation results:',result);
            // return validator.validate(
            //     a[0].schema,                       // Schema
            //     a[0].resolver,
            //     startingNodes,      // Starting Node
            //     a[1].db,                       // db
            //     a[1].resolver,
            //     _this.options.closedShapes,
            //     _this.callbacks.validationResult);
            return cleanResult(result, a[1].triples, _this.callbacks.validationResult)
        });
    }
};

module.exports.Validator = Validator;

function parseData(dataText){
    console.log('split data');
    console.log(dataText.split("\n"));
    console.log('this',this);
    return new Promise(function (resolve, reject) {
        var lineIndex = new Object();
        var db = n3.Store();
        n3.Parser({documentIRI: DefaultBase}).parse(dataText, function (error, triple, prefixes) {
            // console.log('db', db);
            // console.log('DB');
            console.log('triple callback')
            if (error) {
                // throw Error("error parsing " + data + ": " + error);
                reject(parseN3Error(error));
            } else if (triple) {
                console.log("N3triple",triple);
                lineIndex[JSON.stringify({'subject':triple.subject,'predicate':triple.predicate,'object':triple.object,'graph':triple.graph})] = triple.line;
                // lineIndex[triple.line] = {'object':triple.object,'subject':triple.subject,'predicate':triple.predicate,'graph':triple.graph};
                db.addTriple(triple);

            } else {
                var triples = db.getTriples();
                for (var i = triples.length - 1; i >= 0; i--) {
                    var triple_key = JSON.stringify({'subject':triples[i].subject,'predicate':triples[i].predicate,'object':triples[i].object,'graph':""});
                    triples[i].line = lineIndex[triple_key];
                }
                resolve({db: db, triples:triples});
            }
        });

    });
}

function parseSchema(base, schemaText) {
    return new Promise(function (resolve, reject) {
        var schema;
        try {
            schema = shexjs.Parser.construct(base).parse(schemaText);
        }
        catch (e) {
            reject(e);
        }
        resolve({schema: schema, shapes: schema.shapes});

    });
};

function cleanResult(result, parsedTriples, callback){
    console.log('validation result', result);
    var errors = [];
    var solutions = [];
    if (result.type == 'Failure'){
        errors = cleanErrors(parsedTriples, result);
    } else {
        solutions = result.solution;
    }
    var clean_result = {
            errors: errors,
            matches: solutions,
            startingResource: result.node,
            passed: errors.length === 0,
            full_result:result
        };
    return callback(clean_result);
}

function parseN3Error(error) {
    var line = error.message.match(/line [0-9]*/g);

    line = (line && line.length > 0 && line[0].length > 5)?Number(line[0].substr(5)):null;

    return {
        message: error.message,
        line: line,
        column: 0
    }
}
// returns the matched triples and the corresponding lines
function cleanMatches(validationResult){
    var results = []
    if (validationResult.type == 'ShapeTest') {
        cleanMatches(validationResult.solution);
    }
    else if (validationResult.type == 'EachOfSolutions') {

    }
    else if (validationResult.type == 'OneOfSolutions') {

    }
    else if (validationResult.type == 'TripleConstraintSolutions') {

    }
    else if (validationResult.type == 'TestedTriple') {

    }
    else if (validationResult instanceof Array){
        for (var i = validationResult.length - 1; i >= 0; i--) {
            cleanMatches(validationResult[i]);
        }
    }
    return results
}

function cleanErrors(parsedTriples, validationResult){
    var results = []
    var errors = validationResult.errors;

    for (var i = errors.length - 1; i >= 0; i--) {
        if (errors[i].triple) {
                // if (errors[i].triple.object.type) {
                //     errors[i].triple.object = errors[i].triple.object.value;
                // }
                console.log(errors[i].triple.subject,parsedTriples[2].subject,errors[i].triple.subject == parsedTriples[2].subject);
                console.log(errors[i].triple.predicate,parsedTriples[2].predicate,errors[i].triple.predicate == parsedTriples[2].predicate);
                console.log(errors[i].triple.object,parsedTriples[2].object,errors[i].triple.object == parsedTriples[2].object);
            try {
                //shex validator gives object sometimes

                errors[i].line = parsedTriples.find(function (triple) { return triple.subject === errors[i].triple.subject &&
                                                                            triple.predicate === errors[i].triple.predicate &&
                                                                            triple.object === errors[i].triple.object; }).line;
                errors[i].message = String(errors[i].type) + ' on line ' + String(errors[i].line);
            }
            catch(error){
                console.error(error);
            }

        }
        else if (validationResult.type == 'MissingProperty') {
            console.log('missing property error');

        }
        else {
            console.log('VALIDATION ERROR:',errors.type);
        }
        results.push(errors[i]);
    }

    return results
}<commit_msg>added support for matches<commit_after>var Promise = require('promise');
var shexjs = require("shex");
var n3 = require("n3");

var DefaultBase = "";

function Validator(schemaText, dataText, callbacks, options) {
    this.callbacks = callbacks;
    this.options = options;

    this.updateSchema(location.origin + '/schema.shex', schemaText);
    this.updateData(dataText);
}

Validator.prototype = {
    updateSchema: function (base, schemaText) {
        this.schema = parseSchema(base ,schemaText);
        this.schema.done(this.callbacks.schemaParsed, this.callbacks.schemaParseError);
    },
    updateData: function (dataText) {
        this.data = parseData(dataText);
        this.data.done(this.callbacks.dataParsed, this.callbacks.dataParseError);
    },
    findShapes: function () {
        var _this = this;
        return Promise.all([this.schema, this.data]).then(function (a) {
            console.log('showing shapes');
            console.log(this.schema);
            console.log(this.data);
        });
    },
    validate: function(startingNodes) {
        var _this = this;
        console.log('validate function',_this);
        return Promise.all([this.schema, this.data, this.options]).then(function (a) {
            console.log(a);
            var node = Object.keys(a[2].resourceShapeMap)[0];
            var result = shexjs.Validator.construct(a[0].schema).validate(a[1].db, node, a[2].resourceShapeMap[node]);
            console.log('callbacks in validator',_this.callbacks);
            console.log('db to validate',a[1].db)
            // console.log('validation results:',result);
            // return validator.validate(
            //     a[0].schema,                       // Schema
            //     a[0].resolver,
            //     startingNodes,      // Starting Node
            //     a[1].db,                       // db
            //     a[1].resolver,
            //     _this.options.closedShapes,
            //     _this.callbacks.validationResult);
            return cleanResult(result, a[1].triples, _this.callbacks.validationResult)
        });
    }
};

module.exports.Validator = Validator;

function parseData(dataText){
    console.log('split data');
    console.log(dataText.split("\n"));
    console.log('this',this);
    return new Promise(function (resolve, reject) {
        var lineIndex = new Object();
        var db = n3.Store();
        n3.Parser({documentIRI: DefaultBase}).parse(dataText, function (error, triple, prefixes) {
            // console.log('db', db);
            // console.log('DB');
            console.log('triple callback')
            if (error) {
                // throw Error("error parsing " + data + ": " + error);
                reject(parseN3Error(error));
            } else if (triple) {
                console.log("N3triple",triple);
                lineIndex[JSON.stringify({'subject':triple.subject,'predicate':triple.predicate,'object':triple.object,'graph':triple.graph})] = triple.line;
                // lineIndex[triple.line] = {'object':triple.object,'subject':triple.subject,'predicate':triple.predicate,'graph':triple.graph};
                db.addTriple(triple);

            } else {
                var triples = db.getTriples();
                for (var i = triples.length - 1; i >= 0; i--) {
                    var triple_key = JSON.stringify({'subject':triples[i].subject,'predicate':triples[i].predicate,'object':triples[i].object,'graph':""});
                    triples[i].line = lineIndex[triple_key];
                }
                resolve({db: db, triples:triples});
            }
        });

    });
}

function parseSchema(base, schemaText) {
    return new Promise(function (resolve, reject) {
        var schema;
        try {
            schema = shexjs.Parser.construct(base).parse(schemaText);
        }
        catch (e) {
            reject(e);
        }
        resolve({schema: schema, shapes: schema.shapes});

    });
};

function cleanResult(result, parsedTriples, callback){
    console.log('validation result', result);
    var errors = [];
    var matches = [];
    if (result.type == 'Failure'){
        errors = cleanErrors(parsedTriples, result);
    } else {
        matches = cleanMatches(parsedTriples, result);
        // console.log('result',result);
        // console.log('matches',matches);
    }
    var clean_result = {
            errors: errors,
            matches: matches,
            startingResource: result.node,
            passed: errors.length === 0,
            full_result:result
        };
    return callback(clean_result);
}

function parseN3Error(error) {
    var line = error.message.match(/line [0-9]*/g);

    line = (line && line.length > 0 && line[0].length > 5)?Number(line[0].substr(5)):null;

    return {
        message: error.message,
        line: line,
        column: 0
    }
}
// returns the matched triples and the corresponding lines

function cleanMatches(parsedTriples, validationResult){
    var results = [];
    var messages = [];
    var matches = parseMatches(validationResult.solution);
    for (var i = matches.length - 1; i >= 0; i--) {
        var currentMatch = {};
        currentMatch.line = matchTriple(parsedTriples, matches[i]).line;
        currentMatch.subject = matches[i].subject;
        currentMatch.predicate = matches[i].predicate;

        if (matches[i].object.value && matches[i].object.type) {
                currentMatch.object = '<type>:' +String(matches[i].object.type) +' <value>:'+ String(matches[i].object.value);

        } else {
            currentMatch.object = matches[i].object;
        }
            currentMatch.message = 'Matched '+ String(currentMatch.predicate)+' '+ String(currentMatch.object) + ' on line ' + String(currentMatch.line);

        // console.log('cleanMatches',matches[i]);

        if (!messages.includes(currentMatch.message)){
            results.push(currentMatch);
            messages.push(currentMatch.message);
        }

    }
    // console.log('results returned',results);
    return results
}

function parseMatches(solution){
    var results = [];
    var values = Object.values(solution)
    // console.log('object values',values);
    for (var i = values.length - 1; i >= 0; i--) {
        if (values[i].subject && values[i].predicate && values[i].object){
            // console.log('istriple',values[i]);
            results.push(values[i]);
        }
        else if (typeof(values[i]) == 'string'){
            // console.log('string found',values[i])
        } else {
            Array.prototype.push.apply(results,parseMatches(values[i]));
        }
    }

    return results
}

function parseErrors(errors){
    var results = [];
    for (var i = errors.length - 1; i >= 0; i--) {
        if (Array.isArray(errors[i])){
            console.log('rec call',errors[i]);
            Array.prototype.push.apply(results,parseErrors(errors[i]));

        } else {
            console.log('non rec call',errors[i]);
            results.push(errors[i])
        }
    }
    console.log('results',results);
    return results
}

function matchTriple(parsedTriples, keyTriple){
    var match;

    try {
        match = parsedTriples.find(function (triple) {
            var lookup = []
            if (typeof(keyTriple.subject) == 'string' ){
                if (triple.subject === keyTriple.subject){
                    lookup.push(true)
                } else{
                    return false
                }
            } else {
                lookup.push(true);
            }
            // console.log('subject',keyTriple.subject);

            if (typeof(keyTriple.predicate) == 'string'){
                if (triple.predicate === keyTriple.predicate){
                    lookup.push(true);
                } else {
                    return false
                }
            }else {
                lookup.push(true);
            }

            // console.log('predicate',keyTriple.predicate);

            if (typeof(keyTriple.object) == 'string'){
                if (triple.object === keyTriple.object){
                    lookup.push(true);
                } else {
                    return false
                }
            }else {
                lookup.push(true);
            }
            // console.log('object',keyTriple.object);

            return lookup[0] == lookup[1] == lookup[2]
        });
    } catch (error) {
        console.error(error);
    }
    console.log('keyTriple',keyTriple,'matchedTriple',match);

    return match
}

function cleanErrors(parsedTriples, validationResult){
    var results = [];
    var messages = [];
    var errors = parseErrors(validationResult.errors);
    console.log('errors',validationResult.errors);
    //sometimes errors are in arrays of length one for some reason :/

    console.log('errors',errors);
    console.log('validationResult',validationResult);
    for (var i = errors.length - 1; i >= 0; i--) {
        if (errors[i].type == 'TypeMismatch'){
            if (errors[i].triple) {
                // if (errors[i].triple.object.type) {
                //     errors[i].triple.object = errors[i].triple.object.value;
                // }
                // console.log(errors[i].triple.subject,parsedTriples[2].subject,errors[i].triple.subject == parsedTriples[2].subject);
                // console.log(errors[i].triple.predicate,parsedTriples[2].predicate,errors[i].triple.predicate == parsedTriples[2].predicate);
                // console.log(errors[i].triple.object,parsedTriples[2].object,errors[i].triple.object == parsedTriples[2].object);

            try {
                //shex validator gives object sometimes
                var match = parsedTriples.find(function (triple) {
                    var lookup = []
                    if (typeof(errors[i].triple.subject) == 'string' ){
                        if (triple.subject === errors[i].triple.subject){
                            lookup.push(true)
                        } else{
                            return false
                        }
                    } else {
                        lookup.push(true);
                    }
                    console.log('subject',errors[i].triple.subject);

                    if (typeof(errors[i].triple.predicate) == 'string'){
                        if (triple.predicate === errors[i].triple.predicate){
                            lookup.push(true);
                        } else {
                            return false
                        }
                    }else {
                        lookup.push(true);
                    }

                    console.log('predicate',errors[i].triple.predicate);

                    if (typeof(errors[i].triple.object) == 'string'){
                        if (triple.object === errors[i].triple.object){
                            lookup.push(true);
                        } else {
                            return false
                        }
                    }else {
                        lookup.push(true);
                    }
                    console.log('object',errors[i].triple.object);

                    return lookup[0] == lookup[1] == lookup[2]
                });
                console.log('match',match);
                errors[i].line = match.line;

                errors[i].message = 'Type mismatch on line ' + String(errors[i].line) + ' in ' + String(validationResult.node);
            }
            catch(error){
                console.error(error);
                // errors[i].message = ' Missing property ' + String(errors[i].property) + ' in ' + String(validationResult.node);
            }

            }
        }

        else if (errors[i].type == 'MissingProperty') {
            try {
                errors[i].message = ' Missing property ' + String(errors[i].property) ;

            }catch (error){
                console.error(error);
            }
            console.log('missing property error',errors[i]);

        }
        else {
            console.log('VALIDATION ERROR:',errors[i].type);
        }
        //check if the same error has been already parsed, as the validation library does produce duplicates
        if (!messages.includes(errors[i].message)){
            results.push(errors[i]);
            messages.push(errors[i].message);
        }
    }

    return results
}<|endoftext|>


<commit_before>'use strict';

(function (angular, buildfire) {
  angular
    .module('loyaltyPluginDesign')
    .controller('DesignHomeCtrl', ['$scope', 'LAYOUTS', 'DataStore','TAG_NAMES','Buildfire',
      function ($scope, LAYOUTS, DataStore,TAG_NAMES,Buildfire) {
        var DesignHome = this;
        var _data = {
          "design": {
            "listLayout": LAYOUTS.listLayout[0].name,
            "listBgImage": "",
            "itemDetailsBgImage": ""
          }
        };
        DesignHome.masterData = null;
        DesignHome.layouts = LAYOUTS;
        DesignHome.data = angular.copy(_data);

        /*On item list layout click event*/
        DesignHome.changeListLayout = function (layoutName) {
          DesignHome.data.design.listLayout = layoutName;
          if (tmrDelay)clearTimeout(tmrDelay);
        };

        function updateMasterItem(data) {
          DesignHome.masterData = angular.copy(data);
        }

        function isUnchanged(data) {
          return angular.equals(data, DesignHome.masterData);
        }

        /* item List background image add <start>*/
        DesignHome.itemListBackground = new Buildfire.components.images.thumbnail("#itemListBackground", {title: "Item List Background Image"});
        DesignHome.itemListBackground.onChange = function (url) {
          DesignHome.data.design.itemListbackgroundImage = url;
          if (!$scope.$$phase && !$scope.$root.$$phase) {
            $scope.$apply();
          }
        };

        DesignHome.itemListBackground.onDelete = function (url) {
          DesignHome.data.design.itemListbackgroundImage = "";
          if (!$scope.$$phase && !$scope.$root.$$phase) {
            $scope.$apply();
          }
        };
        /* item List background image add <end>*/

        /* item Details background image add <start>*/
        DesignHome.itemDetailsBackground = new Buildfire.components.images.thumbnail("#itemDetailsBackground", {title: "Item Details Background Image"});
        DesignHome.itemDetailsBackground.onChange = function (url) {
          DesignHome.data.design.itemDetailsBackgroundImage = url;
          if (!$scope.$$phase && !$scope.$root.$$phase) {
            $scope.$apply();
          }
        };

        DesignHome.itemDetailsBackground.onDelete = function (url) {
          DesignHome.data.design.itemDetailsBackgroundImage = "";
          if (!$scope.$$phase && !$scope.$root.$$phase) {
            $scope.$apply();
          }
        };

        /* item Details background image add <end>*/
        var init = function () {
          var success = function (result) {
              console.log("---------------------------", result);
              DesignHome.data = result.data;
              if (DesignHome.data && !DesignHome.data.design) {
                DesignHome.data.design = {};
              }
              if (!DesignHome.data.design.listLayout) {
                DesignHome.data.design.listLayout = DesignHome.layouts.listLayout[0].name;
              }
              updateMasterItem(DesignHome.data);
                if (DesignHome.data.design.itemListbackgroundImage) {
                  DesignHome.itemListBackground.loadbackground(DesignHome.data.design.itemListbackgroundImage);
                }
                if (DesignHome.data.design.itemListbackgroundImage) {
                  DesignHome.itemDetailsBackground.loadbackground(DesignHome.data.design.itemDetailsBackgroundImage);
                }
              if (tmrDelay)clearTimeout(tmrDelay);
            }
            , error = function (err) {
              console.error('Error while getting data', err);
              if (tmrDelay)clearTimeout(tmrDelay);
            };
          DataStore.get(TAG_NAMES.LOYALTY_INFO).then(success, error);
        };

        /*
         * Call the datastore to save the data object
         */
        var saveData = function (newObj, tag) {
          if (typeof newObj === 'undefined') {
            return;
          }
          var success = function (result) {
              console.info('Saved data result: ', result);
              updateMasterItem(newObj);
            }
            , error = function (err) {
              console.error('Error while saving data : ', err);
            };
          DataStore.save(newObj, tag).then(success, error);
        };

        /*
         * create an artificial delay so api isnt called on every character entered
         * */
        var tmrDelay = null;

        var saveDataWithDelay = function (newObj) {
          if (newObj) {
            if (isUnchanged(newObj)) {
              return;
            }
            if (tmrDelay) {
              clearTimeout(tmrDelay);
            }
            tmrDelay = setTimeout(function () {
              saveData(JSON.parse(angular.toJson(newObj)), TAG_NAMES.LOYALTY_INFO);
            }, 500);
          }
        };

        /*
         * watch for changes in data and trigger the saveDataWithDelay function on change
         * */
        $scope.$watch(function () {
          return DesignHome.data;
        }, saveDataWithDelay, true);

        updateMasterItem(_data);

        init();
      }]);
})(window.angular, window.buildfire);

<commit_msg>Fixed the itemDetail background image issue in design section.<commit_after>'use strict';

(function (angular, buildfire) {
  angular
    .module('loyaltyPluginDesign')
    .controller('DesignHomeCtrl', ['$scope', 'LAYOUTS', 'DataStore','TAG_NAMES','Buildfire',
      function ($scope, LAYOUTS, DataStore,TAG_NAMES,Buildfire) {
        var DesignHome = this;
        var _data = {
          "design": {
            "listLayout": LAYOUTS.listLayout[0].name,
            "listBgImage": "",
            "itemDetailsBgImage": ""
          }
        };
        DesignHome.masterData = null;
        DesignHome.layouts = LAYOUTS;
        DesignHome.data = angular.copy(_data);

        /*On item list layout click event*/
        DesignHome.changeListLayout = function (layoutName) {
          DesignHome.data.design.listLayout = layoutName;
          if (tmrDelay)clearTimeout(tmrDelay);
        };

        function updateMasterItem(data) {
          DesignHome.masterData = angular.copy(data);
        }

        function isUnchanged(data) {
          return angular.equals(data, DesignHome.masterData);
        }

        /* item List background image add <start>*/
        DesignHome.itemListBackground = new Buildfire.components.images.thumbnail("#itemListBackground", {title: "Item List Background Image"});
        DesignHome.itemListBackground.onChange = function (url) {
          DesignHome.data.design.itemListbackgroundImage = url;
          if (!$scope.$$phase && !$scope.$root.$$phase) {
            $scope.$apply();
          }
        };

        DesignHome.itemListBackground.onDelete = function (url) {
          DesignHome.data.design.itemListbackgroundImage = "";
          if (!$scope.$$phase && !$scope.$root.$$phase) {
            $scope.$apply();
          }
        };
        /* item List background image add <end>*/

        /* item Details background image add <start>*/
        DesignHome.itemDetailsBackground = new Buildfire.components.images.thumbnail("#itemDetailsBackground", {title: "Item Details Background Image"});
        DesignHome.itemDetailsBackground.onChange = function (url) {
          DesignHome.data.design.itemDetailsBackgroundImage = url;
          if (!$scope.$$phase && !$scope.$root.$$phase) {
            $scope.$apply();
          }
        };

        DesignHome.itemDetailsBackground.onDelete = function (url) {
          DesignHome.data.design.itemDetailsBackgroundImage = "";
          if (!$scope.$$phase && !$scope.$root.$$phase) {
            $scope.$apply();
          }
        };

        /* item Details background image add <end>*/
        var init = function () {
          var success = function (result) {
              console.log("---------------------------", result);
              DesignHome.data = result.data;
              if (DesignHome.data && !DesignHome.data.design) {
                DesignHome.data.design = {};
              }
              if (!DesignHome.data.design.listLayout) {
                DesignHome.data.design.listLayout = DesignHome.layouts.listLayout[0].name;
              }
              updateMasterItem(DesignHome.data);
                if (DesignHome.data.design.itemListbackgroundImage) {
                  DesignHome.itemListBackground.loadbackground(DesignHome.data.design.itemListbackgroundImage);
                }
                if (DesignHome.data.design.itemDetailsBackgroundImage) {
                  DesignHome.itemDetailsBackground.loadbackground(DesignHome.data.design.itemDetailsBackgroundImage);
                }
              if (tmrDelay)clearTimeout(tmrDelay);
            }
            , error = function (err) {
              console.error('Error while getting data', err);
              if (tmrDelay)clearTimeout(tmrDelay);
            };
          DataStore.get(TAG_NAMES.LOYALTY_INFO).then(success, error);
        };

        /*
         * Call the datastore to save the data object
         */
        var saveData = function (newObj, tag) {
          if (typeof newObj === 'undefined') {
            return;
          }
          var success = function (result) {
              console.info('Saved data result: ', result);
              updateMasterItem(newObj);
            }
            , error = function (err) {
              console.error('Error while saving data : ', err);
            };
          DataStore.save(newObj, tag).then(success, error);
        };

        /*
         * create an artificial delay so api isnt called on every character entered
         * */
        var tmrDelay = null;

        var saveDataWithDelay = function (newObj) {
          if (newObj) {
            if (isUnchanged(newObj)) {
              return;
            }
            if (tmrDelay) {
              clearTimeout(tmrDelay);
            }
            tmrDelay = setTimeout(function () {
              saveData(JSON.parse(angular.toJson(newObj)), TAG_NAMES.LOYALTY_INFO);
            }, 500);
          }
        };

        /*
         * watch for changes in data and trigger the saveDataWithDelay function on change
         * */
        $scope.$watch(function () {
          return DesignHome.data;
        }, saveDataWithDelay, true);

        updateMasterItem(_data);

        init();
      }]);
})(window.angular, window.buildfire);

<|endoftext|>


<commit_before>module.exports = function (config) {
    config.set({
        basePath: '../',
        files: [
            '/bower_components/jquery/jquery.js',
            '/bower_components/angular/angular.js',
            '/bower_components/angular-mocks/angular-mocks.js',
            'src/js/app.js',
            'src/js/controllers.js',
            'src/js/filters.js',
            'test/unit/**/*.js'
        ],
        autoWatch: true,
        frameworks: ['jasmine'],
        browsers: ['Firefox'],
        plugins: ['karma-firefox-launcher', 'karma-jasmine']
    })
};
<commit_msg>Accidently left dashes in the path, which breaks CI<commit_after>module.exports = function (config) {
    config.set({
        basePath: '../',
        files: [
            'bower_components/jquery/jquery.js',
            'bower_components/angular/angular.js',
            'bower_components/angular-mocks/angular-mocks.js',
            'src/js/app.js',
            'src/js/controllers.js',
            'src/js/filters.js',
            'test/unit/**/*.js'
        ],
        autoWatch: true,
        frameworks: ['jasmine'],
        browsers: ['Firefox'],
        plugins: ['karma-firefox-launcher', 'karma-jasmine']
    })
};
<|endoftext|>


<commit_before>import { select } from 'd3-selection';
import { controlBar } from '@scola/d3-generic';
import 'd3-selection-multi';

export default class Table {
  constructor() {
    this._columns = [];

    this._column = () => {};
    this._cell = (d) => d;

    this._enter = () => {};
    this._exit = () => {};

    this._root = select('body')
      .append('div')
      .remove()
      .classed('scola table', true)
      .styles({
        'padding-bottom': '3em'
      });

    this._table = this._root
      .append('table')
      .styles({
        'background': '#FFF',
        'border-bottom': '1px solid #CCC',
        'border-top': '1px solid #CCC',
        'border-collapse': 'collapse',
        'overflow': 'hidden',
        'width': '100%'
      });

    this._head = this._table
      .append('thead');

    this._headerRow = this._head
      .append('tr')
      .append('th')
      .style('padding', 0);

    this._columnRow = this._head
      .append('tr');

    this._foot = this._table
      .append('tfoot');

    this._footerRow = this._foot
      .append('tr')
      .append('td')
      .style('padding', 0);

    this._body = this._table
      .append('tbody');
  }

  destroy() {
    this._root.remove();
    this._root = null;
  }

  root() {
    return this._root;
  }

  body() {
    return this._body;
  }

  footer(action) {
    if (typeof action === 'undefined') {
      return this._footer;
    }

    if (action === false) {
      this._footer.destroy();
      this._footer = null;

      return this;
    }

    this._footer = controlBar();

    this._footer.root()
      .classed('scola footer', true)
      .styles({
        'border-top': '1px solid #CCC'
      });

    this._footerRow.node()
      .appendChild(this._footer.root().node());

    return this;
  }

  header(action) {
    if (typeof action === 'undefined') {
      return this._header;
    }

    if (action === false) {
      this._header.destroy();
      this._header = null;

      return this;
    }

    this._header = controlBar();

    this._header.root()
      .classed('scola header', true)
      .styles({
        'border-bottom': '1px solid #CCC'
      });

    this._headerRow.node()
      .appendChild(this._header.root().node());

    return this;
  }

  column(columns, modifier) {
    this._columns = columns;
    this._column = modifier;

    this._headerRow.attr('colspan', columns.length);
    this._footerRow.attr('colspan', columns.length);

    return this;
  }

  cell(value) {
    this._cell = value;
    return this;
  }

  enter(value) {
    this._enter = value;
    return this;
  }

  exit(value) {
    this._exit = value;
    return this;
  }

  inset() {
    this._root.styles({
      'padding-left': '1em',
      'padding-right': '1em'
    });

    this._table.styles({
      'border-style': 'none',
      'border-radius': '0.5em'
    });

    return this;
  }

  message(text, modifier = () => {}) {
    const message = this._body
      .append('tr')
      .classed('scola message', true)
      .append('td')
      .attr('colspan', this._columns.length)
      .styles({
        'cursor': 'default',
        'padding': '1em',
        'text-align': 'center'
      })
      .text(text);

    modifier(message);
    return this;
  }

  render(data, key) {
    this._body
      .select('.scola.message')
      .remove();

    const column = this._columnRow
      .selectAll('th')
      .data(this._columns)
      .enter()
      .append('th')
      .styles({
        'border-bottom': '1px solid #CCC',
        'color': '#AAA',
        'font-weight': 'normal',
        'font-size': '0.9em',
        'padding': '0.5em 0 0.5em 1em',
        'text-align': 'start',
        'text-transform': 'uppercase',
        'vertical-align': 'center'
      });

    const row = this._body
      .selectAll('tr')
      .data(data, key);

    const cell = row.selectAll('td')
      .data(this._cell);

    const exit = row.exit();

    const enter = row
      .enter()
      .append('tr')
      .merge(row)
      .style('border-top', (datum, index) => {
        return index > 0 ? '1px solid #CCC' : null;
      })
      .selectAll('td')
      .data(this._cell)
      .enter()
      .append('td')
      .merge(cell)
      .styles({
        'line-height': '3em',
        'overflow': 'hidden',
        'padding': '0 0 0 1em',
        'text-overflow': 'ellipsis',
        'white-space': 'nowrap'
      });

    this._column(column);
    this._exit(exit);
    this._enter(enter);
  }
}
<commit_msg>Handle inset by media<commit_after>import { select } from 'd3-selection';
import { controlBar } from '@scola/d3-generic';
import 'd3-selection-multi';
import '@scola/d3-media';

export default class Table {
  constructor() {
    this._rootMedia = null;
    this._bodyMedia = null;

    this._columns = [];

    this._column = () => {};
    this._cell = (d) => d;

    this._enter = () => {};
    this._exit = () => {};

    this._root = select('body')
      .append('div')
      .remove()
      .classed('scola table', true)
      .styles({
        'padding-bottom': '3em'
      });

    this._table = this._root
      .append('table')
      .styles({
        'background': '#FFF',
        'border-collapse': 'collapse',
        'border-color': '#CCC',
        'border-style': 'solid',
        'border-width': '1px 0',
        'overflow': 'hidden',
        'width': '100%'
      });

    this._head = this._table
      .append('thead');

    this._headerRow = this._head
      .append('tr')
      .append('th')
      .style('padding', 0);

    this._columnRow = this._head
      .append('tr');

    this._foot = this._table
      .append('tfoot');

    this._footerRow = this._foot
      .append('tr')
      .append('td')
      .style('padding', 0);

    this._body = this._table
      .append('tbody');
  }

  destroy() {
    if (this._rootMedia) {
      this._rootMedia.destroy();
      this._rootMedia = null;
    }

    if (this._bodyMedia) {
      this._bodyMedia.destroy();
      this._bodyMedia = null;
    }

    this._root.remove();
    this._root = null;
  }

  root() {
    return this._root;
  }

  body() {
    return this._body;
  }

  footer(action) {
    if (typeof action === 'undefined') {
      return this._footer;
    }

    if (action === false) {
      this._footer.destroy();
      this._footer = null;

      return this;
    }

    this._footer = controlBar();

    this._footer.root()
      .classed('scola footer', true)
      .styles({
        'border-top': '1px solid #CCC'
      });

    this._footerRow.node()
      .appendChild(this._footer.root().node());

    return this;
  }

  header(action) {
    if (typeof action === 'undefined') {
      return this._header;
    }

    if (action === false) {
      this._header.destroy();
      this._header = null;

      return this;
    }

    this._header = controlBar();

    this._header.root()
      .classed('scola header', true)
      .styles({
        'border-bottom': '1px solid #CCC'
      });

    this._headerRow.node()
      .appendChild(this._header.root().node());

    return this;
  }

  column(columns, modifier) {
    this._columns = columns;
    this._column = modifier;

    this._headerRow.attr('colspan', columns.length);
    this._footerRow.attr('colspan', columns.length);

    return this;
  }

  cell(value) {
    this._cell = value;
    return this;
  }

  enter(value) {
    this._enter = value;
    return this;
  }

  exit(value) {
    this._exit = value;
    return this;
  }

  inset(width = '48em') {
    if (width === false) {
      this._rootMedia.destroy();
      this._rootMedia = null;

      this._bodyedia.destroy();
      this._bodyMedia = null;

      return this;
    }

    this._rootMedia = this._root
      .media(`(min-width: ${width})`)
      .styles({
        'padding-left': '1em',
        'padding-right': '1em'
      })
      .start();

    this._bodyMedia = this._table
      .media(`(min-width: ${width})`)
      .styles({
        'border-radius': '0.5em',
        'border-style': 'none',
        'overflow': 'hidden'
      })
      .start();

    return this;
  }

  message(text, modifier = () => {}) {
    const message = this._body
      .append('tr')
      .classed('scola message', true)
      .append('td')
      .attr('colspan', this._columns.length)
      .styles({
        'cursor': 'default',
        'padding': '1em',
        'text-align': 'center'
      })
      .text(text);

    modifier(message);
    return this;
  }

  render(data, key) {
    this._body
      .select('.scola.message')
      .remove();

    const column = this._columnRow
      .selectAll('th')
      .data(this._columns)
      .enter()
      .append('th')
      .styles({
        'border-bottom': '1px solid #CCC',
        'color': '#AAA',
        'font-weight': 'normal',
        'font-size': '0.9em',
        'padding': '0.5em 0 0.5em 1em',
        'text-align': 'start',
        'text-transform': 'uppercase',
        'vertical-align': 'center'
      });

    const row = this._body
      .selectAll('tr')
      .data(data, key);

    const cell = row.selectAll('td')
      .data(this._cell);

    const exit = row.exit();

    const enter = row
      .enter()
      .append('tr')
      .merge(row)
      .style('border-top', (datum, index) => {
        return index > 0 ? '1px solid #CCC' : null;
      })
      .selectAll('td')
      .data(this._cell)
      .enter()
      .append('td')
      .merge(cell)
      .styles({
        'line-height': '3em',
        'overflow': 'hidden',
        'padding': '0 0 0 1em',
        'text-overflow': 'ellipsis',
        'white-space': 'nowrap'
      });

    this._column(column);
    this._exit(exit);
    this._enter(enter);
  }
}
<|endoftext|>


<commit_before>var $ = require("jquery");
require("./../lib/DataTables/media/js/jquery.dataTables.js");
var imgs = require("yasgui-utils").imgs;

/**
 * Constructor of plugin which displays results as a table
 *
 * @param yasr {object}
 * @param parent {DOM element}
 * @param options {object}
 * @class YASR.plugins.table
 * @return yasr-table (doc)
 *
 */
var root = module.exports = function(yasr,parent, options) {
	var plugin = {};
	plugin.options = $.extend(true, {}, root.defaults, options);
	plugin.yasr = yasr;
	plugin.parent = parent;
	plugin.draw = function() {
		root.draw(plugin);
	};
	/**
	 * Human-readable name of this plugin (used in selection widget)
	 *
	 * @property pluginDoc.name
	 * @type string
	 * @default "Table"
	 */
	plugin.name = "Table";
	/**
	 * Check whether this plugin can handler the current results
	 *
	 * @property canHandleResults
	 * @type function
	 * @default If resultset contains variables in the resultset, return true
	 */
	plugin.canHandleResults = function(yasr){
		return yasr.results && yasr.results.getVariables() && yasr.results.getVariables().length > 0;
	};
	/**
	 * If we need to dynamically check which plugin to use, we rank the possible plugins by priority, and select the highest one
	 *
	 * @property getPriority
	 * @param yasrDoc
	 * @type int|function
	 * @default 10
	 */
	plugin.getPriority =  function(yasr){return 10;};

	plugin.getDownloadInfo = function() {
		return {
			getContent: function(){return require("./bindingsToCsv.js")(yasr.results.getAsJson());},
			filename: "queryResults.csv",
			contentType: "text/csv",
			buttonTitle: "Download as CSV"
		};
	};

	plugin.disableSelectorOn = function(yasr) {

	};
	return plugin;
};

root.draw = function(plugin) {
	plugin.table = $('

');
	$(plugin.parent).html(plugin.table);

	var dataTableConfig = plugin.options.datatable;
	dataTableConfig.aaData = getRows(plugin);
	dataTableConfig.aoColumns = getVariablesAsCols(plugin),
	plugin.table.dataTable(dataTableConfig);

	drawSvgIcons(plugin);

	addEvents(plugin);

	//move the table upward, so the table options nicely aligns with the yasr header
	var headerHeight = plugin.yasr.header.outerHeight() - 5; //add some space of 5 px between table and yasr header
	if (headerHeight > 0) {
		plugin.yasr.container.find(".dataTables_wrapper")
		.css("position", "relative")
		.css("top", "-" + headerHeight + "px")
		.css("margin-bottom", "-" + headerHeight + "px");
	}

	//make sure we redraw the table on resize
	$(window).on('resize', function () {
		if (plugin.table) plugin.table.fnAdjustColumnSizing();
	});
};

var getVariablesAsCols = function(plugin) {
	var cols = [];
	cols.push({"sTitle": ""});//row numbers
	var sparqlVars = plugin.yasr.results.getVariables();
	for (var i = 0; i < sparqlVars.length; i++) {
		cols.push({"sTitle": sparqlVars[i]});
	}
	return cols;
};

var getRows = function(plugin) {
	var rows = [];
	var bindings = plugin.yasr.results.getBindings();
	var vars = plugin.yasr.results.getVariables();
	for (var rowId = 0; rowId < bindings.length; rowId++) {
		var row = [];
		row.push("");//row numbers
		var binding = bindings[rowId];
		for (var colId = 0; colId < vars.length; colId++) {
			var sparqlVar = vars[colId];
			if (sparqlVar in binding) {
				if (plugin.options.drawCellContent) {
					row.push(plugin.options.drawCellContent(rowId, colId, binding[sparqlVar]));
				} else {
					row.push("");
				}
			} else {
				row.push("");
			}
		}
		rows.push(row);
	}
	return rows;
};

root.getFormattedValueFromBinding = function(rowId, colId, binding) {
	var value = null;
	if (binding.type == "uri") {
		value = "" + binding.value + "";
	} else {
		value = "" + binding.value + "";
	}
	return value;
};
var getExternalLinkElement = function() {
	var element = $("#externalLink");
	if (element.length == 0) {
		element = $("")
			.on("click", function(){
				window.open($(this).parent().text());
			});
	}
	return element;
};
var executeSnorqlQuery = function(uri) {
	console.log("exec snorql");
//	var newQuery = Yasgui.settings.defaults.tabularBrowsingTemplate;
//	newQuery = newQuery.replace(/<URI>/g, "<" + uri + ">");
//	Yasgui.settings.getCurrentTab().query = newQuery;
//	Yasgui.tabs.getCurrentTab().cm.reloadFromSettings();
//	Yasgui.sparql.query();
};

var addEvents = function(plugin) {
	plugin.table.on( 'order.dt', function () {
	    drawSvgIcons(plugin);
	});

	plugin.table.delegate("td", "click", function() {
		if (plugin.options.handlers && plugin.options.handlers.onCellClick) {
			var result = plugin.options.handlers.onCellClick(this);
			if (result === false) return false;
		}
	}).delegate("td",'mouseenter', function(event) {
		if (plugin.options.handlers && plugin.options.handlers.onCellMouseEnter) {
			plugin.options.handlers.onCellMouseEnter(this);
		}
		var tdEl = $(this);
		if (plugin.options.fetchTitlesFromPreflabel
				&& !tdEl.attr("title")
				&& tdEl.text().trim().indexOf("http") == 0) {
			addPrefLabelTo(tdEl);
		}
	}).delegate("td",'mouseleave', function(event) {
		if (plugin.options.handlers && plugin.options.handlers.onCellMouseLeave) {
			plugin.options.handlers.onCellMouseLeave(this);

		}
	});
};

var addPrefLabelTo = function(td) {
	$.get("http://preflabel.org/api/label/" + encodeURIComponent(td.text()))
		.success(function(data) {
			td.attr("title", data);
		});
};

var drawSvgIcons = function(plugin) {
	var sortings = {
		"sorting": "unsorted",
		"sorting_asc": "sortAsc",
		"sorting_desc": "sortDesc"
	};
	plugin.table.find(".sortIcons").remove();
	for (var sorting in sortings) {
		var svgDiv = $("

").css("float", "right").css("margin-right", "-12px").width(10).height(15);
		imgs.draw(svgDiv, {id: sortings[sorting], width: 12, height: 16});
		plugin.table.find("th." + sorting).append(svgDiv);
	}
};
root.openCellUriInNewWindow = function(cell) {
	if (cell.className.indexOf("uri") >= 0) {
		window.open(this.innerHTML);
	}
};

/**
 * Defaults for table plugin
 *
 * @type object
 * @attribute YASR.plugins.table.defaults
 */
root.defaults = {

	/**
	 * Draw the cell content, from a given binding
	 *
	 * @property drawCellContent
	 * @param binding {object}
	 * @type function
	 * @return string
	 * @default YASR.plugins.table.getFormattedValueFromBinding
	 */
	drawCellContent: root.getFormattedValueFromBinding,

	/**
	 * Try to fetch the label representation for each URI, using the preflabel.org services. (fetching occurs when hovering over the cell)
	 *
	 * @property fetchTitlesFromPreflabel
	 * @type boolean
	 * @default true
	 */
	fetchTitlesFromPreflabel: true,
	/**
	 * Set a number of handlers for the table
	 *
	 * @property handlers
	 * @type object
	 */
	handlers: {
		/**
		 * Mouse-enter-cell event
		 *
		 * @property handlers.onCellMouseEnter
		 * @type function
		 * @param td-element
		 * @default null
		 */
		onCellMouseEnter: null,
		/**
		 * Mouse-leave-cell event
		 *
		 * @property handlers.onCellMouseLeave
		 * @type function
		 * @param td-element
		 * @default null
		 */
		onCellMouseLeave: null,
		/**
		 * Cell clicked event
		 *
		 * @property handlers.onCellClick
		 * @type function
		 * @param td-element
		 * @default null
		 */
//		onCellClick: root.openCellUriInNewWindow
		onCellClick: null
	},
	/**
	 * This plugin uses the datatables jquery plugin (See datatables.net). For any datatables specific defaults, change this object.
	 * See the datatables reference for more information
	 *
	 * @property datatable
	 * @type object
	 */
	datatable: {
		"aaSorting": [],//disable initial sorting
		"iDisplayLength": 50,//default page length
    	"aLengthMenu": [[10, 50, 100, 1000, -1], [10, 50, 100, 1000, "All"]],//possible page lengths
    	"bLengthChange": true,//allow changing page length
    	"sPaginationType": "full_numbers",//how to show the pagination options
        "fnDrawCallback": function ( oSettings ) {
        	//trick to show row numbers
        	for ( var i = 0; i < oSettings.aiDisplay.length; i++) {
				$('td:eq(0)',oSettings.aoData[oSettings.aiDisplay[i]].nTr).html(i + 1);
			}

        	//Hide pagination when we have a single page
        	var activePaginateButton = false;
        	$(oSettings.nTableWrapper).find(".paginate_button").each(function() {
        		if ($(this).attr("class").indexOf("current") == -1 && $(this).attr("class").indexOf("disabled") == -1) {
        			activePaginateButton = true;
        		}
        	});
        	if (activePaginateButton) {
        		$(oSettings.nTableWrapper).find(".dataTables_paginate").show();
        	} else {
        		$(oSettings.nTableWrapper).find(".dataTables_paginate").hide();
        	}
		},
		"aoColumnDefs": [
			{ "sWidth": "12px", "bSortable": false, "aTargets": [ 0 ] }//disable row sorting for first col
		],
	},
};<commit_msg>improved efficiency of fetching preflabels<commit_after>var $ = require("jquery");
require("./../lib/DataTables/media/js/jquery.dataTables.js");
var imgs = require("yasgui-utils").imgs;

/**
 * Constructor of plugin which displays results as a table
 *
 * @param yasr {object}
 * @param parent {DOM element}
 * @param options {object}
 * @class YASR.plugins.table
 * @return yasr-table (doc)
 *
 */
var root = module.exports = function(yasr,parent, options) {
	var plugin = {};
	plugin.options = $.extend(true, {}, root.defaults, options);
	plugin.yasr = yasr;
	plugin.parent = parent;
	plugin.draw = function() {
		root.draw(plugin);
	};
	/**
	 * Human-readable name of this plugin (used in selection widget)
	 *
	 * @property pluginDoc.name
	 * @type string
	 * @default "Table"
	 */
	plugin.name = "Table";
	/**
	 * Check whether this plugin can handler the current results
	 *
	 * @property canHandleResults
	 * @type function
	 * @default If resultset contains variables in the resultset, return true
	 */
	plugin.canHandleResults = function(yasr){
		return yasr.results && yasr.results.getVariables() && yasr.results.getVariables().length > 0;
	};
	/**
	 * If we need to dynamically check which plugin to use, we rank the possible plugins by priority, and select the highest one
	 *
	 * @property getPriority
	 * @param yasrDoc
	 * @type int|function
	 * @default 10
	 */
	plugin.getPriority =  function(yasr){return 10;};

	plugin.getDownloadInfo = function() {
		return {
			getContent: function(){return require("./bindingsToCsv.js")(yasr.results.getAsJson());},
			filename: "queryResults.csv",
			contentType: "text/csv",
			buttonTitle: "Download as CSV"
		};
	};

	plugin.disableSelectorOn = function(yasr) {

	};
	return plugin;
};

root.draw = function(plugin) {
	plugin.table = $('

');
	$(plugin.parent).html(plugin.table);

	var dataTableConfig = plugin.options.datatable;
	dataTableConfig.aaData = getRows(plugin);
	dataTableConfig.aoColumns = getVariablesAsCols(plugin),
	plugin.table.dataTable(dataTableConfig);

	drawSvgIcons(plugin);

	addEvents(plugin);

	//move the table upward, so the table options nicely aligns with the yasr header
	var headerHeight = plugin.yasr.header.outerHeight() - 5; //add some space of 5 px between table and yasr header
	if (headerHeight > 0) {
		plugin.yasr.container.find(".dataTables_wrapper")
		.css("position", "relative")
		.css("top", "-" + headerHeight + "px")
		.css("margin-bottom", "-" + headerHeight + "px");
	}

	//make sure we redraw the table on resize
	$(window).on('resize', function () {
		if (plugin.table) plugin.table.fnAdjustColumnSizing();
	});
};

var getVariablesAsCols = function(plugin) {
	var cols = [];
	cols.push({"sTitle": ""});//row numbers
	var sparqlVars = plugin.yasr.results.getVariables();
	for (var i = 0; i < sparqlVars.length; i++) {
		cols.push({"sTitle": sparqlVars[i]});
	}
	return cols;
};

var getRows = function(plugin) {
	var rows = [];
	var bindings = plugin.yasr.results.getBindings();
	var vars = plugin.yasr.results.getVariables();
	for (var rowId = 0; rowId < bindings.length; rowId++) {
		var row = [];
		row.push("");//row numbers
		var binding = bindings[rowId];
		for (var colId = 0; colId < vars.length; colId++) {
			var sparqlVar = vars[colId];
			if (sparqlVar in binding) {
				if (plugin.options.drawCellContent) {
					row.push(plugin.options.drawCellContent(rowId, colId, binding[sparqlVar]));
				} else {
					row.push("");
				}
			} else {
				row.push("");
			}
		}
		rows.push(row);
	}
	return rows;
};

root.getFormattedValueFromBinding = function(rowId, colId, binding) {
	var value = null;
	if (binding.type == "uri") {
		value = "" + binding.value + "";
	} else {
		value = "" + binding.value + "";
	}
	return value;
};
var getExternalLinkElement = function() {
	var element = $("#externalLink");
	if (element.length == 0) {
		element = $("")
			.on("click", function(){
				window.open($(this).parent().text());
			});
	}
	return element;
};
var executeSnorqlQuery = function(uri) {
	console.log("exec snorql");
//	var newQuery = Yasgui.settings.defaults.tabularBrowsingTemplate;
//	newQuery = newQuery.replace(/<URI>/g, "<" + uri + ">");
//	Yasgui.settings.getCurrentTab().query = newQuery;
//	Yasgui.tabs.getCurrentTab().cm.reloadFromSettings();
//	Yasgui.sparql.query();
};

var addEvents = function(plugin) {
	plugin.table.on( 'order.dt', function () {
	    drawSvgIcons(plugin);
	});

	plugin.table.delegate("td", "click", function() {
		if (plugin.options.handlers && plugin.options.handlers.onCellClick) {
			var result = plugin.options.handlers.onCellClick(this);
			if (result === false) return false;
		}
	}).delegate("td",'mouseenter', function(event) {
		if (plugin.options.handlers && plugin.options.handlers.onCellMouseEnter) {
			plugin.options.handlers.onCellMouseEnter(this);
		}
		var tdEl = $(this);
		if (plugin.options.fetchTitlesFromPreflabel
				&& !tdEl.attr("title")
				&& tdEl.text().trim().indexOf("http") == 0) {
			addPrefLabelTo(tdEl);
		}
	}).delegate("td",'mouseleave', function(event) {
		if (plugin.options.handlers && plugin.options.handlers.onCellMouseLeave) {
			plugin.options.handlers.onCellMouseLeave(this);

		}
	});
};

var addPrefLabelTo = function(td) {
	$.get("http://preflabel.org/api/label/" + encodeURIComponent(td.text()))
		.success(function(data) {
			td.attr("title", data);
		})
		.fail(function() {
			td.attr("title", "");//this avoids trying to fetch the label again on next hover
		});
};

var drawSvgIcons = function(plugin) {
	var sortings = {
		"sorting": "unsorted",
		"sorting_asc": "sortAsc",
		"sorting_desc": "sortDesc"
	};
	plugin.table.find(".sortIcons").remove();
	for (var sorting in sortings) {
		var svgDiv = $("

").css("float", "right").css("margin-right", "-12px").width(10).height(15);
		imgs.draw(svgDiv, {id: sortings[sorting], width: 12, height: 16});
		plugin.table.find("th." + sorting).append(svgDiv);
	}
};
root.openCellUriInNewWindow = function(cell) {
	if (cell.className.indexOf("uri") >= 0) {
		window.open(this.innerHTML);
	}
};

/**
 * Defaults for table plugin
 *
 * @type object
 * @attribute YASR.plugins.table.defaults
 */
root.defaults = {

	/**
	 * Draw the cell content, from a given binding
	 *
	 * @property drawCellContent
	 * @param binding {object}
	 * @type function
	 * @return string
	 * @default YASR.plugins.table.getFormattedValueFromBinding
	 */
	drawCellContent: root.getFormattedValueFromBinding,

	/**
	 * Try to fetch the label representation for each URI, using the preflabel.org services. (fetching occurs when hovering over the cell)
	 *
	 * @property fetchTitlesFromPreflabel
	 * @type boolean
	 * @default true
	 */
	fetchTitlesFromPreflabel: true,
	/**
	 * Set a number of handlers for the table
	 *
	 * @property handlers
	 * @type object
	 */
	handlers: {
		/**
		 * Mouse-enter-cell event
		 *
		 * @property handlers.onCellMouseEnter
		 * @type function
		 * @param td-element
		 * @default null
		 */
		onCellMouseEnter: null,
		/**
		 * Mouse-leave-cell event
		 *
		 * @property handlers.onCellMouseLeave
		 * @type function
		 * @param td-element
		 * @default null
		 */
		onCellMouseLeave: null,
		/**
		 * Cell clicked event
		 *
		 * @property handlers.onCellClick
		 * @type function
		 * @param td-element
		 * @default null
		 */
//		onCellClick: root.openCellUriInNewWindow
		onCellClick: null
	},
	/**
	 * This plugin uses the datatables jquery plugin (See datatables.net). For any datatables specific defaults, change this object.
	 * See the datatables reference for more information
	 *
	 * @property datatable
	 * @type object
	 */
	datatable: {
		"aaSorting": [],//disable initial sorting
		"iDisplayLength": 50,//default page length
    	"aLengthMenu": [[10, 50, 100, 1000, -1], [10, 50, 100, 1000, "All"]],//possible page lengths
    	"bLengthChange": true,//allow changing page length
    	"sPaginationType": "full_numbers",//how to show the pagination options
        "fnDrawCallback": function ( oSettings ) {
        	//trick to show row numbers
        	for ( var i = 0; i < oSettings.aiDisplay.length; i++) {
				$('td:eq(0)',oSettings.aoData[oSettings.aiDisplay[i]].nTr).html(i + 1);
			}

        	//Hide pagination when we have a single page
        	var activePaginateButton = false;
        	$(oSettings.nTableWrapper).find(".paginate_button").each(function() {
        		if ($(this).attr("class").indexOf("current") == -1 && $(this).attr("class").indexOf("disabled") == -1) {
        			activePaginateButton = true;
        		}
        	});
        	if (activePaginateButton) {
        		$(oSettings.nTableWrapper).find(".dataTables_paginate").show();
        	} else {
        		$(oSettings.nTableWrapper).find(".dataTables_paginate").hide();
        	}
		},
		"aoColumnDefs": [
			{ "sWidth": "12px", "bSortable": false, "aTargets": [ 0 ] }//disable row sorting for first col
		],
	},
};<|endoftext|>


<commit_before>/* globals jQuery */
/*
 * hqModules provides a poor man's module system for js. It is not a module *loader*,
 * only a module *referencer*: "importing" a module doesn't automatically load it as
 * a script to the page; it must already have been loaded with an explict script tag.
 *
 * Modules MUST have a name, and SHOULD be given the name of the javascript file in
 * which they reside, and SHOULD be themselves simple javascript objects.
 *
 * Modules are defined with hqDefine, and "imported" (referenced) with hqImport. Example:
 *
 * Define the module. Note that as a convention, the module name should match the file path
 * but exclude the .js extension.
 *   // myapp/static/myapp/js/utils.js
 *   hqDefine('myapp/js/utils', function () {
 *      var module = {};
 *      module.util1 = function () {...};
 *      module.util2 = function () {...};
 *      return module;
 *   });
 *
 * Include the module source on your page:
 *   // myapp/templates/myapp/page.html
 *   ...
 *   <script src="myapp/js/utils.js"></script>
 *   ...
 *
 * Reference the module in other code (either directly in the template or in another
 * file/module):
 *
 *   var utils = hqImport('myapp/js/utils');
 *   ... utils.util1() ...
 *   ... utils.util2() ...
 *
 * You can also use the following idiom to effectively import only one property or
 * function:
 *
 *   var util1 = hqImport('myapp/js/utils').util1;
 */

var COMMCAREHQ_MODULES = {};

/*
 * Transitional version of "define" to handle both RequireJS and non-RequireJS pages.
 * Signature deliberately matches that of "define". On non-RequireJS pages, the dependencies
 * argument is optional, and the major globals ($, ko, _) are available.
 */
function hqDefine(path, dependencies, moduleAccessor) {
    if (arguments.length === 2) {
        return hqDefine(path, [], dependencies);
    }

    (function(factory) {
        if (typeof define === 'function' && define.amd && window.USE_REQUIREJS) {
            define(path, dependencies, factory);
        } else {
            var thirdPartyGlobals = {
                    'jquery': '$',
                    'knockout': 'ko',
                    'underscore': '_',
                    'clipboard/dist/clipboard': 'Clipboard',
                    'ace-builds/src-min-noconflict/ace': 'ace',
                },
                thirdPartyPlugins = [
                    'jquery-form/dist/jquery.form.min',
                    'jquery.rmi/jquery.rmi',
                    'jquery-ui/ui/sortable',
                    'select2-3.5.2-legacy/select2',
                ];
            var args = [];
            for (var i = 0; i < dependencies.length; i++) {
                var dependency = dependencies[i];
                if (COMMCAREHQ_MODULES.hasOwnProperty(dependency)) {
                    args[i] = hqImport(dependency);
                } else if (thirdPartyGlobals.hasOwnProperty(dependency)) {
                    args[i] = window[thirdPartyGlobals[dependency]];
                } else if (!_.contains(thirdPartyPlugins, dependency)) {
                    var message = "Could not find module '" + dependency + "'.";
                    message += " Verify that its script tag appears before the script tag for '" + path + "'.";
                    message += " If this is a third-party module, verify it appears in thirdPartyGlobals in hqModules.js.";
                    console.warn(message);
                }
            }
            if (!COMMCAREHQ_MODULES.hasOwnProperty(path)) {
                if (path.match(/\.js$/)) {
                    throw new Error("Error in '" + path + "': module names should not end in .js.");
                }
                COMMCAREHQ_MODULES[path] = factory.apply(undefined, args);
            }
            else {
                throw new Error("The module '" + path + "' has already been defined elsewhere.");
            }
        }
    }(moduleAccessor));
}
if (typeof define === 'undefined') {
    define = hqDefine;
}

// For use only with modules that are never used in a requirejs context.
function hqImport(path) {
    if (COMMCAREHQ_MODULES[path] === undefined) {
        throw new Error("The module '" + path + "' has not yet been defined.\n\n" +
            'Did you include <script src="' + path + '.js"></script> on your html page?');
    }
    return COMMCAREHQ_MODULES[path];
}

// Support require calls within a module. Best practice is to require all dependencies
// at module definition time, but this function can be used when doing so would
// introduce a circular dependency.
function hqRequire(paths, callback) {
    if (typeof define === 'function' && define.amd && window.USE_REQUIREJS) {
        requirejs(paths, callback);
    } else {
        var args = [];
        for (var i = 0; i < paths.length; i++) {
            args.push(hqImport(paths[i]));
        }
        callback.apply(undefined, args);
    }
}
<commit_msg>Add DOMPurify to third party plugins so it works on non-requirejs pages<commit_after>/* globals jQuery */
/*
 * hqModules provides a poor man's module system for js. It is not a module *loader*,
 * only a module *referencer*: "importing" a module doesn't automatically load it as
 * a script to the page; it must already have been loaded with an explict script tag.
 *
 * Modules MUST have a name, and SHOULD be given the name of the javascript file in
 * which they reside, and SHOULD be themselves simple javascript objects.
 *
 * Modules are defined with hqDefine, and "imported" (referenced) with hqImport. Example:
 *
 * Define the module. Note that as a convention, the module name should match the file path
 * but exclude the .js extension.
 *   // myapp/static/myapp/js/utils.js
 *   hqDefine('myapp/js/utils', function () {
 *      var module = {};
 *      module.util1 = function () {...};
 *      module.util2 = function () {...};
 *      return module;
 *   });
 *
 * Include the module source on your page:
 *   // myapp/templates/myapp/page.html
 *   ...
 *   <script src="myapp/js/utils.js"></script>
 *   ...
 *
 * Reference the module in other code (either directly in the template or in another
 * file/module):
 *
 *   var utils = hqImport('myapp/js/utils');
 *   ... utils.util1() ...
 *   ... utils.util2() ...
 *
 * You can also use the following idiom to effectively import only one property or
 * function:
 *
 *   var util1 = hqImport('myapp/js/utils').util1;
 */

var COMMCAREHQ_MODULES = {};

/*
 * Transitional version of "define" to handle both RequireJS and non-RequireJS pages.
 * Signature deliberately matches that of "define". On non-RequireJS pages, the dependencies
 * argument is optional, and the major globals ($, ko, _) are available.
 */
function hqDefine(path, dependencies, moduleAccessor) {
    if (arguments.length === 2) {
        return hqDefine(path, [], dependencies);
    }

    (function(factory) {
        if (typeof define === 'function' && define.amd && window.USE_REQUIREJS) {
            define(path, dependencies, factory);
        } else {
            var thirdPartyGlobals = {
                    'jquery': '$',
                    'knockout': 'ko',
                    'underscore': '_',
                    'clipboard/dist/clipboard': 'Clipboard',
                    'ace-builds/src-min-noconflict/ace': 'ace',
                    'DOMPurify/dist/purify.min': 'DOMPurify',
                },
                thirdPartyPlugins = [
                    'jquery-form/dist/jquery.form.min',
                    'jquery.rmi/jquery.rmi',
                    'jquery-ui/ui/sortable',
                    'select2-3.5.2-legacy/select2',
                ];
            var args = [];
            for (var i = 0; i < dependencies.length; i++) {
                var dependency = dependencies[i];
                if (COMMCAREHQ_MODULES.hasOwnProperty(dependency)) {
                    args[i] = hqImport(dependency);
                } else if (thirdPartyGlobals.hasOwnProperty(dependency)) {
                    args[i] = window[thirdPartyGlobals[dependency]];
                } else if (!_.contains(thirdPartyPlugins, dependency)) {
                    var message = "Could not find module '" + dependency + "'.";
                    message += " Verify that its script tag appears before the script tag for '" + path + "'.";
                    message += " If this is a third-party module, verify it appears in thirdPartyGlobals in hqModules.js.";
                    console.warn(message);
                }
            }
            if (!COMMCAREHQ_MODULES.hasOwnProperty(path)) {
                if (path.match(/\.js$/)) {
                    throw new Error("Error in '" + path + "': module names should not end in .js.");
                }
                COMMCAREHQ_MODULES[path] = factory.apply(undefined, args);
            }
            else {
                throw new Error("The module '" + path + "' has already been defined elsewhere.");
            }
        }
    }(moduleAccessor));
}
if (typeof define === 'undefined') {
    define = hqDefine;
}

// For use only with modules that are never used in a requirejs context.
function hqImport(path) {
    if (COMMCAREHQ_MODULES[path] === undefined) {
        throw new Error("The module '" + path + "' has not yet been defined.\n\n" +
            'Did you include <script src="' + path + '.js"></script> on your html page?');
    }
    return COMMCAREHQ_MODULES[path];
}

// Support require calls within a module. Best practice is to require all dependencies
// at module definition time, but this function can be used when doing so would
// introduce a circular dependency.
function hqRequire(paths, callback) {
    if (typeof define === 'function' && define.amd && window.USE_REQUIREJS) {
        requirejs(paths, callback);
    } else {
        var args = [];
        for (var i = 0; i < paths.length; i++) {
            args.push(hqImport(paths[i]));
        }
        callback.apply(undefined, args);
    }
}
<|endoftext|>


<commit_before>function(doc) {
    if (doc.doc_type == "Location") {
	var path = [doc.domain];
	for (var i = doc.lineage.length - 1; i >= 0; i--) {
	    path.push(doc.lineage[i]);
	}
	path.push(doc._id);

	emit(path, null);
    }
}
<commit_msg>better formatting of couch view<commit_after>function(doc) {
    if (doc.doc_type == "Location") {
        var path = [doc.domain];
        for (var i = doc.lineage.length - 1; i >= 0; i--) {
            path.push(doc.lineage[i]);
        }
        path.push(doc._id);
        emit(path, null);
    }
}
<|endoftext|>


<commit_before>var test = require("tape");
var path = require("path");
var async = require("async");
var tempfs = require("temp-fs");
var setupServer = require("./setupServer");
var startPicoEngine = require("./startPicoEngine");

var startTestServer = function(callback){
    var is_windows = /^win/.test(process.platform);

    tempfs.mkdir({
        dir: path.resolve(__dirname, ".."),
        prefix: "pico-engine_test",
        recursive: true,//It and its content will be remove recursively.
        track: !is_windows//Auto-delete it on fail.
    }, function(err, dir){
        if(err) throw err;//throw ensures process is killed with non-zero exit code

        //try setting up the engine including registering rulesets
        startPicoEngine({
            host: "http://localhost:8080",
            home: dir.path,
            no_logging: true,
        }, function(err, pe){
            if(err) throw err;//throw ensures process is killed with non-zero exit code

            //setup the server without throwing up
            setupServer(pe);

            pe.getRootPico(function(err, root_pico){
                if(err) throw err;//throw ensures process is killed with non-zero exit code

                callback(null, {
                    pe: pe,
                    root_eci: root_pico.eci,
                    stopServer: function(){
                        if(!is_windows){
                            dir.unlink();
                        }
                    },
                });
            });
        });
    });
};

test("pio-engine", function(t){
    var pe;
    var root_eci;
    var stopServer;
    async.series([
        function(next){
            startTestServer(function(err, tstserver){
                if(err) return next(err);
                pe = tstserver.pe;
                root_eci = tstserver.root_eci;
                stopServer = tstserver.stopServer;
                next();
            });
        },

        ////////////////////////////////////////////////////////////////////////
        //
        // Wrangler tests
        //

        function(next){
            pe.runQuery({
                eci: root_eci,
                rid: "io.picolabs.pico",
                name: "myself",
                args: {},
            }, function(err, data){
                if(err) return next(err);

                t.equals(data.eci, root_eci);

                next();
            });
        },

        //
        // end Wrangler tests
        //
        ////////////////////////////////////////////////////////////////////////
    ], function(err){
        t.end(err);
        stopServer();
        process.exit(err ? 1 : 0);//ensure server stops
    });
});
<commit_msg>test creation of children<commit_after>var test = require("tape");
var path = require("path");
var async = require("async");
var tempfs = require("temp-fs");
var setupServer = require("./setupServer");
var startPicoEngine = require("./startPicoEngine");

var startTestServer = function(callback){
    var is_windows = /^win/.test(process.platform);

    tempfs.mkdir({
        dir: path.resolve(__dirname, ".."),
        prefix: "pico-engine_test",
        recursive: true,//It and its content will be remove recursively.
        track: !is_windows//Auto-delete it on fail.
    }, function(err, dir){
        if(err) throw err;//throw ensures process is killed with non-zero exit code

        //try setting up the engine including registering rulesets
        startPicoEngine({
            host: "http://localhost:8080",
            home: dir.path,
            no_logging: true,
        }, function(err, pe){
            if(err) throw err;//throw ensures process is killed with non-zero exit code

            //setup the server without throwing up
            setupServer(pe);

            pe.getRootPico(function(err, root_pico){
                if(err) throw err;//throw ensures process is killed with non-zero exit code

                callback(null, {
                    pe: pe,
                    root_eci: root_pico.eci,
                    stopServer: function(){
                        if(!is_windows){
                            dir.unlink();
                        }
                    },
                });
            });
        });
    });
};

test("pio-engine", function(t){
    var pe, root_eci, stopServer, child_count;//, child;
    async.series([
        function(next){
            startTestServer(function(err, tstserver){
                if(err) return next(err);
                pe = tstserver.pe;
                root_eci = tstserver.root_eci;
                stopServer = tstserver.stopServer;
                next();
            });
        },

        ////////////////////////////////////////////////////////////////////////
        //
        //                      Wrangler tests
        //

        function(next){ // example , call myself function check if eci is the same as root.
            pe.runQuery({
                eci: root_eci,
                rid: "io.picolabs.pico",
                name: "myself",
                args: {},
            }, function(err, data){
                if(err) return next(err);

                t.equals(data.eci, root_eci);

                next();
            });
        },
        ///////////////////////////////// create child tests ///////////////
        function(next){// store created children
            pe.runQuery({
                eci: root_eci,
                rid: "io.picolabs.pico",
                name: "children",
                args: {},
            }, function(err, data){
                if(err) return next(err);
                child_count = data.length;
                next();
            });
        },
        function(next){// create child
            pe.signalEvent({
                eci: root_eci,
                eid: "84",
                domain: "pico",
                type: "new_child_request",
                attrs: {"dname":"ted"}
            }, function(err, response){
                if(err) return next(err);
                console.log("this is the response:",response);
                pe.emitter.on("episode_start", function(context){
                    if (context.event && context.event.type == "child_created"){
                        console.log("this is the context:",context);
                        //store child information from event for deleting
                    }
                });
                next();
            });
        },
        function(next){// list children and check for new child
            pe.runQuery({
                eci: root_eci,
                rid: "io.picolabs.pico",
                name: "children",
                args: {},
            }, function(err, data){
                if(err) return next(err);
                t.equals(data.length > child_count, true); // created a child
                t.equals(data.length , child_count+1); // created only 1 child
                //check that child is the same from the event above
                next();
            });
        },

        //
        //                      end Wrangler tests
        //
        ////////////////////////////////////////////////////////////////////////
    ], function(err){
        t.end(err);
        stopServer();
        process.exit(err ? 1 : 0);//ensure server stops
    });
});
<|endoftext|>


<commit_before>var $F = Ti.Filesystem,
	fs = exports,
	util = require('util');

var MODE_MAP = {};
MODE_MAP['r'] = MODE_MAP['r+'] = MODE_MAP['rs'] = MODE_MAP['rs+'] = $F.MODE_READ;
MODE_MAP['w'] = MODE_MAP['w+'] = MODE_MAP['wx'] = MODE_MAP['wx+'] = $F.MODE_WRITE;
MODE_MAP['a'] = MODE_MAP['a+'] = MODE_MAP['ax'] = MODE_MAP['ax+'] = $F.MODE_APPEND;

fs.Stats = function Stats() {
	throw new Error('Stats not yet implemented');
};

fs.exists = function exists(path, callback) {
	setTimeout(function() {
		return callback(fs.existsSync(path));
	}, 0);
};

fs.existsSync = function existsSync(path) {
	return $F.getFile(path).exists();
};

fs.readFile = function readFile(path, options, callback_) {
	throw new Error('readFile not yet implemented');
};

fs.readFileSync = function readFileSync(path, options) {
 throw new Error('readFileSync not yet implemented');
};

fs.close = function close(fd, callback) {
	setTimeout(function() {
		var err = null;
		try {
			fd.close();
		} catch (e) {
			err = e;
		}
		console.log(callback);
		return callback(err);
	}, 0);
};

fs.closeSync = function closeSync(fd) {
	fd.close();
};

fs.open = function open(path, flags, mode, callback) {
	callback = maybeCallback(arguments[arguments.length-1]);
	if (!mode || util.isFunction(mode)) {
		mode = null;
	}

	setTimeout(function() {
		var fd = null,
			err = null;
		try {
			fd = fs.openSync(path, flags, mode);
		} catch (e) {
			err = e;
		}
		return callback(err, fd);
	}, 0);
};

fs.openSync = function openSync(path, flags, mode) {
	var tiMode = MODE_MAP[flags];
	if (!tiMode) {
		throw new Error('Unknown file open flag: ' + flags);
	}
	return $F.getFile(path).open(tiMode);
};

fs.read = function read(fd, buffer, offset, length, position, callback) {
	throw new Error('read not yet implemented');
};

fs.readSync = function readSync(fd, buffer, offset, length, position) {
	throw new Error('readSync not yet implemented');
};

fs.write = function write(fd, buffer, offset, length, position, callback) {
	throw new Error('write not yet implemented');
};

fs.writeSync = function writeSync(fd, buffer, offset, length, position) {
	throw new Error('writeSync not yet implemented');
};

fs.rename = function rename(oldPath, newPath, callback) {
	throw new Error('rename not yet implemented');
};

fs.renameSync = function renameSync(oldPath, newPath) {
	throw new Error('renameSync not yet implemented');
};

fs.truncate = function truncate(path, len, callback) {
	throw new Error('truncate not yet implemented');
};

fs.truncateSync = function truncateSync(path, len) {
	throw new Error('truncateSync not yet implemented');
};

fs.ftruncate = function ftruncate(fd, len, callback) {
	throw new Error('ftruncate not yet implemented');
};

fs.ftruncateSync = function ftruncateSync(fd, len) {
	throw new Error('ftruncateSync not yet implemented');
};

fs.rmdir = function rmdir(path, callback) {
	throw new Error('rmdir not yet implemented');
};

fs.rmdirSync = function rmdirSync(path) {
	throw new Error('rmdirSync not yet implemented');
};

fs.fdatasync = function fdatasync(fd, callback) {
	throw new Error('fdatasync not yet implemented');
};

fs.fdatasyncSync = function fdatasyncSync(fd) {
	throw new Error('fdatasyncSync not yet implemented');
};

fs.fsync = function fsync(fd, callback) {
	throw new Error('fsync not yet implemented');
};

fs.fsyncSync = function fsyncSync(fd) {
	throw new Error('fsyncSync not yet implemented');
};

fs.mkdir = function mkdir(path, mode, callback) {
	throw new Error('mkdir not yet implemented');
};

fs.mkdirSync = function mkdirSync(path, mode) {
	throw new Error('mkdirSync not yet implemented');
};

fs.readdir = function readdir(path, callback) {
	throw new Error('readdir not yet implemented');
};

fs.readdirSync = function readdirSync(path) {
	throw new Error('readdirSync not yet implemented');
};

fs.fstat = function fstat(fd, callback) {
	throw new Error('fstat not yet implemented');
};

fs.lstat = function lstat(path, callback) {
	throw new Error('lstat not yet implemented');
};

fs.stat = function stat(path, callback) {
	throw new Error('stat not yet implemented');
};

fs.fstatSync = function fstatSync(fd) {
	throw new Error('fstatSync not yet implemented');
};

fs.lstatSync = function lstatSync(path) {
	throw new Error('lstatSync not yet implemented');
};

fs.statSync = function statSync(path) {
	throw new Error('statSync not yet implemented');
};

fs.readlink = function readlink(path, callback) {
	throw new Error('readlink not yet implemented');
};

fs.readlinkSync = function readlinkSync(path) {
	throw new Error('readlinkSync not yet implemented');
};

fs.symlink = function symlink(destination, path, type_, callback) {
	throw new Error('symlink not yet implemented');
};

fs.symlinkSync = function symlinkSync(destination, path, type) {
	throw new Error('symlinkSync not yet implemented');
};

fs.link = function link(srcpath, dstpath, callback) {
	throw new Error('link not yet implemented');
};

fs.linkSync = function linkSync(srcpath, dstpath) {
	throw new Error('linkSync not yet implemented');
};

fs.unlink = function unlink(path, callback) {
	throw new Error('unlink not yet implemented');
};

fs.unlinkSync = function unlinkSync(path) {
	throw new Error('unlinkSync not yet implemented');
};

fs.fchmod = function fchmod(fd, mode, callback) {
	throw new Error('fchmod not yet implemented');
};

fs.fchmodSync = function fchmodSync(fd, mode) {
	throw new Error('fchmodSync not yet implemented');
};

fs.lchmod = function lchmod(path, mode, callback) {
	throw new Error('lchmod not yet implemented');
};

fs.lchmodSync = function lchmodSync(path, mode) {
	throw new Error('lchmodSync not yet implemented');
};

fs.chmod = function chmod(path, mode, callback) {
	throw new Error('chmod not yet implemented');
};

fs.chmodSync = function chmodSync(path, mode) {
	throw new Error('chmodSync not yet implemented');
};

fs.lchown = function lchown(path, uid, gid, callback) {
	throw new Error('lchown not yet implemented');
};

fs.lchownSync = function lchownSync(path, uid, gid) {
	throw new Error('lchownSync not yet implemented');
};

fs.fchown = function fchown(fd, uid, gid, callback) {
	throw new Error('fchown not yet implemented');
};

fs.fchownSync = function fchownSync(fd, uid, gid) {
	throw new Error('fchownSync not yet implemented');
};

fs.chown = function chown(path, uid, gid, callback) {
	throw new Error('chown not yet implemented');
};

fs.chownSync = function chownSync(path, uid, gid) {
	throw new Error('chownSync not yet implemented');
};

fs._toUnixTimestamp = function _toUnixTimestamp(time) {
	throw new Error('_toUnixTimestamp not yet implemented');
};

fs.utimes = function utimes(path, atime, mtime, callback) {
	throw new Error('utimes not yet implemented');
};

fs.utimesSync = function utimesSync(path, atime, mtime) {
	throw new Error('utimesSync not yet implemented');
};

fs.futimes = function futimes(fd, atime, mtime, callback) {
	throw new Error('futimes not yet implemented');
};

fs.futimesSync = function futimesSync(fd, atime, mtime) {
	throw new Error('futimesSync not yet implemented');
};

fs.writeFile = function writeFile(path, data, options, callback) {
	throw new Error('writeFile not yet implemented');
};

fs.writeFileSync = function writeFileSync(path, data, options) {
	throw new Error('writeFileSync not yet implemented');
};

fs.appendFile = function appendFile(path, data, options, callback_) {
	throw new Error('appendFile not yet implemented');
};

fs.appendFileSync = function appendFileSync(path, data, options) {
	throw new Error('appendFileSync not yet implemented');
};

fs.watch = function watch(filename) {
	throw new Error('watch not yet implemented');
};

fs.watchFile = function watchFile(filename) {
	throw new Error('watchFile not yet implemented');
};

fs.unwatchFile = function unwatchFile(filename, listener) {
	throw new Error('unwatchFile not yet implemented');
};

fs.realpathSync = function realpathSync(p, cache) {
	throw new Error('realpathSync not yet implemented');
};

fs.realpath = function realpath(p, cache, cb) {
	throw new Error('realpath not yet implemented');
};

fs.createReadStream = function createReadStream(path, options) {
	throw new Error('createReadStream not yet implemented');
};

fs.ReadStream = function ReadStream(path, options) {
	throw new Error('ReadStream not yet implemented');
};

fs.FileReadStream = function FileReadStream(path, options) {
	throw new Error('FileReadStream not yet implemented');
};

fs.createWriteStream = function createWriteStream(path, options) {
	throw new Error('createWriteStream not yet implemented');
};

fs.WriteStream = function WriteStream(path, options) {
	throw new Error('WriteStream not yet implemented');
};

fs.FileWriteStream = function FileWriteStream(path, options) {
	throw new Error('FileWriteStream not yet implemented');
};

fs.SyncWriteStream = function SyncWriteStream(fd, options) {
	throw new Error('SyncWriteStream not yet implemented');
};

function maybeCallback(o) {
	return o && Object.prototype.toString.call(o) === '[object Function]' ? o : function(err) {
		if (err) { throw err; }
	};
}
<commit_msg>rebuild<commit_after>var $F = Ti.Filesystem,
	fs = exports,
	util = require('util');

var MODE_MAP = {};
MODE_MAP['r'] = MODE_MAP['r+'] = MODE_MAP['rs'] = MODE_MAP['rs+'] = $F.MODE_READ;
MODE_MAP['w'] = MODE_MAP['w+'] = MODE_MAP['wx'] = MODE_MAP['wx+'] = $F.MODE_WRITE;
MODE_MAP['a'] = MODE_MAP['a+'] = MODE_MAP['ax'] = MODE_MAP['ax+'] = $F.MODE_APPEND;

fs.Stats = function Stats() {
	throw new Error('Stats not yet implemented');
};

fs.exists = function exists(path, callback) {
	setTimeout(function() {
		return callback(fs.existsSync(path));
	}, 0);
};

fs.existsSync = function existsSync(path) {
	return $F.getFile(path).exists();
};

fs.readFile = function readFile(path, options, callback_) {
	throw new Error('readFile not yet implemented');
};

fs.readFileSync = function readFileSync(path, options) {
 throw new Error('readFileSync not yet implemented');
};

fs.close = function close(fd, callback) {
	setTimeout(function() {
		var err = null;
		try {
			fd.close();
		} catch (e) {
			err = e;
		}
		return callback(err);
	}, 0);
};

fs.closeSync = function closeSync(fd) {
	fd.close();
};

fs.open = function open(path, flags, mode, callback) {
	callback = maybeCallback(arguments[arguments.length-1]);
	if (!mode || util.isFunction(mode)) {
		mode = null;
	}

	setTimeout(function() {
		var fd = null,
			err = null;
		try {
			fd = fs.openSync(path, flags, mode);
		} catch (e) {
			err = e;
		}
		return callback(err, fd);
	}, 0);
};

fs.openSync = function openSync(path, flags, mode) {
	var tiMode = MODE_MAP[flags];
	if (!tiMode) {
		throw new Error('Unknown file open flag: ' + flags);
	}
	return $F.getFile(path).open(tiMode);
};

fs.read = function read(fd, buffer, offset, length, position, callback) {
	throw new Error('read not yet implemented');
};

fs.readSync = function readSync(fd, buffer, offset, length, position) {
	throw new Error('readSync not yet implemented');
};

fs.write = function write(fd, buffer, offset, length, position, callback) {
	throw new Error('write not yet implemented');
};

fs.writeSync = function writeSync(fd, buffer, offset, length, position) {
	throw new Error('writeSync not yet implemented');
};

fs.rename = function rename(oldPath, newPath, callback) {
	throw new Error('rename not yet implemented');
};

fs.renameSync = function renameSync(oldPath, newPath) {
	throw new Error('renameSync not yet implemented');
};

fs.truncate = function truncate(path, len, callback) {
	throw new Error('truncate not yet implemented');
};

fs.truncateSync = function truncateSync(path, len) {
	throw new Error('truncateSync not yet implemented');
};

fs.ftruncate = function ftruncate(fd, len, callback) {
	throw new Error('ftruncate not yet implemented');
};

fs.ftruncateSync = function ftruncateSync(fd, len) {
	throw new Error('ftruncateSync not yet implemented');
};

fs.rmdir = function rmdir(path, callback) {
	throw new Error('rmdir not yet implemented');
};

fs.rmdirSync = function rmdirSync(path) {
	throw new Error('rmdirSync not yet implemented');
};

fs.fdatasync = function fdatasync(fd, callback) {
	throw new Error('fdatasync not yet implemented');
};

fs.fdatasyncSync = function fdatasyncSync(fd) {
	throw new Error('fdatasyncSync not yet implemented');
};

fs.fsync = function fsync(fd, callback) {
	throw new Error('fsync not yet implemented');
};

fs.fsyncSync = function fsyncSync(fd) {
	throw new Error('fsyncSync not yet implemented');
};

fs.mkdir = function mkdir(path, mode, callback) {
	throw new Error('mkdir not yet implemented');
};

fs.mkdirSync = function mkdirSync(path, mode) {
	throw new Error('mkdirSync not yet implemented');
};

fs.readdir = function readdir(path, callback) {
	throw new Error('readdir not yet implemented');
};

fs.readdirSync = function readdirSync(path) {
	throw new Error('readdirSync not yet implemented');
};

fs.fstat = function fstat(fd, callback) {
	throw new Error('fstat not yet implemented');
};

fs.lstat = function lstat(path, callback) {
	throw new Error('lstat not yet implemented');
};

fs.stat = function stat(path, callback) {
	throw new Error('stat not yet implemented');
};

fs.fstatSync = function fstatSync(fd) {
	throw new Error('fstatSync not yet implemented');
};

fs.lstatSync = function lstatSync(path) {
	throw new Error('lstatSync not yet implemented');
};

fs.statSync = function statSync(path) {
	throw new Error('statSync not yet implemented');
};

fs.readlink = function readlink(path, callback) {
	throw new Error('readlink not yet implemented');
};

fs.readlinkSync = function readlinkSync(path) {
	throw new Error('readlinkSync not yet implemented');
};

fs.symlink = function symlink(destination, path, type_, callback) {
	throw new Error('symlink not yet implemented');
};

fs.symlinkSync = function symlinkSync(destination, path, type) {
	throw new Error('symlinkSync not yet implemented');
};

fs.link = function link(srcpath, dstpath, callback) {
	throw new Error('link not yet implemented');
};

fs.linkSync = function linkSync(srcpath, dstpath) {
	throw new Error('linkSync not yet implemented');
};

fs.unlink = function unlink(path, callback) {
	throw new Error('unlink not yet implemented');
};

fs.unlinkSync = function unlinkSync(path) {
	throw new Error('unlinkSync not yet implemented');
};

fs.fchmod = function fchmod(fd, mode, callback) {
	throw new Error('fchmod not yet implemented');
};

fs.fchmodSync = function fchmodSync(fd, mode) {
	throw new Error('fchmodSync not yet implemented');
};

fs.lchmod = function lchmod(path, mode, callback) {
	throw new Error('lchmod not yet implemented');
};

fs.lchmodSync = function lchmodSync(path, mode) {
	throw new Error('lchmodSync not yet implemented');
};

fs.chmod = function chmod(path, mode, callback) {
	throw new Error('chmod not yet implemented');
};

fs.chmodSync = function chmodSync(path, mode) {
	throw new Error('chmodSync not yet implemented');
};

fs.lchown = function lchown(path, uid, gid, callback) {
	throw new Error('lchown not yet implemented');
};

fs.lchownSync = function lchownSync(path, uid, gid) {
	throw new Error('lchownSync not yet implemented');
};

fs.fchown = function fchown(fd, uid, gid, callback) {
	throw new Error('fchown not yet implemented');
};

fs.fchownSync = function fchownSync(fd, uid, gid) {
	throw new Error('fchownSync not yet implemented');
};

fs.chown = function chown(path, uid, gid, callback) {
	throw new Error('chown not yet implemented');
};

fs.chownSync = function chownSync(path, uid, gid) {
	throw new Error('chownSync not yet implemented');
};

fs._toUnixTimestamp = function _toUnixTimestamp(time) {
	throw new Error('_toUnixTimestamp not yet implemented');
};

fs.utimes = function utimes(path, atime, mtime, callback) {
	throw new Error('utimes not yet implemented');
};

fs.utimesSync = function utimesSync(path, atime, mtime) {
	throw new Error('utimesSync not yet implemented');
};

fs.futimes = function futimes(fd, atime, mtime, callback) {
	throw new Error('futimes not yet implemented');
};

fs.futimesSync = function futimesSync(fd, atime, mtime) {
	throw new Error('futimesSync not yet implemented');
};

fs.writeFile = function writeFile(path, data, options, callback) {
	throw new Error('writeFile not yet implemented');
};

fs.writeFileSync = function writeFileSync(path, data, options) {
	throw new Error('writeFileSync not yet implemented');
};

fs.appendFile = function appendFile(path, data, options, callback_) {
	throw new Error('appendFile not yet implemented');
};

fs.appendFileSync = function appendFileSync(path, data, options) {
	throw new Error('appendFileSync not yet implemented');
};

fs.watch = function watch(filename) {
	throw new Error('watch not yet implemented');
};

fs.watchFile = function watchFile(filename) {
	throw new Error('watchFile not yet implemented');
};

fs.unwatchFile = function unwatchFile(filename, listener) {
	throw new Error('unwatchFile not yet implemented');
};

fs.realpathSync = function realpathSync(p, cache) {
	throw new Error('realpathSync not yet implemented');
};

fs.realpath = function realpath(p, cache, cb) {
	throw new Error('realpath not yet implemented');
};

fs.createReadStream = function createReadStream(path, options) {
	throw new Error('createReadStream not yet implemented');
};

fs.ReadStream = function ReadStream(path, options) {
	throw new Error('ReadStream not yet implemented');
};

fs.FileReadStream = function FileReadStream(path, options) {
	throw new Error('FileReadStream not yet implemented');
};

fs.createWriteStream = function createWriteStream(path, options) {
	throw new Error('createWriteStream not yet implemented');
};

fs.WriteStream = function WriteStream(path, options) {
	throw new Error('WriteStream not yet implemented');
};

fs.FileWriteStream = function FileWriteStream(path, options) {
	throw new Error('FileWriteStream not yet implemented');
};

fs.SyncWriteStream = function SyncWriteStream(fd, options) {
	throw new Error('SyncWriteStream not yet implemented');
};

function maybeCallback(o) {
	return o && Object.prototype.toString.call(o) === '[object Function]' ? o : function(err) {
		if (err) { throw err; }
	};
}
<|endoftext|>