signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
def valid_symbol_name(name): | if name in RESERVED_WORDS:<EOL><INDENT>return False<EOL><DEDENT>gen = generate_tokens(io.BytesIO(name.encode('<STR_LIT:utf-8>')).readline)<EOL>typ, _, start, end, _ = next(gen)<EOL>if typ == tk_ENCODING:<EOL><INDENT>typ, _, start, end, _ = next(gen)<EOL><DEDENT>return typ == tk_NAME and start == (<NUM_LIT:1>, <NUM_LIT:... | Determine whether the input symbol name is a valid name.
Arguments
---------
name : str
name to check for validity.
Returns
--------
valid : bool
whether name is a a valid symbol name
This checks for Python reserved words and that the name matches
the regular ex... | f12457:m6 |
def op2func(op): | return OPERATORS[op.__class__]<EOL> | Return function for operator nodes. | f12457:m7 |
def get_ast_names(astnode): | finder = NameFinder()<EOL>finder.generic_visit(astnode)<EOL>return finder.names<EOL> | Return symbol Names from an AST node. | f12457:m8 |
def make_symbol_table(use_numpy=True, **kws): | symtable = {}<EOL>for sym in FROM_PY:<EOL><INDENT>if sym in builtins:<EOL><INDENT>symtable[sym] = builtins[sym]<EOL><DEDENT><DEDENT>for sym in FROM_MATH:<EOL><INDENT>if hasattr(math, sym):<EOL><INDENT>symtable[sym] = getattr(math, sym)<EOL><DEDENT><DEDENT>if HAS_NUMPY and use_numpy:<EOL><INDENT>for sym in FROM_NUMPY:<E... | Create a default symboltable, taking dict of user-defined symbols.
Arguments
---------
numpy : bool, optional
whether to include symbols from numpy
kws : optional
additional symbol name, value pairs to include in symbol table
Returns
--------
symbol_table : dict
a sym... | f12457:m9 |
def __init__(self): | pass<EOL> | TODO: docstring in public method. | f12457:c0:m0 |
def __nonzero__(self): | return False<EOL> | TODO: docstring in magic method. | f12457:c0:m1 |
def __init__(self, node, exc=None, msg='<STR_LIT>', expr=None, lineno=None): | self.node = node<EOL>self.expr = expr<EOL>self.msg = msg<EOL>self.exc = exc<EOL>self.lineno = lineno<EOL>self.exc_info = exc_info()<EOL>if self.exc is None and self.exc_info[<NUM_LIT:0>] is not None:<EOL><INDENT>self.exc = self.exc_info[<NUM_LIT:0>]<EOL><DEDENT>if self.msg is '<STR_LIT>' and self.exc_info[<NUM_LIT:1>] ... | TODO: docstring in public method. | f12457:c1:m0 |
def get_error(self): | col_offset = -<NUM_LIT:1><EOL>if self.node is not None:<EOL><INDENT>try:<EOL><INDENT>col_offset = self.node.col_offset<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>try:<EOL><INDENT>exc_name = self.exc.__name__<EOL><DEDENT>except AttributeError:<EOL><INDENT>exc_name = str(self.exc)<EOL><DEDENT... | Retrieve error data. | f12457:c1:m1 |
def __init__(self): | self.names = []<EOL>ast.NodeVisitor.__init__(self)<EOL> | TODO: docstring in public method. | f12457:c2:m0 |
def generic_visit(self, node): | if node.__class__.__name__ == '<STR_LIT:Name>':<EOL><INDENT>if node.ctx.__class__ == ast.Load and node.id not in self.names:<EOL><INDENT>self.names.append(node.id)<EOL><DEDENT><DEDENT>ast.NodeVisitor.generic_visit(self, node)<EOL> | TODO: docstring in public method. | f12457:c2:m1 |
def remove_nodehandler(self, node): | out = None<EOL>if node in self.node_handlers:<EOL><INDENT>out = self.node_handlers.pop(node)<EOL><DEDENT>return out<EOL> | remove support for a node
returns current node handler, so that it
might be re-added with add_nodehandler() | f12458:c0:m1 |
def set_nodehandler(self, node, handler): | self.node_handlers[node] = handler<EOL> | set node handler | f12458:c0:m2 |
def user_defined_symbols(self): | sym_in_current = set(self.symtable.keys())<EOL>sym_from_construction = set(self.no_deepcopy)<EOL>unique_symbols = sym_in_current.difference(sym_from_construction)<EOL>return unique_symbols<EOL> | Return a set of symbols that have been added to symtable after
construction.
I.e., the symbols from self.symtable that are not in
self.no_deepcopy.
Returns
-------
unique_symbols : set
symbols in symtable that are not in self.no_deepcopy | f12458:c0:m3 |
def unimplemented(self, node): | self.raise_exception(node, exc=NotImplementedError,<EOL>msg="<STR_LIT>" %<EOL>(node.__class__.__name__))<EOL> | Unimplemented nodes. | f12458:c0:m4 |
def raise_exception(self, node, exc=None, msg='<STR_LIT>', expr=None,<EOL>lineno=None): | if self.error is None:<EOL><INDENT>self.error = []<EOL><DEDENT>if expr is None:<EOL><INDENT>expr = self.expr<EOL><DEDENT>if len(self.error) > <NUM_LIT:0> and not isinstance(node, ast.Module):<EOL><INDENT>msg = '<STR_LIT:%s>' % msg<EOL><DEDENT>err = ExceptionHolder(node, exc=exc, msg=msg, expr=expr, lineno=lineno)<EOL>s... | Add an exception. | f12458:c0:m5 |
def parse(self, text): | self.expr = text<EOL>try:<EOL><INDENT>out = ast.parse(text)<EOL><DEDENT>except SyntaxError:<EOL><INDENT>self.raise_exception(None, msg='<STR_LIT>', expr=text)<EOL><DEDENT>except:<EOL><INDENT>self.raise_exception(None, msg='<STR_LIT>', expr=text)<EOL><DEDENT>return out<EOL> | Parse statement/expression to Ast representation. | f12458:c0:m6 |
def run(self, node, expr=None, lineno=None, with_raise=True): | <EOL>if time.time() - self.start_time > self.max_time:<EOL><INDENT>raise RuntimeError(ERR_MAX_TIME.format(self.max_time))<EOL><DEDENT>out = None<EOL>if len(self.error) > <NUM_LIT:0>:<EOL><INDENT>return out<EOL><DEDENT>if node is None:<EOL><INDENT>return out<EOL><DEDENT>if isinstance(node, str):<EOL><INDENT>node = self.... | Execute parsed Ast representation for an expression. | f12458:c0:m7 |
def __call__(self, expr, **kw): | return self.eval(expr, **kw)<EOL> | Call class instance as function. | f12458:c0:m8 |
def eval(self, expr, lineno=<NUM_LIT:0>, show_errors=True): | self.lineno = lineno<EOL>self.error = []<EOL>self.start_time = time.time()<EOL>try:<EOL><INDENT>node = self.parse(expr)<EOL><DEDENT>except:<EOL><INDENT>errmsg = exc_info()[<NUM_LIT:1>]<EOL>if len(self.error) > <NUM_LIT:0>:<EOL><INDENT>errmsg = "<STR_LIT:\n>".join(self.error[<NUM_LIT:0>].get_error())<EOL><DEDENT>if not ... | Evaluate a single statement. | f12458:c0:m9 |
@staticmethod<EOL><INDENT>def dump(node, **kw):<DEDENT> | return ast.dump(node, **kw)<EOL> | Simple ast dumper. | f12458:c0:m10 |
def on_expr(self, node): | return self.run(node.value)<EOL> | Expression. | f12458:c0:m11 |
def on_index(self, node): | return self.run(node.value)<EOL> | Index. | f12458:c0:m12 |
def on_return(self, node): | self.retval = self.run(node.value)<EOL>if self.retval is None:<EOL><INDENT>self.retval = ReturnedNone<EOL><DEDENT>return<EOL> | Return statement: look for None, return special sentinal. | f12458:c0:m13 |
def on_repr(self, node): | return repr(self.run(node.value))<EOL> | Repr. | f12458:c0:m14 |
def on_module(self, node): | out = None<EOL>for tnode in node.body:<EOL><INDENT>out = self.run(tnode)<EOL><DEDENT>return out<EOL> | Module def. | f12458:c0:m15 |
def on_expression(self, node): | return self.on_module(node)<EOL> | basic expression | f12458:c0:m16 |
def on_pass(self, node): | return None<EOL> | Pass statement. | f12458:c0:m17 |
def on_ellipsis(self, node): | return Ellipsis<EOL> | Ellipses. | f12458:c0:m18 |
def on_interrupt(self, node): | self._interrupt = node<EOL>return node<EOL> | Interrupt handler. | f12458:c0:m19 |
def on_break(self, node): | return self.on_interrupt(node)<EOL> | Break. | f12458:c0:m20 |
def on_continue(self, node): | return self.on_interrupt(node)<EOL> | Continue. | f12458:c0:m21 |
def on_list(self, node): | return [self.run(e) for e in node.elts]<EOL> | List. | f12458:c0:m23 |
def on_tuple(self, node): | return tuple(self.on_list(node))<EOL> | Tuple. | f12458:c0:m24 |
def on_dict(self, node): | return dict([(self.run(k), self.run(v)) for k, v in<EOL>zip(node.keys, node.values)])<EOL> | Dictionary. | f12458:c0:m25 |
def on_num(self, node): | return node.n<EOL> | Return number. | f12458:c0:m26 |
def on_str(self, node): | return node.s<EOL> | Return string. | f12458:c0:m27 |
def on_nameconstant(self, node): | return node.value<EOL> | named constant | f12458:c0:m28 |
def on_name(self, node): | ctx = node.ctx.__class__<EOL>if ctx in (ast.Param, ast.Del):<EOL><INDENT>return str(node.id)<EOL><DEDENT>else:<EOL><INDENT>if node.id in self.symtable:<EOL><INDENT>return self.symtable[node.id]<EOL><DEDENT>else:<EOL><INDENT>msg = "<STR_LIT>" % node.id<EOL>self.raise_exception(node, exc=NameError, msg=msg)<EOL><DEDENT><... | Name node. | f12458:c0:m29 |
def on_nameconstant(self, node): | return node.value<EOL> | True, False, None in python >= 3.4 | f12458:c0:m30 |
def node_assign(self, node, val): | if node.__class__ == ast.Name:<EOL><INDENT>if not valid_symbol_name(node.id) or node.id in self.readonly_symbols:<EOL><INDENT>errmsg = "<STR_LIT>" % node.id<EOL>self.raise_exception(node, exc=NameError, msg=errmsg)<EOL><DEDENT>self.symtable[node.id] = val<EOL>if node.id in self.no_deepcopy:<EOL><INDENT>self.no_deepcopy... | Assign a value (not the node.value object) to a node.
This is used by on_assign, but also by for, list comprehension,
etc. | f12458:c0:m31 |
def on_attribute(self, node): | ctx = node.ctx.__class__<EOL>if ctx == ast.Store:<EOL><INDENT>msg = "<STR_LIT>"<EOL>self.raise_exception(node, exc=RuntimeError, msg=msg)<EOL><DEDENT>sym = self.run(node.value)<EOL>if ctx == ast.Del:<EOL><INDENT>return delattr(sym, node.attr)<EOL><DEDENT>fmt = "<STR_LIT>"<EOL>if node.attr not in UNSAFE_ATTRS:<EOL><INDE... | Extract attribute. | f12458:c0:m32 |
def on_assign(self, node): | val = self.run(node.value)<EOL>for tnode in node.targets:<EOL><INDENT>self.node_assign(tnode, val)<EOL><DEDENT>return<EOL> | Simple assignment. | f12458:c0:m33 |
def on_augassign(self, node): | return self.on_assign(ast.Assign(targets=[node.target],<EOL>value=ast.BinOp(left=node.target,<EOL>op=node.op,<EOL>right=node.value)))<EOL> | Augmented assign. | f12458:c0:m34 |
def on_slice(self, node): | return slice(self.run(node.lower),<EOL>self.run(node.upper),<EOL>self.run(node.step))<EOL> | Simple slice. | f12458:c0:m35 |
def on_extslice(self, node): | return tuple([self.run(tnode) for tnode in node.dims])<EOL> | Extended slice. | f12458:c0:m36 |
def on_subscript(self, node): | val = self.run(node.value)<EOL>nslice = self.run(node.slice)<EOL>ctx = node.ctx.__class__<EOL>if ctx in (ast.Load, ast.Store):<EOL><INDENT>if isinstance(node.slice, (ast.Index, ast.Slice, ast.Ellipsis)):<EOL><INDENT>return val.__getitem__(nslice)<EOL><DEDENT>elif isinstance(node.slice, ast.ExtSlice):<EOL><INDENT>return... | Subscript handling -- one of the tricky parts. | f12458:c0:m37 |
def on_delete(self, node): | for tnode in node.targets:<EOL><INDENT>if tnode.ctx.__class__ != ast.Del:<EOL><INDENT>break<EOL><DEDENT>children = []<EOL>while tnode.__class__ == ast.Attribute:<EOL><INDENT>children.append(tnode.attr)<EOL>tnode = tnode.value<EOL><DEDENT>if tnode.__class__ == ast.Name and tnode.id not in self.readonly_symbols:<EOL><IND... | Delete statement. | f12458:c0:m38 |
def on_unaryop(self, node): | return op2func(node.op)(self.run(node.operand))<EOL> | Unary operator. | f12458:c0:m39 |
def on_binop(self, node): | return op2func(node.op)(self.run(node.left),<EOL>self.run(node.right))<EOL> | Binary operator. | f12458:c0:m40 |
def on_boolop(self, node): | val = self.run(node.values[<NUM_LIT:0>])<EOL>is_and = ast.And == node.op.__class__<EOL>if (is_and and val) or (not is_and and not val):<EOL><INDENT>for n in node.values[<NUM_LIT:1>:]:<EOL><INDENT>val = op2func(node.op)(val, self.run(n))<EOL>if (is_and and not val) or (not is_and and val):<EOL><INDENT>break<EOL><DEDENT>... | Boolean operator. | f12458:c0:m41 |
def on_compare(self, node): | lval = self.run(node.left)<EOL>out = True<EOL>for op, rnode in zip(node.ops, node.comparators):<EOL><INDENT>rval = self.run(rnode)<EOL>out = op2func(op)(lval, rval)<EOL>lval = rval<EOL>if self.use_numpy and isinstance(out, numpy.ndarray) and out.any():<EOL><INDENT>break<EOL><DEDENT>elif not out:<EOL><INDENT>break<EOL><... | comparison operators | f12458:c0:m42 |
def on_print(self, node): | dest = self.run(node.dest) or self.writer<EOL>end = '<STR_LIT>'<EOL>if node.nl:<EOL><INDENT>end = '<STR_LIT:\n>'<EOL><DEDENT>out = [self.run(tnode) for tnode in node.values]<EOL>if out and len(self.error) == <NUM_LIT:0>:<EOL><INDENT>self._printer(*out, file=dest, end=end)<EOL><DEDENT> | Note: implements Python2 style print statement, not print()
function.
May need improvement.... | f12458:c0:m43 |
def _printer(self, *out, **kws): | flush = kws.pop('<STR_LIT>', True)<EOL>fileh = kws.pop('<STR_LIT:file>', self.writer)<EOL>sep = kws.pop('<STR_LIT>', '<STR_LIT:U+0020>')<EOL>end = kws.pop('<STR_LIT>', '<STR_LIT:\n>')<EOL>print(*out, file=fileh, sep=sep, end=end)<EOL>if flush:<EOL><INDENT>fileh.flush()<EOL><DEDENT> | Generic print function. | f12458:c0:m44 |
def on_for(self, node): | for val in self.run(node.iter):<EOL><INDENT>self.node_assign(node.target, val)<EOL>self._interrupt = None<EOL>for tnode in node.body:<EOL><INDENT>self.run(tnode)<EOL>if self._interrupt is not None:<EOL><INDENT>break<EOL><DEDENT><DEDENT>if isinstance(self._interrupt, ast.Break):<EOL><INDENT>break<EOL><DEDENT><DEDENT>els... | For blocks. | f12458:c0:m48 |
def on_listcomp(self, node): | out = []<EOL>for tnode in node.generators:<EOL><INDENT>if tnode.__class__ == ast.comprehension:<EOL><INDENT>for val in self.run(tnode.iter):<EOL><INDENT>self.node_assign(tnode.target, val)<EOL>add = True<EOL>for cond in tnode.ifs:<EOL><INDENT>add = add and self.run(cond)<EOL><DEDENT>if add:<EOL><INDENT>out.append(self.... | List comprehension. | f12458:c0:m49 |
def on_excepthandler(self, node): | return (self.run(node.type), node.name, node.body)<EOL> | Exception handler... | f12458:c0:m50 |
def on_try(self, node): | no_errors = True<EOL>for tnode in node.body:<EOL><INDENT>self.run(tnode, with_raise=False)<EOL>no_errors = no_errors and len(self.error) == <NUM_LIT:0><EOL>if len(self.error) > <NUM_LIT:0>:<EOL><INDENT>e_type, e_value, e_tback = self.error[-<NUM_LIT:1>].exc_info<EOL>for hnd in node.handlers:<EOL><INDENT>htype = None<EO... | Try/except/else/finally blocks. | f12458:c0:m51 |
def on_raise(self, node): | if version_info[<NUM_LIT:0>] == <NUM_LIT:3>:<EOL><INDENT>excnode = node.exc<EOL>msgnode = node.cause<EOL><DEDENT>else:<EOL><INDENT>excnode = node.type<EOL>msgnode = node.inst<EOL><DEDENT>out = self.run(excnode)<EOL>msg = '<STR_LIT:U+0020>'.join(out.args)<EOL>msg2 = self.run(msgnode)<EOL>if msg2 not in (None, '<STR_LIT:... | Raise statement: note difference for python 2 and 3. | f12458:c0:m52 |
def on_call(self, node): | <EOL>func = self.run(node.func)<EOL>if not hasattr(func, '<STR_LIT>') and not isinstance(func, type):<EOL><INDENT>msg = "<STR_LIT>" % (func)<EOL>self.raise_exception(node, exc=TypeError, msg=msg)<EOL><DEDENT>args = [self.run(targ) for targ in node.args]<EOL>starargs = getattr(node, '<STR_LIT>', None)<EOL>if starargs is... | Function execution. | f12458:c0:m53 |
def on_functiondef(self, node): | <EOL>if node.decorator_list:<EOL><INDENT>raise Warning("<STR_LIT>")<EOL><DEDENT>kwargs = []<EOL>if not valid_symbol_name(node.name) or node.name in self.readonly_symbols:<EOL><INDENT>errmsg = "<STR_LIT>" % node.name<EOL>self.raise_exception(node, exc=NameError, msg=errmsg)<EOL><DEDENT>offset = len(node.args.args) - len... | Define procedures. | f12458:c0:m55 |
def __init__(self, name, interp, doc=None, lineno=<NUM_LIT:0>,<EOL>body=None, args=None, kwargs=None,<EOL>vararg=None, varkws=None): | self.__ininit__ = True<EOL>self.name = name<EOL>self.__name__ = self.name<EOL>self.__asteval__ = interp<EOL>self.raise_exc = self.__asteval__.raise_exception<EOL>self.__doc__ = doc<EOL>self.body = body<EOL>self.argnames = args<EOL>self.kwargs = kwargs<EOL>self.vararg = vararg<EOL>self.varkws = varkws<EOL>self.lineno = ... | TODO: docstring in public method. | f12458:c1:m0 |
def __repr__(self): | sig = "<STR_LIT>"<EOL>if len(self.argnames) > <NUM_LIT:0>:<EOL><INDENT>sig = "<STR_LIT>" % (sig, '<STR_LIT:U+002CU+0020>'.join(self.argnames))<EOL><DEDENT>if self.vararg is not None:<EOL><INDENT>sig = "<STR_LIT>" % (sig, self.vararg)<EOL><DEDENT>if len(self.kwargs) > <NUM_LIT:0>:<EOL><INDENT>if len(sig) > <NUM_LIT:0>:<... | TODO: docstring in magic method. | f12458:c1:m3 |
def __call__(self, *args, **kwargs): | symlocals = {}<EOL>args = list(args)<EOL>nargs = len(args)<EOL>nkws = len(kwargs)<EOL>nargs_expected = len(self.argnames)<EOL>if (nargs < nargs_expected) and nkws > <NUM_LIT:0>:<EOL><INDENT>for name in self.argnames[nargs:]:<EOL><INDENT>if name in kwargs:<EOL><INDENT>args.append(kwargs.pop(name))<EOL><DEDENT><DEDENT>na... | TODO: docstring in public method. | f12458:c1:m4 |
def serialize_number(x, fmt=SER_BINARY, outlen=None): | ret = b'<STR_LIT>'<EOL>if fmt == SER_BINARY:<EOL><INDENT>while x:<EOL><INDENT>x, r = divmod(x, <NUM_LIT>)<EOL>ret = six.int2byte(int(r)) + ret<EOL><DEDENT>if outlen is not None:<EOL><INDENT>assert len(ret) <= outlen<EOL>ret = ret.rjust(outlen, b'<STR_LIT>')<EOL><DEDENT>return ret<EOL><DEDENT>assert fmt == SER_COMPACT<E... | Serializes `x' to a string of length `outlen' in format `fmt | f12466:m0 |
def deserialize_number(s, fmt=SER_BINARY): | ret = gmpy.mpz(<NUM_LIT:0>)<EOL>if fmt == SER_BINARY:<EOL><INDENT>if isinstance(s, six.text_type):<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>" +<EOL>"<STR_LIT>")<EOL><DEDENT>for c in s:<EOL><INDENT>ret *= <NUM_LIT><EOL>ret += byte2int(c)<EOL><DEDENT>return ret<EOL><DEDENT>assert fmt == SER_COMPACT<EOL>if isinstance(s... | Deserializes a number from a string `s' in format `fmt | f12466:m1 |
def mod_issquare(a, p): | if not a:<EOL><INDENT>return True<EOL><DEDENT>p1 = p // <NUM_LIT:2><EOL>p2 = pow(a, p1, p)<EOL>return p2 == <NUM_LIT:1><EOL> | Returns whether `a' is a square modulo p | f12466:m3 |
def mod_root(a, p): | if a == <NUM_LIT:0>:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>if not mod_issquare(a, p):<EOL><INDENT>raise ValueError<EOL><DEDENT>n = <NUM_LIT:2><EOL>while mod_issquare(n, p):<EOL><INDENT>n += <NUM_LIT:1><EOL><DEDENT>q = p - <NUM_LIT:1><EOL>r = <NUM_LIT:0><EOL>while not q.getbit(r):<EOL><INDENT>r += <NUM_LIT:1><EOL><... | Return a root of `a' modulo p | f12466:m4 |
def _passphrase_to_hash(passphrase): | return hashlib.sha256(passphrase).digest()<EOL> | Converts a passphrase to a hash. | f12466:m5 |
def encrypt(s, pk, pk_format=SER_COMPACT, mac_bytes=<NUM_LIT:10>, curve=None): | curve = (Curve.by_pk_len(len(pk)) if curve is None<EOL>else Curve.by_name(curve))<EOL>p = curve.pubkey_from_string(pk, pk_format)<EOL>return p.encrypt(s, mac_bytes)<EOL> | Encrypts `s' for public key `pk | f12466:m6 |
def decrypt(s, passphrase, curve='<STR_LIT>', mac_bytes=<NUM_LIT:10>): | curve = Curve.by_name(curve)<EOL>privkey = curve.passphrase_to_privkey(passphrase)<EOL>return privkey.decrypt(s, mac_bytes)<EOL> | Decrypts `s' with passphrase `passphrase | f12466:m7 |
def encrypt_file(in_path_or_file, out_path_or_file, pk, pk_format=SER_COMPACT,<EOL>mac_bytes=<NUM_LIT:10>, chunk_size=<NUM_LIT>, curve=None): | close_in, close_out = False, False<EOL>in_file, out_file = in_path_or_file, out_path_or_file<EOL>try:<EOL><INDENT>if stringlike(in_path_or_file):<EOL><INDENT>in_file = open(in_path_or_file, '<STR_LIT:rb>')<EOL>close_in = True<EOL><DEDENT>if stringlike(out_path_or_file):<EOL><INDENT>out_file = open(out_path_or_file, '<S... | Encrypts `in_file' to `out_file' for pubkey `pk | f12466:m8 |
def decrypt_file(in_path_or_file, out_path_or_file, passphrase,<EOL>curve='<STR_LIT>', mac_bytes=<NUM_LIT:10>, chunk_size=<NUM_LIT>): | close_in, close_out = False, False<EOL>in_file, out_file = in_path_or_file, out_path_or_file<EOL>try:<EOL><INDENT>if stringlike(in_path_or_file):<EOL><INDENT>in_file = open(in_path_or_file, '<STR_LIT:rb>')<EOL>close_in = True<EOL><DEDENT>if stringlike(out_path_or_file):<EOL><INDENT>out_file = open(out_path_or_file, '<S... | Decrypts `in_file' to `out_file' with passphrase `passphrase | f12466:m9 |
def verify(s, sig, pk, sig_format=SER_COMPACT, pk_format=SER_COMPACT,<EOL>curve=None): | if isinstance(s, six.text_type):<EOL><INDENT>raise ValueError("<STR_LIT>" +<EOL>"<STR_LIT>")<EOL><DEDENT>curve = (Curve.by_pk_len(len(pk)) if curve is None<EOL>else Curve.by_name(curve))<EOL>p = curve.pubkey_from_string(pk, pk_format)<EOL>return p.verify(hashlib.sha512(s).digest(), sig, sig_format)<EOL> | Verifies that `sig' is a signature of pubkey `pk' for the
message `s'. | f12466:m12 |
def sign(s, passphrase, sig_format=SER_COMPACT, curve='<STR_LIT>'): | if isinstance(s, six.text_type):<EOL><INDENT>raise ValueError("<STR_LIT>" +<EOL>"<STR_LIT>")<EOL><DEDENT>curve = Curve.by_name(curve)<EOL>privkey = curve.passphrase_to_privkey(passphrase)<EOL>return privkey.sign(hashlib.sha512(s).digest(), sig_format)<EOL> | Signs `s' with passphrase `passphrase | f12466:m13 |
def generate_keypair(curve='<STR_LIT>', randfunc=None): | if randfunc is None:<EOL><INDENT>randfunc = Crypto.Random.new().read<EOL><DEDENT>curve = Curve.by_name(curve)<EOL>raw_privkey = randfunc(curve.order_len_bin)<EOL>privkey = serialize_number(deserialize_number(raw_privkey), SER_COMPACT)<EOL>pubkey = str(passphrase_to_pubkey(privkey))<EOL>return (privkey, pubkey)<EOL> | Convenience function to generate a random
new keypair (passphrase, pubkey). | f12466:m15 |
def verify(self, h, sig, sig_fmt=SER_BINARY): | s = deserialize_number(sig, sig_fmt)<EOL>return self.p._ECDSA_verify(h, s)<EOL> | Verifies that `sig' is a signature for a message with
SHA-512 hash `h'. | f12466:c3:m1 |
@contextlib.contextmanager<EOL><INDENT>def encrypt_to(self, f, mac_bytes=<NUM_LIT:10>):<DEDENT> | ctx = EncryptionContext(f, self.p, mac_bytes)<EOL>yield ctx<EOL>ctx.finish()<EOL> | Returns a file like object `ef'. Anything written to `ef'
will be encrypted for this pubkey and written to `f'. | f12466:c3:m2 |
def encrypt(self, s, mac_bytes=<NUM_LIT:10>): | if isinstance(s, six.text_type):<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>" +<EOL>"<STR_LIT>")<EOL><DEDENT>out = BytesIO()<EOL>with self.encrypt_to(out, mac_bytes) as f:<EOL><INDENT>f.write(s)<EOL><DEDENT>return out.getvalue()<EOL> | Encrypt `s' for this pubkey. | f12466:c3:m3 |
@contextlib.contextmanager<EOL><INDENT>def decrypt_from(self, f, mac_bytes=<NUM_LIT:10>):<DEDENT> | ctx = DecryptionContext(self.curve, f, self, mac_bytes)<EOL>yield ctx<EOL>ctx.read()<EOL> | Decrypts a message from f. | f12466:c4:m1 |
def sign(self, h, sig_format=SER_BINARY): | outlen = (self.curve.sig_len_compact if sig_format == SER_COMPACT<EOL>else self.curve.sig_len_bin)<EOL>sig = self._ECDSA_sign(h)<EOL>return serialize_number(sig, sig_format, outlen)<EOL> | Signs the message with SHA-512 hash `h' with this private key. | f12466:c4:m3 |
def __init__(self, raw_curve_params): | r = raw_curve_parameters(*raw_curve_params)<EOL>self.name = r.name<EOL>self.a = deserialize_number(binascii.unhexlify(r.a), SER_BINARY)<EOL>self.b = deserialize_number(binascii.unhexlify(r.b), SER_BINARY)<EOL>self.m = deserialize_number(binascii.unhexlify(r.m), SER_BINARY)<EOL>self.order = deserialize_number(<EOL>binas... | Initialize a new curve from raw curve parameters.
Use `Curve.by_pk_len' instead | f12466:c7:m3 |
@property<EOL><INDENT>def key_bytes(self):<DEDENT> | return self.pk_len_bin<EOL> | The approximate number of bytes of information in a key. | f12466:c7:m4 |
def hash_to_exponent(self, h): | ctr = Crypto.Util.Counter.new(<NUM_LIT>, initial_value=<NUM_LIT:0>)<EOL>cipher = Crypto.Cipher.AES.new(h,<EOL>Crypto.Cipher.AES.MODE_CTR, counter=ctr)<EOL>buf = cipher.encrypt(b'<STR_LIT>' * self.order_len_bin)<EOL>return self._buf_to_exponent(buf)<EOL> | Converts a 32 byte hash to an exponent | f12466:c7:m9 |
def get(self, path): | return json.loads(self._make_request('<STR_LIT:GET>', path))<EOL> | Make a GET request.
Args:
`path`: The path to the resource.
Returns:
The content of the response.
Raises:
An exception depending on the HTTP status code of the response. | f12472:c0:m0 |
def post(self, path, data, filename=None): | return self._send('<STR_LIT:POST>', path, data, filename)<EOL> | Make a POST request.
If a `filename` is not specified, then the data must already be
JSON-encoded. We specify the Content-Type accordingly.
Else, we make a multipart/form-encoded request. In this case, the data
variable must be a dict-like object. The file must already be
suita... | f12472:c0:m1 |
def put(self, path, data, filename=None): | return self._send('<STR_LIT>', path, data, filename)<EOL> | Make a PUT request.
If a `filename` is not specified, then the data must already be
JSON-encoded. We specify the Content-Type accordingly.
Else, we make a multipart/form-encoded request. In this case, the data
variable must be a dict-like object. The file must already be
suitab... | f12472:c0:m2 |
def delete(self, path): | return self._make_request('<STR_LIT>', path)<EOL> | Make a DELETE request.
Args:
`path`: The path to the resource.
Returns:
The content of the response.
Raises:
An exception depending on the HTTP status code of the response. | f12472:c0:m3 |
def _make_request(self, method, path, data=None, **kwargs): | _logger.debug("<STR_LIT>" % method)<EOL>url = self._construct_full_url(path)<EOL>_logger.debug("<STR_LIT>" % url)<EOL>self._auth_info.populate_request_data(kwargs)<EOL>_logger.debug("<STR_LIT>" % kwargs)<EOL>if self._auth_info._headers:<EOL><INDENT>kwargs.setdefault('<STR_LIT>', {}).update(self._auth_info._headers)<EOL... | Make a request.
Use the `requests` module to actually perform the request.
Args:
`method`: The method to use.
`path`: The path to the resource.
`data`: Any data to send (for POST and PUT requests).
`kwargs`: Other parameters for `requests`.
Retur... | f12472:c0:m4 |
def _send(self, method, path, data, filename): | if filename is None:<EOL><INDENT>return self._send_json(method, path, data)<EOL><DEDENT>else:<EOL><INDENT>return self._send_file(method, path, data, filename)<EOL><DEDENT> | Send data to a remote server, either with a POST or a PUT request.
Args:
`method`: The method (POST or PUT) to use.
`path`: The path to the resource.
`data`: The data to send.
`filename`: The filename of the file to send (if any).
Returns:
The... | f12472:c0:m5 |
def _send_json(self, method, path, data): | headers = {'<STR_LIT>': '<STR_LIT:application/json>'}<EOL>return self._make_request(method, path, data=data, headers=headers)<EOL> | Make a application/json request.
Args:
`method`: The method of the request (POST or PUT).
`path`: The path to the resource.
`data`: The JSON-encoded data.
Returns:
The content of the response.
Raises:
An exception depending on the HTTP... | f12472:c0:m6 |
def _send_file(self, method, path, data, filename): | with open(filename, '<STR_LIT:r>') as f:<EOL><INDENT>return self._make_request(method, path, data=data, files=[f, ])<EOL><DEDENT> | Make a multipart/form-encoded request.
Args:
`method`: The method of the request (POST or PUT).
`path`: The path to the resource.
`data`: The JSON-encoded data.
`filename`: The filename of the file to send.
Returns:
The content of the response... | f12472:c0:m7 |
def __init__(self, hostname, auth=AnonymousAuth()): | self._hostname = self._construct_full_hostname(hostname)<EOL>_logger.debug("<STR_LIT>" % self._hostname)<EOL>self._auth_info = auth<EOL> | Initializer for the base class.
Save the hostname to use for all requests as well as any
authentication info needed.
Args:
hostname: The host for the requests.
auth: The authentication info needed for any requests. | f12473:c0:m0 |
def _construct_full_hostname(self, hostname): | if hostname.startswith(('<STR_LIT>', '<STR_LIT>', )):<EOL><INDENT>return hostname<EOL><DEDENT>if '<STR_LIT>' in hostname:<EOL><INDENT>protocol, host = hostname.split('<STR_LIT>', <NUM_LIT:1>)<EOL>raise ValueError('<STR_LIT>' % protocol)<EOL><DEDENT>return '<STR_LIT>'.join([self.default_scheme, hostname, ])<EOL> | Create a full (scheme included) hostname from the argument given.
Only HTTP and HTTP+SSL protocols are allowed.
Args:
hostname: The hostname to use.
Returns:
The full hostname.
Raises:
ValueError: A not supported protocol is used. | f12473:c0:m1 |
def _construct_full_url(self, path): | return urlparse.urljoin(self._hostname, path)<EOL> | Construct the full url from the host and the path parts. | f12473:c0:m2 |
def _error_message(self, code, msg): | return self.error_messages[code] % msg<EOL> | Return the message that corresponds to the
request (status code and error message) specified.
Args:
`code`: The http status code.
`msg`: The message to display.
Returns:
The error message for the code given. | f12473:c0:m3 |
def _exception_for(self, code): | if code in self.errors:<EOL><INDENT>return self.errors[code]<EOL><DEDENT>elif <NUM_LIT> <= code < <NUM_LIT>:<EOL><INDENT>return exceptions.RemoteServerError<EOL><DEDENT>else:<EOL><INDENT>return exceptions.UnknownError<EOL><DEDENT> | Return the exception class suitable for the specified HTTP
status code.
Raises:
UnknownError: The HTTP status code is not one of the knowns. | f12473:c0:m4 |
@classmethod<EOL><INDENT>def get(self, username=None, password=None, headers={}):<DEDENT> | if all((username, password, )):<EOL><INDENT>return BasicAuth(username, password, headers)<EOL><DEDENT>elif not any((username, password, )):<EOL><INDENT>return AnonymousAuth(headers)<EOL><DEDENT>else:<EOL><INDENT>if username is None:<EOL><INDENT>data = ("<STR_LIT:username>", username, )<EOL><DEDENT>else:<EOL><INDENT>dat... | Factory method to get the correct AuthInfo object.
The returned value depends on the arguments given. In case the
username and password don't have a value (ie evaluate to False),
return an object for anonymous access. Else, return an auth
object that supports basic authentication.
... | f12474:c0:m0 |
def populate_request_data(self, request_args): | return request_args<EOL> | Add any auth info to the arguments of the (to be performed) request.
The method of the base class does nothing.
Args:
`request_args`: The arguments of the next request.
Returns:
The updated arguments for the request. | f12474:c0:m1 |
def __init__(self, username, password, headers={}): | self._username = username<EOL>self._password = password<EOL>self._headers = headers<EOL> | Initializer.
:param str username: The username to be used for the authentication with
Transifex. It can either have the value 'API' (suggested) or the
username of a user
:param str password: The password to be used for the authentication with
Transifex. It should be ... | f12474:c1:m0 |
def populate_request_data(self, request_args): | request_args['<STR_LIT>'] = HTTPBasicAuth(<EOL>self._username, self._password)<EOL>return request_args<EOL> | Add the authentication info to the supplied dictionary.
We use the `requests.HTTPBasicAuth` class as the `auth` param.
Args:
`request_args`: The arguments that will be passed to the request.
Returns:
The updated arguments for the request. | f12474:c1:m1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.