code stringlengths 1 18.2k |
|---|
def run(self): """A bit bulky atm...""" self.close_connection = False try: while True: self.started_response = False self.status = "" self.outheaders = [] self.sent_headers = False self.chunked_write = False self.write_buffer = StringIO.StringIO() self.content_length = None # Copy the class environ into self. ENVIRON =... |
";" + params ENVIRON["SCRIPT_NAME"] = "" # Unquote the path+params (e.g. "/this%20path" -> "this path"). # http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2 # # But note that "...a URI must be separated into its components # before the escaped characters within those components can be # safely decoded." ht... |
a 1.0 1.0 1.0 1.0 # b 1.0 1.1 1.1 1.0 # c 1.1 1.0 1.0 1.0 # d 1.1 1.1 1.1 1.1 # Notice that, in (b), the response will be "HTTP/1.1" even though # the client only understands 1.0. RFC 2616 10.5.6 says we should # only return 505 if the _major_ version is different. rp = int(req_protocol[5]), int(req_protocol[7]) server... |
'\r\n': # Normal end of headers break if line[0] in ' \t': # It's a continuation line. v = line.strip() else: k, v = line.split(":", 1) k, v = k.strip().upper(), v.strip() envname = "HTTP_" + k.replace("-", "_") if k in comma_separated_headers: existing = ENVIRON.get(envname) if existing: v = ", ".join((existing, v)) E... |
True # Transfer-Encoding support te = None if self.response_protocol == "HTTP/1.1": te = ENVIRON.get("HTTP_TRANSFER_ENCODING") if te: te = [x.strip().lower() for x in te.split(",") if x.strip()] if te: # reject transfer encodings for now yield self.simple_response("501 Unimplemented") self.close_connection = True retur... |
not self.sent_headers self.sent_headers = True yield sockets.SendAll(self.conn, self.render_headers()+self.write_buffer.getvalue() ) offset = response.filelike.tell() if self.chunked_write: fsize = os.fstat(response.filelike.fileno()).st_size yield sockets.SendAll(self.conn, hex(int(fsize-offset))+"\r\n") yield self.co... |
self.render_headers()+self.write_buffer.getvalue()) if ENV_COGEN_PROXY.operation: op = ENV_COGEN_PROXY.operation ENV_COGEN_PROXY.operation = None try: #~ print 'WSGI OP:', op ENV_COGEN_PROXY.exception = None ENV_COGEN_PROXY.result = yield op #~ print 'WSGI OP RESULT:',ENVIRON['cogen.wsgi'].result except: #~ print 'WSGI... |
"*" * 60 traceback.print_exc() print "*" * 60 sys.exc_clear() finally: self.conn.close() ENVIRON = self.environ = None |
def serve(self): """Run the server forever.""" # We don't have to trap KeyboardInterrupt or SystemExit here, # Select the appropriate socket if isinstance(self.bind_addr, basestring): # AF_UNIX socket # So we can reuse the socket... try: os.unlink(self.bind_addr) except: pass # So everyone can access the socket... try:... |
try: self.bind(af, socktype, proto) except socket.error, msg: if self.socket: self.socket.close() self.socket = None continue break if not self.socket: raise socket.error, msg self.socket.listen(self.request_queue_size) with closing(self.socket): while True: try: s, addr = yield sockets.Accept(self.socket, timeout=-1) ... |
domain sockets. But it's better than nothing. environ["SERVER_PORT"] = "" else: environ["SERVER_PORT"] = str(self.bind_addr[1]) # optional values # Until we do DNS lookups, omit REMOTE_HOST environ["REMOTE_ADDR"] = addr[0] environ["REMOTE_PORT"] = str(addr[1]) conn = self.ConnectionClass(s, self.wsgi_app, environ, self... |
def bind(self, family, type, proto=0): """Create (or recreate) the actual socket object.""" self.socket = sockets.Socket(family, type, proto) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.setblocking(0) #~ self.socket.setsockopt(socket.SOL_SOCKET, socket.TCP_NODELAY, 1) self.socket.bind(... |
def load(self, name): """Loads and returns foreign library.""" name = ctypes.util.find_library(name) return ctypes.cdll.LoadLibrary(name) |
def _set_signatures(self): """Sets return and parameter types for the foreign C functions.""" # We currently pass structs as void pointers. code_t = ctypes.c_int gpr_t = ctypes.c_int32 int32_t = ctypes.c_int32 node_p = ctypes.c_void_p pointer_t = ctypes.c_void_p state_p = ctypes.c_void_p void = None def sig(rettype, fn... |
sig(void, "_jit_ellipsis", state_p) sig(void, "_jit_epilog", state_p) sig(void, "_jit_finishr", state_p, gpr_t) sig(void, "_jit_getarg_i", state_p, gpr_t, node_p) sig(void, "_jit_getarg_l", state_p, gpr_t, node_p) sig(void, "_jit_link", state_p, node_p) sig(void, "_jit_patch", state_p, node_p) sig(void, "_jit_patch_at"... |
def state(self): """Returns a new JIT state. You have to clean up by calling .destroy() afterwards. """ return Emitter(weakref.proxy(self.lib), self.lib.jit_new_state()) |
def __to_plain_containers(self, container: Union[CommentedSeq, CommentedMap] ) -> Union[OrderedDict, list]: """Converts any sequence or mapping to list or OrderedDict Stops at anything that isn't a sequence or a mapping. One day, we'll extract the comments and formatting and store \ them out-of-band. Args: mapping: The... |
def __split_off_extra_attributes(self, mapping: CommentedMap, known_attrs: List[str]) -> CommentedMap: """Separates the extra attributes in mapping into yatiml_extra. This returns a mapping containing all key-value pairs from \ mapping whose key is in known_attrs, and an additional key \ yatiml_extra which maps to a di... |
def __type_matches(self, obj: Any, type_: Type) -> bool: """Checks that the object matches the given type. Like isinstance(), but will work with union types using Union, \ Dict and List. Args: obj: The object to check type_: The type to check against Returns: True iff obj is of type type_ """ if is_generic_union(type_)... |
def __check_no_missing_attributes(self, node: yaml.Node, mapping: CommentedMap) -> None: """Checks that all required attributes are present. Also checks that they're of the correct type. Args: mapping: The mapping with subobjects of this object. Raises: RecognitionError: if an attribute is missing or the type \ is inco... |
def __type_check_attributes(self, node: yaml.Node, mapping: CommentedMap, argspec: inspect.FullArgSpec) -> None: """Ensure all attributes have a matching constructor argument. This checks that there is a constructor argument with a \ matching type for each existing attribute. If the class has a yatiml_extra attribute, ... |
attributes' ' and {} does not support those').format( node.start_mark, os.linesep, self.class_.__name__)) if key in argspec.args and not self.__type_matches( value, argspec.annotations[key]): raise RecognitionError(('{}{}Expected attribute {} to be of' ' type {} but it is a(n) {}').format( node.start_mark, os.linesep, ... |
def __strip_extra_attributes(self, node: yaml.Node, known_attrs: List[str]) -> None: """Strips tags from extra attributes. This prevents nodes under attributes that are not part of our \ data model from being converted to objects. They'll be plain \ CommentedMaps instead, which then get converted to OrderedDicts \ for ... |
def __strip_tags(self, node: yaml.Node) -> None: """Strips tags from mappings in the tree headed by node. This keeps yaml from constructing any objects in this tree. Args: node: Head of the tree to strip """ if isinstance(node, yaml.SequenceNode): for subnode in node.value: self.__strip_tags(subnode) elif isinstance(no... |
def publish(self, message, key=None, **kws): """Put a message in the queue and updates any coroutine wating with fetch. *works as a coroutine operation*""" return PSPut(self, message, key, **kws) |
def compact(self): """Compacts the queue: removes all the messages from the queue that have been fetched by all the subscribed coroutines. Returns the number of messages that have been removed.""" if self.subscribers: level = min(self.subscribers.itervalues()) if level: del self.messages[:level] return level else: leve... |
def has_provider_support(provider, media_type): """ Verifies if API provider has support for requested media type """ if provider.lower() not in API_ALL: return False provider_const = "API_" + media_type.upper() return provider in globals().get(provider_const, {}) |
def provider_factory(provider, **options): """ Factory function for DB Provider Concrete Classes """ try: return {"tmdb": TMDb, "tvdb": TVDb}[provider.lower()](**options) except KeyError: msg = "Attempted to initialize non-existing DB Provider" log.error(msg) raise MapiException(msg) |
def _year_expand(s): """ Parses a year or dash-delimeted year range """ regex = r"^((?:19|20)\d{2})?(\s*-\s*)?((?:19|20)\d{2})?$" try: start, dash, end = match(regex, ustr(s)).groups() start = start or 1900 end = end or 2099 except AttributeError: return 1900, 2099 return (int(start), int(end)) if dash else (int(start)... |
def search(self, id_key=None, **parameters): """ Searches TMDb for movie metadata """ id_tmdb = parameters.get("id_tmdb") or id_key id_imdb = parameters.get("id_imdb") title = parameters.get("title") year = parameters.get("year") if id_tmdb: yield self._search_id_tmdb(id_tmdb) elif id_imdb: yield self._search_id_imdb(i... |
def search(self, id_key=None, **parameters): """ Searches TVDb for movie metadata TODO: Consider making parameters for episode ids """ episode = parameters.get("episode") id_tvdb = parameters.get("id_tvdb") or id_key id_imdb = parameters.get("id_imdb") season = parameters.get("season") series = parameters.get("series")... |
def _mkdirs(d): """ Make all directories up to d. No exception is raised if d exists. """ try: os.makedirs(d) except OSError as e: if e.errno != errno.EEXIST: raise |
def _templated(fn): """ Return a function which applies ``str.format(**ctl)`` to all results of ``fn(ctl)``. """ @functools.wraps(fn) def inner(ctl): return [i.format(**ctl) for i in fn(ctl)] return inner |
def nest_map(control_iter, map_fn): """ Apply ``map_fn`` to the directories defined by ``control_iter`` For each control file in control_iter, map_fn is called with the directory and control file contents as arguments. Example:: >>> list(nest_map(['run1/control.json', 'run2/control.json'], ... lambda d, c: c['run_id'])... |
def control_iter(base_dir, control_name=CONTROL_NAME): """ Generate the names of all control files under base_dir """ controls = (os.path.join(p, control_name) for p, _, fs in os.walk(base_dir) if control_name in fs) return controls |
def iter(self, root=None): """ Create an iterator of (directory, control_dict) tuples for all valid parameter choices in this :class:`Nest`. :param root: Root directory :rtype: Generator of ``(directory, control_dictionary)`` tuples. """ if root is None: return iter(self._controls) return ((os.path.join(root, outdir), ... |
def build(self, root="runs"): """ Build a nested directory structure, starting in ``root`` :param root: Root directory for structure """ for d, control in self.iter(root): _mkdirs(d) with open(os.path.join(d, self.control_name), 'w') as fp: json.dump(control, fp, indent=self.indent) # RJSON and some other tools like a ... |
def add(self, name, nestable, create_dir=True, update=False, label_func=str, template_subs=False): """ Add a level to the nest :param string name: Name of the level. Forms the key in the output dictionary. :param nestable: Either an iterable object containing values, _or_ a function which takes a single argument (the c... |
in / returned by nestable be treated as templates? If true, str.format is called with the current values of the control dictionary. """ # Convert everything to functions if not callable(nestable): if not _is_iter(nestable): raise ValueError("Invalid nestable: " + str(nestable)) if is_string(nestable): warnings.warn( "P... |
to_label = r if create_dir: new_outdir = os.path.join(outdir, label_func(to_label)) if self.include_outdir: new_control['OUTDIR'] = new_outdir new_controls.append((new_outdir, new_control)) self._controls = new_controls |
def compose(self, *args, **kwargs): """ Generate a file from the current template and given arguments. Warning: Make certain to check the formatted editor for correctness! Args: args: Positional arguments to update the template kwargs: Keyword arguments to update the template Returns: editor: An editor containing the f... |
name, indent, delim, qual, _ = match if indent != "": indent = " "*int(indent) delim = delim.replace("\\|", "|") # Collect and format the data accordingly data = getattr(self, name, None) # If no data exists, treat as optional if data is None: cline = cline.replace(search, "") continue elif delim.isdigit(): fkwargs[nam... |
def get_kwargs(self): """Return kwargs from attached attributes.""" return {k: v for k, v in vars(self).items() if k not in self._ignored} |
def complete(self): """ Complete current task :return: :rtype: requests.models.Response """ return self._post_request( data='', endpoint=self.ENDPOINT + '/' + str(self.id) + '/complete' ) |
def list_upcoming(cls): """ Returns a collection of upcoming tasks (tasks that have not yet been completed, regardless of whether they’re overdue) for the authenticated user :return: :rtype: list """ return fields.ListField(name=cls.ENDPOINT, init_class=cls).decode( cls.element_from_string( cls._get_request(endpoint=cl... |
def print_headers(head, outfile=None, silent=False): """ Print the vcf headers. If a result file is provided headers will be printed here, otherwise they are printed to stdout. Args: head (HeaderParser): A vcf header object outfile (FileHandle): A file handle silent (Bool): If nothing should be printed. """ for header_... |
def print_variant(variant_line, outfile=None, silent=False): """ Print a variant. If a result file is provided the variante will be appended to the file, otherwise they are printed to stdout. Args: variants_file (str): A string with the path to a file outfile (FileHandle): An opened file_handle silent (bool): Bool. If ... |
def lines_from_file(path, as_interned=False, encoding=None): """ Create a list of file lines from a given filepath. Args: path (str): File path as_interned (bool): List of "interned" strings (default False) Returns: strings (list): File line list """ lines = None with io.open(path, encoding=encoding) as f: if as_intern... |
def lines_from_stream(f, as_interned=False): """ Create a list of file lines from a given file stream. Args: f (io.TextIOWrapper): File stream as_interned (bool): List of "interned" strings (default False) Returns: strings (list): File line list """ if as_interned: return [sys.intern(line) for line in f.read().splitlin... |
def lines_from_string(string, as_interned=False): """ Create a list of file lines from a given string. Args: string (str): File string as_interned (bool): List of "interned" strings (default False) Returns: strings (list): File line list """ if as_interned: return [sys.intern(line) for line in string.splitlines()] retu... |
def write(self, path=None, *args, **kwargs): """ Perform formatting and write the formatted string to a file or stdout. Optional arguments can be used to format the editor's contents. If no file path is given, prints to standard output. Args: path (str): Full file path (default None, prints to stdout) *args: Positional... |
def format(self, *args, **kwargs): """ Format the string representation of the editor. Args: inplace (bool): If True, overwrite editor's contents with formatted contents """ inplace = kwargs.pop("inplace", False) if not inplace: return str(self).format(*args, **kwargs) self._lines = str(self).format(*args, **kwargs).sp... |
def head(self, n=10): """ Display the top of the file. Args: n (int): Number of lines to display """ r = self.__repr__().split('\n') print('\n'.join(r[:n]), end=' ') |
def append(self, lines): """ Args: lines (list): List of line strings to append to the end of the editor """ if isinstance(lines, list): self._lines = self._lines + lines elif isinstance(lines, str): lines = lines.split('\n') self._lines = self._lines + lines else: raise TypeError('Unsupported type {0} for lines.'.form... |
def insert(self, lines=None): """ Insert lines into the editor. Note: To insert before the first line, use :func:`~exa.core.editor.Editor.preappend` (or key 0); to insert after the last line use :func:`~exa.core.editor.Editor.append`. Args: lines (dict): Dictionary of lines of form (lineno, string) pairs """ for i, (ke... |
def remove_blank_lines(self): """Remove all blank lines (blank lines are those with zero characters).""" to_remove = [] for i, line in enumerate(self): ln = line.strip() if ln == '': to_remove.append(i) self.delete_lines(to_remove) |
def _data(self, copy=False): """ Get all data associated with the container as key value pairs. """ data = {} for key, obj in self.__dict__.items(): if isinstance(obj, (pd.Series, pd.DataFrame, pd.SparseSeries, pd.SparseDataFrame)): if copy: data[key] = obj.copy() else: data[key] = obj return data |
def delete_lines(self, lines): """ Delete all lines with given line numbers. Args: lines (list): List of integers corresponding to line numbers to delete """ for k, i in enumerate(lines): del self[i-k] |
def find(self, *strings, **kwargs): """ Search the entire editor for lines that match the string. .. code-block:: Python string = '''word one word two three''' ed = Editor(string) ed.find('word') # [(0, "word one"), (1, "word two")] ed.find('word', 'three') # {'word': [...], 'three': [(2, "three")]} Args: strings (str)... |
for string in strings: if string in line: if keys_only: results[string].append(i) else: results[string].append((i, line)) if len(strings) == 1: return results[strings[0]] return results |
def find_next(self, *strings, **kwargs): """ From the editor's current cursor position find the next instance of the given string. Args: strings (iterable): String or strings to search for Returns: tup (tuple): Tuple of cursor position and line or None if not found Note: This function cycles the entire editor (i.e. cur... |
def regex(self, *patterns, **kwargs): """ Search the editor for lines matching the regular expression. re.MULTILINE is not currently supported. Args: \*patterns: Regular expressions to search each line for keys_only (bool): Only return keys flags (re.FLAG): flags passed to re.search Returns: results (dict): Dictionary ... |
def replace(self, pattern, replacement): """ Replace all instances of a pattern with a replacement. Args: pattern (str): Pattern to replace replacement (str): Text to insert """ for i, line in enumerate(self): if pattern in line: self[i] = line.replace(pattern, replacement) |
def pandas_dataframe(self, start, stop, ncol, **kwargs): """ Returns the result of tab-separated pandas.read_csv on a subset of the file. Args: start (int): line number where structured data starts stop (int): line number where structured data stops ncol (int or list): the number of columns in the structured data or a ... |
def variables(self): """ Display a list of templatable variables present in the file. Templating is accomplished by creating a bracketed object in the same way that Python performs `string formatting`_. The editor is able to replace the placeholder value of the template. Integer templates are positional arguments. .. _... |
def from_file(cls, path, **kwargs): """Create an editor instance from a file on disk.""" lines = lines_from_file(path) if 'meta' not in kwargs: kwargs['meta'] = {'from': 'file'} kwargs['meta']['filepath'] = path return cls(lines, **kwargs) |
def from_stream(cls, f, **kwargs): """Create an editor instance from a file stream.""" lines = lines_from_stream(f) if 'meta' not in kwargs: kwargs['meta'] = {'from': 'stream'} kwargs['meta']['filepath'] = f.name if hasattr(f, 'name') else None return cls(lines, **kwargs) |
def is_generic_list(type_: Type) -> bool: """Determines whether a type is a List[...]. How to do this varies for different Python versions, due to the typing library not having a stable API. This functions smooths over the differences. Args: type_: The type to check. Returns: True iff it's a List[...something...]. """ ... |
def is_generic_dict(type_: Type) -> bool: """Determines whether a type is a Dict[...]. How to do this varies for different Python versions, due to the typing library not having a stable API. This functions smooths over the differences. Args: type_: The type to check. Returns: True iff it's a Dict[...something...]. """ ... |
def is_generic_union(type_: Type) -> bool: """Determines whether a type is a Union[...]. How to do this varies for different Python versions, due to the typing library not having a stable API. This functions smooths over the differences. Args: type_: The type to check. Returns: True iff it's a Union[...something...]. "... |
def generic_type_args(type_: Type) -> List[Type]: """Gets the type argument list for the given generic type. If you give this function List[int], it will return [int], and if you give it Union[int, str] it will give you [int, str]. Note that on Python < 3.7, Union[int, bool] collapses to Union[int] and then to int; thi... |
def type_to_desc(type_: Type) -> str: """Convert a type to a human-readable description. This is used for generating nice error messages. We want users \ to see a nice readable text, rather than something like \ "typing.List<~T>[str]". Args: type_: The type to represent. Returns: A human-readable description. """ scala... |
def staticdir(): """Return the location of the static data directory.""" root = os.path.abspath(os.path.dirname(__file__)) return os.path.join(root, "static") |
def resource(name): """ Return the full path of a named resource in the static directory. If multiple files with the same name exist, **name** should contain the first directory as well. .. code-block:: python resource("myfile") resource("test01/test.txt") resource("test02/test.txt") """ for path, _, files in os.walk(s... |
def load_uri(self, uri, verbose): """ :param uri: :param rdf_format_opts: :param verbose: :return: """ if verbose: printDebug("----------") if verbose: printDebug("Reading: <%s>" % uri) success = False for f in self.rdf_format_opts: if verbose: printDebug(".. trying rdf serialization: <%s>" % f) try: self.rdfgraph.pars... |
def load_text(self, text, verbose): """ :param text: :param rdf_format_opts: :param verbose: :return: """ if verbose: printDebug("----------") if verbose: printDebug("Reading: '%s ...'" % text[:10]) success = False for f in self.rdf_format_opts: if verbose: printDebug(".. trying rdf serialization: <%s>" % f) try: self.... |
def load_file(self, file_obj, verbose): """ The type of open file objects such as sys.stdout; alias of the built-in file. @TODO: when is this used? """ if verbose: printDebug("----------") if verbose: printDebug("Reading: <%s> ...'" % file_obj.name) if type(file_obj) == file: self.rdfgraph = self.rdfgraph + file_obj se... |
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. epoll timeout param is a integer number of seconds. """ ptimeout = float( timeout.microseconds/1000000+timeout.seconds if timeout else (self.resolution if timeout is None else 0) )... |
def _check(self, terms): """Check terms do not contain unknown characters""" for t in terms: try: _ = urllib.parse.quote(six.text_type(t).encode('utf8')) except: self.logger.error('Unknown character in [{0}]!'.format(t)) self.logger.error('.... remove character and try again.') raise EncodingError |
def main(self): """Search and sieve query names.""" # TODO: Break up, too complex primary_bool = True no_records = True nsearch = 1 search_terms = self.terms original_names = [] while True: if primary_bool: self.logger.info('Searching [{0}] ...'.format( self.primary_datasource)) else: self.logger.info('Searching other ... |
break nsearch += 1 search_terms = no_records # Check for multiple records multi_records = self._count(greater=True, nrecords=1) if multi_records: self.logger.info('Choosing best records to return ...') res = self._sieve(multi_records) self._store.replace(res) |
def _sieve(self, multiple_records): """Return json object without multiple returns per resolved name.\ Names with multiple records are reduced by finding the name in the clade of\ interest, have the highest score, have the lowest taxonomic rank (if lowrank is true) and/or are the first item returned.""" # TODO: Break u... |
'subphylum', 'phylum', 'kingdom', 'superkingdom'] for term in multiple_records: results = GnrStore[term] while len(results) > 1: # choose result with best score scores = [result['score'] for result in results] bool_score = [1 if score == max(scores) else 0 for score in scores] results = boolResults(results, bool_score)... |
min(unnmd_rnks) else 0 for e in unnmd_rnks] results = boolResults(results, bool_rank) results = boolResults(results, [], rand=True) record = writeAsJson(term, results) sieved.append(record) return sieved |
def write(self): """Write csv file of resolved names and txt file of unresolved names. """ csv_file = os.path.join(self.outdir, 'search_results.csv') txt_file = os.path.join(self.outdir, 'unresolved.txt') headers = self.key_terms unresolved = [] with open(csv_file, 'w') as file: writer = csv.writer(file) writer.writero... |
in dir(element): # element = element.encode('ascii') row.append(element) writer.writerow(row) if len(unresolved) > 0: with open(txt_file, 'w') as file: for name in unresolved: file.write("{0}\n".format(name)) |
def retrieve(self, key_term): """Return data for key term specified for each resolved name as a list. Possible terms (02/12/2013): 'query_name', 'classification_path', 'data_source_title', 'match_type', 'score', 'classification_path_ranks', 'name_string', 'canonical_form',\ 'classification_path_ids', 'prescore', 'data_... |
def set_document_type(loader_cls: Type, type_: Type) -> None: """Set the type corresponding to the whole document. Args: loader_cls: The loader class to set the document type for. type_: The type to loader should process the document into. """ loader_cls.document_type = type_ if not hasattr(loader_cls, '_registered_cla... |
def add_to_loader(loader_cls: Type, classes: List[Type]) -> None: """Registers one or more classes with a YAtiML loader. Once a class has been registered, it can be recognized and \ constructed when reading a YAML text. Args: loader_cls: The loader to register the classes with. classes: The class(es) to register, a pla... |
def get_single_node(self) -> yaml.Node: """Hook used when loading a single document. This is the hook we use to hook yatiml into ruamel.yaml. It is \ called by the yaml libray when the user uses load() to load a \ YAML document. Returns: A processed node representing the document. """ node = super().get_single_node() i... |
def __type_to_tag(self, type_: Type) -> str: """Convert a type to the corresponding YAML tag. Args: type_: The type to convert Returns: A string containing the YAML tag. """ if type_ in scalar_type_to_tag: return scalar_type_to_tag[type_] if is_generic_list(type_): return 'tag:yaml.org,2002:seq' if is_generic_dict(type... |
def __savorize(self, node: yaml.Node, expected_type: Type) -> yaml.Node: """Removes syntactic sugar from the node. This calls yatiml_savorize(), first on the class's base \ classes, then on the class itself. Args: node: The node to modify. expected_type: The type to assume this type is. """ logger.debug('Savorizing nod... |
def __process_node(self, node: yaml.Node, expected_type: Type) -> yaml.Node: """Processes a node. This is the main function that implements yatiml's \ functionality. It figures out how to interpret this node \ (recognition), then applies syntactic sugar, and finally \ recurses to the subnodes, if any. Args: node: The n... |
'tag:yaml.org,2002:seq': raise RecognitionError('{}{}Expected a {} here'.format( node.start_mark, os.linesep, type_to_desc(expected_type))) for item in node.value: self.__process_node(item, generic_type_args(recognized_type)[0]) elif is_generic_dict(recognized_type): if node.tag != 'tag:yaml.org,2002:map': raise Recogn... |
def create(self): """ Creates the object :return: the created object :rtype: object """ # In the header.location there is the newly created object so get the id out of the url created_id = self._post_request( data=self.element_to_string(self.encode()) ).headers.get('Location').split('/')[-1] return self.get(created_id) |
def set_cell_value(cell, value): """ Convenience method for setting the value of an openpyxl cell This is necessary since the value property changed from internal_value to value between version 1.* and 2.*. """ if OPENPYXL_MAJOR_VERSION > 1: cell.value = value else: cell.internal_value = value |
def get_change_type(self, ref, a1, a2): """ Given ref, allele1, and allele2, returns the type of change. The only case of an amino acid insertion is when the ref is represented as a '.'. """ if ref == '.': return self.INSERTION elif a1 == '.' or a2 == '.': return self.DELETION |
def get_osid_form_mdata(): """Return default mdata map for OsidForm""" return { 'journal_comment': { 'element_label': { 'text': 'Journal Comment', 'languageTypeId': str(DEFAULT_LANGUAGE_TYPE), 'scriptTypeId': str(DEFAULT_SCRIPT_TYPE), 'formatTypeId': str(DEFAULT_FORMAT_TYPE), }, 'instructions': { 'text': 'Optional form... |
def get_osid_object_mdata(): """Return default mdata map for OsidObject""" return { 'display_name': { 'element_label': { 'text': 'Display Name', 'languageTypeId': str(DEFAULT_LANGUAGE_TYPE), 'scriptTypeId': str(DEFAULT_SCRIPT_TYPE), 'formatTypeId': str(DEFAULT_FORMAT_TYPE), }, 'instructions': { 'text': 'Required, 255 c... |
str(DEFAULT_SCRIPT_TYPE), 'formatTypeId': str(DEFAULT_FORMAT_TYPE), }, 'instructions': { 'text': 'Required genus Type of type osid.type.Type', 'languageTypeId': str(DEFAULT_LANGUAGE_TYPE), 'scriptTypeId': str(DEFAULT_SCRIPT_TYPE), 'formatTypeId': str(DEFAULT_FORMAT_TYPE), }, 'required': True, 'value': False, 'read_only... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.