code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
splits = yield asyncGetSplits(_INPUT, conf['RULE'], **kwargs) parsed = yield asyncDispatch(splits, *get_async_dispatch_funcs()) _OUTPUT = yield asyncStarMap(asyncParseResult, parsed) returnValue(iter(_OUTPUT))
def asyncPipeStrreplace(context=None, _INPUT=None, conf=None, **kwargs)
A string module that asynchronously replaces text. Loopable. Parameters ---------- context : pipe2py.Context object _INPUT : twisted Deferred iterable of items or strings conf : { 'RULE': [ { 'param': {'value': <match type: 1=first, 2=last, 3=every>}, ...
15.303635
15.658498
0.977337
splits = get_splits(_INPUT, conf['RULE'], **kwargs) parsed = utils.dispatch(splits, *get_dispatch_funcs()) _OUTPUT = starmap(parse_result, parsed) return _OUTPUT
def pipe_strreplace(context=None, _INPUT=None, conf=None, **kwargs)
A string module that replaces text. Loopable. Parameters ---------- context : pipe2py.Context object _INPUT : iterable of items or strings conf : { 'RULE': [ { 'param': {'value': <match type: 1=first, 2=last, 3=every>}, 'find': {'value': <text to ...
13.26754
12.360447
1.073387
_input = yield _INPUT asyncFuncs = yield asyncGetSplits(None, conf, **cdicts(opts, kwargs)) pieces = yield asyncFuncs[0]() _pass = yield asyncFuncs[2]() if _pass: _OUTPUT = _input else: start = int(pieces.start) stop = start + int(pieces.count) _OUTPUT = isl...
def asyncPipeUniq(context=None, _INPUT=None, conf=None, **kwargs)
An operator that asynchronously returns a specified number of items from the top of a feed. Not loopable. Parameters ---------- context : pipe2py.Context object _INPUT : twisted Deferred iterable of items conf : { 'start': {'type': 'number', value': <starting location>} 'count':...
9.292661
10.250425
0.906563
funcs = get_splits(None, conf, **cdicts(opts, kwargs)) pieces, _pass = funcs[0](), funcs[2]() if _pass: _OUTPUT = _INPUT else: try: start = int(pieces.start) except AttributeError: start = 0 stop = start + int(pieces.count) _OUTPUT =...
def pipe_truncate(context=None, _INPUT=None, conf=None, **kwargs)
An operator that returns a specified number of items from the top of a feed. Not loopable. Parameters ---------- context : pipe2py.Context object _INPUT : pipe2py.modules pipe like object (iterable of items) kwargs -- terminal, if the truncation value is wired in conf : { 'start': {...
7.538857
7.68222
0.981338
conf['delimiter'] = conf.pop('to-str', dict.get(conf, 'delimiter')) splits = yield asyncGetSplits(_INPUT, conf, **cdicts(opts, kwargs)) parsed = yield asyncDispatch(splits, *get_async_dispatch_funcs()) items = yield asyncStarMap(partial(maybeDeferred, parse_result), parsed) _OUTPUT = utils.mult...
def asyncPipeStringtokenizer(context=None, _INPUT=None, conf=None, **kwargs)
A string module that asynchronously splits a string into tokens delimited by separators. Loopable. Parameters ---------- context : pipe2py.Context object _INPUT : twisted Deferred iterable of items or strings conf : { 'to-str': {'value': <delimiter>}, 'dedupe': {'type': 'bool', ...
13.99322
13.925429
1.004868
offline = conf.get('offline', {}).get('value') # TODO add async rate data fetching rate_data = get_offline_rate_data() if offline else get_rate_data() rates = parse_request(rate_data) splits = yield asyncGetSplits(_INPUT, conf, **cdicts(opts, kwargs)) parsed = yield asyncDispatch(splits, *g...
def asyncPipeExchangerate(context=None, _INPUT=None, conf=None, **kwargs)
A string module that asynchronously retrieves the current exchange rate for a given currency pair. Loopable. Parameters ---------- context : pipe2py.Context object _INPUT : twisted Deferred iterable of items or strings (base currency) conf : { 'quote': {'value': <'USD'>}, 'defau...
10.076847
10.138783
0.993891
offline = conf.get('offline', {}).get('value') rate_data = get_offline_rate_data(err=False) if offline else get_rate_data() rates = parse_request(rate_data) splits = get_splits(_INPUT, conf, **cdicts(opts, kwargs)) parsed = utils.dispatch(splits, *get_dispatch_funcs()) _OUTPUT = starmap(par...
def pipe_exchangerate(context=None, _INPUT=None, conf=None, **kwargs)
A string module that retrieves the current exchange rate for a given currency pair. Loopable. Parameters ---------- context : pipe2py.Context object _INPUT : iterable of items or strings (base currency) conf : { 'quote': {'value': <'USD'>}, 'default': {'value': <'USD'>}, ...
9.370102
9.549529
0.981211
splits = get_splits(_INPUT, conf, **cdicts(opts, kwargs)) parsed = utils.dispatch(splits, *get_dispatch_funcs()) _OUTPUT = starmap(parse_result, parsed) return _OUTPUT
def pipe_strtransform(context=None, _INPUT=None, conf=None, **kwargs)
A string module that splits a string into tokens delimited by separators. Loopable. Parameters ---------- context : pipe2py.Context object _INPUT : iterable of items or strings conf : {'transformation': {value': <'swapcase'>}} Returns ------- _OUTPUT : generator of tokenized string...
16.513052
18.60117
0.887743
value = utils.get_input(context, conf) while True: yield value
def pipe_privateinput(context=None, _INPUT=None, conf=None, **kwargs)
An input that prompts the user for some text and yields it forever. Not loopable. Parameters ---------- context : pipe2py.Context object _INPUT : unused conf : { 'name': {'value': 'parameter name'}, 'prompt': {'value': 'User prompt'}, 'default': {'value': 'default value'...
13.204105
14.662534
0.900534
conf = DotDict(conf) loop_with = kwargs.pop('with', None) date_format = conf.get('format', **kwargs) # timezone = conf.get('timezone', **kwargs) for item in _INPUT: _with = item.get(loop_with, **kwargs) if loop_with else item try: # todo: check that all PHP formats...
def pipe_dateformat(context=None, _INPUT=None, conf=None, **kwargs)
Formats a datetime value. Loopable. Parameters ---------- context : pipe2py.Context object _INPUT : pipedatebuilder pipe like object (iterable of date timetuples) conf : { 'format': {'value': <'%B %d, %Y'>}, 'timezone': {'value': <'EST'>} } Yields ------ _OUTPUT : f...
5.473547
5.645518
0.969539
path = DotDict(conf).get('path', **kwargs) for item in _INPUT: element = DotDict(item).get(path, **kwargs) for i in utils.gen_items(element): yield {'content': i} if item.get('forever'): # _INPUT is pipeforever and not a loop, # so we just yiel...
def pipe_subelement(context=None, _INPUT=None, conf=None, **kwargs)
An operator extracts select sub-elements from a feed. Not loopable. Parameters ---------- context : pipe2py.Context object _INPUT : pipe2py.modules pipe like object (iterable of items) conf : {'path': {'value': <element path>}} Yields ------ _OUTPUT : items
12.51466
12.811807
0.976807
conf = DotDict(conf) urls = utils.listize(conf['URL']) for item in _INPUT: for item_url in urls: url = utils.get_value(DotDict(item_url), DotDict(item), **kwargs) url = utils.get_abspath(url) if context and context.verbose: print "pipe_feeda...
def pipe_feedautodiscovery(context=None, _INPUT=None, conf=None, **kwargs)
A source that searches for and returns feed links found in a page. Loopable. Parameters ---------- context : pipe2py.Context object _INPUT : pipeforever pipe or an iterable of items or fields conf : URL -- url Yields ------ _OUTPUT : items
10.300124
10.248328
1.005054
value = utils.get_input(context, conf) value = utils.url_quote(value) while True: yield value
def pipe_urlinput(context=None, _INPUT=None, conf=None, **kwargs)
An input that prompts the user for a url and yields it forever. Not loopable. Parameters ---------- context : pipe2py.Context object _INPUT : unused conf : { 'name': {'value': 'parameter name'}, 'prompt': {'value': 'User prompt'}, 'default': {'value': 'default value'}, ...
8.535097
8.791811
0.970801
# todo: get from a config/env file url = "http://query.yahooapis.com/v1/public/yql" conf = DotDict(conf) query = conf['yqlquery'] for item in _INPUT: item = DotDict(item) yql = utils.get_value(query, item, **kwargs) # note: we use the default format of xml since json l...
def pipe_yql(context=None, _INPUT=None, conf=None, **kwargs)
A source that issues YQL queries. Loopable. Parameters ---------- context : pipe2py.Context object _INPUT : pipeforever pipe or an iterable of items or fields conf : yqlquery -- YQL query # todo: handle envURL Yields ------ _OUTPUT : query results
8.740616
8.717748
1.002623
value = utils.get_input(context, conf) try: value = int(value) except: value = 0 while True: yield value
def pipe_numberinput(context=None, _INPUT=None, conf=None, **kwargs)
An input that prompts the user for a number and yields it forever. Not loopable. Parameters ---------- context : pipe2py.Context object _INPUT : not used conf : { 'name': {'value': 'parameter name'}, 'prompt': {'value': 'User prompt'}, 'default': {'value': 'default value...
4.484286
5.837646
0.768167
pkwargs = cdicts(opts, kwargs) get_params = get_funcs(conf.get('PARAM', []), **kwargs)[0] get_paths = get_funcs(conf.get('PATH', []), **pkwargs)[0] get_base = get_funcs(conf['BASE'], listize=False, **pkwargs)[0] parse_params = utils.parse_params splits = get_splits(_INPUT, funcs=[get_params...
def pipe_urlbuilder(context=None, _INPUT=None, conf=None, **kwargs)
A url module that builds a url. Loopable. Parameters ---------- context : pipe2py.Context object _INPUT : pipeforever pipe or an iterable of items or fields conf : { 'PARAM': [ {'key': {'value': <'order'>}, 'value': {'value': <'desc'>}}, {'key': {'value': <'page'>}, ...
7.08032
6.610292
1.071105
conf = DotDict(conf) conf_sep = conf['separator'] conf_mode = conf['col_mode'] col_name = conf['col_name'] for item in _INPUT: item = DotDict(item) url = utils.get_value(conf['URL'], item, **kwargs) url = utils.get_abspath(url) separator = utils.get_value(conf_s...
def pipe_csv(context=None, _INPUT=None, conf=None, **kwargs)
A source that fetches and parses a csv file to yield items. Loopable. Parameters ---------- context : pipe2py.Context object _INPUT : pipeforever pipe or an iterable of items or fields conf : URL -- url skip -- number of header rows to skip col_mode -- column name source: row=header...
4.420496
4.026083
1.097964
splits = yield asyncGetSplits(_INPUT, conf['RULE'], **cdicts(opts, kwargs)) _OUTPUT = yield maybeDeferred(parse_results, splits, **kwargs) returnValue(_OUTPUT)
def asyncPipeRename(context=None, _INPUT=None, conf=None, **kwargs)
An operator that asynchronously renames or copies fields in the input source. Not loopable. Parameters ---------- context : pipe2py.Context object _INPUT : asyncPipe like object (twisted Deferred iterable of items) conf : { 'RULE': [ { 'op': {'value': 'rename...
23.572712
24.227474
0.972974
splits = get_splits(_INPUT, conf['RULE'], **cdicts(opts, kwargs)) _OUTPUT = parse_results(splits, **kwargs) return _OUTPUT
def pipe_rename(context=None, _INPUT=None, conf=None, **kwargs)
An operator that renames or copies fields in the input source. Not loopable. Parameters ---------- context : pipe2py.Context object _INPUT : pipe2py.modules pipe like object (iterable of items) conf : { 'RULE': [ { 'op': {'value': 'rename or copy'}, ...
20.029902
17.943232
1.116293
for item in reversed(list(_INPUT)): yield item
def pipe_reverse(context=None, _INPUT=None, conf=None, **kwargs)
An operator that reverses the order of source items. Not loopable. Not lazy. Parameters ---------- context : pipe2py.Context object _INPUT : pipe2py.modules pipe like object (iterable of items) conf : unused Yields ------ _OUTPUT : items
8.812396
11.388156
0.773821
count = len(list(_INPUT)) # todo: check all operators (not placeable in loops) while True: yield count
def pipe_count(context=None, _INPUT=None, conf=None, **kwargs)
An operator that counts the number of _INPUT items and yields it forever. Not loopable. Parameters ---------- context : pipe2py.Context object _INPUT : pipe2py.modules pipe like object (iterable of items) conf : not used Yields ------ _OUTPUT : number of items in the feed Exam...
29.912802
29.445593
1.015867
conf['start'] = conf.pop('from', dict.get(conf, 'start')) splits = yield asyncGetSplits(_INPUT, conf, **cdicts(opts, kwargs)) parsed = yield asyncDispatch(splits, *get_async_dispatch_funcs()) _OUTPUT = yield asyncStarMap(partial(maybeDeferred, parse_result), parsed) returnValue(iter(_OUTPUT))
def asyncPipeSubstr(context=None, _INPUT=None, conf=None, **kwargs)
A string module that asynchronously returns a substring. Loopable. Parameters ---------- context : pipe2py.Context object _INPUT : twisted Deferred iterable of items or strings conf : { 'from': {'type': 'number', value': <starting position>}, 'length': {'type': 'number', 'value': <c...
13.441789
15.579649
0.862779
conf['start'] = conf.pop('from', dict.get(conf, 'start')) splits = get_splits(_INPUT, conf, **cdicts(opts, kwargs)) parsed = utils.dispatch(splits, *get_dispatch_funcs()) _OUTPUT = starmap(parse_result, parsed) return _OUTPUT
def pipe_substr(context=None, _INPUT=None, conf=None, **kwargs)
A string module that returns a substring. Loopable. Parameters ---------- context : pipe2py.Context object _INPUT : iterable of items or strings conf : { 'from': {'type': 'number', value': <starting position>}, 'length': {'type': 'number', 'value': <count of characters to return>} ...
13.005397
13.8803
0.936968
ret = b'' if fmt == SER_BINARY: while x: x, r = divmod(x, 256) ret = six.int2byte(int(r)) + ret if outlen is not None: assert len(ret) <= outlen ret = ret.rjust(outlen, b'\0') return ret assert fmt == SER_COMPACT while x: ...
def serialize_number(x, fmt=SER_BINARY, outlen=None)
Serializes `x' to a string of length `outlen' in format `fmt'
1.993438
1.97468
1.009499
ret = gmpy.mpz(0) if fmt == SER_BINARY: if isinstance(s, six.text_type): raise ValueError( "Encode `s` to a bytestring yourself to" + " prevent problems with different default encodings") for c in s: ret *= 256 ret += byte2...
def deserialize_number(s, fmt=SER_BINARY)
Deserializes a number from a string `s' in format `fmt'
4.234901
4.260514
0.993988
if not a: return True p1 = p // 2 p2 = pow(a, p1, p) return p2 == 1
def mod_issquare(a, p)
Returns whether `a' is a square modulo p
4.143887
4.106461
1.009114
if a == 0: return 0 if not mod_issquare(a, p): raise ValueError n = 2 while mod_issquare(n, p): n += 1 q = p - 1 r = 0 while not q.getbit(r): r += 1 q = q >> r y = pow(n, q, p) h = q >> 1 b = pow(a, h, p) x = (a * b) % p b = (b * x...
def mod_root(a, p)
Return a root of `a' modulo p
3.028806
3.01774
1.003667
curve = (Curve.by_pk_len(len(pk)) if curve is None else Curve.by_name(curve)) p = curve.pubkey_from_string(pk, pk_format) return p.encrypt(s, mac_bytes)
def encrypt(s, pk, pk_format=SER_COMPACT, mac_bytes=10, curve=None)
Encrypts `s' for public key `pk'
4.118964
4.076684
1.010371
curve = Curve.by_name(curve) privkey = curve.passphrase_to_privkey(passphrase) return privkey.decrypt(s, mac_bytes)
def decrypt(s, passphrase, curve='secp160r1', mac_bytes=10)
Decrypts `s' with passphrase `passphrase'
3.294237
3.115738
1.057289
close_in, close_out = False, False in_file, out_file = in_path_or_file, out_path_or_file try: if stringlike(in_path_or_file): in_file = open(in_path_or_file, 'rb') close_in = True if stringlike(out_path_or_file): out_file = open(out_path_or_file, 'wb'...
def encrypt_file(in_path_or_file, out_path_or_file, pk, pk_format=SER_COMPACT, mac_bytes=10, chunk_size=4096, curve=None)
Encrypts `in_file' to `out_file' for pubkey `pk'
1.603554
1.619594
0.990096
close_in, close_out = False, False in_file, out_file = in_path_or_file, out_path_or_file try: if stringlike(in_path_or_file): in_file = open(in_path_or_file, 'rb') close_in = True if stringlike(out_path_or_file): out_file = open(out_path_or_file, 'wb'...
def decrypt_file(in_path_or_file, out_path_or_file, passphrase, curve='secp160r1', mac_bytes=10, chunk_size=4096)
Decrypts `in_file' to `out_file' with passphrase `passphrase'
1.609418
1.626138
0.989718
if isinstance(s, six.text_type): raise ValueError("Encode `s` to a bytestring yourself to" + " prevent problems with different default encodings") curve = (Curve.by_pk_len(len(pk)) if curve is None else Curve.by_name(curve)) p = curve.pubkey_from_string(pk,...
def verify(s, sig, pk, sig_format=SER_COMPACT, pk_format=SER_COMPACT, curve=None)
Verifies that `sig' is a signature of pubkey `pk' for the message `s'.
5.026433
5.109766
0.983691
if isinstance(s, six.text_type): raise ValueError("Encode `s` to a bytestring yourself to" + " prevent problems with different default encodings") curve = Curve.by_name(curve) privkey = curve.passphrase_to_privkey(passphrase) return privkey.sign(hashlib.sha512(s).di...
def sign(s, passphrase, sig_format=SER_COMPACT, curve='secp160r1')
Signs `s' with passphrase `passphrase'
4.934387
4.914984
1.003948
if randfunc is None: randfunc = Crypto.Random.new().read curve = Curve.by_name(curve) raw_privkey = randfunc(curve.order_len_bin) privkey = serialize_number(deserialize_number(raw_privkey), SER_COMPACT) pubkey = str(passphrase_to_pubkey(privkey)) return (privkey, pubkey)
def generate_keypair(curve='secp160r1', randfunc=None)
Convenience function to generate a random new keypair (passphrase, pubkey).
4.608019
4.840561
0.95196
s = deserialize_number(sig, sig_fmt) return self.p._ECDSA_verify(h, s)
def verify(self, h, sig, sig_fmt=SER_BINARY)
Verifies that `sig' is a signature for a message with SHA-512 hash `h'.
10.46898
9.947296
1.052445
ctx = EncryptionContext(f, self.p, mac_bytes) yield ctx ctx.finish()
def encrypt_to(self, f, mac_bytes=10)
Returns a file like object `ef'. Anything written to `ef' will be encrypted for this pubkey and written to `f'.
11.237281
10.785588
1.041879
if isinstance(s, six.text_type): raise ValueError( "Encode `s` to a bytestring yourself to" + " prevent problems with different default encodings") out = BytesIO() with self.encrypt_to(out, mac_bytes) as f: f.write(s) retur...
def encrypt(self, s, mac_bytes=10)
Encrypt `s' for this pubkey.
5.436167
5.140712
1.057474
ctx = DecryptionContext(self.curve, f, self, mac_bytes) yield ctx ctx.read()
def decrypt_from(self, f, mac_bytes=10)
Decrypts a message from f.
10.458449
11.840301
0.883293
outlen = (self.curve.sig_len_compact if sig_format == SER_COMPACT else self.curve.sig_len_bin) sig = self._ECDSA_sign(h) return serialize_number(sig, sig_format, outlen)
def sign(self, h, sig_format=SER_BINARY)
Signs the message with SHA-512 hash `h' with this private key.
5.302438
5.041009
1.051861
ctr = Crypto.Util.Counter.new(128, initial_value=0) cipher = Crypto.Cipher.AES.new(h, Crypto.Cipher.AES.MODE_CTR, counter=ctr) buf = cipher.encrypt(b'\0' * self.order_len_bin) return self._buf_to_exponent(buf)
def hash_to_exponent(self, h)
Converts a 32 byte hash to an exponent
4.556983
4.251001
1.071979
parser = argparse.ArgumentParser(description='The DomainTools CLI API Client') parser.add_argument('-u', '--username', dest='user', default='', help='API Username') parser.add_argument('-k', '--key', dest='key', default='', help='API Key') parser.add_argument('-c', '--credfile', dest='credentials',...
def parse(args=None)
Defines how to parse CLI arguments for the DomainTools API
2.486953
2.411372
1.031344
sys.stderr.write('Credentials are required to perform API calls.\n') sys.exit(1) api = API(user, key, https=arguments.pop('https'), verify_ssl=arguments.pop('verify_ssl'), rate_limit=arguments.pop('rate_limit')) response = getattr(api, arguments.pop('api_call'))(**arguments) o...
def run(): # pragma: no cover out_file, out_format, arguments = parse() user, key = arguments.pop('user', None), arguments.pop('key', None) if not user or not key
Defines how to start the CLI for the DomainTools API
4.086063
3.69053
1.107175
login_url = kwargs.pop('login_url', settings.LOGIN_URL) redirect_field_name = kwargs.pop('redirect_field_name', REDIRECT_FIELD_NAME) redirect_to_login = kwargs.pop('redirect_to_login', True) def decorate(view_func): def decorated(request, *args, **kwargs): if request.user.is_au...
def permission_required(perm, *lookup_variables, **kwargs)
Decorator for views that checks whether a user has a particular permission enabled, redirecting to the log-in page if necessary.
1.992293
1.996948
0.997669
kwargs['redirect_to_login'] = False return permission_required(perm, *args, **kwargs)
def permission_required_or_403(perm, *args, **kwargs)
Decorator that wraps the permission_required decorator and returns a permission denied (403) page instead of redirecting to the login URL.
4.621486
4.640318
0.995942
return PermissionsForObjectNode.handle_token(parser, token, approved=True, name='"permissions"')
def get_permissions(parser, token)
Retrieves all permissions associated with the given obj and user and assigns the result to a context variable. Syntax:: {% get_permissions obj %} {% for perm in permissions %} {{ perm }} {% endfor %} {% get_permissions obj as "my_permissions" %} {% get_perm...
20.030876
49.505268
0.404621
return PermissionsForObjectNode.handle_token(parser, token, approved=False, name='"permission_requests"')
def get_permission_requests(parser, token)
Retrieves all permissions requests associated with the given obj and user and assigns the result to a context variable. Syntax:: {% get_permission_requests obj %} {% for perm in permissions %} {{ perm }} {% endfor %} {% get_permission_requests obj as "my_permission...
15.985905
35.705959
0.44771
return PermissionForObjectNode.handle_token(parser, token, approved=True, name='"permission"')
def get_permission(parser, token)
Performs a permission check with the given signature, user and objects and assigns the result to a context variable. Syntax:: {% get_permission PERMISSION_LABEL.CHECK_NAME for USER and *OBJS [as VARNAME] %} {% get_permission "poll_permission.change_poll" for request.user and poll ...
17.220686
54.660404
0.315049
return PermissionForObjectNode.handle_token( parser, token, approved=False, name='"permission_request"')
def get_permission_request(parser, token)
Performs a permission request check with the given signature, user and objects and assigns the result to a context variable. Syntax:: {% get_permission_request PERMISSION_LABEL.CHECK_NAME for USER and *OBJS [as VARNAME] %} {% get_permission_request "poll_permission.change_poll" fo...
13.586755
33.48201
0.405793
user = context['request'].user if user.is_authenticated(): if (user.has_perm('authority.delete_foreign_permissions') or user.pk == perm.creator.pk): return base_link(context, perm, 'authority-delete-permission') return {'url': None}
def permission_delete_link(context, perm)
Renders a html link to the delete view of the given permission. Returns no content if the request-user has no permission to delete foreign permissions.
5.587586
5.165943
1.08162
user = context['request'].user if user.is_authenticated(): link_kwargs = base_link(context, perm, 'authority-delete-permission-request') if user.has_perm('authority.delete_permission'): link_kwargs['is_requestor'] = False return link_k...
def permission_request_delete_link(context, perm)
Renders a html link to the delete view of the given permission request. Returns no content if the request-user has no permission to delete foreign permissions.
4.670935
4.617736
1.01152
user = context['request'].user if user.is_authenticated(): if user.has_perm('authority.approve_permission_requests'): return base_link(context, perm, 'authority-approve-permission-request') return {'url': None}
def permission_request_approve_link(context, perm)
Renders a html link to the approve view of the given permission request. Returns no content if the request-user has no permission to delete foreign permissions.
4.918925
4.959754
0.991768
if var is None: return var if var[0] in ('"', "'") and var[-1] == var[0]: return var[1:-1] else: return template.Variable(var).resolve(context)
def resolve(self, var, context)
Resolves a variable out of context if it's not in quotes
2.826693
2.38121
1.187082
return self.get_for_model(obj).select_related( 'user', 'group', 'creator').filter(group=group, codename=perm, approved=approved)
def group_permissions(self, group, perm, obj, approved=True)
Get objects that have Group perm permission on
6.003654
6.476279
0.927022
user_perms = self.user_permissions(user, perm, obj, check_groups=False) if not user_perms.filter(object_id=obj.id): return perms = self.user_permissions(user, perm, obj).filter(object_id=obj.id) perms.delete()
def delete_user_permissions(self, user, perm, obj, check_groups=False)
Remove granular permission perm from user on an object instance
2.63099
2.678565
0.982238
parsed = self['parsed_whois'] flat = OrderedDict() for key in ('domain', 'created_date', 'updated_date', 'expired_date', 'statuses', 'name_servers'): value = parsed[key] flat[key] = ' | '.join(value) if type(value) in (list, tuple) else value registrar =...
def flattened(self)
Returns a flattened version of the parsed whois data
2.657484
2.440865
1.088747
if template_name is None: template_name = ('403.html', 'authority/403.html') context = { 'request_path': request.path, } if extra_context: context.update(extra_context) return HttpResponseForbidden(loader.render_to_string( template_name=template_name, con...
def permission_denied(request, template_name=None, extra_context=None)
Default 403 handler. Templates: `403.html` Context: request_path The path of the requested URL (e.g., '/app/pages/bad_page/')
2.162158
2.324774
0.930051
self.approved = True self.creator = creator self.save()
def approve(self, creator)
Approve granular permission request setting a Permission entry as approved=True for a specific action from an user on an object instance.
4.407917
4.531353
0.97276
import imp from django.conf import settings for app in settings.INSTALLED_APPS: try: __import__(app) app_path = sys.modules[app].__path__ except AttributeError: continue try: imp.find_module('permissions', app_path) except...
def autodiscover_modules()
Goes and imports the permissions submodule of every app in INSTALLED_APPS to make sure the permission set classes are registered correctly.
2.703971
2.567912
1.052984
if not self.user: return {}, {} group_pks = set(self.user.groups.values_list( 'pk', flat=True, )) perms = Permission.objects.filter( Q(user__pk=self.user.pk) | Q(group__pk__in=group_pks), ) user_permissions = {} ...
def _get_user_cached_perms(self)
Set up both the user and group caches.
2.935623
2.795118
1.050268
if not self.group: return {} perms = Permission.objects.filter( group=self.group, ) group_permissions = {} for perm in perms: group_permissions[( perm.object_id, perm.content_type_id, per...
def _get_group_cached_perms(self)
Set group cache.
3.154974
2.969315
1.062526
perm_cache, group_perm_cache = self._get_user_cached_perms() self.user._authority_perm_cache = perm_cache self.user._authority_group_perm_cache = group_perm_cache self.user._authority_perm_cache_filled = True
def _prime_user_perm_caches(self)
Prime both the user and group caches and put them on the ``self.user``. In addition add a cache filled flag on ``self.user``.
3.262973
2.477539
1.317022
perm_cache = self._get_group_cached_perms() self.group._authority_perm_cache = perm_cache self.group._authority_perm_cache_filled = True
def _prime_group_perm_caches(self)
Prime the group cache and put them on the ``self.group``. In addition add a cache filled flag on ``self.group``.
6.080556
3.796058
1.601808
# Check to see if the cache has been primed. if not self.user: return {} cache_filled = getattr( self.user, '_authority_perm_cache_filled', False, ) if cache_filled: # Don't really like the name for this, but th...
def _user_perm_cache(self)
cached_permissions will generate the cache in a lazy fashion.
5.000915
4.507305
1.109513
# Check to see if the cache has been primed. if not self.group: return {} cache_filled = getattr( self.group, '_authority_perm_cache_filled', False, ) if cache_filled: # Don't really like the name for this, but ...
def _group_perm_cache(self)
cached_permissions will generate the cache in a lazy fashion.
5.107403
4.600014
1.110302
# Check to see if the cache has been primed. if not self.user: return {} cache_filled = getattr( self.user, '_authority_perm_cache_filled', False, ) if cache_filled: return self.user._authority_group_perm_cache ...
def _user_group_perm_cache(self)
cached_permissions will generate the cache in a lazy fashion.
3.940998
3.546483
1.111241
if self.user: self.user._authority_perm_cache_filled = False if self.group: self.group._authority_perm_cache_filled = False
def invalidate_permissions_cache(self)
In the event that the Permission table is changed during the use of a permission the Permission cache will need to be invalidated and regenerated. By calling this method the invalidation will occur, and the next time the cached_permissions is used the cache will be re-primed.
4.436833
4.763333
0.931456
if not self.group: return False if self.use_smart_cache: content_type_pk = Permission.objects.get_content_type(obj).pk def _group_has_perms(cached_perms): # Check to see if the permission is in the cache. return cached_perms....
def has_group_perms(self, perm, obj, approved)
Check if group has the permission for the given object
4.063348
4.046212
1.004235
if self.user: if self.has_user_perms(perm, obj, approved, check_groups): return True if self.group: return self.has_group_perms(perm, obj, approved) return False
def has_perm(self, perm, obj, check_groups=True, approved=True)
Check if user has the permission for the given object
2.665045
2.708359
0.984007
return self.has_perm(perm, obj, check_groups, False)
def requested_perm(self, perm, obj, check_groups=True)
Check if user requested a permission for the given object
4.802845
4.771919
1.006481
result = [] if not content_object: content_objects = (self.model,) elif not isinstance(content_object, (list, tuple)): content_objects = (content_object,) else: content_objects = content_object if not check: checks = self...
def assign(self, check=None, content_object=None, generic=False)
Assign a permission to a user. To assign permission for all checks: let check=None. To assign permission for all objects: let content_object=None. If generic is True then "check" will be suffixed with _modelname.
2.409981
2.384049
1.010878
return '|'.join(items) if type(items) in (list, tuple, set) else items
def delimited(items, character='|')
Returns a character delimited version of the provided list as a Python string
4.591768
4.543694
1.01058
self.limits_set = True for product in self.account_information(): self.limits[product['id']] = {'interval': timedelta(seconds=60 / float(product['per_minute_limit']))}
def _rate_limit(self)
Pulls in and enforces the latest rate limits for the specified user
11.084034
9.250568
1.1982
if product != 'account-information' and self.rate_limit and not self.limits_set and not self.limits: self._rate_limit() uri = '/'.join(('{0}://api.domaintools.com'.format('https' if self.https else 'http'), path.lstrip('/'))) parameters = self.default_parameters.copy() ...
def _results(self, product, path, cls=Results, **kwargs)
Returns _results for the specified API path with the specified **kwargs parameters
3.733629
3.641837
1.025205
return self._results('mark-alert', '/v1/mark-alert', query=delimited(query), exclude=delimited(exclude), domain_status=domain_status, days_back=days_back, items_path=('alerts', ), **kwargs)
def brand_monitor(self, query, exclude=[], domain_status=None, days_back=None, **kwargs)
Pass in one or more terms as a list or separated by the pipe character ( | )
8.345089
7.933167
1.051924
return self._results('domain-search', '/v2/domain-search', query=delimited(query, ' '), exclude_query=delimited(exclude_query, ' '), max_length=max_length, min_length=min_length, has_hyphen=has_hyphen, has_number=has_number, ...
def domain_search(self, query, exclude_query=[], max_length=25, min_length=2, has_hyphen=True, has_number=True, active_only=False, deleted_only=False, anchor_left=False, anchor_right=False, page=1, **kwargs)
Each term in the query string must be at least three characters long. Pass in a list or use spaces to separate multiple terms.
2.363158
2.347993
1.006459
return self._results('domain-suggestions', '/v1/domain-suggestions', query=delimited(query, ' '), items_path=('suggestions', ), **kwargs)
def domain_suggestions(self, query, **kwargs)
Passed in name must be at least two characters long. Use a list or spaces to separate multiple terms.
14.958274
14.633011
1.022228
return self._results('hosting-history', '/v1/{0}/hosting-history'.format(query), cls=GroupedIterable, **kwargs)
def hosting_history(self, query, **kwargs)
Returns the hosting history from the given domain name
15.300931
17.458099
0.876437
return self._results('ip-monitor', '/v1/ip-monitor', query=query, days_back=days_back, page=page, items_path=('alerts', ), **kwargs)
def ip_monitor(self, query, days_back=0, page=1, **kwargs)
Pass in the IP Address you wish to query ( i.e. 199.30.228.112 ).
6.70945
6.510137
1.030616
return self._results('ip-registrant-monitor', '/v1/ip-registrant-monitor', query=query, days_back=days_back, search_type=search_type, server=server, country=country, org=org, page=page, include_total_count=include_total_count, **kwargs)
def ip_registrant_monitor(self, query, days_back=0, search_type="all", server=None, country=None, org=None, page=1, include_total_count=False, **kwargs)
Query based on free text query terms
2.078388
2.076198
1.001055
return self._results('name-server-monitor', '/v1/name-server-monitor', query=query, days_back=days_back, page=page, items_path=('alerts', ), **kwargs)
def name_server_monitor(self, query, days_back=0, page=1, **kwargs)
Pass in the hostname of the Name Server you wish to query ( i.e. dynect.net ).
6.193737
5.890042
1.051561
return self._results('parsed-whois', '/v1/{0}/whois/parsed'.format(query), cls=ParsedWhois, **kwargs)
def parsed_whois(self, query, **kwargs)
Pass in a domain name
8.607859
8.744533
0.98437
return self._results('registrant-alert', '/v1/registrant-alert', query=delimited(query), exclude=delimited(exclude), days_back=days_back, limit=limit, items_path=('alerts', ), **kwargs)
def registrant_monitor(self, query, exclude=[], days_back=0, limit=None, **kwargs)
One or more terms as a Python list or separated by the pipe character ( | ).
7.684865
7.296769
1.053187
return self._results('reputation', '/v1/reputation', domain=query, include_reasons=include_reasons, cls=Reputation, **kwargs)
def reputation(self, query, include_reasons=False, **kwargs)
Pass in a domain name to see its reputation score
6.845622
5.473807
1.250614
return self._results('reverse-ip', '/v1/{0}/reverse-ip'.format(domain), limit=limit, **kwargs)
def reverse_ip(self, domain=None, limit=None, **kwargs)
Pass in a domain name.
6.018848
5.572904
1.08002
return self._results('reverse-ip', '/v1/{0}/host-domains'.format(ip), limit=limit, **kwargs)
def host_domains(self, ip=None, limit=None, **kwargs)
Pass in an IP address.
8.411223
7.769381
1.082612
if (ip and query) or not (ip or query): raise ValueError('Query or IP Address (but not both) must be defined') return self._results('reverse-ip-whois', '/v1/reverse-ip-whois', query=query, ip=ip, country=country, server=server, include_total_count=includ...
def reverse_ip_whois(self, query=None, ip=None, country=None, server=None, include_total_count=False, page=1, **kwargs)
Pass in an IP address or a list of free text query terms.
3.988384
3.864511
1.032054
return self._results('reverse-name-server', '/v1/{0}/name-server-domains'.format(query), items_path=('primary_domains', ), limit=limit, **kwargs)
def reverse_name_server(self, query, limit=None, **kwargs)
Pass in a domain name or a name server.
12.768602
12.191342
1.04735
return self._results('reverse-whois', '/v1/reverse-whois', terms=delimited(query), exclude=delimited(exclude), scope=scope, mode=mode, **kwargs)
def reverse_whois(self, query, exclude=[], scope='current', mode=None, **kwargs)
List of one or more terms to search for in the Whois record, as a Python list or separated with the pipe character ( | ).
6.97172
6.318407
1.103398
return self._results('whois-history', '/v1/{0}/whois/history'.format(query), items_path=('history', ), **kwargs)
def whois_history(self, query, **kwargs)
Pass in a domain name.
9.657083
9.256229
1.043306
return self._results('phisheye', '/v1/phisheye', query=query, days_back=days_back, items_path=('domains', ), **kwargs)
def phisheye(self, query, days_back=None, **kwargs)
Returns domain results for the specified term for today or the specified number of days_back. Terms must be setup for monitoring via the web interface: https://research.domaintools.com/phisheye. NOTE: Properties of a domain are only provided if we have been able to obtain them. M...
7.753328
6.616404
1.171834
return self._results('phisheye_term_list', '/v1/phisheye/term-list', include_inactive=include_inactive, items_path=('terms', ), **kwargs)
def phisheye_term_list(self, include_inactive=False, **kwargs)
Provides a list of terms that are set up for this account. This call is not charged against your API usage limit. NOTE: The terms must be configured in the PhishEye web interface: https://research.domaintools.com/phisheye. There is no API call to set up the terms.
5.636481
5.952983
0.946833
if ((not domain and not ip and not email and not nameserver and not registrar and not registrant and not registrant_org and not kwargs)): raise ValueError('At least one search term must be specified') return self._results('iris', '/v1/iris', domain=domain, ip=ip, email...
def iris(self, domain=None, ip=None, email=None, nameserver=None, registrar=None, registrant=None, registrant_org=None, **kwargs)
Performs a search for the provided search terms ANDed together, returning the pivot engine row data for the resulting domains.
2.636079
2.615583
1.007836
return self._results('risk', '/v1/risk', items_path=('components', ), domain=domain, cls=Reputation, **kwargs)
def risk(self, domain, **kwargs)
Returns back the risk score for a given domain
23.650227
22.66658
1.043396
return self._results('risk-evidence', '/v1/risk/evidence/', items_path=('components', ), domain=domain, **kwargs)
def risk_evidence(self, domain, **kwargs)
Returns back the detailed risk evidence associated with a given domain
17.413773
15.815706
1.101043
if not domains: raise ValueError('One or more domains to enrich must be provided') domains = ','.join(domains) data_updated_after = kwargs.get('data_updated_after', None) if hasattr(data_updated_after, 'strftime'): data_updated_after = data_updated_after...
def iris_enrich(self, *domains, **kwargs)
Returns back enriched data related to the specified domains using our Iris Enrich service each domain should be passed in as an un-named argument to the method: iris_enrich('domaintools.com', 'google.com') api.iris_enrich(*DOMAIN_LIST)['results_count'] Returns the number of results...
3.603078
3.715137
0.969837
if not (kwargs or domains): raise ValueError('Need to define investigation using kwarg filters or domains') if type(domains) in (list, tuple): domains = ','.join(domains) if hasattr(data_updated_after, 'strftime'): data_updated_after = data_updated_a...
def iris_investigate(self, domains=None, data_updated_after=None, expiration_date=None, create_date=None, active=None, **kwargs)
Returns back a list of domains based on the provided filters. The following filters are available beyond what is parameterized as kwargs: - ip: Search for domains having this IP. - email: Search for domains with this email in their data. - email_domain: Search for domains wh...
2.654257
2.767452
0.959098
url = 'https://finance.yahoo.com/quote/%s/history' % (self.ticker) r = requests.get(url) txt = r.content cookie = r.cookies['B'] pattern = re.compile('.*"CrumbStore":\{"crumb":"(?P<crumb>[^"]+)"\}') for line in txt.splitlines(): m = pattern.match(lin...
def init(self)
Returns a tuple pair of cookie and crumb used in the request
3.05137
2.690872
1.133971
if self.interval not in ["1d", "1wk", "1mo"]: raise ValueError("Incorrect interval: valid intervals are 1d, 1wk, 1mo") url = self.api_url % (self.ticker, self.start, self.end, self.interval, events, self.crumb) data = requests.get(url, cookies={'B':self.cookie}) co...
def getData(self, events)
Returns a list of historical data from Yahoo Finance
4.002709
3.324314
1.204071
if self.disk_mounter == 'auto': methods = [] def add_method_if_exists(method): if (method == 'avfs' and _util.command_exists('avfsd')) or \ _util.command_exists(method): methods.append(method) if self.read...
def _get_mount_methods(self, disk_type)
Finds which mount methods are suitable for the specified disk type. Returns a list of all suitable mount methods.
2.847806
2.911565
0.978102
self._paths['avfs'] = tempfile.mkdtemp(prefix='image_mounter_avfs_') # start by calling the mountavfs command to initialize avfs _util.check_call_(['avfsd', self._paths['avfs'], '-o', 'allow_other'], stdout=subprocess.PIPE) # no multifile support for avfs avfspath = s...
def _mount_avfs(self)
Mounts the AVFS filesystem.
5.046511
4.985053
1.012328