code stringlengths 1 18.2k |
|---|
been altered.""" state = variables.get(block.args[0], None) if state == cls.STATE_NOT_MODIFIED: variables[block.args[0]] = cls.STATE_MODIFIED green_flag, other = partition_scripts(scripts, cls.HAT_GREEN_FLAG) variables = dict((x, cls.STATE_NOT_MODIFIED) for x in variables) for script in green_flag: in_zone = True for n... |
None: continue # Not a variable we care about if in_zone and level == 0: # Success! if state == cls.STATE_NOT_MODIFIED: state = cls.STATE_INITIALIZED else: # Multiple when green flag clicked conflict # TODO: Need to allow multiple sets of a variable # within the same script # print 'CONFLICT', script state = cls.STATE_... |
state == cls.STATE_NOT_MODIFIED: state = cls.STATE_MODIFIED variables[block.args[0]] = state elif name == 'change %s effect by %s': conditionally_set_not_modified() for script in other: for name, _, block in cls.iter_blocks(script.blocks): if name in ('change %s effect by %s', 'set %s effect to %s'): conditionally_set_... |
def analyze(self, scratch, **kwargs): """Run and return the results of the VariableInitialization plugin.""" variables = dict((x, self.variable_state(x.scripts, x.variables)) for x in scratch.sprites) variables['global'] = self.variable_state(self.iter_scripts(scratch), scratch.stage.variables) # Output for now import ... |
def finalize(self): """Output the default sprite names found in the project.""" print('{} default sprite names found:'.format(self.total_default)) for name in self.list_default: print(name) |
def analyze(self, scratch, **kwargs): """Run and return the results from the SpriteNaming plugin.""" for sprite in self.iter_sprites(scratch): for default in self.default_names: if default in sprite.name: self.total_default += 1 self.list_default.append(sprite.name) |
def get_tunneling(handler, registry): """ Allows all methods to be tunneled via GET for dev/debuging purposes. """ log.info('get_tunneling enabled') def get_tunneling(request): if request.method == 'GET': method = request.GET.pop('_m', 'GET') request.method = method if method in ['POST', 'PUT', 'PATCH']: get_params = r... |
def enable_selfalias(config, id_name): """ This allows replacing id_name with "self". e.g. /users/joe/account == /users/self/account if joe is in the session as an authorized user """ def context_found_subscriber(event): request = event.request user = getattr(request, 'user', None) if (request.matchdict and request.mat... |
def convert_dotted(params): """ Convert dotted keys in :params: dictset to a nested dictset. E.g. {'settings.foo': 'bar'} -> {'settings': {'foo': 'bar'}} """ if not isinstance(params, dictset): params = dictset(params) dotted_items = {k: v for k, v in params.items() if '.' in k} if dotted_items: dicts = [str2dict(key, ... |
dotted_items.keys()]) params.update(dict(dotted)) return params |
def prepare_request_params(self, _query_params, _json_params): """ Prepare query and update params. """ self._query_params = dictset( _query_params or self.request.params.mixed()) self._json_params = dictset(_json_params) ctype = self.request.content_type if self.request.method in ['POST', 'PUT', 'PATCH']: if ctype == ... |
def set_override_rendered(self): """ Set self.request.override_renderer if needed. """ if '' in self.request.accept: self.request.override_renderer = self._default_renderer elif 'application/json' in self.request.accept: self.request.override_renderer = 'nefertari_json' elif 'text/plain' in self.request.accept: self.re... |
def _setup_aggregation(self, aggregator=None): """ Wrap `self.index` method with ESAggregator. This makes `self.index` to first try to run aggregation and only on fail original method is run. Method is wrapped only if it is defined and `elasticsearch.enable_aggregations` setting is true. """ from nefertari.elasticsearc... |
enabled') return index = getattr(self, 'index', None) index_defined = index and index != self.not_allowed_action if index_defined: self.index = aggregator(self).wrap(self.index) |
def get_collection_es(self): """ Query ES collection and return results. This is default implementation of querying ES collection with `self._query_params`. It must return found ES collection results for default response renderers to work properly. """ from nefertari.elasticsearch import ES return ES(self.Model.__name_... |
def fill_null_values(self): """ Fill missing model fields in JSON with {key: null value}. Only run for PUT requests. """ if not self.Model: log.info("%s has no model defined" % self.__class__.__name__) return empty_values = self.Model.get_null_values() for field, value in empty_values.items(): if field not in self._jso... |
def set_public_limits(self): """ Set public limits if auth is enabled and user is not authenticated. Also sets default limit for GET, HEAD requests. """ if self.request.method.upper() in ['GET', 'HEAD']: self._query_params.process_int_param('_limit', 20) if self._auth_enabled and not getattr(self.request, 'user', None)... |
def convert_ids2objects(self): """ Convert object IDs from `self._json_params` to objects if needed. Only IDs that belong to relationship field of `self.Model` are converted. """ if not self.Model: log.info("%s has no model defined" % self.__class__.__name__) return for field in self._json_params.keys(): if not engine.... |
def setup_default_wrappers(self): """ Setup defaulf wrappers. Wrappers are applied when view method does not return instance of Response. In this case nefertari renderers call wrappers and handle response generation. """ # Index self._after_calls['index'] = [ wrappers.wrap_in_dict(self.request), wrappers.add_meta(self.... |
wrappers.add_object_url(self.request), ] # Replace self._after_calls['replace'] = [ wrappers.wrap_in_dict(self.request), wrappers.add_meta(self.request), wrappers.add_object_url(self.request), ] # Privacy wrappers if self._auth_enabled: for meth in ('index', 'show', 'create', 'update', 'replace'): self._after_calls[met... |
def migrate_codec(config_old, config_new): '''Migrate data from mongodict <= 0.2.1 to 0.3.0 `config_old` and `config_new` should be dictionaries with the keys regarding to MongoDB server: - `host` - `port` - `database` - `collection` ''' assert mongodict.__version__ in [(0, 3, 0), (0, 3, 1)] connection = pymongo.Connec... |
start_time = time.time() for counter, pair in enumerate(collection.find(), start=1): key, value = pair['_id'], pair['value'] new_dict[key] = value if counter % REPORT_INTERVAL == 0: print_report(counter, total_pairs, start_time) print_report(counter, total_pairs, start_time) print('') |
def from_dict(cls, data, model): """ Generate map of `fieldName: clsInstance` from dict. :param data: Dict where keys are field names and values are new values of field. :param model: Model class to which fields from :data: belong. """ model_provided = model is not None result = {} for name, new_value in data.items(): ... |
model.get_field_params(name) result[name] = cls(**kwargs) return result |
def register(self): """ Register new user by POSTing all required data. """ user, created = self.Model.create_account( self._json_params) if not created: raise JHTTPConflict('Looks like you already have an account.') self.request._user = user pk_field = user.pk_field() headers = remember(self.request, getattr(user, pk_... |
def register(self): """ Register a new user by POSTing all required data. User's `Authorization` header value is returned in `WWW-Authenticate` header. """ user, created = self.Model.create_account(self._json_params) if user.api_key is None: raise JHTTPBadRequest('Failed to generate ApiKey for user') if not created: ra... |
def claim_token(self, **params): """Claim current token by POSTing 'login' and 'password'. User's `Authorization` header value is returned in `WWW-Authenticate` header. """ self._json_params.update(params) success, self.user = self.Model.authenticate_by_password( self._json_params) if success: headers = remember(self.r... |
def reset_token(self, **params): """ Reset current token by POSTing 'login' and 'password'. User's `Authorization` header value is returned in `WWW-Authenticate` header. """ response = self.claim_token(**params) if not self.user: return response self.user.api_key.reset_token() headers = remember(self.request, self.user... |
def _apply_nested_privacy(self, data): """ Apply privacy to nested documents. :param data: Dict of data to which privacy is already applied. """ kw = { 'is_admin': self.is_admin, 'drop_hidden': self.drop_hidden, } for key, val in data.items(): if is_document(val): data[key] = apply_privacy(self.request)(result=val, **k... |
def _set_object_self(self, obj): """ Add '_self' key value to :obj: dict. """ from nefertari.elasticsearch import ES location = self.request.path_url route_kwargs = {} """ Check for parents """ if self.request.matchdict: route_kwargs.update(self.request.matchdict) try: type_, obj_pk = obj['_type'], obj['_pk'] except Ke... |
def get_root_resource(config): """Returns the root resource.""" app_package_name = get_app_package_name(config) return config.registry._root_resources.setdefault( app_package_name, Resource(config)) |
def add_resource_routes(config, view, member_name, collection_name, **kwargs): """ ``view`` is a dotted name of (or direct reference to) a Python view class, e.g. ``'my.package.views.MyView'``. ``member_name`` should be the appropriate singular version of the resource given your locale and used with members of the coll... |
All keyword arguments are optional. ``path_prefix`` Prepends the URL path for the Route with the path_prefix given. This is most useful for cases where you want to mix resources or relations between resources. ``name_prefix`` Prepends the route names that are generated with the name_prefix given. Combined with the path... |
relations. Example:: config.add_resource_routes( 'myproject.views:CategoryView', 'message', 'messages', path_prefix='/category/{category_id}', name_prefix="category_") # GET /category/7/messages/1 # has named route "category_message" """ view = maybe_dotted(view) path_prefix = kwargs.pop('path_prefix', '') name_prefix ... |
If factory is not set, than auth should be False _auth = kwargs.pop('auth', None) and _factory _traverse = (kwargs.pop('traverse', None) or id_name) if _factory else None action_route = {} added_routes = {} def add_route_and_view(config, action, route_name, path, request_method, **route_kwargs): if route_name not in ad... |
= PERMISSIONS[action] else: permission = None config.add_view(view=view, attr=action, route_name=route_name, request_method=request_method, permission=permission, **kwargs) config.commit() if collection_name == member_name: collection_name = collection_name + '_collection' if collection_name: add_route_and_view( config... |
'replace', name_prefix + member_name, path + id_name, 'PUT', traverse=_traverse) add_route_and_view( config, 'update', name_prefix + member_name, path + id_name, 'PATCH', traverse=_traverse) add_route_and_view( config, 'create', name_prefix + (collection_name or member_name), path, 'POST') add_route_and_view( config, '... |
traverse=_traverse) add_route_and_view( config, 'delete_many', name_prefix + (collection_name or member_name), path, 'DELETE', traverse=_traverse) return action_route |
def get_default_view_path(resource): "Returns the dotted path to the default view class." parts = [a.member_name for a in resource.ancestors] +\ [resource.collection_name or resource.member_name] if resource.prefix: parts.insert(-1, resource.prefix) view_file = '%s' % '_'.join(parts) view = '%s:%sView' % (view_file, sn... |
def get_ancestors(self): "Returns the list of ancestor resources." if self._ancestors: return self._ancestors if not self.parent: return [] obj = self.resource_map.get(self.parent.uid) while obj and obj.member_name: self._ancestors.append(obj) obj = obj.parent self._ancestors.reverse() return self._ancestors |
def add(self, member_name, collection_name='', parent=None, uid='', **kwargs): """ :param member_name: singular name of the resource. It should be the appropriate singular version of the resource given your locale and used with members of the collection. :param collection_name: plural name of the resource. It will be u... |
if collection_name is empty, it means resource is singular :param parent: parent resource name or object. :param uid: unique name for the resource :param kwargs: view: custom view to overwrite the default one. the rest of the keyward arguments are passed to add_resource_routes call. :return: ResourceMap object """ # se... |
type(parent) is str else parent or self) prefix = kwargs.pop('prefix', '') uid = (uid or ':'.join(filter(bool, [parent.uid, prefix, member_name]))) if uid in self.resource_map: raise ValueError('%s already exists in resource map' % uid) # Use id_name of parent for singular views to make url generation # easier id_name ... |
uid=uid, id_name=id_name, prefix=prefix) view = maybe_dotted( kwargs.pop('view', None) or get_default_view_path(new_resource)) for name, val in kwargs.pop('view_args', {}).items(): setattr(view, name, val) root_resource = self.config.get_root_resource() view.root_resource = root_resource new_resource.view = view path_s... |
if prefix: kwargs['path_prefix'] += '/' + prefix name_segs = [a.member_name for a in new_resource.ancestors] name_segs.insert(1, prefix) name_segs = [seg for seg in name_segs if seg] if name_segs: kwargs['name_prefix'] = '_'.join(name_segs) + ':' new_resource.renderer = kwargs.setdefault( 'renderer', view._default_rend... |
# add all route names for this resource as keys in the dict, # so its easy to find it in the view. self.resource_map.update(dict.fromkeys( list(new_resource.action_route_map.values()), new_resource)) # Store resources in {modelName: resource} map if: # * Its view has Model defined # * It's not singular # * Its parent i... |
not None and not new_resource.is_singular if is_collection: is_needed = (model.__name__ not in self.model_collections or new_resource.parent is root_resource) if is_needed: self.model_collections[model.__name__] = new_resource parent.children.append(new_resource) view._resource = new_resource view._factory = _factory r... |
def add_from_child(self, resource, **kwargs): """ Add a resource with its all children resources to the current resource. """ new_resource = self.add( resource.member_name, resource.collection_name, **kwargs) for child in resource.children: new_resource.add_from_child(child, **kwargs) |
def add(self, path): """ Add the path of a data set to the list of available sets NOTE: a data set is assumed to be a pickled and gzip compressed Pandas DataFrame Parameters ---------- path : str """ name_with_ext = os.path.split(path)[1] # split directory and filename name = name_with_ext.split('.')[0] # remove extens... |
def unpack(self, name): """ Unpacks a data set to a Pandas DataFrame Parameters ---------- name : str call `.list` to see all availble datasets Returns ------- pd.DataFrame """ path = self.list[name] df = pd.read_pickle(path, compression='gzip') return df |
def six_frame(genome, table, minimum = 10): """ translate each sequence into six reading frames """ for seq in parse_fasta(genome): dna = Seq(seq[1].upper().replace('U', 'T'), IUPAC.ambiguous_dna) counter = 0 for sequence in ['f', dna], ['rc', dna.reverse_complement()]: direction, sequence = sequence for frame in range... |
'%s_%s table=%s frame=%s-%s %s' % \ (seq[0].split()[0], counter, table, frame+1, \ direction, ' '.join(seq[0].split()[1:])) yield [header, prot] |
def publish_processed_network_packets( name="not-set", task_queue=None, result_queue=None, need_response=False, shutdown_msg="SHUTDOWN"): """ # Redis/RabbitMQ/SQS messaging endpoints for pub-sub routing_key = ev("PUBLISH_EXCHANGE", "reporting.accounts") queue_name = ev("PUBLISH_QUEUE", "reporting.accounts") auth_url = ... |
include_filter_key = filter_key filter_keys = [filter_key] log.info(("START consumer={} " "forward={}:{} with " "key={} filters={}") .format(name, forward_host, forward_port, include_filter_key, filter_key)) forward_skt = None not_done = True while not_done: if not forward_skt: forward_skt = connect_forwarder( forward_... |
shutdown case try: log.debug(("{} parsing") .format(name)) source = next_task.source packet = next_task.payload if not packet: log.error(("{} invalid task found " "{} missing payload") .format(name, next_task)) break log.debug(("{} found msg from src={}") .format(name, source)) network_data = parse_network_data( data_p... |
packet={} " "data={}") .format(name, network_data["id"], network_data["data_type"], network_data["target_data"])) if not forward_skt: forward_skt = connect_forwarder( forward_host=forward_host, forward_port=forward_port) if forward_skt: if network_data["stream"]: sent = False while not sent: try: log.info("sending={}".... |
log.info("sent={}".format( network_data["stream"])) if need_response: log.info("receiving") cdr_res = forward_skt.recv(1024) log.info(("cdr - res{}") .format(cdr_res)) else: log.info(("{} EMPTY stream={} " "error={} status={}") .format( name, network_data["stream"], network_data["err"], network_data["status"])) else: l... |
unknown={} packet={} " "error={} status={}") .format(name, network_data["id"], network_data["data_type"], network_data["error"], network_data["status"])) # end of if valid or not data except KeyboardInterrupt as k: log.info(("{} stopping") .format(name)) break except Exception as e: log.error(("{} failed packaging pack... |
answer = "processed: {}".format(next_task()) result_queue.put(answer) # end of while if forward_skt: try: forward_skt.close() log.info("CLOSED connection") forward_skt = None except Exception: log.info("CLOSED connection") # end of cleaning up forwarding socket log.info("{} Done".format(name)) return |
def run_main( need_response=False, callback=None): """run_main start the packet consumers and the packet processors :param need_response: should send response back to publisher :param callback: handler method """ stop_file = ev("STOP_FILE", "/opt/stop_recording") num_workers = int(ev("NUM_WORKERS", "1")) shutdown_msg =... |
num_workers=num_workers, tasks=tasks, queue_to_consume=queue_to_consume, shutdown_msg=shutdown_msg, consumer_class=WorkerToProcessPackets, callback=callback) log.info("creating socket") skt = create_layer_2_socket() log.info("socket created") not_done = True while not_done: if not skt: log.info("Failed to create layer ... |
log.info(("Detected stop_file={}") .format(stop_file)) not_done = False break # stop if the file was created during a wait loop tasks.put(NetworkPacketTask(source=host, payload=packet)) except KeyboardInterrupt as k: log.info("Stopping") not_done = False break except Exception as e: log.error(("Failed reading socket wi... |
Wait for all of the tasks to finish if need_response: log.info("Waiting for tasks to finish") tasks.join() log.info("Done waiting for tasks to finish") |
def best_model(seq2hmm): """ determine the best model: archaea, bacteria, eukarya (best score) """ for seq in seq2hmm: best = [] for model in seq2hmm[seq]: best.append([model, sorted([i[-1] for i in seq2hmm[seq][model]], reverse = True)[0]]) best_model = sorted(best, key = itemgetter(1), reverse = True)[0][0] seq2hmm[s... |
def check_gaps(matches, gap_threshold = 0): """ check for large gaps between alignment windows """ gaps = [] prev = None for match in sorted(matches, key = itemgetter(0)): if prev is None: prev = match continue if match[0] - prev[1] >= gap_threshold: gaps.append([prev, match]) prev = match return [[i[0][1], i[1][0]] fo... |
def check_overlap(current, hit, overlap = 200): """ determine if sequence has already hit the same part of the model, indicating that this hit is for another 16S rRNA gene """ for prev in current: p_coords = prev[2:4] coords = hit[2:4] if get_overlap(coords, p_coords) >= overlap: return True return False |
def check_order(current, hit, overlap = 200): """ determine if hits are sequential on model and on the same strand * if not, they should be split into different groups """ prev_model = current[-1][2:4] prev_strand = current[-1][-2] hit_model = hit[2:4] hit_strand = hit[-2] # make sure they are on the same strand if pre... |
strand if prev_strand == '+' and (prev_model[1] - hit_model[0] >= overlap): return False # check for sequential hits on - strand if prev_strand == '-' and (hit_model[1] - prev_model[0] >= overlap): return False else: return True |
def hit_groups(hits): """ * each sequence may have more than one 16S rRNA gene * group hits for each gene """ groups = [] current = False for hit in sorted(hits, key = itemgetter(0)): if current is False: current = [hit] elif check_overlap(current, hit) is True or check_order(current, hit) is False: groups.append(curre... |
def find_coordinates(hmms, bit_thresh): """ find 16S rRNA gene sequence coordinates """ # get coordinates from cmsearch output seq2hmm = parse_hmm(hmms, bit_thresh) seq2hmm = best_model(seq2hmm) group2hmm = {} # group2hmm[seq][group] = [model, strand, coordinates, matches, gaps] for seq, info in list(seq2hmm.items()): ... |
single 16S gene # determine matching strand based on best hit best = sorted(group, reverse = True, key = itemgetter(-1))[0] strand = best[5] coordinates = [i[0] for i in group] + [i[1] for i in group] coordinates = [min(coordinates), max(coordinates), strand] # make sure all hits are to the same strand matches = [i for... |
= [[gstart, gend], [gstart2, gend2]] gaps = check_gaps(matches) group2hmm[seq][group_num] = [info[0], strand, coordinates, matches, gaps] return group2hmm |
def get_info(line, bit_thresh): """ get info from either ssu-cmsearch or cmsearch output """ if len(line) >= 18: # output is from cmsearch id, model, bit, inc = line[0].split()[0], line[2], float(line[14]), line[16] sstart, send, strand = int(line[7]), int(line[8]), line[9] mstart, mend = int(line[5]), int(line[6]) eli... |
threshold, ', file=sys.stderr) print('# please specify a bit score threshold', file=sys.stderr) exit() id, model, bit = line[1].split()[0], line[0], float(line[6]) inc = '!' # this is not a feature of ssu-cmsearch sstart, send = int(line[2]), int(line[3]) mstart, mend = int(4), int(5) if send >= sstart: strand = '+' el... |
cmsearch supported', file=sys.stderr) exit() coords = [sstart, send] sstart, send = min(coords), max(coords) mcoords = [mstart, mend] mstart, mend = min(mcoords), max(mcoords) return id, model, bit, sstart, send, mstart, mend, strand, inc |
def check_buffer(coords, length, buffer): """ check to see how much of the buffer is being used """ s = min(coords[0], buffer) e = min(length - coords[1], buffer) return [s, e] |
def convert_parser_to(parser, parser_or_type, metadata_props=None): """ :return: a parser of type parser_or_type, initialized with the properties of parser. If parser_or_type is a type, an instance of it must contain a update method. The update method must also process the set of properties supported by MetadataParser ... |
:param parser_or_type: a parser (or content) or type of parser to return :see: get_metadata_parser(metadata_container) for more on how parser_or_type is treated """ old_parser = parser if isinstance(parser, MetadataParser) else get_metadata_parser(parser) new_parser = get_metadata_parser(parser_or_type) for prop in (me... |
def get_metadata_parser(metadata_container, **metadata_defaults): """ Takes a metadata_container, which may be a type or instance of a parser, a dict, string, or file. :return: a new instance of a parser corresponding to the standard represented by metadata_container :see: get_parsed_content(metdata_content) for more o... |
metadata_container = metadata_container().update(**metadata_defaults) xml_root, xml_tree = get_parsed_content(metadata_container) # The get_parsed_content method ensures only these roots will be returned parser = None if parser_type is not None: parser = parser_type(xml_tree, **metadata_defaults) elif xml_root in ISO_R... |
ArcGISParser(xml_tree, **metadata_defaults) return parser |
def get_parsed_content(metadata_content): """ Parses any of the following types of content: 1. XML string or file object: parses XML content 2. MetadataParser instance: deep copies xml_tree 3. Dictionary with nested objects containing: - name (required): the name of the element tag - text: the text contained by element... |
a List of converted child elements :raises InvalidContent: if the XML is invalid or does not conform to a supported metadata standard :raises NoContent: If the content passed in is null or otherwise empty :return: the XML root along with an XML Tree parsed by and compatible with element_utils """ _import_parsers() # Pr... |
raise NoContent('Metadata has no data') else: if isinstance(metadata_content, MetadataParser): xml_tree = deepcopy(metadata_content._xml_tree) elif isinstance(metadata_content, dict): xml_tree = get_element_tree(metadata_content) else: try: # Strip name spaces from file or XML content xml_tree = get_element_tree(metada... |
= get_element_name(xml_tree) if xml_root is None: raise NoContent('Metadata contains no data') elif xml_root not in VALID_ROOTS: content = type(metadata_content).__name__ raise InvalidContent('Invalid root element for {content}: {xml_root}', content=content, xml_root=xml_root) return xml_root, xml_tree |
def _import_parsers(): """ Lazy imports to prevent circular dependencies between this module and utils """ global ARCGIS_NODES global ARCGIS_ROOTS global ArcGISParser global FGDC_ROOT global FgdcParser global ISO_ROOTS global IsoParser global VALID_ROOTS if ARCGIS_NODES is None or ARCGIS_ROOTS is None or ArcGISParser i... |
gis_metadata.fgdc_metadata_parser import FGDC_ROOT from gis_metadata.fgdc_metadata_parser import FgdcParser if ISO_ROOTS is None or IsoParser is None: from gis_metadata.iso_metadata_parser import ISO_ROOTS from gis_metadata.iso_metadata_parser import IsoParser if VALID_ROOTS is None: VALID_ROOTS = {FGDC_ROOT}.union(ARC... |
def _init_metadata(self): """ Dynamically sets attributes from a Dictionary passed in by children. The Dictionary will contain the name of each attribute as keys, and either an XPATH mapping to a text value in _xml_tree, or a function that takes no parameters and returns the intended value. """ if self._data_map is Non... |
parse(val) for prop in self._data_map: setattr(self, prop, parse_property(self._xml_tree, None, self._data_map, prop)) self.has_data = any(getattr(self, prop) for prop in self._data_map) |
def _init_data_map(self): """ Default data map initialization: MUST be overridden in children """ if self._data_map is None: self._data_map = {'_root': None} self._data_map.update({}.fromkeys(self._metadata_props)) |
def _get_template(self, root=None, **metadata_defaults): """ Iterate over items metadata_defaults {prop: val, ...} to populate template """ if root is None: if self._data_map is None: self._init_data_map() root = self._xml_root = self._data_map['_root'] template_tree = self._xml_tree = create_element_tree(root) for pro... |
def _get_xpath_for(self, prop): """ :return: the configured xpath for a given property """ xpath = self._data_map.get(prop) return getattr(xpath, 'xpath', xpath) |
def _parse_complex(self, prop): """ Default parsing operation for a complex struct """ xpath_root = None xpath_map = self._data_structures[prop] return parse_complex(self._xml_tree, xpath_root, xpath_map, prop) |
def _parse_complex_list(self, prop): """ Default parsing operation for lists of complex structs """ xpath_root = self._get_xroot_for(prop) xpath_map = self._data_structures[prop] return parse_complex_list(self._xml_tree, xpath_root, xpath_map, prop) |
def _parse_dates(self, prop=DATES): """ Creates and returns a Date Types data structure parsed from the metadata """ return parse_dates(self._xml_tree, self._data_structures[prop]) |
def _update_complex(self, **update_props): """ Default update operation for a complex struct """ prop = update_props['prop'] xpath_root = self._get_xroot_for(prop) xpath_map = self._data_structures[prop] return update_complex(xpath_root=xpath_root, xpath_map=xpath_map, **update_props) |
def _update_complex_list(self, **update_props): """ Default update operation for lists of complex structs """ prop = update_props['prop'] xpath_root = self._get_xroot_for(prop) xpath_map = self._data_structures[prop] return update_complex_list(xpath_root=xpath_root, xpath_map=xpath_map, **update_props) |
def _update_dates(self, xpath_root=None, **update_props): """ Default update operation for Dates metadata :see: gis_metadata.utils._complex_definitions[DATES] """ tree_to_update = update_props['tree_to_update'] prop = update_props['prop'] values = (update_props['values'] or {}).get(DATE_VALUES) or u'' xpaths = self._da... |
def write(self, use_template=False, out_file_or_path=None, encoding=DEFAULT_ENCODING): """ Validates instance properties, updates an XML tree with them, and writes the content to a file. :param use_template: if True, updates a new template XML tree; otherwise the original XML tree :param out_file_or_path: optionally ov... |
not out_file_or_path: # FileNotFoundError doesn't exist in Python 2 raise IOError('Output file path has not been provided') write_element(self.update(use_template), out_file_or_path, encoding) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.