code
stringlengths
1
18.2k
function. arg_spec = {} is_option = False # Get the type and default from the annotation. arg_type, description = _get_type_description(param.annotation) # Get the default value default = param.default # If there is no explicit type, and the default is present and not None, # infer the type from the default. if arg_typ...
# Switches are always options is_option = True # Special case for file types: make it a string type, for filename elif isinstance(default, IOBase): arg_spec['type'] = str # TODO: special case for list type. # - How to specificy type of list members? # - param: [int] # - param: int =[] # - action='append' vs nargs='*' e...
# Add the first letter as a -short option. for letter in name[0], name[0].swapcase(): if letter not in used_char_args: used_char_args.add(letter) flags.append('-{}'.format(letter)) break # If the parameter is a --long option, or is a -short option that # somehow failed to get a flag, add it. if len(name) > 1 or not fla...
def make_parser(func_sig, description, epilog, add_nos): ''' Given the signature of a function, create an ArgumentParser ''' parser = ArgumentParser(description=description, epilog=epilog) used_char_args = {'h'} # Arange the params so that single-character arguments are first. This # esnures they don't have to get --lo...
def parse_docstring(docstring): ''' Given a docstring, parse it into a description and epilog part ''' if docstring is None: return '', '' parts = _DOCSTRING_SPLIT.split(docstring) if len(parts) == 1: return docstring, '' elif len(parts) == 2: return parts[0], parts[1] else: raise TooManySplitsError()
def autoparse( func=None, *, description=None, epilog=None, add_nos=False, parser=None): ''' This decorator converts a function that takes normal arguments into a function which takes a single optional argument, argv, parses it using an argparse.ArgumentParser, and calls the underlying function with the parsed argument...
same respective argparse parameters. If no description is given, it defaults to the decorated functions's docstring, if present. If add_nos is True, every boolean option (that is, every parameter with a default of True/False or a type of bool) will have a --no- version created as well, which inverts the option. For ins...
decorated function is attached to the result as the `func` attribute, and the parser is attached as the `parser` attribute. ''' # If @autoparse(...) is used instead of @autoparse if func is None: return lambda f: autoparse( f, description=description, epilog=epilog, add_nos=add_nos, parser=parser) func_sig = signature(...
parser, and return the wrapper. autoparse_wrapper.func = func autoparse_wrapper.parser = parser return autoparse_wrapper
def smart_open(filename_or_file, *args, **kwargs): ''' This context manager allows you to open a filename, if you want to default some already-existing file object, like sys.stdout, which shouldn't be closed at the end of the context. If the filename argument is a str, bytes, or int, the file object is created via a ca...
was a filename, f is closed at the end here. ''' if isinstance(filename_or_file, (str, bytes, int)): with open(filename_or_file, *args, **kwargs) as file: yield file else: yield filename_or_file
def list_comments(self, page=0): """ Get the comments of current object :param page: the page starting at 0 :return: the emails :rtype: list """ from highton.models.comment import Comment params = {'page': int(page) * self.COMMENT_OFFSET} return fields.ListField( name=self.ENDPOINT, init_class=Comment ).decode( self.el...
def update_status(self, status): """ Updates the status of the deal :param status: status have to be ('won', 'pending', 'lost') :return: successfull response or raise Exception :rtype: """ assert (status in (HightonConstants.WON, HightonConstants.PENDING, HightonConstants.LOST)) from highton.models import Status status...
def dict_merge(s, m): """Recursively merge one dict into another.""" if not isinstance(m, dict): return m out = copy.deepcopy(s) for k, v in m.items(): if k in out and isinstance(out[k], dict): out[k] = dict_merge(out[k], v) else: out[k] = copy.deepcopy(v) return out
def settings(instance): """Definition to set settings from config file to the app instance.""" with open(instance.root_dir + '/Config/config.yml') as config: config = yaml.load(config) instance.name = config['name'] instance.port = config['web']['port'] # default host instance.host = "http://localhost" if 'host' in con...
def routing(routes, request): """Definition for route matching : helper""" # strip trailing slashes from request path path = request.path.strip('/') # iterate through routes to match args = {} for name, route in routes.items(): if route['path'] == '^': # this section exists because regex doesn't work for null character...
if not values[i] and route['variables'][i] in route['defaults']: values[i] = route['defaults'][route['variables'][i]] args[route['variables'][i]] = values[i] # we have the variables we need, args, path, controller return { 'kwargs' : args, 'controller' : route['controller'] } raise TornNotFoundError
def uri_creator(uri, regex, defaults): """Creates url and replaces regex and gives variables""" # strip trailing slash uri = uri.strip('/') # take out variables in uri matches = re.findall('{[a-zA-Z0-9\_]+}', uri) default_regex = '[a-zA-Z0-9]+' variables = [] # iter through matches and replace it with user given regex ...
'uri' : uri }
def get(cls, object_id): """ Retrieves a single model :param object_id: the primary id of the model :type object_id: integer :return: the object of the parsed xml object :rtype: object """ return fields.ObjectField(name=cls.ENDPOINT, init_class=cls).decode( cls.element_from_string( cls._get_request(endpoint=cls.ENDPOIN...
def cached_unless_authenticated(timeout=50, key_prefix='default'): """Cache anonymous traffic.""" def caching(f): @wraps(f) def wrapper(*args, **kwargs): cache_fun = current_cache.cached( timeout=timeout, key_prefix=key_prefix, unless=lambda: current_cache_ext.is_authenticated_callback()) return cache_fun(f)(*args, **k...
async def reset(self): """ reset the tournament on Challonge |methcoro| Note: |from_api| Reset a tournament, clearing all of its scores and attachments. You can then add/remove/edit participants before starting the tournament again. Raises: APIException """ params = { 'include_participants': 1 if AUTO_GET_PARTICIPANTS ...
async def update(self, **params): """ update some parameters of the tournament Use this function if you want to update multiple options at once, but prefer helpers functions like :func:`allow_attachments`, :func:`set_start_date`... |methcoro| Args: params: one or more of: ``name`` ``tournament_type`` ``url`` ``subdomai...
async def set_start_date(self, date: str, time: str, check_in_duration: int = None): """ set the tournament start date (and check in duration) |methcoro| Args: date: fomatted date as YYYY/MM/DD (2017/02/14) time: fromatted time as HH:MM (20:15) check_in_duration (optional): duration in minutes Raises: APIException """ ...
async def update_notifications(self, on_match_open: bool = None, on_tournament_end: bool = None): """ update participants notifications for this tournament |methcoro| Args: on_match_open: Email registered Challonge participants when matches open up for them on_tournament_end: Email registered Challonge participants the...
async def get_participant(self, p_id: int, force_update=False) -> Participant: """ get a participant by its id |methcoro| Args: p_id: participant id force_update (dfault=False): True to force an update to the Challonge API Returns: Participant: None if not found Raises: APIException """ found_p = self._find_participant...
async def get_participants(self, force_update=False) -> list: """ get all participants |methcoro| Args: force_update (default=False): True to force an update to the Challonge API Returns: list[Participant]: Raises: APIException """ if force_update or self.participants is None: res = await self.connection('GET', 'tourna...
async def search_participant(self, name, force_update=False): """ search a participant by (display) name |methcoro| Args: name: display name of the participant force_update (dfault=False): True to force an update to the Challonge API Returns: Participant: None if not found Raises: APIException """ if force_update or se...
async def add_participant(self, display_name: str = None, username: str = None, email: str = None, seed: int = 0, misc: str = None, **params): """ add a participant to the tournament |methcoro| Args: display_name: The name displayed in the bracket/schedule - not required if email or challonge_username is provided. Must...
between 1 and the current number of participants (including the new record). Overwriting an existing seed will automatically bump other participants as you would expect. misc: Max: 255 characters. Multi-purpose field that is only visible via the API and handy for site integration (e.g. key to your users table) params: ...
async def remove_participant(self, p: Participant): """ remove a participant from the tournament |methcoro| Args: p: the participant to remove Raises: APIException """ await self.connection('DELETE', 'tournaments/{}/participants/{}'.format(self._id, p._id)) if p in self.participants: self.participants.remove(p)
async def get_match(self, m_id, force_update=False) -> Match: """ get a single match by id |methcoro| Args: m_id: match id force_update (default=False): True to force an update to the Challonge API Returns: Match Raises: APIException """ found_m = self._find_match(m_id) if force_update or found_m is None: await self.ge...
async def get_matches(self, force_update=False) -> list: """ get all matches (once the tournament is started) |methcoro| Args: force_update (default=False): True to force an update to the Challonge API Returns: list[Match]: Raises: APIException """ if force_update or self.matches is None: res = await self.connection('G...
async def shuffle_participants(self): """ Shuffle participants' seeds |methcoro| Note: |from_api| Randomize seeds among participants. Only applicable before a tournament has started. Raises: APIException """ res = await self.connection('POST', 'tournaments/{}/participants/randomize'.format(self._id)) self._refresh_part...
async def process_check_ins(self): """ finalize the check in phase |methcoro| Warning: |unstable| Note: |from_api| This should be invoked after a tournament's check-in window closes before the tournament is started. 1. Marks participants who have not checked in as inactive. 2. Moves inactive participants to bottom seed...
async def get_final_ranking(self) -> OrderedDict: """ Get the ordered players ranking Returns: collections.OrderedDict[rank, List[Participant]]: Raises: APIException """ if self._state != TournamentState.complete.value: return None ranking = {} for p in self.participants: if p.final_rank in ranking: ranking[p.final_ran...
def run(self, timeout = 0): """ Run a proactor loop and return new socket events. Timeout is a timedelta object, 0 if active coros or None. kqueue timeout param is a integer number of nanoseconds (seconds/10**9). """ ptimeout = float( timeout.microseconds/1000000+timeout.seconds if timeout else (self.resolution if time...
def generate_xhtml(path, dirs, files): """Return a XHTML document listing the directories and files.""" # Prepare the path to display. if path != '/': dirs.insert(0, '..') if not path.endswith('/'): path += '/' def itemize(item): return '<a href="%s">%s</a>' % (item, path+item) dirs = [d + '/' for d in dirs] return """...
def get_entries(path): """Return sorted lists of directories and files in the given path.""" dirs, files = [], [] for entry in os.listdir(path): # Categorize entry as directory or file. if os.path.isdir(os.path.join(path, entry)): dirs.append(entry) else: files.append(entry) dirs.sort() files.sort() return dirs, files
def _conditions(self, full_path, environ): """Return a tuple of etag, last_modified by mtime from stat.""" mtime = os.stat(full_path).st_mtime size = os.stat(full_path).st_size return str(mtime), rfc822.formatdate(mtime), size
def hashes(peaks, f_width=F_WIDTH, t_gap=ROWS_PER_SECOND, t_width=2*ROWS_PER_SECOND): """ Generator function for successive hashes calculated from a mono-channel time-domain audio signal as a set of tuples, (<long>, <int>). The <long> is an integral 64-bit hash so it can be used as a database ID, and the <int> is the f...
bound t_min = t1 + t_gap t_max = t_min + t_width f_min = f1 - f_width // 2 f_max = f1 + f_width // 2 for t2, f2 in peaks[i:]: if t2 < t_min or f2 < f_min: continue elif t2 > t_max: break elif f2 < f_max: yield (_get_hash(f1, f2, t2 - t1), t1)
def spectrogram(t_signal, frame_width=FRAME_WIDTH, overlap=FRAME_STRIDE): """ Calculate the magnitude spectrogram of a single-channel time-domain signal from the real frequency components of the STFT with a hanning window applied to each frame. The frame size and overlap between frames should be specified in number of ...
def _get_hash(f1, f2, dt): """ Calculate a 64-bit integral hash from <f1:f2:dt>, where f1 and f2 are FFT frequency bins (based on frame width), and dt is propotional to the time difference between f1 and f2 as the the difference in frame number between the points. """ return ((long(f1) & 0xffff) << 48 | (long(f2) & 0xf...
def _extract_peaks(specgram, neighborhood, threshold): """ Partition the spectrogram into subcells and extract peaks from each cell if the peak is sufficiently energetic compared to the neighborhood. """ kernel = np.ones(shape=neighborhood) local_averages = convolve(specgram, kernel / kernel.sum(), mode="constant", cva...
def list(self,table, **kparams): """ get a collection of records by table name. returns a dict (the json map) for python 3.4 """ result = self.table_api_get(table, **kparams) return self.to_records(result, table)
def update(self,table, sys_id, **kparams): """ use PUT to update a single record by table name and sys_id returns a dict (the json map) for python 3.4 """ result = self.table_api_put(table, sys_id, **kparams) return self.to_record(result, table)
def get(self,table, sys_id): """ get a single record by table name and sys_id returns a dict (the json map) for python 3.4 """ result = self.table_api_get(table, sys_id) return self.to_record(result, table)
def req(self, meth, url, http_data=''): """ sugar that wraps the 'requests' module with basic auth and some headers. """ self.logger.debug("Making request: %s %s\nBody:%s" % (meth, url, http_data)) req_method = getattr(requests, meth) return (req_method(url, auth=(self.__username, self.__password), data=http_data, head...
def user_agent(self): """ its a user agent string! """ version = "" project_root = os.path.dirname(os.path.abspath(__file__)) with open(os.path.join(project_root, 'VERSION')) as version_file: version = version_file.read().strip() return "Python Snow Api Client (Version %s)" % version
def table_api_get(self, *paths, **kparams): """ helper to make GET /api/now/v1/table requests """ url = self.flattened_params_url("/api/now/v1/table", *paths, **kparams) rjson = self.req("get", url).text return json.loads(rjson)
def table_api_put(self, *paths, **kparams): """ helper to make PUT /api/now/v1/table requests """ url = self.flattened_params_url("/api/now/v1/table", *paths) # json.dumps(kparams) is the body of the put/post rjson = self.req("put", url, json.dumps(kparams)).text return json.loads(rjson)
def flattened_params_url(self, path_prefix, *paths, **kparams): """ url builder helper to make /api/now/v1/table paths for GET requests. Snow is Woe.""" base = self.base_url + path_prefix for p in paths: base += "/" base += p if kparams: base += "?" # use %r in val? base += '&'.join("%s=%s" % (key,val) for (key,val) in...
def resolve_links(self, snow_record, **kparams): """ Get the infos from the links and return SnowRecords[]. """ records = [] for attr, link in snow_record.links().items(): records.append(self.resolve_link(snow_record, attr, **kparams)) return records
def resolve_link(self, snow_record, field_to_resolve, **kparams): """ Get the info from the link and return a SnowRecord. """ try: link = snow_record.links()[field_to_resolve] except KeyError as e: return SnowRecord.NotFound(self, snow_record._table_name, "Could not find field %s in record" % field_to_resolve, [snow_re...
def to_serializable_value(self): """ Parses the Hightonmodel to a serializable value such dicts, lists, strings This can be used to save the model in a NoSQL database :return: the serialized HightonModel :rtype: dict """ return_dict = {} for name, field in self.__dict__.items(): if isinstance(field, fields.Field): retu...
def textile(text, **kwargs): """ Applies Textile conversion to a string, and returns the HTML. This is simply a pass-through to the ``textile`` template filter included in ``django.contrib.markup``, which works around issues PyTextile has with Unicode strings. If you're not using Django but want to use Textile with ``M...
def restructuredtext(text, **kwargs): """ Applies reStructuredText conversion to a string, and returns the HTML. """ from docutils import core parts = core.publish_parts(source=text, writer_name='html4css1', **kwargs) return parts['fragment']
def _typed_from_items(items): """ Construct strongly typed attributes (properties) from a dictionary of name and :class:`~exa.typed.Typed` object pairs. See Also: :func:`~exa.typed.typed` """ dct = {} for name, attr in items: if isinstance(attr, Typed): dct[name] = attr(name) return dct
def typed(cls): """ Class decorator that updates a class definition with strongly typed property attributes. See Also: If the class will be inherited, use :class:`~exa.typed.TypedClass`. """ for name, attr in _typed_from_items(vars(cls).items()).items(): setattr(cls, name, attr) return cls
def yield_typed(obj_or_cls): """ Generator that yields typed object names of the class (or object's class). Args: obj_or_cls (object): Class object or instance of class Returns: name (array): Names of class attributes that are strongly typed """ if not isinstance(obj_or_cls, type): obj_or_cls = type(obj_or_cls) for att...
def reconcile(constraint): ''' Returns an assignment of type variable names to types that makes this constraint satisfiable, or a Refutation ''' if isinstance(constraint.subtype, NamedType): if isinstance(constraint.supertype, NamedType): if constraint.subtype.name == constraint.supertype.name: return {} else: return R...
def clean_value(self, val): """ val = :param dict val: {"content":"", "name":"", "ext":"", "type":""} :return: """ if isinstance(val, dict): if self.random_name: val['random_name'] = self.random_name if 'file_name' in val.keys(): val['name'] = val.pop('file_name') val['content'] = val.pop('file_content') return self.fi...
def prnt(self): """ Prints DB data representation of the object. """ print("= = = =\n\n%s object key: \033[32m%s\033[0m" % (self.__class__.__name__, self.key)) pprnt(self._data or self.clean_value())
def get_choices_for(self, field): """ Get the choices for the given fields. Args: field (str): Name of field. Returns: List of tuples. [(name, value),...] """ choices = self._fields[field].choices if isinstance(choices, six.string_types): return [(d['value'], d['name']) for d in self._choices_manager.get_all(choices)] ...
def set_data(self, data, from_db=False): """ Fills the object's fields with given data dict. Internally calls the self._load_data() method. Args: data (dict): Data to fill object's fields. from_db (bool): if data coming from db then we will use related field type's _load_data method Returns: Self. Returns objects itsel...
def _apply_cell_filters(self, context): """ Applies the field restrictions based on the return value of the context's "has_permission()" method. Stores them on self._unpermitted_fields. Returns: List of unpermitted fields names. """ self.setattrs(_is_unpermitted_fields_set=True) for perm, fields in self.Meta.field_perm...
def get_unpermitted_fields(self): """ Gives unpermitted fields for current context/user. Returns: List of unpermitted field names. """ return (self._unpermitted_fields if self._is_unpermitted_fields_set else self._apply_cell_filters(self._context))
def _update_new_linked_model(self, internal, linked_mdl_ins, link): """ Iterates through linked_models of given model instance to match it's "reverse" with given link's "field" values. """ # If there is a link between two sides (A and B), if a link from A to B, # link should be saved at B but it is not necessary to con...
if linked_mdl_ins._exists is False: raise ObjectDoesNotExist('Linked %s on field %s with key %s doesn\'t exist' % ( linked_mdl_ins.__class__.__name__, remote_field_name, linked_mdl_ins.key, )) linked_mdl_ins.save(internal=True) else: linked_mdl_ins.setattr(remote_field_name, self._root_node) if linked_mdl_ins._exists i...
def _handle_changed_fields(self, old_data): """ Looks for changed relation fields between new and old data (before/after save). Creates back_link references for updated fields. Args: old_data: Object's data before save. """ for link in self.get_links(is_set=False): fld_id = un_camel_id(link['field']) if not old_data or...
def reload(self): """ Reloads current instance from DB store """ self._load_data(self.objects.data().filter(key=self.key)[0][0], True)
def _handle_uniqueness(self): """ Checks marked as unique and unique_together fields of the Model at each creation and update, and if it violates the uniqueness raises IntegrityError. First, looks at the fields which marked as "unique". If Model's unique fields did not change, it means that there is still a record at d...
and unique_together checks does not pass """ def _getattr(u): try: return self._field_values[u] except KeyError: return getattr(self, u) if self._uniques: for u in self._uniques: val = _getattr(u) changed_fields = self.changed_fields(from_db=True) if self.exist and not (u in changed_fields if not callable(val) else (st...
= uni in changed_fields query_is_changed.append(is_changed) is_unique_changed = any(query_is_changed) if not is_unique_changed: if self.objects.filter(**vals).count() > 1: raise IntegrityError( "Unique together mismatch: %s combination already exists for %s" % (vals, self.__class__.__name__)) else: if self.objects.filt...
def save(self, internal=False, meta=None, index_fields=None): """ Save's object to DB. Do not override this method, use pre_save and post_save methods. Args: internal (bool): True if called within model. Used to prevent unneccessary calls to pre_save and post_save methods. meta (dict): JSON serializable meta data for l...
or self._post_save_hook_called): self._post_save_hook_called = True self.post_save() if self._just_created: self.setattrs(just_created=self._just_created, _just_created=False) self.post_creation() self._pre_save_hook_called = False self._post_save_hook_called = False if not internal: self._initial_data = self.clean_val...
def changed_fields(self, from_db=False): """ Args: from_db (bool): Check changes against actual db data Returns: list: List of fields names which their values changed. """ if self.exist: current_dict = self.clean_value() # `from_db` attr is set False as default, when a `ListNode` is # initialized just after above `clea...
def is_changed(self, field, from_db=False): """ Args: field (string): Field name. from_db (bool): Check changes against actual db data Returns: bool: True if given fields value is changed. """ return field in self.changed_fields(from_db=from_db)
def blocking_save(self, query_dict=None, meta=None, index_fields=None): """ Saves object to DB. Waits till the backend properly indexes the new object. Args: query_dict(dict) : contains keys - values of the model fields meta (dict): JSON serializable meta data for logging of save operation. {'lorem': 'ipsum', 'dolar': ...
def blocking_delete(self, meta=None, index_fields=None): """ Deletes and waits till the backend properly update indexes for just deleted object. meta (dict): JSON serializable meta data for logging of save operation. {'lorem': 'ipsum', 'dolar': 5} index_fields (list): Tuple list for indexing keys in riak (with 'bin' or...
def delete(self, dry=False, meta=None, index_fields=None): """ Sets the objects "deleted" field to True and, current time to "deleted_at" fields then saves it to DB. Args: dry (bool): False. Do not execute the actual deletion. Just list what will be deleted as a result of relations. meta (dict): JSON serializable meta ...
self.save(internal=True, meta=meta, index_fields=index_fields) self.post_delete() if settings.ENABLE_CACHING: cache.delete(self.key) return results, errors
def __clip(val, minimum, maximum): """ :param val: input value :param minimum: min value :param maximum: max value :return: val clipped to range [minimum, maximum] """ if val is None or minimum is None or maximum is None: return None if val < minimum: return minimum if val > maximum: return maximum return val
def make_frame(self, frame, birthframe, startframe, stopframe, deathframe, noiseframe=None): """ :param frame: current frame :param birthframe: frame where animation starts to return something other than None :param startframe: frame where animation starts to evolve :param stopframe: frame where animation stops evolvin...
def __recognize_scalar(self, node: yaml.Node, expected_type: Type) -> RecResult: """Recognize a node that we expect to be a scalar. Args: node: The node to recognize. expected_type: The type it is expected to be. Returns: A list of recognized types and an error message """ logger.debug('Recognizing as a scalar') if (is...
def __recognize_list(self, node: yaml.Node, expected_type: Type) -> RecResult: """Recognize a node that we expect to be a list of some kind. Args: node: The node to recognize. expected_type: List[...something...] Returns expected_type and the empty string if it was recognized, [] and an error message otherwise. """ log...
def __recognize_dict(self, node: yaml.Node, expected_type: Type) -> RecResult: """Recognize a node that we expect to be a dict of some kind. Args: node: The node to recognize. expected_type: Dict[str, ...something...] Returns: expected_type if it was recognized, [] otherwise. """ logger.debug('Recognizing as a dict') i...
def __recognize_union(self, node: yaml.Node, expected_type: Type) -> RecResult: """Recognize a node that we expect to be one of a union of types. Args: node: The node to recognize. expected_type: Union[...something...] Returns: The specific type that was recognized, multiple, or none. """ logger.debug('Recognizing as a...
def __recognize_user_class(self, node: yaml.Node, expected_type: Type) -> RecResult: """Recognize a user-defined class in the node. This tries to recognize only exactly the specified class. It \ recurses down into the class's attributes, but not to its \ subclasses. See also __recognize_user_classes(). Args: node: The ...
yaml.ScalarNode) or node.tag != 'tag:yaml.org,2002:str'): message = 'Expected an enum value from {}\n{}'.format( expected_type.__class__, loc_str) return [], message elif (issubclass(expected_type, UserString) or issubclass(expected_type, str)): if (not isinstance(node, yaml.ScalarNode) or node.tag != 'tag:yaml.org,200...
'Error recognizing a {}\n{}because it' ' is missing an attribute named {}').format( expected_type.__name__, loc_str, attr_name) if '_' in attr_name: message += ' or maybe {}.\n'.format( attr_name.replace('_', '-')) else: message += '.\n' return [], message return [expected_type], ''
def __recognize_user_classes(self, node: yaml.Node, expected_type: Type) -> RecResult: """Recognize a user-defined class in the node. This returns a list of classes from the inheritance hierarchy \ headed by expected_type which match the given node and which \ do not have a registered derived class that matches the giv...
if len(sub_subclasses) == 0: message += msg if len(recognized_subclasses) == 0: recognized_subclasses, msg = self.__recognize_user_class( node, expected_type) if len(recognized_subclasses) == 0: message += msg if len(recognized_subclasses) == 0: message = ('Failed to recognize a {}\n{}\nbecause of the following' ' erro...
def recognize(self, node: yaml.Node, expected_type: Type) -> RecResult: """Figure out how to interpret this node. This is not quite a type check. This function makes a list of \ all types that match the expected type and also the node, and \ returns that list. The goal here is not to test validity, but \ to determine h...
bool_union_fix, datetime, None, type(None) ]: recognized_types, message = self.__recognize_scalar( node, expected_type) elif is_generic_union(expected_type): recognized_types, message = self.__recognize_union( node, expected_type) elif is_generic_list(expected_type): recognized_types, message = self.__recognize_list( n...
def cli(ctx, vcf, verbose, outfile, silent): """Simple vcf operations""" # configure root logger to print to STDERR loglevel = LEVELS.get(min(verbose, 3)) configure_stream(level=loglevel) if vcf == '-': handle = get_vcf_handle(fsock=sys.stdin) else: handle = get_vcf_handle(infile=vcf) head = HeaderParser() for line in ...
def delete_info(ctx, info): """Delete a info field from all variants in a vcf""" head = ctx.parent.head vcf_handle = ctx.parent.handle outfile = ctx.parent.outfile silent = ctx.parent.silent if not info: logger.error("No info provided") sys.exit("Please provide a info string") if not info in head.info_dict: logger.erro...
def variants(ctx, snpeff): """Print the variants in a vcf""" head = ctx.parent.head vcf_handle = ctx.parent.handle outfile = ctx.parent.outfile silent = ctx.parent.silent print_headers(head, outfile=outfile, silent=silent) for line in vcf_handle: print_variant(variant_line=line, outfile=outfile, silent=silent) if snpef...
def sort(ctx): """Sort the variants of a vcf file""" head = ctx.parent.head vcf_handle = ctx.parent.handle outfile = ctx.parent.outfile silent = ctx.parent.silent print_headers(head, outfile=outfile, silent=silent) for line in sort_variants(vcf_handle): print_variant(variant_line=line, outfile=outfile, silent=silent)