Build a pattern for the given descriptor in the current
context and using the given utils object
346240
public RuleConditionElement build(RuleBuildContext context,
                                      PatternDescr patternDescr,
                                      Pattern prefixPattern) {
        if (patternDescr.getObjectType() == null) {
            lookupObjectType(context, patternDescr);
        }

        if (patternDescr.getObjectType() == null || patternDescr.getObjectType().equals("")) {
            registerDescrBuildError(context, patternDescr, "ObjectType not correctly defined");
            return null;
        }

        ObjectType objectType = getObjectType(context, patternDescr);
        if (objectType == null) { // if the objectType doesn't exist it has to be query
            return buildQuery(context, patternDescr, patternDescr);
        }

        Pattern pattern = buildPattern(context, patternDescr, objectType);
        processClassObjectType(context, objectType, pattern);
        processAnnotations(context, patternDescr, pattern);
        processSource(context, patternDescr, pattern);
        processConstraintsAndBinds(context, patternDescr, pattern);
        processBehaviors(context, patternDescr, pattern);

        if (!pattern.hasNegativeConstraint() && "on".equals(System.getProperty("drools.negatable"))) {
            // this is a non-negative pattern, so we must inject the constraint
            pattern.addConstraint(new NegConstraint(false));
        }

        // poping the pattern
        context.getDeclarationResolver().popBuildStack();

        return pattern;
    }
557228
function define (File, utils) {
  const { debug, error, strong } = utils.cnsl;

  return class STYLUSFile extends File {
    /**
     * Constructor
     * @param {String} id
     * @param {String} filepath
     * @param {Object} options
     *  - {Object} caches
     *  - {Object} fileExtensions
     *  - {Function} fileFactory
     *  - {Object} globalAliases
     *  - {Array} npmModulepaths
     *  - {Object} pluginOptions
     *  - {Object} runtimeOptions
     */
    constructor (id, filepath, options) {
      super(id, filepath, options);

      this.workflows.writeable = WORKFLOW_WRITEABLE;
    }

    /**
     * Compile file contents
     * @param {Object} buildOptions
     *  - {Boolean} batch
     *  - {Boolean} bootstrap
     *  - {Boolean} boilerplate
     *  - {Boolean} browser
     *  - {Boolean} bundle
     *  - {Boolean} compress
     *  - {Array} ignoredFiles
     *  - {Boolean} helpers
     *  - {Boolean} watchOnly
     * @param {Function} fn(err)
     */
    compile (buildOptions, fn) {
      const style = stylus(this.content)
        .set('filename', this.relpath)
        // Gather all source directories
        .set('paths', this.options.fileCache.getDirs());

      if (this.hasMaps) style.set('sourcemap', { comment: false });
      if (this.options.pluginOptions.stylus) {
        for (const option in this.options.pluginOptions.stylus) {
          style.set(option, this.options.pluginOptions.stylus[option]);
        }
      }

      style.render((err, css) => {
        if (err) {
          if (!this.options.runtimeOptions.watch) return fn(err);
          error(err, 4, false);
        }

        this.setContent(css);
        if (style.sourcemap) this.setMap(style.sourcemap);
        debug(`compile: ${strong(this.relpath)}`, 4);
        fn();
      });
    }
  };
}
1211518
def Pattern(*pattern)
      (self.class)::B._clear_bindings!(caller_locations(1,1)[0].label)
      ::PatternMatching::PatternMatch.new(*pattern)
    end
479058
def pattern(head, *args, mode=1, wc_name=None, conditions=None, **kwargs) \
        -> Pattern:
    """'
    """
    if len(args) == 0:
        args = None
    if len(kwargs) == 0:
        kwargs = None
    return Pattern(head, args, kwargs, mode=mode, wc_name=wc_name,
                   conditions=conditions)
39650
def patterns(instance, options):
    
    if instance['type'] != 'indicator' or 'pattern' not in instance:
        return

    pattern = instance['pattern']
    if not isinstance(pattern, string_types):
        return  # This error already caught by schemas
    errors = pattern_validator(pattern)

    # Check pattern syntax
    if errors:
        for e in errors:
            yield PatternError(str(e), instance['id'])
        return

    type_format_re = re.compile(r'^\-?[a-z0-9]+(-[a-z0-9]+)*\-?$')
    property_format_re = re.compile(r'^[a-z0-9_]{3,250}$')

    p = Pattern(pattern)
    inspection = p.inspect().comparisons
    for objtype in inspection:
        # Check observable object types
        if objtype in enums.OBSERVABLE_TYPES:
            pass
        elif options.strict_types:
            yield PatternError("'%s' is not a valid STIX observable type"
                               % objtype, instance['id'])
        elif (not type_format_re.match(objtype) or
              len(objtype) < 3 or len(objtype) > 250):
            yield PatternError("'%s' is not a valid observable type name"
                               % objtype, instance['id'])
        elif (all(x not in options.disabled for x in ['all', 'format-checks', 'custom-prefix']) and
              not CUSTOM_TYPE_PREFIX_RE.match(objtype)):
            yield PatternError("Custom Observable Object type '%s' should start "
                               "with 'x-' followed by a source unique identifier "
                               "(like a domain name with dots replaced by "
                               "hyphens), a hyphen and then the name"
                               % objtype, instance['id'])
        elif (all(x not in options.disabled for x in ['all', 'format-checks', 'custom-prefix-lax']) and
              not CUSTOM_TYPE_LAX_PREFIX_RE.match(objtype)):
            yield PatternError("Custom Observable Object type '%s' should start "
                               "with 'x-'" % objtype, instance['id'])

        # Check observable object properties
        expression_list = inspection[objtype]
        for exp in expression_list:
            path = exp[0]
            # Get the property name without list index, dictionary key, or referenced object property
            prop = path[0]
            if objtype in enums.OBSERVABLE_PROPERTIES and prop in enums.OBSERVABLE_PROPERTIES[objtype]:
                continue
            elif options.strict_properties:
                yield PatternError("'%s' is not a valid property for '%s' objects"
                                   % (prop, objtype), instance['id'])
            elif not property_format_re.match(prop):
                yield PatternError("'%s' is not a valid observable property name"
                                   % prop, instance['id'])
            elif (all(x not in options.disabled for x in ['all', 'format-checks', 'custom-prefix']) and
                  not CUSTOM_PROPERTY_PREFIX_RE.match(prop)):
                yield PatternError("Cyber Observable Object custom property '%s' "
                                   "should start with 'x_' followed by a source "
                                   "unique identifier (like a domain name with "
                                   "dots replaced by underscores), an "
                                   "underscore and then the name"
                                   % prop, instance['id'])
            elif (all(x not in options.disabled for x in ['all', 'format-checks', 'custom-prefix-lax']) and
                  not CUSTOM_PROPERTY_LAX_PREFIX_RE.match(prop)):
                yield PatternError("Cyber Observable Object custom property '%s' "
                                   "should start with 'x_'" % prop, instance['id'])
358519
def AddDescriptor(cls, field_desc):
    """"""
    if not isinstance(field_desc, ProtoType):
      raise type_info.TypeValueError(
          "%s field '%s' should be of type ProtoType" %
          (cls.__name__, field_desc.name))

    # Ensure the field descriptor knows the class that owns it.
    field_desc.SetOwner(cls)

    # If the field is late bound we do not really add it to the descriptor set
    # yet. We must wait for the LateBindingPlaceHolder() to add it later.
    if field_desc.late_bound:
      # Keep track of unbound fields.
      cls.late_bound_type_infos[field_desc.name] = field_desc
      return

    # Ensure this field number is unique:
    if field_desc.field_number in cls.type_infos_by_field_number:
      raise type_info.TypeValueError(
          "Field number %s for field %s is not unique in %s" %
          (field_desc.field_number, field_desc.name, cls.__name__))

    # We store an index of the type info by tag values to speed up parsing.
    cls.type_infos_by_field_number[field_desc.field_number] = field_desc
    cls.type_infos_by_encoded_tag[field_desc.encoded_tag] = field_desc

    cls.type_infos.Append(field_desc)
    cls.late_bound_type_infos.pop(field_desc.name, None)

    # Add direct accessors only if the class does not already have them.
    if not hasattr(cls, field_desc.name):
      # This lambda is a class method so pylint: disable=protected-access
      # This is much faster than __setattr__/__getattr__
      setattr(
          cls, field_desc.name,
          property(lambda self: self.Get(field_desc.name), lambda self, x: self.
                   _Set(x, field_desc), None, field_desc.description))
925307
function(node, ufNameArr) {
			var context = this,
				out = {
					'root': [],
					'properties': []
				},
				classNames,
				key,
				items,
				item,
				i,
				x,
				z,
				y,
				map,
				prop,
				propName,
				v2Name,
				impiedRel,
				ufName;

			// don't get classes from excluded list of tags
			if(modules.domUtils.hasTagName(node, this.excludeTags) === false){

				// find classes for node
				classNames = modules.domUtils.getAttribute(node, 'class');
				if(classNames) {
					items = classNames.split(' ');
					x = 0;
					i = items.length;
					while(x < i) {

						item = modules.utils.trim(items[x]);

						// test for root prefix - v2
						if(modules.utils.startWith(item, context.rootPrefix) && modules.utils.isLowerCase(item)) {
							if(out.root.indexOf(item) === -1){
								out.root.push(item);
							}
							out.typeVersion = 'v2';
						}

						// test for property prefix - v2
						z = context.propertyPrefixes.length;
						while(z--) {
							if(modules.utils.startWith(item, context.propertyPrefixes[z]) && modules.utils.isLowerCase(item)) {
								out.properties.push([item,'v2']);
							}
						}

						// test for mapped root classnames v1
						for(key in modules.maps) {
							if(modules.maps.hasOwnProperty(key)) {
								// only add a root once
								if(modules.maps[key].root === item && out.root.indexOf(key) === -1) {
									// if root map has subTree set to true
									// test to see if we should create a property or root
									if(modules.maps[key].subTree) {
										out.properties.push(['p-' + modules.maps[key].root, 'v1']);
									} else {
										out.root.push(key);
										if(!out.typeVersion){
											out.typeVersion = 'v1';
										}
									}
								}
							}
						}


						// test for mapped property classnames v1
						if(ufNameArr){
							for (var a = 0; a < ufNameArr.length; a++) {
								ufName = ufNameArr[a];
								// get mapped property v1 microformat
								map = context.getMapping(ufName);
								if(map) {
									for(key in map.properties) {
										if (map.properties.hasOwnProperty(key)) {

											prop = map.properties[key];
											propName = (prop.map) ? prop.map : 'p-' + key;

											if(key === item) {
												if(prop.uf) {
													// loop all the classList make sure
													//   1. this property is a root
													//   2. that there is not already an equivalent v2 property i.e. url and u-url on the same element
													y = 0;
													while(y < i) {
														v2Name = context.getV2RootName(items[y]);
														// add new root
														if(prop.uf.indexOf(v2Name) > -1 && out.root.indexOf(v2Name) === -1) {
															out.root.push(v2Name);
															out.typeVersion = 'v1';
														}
														y++;
													}
													//only add property once
													if(out.properties.indexOf(propName) === -1) {
														out.properties.push([propName,'v1']);
													}
												} else {
													if(out.properties.indexOf(propName) === -1) {
														out.properties.push([propName,'v1']);
													}
												}
											}
										}

									}
								}
							}

						}

						x++;

					}
				}
			}


			// finds any alt rel=* mappings for a given node/microformat
			if(ufNameArr && this.findRelImpied){
				for (var b = 0; b < ufNameArr.length; b++) {
					ufName = ufNameArr[b];
					impiedRel = this.findRelImpied(node, ufName);
					if(impiedRel && out.properties.indexOf(impiedRel) === -1) {
						out.properties.push([impiedRel, 'v1']);
					}
				}
			}


			//if(out.root.length === 1 && out.properties.length === 1) {
			//	if(out.root[0].replace('h-','') === this.removePropPrefix(out.properties[0][0])) {
			//		out.typeVersion = 'v2';
			//	}
			//}

			return out;
		}
679690
function (object, descriptors) {
      for(var key in descriptors) {
        if (hasOwnProperty.call(descriptors, key)) {
          try {
            defineProperty(object, key, descriptors[key]);
          } catch(o_O) {
            if (window.console) {
              console.log(key + ' failed on object:', object, o_O.message);
            }
          }
        }
      }
    }
181226
async function infer(pattern, {basePath}={}) {
  const dataPackage = await Package.load({}, {basePath})
  const descriptor = await dataPackage.infer(pattern)
  return descriptor
}
439353
function createStamp(descriptor) {
    var1 = createFactory();

    var2 = descriptor[_staticDeepProperties];
    if (var2) merge(var1, var2);

    var2 = descriptor[_staticProperties];
    if (var2) assign(var1, var2);

    var2 = descriptor[_staticPropertyDescriptors];
    if (var2) defineProperties(var1, var2);

    var2 = isFunction(var1[_compose]) ? var1[_compose] : compose;
    assign(var1[_compose] = function() {
      return var2.apply(this, arguments);
    }, descriptor);

    return var1;
  }
1165833
function(context, descriptor, args) {
		var ok, condition = args[0],
			successTempl = args[1],
			failTempl = args[2];
		if (condition && condition.__interpolable__)
			ok = condition.output(context);
		else if (typeof condition === 'function')
			ok = condition.call(this, context);
		var sod = new SOD();
		if (ok)
			successTempl.toHTMLString(context, sod);
		else if (failTempl)
			failTempl.toHTMLString(context, sod);
		if (sod.children)
			descriptor.children += sod.children;
	}
77776
function define (File, utils) {
  const { callable } = utils;
  const { debug, error, strong } = utils.cnsl;
  const { regexpEscape, uniqueMatch } = utils.string;

  return class NUNJUCKSFile extends File {
    /**
     * Constructor
     * @param {String} id
     * @param {String} filepath
     * @param {Object} options
     *  - {Object} caches
     *  - {Object} fileExtensions
     *  - {Function} fileFactory
     *  - {Object} globalAliases
     *  - {Array} npmModulepaths
     *  - {Object} pluginOptions
     *  - {Object} runtimeOptions
     */
    constructor (id, filepath, options) {
      super(id, filepath, options);

      this.workflows.writeable = WORKFLOW_WRITEABLE;
    }

    /**
     * Parse file contents for dependency references
     * @param {Object} buildOptions
     *  - {Boolean} batch
     *  - {Boolean} bootstrap
     *  - {Boolean} boilerplate
     *  - {Boolean} browser
     *  - {Boolean} bundle
     *  - {Boolean} compress
     *  - {Array} ignoredFiles
     *  - {Boolean} helpers
     *  - {Boolean} watchOnly
     * @param {Function} fn(err)
     */
    parse (buildOptions, fn) {
      super.parse(buildOptions, (err) => {
        if (err) return fn(err);

        // Find sidecar json file
        const sidecarData = super.parseSidecarDependency();
        // Parse includes
        let matches = uniqueMatch(this.content, RE_INCLUDE)
          .map((match) => {
            match.id = match.match;
            match.isInclude = true;
            return match;
          });

        // Parse imports
        matches.push(...uniqueMatch(this.content, RE_IMPORT)
          .map((match) => {
            match.id = match.match;
            match.isImport = true;
            return match;
          }));
        if (sidecarData) matches.push(sidecarData);

        super.addDependencies(matches, buildOptions);
        fn();
      });
    }

    /**
     * Replace relative dependency references with fully resolved
     * @param {Object} buildOptions
     *  - {Boolean} batch
     *  - {Boolean} bootstrap
     *  - {Boolean} boilerplate
     *  - {Boolean} browser
     *  - {Boolean} bundle
     *  - {Boolean} compress
     *  - {Boolean} helpers
     *  - {Array} ignoredFiles
     *  - {Boolean} import
     *  - {Boolean} watchOnly
     * @param {Function} fn(err)
     */
    replaceReferences (buildOptions, fn) {
      [...this.getAllDependencies(), this].forEach((file) => {
        if (file instanceof NUNJUCKSFile && this.dependencyReferences.length) {
          let content = file.content;

          file.dependencyReferences.forEach((reference) => {
            if (reference.file && reference.isImport) {
              const context = reference.context.replace(reference.id, reference.file.filepath);

              // Create new RegExp so that flags work properly
              content = content.replace(new RegExp(regexpEscape(reference.context), 'g'), context);
            }
          });

          file.setContent(content);
        }
      });
      fn();
    }

    /**
     * Inline css/img/js dependency content
     * @param {Object} buildOptions
     *  - {Boolean} batch
     *  - {Boolean} bootstrap
     *  - {Boolean} boilerplate
     *  - {Boolean} browser
     *  - {Boolean} bundle
     *  - {Boolean} compress
     *  - {Boolean} helpers
     *  - {Array} ignoredFiles
     *  - {Boolean} import
     *  - {Boolean} watchOnly
     * @param {Function} fn(err)
     */
    inlineInlineable (buildOptions, fn) {
      // Only dependencies
      parallel([...this.getAllDependencies()].reduce((inlineable, file) => {
        if (file instanceof NUNJUCKSFile && this.dependencyReferences.length) {
          inlineable.push(callable(file, 'inline', buildOptions));
        }
        return inlineable;
      }, []), fn);
    }

    /**
     * Inline included content
     * @param {Object} buildOptions
     *  - {Boolean} batch
     *  - {Boolean} bootstrap
     *  - {Boolean} boilerplate
     *  - {Boolean} browser
     *  - {Boolean} bundle
     *  - {Boolean} compress
     *  - {Boolean} helpers
     *  - {Array} ignoredFiles
     *  - {Boolean} import
     *  - {Boolean} watchOnly
     * @param {Function} fn(err)
     */
    inlineIncludes (buildOptions, fn) {
      [...this.getAllDependencies(), this].forEach((file) => {
        if (file instanceof NUNJUCKSFile && file.dependencyReferences.length) {
          let content = file.content;

          file.dependencyReferences.forEach((reference) => {
            if (reference.file && reference.context && reference.isInclude) {
              content = content.replace(new RegExp(regexpEscape(reference.context), 'g'), reference.file.content);
            }
          });

          file.setContent(content);
        }
      });
      fn();
    }

    /**
     * Compile file contents
     * @param {Object} buildOptions
     *  - {Boolean} batch
     *  - {Boolean} bootstrap
     *  - {Boolean} boilerplate
     *  - {Boolean} browser
     *  - {Boolean} bundle
     *  - {Boolean} compress
     *  - {Array} ignoredFiles
     *  - {Boolean} helpers
     *  - {Boolean} watchOnly
     * @param {Function} fn(err)
     */
    compile (buildOptions, fn) {
      const options = Object.assign({}, DEFAULT_OPTIONS, this.options.pluginOptions.nunjucks);

      nunjucks.configure(null, options);
      nunjucks.renderString(this.content, this.findSidecarDependency(), (err, content) => {
        if (err) {
          if (!this.options.runtimeOptions.watch) return fn(err);
          error(err, 4, false);
        }
        this.setContent(content);
        debug(`compile: ${strong(this.relpath)}`, 4);
        fn();
      });
    }

    /**
     * Reparse file contents for dependency references
     * @param {Object} buildOptions
     *  - {Boolean} batch
     *  - {Boolean} bootstrap
     *  - {Boolean} boilerplate
     *  - {Boolean} browser
     *  - {Boolean} bundle
     *  - {Boolean} compress
     *  - {Array} ignoredFiles
     *  - {Boolean} helpers
     *  - {Boolean} watchOnly
     * @param {Function} fn(err)
     */
    reparse (buildOptions, fn) {
      this.allDependencies = null;
      this.allDependencyReferences = null;
      this.dependencies = [];
      this.dependencyReferences = [];

      super.parse(buildOptions, fn);
    }
  };
}
1247293
def build_string(self, *pattern, **kwargs):
        
        set_defaults(self._string_defaults, kwargs)
        set_defaults(self._defaults, kwargs)
        return StringPattern(*pattern, **kwargs)
433209
def utils(opts, whitelist=None, context=None, proxy=proxy):
    '''
    
    '''
    return LazyLoader(
        _module_dirs(opts, 'utils', ext_type_dirs='utils_dirs'),
        opts,
        tag='utils',
        whitelist=whitelist,
        pack={'__context__': context, '__proxy__': proxy or {}},
    )
172271
def build_import_pattern(mapping1, mapping2):
    
    """
    # py3k: urllib.request, py2k: ('urllib2', 'urllib')
    yield from_import % (all_modules_subpattern())
    for py3k, py2k in mapping1.items():
        name, attr = py3k.split(u'.')
        s_name = simple_name % (name)
        s_attr = simple_attr % (attr)
        d_name = dotted_name % (s_name, s_attr)
        yield name_import % (d_name)
        yield power_twoname % (s_name, s_attr)
        if attr == u'__init__':
            yield name_import % (s_name)
            yield power_onename % (s_name)
        yield name_import_rename % (d_name)
        yield from_import_rename % (s_name, s_attr, s_attr, s_attr, s_attr)
884050
function createFactory(descriptor) {
  return function Stamp(options = {}, ...args) {
    // The 'methods' metadata object becomes the prototype for new object instances.
    const instance = Object.create(descriptor.methods || {});

    // Deep merge, then override with shallow merged properties, then apply property descriptors.
    merge(instance, descriptor.deepProperties);
    assign(instance, descriptor.properties);
    Object.defineProperties(instance, descriptor.propertyDescriptors || {});

    // Run initializers sequentially.
    return (descriptor.initializers || [])
      .filter(isFunction)
      .reduce((resultingInstance, initializer) => {
        // Invoke an initializer in the way specification tell us to.
        const returnedValue = initializer.call(
          // 'this' context will be the object instance itself
          resultingInstance,
          // the first argument passed from factory to initializer
          options,
          // special arguments. See specification.
          {instance: resultingInstance, stamp: Stamp, args: [options].concat(args)}
        );

        // Any initializer can override the object instance with basically anything.
        return returnedValue === undefined ? resultingInstance : returnedValue;
      }, instance);
  };
}
1193902
function(context, descriptor, args, stack) {
		var name = args[0],
			template = args[1],
			newDescriptor = new SOD();
		if (template)
			secondPass(template, context, newDescriptor, stack);
		utils.tagOutput(descriptor, newDescriptor, name);
	}