exports.parent = function(selector, limit){
  return this.dom(traverse('parentNode',
    this[0],
    selector,
    limit
    || 1));
};
Example #2
0
AWS.mock = function(service, method, replace) {
  // If the service does not exist yet, we need to create and stub it.
  if (!services[service]) {
    services[service]             = {};

    /**
     * Save the real constructor so we can invoke it later on.
     * Uses traverse for easy access to nested services (dot-separated)
     */
    services[service].Constructor = traverse(_AWS).get(service.split('.'));
    services[service].methodMocks = {};
    services[service].invoked = false;
    mockService(service);
  }

  // Register the method to be mocked out.
  if(!services[service].methodMocks[method]) {
    services[service].methodMocks[method] = { replace: replace };

    // If the constructor was already invoked, we need to mock the method here.
    if(services[service].invoked) {
      mockServiceMethod(service, services[service].client, method, replace);
    }
  }
  return services[service].methodMocks[method];
}
/**
 * Discover model definitions from a JSON object
 * @param json
 * @param options
 * @returns {Array}
 */
function discoverModelDefinitions(json, options) {
  var schemas = [];
  var stack = [];
  var result = traverse(json).forEach(function(item) {
    var type = typeof item;

    if (Array.isArray(item)) {
      type = 'array';
    }
    if (type === 'object') {
      type = item.constructor.name.toLowerCase();
    }

    var name = this.key ? this.key : 'root';
    if (type === 'object' || type === 'array') {
      var s = { name: name, properties: {}};
      stack[this.level] = s;
      schemas.push(s);
      if (type === 'object') {
        type = name;
      }
    }

    if (this.level > 0) {
      stack[this.level - 1].properties[this.key] = type;
    }

    return item;
  });

  console.log(schemas);
  return schemas;
}
Example #4
0
formatDateInstances = function (obj) {
    return Traverse(obj).forEach(function (x) {
        if (x && x.constructor && x.constructor.name == 'Date') {
            this.update(x.getTime());
        }
    });
};
Example #5
0
function buildTree() {
    var input = document.forms['input']['expression'].value
    var xhr = new XMLHttpRequest()
    xhr.open('POST', 'buildtree', false)
    xhr.setRequestHeader("Content-Type", "application/octet-stream")
    xhr.send(input)
    var response = JSON.parse(xhr.responseText)
    traverse(response).forEach(function(x) {
        if (this.key == 'text')
            this.update({'name': x})
    })
    response.collapsed = true
    if (currentTree !== undefined)
        currentTree.destroy()
    currentTree = new Treant({
        chart: {
            container: "#parse-tree",
            rootOrientation: "WEST",
            connectors: {
                type: "step"
            },
            node: {
                collapsable: true
            }
        },
        nodeStructure: response
    })
}
Example #6
0
  exportObject: function(data) {

    let convert = function(instance) {
      let obj = {};
      for (let i = 0; i < Object.keys(instance).length; i++) {
        let key = Object.keys(instance)[i];
        if (instance.hasOwnProperty(key) &&
            !key.startsWith('_') &&
            typeof instance[key] !== 'function') {
          obj[key] = instance[key];
        }
      }
      return obj;
    };

    data = { data: data };

    traverse(data).forEach(function (val) {
      if (val && val._class) {
        let newVal = convert(val);
        return this.update(newVal);
      }
    });

    return data.data;
  },
Example #7
0
module.exports = function prefix(name, tree) {
    traverse(tree).forEach(function (node) {
        if (node !== 'simpleselector') {
            return;
        }

        var nodes = this.parent.node;

        // don't prefix if any of the following conditions are met:
        // .module exists as a parent then ok
        // .module exists in a set of classes right after an element
        // .module exists in the first set of classes
        for (var i=1 ; i<nodes.length ; ++i) {
            var node = nodes[i];

            // first space exists search
            if (node[0] === 's') {
                break;
            }

            if (node[0] === 'clazz' && node[1][0] === 'ident' &&
                node[1][1] === name) {
                return;
            }
        }

        // prefix the css rule
        this.parent.node.splice(1, 0,
            [ 'clazz', [ 'ident', name ] ],
            [ 's', ' ' ]
        );
    });

    return tree;
};
Example #8
0
    return components.map(function (componentFile) {
      let code = fs.readFileSync(path.join(searchPath, componentFile), 'utf8');
      let tree;
      try {
        tree = componentFinder.parseJsx(code);
      } catch (e) {
        return {path: componentFile, error: e};
      }

      // Seek new-style class first (faster)
      let className = _(tree.body)
        .where({type: 'ClassDeclaration'})
        .pluck(['id', 'name'])
        .first();

      if (!className) {
        // Recursively search through the AST tree until we find a React.createClass being assigned to a variable
        traverse(tree.body).forEach(function (x) {
          if (x && x.type === 'VariableDeclarator') {
            if (_.get(x, 'init.callee.object.name') === 'React' &&
              _.get(x, 'init.callee.property.name') === 'createClass') {
              className = _.get(x, 'id.name');
              this.stop();
            }
          }
        });
      }

      return {name: className, path: componentFile};
    });
Example #9
0
module.exports = function (source, mapping) {
  return traverse(mapping).map(function (item) {
    if (typeof item === 'string') {
      this.update(getobject.get(source, item));
    }
  });
};
    traverse(clonedSchema).forEach(function (x) {
        if (!!x && x.elementName === REPEATER_CONTAINER_NAME){
            var binding = x.props && x.props.binding;
            if(!!binding && !!binding.path && !!binding.range) {
                //for each row - deep clone row template
                var clonedRows = [];
                var range = binding.range;
                for (var i = range.from; i != range.to; i++) {

                    var clonedRow = _.cloneDeep(x);
                    clonedRow.elementName = CONTAINER_NAME;
                    clonedRow.props.binding = undefined;
                    //apply binding using square brackets notation
                    traverse(clonedRow).forEach(function (y) {
                        //TODO: simple solution for demonstration purposes
                        if (this.key === "path") {
                            var lastIndex = binding.path.lastIndexOf('[');

                            var arrayPath = lastIndex!==-1?binding.path.substr(0,lastIndex):binding.path;
                            var rowExpression = arrayPath + "[" + i + "]." + y;

                            this.update(rowExpression);
                        }
                    });

                    clonedRows.push(clonedRow);
                }

                //assign all cloned rows to parent section
                x.containers = clonedRows;
                x.boxes = [];

            }
        }
    });
var scrubb = function scrubbFn (o) {
	return t(o).map(function (x) {
    	if (this.circular) {
    		this.remove();
    	}
	});
};
Example #12
0
    var applyFilter = function (data) {

        Traverse(data).forEach(function (value) {

            if (this.isRoot) {
                return;
            }

            if (this.isLeaf) {
                var filter = internals.getOwnProperty(filterRules, this.key) || internals.getOwnProperty(filterRules, this.parent.key);

                if (filter) {
                    filter = filter.toLowerCase();

                    if (filter === 'censor') {
                        this.update(('' + value).replace(/./g, 'X'));
                    }
                    else if (filter === 'remove') {
                        this.delete();
                    }
                    // Means this is a string that needs to be turned into a RegEx
                    else {
                        var regex = new RegExp(filter);
                        this.update(('' + value).replace(regex, replacer));
                    }
                }
            }
        });
    };
exports.previous = function(selector, limit){
  return this.dom(traverse('previousSibling',
    this[0],
    selector,
    limit
    || 1));
};
exports.next = function(selector, limit){
  return this.dom(traverse('nextSibling',
    this[0],
    selector,
    limit
    || 1));
};
Example #15
0
SharedMethod.convertArg = function(accept, raw) {
  if(accept.http && (accept.http.source === 'req'
    || accept.http.source === 'res'
    || accept.http.source === 'context'
    )) {
    return raw;
  }
  if(raw === null || typeof raw !== 'object') {
    return raw;
  }
  var data = traverse(raw).forEach(function(x) {
    if(x === null || typeof x !== 'object') {
      return x;
    }
    var result = x;
    if(x.$type === 'base64' || x.$type === 'date') {
      switch (x.$type) {
        case 'base64':
          result = new Buffer(x.$data, 'base64');
          break;
        case 'date':
          result = new Date(x.$data);
          break;
      }
      this.update(result);
    }
    return result;
  });
  return data;
};
/**
 * Remove undefined values from the queury object
 * @param query
 * @param handleUndefined {String} either "nullify", "throw" or "ignore" (default: "ignore")
 * @returns {exports.map|*}
 */
function removeUndefined(query, handleUndefined) {
  if (typeof query !== 'object' || query === null) {
    return query;
  }
  // WARNING: [rfeng] Use map() will cause mongodb to produce invalid BSON
  // as traverse doesn't transform the ObjectId correctly
  return traverse(query).forEach(function(x) {
    if (x === undefined) {
      switch (handleUndefined) {
        case 'nullify':
          this.update(null);
          break;
        case 'throw':
          throw new Error(g.f('Unexpected `undefined` in query'));
          break;
        case 'ignore':
        default:
          this.remove();
      }
    }

    if (!Array.isArray(x) && (typeof x === 'object' && x !== null &&
        x.constructor !== Object)) {
      // This object is not a plain object
      this.update(x, true); // Stop navigating into this object
      return x;
    }

    return x;
  });
}
/**
 * parse markdown text and return ast mapped location info.
 * @param {string} text
 * @returns {TxtNode}
 */
function parse(text) {
    var mdast = require('mdast');
    var ast = mdast.parse(text);
    var SyntaxMap = require("./mapping/markdown-syntax-map");
    var src = new StructuredSource(text);
    traverse(ast).forEach(function (node) {
        if (this.notLeaf) {
            if (node.type) {
                var replacedType = SyntaxMap[node.type];
                if(!replacedType) {
                    debug("replacedType : " + replacedType + " , node.type: " + node.type);
                }
                node.type = replacedType;
            }
            // map `range`, `loc` and `raw` to node
            if (node.position) {
                var position = node.position;
                var positionCompensated = {
                    start: {line: position.start.line, column: position.start.column - 1},
                    end: {line: position.end.line, column: position.end.column - 1}
                };
                var range = src.locationToRange(positionCompensated);
                node.loc = positionCompensated;
                node.range = range;
                node.raw = text.slice(range[0], range[1]);
            }
            removeUnusedProperties(node);
        }
    });
    return ast;
}
Example #18
0
                                napi_res.on('end', function () {
                                    var napi_obj = JSON.parse(raw2.join(''));
                                    //console.log(util.inspect(napi_obj, false, null));

                                    // console.log("TRAVERSING: " + JSON.stringify(napi_obj));
                                    var names = traverse(napi_obj).reduce(function (acc, x) {
                                        if (x && x.name && this.parent.key === "names" && typeof x !== 'string') {
                                            //console.log("============");
                                            //console.dir(x);
                                            //console.log("============");
                                            var joined = "name_"

                                            if (x.language) {
                                                joined += abbreviate(x.language)
                                            }
                                            if (x.relationship) {
                                                if (typeof x.relationship == 'string' || x.relationship.code ) {
                                                    joined += "_" + abbreviate(x.relationship);
                                                }
                                            }
                                            if (x.writing_system) {
                                                joined += "_" + abbreviate(x.writing_system);
                                            }
                                            acc[joined] = x.name;
                                        }
                                        return acc;
                                    }, {});
                                    //console.dir(names);
                                    _.extend(doc, names);
                                    doc.checksum = checksum(doc);
                                    callback(null, doc);
                                    napi_res.resume();
				    if (--napi_count !== 0) console.log("COUNT napi = " + ( napi_count ));
                                });
Example #19
0
            .then( function(jiveConfig) {
                traverse(jiveConfig).forEach(function(value) {
                    if (typeof (value) === 'string') {
                        var self = this;
                        mustache.render(value, process.env)
                          .then(
                            function(processed) {
                              self.update(processed);
                            } // end function
                          );

                    }
                });

                applyDefaults(jiveConfig);
                applyOverrides(jiveConfig);

                exports.options = jiveConfig;
                jive.context.config = exports.options;

                jive.logger.debug('Startup configuration from', options);
                jive.logger.debug(jiveConfig);

                return jiveConfig;
            })
Example #20
0
 this.post(function (child) {
     if (!child.isLast && !(indent && commaFirst)) {
         write(',');
     }
     
     var prev = prevNode && prevNode[child.key];
     if (indent && opts.comment && child.node !== prev
     && (typeof child.node !== 'object' || typeof prev !== 'object')
     ) {
         set('comment');
         write(' // != ');
         traverse(prev).forEach(function (x) {
             plainStringify.call(this, x, { indent : 0 });
         });
         unset('comment');
     }
     
     if (!child.isLast) {
         if (indent && commaFirst) {
             write('\n' + indentx + ', ');
         }
         else if (indent) {
             write('\n' + indentx);
         }
     }
 });
Example #21
0
exports['sort test'] = function () {
    var acc = [];
    Traverse({
        a: 30,
        b: 22,
        id: 9
    }).forEach(function (node) {
        if ((! Array.isArray(node)) && typeof node === 'object') {
            this.before(function(node) {
                this.keys = Object.keys(node);
                this.keys.sort(function(a, b) {
                    a = [a === "id" ? 0 : 1, a];
                    b = [b === "id" ? 0 : 1, b];
                    return a < b ? -1 : a > b ? 1 : 0;
                });
            });
        }
        if (this.isLeaf) acc.push(node);
    });
    
    assert.equal(
        acc.join(' '),
        '9 30 22',
        'Traversal in a custom order'
    );
};
Example #22
0
 deleted.forEach(function (key, ix) {
     if (indent && opts.comment) {
         unset('deleted');
         set('comment');
         write('// ');
         unset('comment');
         set('deleted');
     }
     
     plainStringify(key);
     write(indent ? ' : ' : ':');
     traverse(prevNode[key]).forEach(function (x) {
         plainStringify.call(this, x, { indent : 0 });
     });
     
     var last = ix === deleted.length - 1;
     if (insertable && !last) {
         if (indent && commaFirst) {
             write('\n' + indentx + ', ');
         }
         else if (indent) {
             write(',\n' + indentx);
         }
         else write(',');
     }
 });
Example #23
0
exports.stringify = function (assert) {
    var obj = [ 5, 6, -3, [ 7, 8, -2, 1 ], { f : 10, g : -13 } ];
    
    var s = '';
    Traverse(obj).forEach(function (node) {
        if (Array.isArray(node)) {
            this.before(function () { s += '[' });
            this.post(function (child) {
                if (!child.isLast) s += ',';
            });
            this.after(function () { s += ']' });
        }
        else if (typeof node == 'object') {
            this.before(function () { s += '{' });
            this.pre(function (x, key) {
                s += '"' + key + '"' + ':';
            });
            this.post(function (child) {
                if (!child.isLast) s += ',';
            });
            this.after(function () { s += '}' });
        }
        else if (typeof node == 'function') {
            s += 'null';
        }
        else {
            s += node.toString();
        }
    });
    
    assert.equal(s, JSON.stringify(obj));
}
Example #24
0
module.exports.mergeResults = function(resultSet) {
  var numSets = resultSet.length;

  var fixPercentage = ["Accuracy", "macroPrecision", "macroRecall", "macroF1", "microPrecision",
  "microRecall", "microF1", "HammingLoss", "HammingGain", "Recall", "Precision", "F1" ]

  var object = {};
  var customizer = function(val1, val2) {
    if (_.isNumber(val1) && _.isNumber(val2)) {
      return val1 + val2;
    }
    if (lo.isPlainObject(val1) && lo.isPlainObject(val2)) {
      return lo.mergeWith(val1, val2, customizer);
    }
  }
  for (var i = 0; i < resultSet.length; i++) {
    object = lo.mergeWith(object, resultSet[i], customizer);
  }
  
  traverse(object).forEach(function (value) {
    if (fixPercentage.indexOf(this.key) !== -1) {
      this.update(+((value / numSets).toFixed(3)));
    }
  });

  return object;
}
Example #25
0
    saw.chain = function () {
        var ch = traverse(saw.handlers).map(function (node) {
            if (this.isRoot) return node;
            // Path is method name.
            var ps = this.path;

            if (typeof node === 'function') {
                this.update(function () {
                    saw.actions.push({
                        // Method name.
                        path : ps,
                        // Arguments passed.
                        args : [].slice.call(arguments)
                    });
                    return ch;
                });
            }
        });

        process.nextTick(function () {
            saw.emit('begin');
            saw.next();
        });

        return ch;
    };
Example #26
0
  _convert.prototype.convertToCommon = function(content){
    var code = esprima.parse(content, this.parseOptions);
    // Filter the nodes to find all AMD style defines
    var amdNodes = traverse(code).reduce(function(memo, node){
      var amdNode = new AMDNode(node);
      if(amdNode.isAMDStyle()){
        memo.push(amdNode);
      }
      return memo;
    }, []);

    // For now, let's operate with a 1 per file assumption.
    var validNode = _.first(amdNodes);
    if(!validNode){
      return content;
    }

    var withRequire = requireConverter(content, validNode);

    // Do a second pass of the code now that we've rewritten it
    var secondPassNode = esprima.parse(withRequire, this.parseOptions);
    var withExport = exportConverter(withRequire, secondPassNode);

    var thirdPassNode = esprima.parse(withExport, this.parseOptions);
    return strictConverter(withExport, thirdPassNode);
  };
var removeNullUndefinedProperties = function(obj) {
    return traverse(obj).map(function() {
        if (this.node == null) {
            this.delete();
        }
    });
}
Example #28
0
            res.on('end', function () {
                
                var resXml = domParser.parseFromString(xml);
                var fault = xpath.select(faultTextXpath, resXml);
              
                if (fault.length > 0)  return cb(new Error(fault.toString()));

                var data = xml;
                if (settings.returnJson) {
                    var jsondata = JSON.parse( parser.toJson(xml) );
                    var prefixes = [];
                    //removes namespaces
                    var data_no_ns = traverse(jsondata).map(function(n){
                        if (this.key!=undefined) {
                            var pos = this.key.indexOf('xmlns:');
                            var k = this.key.substring(6, this.key.length) + ':';
                            if ( pos >-1 || this.key.indexOf('xmlns')>-1) {
                                if (prefixes.lastIndexOf(k)==-1) 
                                    prefixes.push(k);                                 
                                this.remove();
                            };
                        };
                    });

                    //removes 'xx:' prefixes
                    data = deepObjCopy(data_no_ns, prefixes);
                };
                
                cb(null,data);
            })
Example #29
0
 self.scrub = function (obj) {
     var paths = {};
     var links = [];
     
     var args = Traverse(obj).map(function (node) {
         if (typeof(node) == 'function') {
             var i = store.indexOf(node);
             if (i >= 0 && !(i in paths)) {
                 // Keep previous function IDs only for the first function
                 // found. This is somewhat suboptimal but the alternatives
                 // are worse.
                 paths[i] = this.path;
             }
             else {
                 var id = store.add(node);
                 paths[id] = this.path;
             }
             
             this.update('[Function]');
         }
         else if (this.circular) {
             links.push({ from : this.circular.path, to : this.path });
             this.update('[Circular]');
         }
     });
     
     return {
         arguments : args,
         callbacks : paths,
         links : links
     };
 };
Example #30
0
      this.toss.afterJSON(function(body) {

        traverse(values).forEach(function(x) {

          //testerInstance.expectEqual(body.sections[0].title, values);
        });
      });