code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
command = [b'ZREVRANGE', key, start, stop] if with_scores: command += ['WITHSCORES'] return self._execute(command)
def zrevrange(self, key, start=0, stop=-1, with_scores=False)
Returns the specified range of elements in the sorted set stored at key. The elements are considered to be ordered from the highest to the lowest score. Descending lexicographical order is used for elements with equal score. Apart from the reversed ordering, :py:meth:`~tredis.Client.zre...
3.118
4.517474
0.690209
'Returns the cache key depending on its type.' base = '{0}.feedjack'.format(settings.CACHE_MIDDLEWARE_KEY_PREFIX) if stype == T_HOST: return '{0}.hostcache'.format(base) elif stype == T_ITEM: return '{0}.{1}.item.{2}'.format(base, site_id, str2md5(key)) elif stype == T_META: return '{0}.{1}.meta'.format(base, site...
def getkey(stype, site_id=None, key=None)
Returns the cache key depending on its type.
3.674155
3.187515
1.15267
'Get adaptive interval between checks for a feed.' val = cache.get(getkey( T_INTERVAL, key=feed_interval_key(feed_id, parameters) )) return val if isinstance(val, tuple) else (val, None)
def feed_interval_get(feed_id, parameters)
Get adaptive interval between checks for a feed.
12.67216
8.170479
1.550969
'Set adaptive interval between checks for a feed.' cache.set(getkey( T_INTERVAL, key=feed_interval_key(feed_id, parameters) ), (interval, interval_ts))
def feed_interval_set(feed_id, parameters, interval, interval_ts)
Set adaptive interval between checks for a feed.
19.236698
10.766941
1.786645
'Invalidate cached adaptive interval value.' cache.delete(getkey( T_INTERVAL, key=feed_interval_key(feed_id, parameters) ))
def feed_interval_delete(feed_id, parameters)
Invalidate cached adaptive interval value.
35.132248
16.080832
2.184728
'''Sets cache data for a site. All keys related to a site are stored in a meta key. This key is per-site.''' tkey = getkey(T_ITEM, site.id, key) mkey = getkey(T_META, site.id) tmp = cache.get(mkey) longdur = 365*24*60*60 if not tmp: tmp = [tkey] cache.set(mkey, [tkey], longdur) elif tkey not in tmp: tmp....
def cache_set(site, key, data)
Sets cache data for a site. All keys related to a site are stored in a meta key. This key is per-site.
4.08474
2.919112
1.399309
'Removes all cache data from a site.' mkey = getkey(T_META, site_id) tmp = cache.get(mkey) if not tmp: return for tkey in tmp: cache.delete(tkey) cache.delete(mkey)
def cache_delsite(site_id)
Removes all cache data from a site.
4.685154
4.101141
1.142403
cipher_text = _Ntlm1Session.encrypt(self, message) signature = _Ntlm1Session.sign(self, message) return cipher_text, signature
def wrap(self, message)
NTM GSSwrap() :param message: The message to be encrypted :return: The signed and encrypted message
6.190389
5.211558
1.187819
plain_text = _Ntlm1Session.decrypt(self, message) _Ntlm1Session.verify(self, plain_text, signature) return plain_text
def unwrap(self, message, signature)
NTLM GSSUnwrap() :param message: The message to be encrypted :return: The signed and encrypted message
6.147993
6.186764
0.993733
if flags & NegotiateFlag.NTLMSSP_KEY_128: return key if flags & NegotiateFlag.NTLMSSP_NEGOTIATE_56: return key[:7] else: return key[:5]
def _weaken_key(flags, key)
NOTE: Key weakening in NTLM2 (Extended Session Security) is performed simply by truncating the master key (or secondary master key, if key exchange is performed) to the appropriate length. 128-bit keys are supported under NTLM2. In this case, the master key is used directly in the generation of subkeys ...
3.313484
3.314126
0.999806
hmac_context = hmac.new(self.outgoing_signing_key) hmac_context.update(struct.pack('<i', self.outgoing_sequence) + message) # If a key exchange key is negotiated the first 8 bytes of the HMAC MD5 are encrypted with RC4 if self.key_exchange: checksum = self.outgoing_...
def sign(self, message)
Generates a signature for the supplied message using NTLM2 Session Security Note: [MS-NLMP] Section 3.4.4 The message signature for NTLM with extended session security is a 16-byte value that contains the following components, as described by the NTLMSSP_MESSAGE_SIGNATURE structure: - A...
5.450241
5.076039
1.073719
# Parse the signature header mac = _Ntlm2MessageSignature() mac.from_string(signature) # validate the sequence if mac['sequence'] != self.incoming_sequence: raise Exception("The message was not received in the correct sequence.") # extract the suppl...
def verify(self, message, signature)
Verified the signature attached to the supplied message using NTLM2 Session Security :param message: The message whose signature will verified :return: True if the signature is valid, otherwise False
5.504908
5.078074
1.084054
cipher_text = _Ntlm2Session.encrypt(self, message) signature = _Ntlm2Session.sign(self, message) return cipher_text, signature
def wrap(self, message)
NTM GSSwrap() :param message: The message to be encrypted :return: A Tuple containing the signature and the encrypted messaging
6.287956
5.04285
1.246905
plain_text = _Ntlm2Session.decrypt(self, message) _Ntlm2Session.verify(self, plain_text, signature) return plain_text
def unwrap(self, message, signature)
NTLM GSSUnwrap() :param message: The message to be decrypted :return: The decrypted message
6.023303
6.178312
0.974911
# allow inject for testing purposes now = now if now else time.time() try: self.connections.remove(connection) except ValueError: # connection not alive or another thread marked it already, ignore return else: dead_count = ...
def mark_dead(self, connection, now=None)
Mark the connection as dead (failed). Remove it from the live pool and put it on a timeout. :arg connection: the failed instance
4.931523
4.902586
1.005902
# no dead connections if self.dead.empty(): return try: # retrieve a connection to check timeout, connection = self.dead.get(block=False) except Empty: # other thread has been faster and the queue is now empty return ...
def resurrect(self, force=False)
Attempt to resurrect a connection from the dead pool. It will try to locate one (not all) eligible (it's timeout is over) connection to return to th live pool. :arg force: resurrect a connection even if there is none eligible (used when we have no live connections)
6.398914
5.845136
1.094742
self.resurrect() # no live nodes, resurrect one by force if not self.connections: self.resurrect(True) connection = self.selector.select(self.connections) return connection
def get_connection(self)
Return a connection from the pool using the `ConnectionSelector` instance. It tries to resurrect eligible connections, forces a resurrection when no connections are availible and passes the list of live connections to the selector instance to choose from. Returns a connection i...
11.62867
7.517016
1.546979
def outer(view_fn): @self.route(*args, **kwargs) def inner(*args, **kwargs): fn_args = getargspec(view_fn) try: idx = fn_args.args.index(_ARG_KEY) except ValueError: idx = -1 if idx > -1: if 'error'...
def _canvas_route(self, *args, **kwargs)
Decorator for canvas route
3.38608
3.295373
1.027526
decoded_sig = _decode(encoded_sig) decoded_data = loads(_decode(encoded_data)) if decoded_sig != hmac.new(app.config['CANVAS_CLIENT_SECRET'], encoded_data, sha256).digest(): raise ValueError("sig doesn't match hash") return decoded_sig, decoded_data
def _decode_signed_user(encoded_sig, encoded_data)
Decodes the ``POST``ed signed data
4.127053
3.963105
1.041368
url = '%s%s?access_token=%s' % ( 'https://graph.facebook.com', path, self['oauth_token']) req = Request(url, data=data) req.get_method = lambda: method return loads(urlopen(req).read())
def request(self, path, data=None, method='GET')
Convenience Facebook request function. Utility function to request resources via the graph API, with the format expected by Facebook.
3.18605
3.159992
1.008246
perms = self.request('/me/permissions')['data'][0].keys() return all(k in perms for k in app.config[ 'CANVAS_SCOPE'].split(','))
def has_permissions(self)
Check current user permission set Checks the current user permission set against the one being requested by the application.
12.828643
12.987896
0.987738
'''Skip posts with exactly same GUID. Parameter: comparison timespan, seconds (int, 0 = inf, default: {0}).''' from feedjack.models import Post if isinstance(parameter, types.StringTypes): parameter = int(parameter.strip()) similar = Post.objects.filtered(for_display=False)\ .exclude(id=post.id).filter(guid=pos...
def same_guid(post, parameter=DEFAULT_SIMILARITY_TIMESPAN)
Skip posts with exactly same GUID. Parameter: comparison timespan, seconds (int, 0 = inf, default: {0}).
5.878362
3.200004
1.836986
'''Skip posts with fuzzy-matched (threshold = levenshtein distance / length) title. Parameters (comma-delimited): minimal threshold, at which values are considired similar (float, 0 < x < 1, default: {0}); comparison timespan, seconds (int, 0 = inf, default: {1}).''' from feedjack.models import Post threshol...
def similar_title(post, parameter=None)
Skip posts with fuzzy-matched (threshold = levenshtein distance / length) title. Parameters (comma-delimited): minimal threshold, at which values are considired similar (float, 0 < x < 1, default: {0}); comparison timespan, seconds (int, 0 = inf, default: {1}).
5.867453
2.54964
2.301287
'''Override URL of the Post to point to url of the first enclosure with href attribute non-empty and type matching specified regexp parameter (empty=any). Missing "type" attribute for enclosure will be matched as an empty string. If none of the enclosures match, link won't be updated.''' for e in (post.enclosu...
def pick_enclosure_link(post, parameter='')
Override URL of the Post to point to url of the first enclosure with href attribute non-empty and type matching specified regexp parameter (empty=any). Missing "type" attribute for enclosure will be matched as an empty string. If none of the enclosures match, link won't be updated.
8.802096
2.097756
4.195958
logging.addLevelName(value, name) setattr(logging, name, value)
def add_log_level(value, name)
Add a new log level to the :mod:`logging` module. :param value: The log level's number (an integer). :param name: The name for the log level (a string).
2.710177
6.86874
0.394567
if self.isEnabledFor(NOTICE): self._log(NOTICE, msg, args, **kw)
def notice(self, msg, *args, **kw)
Log a message with level :data:`NOTICE`. The arguments are interpreted as for :func:`logging.debug()`.
2.97815
2.716151
1.09646
if self.isEnabledFor(SPAM): self._log(SPAM, msg, args, **kw)
def spam(self, msg, *args, **kw)
Log a message with level :data:`SPAM`. The arguments are interpreted as for :func:`logging.debug()`.
3.140602
2.453342
1.280132
if self.isEnabledFor(SUCCESS): self._log(SUCCESS, msg, args, **kw)
def success(self, msg, *args, **kw)
Log a message with level :data:`SUCCESS`. The arguments are interpreted as for :func:`logging.debug()`.
3.219873
2.68852
1.197638
if self.isEnabledFor(VERBOSE): self._log(VERBOSE, msg, args, **kw)
def verbose(self, msg, *args, **kw)
Log a message with level :data:`VERBOSE`. The arguments are interpreted as for :func:`logging.debug()`.
2.666302
2.525676
1.055679
if calculator_name.lower() == "gpaw" or calculator_name is None: return "from gpaw import GPAW as custom_calculator" elif calculator_name.lower() == "espresso": return "from espresso import espresso as custom_calculator" else: possibilities = {"abinit":"abinit.Abinit", ...
def get_calculator_impstr(calculator_name)
Returns the import string for the calculator
3.096367
3.064935
1.010255
possibilities = {"bfgs":"BFGS", "bfgslinesearch":"BFGSLineSearch", "fire":"FIRE", "goodoldquasinewton":"GoodOldQuasiNewton", "hesslbfgs":"HessLBFGS", "lbfgs":"LBFGS", "lbfgslinesearch":...
def get_optimizer_impstr(optimizer_name)
Returns the import string for the optimizer
3.105737
3.052619
1.017401
return_list = [] for getter in getters: if isinstance(getter,basestring): out_args = "" method_name = getter else: method_name, a = getter out_args = convert_the_args(a) return_list.appen...
def convert_the_getters(getters)
A function used to prepare the arguments of calculator and atoms getter methods
3.947761
3.754549
1.051461
if not raw_args: return "" if isinstance(raw_args,dict): out_args = ", ".join([ "{}={}".format(k,v) for k,v in raw_args.iteritems() ]) elif isinstance(raw_args,(list,tuple)): new_list = [] for x in raw_args: if isinstance(x,basestring): ...
def convert_the_args(raw_args)
Function used to convert the arguments of methods
2.488925
2.462378
1.010781
proc = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd) (stdout, stderr) = proc.communicate(command_input) if proc.returncode != 0: sys.stderr.write('ABOR...
def runcmd(command, command_input=None, cwd=None)
Run a command, potentially sending stdin, and capturing stdout/err.
2.092365
2.160424
0.968497
top = os.path.join(os.path.dirname(__file__)) doc = os.path.join(top, 'doc') # Markdown to ronn to man page man_md = os.path.join(doc, 'authprogs.md') man_ronn = os.path.join(doc, 'authprogs.1.ronn') man_1 = os.path.join(doc, 'authprogs.1') # Create man...
def dd_docs(self)
Copy and convert various documentation files.
3.295454
3.223729
1.022249
for filename in self.created: if os.path.exists(filename): os.unlink(filename)
def rm_docs(self)
Remove converted docs.
4.988518
4.146093
1.203185
quality_mapping = { # ascending in terms of quality 'lo': 0, 'hi': 1 } entry = scraped_info['tracks'][0] ''' The structure of entry is as follows: 'src': { 'hi': [ { 'src': 'http://v.iplsc.com...
def extract_entry(scraped_info)
Transform scraped_info dictionary into an entry, under the assumption that there is only one track in 'track' list, since each video/audio is instantiated individually on the RMF website and each of them is scraped independently, so there shouldn't be cases when there are 2 unrelated tracks in o...
5.168229
5.229732
0.98824
if request.method == 'GET': return get(request, obj_id) elif request.method == 'PUT': getPutData(request) return put(request, obj_id)
def index(request, obj_id)
Handles a request based on method and calls the appropriate function
3.429225
2.854882
1.201179
res = Result() c = Comment.objects.get(pk=obj_id) res.append(commentToJson(c)) return JsonResponse(res.asDict())
def get(request, obj_id)
Returns a serialized object :param obj_id: ID of comment object :type obj_id: int :returns: json
5.753578
5.266332
1.092521
data = request.POST or json.loads(request.body)['body'] guid = data.get('guid', None) res = Result() if guid: obj = getObjectsFromGuids([guid,])[0] comment = Comment() comment.comment = data.get('comment', 'No comment') comment.user = request.user comment.us...
def post(request)
Returns a serialized object
3.784128
3.826491
0.988929
res = Result() c = Comment.objects.get(pk=obj_id) data = request.PUT or json.loads(request.body)['body'] content = data.get('comment', None) if content: c.comment = content c.save() res.append(commentToJson(c)) return JsonResponse(res.asDict())
def put(request, obj_id)
Updates the content of a comment :param obj_id: ID of comment object :type obj_id: int :returns: json
4.693025
4.283233
1.095674
if request.method == 'POST': return post(request) comments = [] guid = request.GET.get('guid', None) if guid: obj = getObjectsFromGuids([guid])[0] if obj.AssetType == 1: model = 'image' else: model = 'video' contenttype = ContentType...
def commentList(request)
Returns a rendered list of comments :returns: html
3.628092
4.060132
0.89359
if not obj.author.frog_prefs.get().json()['emailComments']: return if obj.author == request.user: return html = render_to_string('frog/comment_email.html', { 'user': comment.user, 'comment': comment.comment, 'object': obj, 'action_type': 'commented on',...
def emailComment(comment, obj, request)
Send an email to the author about a new comment
4.478905
4.405344
1.016698
def format_response(result): values = [] for row in result.decode('utf-8').split('\n'): if not row: continue parts = row.split(' ') slots = [] for slot in parts[8:]: if '-' i...
def cluster_nodes(self)
Each node in a Redis Cluster has its view of the current cluster configuration, given by the set of known nodes, the state of the connection we have with such nodes, their flags, properties and assigned slots, and so forth. ``CLUSTER NODES`` provides all this information, that is, the c...
2.975976
2.614889
1.138089
return self._execute([b'SADD', key] + list(members), len(members))
def sadd(self, key, *members)
Add the specified members to the set stored at key. Specified members that are already a member of this set are ignored. If key does not exist, a new set is created before adding the specified members. An error is returned when the value stored at key is not a set. Returns :data:`True`...
7.095895
8.83029
0.803586
return self._execute([b'SDIFFSTORE', destination] + list(keys))
def sdiffstore(self, destination, *keys)
This command is equal to :meth:`~tredis.RedisClient.sdiff`, but instead of returning the resulting set, it is stored in destination. If destination already exists, it is overwritten. .. note:: **Time complexity**: ``O(N)`` where ``N`` is the total number of elements in a...
6.230212
7.551608
0.825018
return self._execute([b'SINTERSTORE', destination] + list(keys))
def sinterstore(self, destination, *keys)
This command is equal to :meth:`~tredis.RedisClient.sinter`, but instead of returning the resulting set, it is stored in destination. If destination already exists, it is overwritten. .. note:: **Time complexity**: ``O(N*M)`` worst case where ``N`` is the cardinality of ...
5.209073
7.510097
0.693609
return self._execute([b'SMOVE', source, destination, member], 1)
def smove(self, source, destination, member)
Move member from the set at source to the set at destination. This operation is atomic. In every given moment the element will appear to be a member of source or destination for other clients. If the source set does not exist or does not contain the specified element, no operation is pe...
7.317035
8.095577
0.903831
command = [b'SPOP', key] if count: # pragma: nocover command.append(ascii(count).encode('ascii')) return self._execute(command)
def spop(self, key, count=None)
Removes and returns one or more random elements from the set value store at key. This operation is similar to :meth:`~tredis.RedisClient.srandmember`, that returns one or more random elements from a set but does not remove it. The count argument will be available in a later ver...
6.531502
8.017473
0.814658
command = [b'SRANDMEMBER', key] if count: command.append(ascii(count).encode('ascii')) return self._execute(command)
def srandmember(self, key, count=None)
When called with just the key argument, return a random element from the set value stored at key. Starting from Redis version 2.6, when called with the additional count argument, return an array of count distinct elements if count is positive. If called with a negative count the behavio...
4.315666
7.471354
0.577628
return self._execute([b'SREM', key] + list(members), len(members))
def srem(self, key, *members)
Remove the specified members from the set stored at key. Specified members that are not a member of this set are ignored. If key does not exist, it is treated as an empty set and this command returns ``0``. An error is returned when the value stored at key is not a set. Returns :data:`...
6.607089
7.43725
0.888378
def format_response(value): return int(value[0]), value[1] command = [b'SSCAN', key, ascii(cursor).encode('ascii')] if pattern: command += [b'MATCH', pattern] if count: command += [b'COUNT', ascii(count).encode('ascii')] ...
def sscan(self, key, cursor=0, pattern=None, count=None)
The :meth:`~tredis.RedisClient.sscan` command and the closely related commands :meth:`~tredis.RedisClient.scan`, :meth:`~tredis.RedisClient.hscan` and :meth:`~tredis.RedisClient.zscan` are used in order to incrementally iterate over a collection of elements. - :meth:`~tredis.Red...
3.790033
3.869317
0.97951
return self._execute([b'SUNIONSTORE', destination] + list(keys))
def sunionstore(self, destination, *keys)
This command is equal to :meth:`~tredis.RedisClient.sunion`, but instead of returning the resulting set, it is stored in destination. If destination already exists, it is overwritten. .. note:: **Time complexity**: ``O(N)`` where ``N`` is the total number of elements in ...
5.370385
7.677519
0.699495
match = re.match(self._VALID_URL, self.url) if match: return match.group('video_id') else: raise VideoIdNotMatchedError
def _extract_id(self) -> str
Get video_id needed to obtain the real_url of the video. Raises: VideoIdNotMatchedError: If video_id is not matched with regular expression.
5.99012
3.094128
1.935964
raw_date = raw_info.date date = datetime.strptime(raw_date, '%Y-%m-%d %H:%M') # 2018-04-05 17:00 video_info = raw_info._replace(date=date) return video_info
def _process_info(raw_info: VideoInfo) -> VideoInfo
Process raw information about the video (parse date, etc.).
3.013792
2.74756
1.096898
if t == 0: return '0 s' order = log10(t) if -9 < order < -6: time_units = 'ns' factor = 1000000000 elif -6 <= order < -3: time_units = 'us' factor = 1000000 elif -3 <= order < -1: time_units = 'ms' factor = 1000. elif -1 <= order: ...
def convert_time_units(t)
Convert time in seconds into reasonable time units.
2.182219
2.134346
1.022429
lines = src.splitlines() indent = len(lines[0]) - len(lines[0].strip(' ')) func_src = '' for ii, l in enumerate(src.splitlines()): line = l[indent:] func_src += line + '\n' return func_src
def globalize_indentation(src)
Strip the indentation level so the code runs in the global scope.
2.974009
2.914614
1.020378
src = src.strip() src_lines = src.splitlines() multi_line = False n_deleted = 0 for n in range(len(src_lines)): line = src_lines[n - n_deleted].strip() if (line.startswith('@') and 'Benchmark' in line) or multi_line: del src_lines[n - n_deleted] n_deleted...
def remove_decorators(src)
Remove decorators from the source code
2.915609
2.875108
1.014087
path = [start] for child in path: yield child idx = path.index(child) for grandchild in reversed(getattr(child, attr)): path.insert(idx + 1, grandchild)
def walk_tree(start, attr)
Recursively walk through a tree relationship. This iterates a tree in a top-down approach, fully reaching the end of a lineage before moving onto the next sibling of that generation.
3.688027
3.834239
0.961867
class_code = self.setup_src instance_creation = '\ninstance = {}'.format(self.stmt) for i, benchmark in enumerate(benchmarks): if not benchmark.result_validation: break validation_code = class_code + instance_creation + '\nvalidation_result = ' +...
def validate(self, benchmarks)
Execute the code once to get it's results (to be used in function validation). Compare the result to the first function in the group. :param benchmarks: list of benchmarks to validate.
4.417899
4.090132
1.080136
''' Determines if the cache files have expired, or if it is still valid ''' if os.path.isfile(self.cache_path_cache): mod_time = os.path.getmtime(self.cache_path_cache) current_time = time() if (mod_time + self.cache_max_age) > current_time: i...
def is_cache_valid(self)
Determines if the cache files have expired, or if it is still valid
3.150332
2.456974
1.2822
''' Do API calls to each region, and save data in cache files ''' if self.route53_enabled: self.get_route53_records() for region in self.regions: self.get_instances_by_region(region) if self.rds_enabled: self.get_rds_instances_by_region(regio...
def do_api_calls_update_cache(self)
Do API calls to each region, and save data in cache files
3.121108
2.536418
1.230518
''' create connection to api server''' if self.eucalyptus: conn = boto.connect_euca(host=self.eucalyptus_host) conn.APIVersion = '2010-08-31' else: conn = self.connect_to_aws(ec2, region) return conn
def connect(self, region)
create connection to api server
4.930622
4.45918
1.105724
''' monkey patch for boto issue boto/boto#2100 ''' profile = 'profile ' + self.boto_profile if boto.config.has_option(profile, 'aws_security_token'): connect_args['security_token'] = boto.config.get(profile, 'aws_security_token') return connect_args
def boto_fix_security_token_in_profile(self, connect_args)
monkey patch for boto issue boto/boto#2100
3.790889
2.628445
1.442255
''' Makes an AWS EC2 API call to the list of instances in a particular region ''' try: conn = self.connect(region) reservations = [] if self.ec2_instance_filters: for filter_key, filter_values in self.ec2_instance_filters.items(): ...
def get_instances_by_region(self, region)
Makes an AWS EC2 API call to the list of instances in a particular region
3.020955
2.768928
1.09102
''' Makes an AWS API call to the list of RDS instances in a particular region ''' try: conn = self.connect_to_aws(rds, region) if conn: instances = conn.get_all_dbinstances() for instance in instances: self.add_rds_inst...
def get_rds_instances_by_region(self, region)
Makes an AWS API call to the list of RDS instances in a particular region
4.216748
3.833499
1.099974
''' Makes an AWS API call to the list of ElastiCache clusters (with nodes' info) in a particular region.''' # ElastiCache boto module doesn't provide a get_all_intances method, # that's why we need to call describe directly (it would be called by # the shorthand method anyway......
def get_elasticache_clusters_by_region(self, region)
Makes an AWS API call to the list of ElastiCache clusters (with nodes' info) in a particular region.
6.04587
5.331511
1.133988
''' Makes an AWS API call to the list of ElastiCache replication groups in a particular region.''' # ElastiCache boto module doesn't provide a get_all_intances method, # that's why we need to call describe directly (it would be called by # the shorthand method anyway...) ...
def get_elasticache_replication_groups_by_region(self, region)
Makes an AWS API call to the list of ElastiCache replication groups in a particular region.
5.467107
5.177415
1.055953
''' create an informative error message if there is an issue authenticating''' errors = ["Authentication error retrieving ec2 inventory."] if None in [os.environ.get('AWS_ACCESS_KEY_ID'), os.environ.get('AWS_SECRET_ACCESS_KEY')]: errors.append(' - No AWS_ACCESS_KEY_ID or AWS_SECRET_A...
def get_auth_error_message(self)
create an informative error message if there is an issue authenticating
3.439149
3.09285
1.111968
'''log an error to std err for ansible-playbook to consume and exit''' if err_operation: err_msg = 'ERROR: "{err_msg}", while: {err_operation}'.format( err_msg=err_msg, err_operation=err_operation) sys.stderr.write(err_msg) sys.exit(1)
def fail_with_error(self, err_msg, err_operation=None)
log an error to std err for ansible-playbook to consume and exit
4.858968
2.66919
1.820391
''' Adds an RDS instance to the inventory and index, as long as it is addressable ''' # Only want available instances unless all_rds_instances is True if not self.all_rds_instances and instance.status != 'available': return # Select the best destination address ...
def add_rds_instance(self, instance, region)
Adds an RDS instance to the inventory and index, as long as it is addressable
2.26869
2.174674
1.043232
''' Adds an ElastiCache node to the inventory and index, as long as it is addressable ''' # Only want available nodes unless all_elasticache_nodes is True if not self.all_elasticache_nodes and node['CacheNodeStatus'] != 'available': return # Select the best destinat...
def add_elasticache_node(self, node, cluster, region)
Adds an ElastiCache node to the inventory and index, as long as it is addressable
2.684554
2.566089
1.046166
''' Adds an ElastiCache replication group to the inventory and index ''' # Only want available clusters unless all_elasticache_replication_groups is True if not self.all_elasticache_replication_groups and replication_group['Status'] != 'available': return # Select the best ...
def add_elasticache_replication_group(self, replication_group, region)
Adds an ElastiCache replication group to the inventory and index
4.017485
3.990491
1.006765
''' Get and store the map of resource records to domain names that point to them. ''' r53_conn = route53.Route53Connection() all_zones = r53_conn.get_zones() route53_zones = [ zone for zone in all_zones if zone.name[:-1] not in self.route53_excluded_zo...
def get_route53_records(self)
Get and store the map of resource records to domain names that point to them.
2.681057
2.199355
1.21902
''' Check if an instance is referenced in the records we have from Route53. If it is, return the list of domain names pointing to said instance. If nothing points to it, return an empty list. ''' instance_attributes = [ 'public_dns_name', 'private_dns_name', ...
def get_instance_route53_names(self, instance)
Check if an instance is referenced in the records we have from Route53. If it is, return the list of domain names pointing to said instance. If nothing points to it, return an empty list.
3.946806
2.271214
1.737752
''' Parses the dictionary returned by the API call into a flat list of parameters. This method should be used only when 'describe' is used directly because Boto doesn't provide specific classes. ''' # I really don't agree with prefixing everything with 'ec2' # because EC...
def get_host_info_dict_from_describe_dict(self, describe_dict)
Parses the dictionary returned by the API call into a flat list of parameters. This method should be used only when 'describe' is used directly because Boto doesn't provide specific classes.
2.947234
2.604528
1.131581
''' Get variables about a specific host ''' if len(self.index) == 0: # Need to load index from cache self.load_index_from_cache() if not host in self.index: # try updating the cache self.do_api_calls_update_cache() if not host in self...
def get_host(self, host)
Get variables about a specific host
4.590921
4.346785
1.056165
''' Push an element onto an array that may not have been defined in the dict ''' group_info = my_dict.setdefault(key, []) if isinstance(group_info, dict): host_list = group_info.setdefault('hosts', []) host_list.append(element) else: group_info...
def push(self, my_dict, key, element)
Push an element onto an array that may not have been defined in the dict
4.0785
2.890014
1.411239
''' Push a group as a child of another group. ''' parent_group = my_dict.setdefault(key, {}) if not isinstance(parent_group, dict): parent_group = my_dict[key] = {'hosts': parent_group} child_groups = parent_group.setdefault('children', []) if element not in child_gro...
def push_group(self, my_dict, key, element)
Push a group as a child of another group.
2.891226
2.77977
1.040095
''' Reads the inventory from the cache file and returns it as a JSON object ''' cache = open(self.cache_path_cache, 'r') json_inventory = cache.read() self.inventory = json.loads(json_inventory)
def load_inventory_from_cache(self)
Reads the inventory from the cache file and returns it as a JSON object
5.131128
3.543741
1.447941
''' Reads the index from the cache file sets self.index ''' cache = open(self.cache_path_index, 'r') json_index = cache.read() self.index = json.loads(json_index)
def load_index_from_cache(self)
Reads the index from the cache file sets self.index
5.620943
4.130594
1.360807
''' Writes data in JSON format to a file ''' json_data = json.dumps(data, sort_keys=True, indent=2) cache = open(filename, 'w') cache.write(json_data) cache.close()
def write_to_cache(self, data, filename)
Writes data in JSON format to a file
3.086627
2.926731
1.054633
''' Converts 'bad' characters in a string to underscores so they can be used as Ansible groups ''' regex = "[^A-Za-z0-9\_" if not self.replace_dash_in_groups: regex += "\-" return re.sub(regex + "]", "_", word)
def to_safe(self, word)
Converts 'bad' characters in a string to underscores so they can be used as Ansible groups
7.073138
4.542389
1.55714
keyword_tags = nltk.pos_tag(keyword_list) start = time() while time() - start < timeout: index = 0 output_list = [] tagged_sent = self.random_sentences.get_tagged_sent() for word, tag in tagged_sent: if index >= len(keywor...
def from_keyword_list(self, keyword_list, strictness=2, timeout=3)
Convert a list of keywords to sentence. The result is sometimes None :param list keyword_list: a list of string :param int | None strictness: None for highest strictness. 2 or 1 for a less strict POS matching :param float timeout: timeout of this function :return list of tuple: sentence...
3.542922
3.799061
0.932578
if not keys: keys = [] if not args: args = [] return self._execute([b'EVAL', script, str(len(keys))] + keys + args)
def eval(self, script, keys=None, args=None)
:meth:`~tredis.RedisClient.eval` and :meth:`~tredis.RedisClient.evalsha` are used to evaluate scripts using the Lua interpreter built into Redis starting from version 2.6.0. The first argument of EVAL is a Lua 5.1 script. The script does not need to define a Lua function (and should not...
3.740389
4.149857
0.90133
if not keys: keys = [] if not args: args = [] return self._execute([b'EVALSHA', sha1, str(len(keys))] + keys + args)
def evalsha(self, sha1, keys=None, args=None)
Evaluates a script cached on the server side by its SHA1 digest. Scripts are cached on the server side using the :meth:`~tredis.RedisClient.script_load` command. The command is otherwise identical to :meth:`~tredis.RedisClient.eval`. .. note:: **Time complexity**: Depends on...
3.167916
3.843982
0.824123
start_stats = Counter(vertex for vertex_pair in start_edges for vertex in vertex_pair) result_stats = Counter(vertex for vertex_pair in result_edges for vertex in vertex_pair) return start_stats == result_stats
def valid_kbreak_matchings(start_edges, result_edges)
A staticmethod check implementation that makes sure that degrees of vertices, that are affected by current :class:`KBreak` By the notion of k-break, it shall keep the degree of vertices in :class:`bg.breakpoint_graph.BreakpointGraph` the same, after its application. By utilizing the Counter class, such...
2.741307
2.667204
1.027783
# TODO: Fix defaults when date is not found (empty string or None) # https://stackoverflow.com/questions/23407295/default-kwarg-values-for-pythons-str-format-method from string import Formatter class UnseenFormatter(Formatter): def get_value(self, key, args, kwds):...
def render_path(self) -> str
Render path by filling the path template with video information.
4.060996
3.634555
1.11733
# If lm compatibility level lower than 3, but the server negotiated NTLM2, generate an # NTLM2 response in preference to the weaker LMv1 if flags & NegotiateFlag.NTLMSSP_NTLM2_KEY and self._lm_compatibility < 3: response, key = self._client_challenge + b'\0' * 16, None ...
def get_lm_response(self, flags, challenge)
Computes the 24 byte LMHash password hash given the 8 byte server challenge. :param challenge: The 8-byte challenge message generated by the server :return: The 24 byte LMHash
4.377338
4.641988
0.942988
# TODO: IMPLEMENT THE FOLLOWING FEATURES # If NTLM v2 authentication is used and the CHALLENGE_MESSAGE does not contain both MsvAvNbComputerName and # MsvAvNbDomainName AVPairs and either Integrity is TRUE or Confidentiality is TRUE, then return STATUS_LOGON_FAILURE. # If NTLM ...
def get_ntlm_response(self, flags, challenge, target_info=None, channel_binding=None)
Computes the 24 byte NTLM challenge response given the 8 byte server challenge, along with the session key. If NTLMv2 is used, the TargetInfo structure must be supplied, the updated TargetInfo structure will be returned :param challenge: The 8-byte challenge message generated by the server :retu...
4.893229
4.909132
0.996761
key = key[:7] + b'\0' * (7 - len(key)) byte = struct.unpack_from('BBBBBBB', key) s = struct.pack('B', ((byte[0] >> 1) & 0x7f) << 1) s += struct.pack("B", ((byte[0] & 0x01) << 6 | ((byte[1] >> 2) & 0x3f)) << 1) s += struct.pack("B", ((byte[1] & 0x03) << 5 | ((byte[2] >> ...
def _expand_des_key(key)
Expand the key from a 7-byte password key into a 8-byte DES key
1.476437
1.434648
1.029129
ntlm_hash = PasswordAuthentication.ntowfv1(password.encode('utf-16le')) response = PasswordAuthentication._encrypt_des_block(ntlm_hash[:7], challenge) response += PasswordAuthentication._encrypt_des_block(ntlm_hash[7:14], challenge) response += PasswordAuthentication._encrypt_d...
def get_ntlmv1_response(password, challenge)
Generate the Unicode MD4 hash for the password associated with these credentials.
3.424742
3.246035
1.055054
md5 = hashlib.new('md5') md5.update(server_challenge + client_challenge) ntlm2_session_hash = md5.digest()[:8] ntlm_hash = PasswordAuthentication.ntowfv1(password.encode('utf-16le')) response = PasswordAuthentication._encrypt_des_block(ntlm_hash[:7], ntlm2_session_hash)...
def get_ntlm2_response(password, server_challenge, client_challenge)
Generate the Unicode MD4 hash for the password associated with these credentials.
2.576018
2.546167
1.011724
md4 = hashlib.new('md4') md4.update(password) hmac_context = hmac.HMAC(md4.digest(), hashes.MD5(), backend=default_backend()) hmac_context.update(user.upper().encode('utf-16le')) hmac_context.update(domain.encode('utf-16le')) return hmac_context.finalize()
def ntowfv2(domain, user, password)
NTOWFv2() Implementation [MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol 3.3.2 NTLM v2 Authentication :param domain: The windows domain name :param user: The windows username :param password: The users password :return: Hash Data
2.990513
2.537573
1.178493
hmac_context = hmac.HMAC(response_key, hashes.MD5(), backend=default_backend()) hmac_context.update(server_challenge) hmac_context.update(client_challenge) return hmac_context.finalize()
def _compute_response(response_key, server_challenge, client_challenge)
ComputeResponse() has been refactored slightly to reduce its complexity and improve readability, the 'if' clause which switches between LMv2 and NTLMv2 computation has been removed. Users should not call this method directly, they should rely on get_lmv2_response and get_ntlmv2_response dependin...
2.582511
2.968197
0.870061
ntlmv2_hash = PasswordAuthentication.ntowfv2(domain, username, password.encode('utf-16le')) hmac_context = hmac.HMAC(ntlmv2_hash, hashes.MD5(), backend=default_backend()) hmac_context.update(server_challenge) hmac_context.update(client_challenge) lmv2_hash = hmac_context...
def get_lmv2_response(domain, username, password, server_challenge, client_challenge)
Computes an appropriate LMv2 response based on the supplied arguments The algorithm is based on jCIFS. The response is 24 bytes, with the 16 bytes of hash concatenated with the 8 byte client client_challenge
3.41829
3.465664
0.98633
lo_response_version = b'\x01' hi_response_version = b'\x01' reserved_dword = b'\x00' * 4 reserved_bytes = b'\x00' * 6 response_key = PasswordAuthentication.ntowfv2(domain, user, password) proof_material = lo_response_version proof_material += hi_response...
def get_ntlmv2_response(domain, user, password, server_challenge, client_challenge, timestamp, target_info)
[MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol 3.3.2 NTLM v2 Authentication Computes an appropriate NTLMv2 response. The algorithm is based on jCIFS and the ComputeResponse() implementation the protocol documentation. Note: The MS ComputeResponse() implementation refe...
3.943088
3.618953
1.089566
self._xml = value self._root = s2t(value)
def xml(self, value)
Set new XML string
23.747929
15.810537
1.502032
self._xml = t2s(value) self._root = value
def root(self, value)
Set new XML tree
21.282831
17.422873
1.221545
def append_xsl_elements(xsl_elements, r, xsl): if r is not None: r.xpath('.//w:t', namespaces=self.namespaces)[0].text = xsl xe = XslElement(r, logger=self.logger) xsl_elements.append(xe) return None, '' if not getattr(s...
def xsl_elements(self)
Find all "XSL" styled runs, normalize related paragraph and returns list of XslElements
2.825585
2.578442
1.09585