code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
checksum = self._byte_rot_left(checksum, 1) checksum = checksum + value if (checksum > 255): checksum = checksum - 255 self._debug(PROP_LOGLEVEL_TRACE, "C: " + str(checksum) + " V: " + str(value)) return checksum
def _add_to_checksum(self, checksum, value)
Add a byte to the checksum.
5.379281
4.818481
1.116385
to_return = "" if (self._mode == PROP_MODE_SERIAL): to_return = self._serial.read(1) elif (self._mode == PROP_MODE_TCP): to_return = self._socket.recv(1) elif (self._mode == PROP_MODE_FILE): to_return = struct.pack("B", int(self._file.readlin...
def _read_byte(self)
Read a byte from input.
2.690406
2.607107
1.031951
data = bytearray(0) last = 0 i = 1 while (i < len(packet)): if not (last == 2 and packet[i] == 0): data.append(packet[i]) last = packet[i] i += 1 return data
def _sense_packet_to_data(packet)
Remove the escape pad bytes from a sense packet (\2\0 -> \2).
3.037325
2.485443
1.222046
temp = (byte_1 << 8) + byte_2 if (temp > 32767): temp = temp - 65536 temp = temp / 10 return temp
def _decode_temp(byte_1, byte_2)
Decode a signed short temperature as two bytes to a single number.
2.232631
1.992703
1.120404
status = STATUS_WAITING mode = 0 checksum = 0 checksum_calculated = 0 length = 0 version = 0 i = 0 cnt = 0 packet = bytearray(0) while (status != STATUS_PACKET_DONE): read = self._read_ord_byte() if (stat...
def _read_packet(self)
Read a packet from the input.
2.141444
2.128079
1.006281
data = self._sense_packet_to_data(packet) offset = 4 i = 0 datalen = len(data) - offset - 6 temp_count = int(datalen / 2) temp = [] for i in range(temp_count): temp_index = i * 2 + offset temp.append(self._decode_temp(data[temp...
def _decode_sense_packet(self, version, packet)
Decode a sense packet into the list of sensors.
3.49
3.250962
1.073529
for i in range(5): input_bit = packet[i] self._debug(PROP_LOGLEVEL_DEBUG, "Byte " + str(i) + ": " + str((input_bit >> 7) & 1) + str((input_bit >> 6) & 1) + str((input_bit >> 5) & 1) + str((input_bit >> 4) & 1) + str((input_bit >> 3) & 1) + str((input_bit >> 2) & 1) + str((input...
def _decode_ctrl_packet(self, version, packet)
Decode a control packet into the list of sensors.
2.350344
2.269269
1.035727
while (self._run_thread): (mode, version, packet) = self._read_packet() if (mode == PROP_PACKET_SENSE): self._decode_sense_packet(version, packet) elif (mode == PROP_PACKET_CTRL): self._decode_ctrl_packet(version, packet)
def run(self)
Main thread that reads from input and populates the sensors.
4.69031
4.242392
1.105581
self._run_thread = True self._thread.setDaemon(True) self._thread.start()
def run_thread(self)
Run the main thread.
4.118905
3.072239
1.340685
for key, value in _dict.items(): if value is None: del _dict[key] return _dict
def unused(self, _dict)
Remove empty parameters from the dict
2.879474
2.119797
1.358373
for key in require: if key not in _dict: raise LunrError("'%s' is required argument for method '%s'" % (key, method))
def required(self, method, _dict, require)
Ensure the required items are in the dictionary
4.00946
4.182882
0.95854
for key in _dict.keys(): if key not in allow: raise LunrError("'%s' is not an argument for method '%s'" % (key, method))
def allowed(self, method, _dict, allow)
Only these items are allowed in the dictionary
4.379216
4.425806
0.989473
try: app, event = name.split('.') return '{}.{}'.format(app, EVENTS_MODULE_NAME), event except ValueError: raise InvalidEventNameError( (u'The name "{}" is invalid. ' u'Make sure you are using the "app.KlassName" format' ).format(name))
def parse_event_name(name)
Returns the python module and obj given an event name
5.969004
5.891931
1.013081
try: module, klass = parse_event_name(name) return getattr(import_module(module), klass) except (ImportError, AttributeError): raise EventNotFoundError( ('Event "{}" not found. ' 'Make sure you have a class called "{}" inside the "{}" ' 'module....
def find_event(name)
Actually import the event represented by name Raises the `EventNotFoundError` if it's not possible to find the event class refered by `name`.
3.880888
3.481765
1.114632
if event: if event in HANDLER_REGISTRY: del HANDLER_REGISTRY[event] if event in EXTERNAL_HANDLER_REGISTRY: del EXTERNAL_HANDLER_REGISTRY[event] else: HANDLER_REGISTRY.clear() EXTERNAL_HANDLER_REGISTRY.clear()
def cleanup_handlers(event=None)
Remove handlers of a given `event`. If no event is informed, wipe out all events registered. Be careful!! This function is intended to help when writing tests and for debugging purposes. If you call it, all handlers associated to an event (or to all of them) will be disassociated. Which means that ...
2.25007
2.22133
1.012938
handlers = [] # event_name can be a BaseEvent or the string representation if isinstance(event_name, basestring): matched_events = [event for event in registry.keys() if fnmatch.fnmatchcase(event_name, event)] for matched_event in matched_events: handlers.extend...
def find_handlers(event_name, registry=HANDLER_REGISTRY)
Small helper to find all handlers associated to a given event If the event can't be found, an empty list will be returned, since this is an internal function and all validation against the event name and its existence was already performed.
2.983086
3.208529
0.929736
deserialized = loads(data) event_cls = find_event(event_name) event = event_cls(event_name, deserialized) try: event.clean() except ValidationError as exc: if os.environ.get('EVENTLIB_RAISE_ERRORS'): raise else: logger.warning( "Th...
def process(event_name, data)
Iterates over the event handler registry and execute each found handler. It takes the event name and its its `data`, passing the return of `ejson.loads(data)` to the found handlers.
4.491712
4.756874
0.944257
for handler in find_external_handlers(event_name): try: handler(data) except Exception as exc: logger.warning( (u'One of the handlers for the event "{}" has failed with the ' u'following exception: {}').format(event_name, str(exc))) ...
def process_external(event_name, data)
Iterates over the event handler registry and execute each found handler. It takes the event name and its `data`, passing the return of data to the found handlers.
4.37402
4.619435
0.946873
request = data.get('request') result = {} result['__datetime__'] = datetime.now() result['__ip_address__'] = request and get_ip(request) or '0.0.0.0' return result
def get_default_values(data)
Return all default values that an event should have
4.408274
4.348311
1.01379
banned = ('request',) return {key: val for key, val in data.items() if not key in banned}
def filter_data_values(data)
Remove special values that log function can take There are some special values, like "request" that the `log()` function can take, but they're not meant to be passed to the celery task neither for the event handlers. This function filter these keys and return another dict without them.
5.830873
4.960332
1.175501
for installed_app in getsetting('INSTALLED_APPS'): module_name = u'{}.{}'.format(installed_app, EVENTS_MODULE_NAME) try: import_module(module_name) except ImportError: pass
def import_event_modules()
Import all events declared for all currently installed apps This function walks through the list of installed apps and tries to import a module named `EVENTS_MODULE_NAME`.
3.86192
3.305366
1.168379
ACTIVATED = RegistrationProfile.ACTIVATED expiration_date = datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS) to_delete = [] print "Processing %s registration profiles..." % str(RegistrationProfile.objects.all().count()) for profile in RegistrationProfile.objects.all(): # i...
def handle_expired_accounts()
Check of expired accounts.
3.442905
3.418287
1.007202
if SHA1_RE.search(activation_key): try: profile = RegistrationProfile.objects.get(activation_key=activation_key) except RegistrationProfile.DoesNotExist: return False user = profile.user user.is_active = ...
def activate(self, request, activation_key)
Override default activation process. This will activate the user even if its passed its expiration date.
2.701578
2.82315
0.956937
if Site._meta.installed: site = Site.objects.get_current() else: site = RequestSite(request) email = kwargs['email'] # Generate random password password = User.objects.make_random_password() # Generate username b...
def register(self, request, **kwargs)
Create and immediately log in a new user. Only require a email to register, username is generated automatically and a password is random generated and emailed to the user. Activation is still required for account uses after specified number of days.
3.61612
3.555624
1.017014
ctx_dict = { 'password': password, 'site': site, 'activation_key': profile.activation_key, 'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS} subject = render_to_string( 'registration/email/emai...
def send_activation_email(self, user, profile, password, site)
Custom send email method to supplied the activation link and new generated password.
2.493158
2.553211
0.97648
next_url = "/registration/register/complete/" if "next" in request.GET or "next" in request.POST: next_url = request.GET.get("next", None) or request.POST.get("next", None) or "/" return (next_url, (), {})
def post_registration_redirect(self, request, user)
After registration, redirect to the home page or supplied "next" query string or hidden field value.
3.338969
3.177366
1.050861
if self.start + self.size > self.total_size: result = None else: result = Batch(self.start + self.size, self.size, self.total_size) return result
def next(self)
Returns the next batch for the batched sequence or `None`, if this batch is already the last batch. :rtype: :class:`Batch` instance or `None`.
3.772559
3.339734
1.129599
if self.start - self.size < 0: result = None else: result = Batch(self.start - self.size, self.size, self.total_size) return result
def previous(self)
Returns the previous batch for the batched sequence or `None`, if this batch is already the first batch. :rtype: :class:`Batch` instance or `None`.
4.570967
3.82875
1.193854
start = max(self.number - 1, 0) * self.size return Batch(start, self.size, self.total_size)
def last(self)
Returns the last batch for the batched sequence. :rtype: :class:`Batch` instance.
7.700304
7.859045
0.979801
return int(math.ceil(self.total_size / float(self.size)))
def number(self)
Returns the number of batches the batched sequence contains. :rtype: integer.
8.047359
7.843232
1.026026
# initialize some variables args = args.split(',') params = dict( name=args.pop(0), opacity=0.5, tile=False, scale=1.0, greyscale=False, rotation=0, position=None, quality=QUALITY, obscure=OBSCURE_ORIGINAL, random_position...
def watermark(url, args='')
Returns the URL to a watermarked copy of the image specified.
2.489371
2.513107
0.990555
if url_path.startswith(settings.MEDIA_URL): url_path = url_path[len(settings.MEDIA_URL):] # strip media root url return os.path.normpath(os.path.join(basedir, url2pathname(url_path)))
def _get_filesystem_path(self, url_path, basedir=settings.MEDIA_ROOT)
Makes a filesystem path from the specified URL path
2.594165
2.484537
1.044124
kwargs = kwargs.copy() kwargs['opacity'] = int(kwargs['opacity'] * 100) kwargs['st_mtime'] = kwargs['fstat'].st_mtime kwargs['st_size'] = kwargs['fstat'].st_size params = [ '%(original_basename)s', 'wm', 'w%(watermark)i', ...
def generate_filename(self, mark, **kwargs)
Comes up with a good filename for the watermarked image
4.247804
4.092479
1.037954
try: hash = hashlib.sha1(smart_str(name)).hexdigest() except TypeError: hash = hashlib.sha1(smart_str(name).encode('utf-8')).hexdigest() # figure out where the watermark would be saved on the filesystem if obscure is True: logger.debug('Obsc...
def get_url_path(self, basedir, original_basename, ext, name, obscure=True)
Determines an appropriate watermark path
2.60657
2.530771
1.029951
im = utils.watermark(target, mark, **kwargs) im.save(fpath, quality=quality) return im
def create_watermark(self, target, mark, fpath, quality=QUALITY, **kwargs)
Create the watermarked image on the filesystem
4.228606
4.757839
0.888766
try: if is_percent: var = float(int(var.strip('%')) / 100.0) else: var = int(var) except ValueError: raise ValueError('invalid watermark parameter: ' + var) return var
def _val(var, is_percent=False)
Tries to determine the appropriate value of a particular variable that is passed in. If the value is supposed to be a percentage, a whole integer will be sought after and then turned into a floating point number between 0 and 1. If the value is supposed to be an integer, the variable is cast into an i...
3.563244
3.672235
0.97032
assert opacity >= 0 and opacity <= 1 if img.mode != 'RGBA': img = img.convert('RGBA') else: img = img.copy() alpha = img.split()[3] alpha = ImageEnhance.Brightness(alpha).enhance(opacity) img.putalpha(alpha) return img
def reduce_opacity(img, opacity)
Returns an image with reduced opacity.
1.769781
1.786811
0.990469
if scale: try: scale = float(scale) except (ValueError, TypeError): pass if isinstance(scale, six.string_types) and scale.upper() == 'F': # scale watermark to full, but preserve the aspect ratio scale = min( float(img.size...
def determine_scale(scale, img, mark)
Scales an image using a specified ratio, 'F' or 'R'. If `scale` is 'F', the image is scaled to be as big as possible to fit in `img` without falling off the edges. If `scale` is 'R', the watermark resizes to a percentage of minimum size of source image. Returns the scaled `mark`.
2.993309
2.806581
1.066532
if isinstance(rotation, six.string_types) and rotation.lower() == 'r': rotation = random.randint(0, 359) else: rotation = _int(rotation) return rotation
def determine_rotation(rotation, mark)
Determines the number of degrees to rotate the watermark image.
3.516506
3.348308
1.050234
left = top = 0 max_left = max(img.size[0] - mark.size[0], 0) max_top = max(img.size[1] - mark.size[1], 0) #Added a 10px margin from corners to apply watermark. margin = 10 if not position: position = 'r' if isinstance(position, tuple): left, top = position elif i...
def determine_position(position, img, mark)
Options: TL: top-left TR: top-right BR: bottom-right BL: bottom-left C: centered R: random X%xY%: relative positioning on both the X and Y axes X%xY: relative positioning on the X axis and absolute positioning on the Y axis XxY%: abso...
2.209348
2.151173
1.027044
if opacity < 1: mark = reduce_opacity(mark, opacity) if not isinstance(scale, tuple): scale = determine_scale(scale, img, mark) mark = mark.resize(scale, resample=Image.ANTIALIAS) if greyscale and mark.mode != 'LA': mark = mark.convert('LA') rotation = determine_rot...
def watermark(img, mark, position=(0, 0), opacity=1, scale=1.0, tile=False, greyscale=False, rotation=0, return_name=False, **kwargs)
Adds a watermark to an image
2.276865
2.294624
0.992261
parser = ConfigParser(allow_no_value=True) parser.readfp(config_file) return parser
def parsed_file(config_file)
Parse an ini-style config file.
3.095447
2.902431
1.066502
commands = {cmd: Command(**dict((minus_to_underscore(k), v) for k, v in config.items(cmd))) for cmd in config.sections() if cmd != 'packages'} try: return tuple(commands[x] for x in names) except KeyError as e: raise Ru...
def commands(config, names)
Return the list of commands to run.
6.590751
6.337502
1.03996
return os.path.join(os.path.dirname(__file__), *names)
def project_path(*names)
Path to a file in the project.
3.135576
2.745046
1.142268
description = parser = argparse.ArgumentParser( usage='%(prog)s', description=description, epilog='Licensed "Apache 2.0"', formatter_class=argparse.RawTextHelpFormatter ) parser.add_argument( 'old_commit', action='store', nargs=1, he...
def create_parser()
Setup argument Parsing.
2.56176
2.554637
1.002788
osa_differ.checkout(repo, ref) functions_path = os.path.join(repo.working_tree_dir, 'scripts/functions.sh') release_path = os.path.join(repo.working_tree_dir, 'playbooks/vars/rpc-release.yml') if os.path.exists(release_path): ...
def get_osa_commit(repo, ref, rpc_product=None)
Get the OSA sha referenced by an RPCO Repo.
4.256468
4.15041
1.025554
# Is the commit valid? Just in case the commit is a # PR ref, we try both the ref given and the ref prepended # with the remote 'origin'. try: osa_differ.validate_commits(repo_dir, [commit]) except exceptions.InvalidCommitException: log.debug("The reference {c} cannot be found....
def validate_rpc_sha(repo_dir, commit)
Validate/update a SHA given for the rpc-openstack repo.
7.291681
7.29779
0.999163
# Do we have a valid commit range? # NOTE: # An exception is thrown by osa_differ if these two commits # are the the same, but it is sometimes necessary to compare # two RPC tags that have the same OSA SHA. For example, # comparing two tags that only have differences between the # two ...
def make_rpc_report(repo_dir, old_commit, new_commit, args)
Create initial RST report header for OpenStack-Ansible.
6.290316
6.0981
1.031521
parser = create_parser() args = parser.parse_args() if not args.role_requirements_old_commit: args.role_requirements_old_commit = args.role_requirements if not args.rpc_product_old_commit: args.rpc_product_old_commit = args.rpc_product return args
def parse_arguments()
Parse arguments.
3.920934
3.764089
1.041669
# Print the report to stdout unless the user specified --quiet. output = "" if not args.quiet and not args.gist and not args.file: return report if args.gist: gist_url = post_gist(report, old_commit, new_commit) output += "\nReport posted to GitHub Gist: {0}".format(gist_u...
def publish_report(report, args, old_commit, new_commit)
Publish the RST report based on the user request.
2.938013
2.85216
1.030101
parser = argparse.ArgumentParser( description="poor man's integration testing") parser.add_argument( 'cmds', metavar='cmd', default=['test'], nargs='*', help='Run command(s) defined in the configuration file. Each command ' 'is run on each package before proceeding with...
def main(raw_args=None)
Console script entry point.
4.082508
4.007144
1.018807
xml = SP.DeleteList(SP.listName(list.id)) self.opener.post_soap(LIST_WEBSERVICE, xml, soapaction='http://schemas.microsoft.com/sharepoint/soap/DeleteList') self.all_lists.remove(list)
def remove(self, list)
Removes a list from the site.
9.248078
8.271306
1.118092
try: template = int(template) except ValueError: template = LIST_TEMPLATES[template] if name in self: raise ValueError("List already exists: '{0}".format(name)) if uuid_re.match(name): raise ValueError("Cannot create a list with a ...
def create(self, name, description='', template=100)
Creates a new list in the site.
4.448242
4.297413
1.035098
if not hasattr(self, '_row_class'): attrs = {'fields': self.fields, 'list': self, 'opener': self.opener} for field in self.fields.values(): attrs[field.name] = field.descriptor self._row_class = type('SharePointListRow', (SharePointListRow,), attrs) ...
def Row(self)
The class for a row in this list.
4.220771
3.43535
1.228629
if isinstance(row, dict): row = self.Row(row) elif isinstance(row, self.Row): pass elif isinstance(row, SharePointListRow): raise TypeError("row must be a dict or an instance of SharePointList.Row, not SharePointListRow") else: rai...
def append(self, row)
Appends a row to the list. Takes a dictionary, returns a row.
3.297473
3.074203
1.072627
self._rows.remove(row) self._deleted_rows.add(row)
def remove(self, row)
Removes the row from the list.
5.043026
4.421309
1.140618
# Based on the documentation at # http://msdn.microsoft.com/en-us/library/lists.lists.updatelistitems%28v=office.12%29.aspx # Note, this ends up un-namespaced. SharePoint doesn't care about # namespaces on this XML node, and will bork if any of these elements # have a n...
def save(self)
Updates the list with changes.
4.32051
4.253219
1.015821
if not self._changed: return None batch_method = E.Method(Cmd='Update' if self.id else 'New') batch_method.append(E.Field(text_type(self.id) if self.id else 'New', Name='ID')) for field in self.fields.values(): if fiel...
def get_batch_method(self)
Returns a change batch for SharePoint's UpdateListItems operation.
4.575358
4.143503
1.104225
def convert_to_python(self, xmlrpc=None): if xmlrpc: return xmlrpc.get(self.name, self.default) elif self.default: return self.default else: return None
Extracts a value for the field from an XML-RPC response.
null
null
null
def get_outputs(self, input_value): output_value = self.convert_to_xmlrpc(input_value) output = {} for name in self.output_names: output[name] = output_value return output
Generate a set of output values for a given input.
null
null
null
def struct(self): data = {} for var, fmap in self._def.items(): if hasattr(self, var): data.update(fmap.get_outputs(getattr(self, var))) return data
XML-RPC-friendly representation of the current object state
null
null
null
def get_args(self, client): default_args = self.default_args(client) if self.method_args or self.optional_args: optional_args = getattr(self, 'optional_args', tuple()) args = [] for arg in (self.method_args + optional_args): if hasatt...
Builds final set of XML-RPC method arguments based on the method's arguments, any default arguments, and their defined respective ordering.
null
null
null
def process_result(self, raw_result): if self.results_class and raw_result: if isinstance(raw_result, dict_type): return self.results_class(raw_result) elif isinstance(raw_result, collections.Iterable): return [self.results_class(result) for...
Performs actions on the raw result from the XML-RPC response. If a `results_class` is defined, the response will be converted into one or more object instances of that class.
null
null
null
'''Returns a list of addresses found in text together with parsed address parts ''' results = [] if isinstance(text, str): if six.PY2: text = unicode(text, 'utf-8') self.clean_text = self._normalize_string(text) # get addresses ...
def parse(self, text)
Returns a list of addresses found in text together with parsed address parts
5.36245
3.590792
1.493389
'''Parses address into parts''' match = utils.match(self.rules, address_string, flags=re.VERBOSE | re.U) if match: match_as_dict = match.groupdict() match_as_dict.update({'country_id': self.country}) # combine results cleaned_dict = self._combine_r...
def _parse_address(self, address_string)
Parses address into parts
6.233765
5.69772
1.094081
'''Combine results from different parsed parts: we look for non-empty results in values like 'postal_code_b' or 'postal_code_c' and store them as main value. So 'postal_code_b':'123456' becomes: 'postal_code' :'123456' ...
def _combine_results(self, match_as_dict)
Combine results from different parsed parts: we look for non-empty results in values like 'postal_code_b' or 'postal_code_c' and store them as main value. So 'postal_code_b':'123456' becomes: 'postal_code' :'123456'
4.836517
2.146326
2.253393
'''Prepares incoming text for parsing: removes excessive spaces, tabs, newlines, etc. ''' conversion = { # newlines '\r?\n': ' ', # replace excessive empty spaces '\s+': ' ', # convert all types of hyphens/dashes to a ...
def _normalize_string(self, text)
Prepares incoming text for parsing: removes excessive spaces, tabs, newlines, etc.
4.642306
3.679921
1.261523
'''Returns a list of addresses found in text''' # find addresses addresses = [] matches = utils.findall( self.rules, text, flags=re.VERBOSE | re.U) if(matches): for match in matches: addresses.append(match[0].strip(...
def _get_addresses(self, text)
Returns a list of addresses found in text
5.684296
5.398165
1.053005
ap = parser.AddressParser(**kwargs) return ap.parse(some_text)
def parse(some_text, **kwargs)
Creates request to AddressParser and returns list of Address objects
8.195285
5.271448
1.554655
if isinstance(value, int): values.add().int32_value = value elif isinstance(value, float): values.add().double_value = value elif isinstance(value, long): values.add().int64_value = value elif isinstance(value, str): values.add().string_value = value elif isinsta...
def setAttribute(values, value)
Takes the values of an attribute value list and attempts to append attributes of the proper type, inferred from their Python type.
1.874704
1.851011
1.0128
first, _, rest = path.rpartition('.') return setattr(deepGetAttr(obj, first) if first else obj, rest, val)
def deepSetAttr(obj, path, val)
Sets a deep attribute on an object by resolving a dot-delimited path. If path does not exist an `AttributeError` will be raised`.
3.961057
5.198133
0.762015
if isinstance(value, (list, tuple)): return [common.AttributeValue(string_value=str(v)) for v in value] else: return [common.AttributeValue(string_value=str(value))]
def encodeValue(value)
TODO
3.614915
3.573949
1.011463
epoch = datetime.datetime.utcfromtimestamp(0) delta = t - epoch millis = delta.total_seconds() * 1000 return int(millis)
def convertDatetime(t)
Converts the specified datetime object into its appropriate protocol value. This is the number of milliseconds from the epoch.
2.465963
2.50628
0.983914
if type(value) != common.AttributeValue: raise TypeError( "Expected an AttributeValue, but got {}".format(type(value))) if value.WhichOneof("value") is None: raise AttributeError("Nothing set for {}".format(value)) return getattr(value, value.WhichOneof("value"))
def getValueFromValue(value)
Extract the currently set field from a Value structure
4.372364
4.124449
1.060109
# Using the internal method because this way we can reformat the JSON js = json_format.MessageToDict(protoObject, False) return json.dumps(js, indent=indent)
def toJson(protoObject, indent=None)
Serialises a protobuf object as json
7.393206
8.057385
0.917569
# We keep a manual list of the superclasses that we define here # so we can filter them out when we're getting the protocol # classes. superclasses = set([message.Message]) thisModule = sys.modules[__name__] subclasses = [] for name, class_ in inspect.getmembers(thisModule): if ...
def getProtocolClasses(superclass=message.Message)
Returns all the protocol classes that are subclasses of the specified superclass. Only 'leaf' classes are returned, corresponding directly to the classes defined in the protocol.
3.544375
3.638297
0.974185
try: if silent: with open(os.devnull, 'w') as devnull: subprocess.check_call( splits, stdout=devnull, stderr=devnull, shell=shell) else: subprocess.check_call(splits, shell=shell) except OSError as exception: if exception.e...
def runCommandSplits(splits, silent=False, shell=False)
Run a shell command given the command's parsed command line
2.396648
2.441769
0.981521
splits = shlex.split(command) runCommandSplits(splits, silent=silent, shell=shell)
def runCommand(command, silent=False, shell=False)
Run a shell command
5.425447
5.519837
0.9829
# Create the target directory hierarchy, if neccessary ga4ghPath = os.path.join(destPath, 'ga4gh') if not os.path.exists(ga4ghPath): os.mkdir(ga4ghPath) ga4ghSchemasPath = os.path.join(ga4ghPath, 'schemas') if not os.path.exists(ga4ghSchemasPath): ...
def _createSchemaFiles(self, destPath, schemasPath)
Create a hierarchy of proto files in a destination directory, copied from the schemasPath hierarchy
1.728505
1.66192
1.040065
# ga4gh packages packageString = 'package ga4gh;' if packageString in line: return line.replace( packageString, 'package ga4gh.schemas.ga4gh;') importString = 'import "ga4gh/' if importString in line: return line.re...
def _doLineReplacements(self, line)
Given a line of a proto file, replace the line with one that is appropriate for the hierarchy that we want to compile
2.292238
2.206486
1.038864
with open(src) as srcFile, open(dst, 'w') as dstFile: srcLines = srcFile.readlines() for srcLine in srcLines: toWrite = self._doLineReplacements(srcLine) dstFile.write(toWrite)
def _copySchemaFile(self, src, dst)
Copy a proto file to the temporary directory, with appropriate line replacements
2.510063
2.361861
1.062748
class Editable(object): def __init__(self, prot): self.kind = type(prot) self.name = prot.name self.comment = "" self.options = dict([(key.name, value) for (key, value) in prot.options.ListFields()]) if isinstance(prot, EnumDescriptorProto): ...
def convert_protodef_to_editable(proto)
Protobuf objects can't have arbitrary fields addedd and we need to later on add comments to them, so we instead make "Editable" objects that can do so
2.03474
1.95932
1.038493
def _collapse_comments(comments): return '\n'.join( [c.strip() for c in (comments["leading_comments"] + comments["trailing_comments"]).split('\n')]) def _traverse(package, items, tree): for item_index, item in enumerate(items): item = convert_protodef_to_editable(it...
def traverse(proto_file)
proto_file is a FileDescriptorProto from protoc. We walk the SourceCodeInfo in this file, and find all the comments, and return a flattened out tree of all the messages and enums
2.531162
2.482136
1.019752
if f.type in [1]: return "double" elif f.type in [2]: return "float" elif f.type in [3]: return "long" elif f.type in [4]: return "uint64" elif f.type in [5]: return "integer" elif f.type in [6]: return "fixed64" elif f.type in [7]: ...
def type_to_string(f, map_types)
Convert type info to pretty names, based on numbers from from FieldDescriptorProto https://developers.google.com/protocol-buffers/docs/reference/cpp/google.protobuf.descriptor.pb
2.126982
2.052386
1.036346
for proto_file in request.proto_file: types = [] messages = {} results = traverse(proto_file) map_types = {} def full_name(package, item): return "%s.%s" % (package, item.name) for item, package in results["types"]: if item.options.has_ke...
def generate_code(request, response)
Core function. Starts from a CodeGeneratorRequest and adds files to a CodeGeneratorResponse
2.85804
2.882704
0.991444
# mean earth radius - https://en.wikipedia.org/wiki/Earth_radius#Mean_radius AVG_EARTH_RADIUS_KM = 6371.0088 # Units values taken from http://www.unitconversion.org/unit_converter/length.html conversions = {'km': 1, 'm': 1000, 'mi': 0.621371192, ...
def haversine(point1, point2, unit='km')
Calculate the great-circle distance between two points on the Earth surface. :input: two 2-tuples, containing the latitude and longitude of each point in decimal degrees. Keyword arguments: unit -- a string containing the initials of a unit of measurement (i.e. miles = mi) default 'km' (ki...
1.959848
1.993444
0.983147
logging.basicConfig(level=logging.INFO) run_metrics = py_interop_run_metrics.run_metrics() summary = py_interop_summary.run_summary() valid_to_load = py_interop_run.uchar_vector(py_interop_run.MetricCount, 0) py_interop_run_metrics.list_summary_metrics_to_load(valid_to_load) for run_fold...
def main()
Retrieve run folder paths from the command line Ensure only metrics required for summary are loaded Load the run metrics Calculate the summary metrics Display error by lane, read
3.365507
3.162203
1.064292
'''csv SecurityCenterObj, AssetListName, CSVFields, EmailAddress ''' # First thing we need to do is initialize the csvfile and build the header # for the file. datafile = open(filename, 'wb') csvfile = csv.writer(datafile) header = [] for field in field_list: header.append(field...
def gen_csv(sc, filename, field_list, source, filters)
csv SecurityCenterObj, AssetListName, CSVFields, EmailAddress
7.555213
5.866686
1.287816
'''Logs the user into SecurityCenter and stores the needed token and cookies.''' resp = self.post('token', json={'username': user, 'password': passwd}) self._token = resp.json()['response']['token']
def login(self, user, passwd)
Logs the user into SecurityCenter and stores the needed token and cookies.
7.898513
3.967361
1.990873
'''Scan Downloader Here we will attempt to download all of the scans that have completed between now and AGE days ago. sc = SecurityCenter5 object age = how many days back do we want to pull? (default: 0) unzip = Do we want to uncompress the nessus files? (default: False) path = Path where ...
def download_scans(sc, age=0, unzip=False, path='scans')
Scan Downloader Here we will attempt to download all of the scans that have completed between now and AGE days ago. sc = SecurityCenter5 object age = how many days back do we want to pull? (default: 0) unzip = Do we want to uncompress the nessus files? (default: False) path = Path where the res...
4.908568
3.947768
1.243378
''' Updates a DNS Asset List with the contents of the filename. The assumed format of the file is 1 entry per line. This function will convert the file contents into an array of entries and then upload that array into SecurityCenter. ''' addresses = [] with open(filename) as hostfile: ...
def update(sc, filename, asset_id)
Updates a DNS Asset List with the contents of the filename. The assumed format of the file is 1 entry per line. This function will convert the file contents into an array of entries and then upload that array into SecurityCenter.
6.610597
2.235831
2.956663
''' Generates the HTML report and dumps it into the specified filename ''' jenv = Environment(loader=PackageLoader('swchange', 'templates')) s = Session() #hosts = s.query(Host).filter_by(asset_id=asset_id).all() asset = s.query(AssetList).filter_by(id=asset_id).first() if not asset: ...
def generate_html_report(base_path, asset_id)
Generates the HTML report and dumps it into the specified filename
3.569415
3.21314
1.110881
'''csv SecurityCenterObj, EmailAddress ''' # First thing we need to do is initialize the csvfile and build the header # for the file. datafile = open(filename, 'wb') csvfile = csv.writer(datafile) csvfile.writerow(['Software Package Name', 'Count']) debug.write('Generating %s: ' % file...
def gen_csv(sc, filename)
csv SecurityCenterObj, EmailAddress
8.804237
7.463138
1.179697
'''Report Downloader The report downloader will pull reports down from SecurityCenter based on the conditions provided to the path provided. sc = SecurityCenter5 object age = number of days old the report may be to be included in the search. path = The path to ...
def download(sc, age=0, path='reports', **args)
Report Downloader The report downloader will pull reports down from SecurityCenter based on the conditions provided to the path provided. sc = SecurityCenter5 object age = number of days old the report may be to be included in the search. path = The path to the dow...
4.859566
3.289833
1.477147
'''Calls the specified path with the POST method''' resp = self._session.post(self._url(path), **self._builder(**kwargs)) if 'stream' in kwargs: return resp else: return self._resp_error_check(resp)
def post(self, path, **kwargs)
Calls the specified path with the POST method
6.039051
5.446744
1.108745
''' Imports a repository package using the repository ID specified. ''' # Step 1, lets upload the file filename = self.upload(fileobj).json()['response']['filename'] # Step 2, lets tell SecurityCenter what to do with the file return self.post('repository/{}/impor...
def import_repo(self, repo_id, fileobj)
Imports a repository package using the repository ID specified.
8.39606
6.07936
1.381076
''' Internal function to convert a version string to an integer. ''' intrev = 0 vsplit = version.split('.') for c in range(len(vsplit)): item = int(vsplit[c]) * (10 ** (((len(vsplit) - c - 1) * 2))) intrev += item return intrev
def _revint(self, version)
Internal function to convert a version string to an integer.
3.623898
2.900024
1.24961
''' Internal function to see if a version is func than what we have determined to be talking to. This is very useful for newer API calls to make sure we don't accidentally make a call to something that doesnt exist. ''' current = self._revint(self.version) ...
def _revcheck(self, func, version)
Internal function to see if a version is func than what we have determined to be talking to. This is very useful for newer API calls to make sure we don't accidentally make a call to something that doesnt exist.
6.834022
2.384343
2.866208
''' Internal function to populate the xrefs list with the external references to be used in searching plugins and potentially other functions as well. ''' xrefs = set() plugins = self.plugins() for plugin in plugins: for xref in plugin['xrefs'...
def _build_xrefs(self)
Internal function to populate the xrefs list with the external references to be used in searching plugins and potentially other functions as well.
6.20496
2.834188
2.189325
data = self.raw_query('auth', 'login', data={'username': user, 'password': passwd}) self._token = data["token"] self._user = data
def login(self, user, passwd)
login user passwd Performs the login operation for Security Center, storing the token that Security Center has generated for this login session for future queries.
4.969803
5.29185
0.939143