Parses an extraction rule.

        @rule - Rule string.

        Returns an array of ['<case insensitive matching string>', '<file extension>', '<command to run>', '<comma separated return codes>', <recurse into extracted directories: True|False>].
516766
def _parse_rule(self, rule):
        '''
        
        '''
        values = rule.strip().split(self.RULE_DELIM, 4)

        if len(values) >= 4:
            codes = values[3].split(',')
            for i in range(0, len(codes)):
                try:
                    codes[i] = int(codes[i], 0)
                except ValueError as e:
                    binwalk.core.common.warning("The specified return code '%s' for extractor '%s' is not a valid number!" % (codes[i], values[0]))
            values[3] = codes

        if len(values) >= 5:
            values[4] = (values[4].lower() == 'true')

        return values
76821
def _parse_known_pattern(self, pattern: str) -> List[str]:
        
        if pattern.endswith(os.path.sep):
            patterns = [
                filename
                for filename in os.listdir(pattern)
                if os.path.isdir(os.path.join(pattern, filename))
            ]
        else:
            patterns = [pattern]

        return patterns
90188
function split( command ) {
    if ( typeof command !== 'string' ) {
        throw new Error( 'Command must be a string' );
    }

    var r = command.match( /[^"\s]+|"(?:\\"|[^"])*"/g );
    if ( ! r ) {
        return [];
    }

    return r.map( function ( expr ) {
        var isQuoted = expr.charAt( 0 ) === '"' && expr.charAt( expr.length - 1 ) === '"';
        return isQuoted ? expr.slice( 1, -1 ) : expr;
    } );
}
371602
def parse_rule(cls, txt):
        
        types = {"glob": GlobRule,
                 "regex": RegexRule,
                 "range": RangeRule,
                 "before": TimestampRule,
                 "after": TimestampRule}

        # parse form 'x(y)' into x, y
        label, txt = Rule._parse_label(txt)
        if label is None:
            if '*' in txt:
                label = "glob"
            else:
                label = "range"
        elif label not in types:
            raise ConfigurationError(
                "'%s' is not a valid package filter type" % label)

        rule_cls = types[label]
        txt_ = "%s(%s)" % (label, txt)

        try:
            rule = rule_cls._parse(txt_)
        except Exception as e:
            raise ConfigurationError("Error parsing package filter '%s': %s: %s"
                                     % (txt_, e.__class__.__name__, str(e)))
        return rule
1178795
protected function parse_string_rules( $rules ) {
		$split_rules = explode( '|', $rules );
		$parse_rules = [];

		foreach ( $split_rules as $rule ) {
			$parameters = [];

			// Format rule and parameters follows {rule}:{parameters}.
			if ( strpos( $rule, ':' ) !== false ) {
				list( $rule, $parameter ) = explode( ':', $rule, 2 );

				$parameter = false !== strpos( $parameter, ',' )
					? str_getcsv( $parameter )
					: [ $parameter ];

				$parameters = $this->wrap_parameters( $rule, $parameter );
			}

			$parse_rules[] = [ $this->normalize( $rule ), $parameters ];
		}

		return $parse_rules;
	}
184311
public List<RuleMatch> check(AnnotatedText annotatedText, boolean tokenizeText, ParagraphHandling paraMode, RuleMatchListener listener, Mode mode) throws IOException {
    List<String> sentences;
    if (tokenizeText) { 
      sentences = sentenceTokenize(annotatedText.getPlainText());
    } else {
      sentences = new ArrayList<>();
      sentences.add(annotatedText.getPlainText());
    }
    List<Rule> allRules = getAllRules();
    if (printStream != null) {
      printIfVerbose(allRules.size() + " rules activated for language " + language);
    }

    unknownWords = new HashSet<>();
    List<AnalyzedSentence> analyzedSentences = analyzeSentences(sentences);
    
    List<RuleMatch> ruleMatches = performCheck(analyzedSentences, sentences, allRules, paraMode, annotatedText, listener, mode);
    ruleMatches = new SameRuleGroupFilter().filter(ruleMatches);
    // no sorting: SameRuleGroupFilter sorts rule matches already
    if (cleanOverlappingMatches) {
      ruleMatches = new CleanOverlappingFilter(language).filter(ruleMatches);
    }
    return ruleMatches;
  }
810127
def _parse(data: str) -> list:
        
        if isinstance(data, bytes):
            data = data.decode('utf-8')
        lines = (
            item for item in
            (item.strip() for item in data.split('\n'))
            if len(item) and not item.startswith('#')
        )
        rules = []
        for line in lines:
            rules.append(
                Rule.parse(line)
            )
        return rules
219150
def parse_pattern(s):
    """"""
    if '{' in s:
        return None, None  # Unsupported by fnmatch
    if s and s[0] == '~':
        s = os.path.expanduser(s)
    parts = s.split('/')
    absolute = len(parts) > 1 and not parts[0]
    if parts[-1] == '':  # # Outcome of trailing /
        parts = parts[:-1]  # discard
    if len(parts) == 0:
        directory = ''
        pattern = ''
    else:
        directory = '/'.join(parts[:-1])
        pattern = parts[-1]
    if not is_pattern(directory): # Check for e.g. /abc/*/def
        if is_pattern(pattern):
            if not directory:
                directory = '/' if absolute else '.'
            return directory, pattern
    return None, None
1076606
function _explodeRules(rules) {
    for (var i in rules) {
      if (is_string(rules[i])) {
        rules[i] = rules[i].split('|');
      }
    }
    return rules;
  }
886687
def get_rules_from_disk():
    '''  '''

    # Try to find the yara rules directory relative to the worker
    my_dir = os.path.dirname(os.path.realpath(__file__))
    yara_rule_path = os.path.join(my_dir, 'yara/rules')
    if not os.path.exists(yara_rule_path):
        raise RuntimeError('yara could not find yara rules directory under: %s' % my_dir)

    # Okay load in all the rules under the yara rule path
    rules = yara.load_rules(rules_rootpath=yara_rule_path, fast_match=True)

    return rules
366976
private void parseRule( Rule rule ) {
        ruleStack.add( rule );
        for( ;; ) {
            int ch = reader.nextBlockMarker();
            switch( ch ) {
                case -1:
                    throw createException( "Unexpected end of Less data" );
                case ';':
                    parseSemicolon( rule );
                    break;
                case '{':
                    parseBlock( rule );
                    break;
                case '}':
                    parseSemicolon( rule );
                    ruleStack.removeLast();
                    return;
                default:
                    throw createException( "Unrecognized input: '" + reader.getLookAhead() + "'" );
            }
        }

    }
868955
def parse_updates(rule):
    '''
    
    '''
    rules = shlex.split(rule)
    rules.pop(0)
    return {'url': rules[0]} if rules else True
381756
function extractRules(model, options) {
  // check if rules are passed manually
  if (options.rules) {
    return options.rules;
  }

  // check if Model class had rules defined statically
  if (
    !model ||
    !model.__proto__ ||
    !model.__proto__.constructor ||
    !model.__proto__.constructor.validationRules
  ) {
    return [];
  }

  const rules = model.__proto__.constructor.validationRules;

  // rules not defined properly
  if (!Array.isArray(rules)) {
    throw Error(`Validation rules not defined correctly in Model`);
  }

  return rules;
}
83893
def parse(self, text):
        
        gen = self.lexer.lex(text)
        next_val_fn = partial(next, *(gen,))

        commands = []
        token = next_val_fn()
        while token[0] is not EOF:
            command, token = self.rule_svg_transform(next_val_fn, token)
            commands.append(command)
        return commands
976394
@NotNull
  List<RuleMatch> getFilteredExtensionMatches(List<RuleMatch> matches, List<RemoteRuleMatch> extensionMatches) {
    List<RuleMatch> filteredExtMatches = new ArrayList<>();
    for (RemoteRuleMatch extensionMatch : extensionMatches) {
      if (!extensionMatch.isTouchedByOneOf(matches)) {
        AnalyzedSentence sentence = new AnalyzedSentence(new AnalyzedTokenReadings[]{});
        HiddenRule hiddenRule = new HiddenRule(extensionMatch.getLocQualityIssueType().orElse(null), extensionMatch.estimatedContextForSureMatch());
        RuleMatch hiddenRuleMatch = new RuleMatch(hiddenRule, sentence, extensionMatch.getErrorOffset(),
                extensionMatch.getErrorOffset()+extensionMatch.getErrorLength(), "(hidden message)");
        filteredExtMatches.add(hiddenRuleMatch);
      }
    }
    return filteredExtMatches;
  }
460878
private List<RuleSource> readRulesDirectory(File rulesDirectory) throws MojoExecutionException {
        if (rulesDirectory.exists() && !rulesDirectory.isDirectory()) {
            throw new MojoExecutionException(rulesDirectory.getAbsolutePath() + " does not exist or is not a directory.");
        }
        getLog().info("Reading rules from directory " + rulesDirectory.getAbsolutePath());
        try {
            return FileRuleSource.getRuleSources(rulesDirectory);
        } catch (IOException e) {
            throw new MojoExecutionException("Cannot read rulesDirectory: " + rulesDirectory.getAbsolutePath(), e);
        }
    }
1041900
function _parseRule(rule) {
    var parameters = [];

    // The format for specifying validation rules and parameters follows an
    // easy {rule}:{parameters} formatting convention. For instance the
    // rule "Max:3" states that the value may only be three letters.
    if (rule.indexOf(':')) {
      var ruleInfo  = rule.split(':');
      parameters = _parseParameters(ruleInfo[0], ruleInfo[1]);
    }

    return { parameters: parameters, rule: ruleInfo[0]};
  }