Parser for dynamic code optimization state.
492693
function parseState(s) {
  switch (s) {
  case "": return Profile.CodeState.COMPILED;
  case "~": return Profile.CodeState.OPTIMIZABLE;
  case "*": return Profile.CodeState.OPTIMIZED;
  }
  throw new Error("unknown code state: " + s);
}
696053
def optimize(self, method="simplex", verbosity=False, tolerance=1e-9, **kwargs):
        """"""
        c = np.array([self.objective.get(name, 0) for name in self._variables])
        if self.direction == "max":
            c *= -1

        bounds = list(six.itervalues(self.bounds))
        solution = linprog(c, self.A, self.upper_bounds, bounds=bounds, method=method,
                           options={"maxiter": 10000, "disp": verbosity, "tol": tolerance}, **kwargs)
        self._solution = solution
        self._status = solution.status
        if SCIPY_STATUS[self._status] == interface.OPTIMAL:
            self._var_primals = solution.x
            self._slacks = solution.slack
        else:
            self._var_primals = None
            self._slacks = None

        self._f = solution.fun
726332
def parse(code="", mode="sys"):
    """"""
    if CLI.comp is None:
        setup()
    if mode in PARSERS:
        return PARSERS[mode](CLI.comp)(code)
    else:
        raise CoconutException(
            "invalid parse mode " + ascii(mode),
            extra="valid modes are " + ", ".join(PARSERS),
        )
227774
def _cached_search_compile(pattern, re_verbose, re_version, pattern_type):
    """"""

    return _bregex_parse._SearchParser(pattern, re_verbose, re_version).parse()
1109040
def canonicalize_spec(spec, parent_context):
  """"""

  test_specs = {k:v for (k,v) in spec.items() if k.startswith("Test")}
  local_context = {k:v for (k,v) in spec.items() if not k.startswith("Test")}

  context = reduce_contexts(parent_context, local_context)

  if test_specs:
    return {k: canonicalize_spec(v, context) for (k,v) in test_specs.items()}
  else:
    program_chunks = sum([resolve_module(m,context['Definitions']) for m in context['Modules']],[]) + [context['Program']]
    test_spec = {
      'Arguments': context['Arguments'],
      'Program': "\n".join(program_chunks),
      'Expect': context['Expect'],
    }
    return test_spec
1193097
def runcode(code):
	""""""
	for line in code:
		print('# '+line)
		exec(line,globals())
	print('# return ans')
	return ans
829658
function optimize (source, path, module)
  {
    var result = sourceTrans.optimize (source, module.name, options.moduleVar);
    var stat = sourceTrans.TRANS_STAT;
    switch (result.status) {

      case stat.OK:

        //----------------------------------------------------------
        // Module already enclosed in a closure with no arguments.
        //----------------------------------------------------------
        return /** @type {OperationResult} */ {
          status: STAT.INDENTED,
          data:   sourceTrans.renameModuleRefExps (module, options.indent + result.data, options.moduleVar)
        };


      case stat.NO_CLOSURE_FOUND:

        //----------------------------------------------------------
        // Unwrapped source code.
        // It must be validated to make sure it's safe.
        //----------------------------------------------------------
        if (path)
          verboseOut.write ('Validating ' + path.cyan + '...');
        var valid = sourceTrans.validateUnwrappedCode (source);
        if (valid)
        // The code passed validation.
          verboseOut.ok ();
        else {
          verboseOut.writeln ('FAILED'.yellow);
          warnAboutGlobalCode (valid, path);
          // If --force, continue.
        }
        // Either the code is valid or --force was used, so process it.
        return /** @type {OperationResult} */ {
          status: STAT.OK,
          data:   sourceTrans.renameModuleRefExps (module, source, options.moduleVar)
        };


      case stat.RENAME_REQUIRED:

        //----------------------------------------------------------
        // Module already enclosed in a closure, with its reference
        // passed in as the function's argument.
        //----------------------------------------------------------
        /** @type {ModuleClosureInfo} */
        var modInfo = result.data;
        if (!options.renameModuleRefs) {
          warn ('The module variable reference <cyan>%</cyan> doesn\'t match the preset name on the config setting ' +
            '<cyan>moduleVar=\'%\'</cyan>.%%%',
            modInfo.moduleVar, options.moduleVar, NL, reportErrorLocation (path),
            getExplanation ('Either rename the variable or enable <cyan>renameModuleRefs</cyan>.')
          );
          // If --force, continue.
        }
        return /** @type {OperationResult} */ {
          status: STAT.OK,
          data:   sourceTrans.renameModuleVariableRefs (modInfo.closureBody, modInfo.moduleVar, options.moduleVar)
        };


      case stat.INVALID_DECLARATION:

        warn ('Wrong module declaration: <cyan>%</cyan>', result.data);
        // If --force, continue.
        break;


      default:
        throw new Error ('Optimize failed. It returned ' + JSON.stringify (result));
    }
    // Optimization failed. Return the unaltered source code.
    return /** @type {OperationResult} */ {status: STAT.OK, data: source};
  }
419765
function updateSourceCode(code, changes) {
  // Summary:
  //  This must be called before code is changed some places else rather than ast

  changes.sort((c1, c2) => c2.start - c1.start);
  // Remove same or overlapped changes
  const newChanges = _.reduce(
    changes,
    (cleanChanges, curr) => {
      const last = _.last(cleanChanges);

      if (!cleanChanges.length || last.start > curr.end) {
        cleanChanges.push(curr);
      } else if (last.start === last.end && last.end === curr.start && curr.start === curr.end) {
        // insert code at the same position, merge them
        last.replacement += curr.replacement;
      }
      return cleanChanges;
    },
    [],
  );

  const chars = code.split('');
  newChanges.forEach(c => {
    // Special case: after the change, two empty lines occurs, should delete one line
    if (
      c.replacement === '' &&
      (c.start === 0 || chars[c.start - 1] === '\n') &&
      chars[c.end] === '\n'
    ) {
      c.end += 1;
    }
    chars.splice(c.start, c.end - c.start, c.replacement);
  });
  return chars.join('');
}
1152136
static function processStaticOptimizations( $useComments, $php, $tpl, &$node, &$resourceData, &$newNode )
    {
        $nodeType = $node[0];
        if ( $nodeType == eZTemplate::NODE_ROOT )
        {
            $children = $node[1];
            $newNode[0] = $nodeType;
            $newNode[1] = false;
            if ( $children )
            {
                $newNode[1] = array();
                foreach ( $children as $child )
                {
                    $newChild = array();
                    eZTemplateCompiler::processStaticOptimizations( $useComments, $php, $tpl, $child, $resourceData, $newChild );
                    $newNode[1][] = $newChild;
                }
            }
        }
        else if ( $nodeType == eZTemplate::NODE_TEXT )
        {
            $text = $node[2];
            $placement = $node[3];

            $newNode[0] = $nodeType;
            $newNode[1] = false;
            $newNode[2] = $text;
            $newNode[3] = $placement;
        }
        else if ( $nodeType == eZTemplate::NODE_VARIABLE )
        {
            $variableCustom = $node[1];
            $variableData = $node[2];
            $variablePlacement = $node[3];
            $dataInspection = eZTemplateCompiler::inspectVariableData( $tpl,
                                                                       $variableData, $variablePlacement,
                                                                       $resourceData );
            if ( isset( $dataInspection['new-data'] ) )
            {
                $variableData = $dataInspection['new-data'];
            }
            $newNode = $node;
            $newNode[1] = $variableCustom;
            $newNode[2] = $variableData;
            unset( $dataInspection );
        }
        else if ( $nodeType == eZTemplate::NODE_FUNCTION )
        {
            $functionChildren = $node[1];
            $functionName = $node[2];
            $functionParameters = $node[3];
            $functionPlacement = $node[4];

            $newFunctionChildren = array();
            if ( is_array( $functionChildren ) )
            {
                foreach ( $functionChildren as $functionChild )
                {
                    $newChild = array();
                    eZTemplateCompiler::processStaticOptimizations( $useComments, $php, $tpl,
                                                                        $functionChild, $resourceData, $newChild );
                    $newFunctionChildren[] = $newChild;
                }
                $functionChildren = $newFunctionChildren;
            }

            $newFunctionParameters = array();
            if ( $functionParameters )
            {
                foreach ( $functionParameters as $functionParameterName => $functionParameterData )
                {
                    $dataInspection = eZTemplateCompiler::inspectVariableData( $tpl,
                                                                                   $functionParameterData, false,
                                                                                   $resourceData );
                    if ( isset( $dataInspection['new-data'] ) )
                    {
                        $functionParameterData = $dataInspection['new-data'];
                    }
                    $newFunctionParameters[$functionParameterName] = $functionParameterData;
                }
                $functionParameters = $newFunctionParameters;
            }

            $newNode[0] = $nodeType;
            $newNode[1] = $functionChildren;
            $newNode[2] = $functionName;
            $newNode[3] = $functionParameters;
            $newNode[4] = $functionPlacement;
            if ( isset( $node[5] ) )
                $newNode[5] = $node[5];
        }
        else
            $newNode = $node;
    }
1168968
def parser_from_buffer(cls, fp):
        """"""
        yaml = YAML(typ="safe")
        return cls(yaml.load(fp))
399992
def _cached_replace_compile(pattern, repl, flags, pattern_type):
    """"""

    return _bregex_parse._ReplaceParser().parse(pattern, repl, bool(flags & FORMAT))
973952
function Parser(options) {
  this.options = merge({}, {
    headers: {
      included: false,
      downcase: true,
      upcase: true
    },
    delimiter: 'tab',
    decimalSign: 'comma'
  }, options);
}
342179
def cpp_spec():
    """"""
    return {
        INDENTATION    : '\t',
        BEG_BLOCK      : '{',
        END_BLOCK      : '}',
        BEG_LINE       : '',
        END_LINE       : '\n',
        BEG_ACTION     : '',
        END_ACTION     : ';',
        BEG_CONDITION  : 'if(',
        END_CONDITION  : ')',
        LOGICAL_AND    : ' && ',
        LOGICAL_OR     : ' || '
    }
1340794
def _exprparser(
        expr, scope, lang=None, conf=None, configurable=None,
        safe=DEFAULT_SAFE, besteffort=DEFAULT_BESTEFFORT, tostr=False
):
    """"""

    if scope is None:
        scope = {}

    scope.update({
        'configurable': configurable,
        'conf': conf
    })

    expr = REGEX_EXPR_R.sub(
        _refrepl(
            configurable=configurable, conf=conf, safe=safe, scope=scope,
            besteffort=besteffort
        ), expr
    )

    result = resolve(
        expr=expr, name=lang, safe=safe, scope=scope, tostr=tostr,
        besteffort=besteffort
    )

    return result
1044255
def _parse_cfg_linters(self):
        """"""
        user_value = self._config.get('linters', '')
        # For each line of "linters" value, use comma as separator
        for line in user_value.splitlines():
            yield from self._parse_linters_line(line)
220085
def tokenize(code):
    """"""
    tok_regex = '|'.join('(?P<{}>{})'.format(*pair) for pair in _tokens)
    tok_regex = re.compile(tok_regex, re.IGNORECASE|re.M)
    line_num = 1
    line_start = 0
    for mo in re.finditer(tok_regex, code):
        kind = mo.lastgroup
        value = mo.group(kind)
        if kind == 'NEWLINE':
            line_start = mo.end()
            line_num += 1
        elif kind == 'SKIP' or value=='':
            pass
        else:
            column = mo.start() - line_start
            yield Token(kind, value, line_num, column)
522265
def parser(self):
        """"""
        parser = configparser.RawConfigParser()
        for filename in self.available_files:
            friendly_name = format_path(filename)
            logger.debug("Loading configuration file: %s", friendly_name)
            loaded_files = parser.read(filename)
            if len(loaded_files) == 0:
                self.report_issue("Failed to load configuration file! (%s)", friendly_name)
        logger.debug("Loaded %s from %s.",
                     pluralize(len(parser.sections()), "section"),
                     pluralize(len(self.available_files), "configuration file"))
        return parser