code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
''' Tokenize and parse the VCD file :ivar file_handle: opened file with vcd string ''' # open the VCD file and create a token generator lineIterator = iter(enumerate(file_handle)) tokeniser = ((lineNo, word) for lineNo, line in lineIterator f...
def parse(self, file_handle)
Tokenize and parse the VCD file :ivar file_handle: opened file with vcd string
6.073426
5.228191
1.161669
try: record_id = new_record["id"] except KeyError: raise ValueError("No record ID provided!") record_type = self.resource_type(record_id) if record_type is None: raise ArchivistsToolkitError( "Could not determine type for reco...
def edit_record(self, new_record)
Update a record in Archivist's Toolkit using the provided new_record. The format of new_record is identical to the format returned by get_resource_component_and_children and related methods. This means it's possible, for example, to request a record, modify the returned dict, and pass that dict to this...
3.024366
2.778352
1.088547
if not hasattr(self, "levels_of_description"): cursor = self.db.cursor() levels = set() cursor.execute("SELECT distinct(resourceLevel) FROM Resources") for row in cursor: levels.add(row) cursor.execute("SELECT distinct(resource...
def get_levels_of_description(self)
Returns an array of all levels of description defined in this Archivist's Toolkit instance.
2.884684
2.685413
1.074205
ret = [] cursor = self.db.cursor() if resource_type == "collection": cursor.execute( "SELECT resourceComponentId FROM ResourcesComponents WHERE parentResourceComponentId IS NULL AND resourceId=%s", (resource_id), ) else: ...
def collection_list(self, resource_id, resource_type="collection")
Fetches a list of all resource and component IDs within the specified resource. :param long resource_id: The ID of the resource to fetch children from. :param string resource_type: Specifies whether the resource to fetch is a collection or a child element. Defaults to 'collection'. ...
2.897798
2.985484
0.970629
cursor = self.db.cursor() sql = "SELECT resourceId, parentResourceComponentId FROM ResourcesComponents WHERE resourceComponentId=%s" cursor.execute(sql, (component_id,)) resource_id, parent_id = cursor.fetchone() if resource_id is None: return self.find_res...
def find_resource_id_for_component(self, component_id)
Given the ID of a component, returns the parent resource ID. If the immediate parent of the component is itself a component, this method will progress up the tree until a resource is found. :param long component_id: The ID of the ResourceComponent. :return: The ID of the component's parent res...
2.658782
2.667954
0.996562
cursor = self.db.cursor() sql = "SELECT parentResourceComponentId FROM ResourcesComponents WHERE resourceComponentId=%s" count = cursor.execute(sql, (component_id,)) if count > 0: return (ArchivistsToolkitClient.RESOURCE_COMPONENT, cursor.fetchone()) return...
def find_parent_id_for_component(self, component_id)
Given the ID of a component, returns the parent component's ID. :param string component_id: The ID of the component. :return: A tuple containing: * The type of the parent record; valid values are ArchivesSpaceClient.RESOURCE and ArchivesSpaceClient.RESOURCE_COMPONENT. * The ID o...
4.946891
4.092347
1.208815
cursor = self.db.cursor() if search_pattern == "" and identifier == "": sql = "SELECT resourceId FROM Resources ORDER BY title" params = () else: clause = "resourceid LIKE %s" params = ["%" + search_pattern + "%"] if search_p...
def find_collection_ids( self, search_pattern="", identifier="", page=None, page_size=30 )
Fetches a list of all resource IDs for every resource in the database. :param string search_pattern: A search pattern to use in looking up resources by title or resourceid. The search will match any title or resourceid containing this string; for example, "text" will match "this title h...
2.848441
2.808401
1.014257
dx = self.x - xo dy = self.y - yo psf = tf.exp(-(a * dx ** 2 + 2 * b * dx * dy + c * dy ** 2)) psf_sum = tf.reduce_sum(psf) return flux * psf / psf_sum
def evaluate(self, flux, xo, yo, a, b, c)
Evaluate the Gaussian model Parameters ---------- flux : tf.Variable xo, yo : tf.Variable, tf.Variable Center coordiantes of the Gaussian. a, b, c : tf.Variable, tf.Variable Parameters that control the rotation angle and the stretch along the ...
2.622873
2.690177
0.974982
matches = re.search(r'^\[([^\]]+)\] ([^:]+: .*)', line) error = re.search(r'Traceback', line) if error: return {'line': line, 'step': 'error'} if not matches: return {'line': line, 'step': None} tstamp = matches.group(1) msg = matches.group(2) if not msg.find('Timing: ...
def parse_log_line(line)
Parses a log line and returns it with more information :param line: str - A line from a bcbio-nextgen log :returns dict: A dictionary containing the line, if its a new step if its a Traceback or if the analysis is finished
2.962876
2.857925
1.036723
return { 'timestamp': time.mktime(self.timestamp.timetuple())*1e3 + self.timestamp.microsecond/1e3, 'group': self.group_pk, 'participant': None if not self.participant else self.participant.code, 'channel': self.channel, 'value': self.value ...
def message(self)
Dictionary representation of the Event appropriate for JSON-encoding.
3.760401
3.367653
1.116624
if self.timestamp is None: self.timestamp = timezone.now() super().save(*args, **kwargs)
def save(self, *args, **kwargs)
Saving an Event automatically sets the timestamp if not already set.
3.635054
2.275543
1.597445
lock = get_redis_lock() if not lock: lock = fake_lock() with lock: self.refresh_from_db() if self.ran_ready_function: return for player in self.get_players(): if Connection.objects.filter(participant__code=...
def _on_connect(self, participant)
Called from the WebSocket consumer. Checks if all players in the group have connected; runs :meth:`when_all_players_ready` once all connections are established.
6.411255
5.470435
1.171983
player = None for p in self.get_players(): if p.participant == participant: player = p break self.when_player_disconnects(player)
def _on_disconnect(self, participant)
Trigger the :meth:`when_player_disconnects` callback.
4.431288
3.02228
1.466207
with track('send_channel=' + channel): with track('create event'): Event.objects.create( group=self, channel=channel, value=payload) ChannelGroup(str(self.pk)).send( {'text': json.dum...
def send(self, channel, payload)
Send a message with the given payload on the given channel. Messages are broadcast to all players in the group.
6.498096
5.824101
1.115725
super().save(*args, **kwargs) if self.pk is not None: update_fields = kwargs.get('update_fields') json_fields = {} for field in self._meta.get_fields(): if isinstance(field, JSONField) and (update_fields is None or field.attname in update_fiel...
def save(self, *args, **kwargs)
BUG: Django save-the-change, which all oTree models inherit from, doesn't recognize changes to JSONField properties. So saving the model won't trigger a database save. This is a hack, but fixes it so any JSONFields get updated every save. oTree uses a forked version of save-the-change so...
2.172794
1.863976
1.165677
self.group_decisions = {} self.subperiod_group_decisions = {} for player in self.get_players(): self.group_decisions[player.participant.code] = player.initial_decision() self.subperiod_group_decisions[player.participant.code] = player.initial_decision() i...
def when_all_players_ready(self)
Initializes decisions based on ``player.initial_decision()``. If :attr:`num_subperiods` is set, starts a timed task to run the sub-periods.
3.906195
3.2799
1.190949
self.refresh_from_db() for key, value in self.group_decisions.items(): self.subperiod_group_decisions[key] = value self.send('group_decisions', self.subperiod_group_decisions) self.save(update_fields=['subperiod_group_decisions'])
def _subperiod_tick(self, current_interval, intervals)
Tick each sub-period, copying group_decisions to subperiod_group_decisions.
3.910099
2.535861
1.541921
if not self.ran_ready_function: logger.warning('ignoring decision from {} before when_all_players_ready: {}'.format(event.participant.code, event.value)) return with track('_on_decisions_event'): self.group_decisions[event.participant.code] = event.value ...
def _on_decisions_event(self, event=None, **kwargs)
Called when an Event is received on the decisions channel. Saves the value in group_decisions. If num_subperiods is None, immediately broadcasts the event back out on the group_decisions channel.
6.472222
5.153644
1.255854
return defaultdict(lambda: ' ', { k: v for k, v in matrix.items() if v != ' ' })
def clean(matrix)
Return a copy of given matrix where keys associated to space values are discarded
5.395361
5.136256
1.050446
max_x = max(matrix, key=lambda t: t[0])[0] min_x = min(matrix, key=lambda t: t[0])[0] max_y = max(matrix, key=lambda t: t[1])[1] min_y = min(matrix, key=lambda t: t[1])[1] yield from ( # '{}:'.format(j).ljust(4) + ''.join(matrix[i, j] for i in range(min_x, max_x+1)) ''.join(matr...
def build(matrix)
Yield lines generated from given matrix
2.025
1.936412
1.045748
x, y = coords maxx = max(view.keys(), key=itemgetter(0))[0] for offset in range(x + 1, maxx): letter = view[offset, y] if letter not in REWRITABLE_LETTERS: return offset return None
def next_unwrittable_on_row(view, coords)
Return position of the next (in row) letter that is unwrittable
4.539293
4.002137
1.134217
x, y = coords maxy = max(view.keys(), key=itemgetter(1))[1] for offset in range(y + 1, maxy): letter = view[x, offset] if letter not in REWRITABLE_LETTERS: return offset return None
def next_unwrittable_on_col(view, coords)
Return position of the next letter (in column) that is unwrittable
4.484706
4.116343
1.089488
x, y = coords minx = -1 for offset in range(x - 1, minx, -1): letter = view[offset, y] if letter not in REWRITABLE_LETTERS: return offset return None
def previous_unwrittable_on_row(view, coords)
Return position of the previous (in row) letter that is unwrittable
5.477889
4.790293
1.143539
x, y = coords miny = -1 for offset in range(y - 1, miny, -1): letter = view[x, offset] if letter not in REWRITABLE_LETTERS: return offset return None
def previous_unwrittable_on_col(view, coords)
Return position of the previous (in column) letter that is unwrittable
4.752648
4.427794
1.073367
parsed = urlparse(host) if not parsed.scheme: parsed = parsed._replace(scheme="http") parsed = parsed._replace(path="") netloc, parts = host, host.partition(":") if parts[1] == "" and port is not None: netloc = "{}:{}".format(parts...
def _build_base_url(self, host, port)
Return the API base URL string based on ``host`` and ``port``. It returns a valid URL when ``host`` isn't. The endling slash is always removed so it always need to be added by the consumer.
3.04007
3.021986
1.005984
notes = [] for note in record["notes"]: if note.get("type"): n = {} n["type"] = note["type"] try: if note["jsonmodel_type"] == "note_singlepart": n["content"] = note["content"][0] ...
def _format_notes(self, record)
Extracts notes from a record and reformats them in a simplified format.
3.343554
3.171824
1.054142
if "notes" not in new_record or not new_record["notes"]: return False # This assumes any notes passed into the edit record are intended to # replace the existing set. new_notes = [] for note in new_record["notes"]: # Whitelist of supported types ...
def _process_notes(record, new_record)
Populate the notes property using the provided new_record. If the new_record field was populated, assume that we want to replace the notes. If there are valid changes to be made, they will be added to the new_notes list. An empty list is counted as a request to delete all notes. ...
4.917431
4.583974
1.072744
# Different rules for "title" and "identifier" fields :/ if field == "title": replacement = r"\\\\\1" else: replacement = r"\\\1" return re.sub(r'([\'" +\-!\(\)\{\}\[\]^"~?:\\/]|&&|\|\|)', replacement, query)
def _escape_solr_query(query, field="title")
Escapes special characters in Solr queries. Note that this omits * - this is intentionally permitted in user queries. The list of special characters is located at http://lucene.apache.org/core/4_0_0/queryparser/org/apache/lucene/queryparser/classic/package-summary.html#Escaping_Special_Characters
9.277171
8.737428
1.061774
match = re.search( r"repositories/\d+/(resources|archival_objects)/\d+", resource_id ) if match and match.groups(): type_ = match.groups()[0] return "resource" if type_ == "resources" else "resource_component" else: raise ArchivesS...
def resource_type(self, resource_id)
Given an ID, determines whether a given resource is a resource or a resource_component. :param resource_id string: The URI of the resource whose type to determine. :raises ArchivesSpaceError: if the resource_id does not appear to be either type.
4.64416
3.053123
1.521118
try: record_id = new_record["id"] except KeyError: raise ValueError("No record ID provided!") record = self.get_record(record_id) # TODO: add more fields? field_map = {"title": "title", "level": "levelOfDescription"} fields_updated = Fal...
def edit_record(self, new_record)
Update a record in ArchivesSpace using the provided new_record. The format of new_record is identical to the format returned by get_resource_component_and_children and related methods; consult the documentation for that method in ArchivistsToolkitClient to see the format. This means it's possible, for ...
2.63888
2.386112
1.105933
if not hasattr(self, "levels_of_description"): # TODO: * fetch human-formatted strings # * is hardcoding this ID okay? self.levels_of_description = self._get("/config/enumerations/32").json()[ "values" ] return self.levels_o...
def get_levels_of_description(self)
Returns an array of all levels of description defined in this ArchivesSpace instance.
10.947222
10.570892
1.035601
resource_type = self.resource_type(resource_component_id) return self.get_resource_component_and_children( resource_component_id, resource_type )
def get_resource_component_children(self, resource_component_id)
Given a resource component, fetches detailed metadata for it and all of its children. This is implemented using ArchivesSpaceClient.get_resource_component_children and uses its default options when fetching children. :param string resource_component_id: The URL of the resource component from which to ...
3.644828
4.353219
0.837272
resource_type = self.resource_type(resource_id) if resource_type == "resource": return self._get_resources( resource_id, recurse_max_level=recurse_max_level, sort_by=sort_by ) else: return self._get_components( resource...
def get_resource_component_and_children( self, resource_id, resource_type="collection", level=1, sort_data={}, recurse_max_level=False, sort_by=None, **kwargs )
Fetch detailed metadata for the specified resource_id and all of its children. :param long resource_id: The resource for which to fetch metadata. :param str resource_type: no-op; not required or used in this implementation. :param int recurse_max_level: The maximum depth level to fetch when fet...
2.034546
2.281287
0.891841
response = self.get_record(component_id) if "parent" in response: return (ArchivesSpaceClient.RESOURCE_COMPONENT, response["parent"]["ref"]) # if this is the top archival object, return the resource instead elif "resource" in response: return (ArchivesSpa...
def find_parent_id_for_component(self, component_id)
Given the URL to a component, returns the parent component's URL. :param string component_id: The URL of the component. :return: A tuple containing: * The type of the parent record; valid values are ArchivesSpaceClient.RESOURCE and ArchivesSpaceClient.RESOURCE_COMPONENT. * The U...
5.88307
4.282507
1.373744
params = {"page": page, "q": "primary_type:resource"} if search_pattern != "": search_pattern = self._escape_solr_query(search_pattern, field="title") params["q"] = params["q"] + " AND title:{}".format(search_pattern) if identifier != "": identifier...
def find_collection_ids(self, search_pattern="", identifier="", fetched=0, page=1)
Fetches a list of resource URLs for every resource in the database. :param string search_pattern: A search pattern to use in looking up resources by title or resourceid. The search will match any title containing this string; for example, "text" will match "this title has this text in i...
2.852691
3.085715
0.924483
def format_record(record): dates = self._fetch_dates_from_record(record) date_expression = self._fetch_date_expression_from_record(record) identifier = ( record["id_0"] if "id_0" in record else record.get("component_id", "") ) ...
def find_collections( self, search_pattern="", identifier="", fetched=0, page=1, page_size=30, sort_by=None, )
Fetches a list of all resource IDs for every resource in the database. :param string search_pattern: A search pattern to use in looking up resources by title or resourceid. The search will match any title or resourceid containing this string; for example, "text" will match "this title h...
2.825963
2.95754
0.955511
def format_record(record): resolved = record["_resolved"] identifier = ( resolved["ref_id"] if "ref_id" in resolved else resolved.get("component_id", "") ) return { "id": record["ref"], ...
def find_by_id(self, object_type, field, value)
Find resource by a specific ID. Results are a dict in the format: { 'id': <resource URI fragment>, 'identifier': <resource identifier>, 'title': <title of the resource>, 'levelOfDescription': <level of description>, } :param str object_ty...
3.421505
2.517745
1.358956
parent_record = self.get_record(parent) record_type = self.resource_type(parent) repository = parent_record["repository"]["ref"] if record_type == "resource": resource = parent else: resource = parent_record["resource"]["ref"] new_object...
def add_child( self, parent, title="", level="", start_date="", end_date="", date_expression="", notes=[], )
Adds a new resource component parented within `parent`. :param str parent: The ID to a resource or a resource component. :param str title: A title for the record. :param str level: The level of description. :return: The ID of the newly-created record.
3.220243
3.29616
0.976968
attr = abc.abstractmethod(func) attr.__iattribute__ = True attr = _property(attr) return attr
def attribute(func)
Wrap a function as an attribute.
9.083274
8.50123
1.068466
attr = abc.abstractmethod(func) attr.__iproperty__ = True attr = Property(attr) return attr
def property(func)
Wrap a function as a property. This differs from attribute by identifying properties explicitly listed in the class definition rather than named attributes defined on instances of a class at init time.
10.36196
12.685407
0.816841
attr = abc.abstractmethod(func) attr.__iclassattribute__ = True attr = _property(attr) return attr
def classattribute(func)
Wrap a function as a class attribute. This differs from attribute by identifying attributes explicitly listed in a class definition rather than those only defined on instances of a class.
9.085473
15.178687
0.598568
attr = abc.abstractmethod(func) attr.__imethod__ = True return attr
def method(func)
Wrap a function as a method.
11.983244
10.804333
1.109115
attr = abc.abstractmethod(func) attr.__iclassmethod__ = True attr = _classmethod(attr) return attr
def classmethod(func)
Wrap a function as a classmethod. This applies the classmethod decorator.
8.287926
10.021964
0.826976
try: with open(config_file, 'r') as f: return yaml.load(f) except IOError: print "Configuration file {} not found or not readable.".format(config_file) raise
def parse_config(config_file)
Parse a YAML configuration file
2.700255
2.65671
1.016391
try: ifaces = tuple(ifaces) except TypeError: ifaces = (ifaces,) for iface in ifaces: if not _issubclass(iface, ibc.Iface): raise TypeError('Can only compare against interfaces.') return ifaces
def _ensure_ifaces_tuple(ifaces)
Convert to a tuple of interfaces and raise if not interfaces.
4.773757
4.43631
1.076065
attributes = ( attr for attr in iface.__abstractmethods__ if hasattr(getattr(iface, attr), tag) ) for attribute in attributes: for node in cls.__mro__: if hasattr(node, attribute) and defines(getattr(node, attribute)): return True try:...
def _check_for_definition(iface, cls, tag, defines)
Check for a valid definition of a value. Args: iface (Iface): An Iface specification. cls (type): Some type to check for a definition. tag (str): The name of the tag attribute used to mark the abstract methods. defines (callable): A callable that accepts an attribute and...
7.59963
7.469379
1.017438
ifaces = _ensure_ifaces_tuple(ifaces) for iface in ifaces: return all(( _check_for_definition( iface, cls, '__iclassattribute__', _is_attribute, ), _check_for_definition( iface, ...
def issubclass(cls, ifaces)
Check if the given class is an implementation of the given iface.
2.794544
2.75167
1.015581
ifaces = _ensure_ifaces_tuple(ifaces) for iface in ifaces: attributes = ( attr for attr in iface.__abstractmethods__ if hasattr(getattr(iface, attr), '__iattribute__') ) for attribute in attributes: if not hasattr(instance, attribute...
def isinstance(instance, ifaces)
Check if a given instance is an implementation of the interface.
4.117141
4.031824
1.021161
opt_params = [] cadences = range(pixel_flux.shape[0]) for n in tqdm.tqdm(cadences): feed_dict[data_placeholder] = pixel_flux[n] self.optimizer.minimize(session=session, feed_dict=feed_dict) opt_params.append([session.run(var) for var in var_list]) ...
def fit(self, pixel_flux, data_placeholder, var_list, session, feed_dict={})
Parameters ---------- pixel_flux : ndarray The TPF-like pixel flux time series. The first dimension must represent time, and the remaining two dimensions must represent the spatial dimensions. data_placeholder : tf.placeholder A placeholder which w...
2.726587
3.012586
0.905065
if not raw_entry: raw_entry = self.get_raw_entry( variant_line=variant_line, variant_dict=variant_dict, vcf_header=vcf_header, individual_id=individual_id, dict_key=dict_key ) ent...
def get_entry(self, variant_line=None, variant_dict=None, raw_entry=None, vcf_header=None, csq_format=None, dict_key=None, individual_id=None)
Return the splitted entry from variant information Args: variant_line (str): A vcf formated variant line vcf_header (list): A list with the vcf header line csq_format (list): A list with the csq headers family_id (str): The family ...
2.937106
2.861231
1.026518
if variant_line: variant_line = variant_line.rstrip().split() entry = None if self.field == 'CHROM': if variant_line: entry = variant_line[0] elif variant_dict: entry = variant_dict['CHROM'] ...
def get_raw_entry(self, variant_line=None, variant_dict=None, vcf_header=None, individual_id=None, dict_key=None)
Return the raw entry from the vcf field If no entry was found return None Args: variant_line (str): A vcf formated variant line vcf_header (list): A list with the vcf header line individual_id (str): The individual id to g...
1.975129
1.956411
1.009568
value = None raw_entry = self.get_raw_entry( variant_line = variant_line, variant_dict = variant_dict, vcf_header=vcf_header, individual_id=individual_id, dict_key=dict_key ) # If data type is flag we only n...
def get_value(self, variant_line=None, variant_dict=None, entry=None, raw_entry=None, vcf_header=None, csq_format=None, dict_key=None, individual_id=None)
Return the value as specified by plugin Get value will return one value or None if no correct value is found. Arguments: variant_line (str): A vcf variant line variant_dict (dict): A variant dictionary entry (list): A splitted entry raw_e...
2.408183
2.483421
0.969704
graphviz_layout = graphutils.graphviz_layout(graph, prog=graphviz_prog) # print('GRAPHIZ LAYOUT:', graphviz_layout) layout = {k: (int(x // 10), int(y // 10)) for k, (x, y) in graphviz_layout.items()} # apply an offset for layouts to get all position >= 0 max_x = max(layout.values(...
def create_layout(graph, graphviz_prog=DEFAULT_GRAPHVIZ_PROG)
Return {node: position} for given graph
2.356404
2.245105
1.049574
call_base, call_name = method.split('.', 1) # import the call class's module mod = __import__('ubersmith.calls.{0}'.format(call_base), fromlist=['']) # grab all the public members of the module gen = (getattr(mod, x) for x in dir(mod) if not x.startswith('_')) # filter them down to subclass...
def _get_call_class(method)
Find the call class for method if it exists else create one.
3.290898
3.240826
1.01545
if not self.validate(): raise ValidationError self.process_request() self.clean() return self.response
def render(self)
Validate, process, clean and return the result of the call.
12.86468
5.732496
2.244167
# check if required_fields aren't present for field in set(self.required_fields) - set(self.request_data): if not isinstance(field, string_types): # field was a collection, iterate over it and check by OR return bool(set(field) & set(self.request_data...
def validate(self)
Validate request data before sending it out. Return True/False.
6.785306
5.609846
1.209535
self.response = self.request_handler.process_request( self.method, self.request_data)
def process_request(self)
Processing the call and set response_data.
7.312597
4.842215
1.510176
if self.response.type == 'application/json': cleaned = copy.deepcopy(self.response.data) if self.cleaner is not None: cleaned = self.cleaner(cleaned) typed_response = { dict: DictResponse, int: IntResponse, ...
def clean(self)
Clean response.
4.726389
4.251207
1.111776
raise ValueError('must define at least one ordering operation: < > <= >=') root = max(roots) # prefer __lt__ to __le__ to __gt__ to __ge__ for opname, opfunc in convert[root]: if opname not in roots: opfunc.__name__ = opname opfunc.__doc__ = getattr(int, opname).__d...
def total_ordering(cls): # pragma: no cover convert = { '__lt__': [('__gt__', lambda self, other: not (self < other or self == other)), ('__le__', lambda self, other: self < other or self == other), ('__ge__', lambda self, other: not self < other)], '__le_...
Class decorator that fills in missing ordering methods
3.02414
2.845115
1.062924
log_level = LOG_LEVELS[log_level] if log_level in LOG_LEVELS.keys() else logging.INFO ROOT_LOG.setLevel(log_level) file_handle = logging.FileHandler(log_file) file_handle.setLevel(log_level) file_handle.setFormatter(formatter) ROOT_LOG.addHandler(file_handle)
def init_logger_file(log_file, log_level='INFO')
Append a FileHandler to the root logger. :param str log_file: Path to the log file :param str log_level: Logging level
2.084255
2.402938
0.867378
if not isinstance(crypto_backend, (Backend, MultiBackend)): raise ValueError('backend must be a valid Backend object') if isinstance(signing_key, EllipticCurvePrivateKey): return signing_key elif isinstance(signing_key, (str, unicode)): invalid_strings = [b'-----BEGIN PUBLIC KE...
def load_signing_key(signing_key, crypto_backend=default_backend())
Optional: crypto backend object from the "cryptography" python library
2.604665
2.590845
1.005334
if not isinstance(crypto_backend, (Backend, MultiBackend)): raise ValueError('backend must be a valid Backend object') if isinstance(verifying_key, EllipticCurvePublicKey): return verifying_key elif isinstance(verifying_key, (str, unicode)): try: return load_der_pub...
def load_verifying_key(verifying_key, crypto_backend=default_backend())
Optional: crypto backend object from the "cryptography" python library
2.412746
2.390197
1.009434
notes = [] if "notes" in record: for note in record["notes"]: self._append_note_dict_to_list(notes, "general", note) if "language_and_script_notes" in record: self._append_note_dict_to_list( notes, "language_and_script", record["...
def _format_notes(self, record)
Extracts notes from a record and reformats them in a simplified format.
2.415381
2.358509
1.024114
replacement = r"\\\1" return re.sub(r'([\'" +\-!\(\)\{\}\[\]^"~?:\\/]|&&|\|\|)', replacement, query)
def _escape_lucene_query(query, field=None)
Escapes special characters in Solr queries. Note that this omits * - this is intentionally permitted in user queries. The list of special characters is located at http://lucene.apache.org/core/4_0_0/queryparser/org/apache/lucene/queryparser/classic/package-summary.html#Escaping_Special_Characters
13.07046
11.530849
1.133521
try: record_id = new_record["slug"] except KeyError: raise ValueError("No slug provided!") record = self.get_record(record_id) field_map = {"title": "title", "level": "levelOfDescription"} fields_updated = False for field, targetfield in...
def edit_record(self, new_record)
Update a record in AtoM using the provided new_record. The format of new_record is identical to the format returned by get_resource_component_and_children and related methods; consult the documentation for that method in ArchivistsToolkitClient to see the format. This means it's possible, for example, ...
3.414959
3.112277
1.097254
if not hasattr(self, "levels_of_description"): self.levels_of_description = [ item["name"] for item in self._get(urljoin(self.base_url, "taxonomies/34")).json() ] return self.levels_of_description
def get_levels_of_description(self)
Returns an array of all levels of description defined in this AtoM instance.
3.777043
3.476651
1.086403
def fetch_children(children): results = [] for child in children: results.append(child["slug"]) if "children" in child: results.extend(fetch_children(child["children"])) return results response = self._...
def collection_list(self, resource_id, resource_type="collection")
Fetches a list of slug representing descriptions within the specified parent description. :param resource_id str: The slug of the description to fetch children from. :param resource_type str: no-op; not required or used in this implementation. :return: A list of strings representing the slugs ...
3.777669
3.234801
1.167821
return self._get_resources( resource_id, recurse_max_level=recurse_max_level, sort_by=sort_by )
def get_resource_component_and_children( self, resource_id, resource_type="collection", level=1, sort_data={}, recurse_max_level=False, sort_by=None, **kwargs )
Fetch detailed metadata for the specified resource_id and all of its children. :param str resource_id: The slug for which to fetch description metadata. :param str resource_type: no-op; not required or used in this implementation. :param int recurse_max_level: The maximum depth level to fetch w...
3.318741
3.985158
0.832775
response = self.get_record(slug) if "parent" in response: return response["parent"] # resource was passed in, which has no higher-up record; # return the same ID else: return slug
def find_parent_id_for_component(self, slug)
Given the slug of a description, returns the parent description's slug. :param string slug: The slug of a description. :return: The URL of the parent record. :rtype: string
11.593734
10.978558
1.056034
response = self._collections_search_request(search_pattern, identifier, page) hits = response.json() results = [r["slug"] for r in hits["results"]] results_so_far = fetched + len(results) if hits["total"] > results_so_far: results.extend( sel...
def find_collection_ids(self, search_pattern="", identifier="", fetched=0, page=1)
Fetches a list of resource URLs for every top-level description in the database. :param string search_pattern: A search pattern to use in looking up resources by title or resourceid. The search will match any title containing this string; for example, "text" will match "this title has t...
3.36973
3.938227
0.855647
skip = (page - 1) * page_size params = { "limit": page_size, "skip": skip, "topLod": "1", "sf0": "_all", "sq0": "", } if search_pattern: params["sq0"] = '"' + self._escape_lucene_query(search_pattern) + '"...
def _collections_search_request( self, search_pattern="", identifier="", page=1, page_size=50, sort_by=None )
Fetches a list of resource URLs for every top-level description in the database. :param string search_pattern: A search pattern to use in looking up resources by title or resourceid. The search will match any title containing this string; for example, "text" will match "this title has t...
3.517119
4.114826
0.854743
def format_record(record): # Get record details full_record = self.get_record(record["slug"]) dates = self._fetch_dates_from_record(record) date_expression = self._fetch_date_expression_from_record(record) # Determine whether descendents exi...
def find_collections( self, search_pattern="", identifier="", fetched=0, page=1, page_size=30, sort_by=None, )
Fetches a list of all resource IDs for every resource in the database. :param string search_pattern: A search pattern to use in looking up resources by title or resourceid. The search will match any title or resourceid containing this string; for example, "text" will match "this title h...
3.277439
3.368918
0.972846
resources_augmented = [] for id in resource_ids: # resource_data = self.get_resource_component_and_children(id, recurse_max_level=2) # resources_augmented.append(resource_data) resources_augmented.append( self.get_resource_component_and_childr...
def augment_resource_ids(self, resource_ids)
Given a list of resource IDs, returns a list of dicts containing detailed information about the specified resources and their children. This function recurses to a maximum of two levels when fetching children from the specified resources. Consult the documentation of ArchivistsToolkitClient.get_resourc...
3.274398
2.728545
1.200053
new_object = {"information_object_slug": information_object_slug} if title is not None: new_object["name"] = title if uri is not None: new_object["uri"] = uri if size is not None: new_object["byte_size"] = size if object_type is n...
def add_digital_object( self, information_object_slug, identifier=None, title=None, uri=None, location_of_originals=None, object_type=None, xlink_show="embed", xlink_actuate="onLoad", restricted=False, use_statement="", use_...
Creates a new digital object.
1.64291
1.651495
0.994801
new_object = {"title": title, "level_of_description": level} if parent_slug is not None: new_object["parent_slug"] = parent_slug # Optionally add date specification new_date = {} if start_date is not None: new_date["start_date"] = start_date ...
def add_child( self, parent_slug=None, title="", level="", start_date=None, end_date=None, date_expression=None, notes=[], )
Adds a new resource component parented within `parent`. :param str parent_slug: The parent's slug. :param str title: A title for the record. :param str level: The level of description. :return: The ID of the newly-created record.
2.589958
2.63912
0.981372
self._delete( urljoin(self.base_url, "informationobjects/{}".format(record_id)), expected_response=204, ) return {"status": "Deleted"}
def delete_record(self, record_id)
Delete a record with record_id.
6.612097
6.446126
1.025747
string_info = [] string_dict = {} for key in plugin_info: try: string_info.append(dict(plugin_info[key])) except ValueError: pass string_rules = {} for raw_info in string_info: ...
def get_string_dict(self, plugin_info)
Convert a section with information of priorities to a string dict. To avoid typos we make all letters lower case when comparing Arguments: plugin_info (dict): A dictionary with plugin information Return: string_dict (dict): A dictionary with str...
2.978586
3.087816
0.964625
try: version_info = self['Version'] except KeyError: raise ValidateError('Config file has to have a Version section') try: float(version_info['version']) except KeyError: raise ValidateError('Config file has to have a version secti...
def version_check(self)
Check if the version entry is in the proper format
3.516978
3.314838
1.06098
vcf_section = self[plugin] try: vcf_field = vcf_section['field'] if not vcf_field in self.vcf_columns: raise ValidateError( "field has to be in {0}\n" "Wrong field name in plugin: {1}".for...
def check_plugin(self, plugin)
Check if the section is in the proper format vcf format. Args: vcf_section (dict): The information from a vcf section Returns: True is it is in the proper format
2.627357
2.597342
1.011556
nxg = nx.DiGraph() if oriented else nx.Graph() for node, succs in graph.items(): for succ in succs: nxg.add_edge(node, succ) return nxg
def dict_to_nx(graph, oriented=False)
Return an nx.Graph equivalent of given {node: succs}
2.20933
1.832902
1.205372
@wraps(func) def wrapped_func(*args, **kwargs): input_graph = args[0] if isinstance(input_graph, nx.DiGraph): return func(*args, **kwargs) else: nx_graph = dict_to_nx(args[0], oriented=True) args = [nx_graph] + list(args[1:]) return fu...
def process_input_graph(func)
Decorator, ensuring first argument is a networkx graph object. If the first arg is a dict {node: succs}, a networkx graph equivalent to the dict will be send in place of it.
2.139873
2.06999
1.03376
result = {} try: # Check if there's a sub-span in progress, otherwise use the main span: span = g.get("subspan") if "subspan" in g else g for header in b3_headers: result[header] = span.get(header) except RuntimeError: # We're probably working outside the App...
def values()
Get the full current set of B3 values. :return: A dict containing the keys "X-B3-TraceId", "X-B3-ParentSpanId", "X-B3-SpanId", "X-B3-Sampled" and "X-B3-Flags" for the current span or subspan. NB some of the values are likely be None, but all keys will be present.
6.950024
5.472189
1.270063
global debug try: headers = request_headers if request_headers else request.headers except RuntimeError: # We're probably working outside the Application Context at this point, likely on startup: # https://stackoverflow.com/questions/31444036/runtimeerror-working-outside-of-appl...
def start_span(request_headers=None)
Collects incoming B3 headers and sets up values for this request as needed. The collected/computed values are stored on the application context g using the defined http header names as keys. :param request_headers: Incoming request headers can be passed explicitly. If not passed, Flask request.headers will ...
5.004369
4.772359
1.048615
@wraps(route) def route_decorator(*args, **kwargs): start_span() try: return route(*args, **kwargs) finally: end_span() return route_decorator
def span(route)
Optional decorator for Flask routes. If you don't want to trace all routes using `Flask.before_request()' and 'Flask.after_request()' you can use this decorator as an alternative way to handle incoming B3 headers: @app.route('/instrumented') @span def instrumented(): ... ...
2.597136
2.772523
0.936741
b3 = values() g.subspan = { # Propagate the trace ID b3_trace_id: b3[b3_trace_id], # Start a new span for the outgoing request b3_span_id: _generate_identifier(), # Set the current span as the parent span b3_parent_span_id: b3[b3_span_id], b3_samp...
def _start_subspan(headers=None)
Sets up a new span to contact a downstream service. This is used when making a downstream service call. It returns a dict containing the required sub-span headers. Each downstream call you make is handled as a new span, so call this every time you need to contact another service. This temporarily updates w...
3.197528
3.018554
1.059291
bit_length = 64 byte_length = int(bit_length / 8) identifier = os.urandom(byte_length) return hexlify(identifier).decode('ascii')
def _generate_identifier()
Generates a new, random identifier in B3 format. :return: A 64-bit random identifier, rendered as a hex String.
3.718155
3.435266
1.082348
span = values() _log.debug(message + ": {span} in trace {trace}. (Parent span: {parent}).".format( span=span.get(b3_span_id), trace=span.get(b3_trace_id), parent=span.get(b3_parent_span_id), ))
def _info(message)
Convenience function to log current span values.
5.947663
4.603339
1.292033
if 'autodeclare' in settings.CONFIGURATIONS[configuration]: for annotationtype, set in settings.CONFIGURATIONS['configuration']['autodeclare']: try: r = flat.comm.query(request, "USE pub/" + docid + " DECLARE " + annotationtype + " OF " + set) except Exception as...
def pub_view(request, docid, configuration)
The initial view, does not provide the document content yet
10.898276
11.10076
0.981759
try: for refversion, responseversion in zip([int(x) for x in REQUIREFOLIADOCSERVE.split('.')], [int(x) for x in version.split('.')]): if responseversion > refversion: return 1 #response is newer than library elif responseversion < refversion: retu...
def checkversion(version)
Checks foliadocserve version, returns 1 if the document is newer than the library, -1 if it is older, 0 if it is equal
5.787853
3.792331
1.526199
if flat.users.models.hasreadpermission(request.user.username, namespace, request): if 'autodeclare' in settings.CONFIGURATIONS[request.session['configuration']]: if flat.users.models.haswritepermission(request.user.username, namespace, request): for annotationtype, set in se...
def view(request, namespace, docid)
The initial view, does not provide the document content yet
6.527898
6.582222
0.991747
perspective = request.GET.get('perspective','document') if context is None: context = {} if 'configuration' in request.session: configuration = request.session['configuration'] elif configuration is None: return fatalerror(request, "No configuration specified") if configuration ...
def initdoc(request, namespace, docid, mode, template, context=None, configuration=None)
Initialise a document (not invoked directly)
4.371591
4.337416
1.007879
flatargs = { 'customslicesize': request.POST.get('customslicesize',settings.CONFIGURATIONS[configuration].get('customslicesize','50')), #for pagination of search results } #stupid compatibility stuff if sys.version < '3': if hasattr(request, 'body'): data = json.loads(un...
def query_helper(request,namespace, docid, configuration=None)
Does the actual query, called by query() or pub_query(), not directly
6.219566
6.131243
1.014405
try: r = flat.comm.get(request, '/poll/pub/' + docid + '/', False) except URLError: return HttpResponseForbidden("Unable to connect to the document server [viewer/poll]") return HttpResponse(r, content_type='application/json')
def pub_poll(request, docid)
The initial viewer, does not provide the document content yet
9.462301
9.586794
0.987014
_next(self) if not self.autoincrement_support: return id_field = self.form['id'] del id_field.attrs['required'] id_field.attrs['disabled'] = 'disabled' id_field.getter = _('auto_incremented', default='auto incremented')
def prepare(_next, self)
Hook after prepare and set 'id' disabled.
8.236217
7.597244
1.084106
try: users = model.parent.backend uid = model.model.name del users[uid] users() model.parent.invalidate() localizer = get_localizer(request) message = localizer.translate(_( 'delete_user_from_database', default="Deleted user '${uid...
def delete_user_action(model, request)
Delete user from database.
4.486872
4.263828
1.052311
group_id = request.params.get('id') if not group_id: group_ids = request.params.getall('id[]') else: group_ids = [group_id] try: user = model.model validate_add_users_to_groups(model, [user.id], group_ids) groups = user.root.groups for group_id in gro...
def user_add_to_group_action(model, request)
Add user to group.
3.166634
3.161793
1.001531
try: groups = model.parent.backend uid = model.model.name del groups[uid] groups() model.parent.invalidate() except Exception as e: return { 'success': False, 'message': str(e) } localizer = get_localizer(request) messa...
def delete_group_action(model, request)
Delete group from database.
4.825639
4.611214
1.046501
user_id = request.params.get('id') if not user_id: user_ids = request.params.getall('id[]') else: user_ids = [user_id] try: group = model.model validate_add_users_to_groups(model, user_ids, [group.id]) for user_id in user_ids: group.add(user_id) ...
def group_add_user_action(model, request)
Add user to group.
3.156128
3.137689
1.005876
_next(self) if not self.roles_support: return if not self.request.has_permission('manage', self.model.parent): # XXX: yafowil selection display renderer return value = [] if self.action_resource == 'edit': value = self.mode...
def prepare(_next, self)
Hook after prepare and set 'principal_roles' as selection to ``self.form``.
8.447248
7.634198
1.106501
# custom UGM styles cfg.merged.css.protected.append((static_resources, 'styles.css')) # custom UGM javascript cfg.merged.js.protected.append((static_resources, 'ugm.js')) # UGM settings register_config('ugm_general', GeneralSettings) register_config('ugm_server', ServerSettings) r...
def initialize_ugm(config, global_config, local_config)
Initialize UGM.
4.984005
5.02063
0.992705