Example::

            .. code-block:: python

                from __future__ import print_function
                import math

                print(math.sqrt(10.0))
431872
def code_block(self, code, language, indent=0):
        
        if language not in [None, "console", "python", "ruby", "c"]:
            raise
        prefix = "\t" * indent
        code_prefix = "\t" * (indent + 1)
        lines = list()
        lines.append(prefix + ".. code-block:: %s" % language)
        lines.append(prefix)
        for line in code.split("\n"):
            lines.append(code_prefix + line.strip())
        return "\n".join(lines)
1261298
def _at_dump_functions(self, calculator, rule, scope, block):
        
        sys.stderr.write("%s\n" % repr(rule.namespace._functions))
1161757
def rec_sqrt(x, context=None):
    
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_rec_sqrt,
        (BigFloat._implicit_convert(x),),
        context,
    )
21064
def return_future(fn):
    
    @wraps(fn)
    def decorated(*args, **kwargs):
        return gen.maybe_future(fn(*args, **kwargs))

    return decorated
131363
def printPi(self):
        
        assert self.pi is not None, "Calculate pi before calling printPi()"
        assert len(self.mapping)>0, "printPi() can only be used in combination with the direct or indirect method. Use print(mc.pi) if your subclass is called mc."        
        for key,state in self.mapping.items():
            print(state,self.pi[key])
323506
def _get_preprocessed(self, data):
        
        from rez.serialise import process_python_objects
        from rez.utils.data_utils import get_dict_diff_str
        from copy import deepcopy

        with add_sys_paths(config.package_definition_build_python_paths):
            preprocess_func = getattr(self, "preprocess", None)

            if preprocess_func:
                print_info("Applying preprocess from package.py")
            else:
                # load globally configured preprocess function
                dotted = self.config.package_preprocess_function

                if not dotted:
                    return None

                if '.' not in dotted:
                    print_error(
                        "Setting 'package_preprocess_function' must be of "
                        "form 'module[.module.module...].funcname'. Package  "
                        "preprocessing has not been applied.")
                    return None

                name, funcname = dotted.rsplit('.', 1)

                try:
                    module = __import__(name=name, fromlist=[funcname])
                except Exception as e:
                    print_error("Failed to load preprocessing function '%s': %s"
                                % (dotted, str(e)))
                    return None

                setattr(module, "InvalidPackageError", InvalidPackageError)
                preprocess_func = getattr(module, funcname)

                if not preprocess_func or not isfunction(isfunction):
                    print_error("Function '%s' not found" % dotted)
                    return None

                print_info("Applying preprocess function %s" % dotted)

            preprocessed_data = deepcopy(data)

            # apply preprocessing
            try:
                preprocess_func(this=self, data=preprocessed_data)
            except InvalidPackageError:
                raise
            except Exception as e:
                print_error("Failed to apply preprocess: %s: %s"
                            % (e.__class__.__name__, str(e)))
                return None

        # if preprocess added functions, these may need to be converted to
        # SourceCode instances
        preprocessed_data = process_python_objects(preprocessed_data)

        if preprocessed_data == data:
            return None

        # recreate package from modified package data
        package = create_package(self.name, preprocessed_data,
                                 package_cls=self.__class__)

        # print summary of changed package attributes
        txt = get_dict_diff_str(
            data,
            preprocessed_data,
            title="Package attributes were changed in preprocessing:"
        )
        print_info(txt)

        return package, preprocessed_data
1136370
public void precisionRecall()
	{
		PrintfFormat fmt1 = new PrintfFormat("%9s %9s %9s");
		PrintfFormat fmt2 = new PrintfFormat(" %5.2f");
		PrintfFormat hfmt2 = new PrintfFormat(" r%4.2f");
		// print header
		System.out.print(fmt1.sprintf( new Object[] { "block","dist","data"} ));
		double[] rec = MatchExpt.interpolated11PointRecallLevels();
		for (int m=0; m<rec.length; m++) System.out.print(hfmt2.sprintf(rec[m])); 
		System.out.println("   avgPrec\n");
		// print values
		for (int i=0; i<blockerNames.size(); i++) {
			String blocker = (String)blockerNames.get(i);
			if (blocker.length()>7) blocker = blocker.substring(0,7);
			for (int j=0; j<learnerNames.size(); j++) {
				String distance = (String)learnerNames.get(j);
				if (distance.length()>7) distance = distance.substring(0,7);
				double[] average = new double[11+1]; 
				for (int k=0; k<datasetNames.size(); k++) {
					String dataset = (String)datasetNames.get(k);
					// shorten this name
					dataset = new File(dataset).getName();
					int dotPos = dataset.indexOf('.');
					if (dotPos>=0) dataset = dataset.substring(0,dotPos);
					if (dataset.length()>9) dataset = dataset.substring(0,9);
					System.out.print(fmt1.sprintf( new Object[] { blocker, distance, dataset } ));
					double[] prec = expt[i][j][k].interpolated11PointPrecision();
					for (int m=0; m<prec.length; m++) {
						System.out.print(fmt2.sprintf( prec[m] ));
						average[m] += prec[m];
					}
					double a = ((Double)expt[i][j][k].averagePrecision()).doubleValue();
					System.out.print("   "+fmt2.sprintf( a ));
					average[11] += a;
					System.out.print("\n");
				}
				// show average over all datasets
				System.out.print(fmt1.sprintf( new Object[] { blocker, distance, "avg" }));
				for (int m=0; m<average.length-1; m++) {
					System.out.print(fmt2.sprintf( average[m]/datasetNames.size() ));
				}
				System.out.println("   "+fmt2.sprintf( average[11]/datasetNames.size()) + "\n");
			}
		}
	}
1076429
private static void printSqrtConvergence() {
		int precision = 10000;
		
		for (BigDecimal x : Arrays.asList(BigDecimal.valueOf(2), BigDecimal.valueOf(16))) {
			System.out.println("Newton sqrt(" + x +")");
			sqrtUsingNewtonPrint(x, new MathContext(precision));		
			System.out.println();
			
			System.out.println("Newton adaptive sqrt(" + x +")");
			sqrtUsingNewtonAdaptivePrecisionPrint(x, new MathContext(precision));		
			System.out.println();
			
			System.out.println("Halley sqrt(" + x +")");
			sqrtUsingHalleyPrint(x, new MathContext(precision));		
			System.out.println();
		}
	}
1230545
def _expr2code(self, arg_list, expr):
        """"""
        code = lambdastr(arg_list, expr)
        function_code = code.split(':')[1].strip()
        #for arg in arg_list:
        #    function_code = function_code.replace(arg.name, 'self.'+arg.name)

        return function_code
480807
def main() -> None:
    """""""
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--module", help="name of the module to import",
                        choices=[
                            "functions_100_with_no_contract",

                            "functions_100_with_1_contract",
                            "functions_100_with_5_contracts",
                            "functions_100_with_10_contracts",

                            "functions_100_with_1_disabled_contract",
                            "functions_100_with_5_disabled_contracts",
                            "functions_100_with_10_disabled_contracts",

                            "classes_100_with_no_invariant",

                            "classes_100_with_1_invariant",
                            "classes_100_with_5_invariants",
                            "classes_100_with_10_invariants",

                            "classes_100_with_1_disabled_invariant",
                            "classes_100_with_5_disabled_invariants",
                            "classes_100_with_10_disabled_invariants",
                        ],
                        required=True)
    args = parser.parse_args()


    a_module = str(args.module)
    if a_module == "functions_100_with_no_contract":
        start = time.time()
        import functions_100_with_no_contract
        print(time.time() - start)

    elif a_module == "functions_100_with_1_contract":
        start = time.time()
        import functions_100_with_1_contract
        print(time.time() - start)

    elif a_module == "functions_100_with_5_contracts":
        start = time.time()
        import functions_100_with_5_contracts
        print(time.time() - start)

    elif a_module == "functions_100_with_10_contracts":
        start = time.time()
        import functions_100_with_10_contracts
        print(time.time() - start)

    elif a_module == "functions_100_with_1_disabled_contract":
        start = time.time()
        import functions_100_with_1_disabled_contract
        print(time.time() - start)

    elif a_module == "functions_100_with_5_disabled_contracts":
        start = time.time()
        import functions_100_with_5_disabled_contracts
        print(time.time() - start)

    elif a_module == "functions_100_with_10_disabled_contracts":
        start = time.time()
        import functions_100_with_10_disabled_contracts
        print(time.time() - start)

    elif a_module == "classes_100_with_no_invariant":
        start = time.time()
        import classes_100_with_no_invariant
        print(time.time() - start)

    elif a_module == "classes_100_with_1_invariant":
        start = time.time()
        import classes_100_with_1_invariant
        print(time.time() - start)

    elif a_module == "classes_100_with_5_invariants":
        start = time.time()
        import classes_100_with_5_invariants
        print(time.time() - start)

    elif a_module == "classes_100_with_10_invariants":
        start = time.time()
        import classes_100_with_10_invariants
        print(time.time() - start)

    elif a_module == "classes_100_with_1_disabled_invariant":
        start = time.time()
        import classes_100_with_1_disabled_invariant
        print(time.time() - start)

    elif a_module == "classes_100_with_5_disabled_invariants":
        start = time.time()
        import classes_100_with_5_disabled_invariants
        print(time.time() - start)

    elif a_module == "classes_100_with_10_disabled_invariants":
        start = time.time()
        import classes_100_with_10_disabled_invariants
        print(time.time() - start)

    else:
        raise NotImplementedError("Unhandled module: {}".format(a_module))
815347
def on_error_print_details(actual, expected):
    
    try:
        yield
    except Exception:
        diff = difflib.ndiff(expected.splitlines(), actual.splitlines())
        diff_text = u"\n".join(diff)
        print(u"DIFF (+ ACTUAL, - EXPECTED):\n{0}\n".format(diff_text))
        if DEBUG:
            print(u"expected:\n{0}\n".format(expected))
            print(u"actual:\n{0}".format(actual))
        raise
610370
def from_statement(cls, statement):
        
        if statement[0] in ["TS", "TIMESTAMP", "UTCTIMESTAMP", "UTCTS"]:
            return TimestampFunction.from_statement(statement)
        elif statement[0] in ["NOW", "UTCNOW"]:
            return NowFunction.from_statement(statement)
        else:
            raise SyntaxError("Unknown function %r" % statement[0])
471534
def fromimpute2(args):
    
    p = OptionParser(fromimpute2.__doc__)
    opts, args = p.parse_args(args)

    if len(args) != 3:
        sys.exit(not p.print_help())

    impute2file, fastafile, chr = args
    fasta = Fasta(fastafile)
    print(get_vcfstanza(fastafile, fasta))
    fp = open(impute2file)
    seen = set()
    for row in fp:
        snp_id, rsid, pos, ref, alt, aa, ab, bb = row.split()
        pos = int(pos)
        if pos in seen:
            continue
        seen.add(pos)
        code = max((float(aa), "0/0"), (float(ab), "0/1"), (float(bb), "1/1"))[-1]
        tag = "PR" if snp_id == chr else "IM"
        print("\t".join(str(x) for x in \
                (chr, pos, rsid, ref, alt, ".", ".", tag, \
                "GT:GP", code + ":" + ",".join((aa, ab, bb)))))
380760
def wrap_code(code: str, args: str = '') -> ast.Module:
    

    if sys.version_info >= (3, 7):
        user_code = import_expression.parse(code, mode='exec')
        injected = ''
    else:
        injected = code

    mod = import_expression.parse(CORO_CODE.format(args, textwrap.indent(injected, ' ' * 8)), mode='exec')

    definition = mod.body[-1]  # async def ...:
    assert isinstance(definition, ast.AsyncFunctionDef)

    try_block = definition.body[-1]  # try:
    assert isinstance(try_block, ast.Try)

    if sys.version_info >= (3, 7):
        try_block.body.extend(user_code.body)
    else:
        ast.increment_lineno(mod, -16)  # bring line numbers back in sync with repl

    ast.fix_missing_locations(mod)

    is_asyncgen = any(isinstance(node, ast.Yield) for node in ast.walk(try_block))

    last_expr = try_block.body[-1]

    # if the last part isn't an expression, ignore it
    if not isinstance(last_expr, ast.Expr):
        return mod

    # if the last expression is not a yield
    if not isinstance(last_expr.value, ast.Yield):
        # copy the expression into a return/yield
        if is_asyncgen:
            # copy the value of the expression into a yield
            yield_stmt = ast.Yield(last_expr.value)
            ast.copy_location(yield_stmt, last_expr)
            # place the yield into its own expression
            yield_expr = ast.Expr(yield_stmt)
            ast.copy_location(yield_expr, last_expr)

            # place the yield where the original expression was
            try_block.body[-1] = yield_expr
        else:
            # copy the expression into a return
            return_stmt = ast.Return(last_expr.value)
            ast.copy_location(return_stmt, last_expr)

            # place the return where the original expression was
            try_block.body[-1] = return_stmt

    return mod
630201
def to_code(self, context: Context =None):
        
        # Do not override this method!

        context = context or Context()
        for imp in self.imports:
            if imp not in context.imports:
                context.imports.append(imp)

        counter = Counter()
        lines = list(self.to_lines(context=context, counter=counter))

        if counter.num_indented_non_doc_blocks == 0:
            if self.expects_body_or_pass:
                lines.append("    pass")
            elif self.closed_by:
                lines[-1] += self.closed_by
        else:
            if self.closed_by:
                lines.append(self.closed_by)

        return join_lines(*lines) + self._suffix
627434
def to_code(self, from_function=False):
        """"""

        num_fastnames = sum(1 for op, arg in self.code if isopcode(op) and op in haslocal)
        is_function = self.newlocals or num_fastnames > 0 or len(self.args) > 0
        nested = is_function and from_function

        co_flags = {op[0] for op in self.code}

        is_generator = self.force_generator or (YIELD_VALUE in co_flags or YIELD_FROM in co_flags)
        no_free = (not self.freevars) and (not co_flags & hasfree)

        if version_info >= (3, 5):
            is_native_coroutine = bool(self.force_coroutine or (co_flags & coroutine_opcodes))
            assert not (is_native_coroutine and self.force_iterable_coroutine)

        co_flags =\
            (not(STORE_NAME in co_flags or LOAD_NAME in co_flags or DELETE_NAME in co_flags)) |\
            (self.newlocals and CO_NEWLOCALS) |\
            (self.varargs and CO_VARARGS) |\
            (self.varkwargs and CO_VARKEYWORDS) |\
            (is_generator and CO_GENERATOR) |\
            (no_free and CO_NOFREE) |\
            (nested and CO_NESTED)

        if version_info >= (3, 5):
            co_flags |= (is_native_coroutine and CO_COROUTINE) |\
                        (self.force_iterable_coroutine and CO_ITERABLE_COROUTINE) |\
                        (self.future_generator_stop and CO_FUTURE_GENERATOR_STOP)

        co_consts = [self.docstring]
        co_names = []
        co_varnames = list(self.args)
        co_freevars = tuple(self.freevars)

        # Find all cellvars beforehand for two reasons
        # Need the number of them to construct the numeric arg for ops in hasfree
        # Need to put args which are cells in the beginning of co_cellvars
        cellvars = {arg for op, arg in self.code
                    if isopcode(op) and op in hasfree
                    and arg not in co_freevars}
        co_cellvars = [jumps for jumps in self.args if jumps in cellvars]

        def index(seq, item, eq=True, can_append=True):
            for i, x in enumerate(seq):
                if x == item if eq else x is item:
                    return i
            if can_append:
                seq.append(item)
                return len(seq) - 1
            else:
                raise IndexError("Item not found")

        jumps = []
        label_pos = {}
        lastlineno = self.firstlineno
        lastlinepos = 0
        co_code = bytearray()
        co_lnotab = bytearray()

        for i, (op, arg) in enumerate(self.code):
            if isinstance(op, Label):
                label_pos[op] = len(co_code)
            elif op is SetLineno:
                incr_lineno = arg - lastlineno
                incr_pos = len(co_code) - lastlinepos
                lastlineno = arg
                lastlinepos += incr_pos
                if incr_lineno != 0 or incr_pos != 0:
                    while incr_pos > 255:
                        co_lnotab += b"\xFF\0"
                        incr_pos -= 255
                    while incr_lineno > 255:
                        co_lnotab += (0xFF00|incr_pos).to_bytes(2, "little")
                        incr_pos = 0
                        incr_lineno -= 255
                    if incr_pos or incr_lineno:
                        co_lnotab += bytes((incr_pos, incr_lineno))
            elif op == opcode.EXTENDED_ARG:
                self.code[i + 1][1] |= 1 << 32
            elif op not in hasarg:
                co_code.append(op)
            else:
                if op in hasconst:
                    if isinstance(arg, Code) and\
                            i + 2 < len(self.code) and self.code[i + 2][0] in hascode:
                        arg = arg.to_code(from_function=is_function)
                        assert arg is not None
                    arg = index(co_consts, arg, 0)
                elif op in hasname:
                    arg = index(co_names, arg)
                elif op in hasjump:
                    jumps.append((len(co_code), arg))
                    co_code += op.to_bytes(3, "little")
                    continue
                elif op in haslocal:
                    arg = index(co_varnames, arg)
                elif op in hascompare:
                    arg = index(cmp_op, arg, can_append=False)
                elif op in hasfree:
                    try:
                        arg = index(co_freevars, arg, can_append=False) + len(cellvars)
                    except IndexError:
                        arg = index(co_cellvars, arg)
                if arg > 0xFFFF:
                    co_code += (opcode.EXTENDED_ARG | ((arg & 0xFFFF0000) >> 8)).to_bytes(3, "little")
                co_code += (op | (arg << 8)).to_bytes(3, "little")

        for pos, label in jumps:
            jump = label_pos[label]
            if co_code[pos] in hasjrel:
                jump -= pos + 3
            if jump > 0xFFFF:
                raise NotImplementedError("Extended jumps not implemented")
            co_code[pos + 1] = jump & 0xFF
            co_code[pos + 2] = jump >> 8

        co_argcount = len(self.args) - self.varargs - self.varkwargs - self.kwonly
        co_stacksize = self._compute_stacksize()

        return CodeType(co_argcount, self.kwonly, len(co_varnames), co_stacksize, co_flags,
                        bytes(co_code), tuple(co_consts), tuple(co_names), tuple(co_varnames),
                        self.filename, self.name, self.firstlineno, bytes(co_lnotab), co_freevars,
                        tuple(co_cellvars))
397368
def sqr(x, context=None):
    
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_sqr,
        (BigFloat._implicit_convert(x),),
        context,
    )