A helper function used just to help modularize the code a bit.
197096
def _configure_backend(app):
    """"""
    # Allocate the backend
    # We use URLs to specify the backend. Currently we have file:// URLs (or
    # URLs with no scheme) for the SqlDataRepository, and special empty:// and
    # simulated:// URLs for empty or simulated data sources.
    dataSource = urlparse.urlparse(app.config["DATA_SOURCE"], "file")

    if dataSource.scheme == "simulated":
        # Ignore the query string
        randomSeed = app.config["SIMULATED_BACKEND_RANDOM_SEED"]
        numCalls = app.config["SIMULATED_BACKEND_NUM_CALLS"]
        variantDensity = app.config["SIMULATED_BACKEND_VARIANT_DENSITY"]
        numVariantSets = app.config["SIMULATED_BACKEND_NUM_VARIANT_SETS"]
        numReferenceSets = app.config[
            "SIMULATED_BACKEND_NUM_REFERENCE_SETS"]
        numReferencesPerReferenceSet = app.config[
            "SIMULATED_BACKEND_NUM_REFERENCES_PER_REFERENCE_SET"]
        numAlignmentsPerReadGroup = app.config[
            "SIMULATED_BACKEND_NUM_ALIGNMENTS_PER_READ_GROUP"]
        numReadGroupsPerReadGroupSet = app.config[
            "SIMULATED_BACKEND_NUM_READ_GROUPS_PER_READ_GROUP_SET"]
        numPhenotypeAssociations = app.config[
            "SIMULATED_BACKEND_NUM_PHENOTYPE_ASSOCIATIONS"]
        numPhenotypeAssociationSets = app.config[
            "SIMULATED_BACKEND_NUM_PHENOTYPE_ASSOCIATION_SETS"]
        numRnaQuantSets = app.config[
            "SIMULATED_BACKEND_NUM_RNA_QUANTIFICATION_SETS"]
        numExpressionLevels = app.config[
            "SIMULATED_BACKEND_NUM_EXPRESSION_LEVELS_PER_RNA_QUANT_SET"]

        dataRepository = datarepo.SimulatedDataRepository(
            randomSeed=randomSeed, numCalls=numCalls,
            variantDensity=variantDensity, numVariantSets=numVariantSets,
            numReferenceSets=numReferenceSets,
            numReferencesPerReferenceSet=numReferencesPerReferenceSet,
            numReadGroupsPerReadGroupSet=numReadGroupsPerReadGroupSet,
            numAlignments=numAlignmentsPerReadGroup,
            numPhenotypeAssociations=numPhenotypeAssociations,
            numPhenotypeAssociationSets=numPhenotypeAssociationSets,
            numRnaQuantSets=numRnaQuantSets,
            numExpressionLevels=numExpressionLevels)
    elif dataSource.scheme == "empty":
        dataRepository = datarepo.EmptyDataRepository()
    elif dataSource.scheme == "file":
        path = os.path.join(dataSource.netloc, dataSource.path)
        dataRepository = datarepo.SqlDataRepository(path)
        dataRepository.open(datarepo.MODE_READ)
    else:
        raise exceptions.ConfigurationException(
            "Unsupported data source scheme: " + dataSource.scheme)
    theBackend = backend.Backend(dataRepository)
    theBackend.setRequestValidation(app.config["REQUEST_VALIDATION"])
    theBackend.setDefaultPageSize(app.config["DEFAULT_PAGE_SIZE"])
    theBackend.setMaxResponseLength(app.config["MAX_RESPONSE_LENGTH"])
    return theBackend
640977
def refine(pm, node, optimizations):
    
    # Sanitize input
    pm.apply(ExpandGlobals, node)
    pm.apply(ExpandImportAll, node)
    pm.apply(NormalizeTuples, node)
    pm.apply(ExpandBuiltins, node)
    pm.apply(ExpandImports, node)
    pm.apply(NormalizeMethodCalls, node)
    pm.apply(NormalizeIsNone, node)
    pm.apply(SplitStaticExpression, node)
    pm.apply(NormalizeStaticIf, node)
    pm.apply(NormalizeTuples, node)
    pm.apply(NormalizeException, node)
    pm.apply(NormalizeMethodCalls, node)

    # Some early optimizations
    pm.apply(ComprehensionPatterns, node)

    pm.apply(RemoveLambdas, node)
    pm.apply(RemoveNestedFunctions, node)
    pm.apply(NormalizeCompare, node)

    pm.gather(ExtendedSyntaxCheck, node)

    pm.apply(ListCompToGenexp, node)
    pm.apply(RemoveComprehension, node)
    pm.apply(RemoveNamedArguments, node)

    # sanitize input
    pm.apply(NormalizeReturn, node)
    pm.apply(UnshadowParameters, node)
    pm.apply(FalsePolymorphism, node)

    # some extra optimizations
    apply_optimisation = True
    while apply_optimisation:
        apply_optimisation = False
        for optimization in optimizations:
            apply_optimisation |= pm.apply(optimization, node)[0]
112663
def normalize_rust_function(self, function, line):
        """"""
        # Drop the prefix and return type if there is any
        function = drop_prefix_and_return_type(function)

        # Collapse types
        function = collapse(
            function,
            open_string='<',
            close_string='>',
            replacement='<T>',
            exceptions=(' as ',)
        )

        # Collapse arguments
        if self.collapse_arguments:
            function = collapse(
                function,
                open_string='(',
                close_string=')',
                replacement=''
            )

        if self.signatures_with_line_numbers_re.match(function):
            function = '{}:{}'.format(function, line)

        # Remove spaces before all stars, ampersands, and commas
        function = self.fixup_space.sub('', function)

        # Ensure a space after commas
        function = self.fixup_comma.sub(', ', function)

        # Remove rust-generated uniqueness hashes
        function = self.fixup_hash.sub('', function)

        return function
148694
function compile(
  source,
  filename = '',
  includeModule = false,
  debugMode = false,
) {
  let res
  let resName
  let errors

  try {
    const [moduleName, bsCode, diagnosticErrors] = Retyped.compile(filename, source, debugMode)
    const fmtCode = format(bsCode)
    res = fmtCode
    resName = moduleName
    errors = diagnosticErrors
  } catch (e) {
    console.error(e)
    throw new Error(`${e[0][0]}`)
  }

  if (res.includes('SYNTAX ERROR>')) {
    throw new Error(res)
  }

  if (!includeModule) {
    return res
  } else {
    return {
      moduleName: resName,
      bsCode: res,
      diagnosticErrors: errors
    }
  }
}
209821
function multMod_(x, y, n) {
  var i;
  if (s0.length!=2*x.length)
    s0=new Array(2*x.length);
  copyInt_(s0, 0);
  for (i=0; i<y.length; i++)
    if (y[i])
      linCombShift_(s0, x, y[i], i);   //s0=1*s0+y[i]*(x<<(i*bpe))
  mod_(s0, n);
  copy_(x, s0);
}
711203
def opcode(*opcodes):
    """"""
    def decorator(func):
        setattr(func, "_is_opcode", True)
        setattr(func, "_opcodes", opcodes)
        return func
    return decorator
519748
void maybeAddFunction(Function fn, JSModule module) {
    String name = fn.getName();
    FunctionState functionState = getOrCreateFunctionState(name);

    // TODO(johnlenz): Maybe "smarten" FunctionState by adding this logic to it?

    // If the function has multiple definitions, don't inline it.
    if (functionState.hasExistingFunctionDefinition()) {
      functionState.disallowInlining();
      return;
    }
    Node fnNode = fn.getFunctionNode();

    if (hasNoInlineAnnotation(fnNode)) {
      functionState.disallowInlining();
      return;
    }

    if (enforceMaxSizeAfterInlining
        && !isAlwaysInlinable(fnNode)
        && maxSizeAfterInlining <= NodeUtil.countAstSizeUpToLimit(fnNode, maxSizeAfterInlining)) {
      functionState.disallowInlining();
      return;
    }

    // verify the function hasn't already been marked as "don't inline"
    if (functionState.canInline()) {
      // store it for use when inlining.
      functionState.setFn(fn);
      if (FunctionInjector.isDirectCallNodeReplacementPossible(fn.getFunctionNode())) {
        functionState.inlineDirectly(true);
      }

      if (hasNonInlinableParam(NodeUtil.getFunctionParameters(fnNode))) {
        functionState.disallowInlining();
      }

      // verify the function meets all the requirements.
      // TODO(johnlenz): Minimum requirement checks are about 5% of the
      // run-time cost of this pass.
      if (!isCandidateFunction(fn)) {
        // It doesn't meet the requirements.
        functionState.disallowInlining();
      }

      // Set the module and gather names that need temporaries.
      if (functionState.canInline()) {
        functionState.setModule(module);

        Set<String> namesToAlias = FunctionArgumentInjector.findModifiedParameters(fnNode);
        if (!namesToAlias.isEmpty()) {
          functionState.inlineDirectly(false);
          functionState.setNamesToAlias(namesToAlias);
        }

        Node block = NodeUtil.getFunctionBody(fnNode);
        if (NodeUtil.referencesThis(block)) {
          functionState.setReferencesThis(true);
        }

        if (NodeUtil.containsFunction(block)) {
          functionState.setHasInnerFunctions(true);
          // If there are inner functions, we can inline into global scope
          // if there are no local vars or named functions.
          // TODO(johnlenz): this can be improved by looking at the possible
          // values for locals.  If there are simple values, or constants
          // we could still inline.
          if (!assumeMinimumCapture && hasLocalNames(fnNode)) {
            functionState.disallowInlining();
          }
        }

      }

      if (fnNode.getGrandparent().isVar()) {
        Node block = functionState.getFn().getDeclaringBlock();
        if (block.isBlock()
            && !block.getParent().isFunction()
            && (NodeUtil.containsType(block, Token.LET)
                || NodeUtil.containsType(block, Token.CONST))) {
          // The function might capture a variable that's not in scope at the call site,
          // so don't inline.
          functionState.disallowInlining();
        }
      }

      if (fnNode.isGeneratorFunction()) {
        functionState.disallowInlining();
      }

      if (fnNode.isAsyncFunction()) {
        functionState.disallowInlining();
      }
    }
  }
338928
def modsplit(s):
    """"""
    if ':' in s:
        c = s.split(':')
        if len(c) != 2:
            raise ValueError("Syntax error: {s}")
        return c[0], c[1]
    else:
        c = s.split('.')
        if len(c) < 2:
            raise ValueError("Syntax error: {s}")
        return '.'.join(c[:-1]), c[-1]
132294
def synthesize(self, modules, use_string, x64, native):
        """"""
        # code_opts = CodeOpts(
        #     str.lower, None if use_string else hash_func,
        #     'reloc_delta', '->',
        #     True)
        # gen_opts = GenOpts('defs', transformed)
        print(hash_func)
        groups = group_by(modules, ends_with_punctuation)
        sources = self.make_source(groups, self.database)
        if sources:
            return stylify_files(
                {'defs.h': sources[0], 'init.c': sources[1]}
            )
        else:
            return ''
689657
def preprocessor(accepts, exports, flag=None):
    """"""
    def decorator(f):
        preprocessors.append((accepts, exports, flag, f))
        return f
    return decorator
868876
def _simplify_function(self):
        

        # Computing reaching definitions
        rd = self.project.analyses.ReachingDefinitions(func=self.function, func_graph=self.graph, observe_all=True)

        simp = self.project.analyses.AILSimplifier(self.function, func_graph=self.graph, reaching_definitions=rd)

        for key in list(self._blocks.keys()):
            old_block = self._blocks[key]
            if old_block in simp.blocks:
                self._blocks[key] = simp.blocks[old_block]

        self._update_graph()
977588
function createModifierFunction (modifier) {
  return function (obj, field, value) {
    var fieldParts = typeof field === 'string' ? field.split('.') : field;

    if (fieldParts.length === 1) {
      lastStepModifierFunctions[modifier](obj, field, value);
    } else {
      if (obj[fieldParts[0]] === undefined) {
        if (modifier === '$unset') { return; }   // Bad looking specific fix, needs to be generalized modifiers that behave like $unset are implemented
        obj[fieldParts[0]] = {};
      }
      modifierFunctions[modifier](obj[fieldParts[0]], fieldParts.slice(1), value);
    }
  };
}
1214952
function clean(code) {

    try {
        const ast = babylon.parse(code, {
            // parse in strict mode and allow module declarations
            sourceType: 'module',
            plugins: [
                // enable jsx and flow syntax
                'jsx',
                'flow'
            ]
        });

        const cleanAst = strip(ast).program;

        const resultCode = generate(cleanAst, {}).code;

        return resultCode.replace(/(\/\*\$ | \#\*\/)/g, '');

    } catch (e) {
        console.log(code);
        throw e;
    }
}
623312
function replaceDefine(code) {
    var defineList = getDefineBlock(code);
    var segments = [];
    var index = 0;
    defineList.forEach(function (block) {

        if (block.type === 'function') {
            segments.push(code.slice(index, block.defineRange[0]));
            index = block.factoryRange[0] + 1;

            block.returnRange.forEach(function (range) {
                segments.push(code.slice(index, range[0]));
                segments.push('module.exports =');
                segments.push(code.slice(range[0] + 6, range[1]));
                index = range[1];
            });
            segments.push(code.slice(index, block.factoryRange[1] - 1));

            index = block.defineRange[1];
        }
        else if (block.type === 'object') {
            segments.push(code.slice(index, block.defineRange[0]));
            segments.push('module.exports = ');
            segments.push(code.slice(block.factoryRange[0], block.factoryRange[1]) + ';');
            index = block.defineRange[1];
        }
    });

    segments.push(code.slice(index));

    code = segments.join('');

    return code;
}
1282447
function makeShimNode(main) {
	return {
		bundles: [main],
		dependencies: ["@loader"],
		deps: ["@loader"],
		load: {
			address: "",
			metadata: {
				format: "amd",
				deps: ["@loader"],
				dependencies: ["@loader"]
			},
			name: "@steal",
			source: `
				define("@steal", ["@loader"], function(atLoader) {
					var steal = {};

					steal.loader = atLoader;
					steal.done = function() {
						return Promise.resolve();
					};

					return steal;
				});
			`
		}
	};
}
442585
def _parse_decorated_functions(self, code):
        """"""
        matches = re.finditer(r"""
                # @rest decorators
                (?P<decorators>
                    (?:@rest\(.+?\)\n)+  # one or more @rest decorators inside
                )
                # docstring delimited by 3 double quotes
                .+?"{3}(?P<docstring>.+?)"{3}
                """, code, re.VERBOSE | re.DOTALL)

        for function_match in matches:
            m_dict = function_match.groupdict()
            self._parse_docstring(m_dict['docstring'])
            self._add_function_paths(m_dict['decorators'])
216107
function(parser, expr) {
    var mod = parser.evaluateExpression(expr.arguments[0]);
    var deps = parser.evaluateExpression(expr.arguments[1]);
    this._addModuleDefinition(parser, expr, mod);
    if( deps.items ){
      return deps.items.every(
        this._addDependency.bind(this, parser, expr));
    }
    return this._addDependency(parser, expr, mod);
  }