code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
needs_recommendation = True full_indexes = [] partial_indexes = [] coverage = "unknown" if indexes is not None: for index_key in indexes.keys(): index = indexes[index_key] index_report = self._generate_index_report(index, ...
def _generate_index_analysis(self, query_analysis, indexes)
Compares a query signature to the index cache to identify complete and partial indexes available to the query
3.071653
2.971103
1.033843
all_fields = [] equiv_fields = [] sort_fields = [] range_fields = [] for query_field in query_analysis['analyzedFields']: all_fields.append(query_field['fieldName']) if query_field['fieldType'] is EQUIV_TYPE: equiv_fields.append(...
def _generate_index_report(self, index, query_analysis)
Analyzes an existing index against the results of query analysis
2.286639
2.263443
1.010248
index_rec = '{' for query_field in query_analysis['analyzedFields']: if query_field['fieldType'] is EQUIV_TYPE: if len(index_rec) is not 1: index_rec += ', ' index_rec += '"' + query_field['fieldName'] + '": 1' for query_fi...
def _generate_recommendation(self, query_analysis, db_name, collection_name)
Generates an ideal query recommendation
2.301091
2.278343
1.009984
initial_millis = int(report['parsed']['stats']['millis']) mask = report['queryMask'] existing_report = self._get_existing_report(mask, report) if existing_report is not None: self._merge_report(existing_report, report) else: time = None ...
def add_query_occurrence(self, report)
Adds a report to the report aggregation
4.601306
4.521416
1.017669
return sorted(self._reports, key=lambda x: x['stats']['totalTimeMillis'], reverse=True)
def get_reports(self)
Returns a minimized version of the aggregation
9.010783
7.937954
1.135152
for existing_report in self._reports: if existing_report['namespace'] == report['namespace']: if mask == existing_report['queryMask']: return existing_report return None
def _get_existing_report(self, mask, report)
Returns the aggregated report that matches report
4.217524
3.861196
1.092284
time = None if 'ts' in new['parsed']: time = new['parsed']['ts'] if (target.get('lastSeenDate', None) and time and target['lastSeenDate'] < time): target['lastSeenDate'] = time query_millis = int(new['parsed']['stats'...
def _merge_report(self, target, new)
Merges a new report into the target report
4.05788
3.897813
1.041066
query = None for handler in self._line_handlers: try: query = handler.handle(input) except Exception as e: query = None finally: if query is not None: return query return None
def parse(self, input)
Passes input to each QueryLineHandler in use
4.26509
2.909758
1.465789
return self._query_analyzer.generate_query_report(db_uri, query, db_name, collection_name)
def generate_query_report(self, db_uri, query, db_name, collection_name)
Analyzes a single query
3.723878
3.737906
0.996247
profile_parser = ProfileParser() databases = self._get_requested_databases() connection = pymongo.MongoClient(self._db_uri, document_class=OrderedDict, read_preference=pymongo.ReadPreference.PRIMARY_PREFER...
def analyze_profile(self)
Analyzes queries from a given log file
4.676979
4.549959
1.027917
profile_parser = ProfileParser() databases = self._get_requested_databases() connection = pymongo.MongoClient(self._db_uri, document_class=OrderedDict, read_preference=pymongo.ReadPreference.PRIMARY_PREFER...
def watch_profile(self)
Analyzes queries from a given log file
3.8979
3.844559
1.013874
self._run_stats['logSource'] = logfile_path with open(logfile_path) as obj: self.analyze_logfile_object(obj) self._output_aggregated_report(sys.stdout) return 0
def analyze_logfile(self, logfile_path)
Analyzes queries from a given log file
10.87793
11.40275
0.953974
log_parser = LogParser() if self._start_time is None: self._start_time = datetime.now() if self._timeout != 0: self._end_time = self._start_time + timedelta(minutes=self._timeout) else: self._end_time = None # For eac...
def analyze_logfile_object(self, file_object)
Analyzes queries from a given log file
2.94349
2.775937
1.060359
self._run_stats['logSource'] = logfile_path log_parser = LogParser() # For each new line in the logfile ... output_time = time.time() + WATCH_DISPLAY_REFRESH_SECONDS try: firstLine = True for line in self._tail_file(open(logfile_path), ...
def watch_logfile(self, logfile_path)
Analyzes queries from the tail of a given log file
4.124421
3.867356
1.06647
file.seek(0,2) while True: where = file.tell() line = file.readline() if not line: time.sleep(interval) file.seek(where) else: yield line
def _tail_file(self, file, interval)
Tails a file
2.391914
2.537735
0.942539
latest_doc = None while latest_doc is None: time.sleep(interval) latest_doc = db['system.profile'].find_one() current_time = latest_doc['ts'] while True: time.sleep(interval) cursor = db['system.profile'].find({'ts': {'$gte': cur...
def _tail_profile(self, db, interval)
Tails the system.profile collection
2.649857
2.361369
1.12217
namespace_split = namespace.split('.', 1) if len(namespace_split) is 1: # we treat a single element as a collection name. # this also properly tuplefies '*' namespace_tuple = ('*', namespace_split[0]) elif len(namespace_split) is 2: namesp...
def _tuplefy_namespace(self, namespace)
Converts a mongodb namespace to a db, collection tuple
4.234667
3.716973
1.139278
output_namespaces = [] if input_namespaces == []: return output_namespaces elif '*' in input_namespaces: if len(input_namespaces) > 1: warning = 'Warning: Multiple namespaces are ' warning += 'ignored when one namespace is "*"\n' ...
def _validate_namespaces(self, input_namespaces)
Converts a list of db namespaces to a list of namespace tuples, supporting basic commandline wildcards
2.303374
2.277004
1.011581
if namespace is None: return False namespace_tuple = self._tuplefy_namespace(namespace) if namespace_tuple[0] in IGNORE_DBS: return False elif namespace_tuple[1] in IGNORE_COLLECTIONS: return False else: return self._tuple_...
def _namespace_requested(self, namespace)
Checks whether the requested_namespaces contain the provided namespace
3.961488
4.048732
0.978452
if not isinstance(namespace_tuple[0], unicode): encoded_db = unicode(namespace_tuple[0]) else: encoded_db = namespace_tuple[0] if not isinstance(namespace_tuple[1], unicode): encoded_coll = unicode(namespace_tuple[1]) else: encoded...
def _tuple_requested(self, namespace_tuple)
Helper for _namespace_requested. Supports limited wildcards
2.370303
2.313529
1.02454
requested_databases = [] if ((self._requested_namespaces is not None) and (self._requested_namespaces != [])): for requested_namespace in self._requested_namespaces: if requested_namespace[0] is '*': return [] elif ...
def _get_requested_databases(self)
Returns a list of databases requested, not including ignored dbs
3.25865
2.820349
1.155407
return self._make_request('get')
def retrieve(self, state=None, favorite=None, tag=None, contentType=None, sort=None, detailType=None, search=None, domain=None, since=None, count=None, offset=None)
Retrieve the list of your articles See: https://getpocket.com/developer/docs/v3/retrieve :param state: filter by state :param favorite: only fetch favorite :param tag: filter by tag or _untagged_ :param contentType: get article, video or image :param sort: sort by provide...
20.95281
29.484743
0.710632
self._add_action('add') return self
def bulk_add(self, item_id, ref_id=None, tags=None, time=None, title=None, url=None)
Add an item to list See: https://getpocket.com/developer/docs/v3/modify :param item_id: int :param ref_id: tweet_id :param tags: list of tags :param time: time of action :param title: given title :param url: item url :return: self for chaining :rty...
18.533422
27.051762
0.68511
kwargs = self._get_method_params() kwargs['action'] = action self._bulk_actions.append(kwargs)
def _add_action(self, action)
Register an action into bulk :param action: action name
8.927718
8.537368
1.045723
if isinstance(action, list): kwargs = {'actions': action} action = 'send' else: kwargs = self._get_method_params() kwargs.update({ 'consumer_key': self._consumer_key, 'access_token': self._access_token }) resp...
def _make_request(self, action)
Perform the request :param action: action name :return: a dict containing the request result :rtype: dict
2.689395
2.78675
0.965065
caller = sys._getframe(2) var_names = list(caller.f_code.co_varnames) caller_locals = caller.f_locals var_names.remove('self') kwargs = {key: value for key, value in caller_locals.items() if key in var_names and value is not None} return kwargs
def _get_method_params(self)
This method makes reading and filtering each method implemented in this class a more general approach. It reads the previous frame from Python and filters the params passed to the caller of _make_request. :return: a dictionary of caller's parameters and values :rtype: dict
2.97789
3.050834
0.97609
headers = response.headers limit_headers = [] if 'X-Limit-User-Limit' in headers: limit_headers = [ headers['X-Limit-User-Limit'], headers['X-Limit-User-Remaining'], headers['X-Limit-User-Reset'], headers['X-Li...
def _make_exception(self, response)
In case of exception, construct the exception object that holds all important values returned by the response. :return: The exception instance :rtype: PocketException
2.831619
2.685695
1.054334
if money_currency not in self.money_formats: raise CurrencyDoesNotExist self.money_currency = money_currency
def set_money_currency(self, money_currency)
:type money_currency: str
5.797209
4.991499
1.161416
return self.money_formats[ self.get_money_currency() ]['money_format'].format(amount=amount)
def get_money_format(self, amount)
:type amount: int or float or str Usage: >>> currency = Currency('USD') >>> currency.get_money_format(13) >>> '$13' >>> currency.get_money_format(13.99) >>> '$13.99' >>> currency.get_money_format('13,2313,33') >>> '$13,2313,33' :rtype: str
6.818545
7.995805
0.852765
return self.money_formats[ self.get_money_currency() ]['money_with_currency_format'].format(amount=amount)
def get_money_with_currency_format(self, amount)
:type amount: int or float or str Usage: >>> currency = Currency('USD') >>> currency.get_money_with_currency_format(13) >>> '$13 USD' >>> currency.get_money_with_currency_format(13.99) >>> '$13.99 USD' >>> currency.get_money_with_currency_format('13,2313,33') ...
5.602801
6.494735
0.862668
get_startup = retrieve == "all" or retrieve == "startup" get_running = retrieve == "all" or retrieve == "running" get_candidate = retrieve == "all" or retrieve == "candidate" if retrieve == "all" or get_running: result = self._execute_command_with_vdom('show') ...
def get_config(self, retrieve="all")
get_config implementation for FortiOS.
3.260185
3.082981
1.057478
self._connect() logger.debug('Connected to Deluge, detecting daemon version') self._detect_deluge_version() logger.debug('Daemon version {} detected, logging in'.format(self.deluge_version)) if self.deluge_version == 2: result = self.call('daemon.login', self...
def connect(self)
Connects to the Deluge instance
4.057703
3.537692
1.146992
if self.connected: self._socket.close() self._socket = None self.connected = False
def disconnect(self)
Disconnect from deluge
3.500774
3.411558
1.026151
tried_reconnect = False for _ in range(2): try: self._send_call(self.deluge_version, self.deluge_protocol_version, method, *args, **kwargs) return self._receive_response(self.deluge_version, self.deluge_protocol_version) except (socket.err...
def call(self, method, *args, **kwargs)
Calls an RPC function
3.32606
3.34442
0.99451
array = super(StickerSet, self).to_array() array['name'] = u(self.name) # py2: type unicode, py3: type str array['title'] = u(self.title) # py2: type unicode, py3: type str array['contains_masks'] = bool(self.contains_masks) # type bool array['stickers'] = self._as_...
def to_array(self)
Serializes this StickerSet to a dictionary. :return: dictionary representation of this object. :rtype: dict
2.503221
2.228515
1.123268
if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") from pytgbot.api_types.receivable.media import Sticker data = {} data['name'] = u(array.get('name')) data['title'] = u(arra...
def from_array(array)
Deserialize a new StickerSet from a given dictionary. :return: new StickerSet instance. :rtype: StickerSet
2.96331
2.419196
1.224915
array = super(MaskPosition, self).to_array() array['point'] = u(self.point) # py2: type unicode, py3: type str array['x_shift'] = float(self.x_shift) # type float array['y_shift'] = float(self.y_shift) # type float array['scale'] = float(self.scale) # type float ...
def to_array(self)
Serializes this MaskPosition to a dictionary. :return: dictionary representation of this object. :rtype: dict
3.3715
2.729129
1.235376
if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") data = {} data['point'] = u(array.get('point')) data['x_shift'] = float(array.get('x_shift')) data['y_shift'] = float(array.get('y_s...
def from_array(array)
Deserialize a new MaskPosition from a given dictionary. :return: new MaskPosition instance. :rtype: MaskPosition
3.191976
2.587161
1.233775
try: check_call( [(executable or 'ace'), '-g', cfg_path, '-G', out_path], stdout=log, stderr=log, close_fds=True, env=(env or os.environ) ) except (CalledProcessError, OSError): logging.error( 'Failed to compile grammar with ACE. See {...
def compile(cfg_path, out_path, executable=None, env=None, log=None)
Use ACE to compile a grammar. Args: cfg_path (str): the path to the ACE config file out_path (str): the path where the compiled grammar will be written executable (str, optional): the path to the ACE binary; if `None`, the `ace` command will be used env (dict...
3.934409
3.345116
1.176165
with AceParser(grm, **kwargs) as parser: for datum in data: yield parser.interact(datum)
def parse_from_iterable(grm, data, **kwargs)
Parse each sentence in *data* with ACE using grammar *grm*. Args: grm (str): path to a compiled grammar image data (iterable): the sentences to parse **kwargs: additional keyword arguments to pass to the AceParser Yields: :class:`~delphin.interfaces.ParseResponse` Example: ...
7.304302
9.901488
0.737697
with AceTransferer(grm, **kwargs) as transferer: for datum in data: yield transferer.interact(datum)
def transfer_from_iterable(grm, data, **kwargs)
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....
7.698643
6.464736
1.190867
with AceGenerator(grm, **kwargs) as generator: for datum in data: yield generator.interact(datum)
def generate_from_iterable(grm, data, **kwargs)
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...
7.048168
8.342351
0.844866
try: self._p.stdin.write((datum.rstrip() + '\n')) self._p.stdin.flush() except (IOError, OSError): # ValueError if file was closed manually logging.info( 'Attempted to write to a closed process; attempting to reopen' ) ...
def send(self, datum)
Send *datum* (e.g. a sentence or MRS) to ACE. Warning: Sending data without reading (e.g., via :meth:`receive`) can fill the buffer and cause data to be lost. Use the :meth:`interact` method for most data-processing tasks with ACE.
3.717844
3.91725
0.949095
validated = self._validate_input(datum) if validated: self.send(validated) result = self.receive() else: result, lines = _make_response( [('NOTE: PyDelphin could not validate the input and ' 'refused to send it to ACE...
def interact(self, datum)
Send *datum* to ACE and return the response. This is the recommended method for sending and receiving data to/from an ACE process as it reduces the chances of over-filling or reading past the end of the buffer. It also performs a simple validation of the input to help ensure that ...
10.792035
8.927888
1.2088
response = self.interact(datum) if keys is not None: response['keys'] = keys if 'task' not in response and self.task is not None: response['task'] = self.task return response
def process_item(self, datum, keys=None)
Send *datum* to ACE and return the response with context. The *keys* parameter can be used to track item identifiers through an ACE interaction. If the `task` member is set on the AceProcess instance (or one of its subclasses), it is kept in the response as well. Args: ...
3.908588
3.608139
1.08327
self.run_info['end'] = datetime.now() self._p.stdin.close() for line in self._p.stdout: if line.startswith('NOTE: tsdb run:'): self._read_run_info(line) else: logging.debug('ACE cleanup: {}'.format(line.rstrip())) retval = ...
def close(self)
Close the ACE process and return the process's exit code.
7.220914
5.667012
1.274201
ms = deserialize(fh) if single: ms = next(ms) return ms
def load(fh, single=False)
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`)
7.499639
8.128758
0.922606
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
def loads(s, single=False)
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`)
5.033101
4.822917
1.04358
drv = self.get('derivation') if drv is not None: if isinstance(drv, dict): drv = Derivation.from_dict(drv) elif isinstance(drv, stringtypes): drv = Derivation.from_string(drv) return drv
def derivation(self)
Deserialize and return a Derivation object for UDF- or JSON-formatted derivation data; otherwise return the original string.
2.831529
2.580396
1.097324
tree = self.get('tree') if isinstance(tree, stringtypes): tree = SExpr.parse(tree).data elif tree is None: drv = self.get('derivation') if isinstance(drv, dict) and 'label' in drv: def _extract_tree(d): t = [d.get('...
def tree(self)
Deserialize and return a labeled syntax tree. The tree data may be a standalone datum, or embedded in the derivation.
3.978324
3.568541
1.114832
mrs = self.get('mrs') if mrs is not None: if isinstance(mrs, dict): mrs = Mrs.from_dict(mrs) elif isinstance(mrs, stringtypes): mrs = simplemrs.loads_one(mrs) return mrs
def mrs(self)
Deserialize and return an Mrs object for simplemrs or JSON-formatted MRS data; otherwise return the original string.
3.489209
2.75577
1.266147
_eds = self.get('eds') if _eds is not None: if isinstance(_eds, dict): _eds = eds.Eds.from_dict(_eds) elif isinstance(_eds, stringtypes): _eds = eds.loads_one(_eds) return _eds
def eds(self)
Deserialize and return an Eds object for native- or JSON-formatted EDS data; otherwise return the original string.
3.938698
3.480987
1.131489
dmrs = self.get('dmrs') if dmrs is not None: if isinstance(dmrs, dict): dmrs = Dmrs.from_dict(dmrs) return dmrs
def dmrs(self)
Deserialize and return a Dmrs object for JSON-formatted DMRS data; otherwise return the original string.
2.921892
2.476629
1.179786
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_list(toks) return toks
def tokens(self, tokenset='internal')
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: `...
3.850435
3.005001
1.281343
inserts = [] parse = {} # custom remapping, cleanup, and filling in holes parse['i-id'] = response.get('keys', {}).get('i-id', -1) self._parse_id = max(self._parse_id + 1, parse['i-id']) parse['parse-id'] = self._parse_id parse['run-id'] = response.get('...
def map(self, response)
Process *response* and return a list of (table, rowdata) tuples.
3.085253
3.016874
1.022666
inserts = [] last_run = self._runs[self._last_run_id] if 'end' not in last_run: last_run['end'] = datetime.now() for run_id in sorted(self._runs): run = self._runs[run_id] d = {'run-id': run.get('run-id', -1)} for key in self._ru...
def cleanup(self)
Return aggregated (table, rowdata) tuples and clear the state.
3.436268
3.240034
1.060566
array = super(GameHighScore, self).to_array() array['position'] = int(self.position) # type int array['user'] = self.user.to_array() # type User array['score'] = int(self.score) # type int return array
def to_array(self)
Serializes this GameHighScore to a dictionary. :return: dictionary representation of this object. :rtype: dict
3.242249
2.625489
1.234913
if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") from pytgbot.api_types.receivable.peer import User data = {} data['position'] = int(array.get('position')) data['user'] = User.from...
def from_array(array)
Deserialize a new GameHighScore from a given dictionary. :return: new GameHighScore instance. :rtype: GameHighScore
3.293889
2.785353
1.182575
def link_label(link): return '{}/{}'.format(link.rargname or '', link.post) def label_edge(link): if link.post == H_POST and link.rargname == RSTR_ROLE: return 'rstr' elif link.post == EQ_POST: return 'eq' else: return 'arg' if isins...
def dmrs_tikz_dependency(xs, **kwargs)
Return a LaTeX document with each Xmrs in *xs* rendered as DMRSs. DMRSs use the `tikz-dependency` package for visualization.
5.05501
4.819216
1.048928
@wraps(f) def wrapper(*args, **kwargs): if 'value' in kwargs: val = kwargs['value'] del kwargs['value'] _f = f(*args, **kwargs) def valued_f(*args, **kwargs): result = _f(*args, **kwargs) s, obj, span = result ...
def valuemap(f)
Decorator to help PEG functions handle value conversions.
3.034737
2.776646
1.092951
xlen = len(x) msg = 'Expected: "{}"'.format(x) def match_literal(s, grm=None, pos=0): if s[:xlen] == x: return PegreResult(s[xlen:], x, (pos, pos+xlen)) raise PegreError(msg, pos) return match_literal
def literal(x)
Create a PEG function to consume a literal.
5.770205
5.16227
1.117765
if isinstance(r, stringtypes): p = re.compile(r) else: p = r msg = 'Expected to match: {}'.format(p.pattern) def match_regex(s, grm=None, pos=0): m = p.match(s) if m is not None: start, end = m.span() data = m.groupdict() if p.groupindex else ...
def regex(r)
Create a PEG function to match a regular expression.
4.131106
3.792467
1.089293
def match_nonterminal(s, grm=None, pos=0): if grm is None: grm = {} expr = grm[n] return expr(s, grm, pos) return match_nonterminal
def nonterminal(n)
Create a PEG function to match a nonterminal.
4.600618
4.1456
1.109759
def match_and_next(s, grm=None, pos=0): try: e(s, grm, pos) except PegreError as ex: raise PegreError('Positive lookahead failed', pos) else: return PegreResult(s, Ignore, (pos, pos)) return match_and_next
def and_next(e)
Create a PEG function for positive lookahead.
8.543658
7.315938
1.167815
def match_not_next(s, grm=None, pos=0): try: e(s, grm, pos) except PegreError as ex: return PegreResult(s, Ignore, (pos, pos)) else: raise PegreError('Negative lookahead failed', pos) return match_not_next
def not_next(e)
Create a PEG function for negative lookahead.
7.552296
6.678859
1.130776
def match_sequence(s, grm=None, pos=0): data = [] start = pos for e in es: s, obj, span = e(s, grm, pos) pos = span[1] if obj is not Ignore: data.append(obj) return PegreResult(s, data, (start, pos)) return match_sequence
def sequence(*es)
Create a PEG function to match a sequence.
5.53686
5.001789
1.106976
msg = 'Expected one of: {}'.format(', '.join(map(repr, es))) def match_choice(s, grm=None, pos=0): errs = [] for e in es: try: return e(s, grm, pos) except PegreError as ex: errs.append((ex.message, ex.position)) if errs: ...
def choice(*es)
Create a PEG function to match an ordered choice.
4.411441
3.654927
1.206985
def match_optional(s, grm=None, pos=0): try: return e(s, grm, pos) except PegreError: return PegreResult(s, default, (pos, pos)) return match_optional
def optional(e, default=Ignore)
Create a PEG function to optionally match an expression.
6.753987
6.260562
1.078815
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 else [obj] except PegreError:...
def zero_or_more(e, delimiter=None)
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.
2.706764
2.761013
0.980352
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] data = [] if obj is Ignore else [o...
def one_or_more(e, delimiter=None)
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.
2.939436
3.017742
0.974051
# pump object to it's location with dummy nodes while location: axis = location.pop() obj = XmrsPathNode(None, None, links={axis: obj}) if base is None: return obj _merge(base, obj) # if isinstance(base, XmrsPath): # base.calculate_metrics() return base
def merge(base, obj, location=None)
merge is like XmrsPathNode.update() except it raises errors on unequal non-None values.
12.032069
9.096674
1.322689
links = node.links o_links = node._overlapping_links overlap = {ax2 for ax in links for ax2 in o_links.get(ax, [])} axes = [] for axis in sorted(links.keys(), key=sort_key): if axis in overlap: continue tgt = links[axis] if axis in o_links: s, e = axis[0], ax...
def _prepare_axes(node, sort_key)
Sort axes and combine those that point to the same target and go in the same direction.
4.428381
4.296818
1.030619
try: val = self[key] except KeyError: val = default return val
def get(self, key, default=None)
Return the value for *key* if it exists, otherwise *default*.
3.499363
3.122795
1.120587
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] if isinstance(val, FeatureStruc...
def features(self, expand=False)
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 ...>)] >>...
2.89963
2.928382
0.990181
xs = [] for parent in self._hier[typename][0]: xs.append(parent) xs.extend(self.ancestors(parent)) return xs
def ancestors(self, typename)
Return the ancestor types of *typename*.
4.155352
3.975871
1.045143
xs = [] for child in self._hier[typename][1]: xs.append(child) xs.extend(self.descendants(child)) return xs
def descendants(self, typename)
Return the descendant types of *typename*.
4.086132
3.97675
1.027505
return a == b or b in self.descendants(a)
def subsumes(self, a, b)
Return `True` if type *a* subsumes type *b*.
8.982337
7.845657
1.14488
return len(set([a] + self.descendants(a)) .intersection([b] + self.descendants(b))) > 0
def compatible(self, a, b)
Return `True` if type *a* is compatible with type *b*.
5.657367
5.232806
1.081134
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)
def isomorphic(q, g, check_varprops=True)
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: ...
3.893921
4.406466
0.883684
# first some quick checks if len(q.eps()) != len(g.eps()): return False if len(q.variables()) != len(g.variables()): return False #if len(a.hcons()) != len(b.hcons()): return False try: next(_isomorphisms(q, g, check_varprops=check_varprops)) return True except StopIteration...
def _turbo_isomorphic(q, g, check_varprops=True)
Query Xmrs q is isomorphic to given Xmrs g if there exists an isomorphism (bijection of eps and vars) from q to g.
3.692087
3.074826
1.200747
# convert MRSs to be more graph-like, and add some indices qig = _IsoGraph(q, varprops=check_varprops) # qig = q isograph gig = _IsoGraph(g, varprops=check_varprops) # gig = q isograph # qsigs, qsigidx = _isomorphism_sigs(q, check_varprops) # gsigs, gsigidx = _isomorphism_sigs(g, check_varpro...
def _isomorphisms(q, g, check_varprops=True)
Inspired by Turbo_ISO: http://dl.acm.org/citation.cfm?id=2465300
5.692785
5.657596
1.00622
qadj = qgraph.adj adjsets = lambda x: set(chain.from_iterable(qadj[x].values())) t = ([q_s], []) # (NEC_set, children) visited = {q_s} vcur, vnext = [t], [] while vcur: for (nec, children) in vcur: c = defaultdict(list) for u in nec: for sig,...
def _isomorphism_rewrite_to_NECtree(q_s, qgraph)
Neighborhood Equivalence Class tree (see Turbo_ISO paper)
5.044533
4.97885
1.013192
# first some quick checks a_var_refs = sorted(len(vd['refs']) for vd in a._vars.values()) b_var_refs = sorted(len(vd['refs']) for vd in b._vars.values()) if a_var_refs != b_var_refs: return False print() # these signature: [node] indices are meant to avoid unnecessary # compari...
def _node_isomorphic(a, b, check_varprops=True)
Two Xmrs objects are isomorphic if they have the same structure as determined by variable linkages between preds.
3.956501
3.938488
1.004574
# first some quick checks if len(a.eps()) != len(b.eps()): return False if len(a.variables()) != len(b.variables()): return False #if len(a.hcons()) != len(b.hcons()): return False # pre-populate varmap; first top variables varmap = {} for pair in [(a.top, b.top), (a.index, b.index), (...
def _var_isomorphic(a, b, check_varprops=True)
Two Xmrs objects are isomorphic if they have the same structure as determined by variable linkages between preds.
3.510091
3.472946
1.010695
gold_remaining = list(goldbag) test_unique = [] shared = [] for test in testbag: gold_match = None for gold in gold_remaining: if isomorphic(test, gold): gold_match = gold break if gold_match is not None: gold_remaining...
def compare_bags(testbag, goldbag, count_only=True)
Compare two bags of Xmrs objects, returning a triple of (unique in test, shared, unique in gold). Args: testbag: An iterable of Xmrs objects to test. goldbag: An iterable of Xmrs objects to compare against. count_only: If True, the returned triple will only have the counts o...
2.228411
1.939159
1.149164
queryobj = _parse_query(query) if queryobj['querytype'] in ('select', 'retrieve'): return _select( queryobj['projection'], queryobj['tables'], queryobj['where'], ts, mode=kwargs.get('mode', 'list'), cast=kwargs.get('cast', Tru...
def query(query, ts, **kwargs)
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:...
6.704148
6.613562
1.013697
queryobj = _parse_select(query) return _select( queryobj['projection'], queryobj['tables'], queryobj['where'], ts, mode, cast)
def select(query, ts, mode='list', cast=True)
Perform the TSQL selection query *query* on testsuite *ts*. Note: The `select`/`retrieve` part of the query is not included. Args: query (str): TSQL select query ts (:class:`delphin.itsdb.TestSuite`): testsuite to query over mode (str): how to return the results (see :func:...
4.893757
7.255731
0.674468
s += '.' # make sure there's a terminator to know when to stop parsing lines = enumerate(s.splitlines(), 1) lineno = pos = 0 try: for lineno, line in lines: matches = _tsql_lex_re.finditer(line) for m in matches: gid = m.lastindex if ...
def _lex(s)
Lex the input string according to _tsql_lex_re. Yields (gid, token, line_number)
4.64128
3.817024
1.215942
assert_type_or_raise(offset, None, int, parameter_name="offset") assert_type_or_raise(limit, None, int, parameter_name="limit") assert_type_or_raise(timeout, None, int, parameter_name="timeout") assert_type_or_raise(allowed_updates, None, list, paramet...
def get_updates(self, offset=None, limit=None, timeout=None, allowed_updates=None)
Use this method to receive incoming updates using long polling (wiki). An Array of Update objects is returned. Notes1. This method will not work if an outgoing webhook is set up.2. In order to avoid getting duplicate updates, recalculate offset after each server response. https://core.telegram.org/bo...
2.502429
2.392623
1.045893
from pytgbot.api_types.sendable.files import InputFile assert_type_or_raise(url, unicode_type, parameter_name="url") assert_type_or_raise(certificate, None, InputFile, parameter_name="certificate") assert_type_or_raise(max_connections, None, int, param...
def set_webhook(self, url, certificate=None, max_connections=None, allowed_updates=None)
Use this method to specify a url and receive incoming updates via an outgoing webhook. Whenever there is an update for the bot, we will send an HTTPS POST request to the specified url, containing a JSON-serialized Update. In case of an unsuccessful request, we will give up after a reasonable amount of attempts. Returns...
2.756443
2.571871
1.071766
result = self.do("deleteWebhook", ) if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) try: return from_array_list(bool, result, list_level=0, is_builtin=True) except TgApiParseException: ...
def delete_webhook(self, )
Use this method to remove webhook integration if you decide to switch back to getUpdates. Returns True on success. Requires no parameters. https://core.telegram.org/bots/api#deletewebhook Returns: :return: Returns True on success :rtype: bool
6.736531
6.152714
1.094888
result = self.do("getWebhookInfo", ) if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) from pytgbot.api_types.receivable.updates import WebhookInfo try: return WebhookInfo.from_array(resul...
def get_webhook_info(self, )
Use this method to get current webhook status. Requires no parameters. On success, returns a WebhookInfo object. If the bot is using getUpdates, will return an object with the url field empty. https://core.telegram.org/bots/api#getwebhookinfo Returns: :return: On success, returns a W...
4.089351
4.018221
1.017702
from pytgbot.api_types.sendable.files import InputFile from pytgbot.api_types.sendable.reply_markup import ForceReply from pytgbot.api_types.sendable.reply_markup import InlineKeyboardMarkup from pytgbot.api_types.sendable.reply_markup import ReplyKeyboardMarkup from pyt...
def send_photo(self, chat_id, photo, caption=None, parse_mode=None, disable_notification=None, reply_to_message_id=None, reply_markup=None)
Use this method to send photos. On success, the sent Message is returned. https://core.telegram.org/bots/api#sendphoto Parameters: :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) :type chat_id: ...
1.664108
1.609398
1.033994
from pytgbot.api_types.sendable.input_media import InputMediaPhoto from pytgbot.api_types.sendable.input_media import InputMediaVideo assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id") assert_type_or_raise(media, (list, list), paramete...
def send_media_group(self, chat_id, media, disable_notification=None, reply_to_message_id=None)
Use this method to send a group of photos or videos as an album. On success, an array of the sent Messages is returned. https://core.telegram.org/bots/api#sendmediagroup Parameters: :param chat_id: Unique identifier for the target chat or username of the target channel (in th...
2.255271
2.169268
1.039646
from pytgbot.api_types.sendable.reply_markup import ForceReply from pytgbot.api_types.sendable.reply_markup import InlineKeyboardMarkup from pytgbot.api_types.sendable.reply_markup import ReplyKeyboardMarkup from pytgbot.api_types.sendable.reply_markup import ReplyKeyboardRemove...
def send_location(self, chat_id, latitude, longitude, live_period=None, disable_notification=None, reply_to_message_id=None, reply_markup=None)
Use this method to send point on the map. On success, the sent Message is returned. https://core.telegram.org/bots/api#sendlocation Parameters: :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) :ty...
1.707387
1.656352
1.030812
from pytgbot.api_types.sendable.reply_markup import ForceReply from pytgbot.api_types.sendable.reply_markup import InlineKeyboardMarkup from pytgbot.api_types.sendable.reply_markup import ReplyKeyboardMarkup from pytgbot.api_types.sendable.reply_markup import ReplyKeyboardRemove...
def send_contact(self, chat_id, phone_number, first_name, last_name=None, vcard=None, disable_notification=None, reply_to_message_id=None, reply_markup=None)
Use this method to send phone contacts. On success, the sent Message is returned. https://core.telegram.org/bots/api#sendcontact Parameters: :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) :type ...
1.639756
1.588035
1.03257
assert_type_or_raise(user_id, int, parameter_name="user_id") assert_type_or_raise(offset, None, int, parameter_name="offset") assert_type_or_raise(limit, None, int, parameter_name="limit") result = self.do("getUserProfilePhotos", user_id=user_id, offse...
def get_user_profile_photos(self, user_id, offset=None, limit=None)
Use this method to get a list of profile pictures for a user. Returns a UserProfilePhotos object. https://core.telegram.org/bots/api#getuserprofilephotos Parameters: :param user_id: Unique identifier of the target user :type user_id: int Opt...
2.960453
2.669351
1.109053
assert_type_or_raise(file_id, unicode_type, parameter_name="file_id") result = self.do("getFile", file_id=file_id) if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) from pytgbot.api_types.receivable.media imp...
def get_file(self, file_id)
Use this method to get basic info about a file and prepare it for downloading. For the moment, bots can download files of up to 20MB in size. On success, a File object is returned. The file can then be downloaded via the link https://api.telegram.org/file/bot<token>/<file_path>, where <file_path> is taken from the resp...
3.773364
3.639001
1.036923
assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id") assert_type_or_raise(user_id, int, parameter_name="user_id") assert_type_or_raise(until_date, None, int, parameter_name="until_date") assert_type_or_raise(can_send_messages, N...
def restrict_chat_member(self, chat_id, user_id, until_date=None, can_send_messages=None, can_send_media_messages=None, can_send_other_messages=None, can_add_web_page_previews=None)
Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate admin rights. Pass True for all boolean parameters to lift restrictions from a user. Returns True on success. https://core.telegram.org/bots/api#restrictchatmemb...
1.868462
1.762245
1.060273
from pytgbot.api_types.sendable.files import InputFile assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id") assert_type_or_raise(photo, InputFile, parameter_name="photo") result = self.do("setChatPhoto", chat_id=chat_id, photo=p...
def set_chat_photo(self, chat_id, photo)
Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success. Note: In regular groups (non-supergroups), this method will only work if the ‘A...
3.608132
3.20537
1.125652