docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Initializes an authentication middleware instance. Args: application: a WSGI application to be wrapped authenticator (:class:`google.auth.tokens.Authenticator`): an authenticator that authenticates incoming requests
def __init__(self, application, authenticator): if not isinstance(authenticator, tokens.Authenticator): raise ValueError(u"Invalid authenticator") self._application = application self._authenticator = authenticator
617,966
Obtains a signature for an operation in a ReportRequest. Args: op (:class:`endpoints_management.gen.servicecontrol_v1_messages.Operation`): an operation used in a `ReportRequest` Returns: string: a unique signature for that operation
def _sign_operation(op): md5 = hashlib.md5() md5.update(op.consumerId.encode('utf-8')) md5.update(b'\x00') md5.update(op.operationName.encode('utf-8')) if op.labels: signing.add_dict_to_hash(md5, encoding.MessageToPyValue(op.labels)) return md5.digest()
617,971
Adds a report request to the cache. Returns ``None`` if it could not be aggregated, and callers need to send the request to the server, otherwise it returns ``CACHED_OK``. Args: req (:class:`sc_messages.ReportRequest`): the request to be aggregated Result: ...
def report(self, req): if self._cache is None: return None # no cache, send request now if not isinstance(req, sc_messages.ServicecontrolServicesReportRequest): raise ValueError(u'Invalid request') if req.serviceName != self.service_name: _logger.err...
617,980
Computes a http status code and message `AllocateQuotaResponse` The return value a tuple (code, message) where code: is the http status code message: is the message to return Args: allocate_quota_response (:class:`endpoints_management.gen.servicecontrol_v1_messages.AllocateQuotaResponse`): ...
def convert_response(allocate_quota_response, project_id): if not allocate_quota_response or not allocate_quota_response.allocateErrors: return _IS_OK # only allocate_quota the first error for now, as per ESP theError = allocate_quota_response.allocateErrors[0] error_tuple = _QUOTA_ERROR_C...
617,981
Obtains a signature for an operation in a `AllocateQuotaRequest` Args: op (:class:`endpoints_management.gen.servicecontrol_v1_messages.Operation`): an operation used in a `AllocateQuotaRequest` Returns: string: a secure hash generated from the operation
def sign(allocate_quota_request): if not isinstance(allocate_quota_request, sc_messages.AllocateQuotaRequest): raise ValueError(u'Invalid request') op = allocate_quota_request.allocateOperation if op is None or op.methodName is None or op.consumerId is None: logging.error(u'Bad %s: not ...
617,982
Adds the response from sending to `req` to this instance's cache. Args: req (`ServicecontrolServicesAllocateQuotaRequest`): the request resp (AllocateQuotaResponse): the response from sending the request
def add_response(self, req, resp): if self._cache is None: return signature = sign(req.allocateQuotaRequest) with self._cache as c: now = self._timer() item = c.get(signature) if item is None: c[signature] = CachedItem( ...
617,987
Constructor. update_op_func is used to when updating an `Operation` from a `ReportRequestInfo`. Args: metric_name (str): the name of the metric descriptor kind (:class:`MetricKind`): the ``kind`` of the described metric value_type (:class:`ValueType`): the `val...
def __init__(self, metric_name, kind, value_type, update_op_func, mark=Mark.PRODUCER): self.kind = kind self.metric_name = metric_name if mark is Mark.CONSUMER: self.update_op_func = self._consumer_metric(update_op_func) elif mark is Mark.PRODUCER_BY...
618,006
Determines if a given metric descriptor matches this enum instance Args: desc (:class:`endpoints_management.gen.servicecontrol_v1_messages.MetricDescriptor`): the instance to test Return: `True` if desc is supported, otherwise `False`
def matches(self, desc): return (self.metric_name == desc.name and self.kind == desc.metricKind and self.value_type == desc.valueType)
618,007
Updates an operation using the assigned update_op_func Args: info: (:class:`endpoints_management.control.report_request.Info`): the info instance to update an_op: (:class:`endpoints_management.control.report_request.Info`): the info instance to update ...
def do_operation_update(self, info, an_op): self.update_op_func(self.metric_name, info, an_op)
618,008
Determines if the given metric descriptor is supported. Args: desc (:class:`endpoints_management.gen.servicecontrol_v1_messages.MetricDescriptor`): the metric descriptor to test Return: `True` if desc is supported, otherwise `False`
def is_supported(cls, desc): for m in cls: if m.matches(desc): return True return False
618,011
Adds `a_dict` to `a_hash` Args: a_hash (`Hash`): the secure hash, e.g created by hashlib.md5 a_dict (dict[string, [string]]): the dictionary to add to the hash
def add_dict_to_hash(a_hash, a_dict): if a_dict is None: return for k, v in a_dict.items(): a_hash.update(b'\x00' + k.encode('utf-8') + b'\x00' + v.encode('utf-8'))
618,012
Transfer from each MRS in *data* with ACE using grammar *grm*. Args: grm (str): path to a compiled grammar image data (iterable): source MRSs as SimpleMRS strings **kwargs: additional keyword arguments to pass to the AceTransferer Yields: :class:`~delphin.interfaces....
def transfer_from_iterable(grm, data, **kwargs): with AceTransferer(grm, **kwargs) as transferer: for datum in data: yield transferer.interact(datum)
618,301
Generate from each MRS in *data* with ACE using grammar *grm*. Args: grm (str): path to a compiled grammar image data (iterable): MRSs as SimpleMRS strings **kwargs: additional keyword arguments to pass to the AceGenerator Yields: :class:`~delphin.interfaces.ParseRes...
def generate_from_iterable(grm, data, **kwargs): with AceGenerator(grm, **kwargs) as generator: for datum in data: yield generator.interact(datum)
618,302
Deserialize DMRX from a file (handle or filename) Args: fh (str, file): input filename or file object single: if `True`, only return the first read Xmrs object Returns: a generator of Xmrs objects (unless the *single* option is `True`)
def load(fh, single=False): ms = deserialize(fh) if single: ms = next(ms) return ms
618,322
Deserialize DMRX string representations Args: s (str): a DMRX string single (bool): if `True`, only return the first Xmrs object Returns: a generator of Xmrs objects (unless *single* is `True`)
def loads(s, single=False): corpus = etree.fromstring(s) if single: ds = _deserialize_dmrs(next(iter(corpus))) else: ds = (_deserialize_dmrs(dmrs_elem) for dmrs_elem in corpus) return ds
618,323
Deserialize and return a YyTokenLattice object for the initial or internal token set, if provided, from the YY format or the JSON-formatted data; otherwise return the original string. Args: tokenset (str): return `'initial'` or `'internal'` tokens (default: `...
def tokens(self, tokenset='internal'): toks = self.get('tokens', {}).get(tokenset) if toks is not None: if isinstance(toks, stringtypes): toks = YyTokenLattice.from_string(toks) elif isinstance(toks, Sequence): toks = YyTokenLattice.from_l...
618,338
Create a PEG function to match zero or more expressions. Args: e: the expression to match delimiter: an optional expression to match between the primary *e* matches.
def zero_or_more(e, delimiter=None): if delimiter is None: delimiter = lambda s, grm, pos: (s, Ignore, (pos, pos)) def match_zero_or_more(s, grm=None, pos=0): start = pos try: s, obj, span = e(s, grm, pos) pos = span[1] data = [] if obj is Ignore ...
618,356
Create a PEG function to match one or more expressions. Args: e: the expression to match delimiter: an optional expression to match between the primary *e* matches.
def one_or_more(e, delimiter=None): if delimiter is None: delimiter = lambda s, grm, pos: (s, Ignore, (pos, pos)) msg = 'Expected one or more of: {}'.format(repr(e)) def match_one_or_more(s, grm=None, pos=0): start = pos s, obj, span = e(s, grm, pos) pos = span[1] ...
618,357
Return the list of tuples of feature paths and feature values. Args: expand (bool): if `True`, expand all feature paths Example: >>> fs = FeatureStructure([('A.B', 1), ('A.C', 2)]) >>> fs.features() [('A', <FeatureStructure object at ...>)] >>...
def features(self, expand=False): fs = [] if self._avm is not None: if len(self._feats) == len(self._avm): feats = self._feats else: feats = list(self._avm) for feat in feats: val = self._avm[feat] ...
618,413
Return `True` if Xmrs objects *q* and *g* are isomorphic. Isomorphicity compares the predicates of an Xmrs, the variable properties of their predications (if `check_varprops=True`), constant arguments, and the argument structure between predications. Node IDs and Lnk values are ignored. Args: ...
def isomorphic(q, g, check_varprops=True): qdg = _make_digraph(q, check_varprops) gdg = _make_digraph(g, check_varprops) def nem(qd, gd): # node-edge-match return qd.get('sig') == gd.get('sig') return nx.is_isomorphic(qdg, gdg, node_match=nem, edge_match=nem)
618,423
Perform *query* on the testsuite *ts*. Note: currently only 'select' queries are supported. Args: query (str): TSQL query string ts (:class:`delphin.itsdb.TestSuite`): testsuite to query over kwargs: keyword arguments passed to the more specific query function (e.g., :func:...
def query(query, ts, **kwargs): queryobj = _parse_query(query) if queryobj['querytype'] in ('select', 'retrieve'): return _select( queryobj['projection'], queryobj['tables'], queryobj['where'], ts, mode=kwargs.get('mode', 'list'), ...
618,439
Use this method to get a sticker set. On success, a StickerSet object is returned. https://core.telegram.org/bots/api#getstickerset Parameters: :param name: Name of the sticker set :type name: str|unicode Returns: :return: On succes...
def get_sticker_set(self, name): assert_type_or_raise(name, unicode_type, parameter_name="name") result = self.do("getStickerSet", name=name) if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) from pytgbot.api...
618,481
Instantiate a REPP from a PET-style `.set` configuration file. The *path* parameter points to the configuration file. Submodules are loaded from *directory*. If *directory* is not given, it is the directory part of *path*. Args: path (str): the path to the REPP configuratio...
def from_config(cls, path, directory=None): if not exists(path): raise REPPError('REPP config file not found: {}'.format(path)) confdir = dirname(path) # TODO: can TDL parsing be repurposed for this variant? conf = io.open(path, encoding='utf-8').read() conf...
618,529
Instantiate a REPP from a string. Args: name (str, optional): the name of the REPP module modules (dict, optional): a mapping from identifiers to REPP modules active (iterable, optional): an iterable of default module activations
def from_string(cls, s, name=None, modules=None, active=None): r = cls(name=name, modules=modules, active=active) _parse_repp(s.splitlines(), r, None) return r
618,531
Apply the REPP's rewrite rules to the input string *s*. Args: s (str): the input string to process active (optional): a collection of external module names that may be applied if called Returns: a :class:`REPPResult` object containing the processed ...
def apply(self, s, active=None): if active is None: active = self.active return self.group.apply(s, active=active)
618,533
Rewrite and tokenize the input string *s*. Args: s (str): the input string to process pattern (str, optional): the regular expression pattern on which to split tokens; defaults to `[ \t]+` active (optional): a collection of external module names ...
def tokenize(self, s, pattern=None, active=None): if pattern is None: if self.tokenize_pattern is None: pattern = r'[ \t]+' else: pattern = self.tokenize_pattern if active is None: active = self.active return self.group...
618,535
Test if all nodeids share a label. Args: nodeids: iterable of nodeids label (str, optional): the label that all nodeids must share Returns: bool: `True` if all nodeids share a label, otherwise `False`
def in_labelset(xmrs, nodeids, label=None): nodeids = set(nodeids) if label is None: label = xmrs.ep(next(iter(nodeids))).label return nodeids.issubset(xmrs._vars[label]['refs']['LBL'])
618,595
This object represents one shipping option. https://core.telegram.org/bots/api#shippingoption Parameters: :param id: Shipping option identifier :type id: str|unicode :param title: Option title :type title: str|unicode :param...
def __init__(self, id, title, prices): super(ShippingOption, self).__init__() from pytgbot.api_types.sendable.payments import LabeledPrice assert_type_or_raise(id, unicode_type, parameter_name="id") self.id = id assert_type_or_raise(title, unicode_type,...
618,634
Decode a raw line from a profile into a list of column values. Decoding involves splitting the line by the field delimiter (`"@"` by default) and unescaping special characters. If *fields* is given, cast the values into the datatype given by their respective Field object. Args: line: a raw...
def decode_row(line, fields=None): cols = line.rstrip('\n').split(_field_delimiter) cols = list(map(unescape, cols)) if fields is not None: if len(cols) != len(fields): raise ItsdbError( 'Wrong number of fields: {} != {}' .format(len(cols), len(fields...
618,646
Encode a list of column values into a [incr tsdb()] profile line. Encoding involves escaping special characters for each value, then joining the values into a single string with the field delimiter (`"@"` by default). It does not fill in default values (see make_row()). Args: fields: a lis...
def encode_row(fields): # NOTE: str(f) only works for Python3 unicode_fields = [unicode(f) for f in fields] escaped_fields = map(escape, unicode_fields) return _field_delimiter.join(escaped_fields)
618,649
Encode a mapping of column name to values into a [incr tsdb()] profile line. The *fields* parameter determines what columns are used, and default values are provided if a column is missing from the mapping. Args: row: a mapping of column names to values fields: an iterable of :class:`Fi...
def make_row(row, fields): if not hasattr(row, 'get'): row = {f.name: col for f, col in zip(fields, row)} row_fields = [] for f in fields: val = row.get(f.name, None) if val is None: val = str(f.default_value()) row_fields.append(val) return encode_row(r...
618,653
Return the default value for a column. If the column name (e.g. *i-wf*) is defined to have an idiosyncratic value, that value is returned. Otherwise the default value for the column's datatype is returned. Args: fieldname: the column name (e.g. `i-wf`) datatype: the datatype of the col...
def default_value(fieldname, datatype): if fieldname in tsdb_coded_attributes: return str(tsdb_coded_attributes[fieldname]) else: return _default_datatype_values.get(datatype, '')
618,658
Create a Record from a dictionary of field mappings. The *fields* object is used to determine the column indices of fields in the mapping. Args: fields: the Relation schema for the table of this record mapping: a dictionary or other mapping from field names to ...
def from_dict(cls, fields, mapping): iterable = [None] * len(fields) for key, value in mapping.items(): try: index = fields.index(key) except KeyError: raise ItsdbError('Invalid field name(s): ' + key) iterable[index] = value ...
618,678
Return the field data given by field name *key*. Args: key: the field name of the data to return default: the value to return if *key* is not in the row
def get(self, key, default=None, cast=True): tablename, _, key = key.rpartition(':') if tablename and tablename not in self.fields.name.split('+'): raise ItsdbError('column requested from wrong table: {}' .format(tablename)) try: inde...
618,684
Add each record in *records* to the end of the table. Args: record: an iterable of :class:`Record` or other iterables containing column values
def extend(self, records): fields = self.fields for record in records: record = _cast_record_to_str_tuple(record, fields) self._records.append(record)
618,699
Select columns from each row in the table. See :func:`select_rows` for a description of how to use the *mode* parameter. Args: cols: an iterable of Field (column) names mode: how to return the data
def select(self, cols, mode='list'): if isinstance(cols, stringtypes): cols = _split_cols(cols) if not cols: cols = [f.name for f in self.fields] return select_rows(cols, self, mode=mode)
618,700
Add a filter. When reading *table*, rows in *table* will be filtered by filter_rows(). Args: table: The table the filter applies to. cols: The columns in *table* to filter on. condition: The filter function.
def add_filter(self, table, cols, condition): if table is not None and table not in self.relations: raise ItsdbError('Cannot add filter; table "{}" is not defined ' 'by the relations file.' .format(table)) # this is a hack, t...
618,709
Add an applicator. When reading *table*, rows in *table* will be modified by apply_rows(). Args: table: The table to apply the function to. cols: The columns in *table* to apply the function on. function: The applicator function.
def add_applicator(self, table, cols, function): if table not in self.relations: raise ItsdbError('Cannot add applicator; table "{}" is not ' 'defined by the relations file.' .format(table)) if cols is None: rais...
618,710
Encode and write out *table* to the profile directory. Args: table: The name of the table to write rows: The rows to write to the table append: If `True`, append the encoded rows to any existing data. gzip: If `True`, compress the resulting table ...
def write_table(self, table, rows, append=False, gzip=False): _write_table(self.root, table, rows, self.table_relations(table), append=append, gzip=gzip, encoding=self.encoding)
618,717
Request parses for all *inputs*. Args: inputs (iterable): sentences to parse server (str): the url for the server (the default LOGON server is used by default) params (dict): a dictionary of request parameters headers (dict): a dictionary of additional request headers ...
def parse_from_iterable( inputs, server=default_erg_server, params=None, headers=None): client = DelphinRestClient(server) for input in inputs: yield client.parse(input, params=params, headers=headers)
618,729
Request a parse of *sentence* and return the response. Args: sentence (str): sentence to be parsed params (dict): a dictionary of request parameters headers (dict): a dictionary of additional request headers Returns: A ParseResponse containing the results...
def parse(self, sentence, params=None, headers=None): if params is None: params = {} params['input'] = sentence hdrs = {'Accept': 'application/json'} if headers is not None: hdrs.update(headers) url = urljoin(self.server, 'parse') r = re...
618,732
This object represents one shipping option. https://core.telegram.org/bots/api#shippingoption Parameters: :param id: Shipping option identifier :type id: str|unicode :param title: Option title :type title: str|unicode :param prices: List of price portions ...
def __init__(self, id, title, prices): super(ShippingOption, self).__init__() assert_type_or_raise(id, unicode_type, parameter_name="id") self.id = id assert_type_or_raise(title, unicode_type, parameter_name="title") self.title = title assert_type_or_raise(pri...
618,765
Deserialize MRX string representations Args: s (str): a MRX string single (bool): if `True`, only return the first Xmrs object Returns: a generator of Xmrs objects (unless *single* is `True`)
def loads(s, single=False): corpus = etree.fromstring(s) if single: ds = _deserialize_mrs(next(corpus)) else: ds = (_deserialize_mrs(mrs_elem) for mrs_elem in corpus) return ds
618,784
Facilitate conversion among subclasses. Args: xmrs (:class:`Xmrs`): instance to convert from; possibly an instance of a subclass, such as :class:`Mrs` or :class:`Dmrs` **kwargs: additional keyword arguments that may be used by a subclass's...
def from_xmrs(cls, xmrs, **kwargs): x = cls() x.__dict__.update(xmrs.__dict__) return x
618,902
Return the nodeid of the predication selected by *iv*. Args: iv: the intrinsic variable of the predication to select quantifier: if `True`, treat *iv* as a bound variable and find its quantifier; otherwise the non-quantifier will be returned
def nodeid(self, iv, quantifier=False): return next(iter(self.nodeids(ivs=[iv], quantifier=quantifier)), None)
618,908
Return the list of nodeids given by *ivs*, or all nodeids. Args: ivs: the intrinsic variables of the predications to select; if `None`, return all nodeids (but see *quantifier*) quantifier: if `True`, only return nodeids of quantifiers; if `False`, only r...
def nodeids(self, ivs=None, quantifier=None): if ivs is None: nids = list(self._nodeids) else: _vars = self._vars nids = [] for iv in ivs: if iv in _vars and IVARG_ROLE in _vars[iv]['refs']: nids.extend(_vars[iv...
618,909
Return the EPs with the given *nodeid*, or all EPs. Args: nodeids: an iterable of nodeids of EPs to return; if `None`, return all EPs
def eps(self, nodeids=None): if nodeids is None: nodeids = self._nodeids _eps = self._eps return [_eps[nodeid] for nodeid in nodeids]
618,910
Return the ICONS with left variable *left*, or all ICONS. Args: left: the left variable of the ICONS to return; if `None`, return all ICONS
def icons(self, left=None): if left is not None: return self._icons[left] else: return list(chain.from_iterable(self._icons.values()))
618,911
Return a dictionary of variable properties for *var_or_nodeid*. Args: var_or_nodeid: if a variable, return the properties associated with the variable; if a nodeid, return the properties associated with the intrinsic variable of the predication given ...
def properties(self, var_or_nodeid, as_list=False): props = [] if var_or_nodeid in self._vars: props = self._vars[var_or_nodeid]['props'] elif var_or_nodeid in self._eps: var = self._eps[var_or_nodeid][3].get(IVARG_ROLE) props = self._vars.get(var, {}...
618,912
Return the Pred objects for *nodeids*, or all Preds. Args: nodeids: an iterable of nodeids of predications to return Preds from; if `None`, return all Preds
def preds(self, nodeids=None): if nodeids is None: nodeids = self._nodeids _eps = self._eps return [_eps[nid][1] for nid in nodeids]
618,913
Return the arguments going from *nodeid* to other predications. Valid arguments include regular variable arguments and scopal (label-selecting or HCONS) arguments. MOD/EQ links, intrinsic arguments, and constant arguments are not included. Args: nodeid: the nodeid o...
def outgoing_args(self, nodeid): _vars = self._vars _hcons = self._hcons args = self.args(nodeid) # args is a copy; we can edit it for arg, val in list(args.items()): # don't include constant args or intrinsic args if arg == IVARG_ROLE or val not in _var...
618,915
Return the arguments that target *nodeid*. Valid arguments include regular variable arguments and scopal (label-selecting or HCONS) arguments. MOD/EQ links and intrinsic arguments are not included. Args: nodeid: the nodeid of the EP that is the arguments' target Ret...
def incoming_args(self, nodeid): _vars = self._vars ep = self._eps[nodeid] lbl = ep[2] iv = ep[3].get(IVARG_ROLE) in_args_list = [] # variable args if iv in _vars: for role, nids in _vars[iv]['refs'].items(): # ignore intrinsic...
618,916
Return the heads of the labelset selected by *label*. Args: label: the label from which to find head nodes/EPs. Returns: An iterable of nodeids.
def labelset_heads(self, label): _eps = self._eps _vars = self._vars _hcons = self._hcons nodeids = {nodeid: _eps[nodeid][3].get(IVARG_ROLE, None) for nodeid in _vars[label]['refs']['LBL']} if len(nodeids) <= 1: return list(nodeids) s...
618,917
Return an Xmrs object with only the specified *nodeids*. Necessary variables and arguments are also included in order to connect any nodes that are connected in the original Xmrs. Args: nodeids: the nodeids of the nodes/EPs to include in the subgraph. Return...
def subgraph(self, nodeids): _eps, _vars = self._eps, self._vars _hcons, _icons = self._hcons, self._icons top = index = xarg = None eps = [_eps[nid] for nid in nodeids] lbls = set(ep[2] for ep in eps) hcons = [] icons = [] subvars = {} if...
618,918
Serialize Xmrs objects to the Prolog representation and write to a file. Args: destination: filename or file object where data will be written ms: an iterator of Xmrs objects to serialize (unless the *single* option is `True`) single: if `True`, treat *ms* as a single Xmrs objec...
def dump(destination, ms, single=False, pretty_print=False, **kwargs): text = dumps(ms, single=single, pretty_print=pretty_print, **kwargs) if hasattr(destination, 'write'): print(text, file=destination) else: with open(destination, 'w...
618,952
Serialize an Xmrs object to the Prolog representation Args: ms: an iterator of Xmrs objects to serialize (unless the *single* option is `True`) single: if `True`, treat *ms* as a single Xmrs object instead of as an iterator pretty_print: if `True`, add newlines and i...
def dumps(ms, single=False, pretty_print=False, **kwargs): if single: ms = [ms] return serialize(ms, pretty_print=pretty_print, **kwargs)
618,953
Read a variable-property mapping from *source* and return the VPM. Args: source: a filename or file-like object containing the VPM definitions semi (:class:`~delphin.mrs.semi.SemI`, optional): if provided, it is passed to the VPM constructor Returns: a :class:`VP...
def load(source, semi=None): if hasattr(source, 'read'): return _load(source, semi) else: with open(source, 'r') as fh: return _load(fh, semi)
618,961
Apply the VPM to variable *var* and properties *props*. Args: var: a variable props: a dictionary mapping properties to values reverse: if `True`, apply the rules in reverse (e.g. from grammar-external to grammar-internal forms) Returns: a...
def apply(self, var, props, reverse=False): vs, vid = sort_vid_split(var) if reverse: # variable type mapping is disabled in reverse # tms = [(b, op, a) for a, op, b in self._typemap if op in _RL_OPS] tms = [] else: tms = [(a, op, b) for a...
618,965
Deserialize :class:`Eds` from a file (handle or filename) Args: fh (str, file): input filename or file object single (bool): if `True`, only return the first Xmrs object Returns: a generator of :class:`Eds` objects (unless the *single* option is `True`)
def load(fh, single=False): if isinstance(fh, stringtypes): s = open(fh, 'r').read() else: s = fh.read() return loads(s, single=single)
618,990
Deserialize :class:`Eds` string representations Args: s (str): Eds string single (bool): if `True`, only return the first Xmrs object Returns: a generator of :class:`Eds` objects (unless the *single* option is `True`)
def loads(s, single=False): es = deserialize(s) if single: return next(es) return es
618,991
Deserialize SimpleMRS string representations Args: s (str): a SimpleMRS string single (bool): if `True`, only return the first Xmrs object Returns: a generator of Xmrs objects (unless *single* is `True`)
def loads(s, single=False, version=_default_version, strict=False, errors='warn'): ms = deserialize(s, version=version, strict=strict, errors=errors) if single: return next(ms) else: return ms
619,131
Instantiate a `Derivation` from a UDF or UDX string representation. The UDF/UDX representations are as output by a processor like the `LKB <http://moin.delph-in.net/LkbTop>`_ or `ACE <http://sweaglesw.org/linguistics/ace/>`_, or from the :meth:`UdfNode.to_udf` or :meth:`UdfNode.to_udx` ...
def from_string(cls, s): if not (s.startswith('(') and s.endswith(')')): raise ValueError( 'Derivations must begin and end with parentheses: ( )' ) s_ = s[1:] # get rid of initial open-parenthesis stack = [] deriv = None try: ...
619,164
Deserialize PENMAN graphs from a file (handle or filename) Args: fh: filename or file object model: Xmrs subclass instantiated from decoded triples Returns: a list of objects (of class *model*)
def load(fh, model): graphs = penman.load(fh, cls=XMRSCodec) xs = [model.from_triples(g.triples()) for g in graphs] return xs
619,165
Deserialize PENMAN graphs from a string Args: s (str): serialized PENMAN graphs model: Xmrs subclass instantiated from decoded triples Returns: a list of objects (of class *model*)
def loads(s, model): graphs = penman.loads(s, cls=XMRSCodec) xs = [model.from_triples(g.triples()) for g in graphs] return xs
619,166
Serialize Xmrs (or subclass) objects to PENMAN and write to a file. Args: destination: filename or file object xs: iterator of :class:`~delphin.mrs.xmrs.Xmrs` objects to serialize model: Xmrs subclass used to get triples properties: if `True`, encode variable properties ...
def dump(destination, xs, model=None, properties=False, indent=True, **kwargs): text = dumps( xs, model=model, properties=properties, indent=indent, **kwargs ) if hasattr(destination, 'write'): print(text, file=destination) else: with open(destination, 'w') as fh: ...
619,167
Serialize Xmrs (or subclass) objects to PENMAN notation Args: xs: iterator of :class:`~delphin.mrs.xmrs.Xmrs` objects to serialize model: Xmrs subclass used to get triples properties: if `True`, encode variable properties indent: if `True`, adaptively indent; if `False` ...
def dumps(xs, model=None, properties=False, indent=True, **kwargs): xs = list(xs) if not xs: return '' given_class = xs[0].__class__ # assume they are all the same if model is None: model = xs[0].__class__ if not hasattr(model, 'to_triples'): raise TypeError( ...
619,168
Parse the TDL file *f* and yield the interpreted contents. If *f* is a filename, the file is opened and closed when the generator has finished, otherwise *f* is an open file object and will not be closed when the generator has finished. Args: f (str, file): a filename or open file object ...
def parse(f, encoding='utf-8'): if hasattr(f, 'read'): for event in _parse(f): yield event else: with io.open(f, encoding=encoding) as fh: for event in _parse(fh): yield event
619,241
Append an item to the end of an open ConsList. Args: value (:class:`Conjunction`, :class:`Term`): item to add Raises: :class:`TdlError`: when appending to a closed list
def append(self, value): if self._avm is not None and not self.terminated: path = self._last_path if path: path += '.' self[path + LIST_HEAD] = value self._last_path = path + LIST_TAIL self[self._last_path] = AVM() else...
619,273
Add a term to the conjunction. Args: term (:class:`Term`, :class:`Conjunction`): term to add; if a :class:`Conjunction`, all of its terms are added to the current conjunction. Raises: :class:`TypeError`: when *term* is an invalid type
def add(self, term): if isinstance(term, Conjunction): for term_ in term.terms: self.add(term_) elif isinstance(term, Term): self._terms.append(term) else: raise TypeError('Not a Term or Conjunction')
619,284
Create a Lnk object for a character span. Args: start: the initial character position (cfrom) end: the final character position (cto)
def charspan(cls, start, end): return cls(Lnk.CHARSPAN, (int(start), int(end)))
619,325
Create a Lnk object for a chart span. Args: start: the initial chart vertex end: the final chart vertex
def chartspan(cls, start, end): return cls(Lnk.CHARTSPAN, (int(start), int(end)))
619,326
Create a Lnk object for a token range. Args: tokens: a list of token identifiers
def tokens(cls, tokens): return cls(Lnk.TOKENS, tuple(map(int, tokens)))
619,327
Construct a Search object. Args: access_token (str): A valid Companies House API. If an access token isn't specified then looks for *CompaniesHouseKey* or COMPANIES_HOUSE_KEY environment variables. Defaults to None.
def __init__(self, access_token=None, rate_limit=True): super(Search, self).__init__() self.session = self.get_session(access_token=access_token, rate_limit=rate_limit) self._ignore_codes = [] if rate_limit: self._ignore_codes....
619,691
Search for officers by name. Args: term (str): Officer name to search on. disqualified (Optional[bool]): True to search for disqualified officers kwargs (dict): additional keywords passed into requests.session.get params keyword.
def search_officers(self, term, disqualified=False, **kwargs): search_type = ('officers' if not disqualified else 'disqualified-officers') params = kwargs params['q'] = term baseuri = self._BASE_URI + 'search/{}'.format(search_type) res = self.sess...
619,692
Search for company addresses by company number. Args: num (str): Company number to search on.
def address(self, num): url_root = "company/{}/registered-office-address" baseuri = self._BASE_URI + url_root.format(num) res = self.session.get(baseuri) self.handle_http_error(res) return res
619,693
Search for company profile by company number. Args: num (str): Company number to search on.
def profile(self, num): baseuri = self._BASE_URI + "company/{}".format(num) res = self.session.get(baseuri) self.handle_http_error(res) return res
619,694
Search for a company's filling history by company number. Args: num (str): Company number to search on. transaction (Optional[str]): Filing record number. kwargs (dict): additional keywords passed into requests.session.get params keyword.
def filing_history(self, num, transaction=None, **kwargs): baseuri = self._BASE_URI + "company/{}/filing-history".format(num) if transaction is not None: baseuri += "/{}".format(transaction) res = self.session.get(baseuri, params=kwargs) self.handle_http_error(res) ...
619,695
Search for charges against a company by company number. Args: num (str): Company number to search on. transaction (Optional[str]): Filing record number. kwargs (dict): additional keywords passed into requests.session.get params keyword.
def charges(self, num, charge_id=None, **kwargs): baseuri = self._BASE_URI + "company/{}/charges".format(num) if charge_id is not None: baseuri += "/{}".format(charge_id) res = self.session.get(baseuri, params=kwargs) else: res = self.session.get(base...
619,696
Search for a company's registered officers by company number. Args: num (str): Company number to search on. kwargs (dict): additional keywords passed into requests.session.get *params* keyword.
def officers(self, num, **kwargs): baseuri = self._BASE_URI + "company/{}/officers".format(num) res = self.session.get(baseuri, params=kwargs) self.handle_http_error(res) return res
619,697
Search for disqualified officers by officer ID. Searches for natural disqualifications by default. Specify natural=False to search for corporate disqualifications. Args: num (str): Company number to search on. natural (Optional[bool]): Natural or corporate search ...
def disqualified(self, num, natural=True, **kwargs): search_type = 'natural' if natural else 'corporate' baseuri = (self._BASE_URI + 'disqualified-officers/{}/{}'.format(search_type, num)) res = self.session.get(baseuri, params=kwargs) self.handle_http_error(r...
619,698
Requests for a document by the document id. Normally the response.content can be saved as a pdf file Args: document_id (str): The id of the document retrieved. kwargs (dict): additional keywords passed into requests.session.get *params* keyword.
def document(self, document_id, **kwargs): baseuri = '{}document/{}/content'.format(self._DOCUMENT_URI, document_id) res = self.session.get(baseuri, params=kwargs) self.handle_http_error(res) return res
619,701
Connects an input list of xy tuples with lines forming a set of smallest possible Delauney triangles between them. Arguments: - **points**: A list of xy or xyz point tuples to triangulate. Returns: - A list of triangle polygons. If the input coordinate points contained a third z value ...
def triangulate(points): # Remove duplicate xy points bc that would make delauney fail, and must remember z (if any) for retrieving originals from index results seen = set() uniqpoints = [ p for p in points if str( p[:2] ) not in seen and not seen.add( str( p[:2] ) )] classpoints = [_Point(*poin...
620,037
Deserialize PENMAN-serialized *s* into its Graph object Args: s: a string containing a single PENMAN-serialized graph cls: serialization codec class kwargs: keyword arguments passed to the constructor of *cls* Returns: the Graph object described by *s* Example: >>> ...
def decode(s, cls=PENMANCodec, **kwargs): codec = cls(**kwargs) return codec.decode(s)
622,059
Serialize the graph *g* from *top* to PENMAN notation. Args: g: the Graph object top: the node identifier for the top of the serialized graph; if unset, the original top of *g* is used cls: serialization codec class kwargs: keyword arguments passed to the constructor of ...
def encode(g, top=None, cls=PENMANCodec, **kwargs): codec = cls(**kwargs) return codec.encode(g, top=top)
622,060
Deserialize a list of PENMAN-encoded graphs from *source*. Args: source: a filename or file-like object to read from triples: if True, read graphs as triples instead of as PENMAN cls: serialization codec class kwargs: keyword arguments passed to the constructor of *cls* Returns:...
def load(source, triples=False, cls=PENMANCodec, **kwargs): decode = cls(**kwargs).iterdecode if hasattr(source, 'read'): return list(decode(source.read())) else: with open(source) as fh: return list(decode(fh.read()))
622,061
Deserialize a list of PENMAN-encoded graphs from *string*. Args: string: a string containing graph data triples: if True, read graphs as triples instead of as PENMAN cls: serialization codec class kwargs: keyword arguments passed to the constructor of *cls* Returns: a li...
def loads(string, triples=False, cls=PENMANCodec, **kwargs): codec = cls(**kwargs) return list(codec.iterdecode(string, triples=triples))
622,062
Serialize each graph in *graphs* to PENMAN and write to *file*. Args: graphs: an iterable of Graph objects file: a filename or file-like object to write to triples: if True, write graphs as triples instead of as PENMAN cls: serialization codec class kwargs: keyword arguments...
def dump(graphs, file, triples=False, cls=PENMANCodec, **kwargs): text = dumps(graphs, triples=triples, cls=cls, **kwargs) if hasattr(file, 'write'): print(text, file=file) else: with open(file, 'w') as fh: print(text, file=fh)
622,063
Serialize each graph in *graphs* to the PENMAN format. Args: graphs: an iterable of Graph objects triples: if True, write graphs as triples instead of as PENMAN Returns: the string of serialized graphs
def dumps(graphs, triples=False, cls=PENMANCodec, **kwargs): codec = cls(**kwargs) strings = [codec.encode(g, triples=triples) for g in graphs] return '\n\n'.join(strings)
622,064
Initialize a new codec. Args: indent: if True, adaptively indent; if False or None, don't indent; if a non-negative integer, indent that many spaces per nesting level relation_sort: when encoding, sort the relations on each node according ...
def __init__(self, indent=True, relation_sort=original_order): self.indent = indent self.relation_sort = relation_sort
622,066
Create a Graph from an iterable of triples. Args: data: an iterable of triples (Triple objects or 3-tuples) top: the node identifier of the top node; if unspecified, the source of the first triple is used Example: >>> Graph([ ... ('b'...
def __init__(self, data=None, top=None): self._triples = [] self._top = None if data is None: data = [] else: data = list(data) # make list (e.g., if its a generator) if data: self._triples.extend( Triple(*t, inverte...
622,080
Prepares the request, checks for authentication and retries in case of issues Args: url (str): URL of the request method (str): Any of "get", "post", "delete" data (any): Possible extra data to send with the request extra_headers (dict): Possible extra headers to...
def _make_request(self, url, method="get", data=None, extra_headers=None): attempts = 0 while attempts < 1: # Authenticate first if not authenticated already if not self._is_authenticated: self._authenticate() # Make the request and check for...
623,351
Performs a given request and returns a json object Args: url (str): URL of the request method (str): Any of "get", "post", "delete" data (any): Possible extra data to send with the request extra_headers (dict): Possible extra headers to send along in the request ...
def _send_request(self, url, method="get", data=None, extra_headers=None): headers = {'Content-type': 'application/json'} if isinstance(extra_headers, dict): headers.update(extra_headers) if not data or "password" not in data: logger.debug("Sending {method} requ...
623,352
Determines the controller name for the object's type Args: objtype (str): The object type Returns: A string with the controller name
def _controller_name(self, objtype): # would be better to use inflect.pluralize here, but would add a dependency if objtype.endswith('y'): return objtype[:-1] + 'ies' if objtype[-1] in 'sx' or objtype[-2:] in ['sh', 'ch']: return objtype + 'es' if objty...
623,355
Generate the URL for the specified object Args: objtype (str): The object's type objid (int): The objects ID Returns: A string containing the URL of the object
def _object_url(self, objtype, objid): return "{base_url}/api/{api_version}/{controller}/{obj_id}".format( base_url=self._base_url(), api_version=self.api_version, controller=self._controller_name(objtype), obj_id=objid )
623,356
Generate the URL for the requested method Args: method_name (str): Name of the method Returns: A string containing the URL of the method
def _method_url(self, method_name): return "{base_url}/api/{api}/{method}".format( base_url=self._base_url(), api=self.api_version, method=method_name )
623,357
Execute an arbitrary method. Args: method_name (str): include the controller name: 'devices/search' params (dict): the method parameters Returns: A dict with the response Raises: requests.exceptions.HTTPError
def api_request(self, method_name, params): url = self._method_url(method_name) data = json.dumps(params) return self._make_request(url=url, method="post", data=data)
623,358
Query for a specific resource by ID Args: objtype (str): object type, e.g. 'device', 'interface' objid (int): object ID (DeviceID, etc.) Returns: A dict with that object Raises: requests.exceptions.HTTPError
def show(self, objtype, objid): url = self._object_url(objtype, int(objid)) return self._make_request(url, method="get")
623,359
Get the historical tank data. Args: nmr_problems (int): the number of problems Returns: tuple: (observations, nmr_tanks_ground_truth)
def get_historical_data(nmr_problems): observations = np.tile(np.array([[10, 256, 202, 97]]), (nmr_problems, 1)) nmr_tanks_ground_truth = np.ones((nmr_problems,)) * 276 return observations, nmr_tanks_ground_truth
623,784
Simulate some data. This returns the simulated tank observations and the corresponding ground truth maximum number of tanks. Args: nmr_problems (int): the number of problems Returns: tuple: (observations, nmr_tanks_ground_truth)
def get_simulated_data(nmr_problems): # The number of tanks we observe per problem nmr_observed_tanks = 10 # Generate some maximum number of tanks. Basically the ground truth of the estimation problem. nmr_tanks_ground_truth = normal(nmr_problems, 1, mean=250, std=30, ctype='uint') # Generate...
623,785
Updates the runtime settings. Args: cl_environments (list of CLEnvironment): the new CL environments we wish to use for future computations compile_flags (list): the list of compile flags to use during analysis. double_precision (boolean): if we compute in double precision o...
def __init__(self, cl_environments=None, compile_flags=None, double_precision=None): super().__init__() self._cl_environments = cl_environments self._compile_flags = compile_flags self._double_precision = double_precision
623,795