_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q1800
reply
train
def reply(): """Fetch a reply from RiveScript. Parameters (JSON): * username * message * vars """ params = request.json if not params: return jsonify({ "status": "error", "error": "Request must be of the application/json type!", }) username = params.get("username") message = params.get("message") uservars = params.get("vars", dict()) # Make sure the required params are present. if username is None or message is None: return jsonify({ "status": "error", "error": "username and message are required keys", }) # Copy and
python
{ "resource": "" }
q1801
index
train
def index(path=None): """On all other routes, just return an example `curl` command.""" payload = { "username": "soandso", "message": "Hello bot", "vars": { "name": "Soandso", } }
python
{ "resource": "" }
q1802
RedisSessionManager._key
train
def _key(self, username, frozen=False): """Translate a username into a key for Redis.""" if frozen:
python
{ "resource": "" }
q1803
RedisSessionManager._get_user
train
def _get_user(self, username): """Custom helper method to retrieve a user's data from Redis.""" data = self.client.get(self._key(username))
python
{ "resource": "" }
q1804
sort_trigger_set
train
def sort_trigger_set(triggers, exclude_previous=True, say=None): """Sort a group of triggers in optimal sorting order. The optimal sorting order is, briefly: * Atomic triggers (containing nothing but plain words and alternation groups) are on top, with triggers containing the most words coming first. Triggers with equal word counts are sorted by length, and then alphabetically if they have the same length. * Triggers containing optionals are sorted next, by word count like atomic triggers. * Triggers containing wildcards are next, with ``_`` (alphabetic) wildcards on top, then ``#`` (numeric) and finally ``*``. * At the bottom of the sorted list are triggers consisting of only a single wildcard, in the order: ``_``, ``#``, ``*``. Triggers that have ``{weight}`` tags are grouped together by weight value and sorted amongst themselves. Higher weighted groups are then ordered before lower weighted groups regardless of the normal sorting algorithm. Triggers that come from topics which inherit other topics are also sorted with higher priority than triggers from the inherited topics. Arguments: triggers ([]str): Array of triggers to sort. exclude_previous (bool): Create a sort buffer for 'previous' triggers. say (function): A reference to ``RiveScript._say()`` or provide your own function. """ if say is None: say = lambda x: x # KEEP IN MIND: the `triggers` array is composed of array elements of the form # ["trigger text", pointer to trigger data] # So this code will use e.g. `trig[0]` when referring to the trigger text. # Create a list of trigger objects map. trigger_object_list = [] for index, trig in enumerate(triggers): if exclude_previous and trig[1]["previous"]: continue pattern = trig[0] # Extract only the text of the trigger, with possible tag of inherit # See if it has a weight tag match, weight = re.search(RE.weight, trig[0]), 0 if match: # Value of math is not None if there is a match. weight = int(match.group(1)) # Get the weight from the tag ``{weight}`` # See if it has an inherits tag. match
python
{ "resource": "" }
q1805
sort_list
train
def sort_list(items): """Sort a simple list by number of words and length.""" # Track by number of words. track = {} def by_length(word1, word2): return len(word2) - len(word1) # Loop through each item. for item in items:
python
{ "resource": "" }
q1806
RiveScript.load_directory
train
def load_directory(self, directory, ext=None): """Load RiveScript documents from a directory. :param str directory: The directory of RiveScript documents to load replies from. :param []str ext: List of file extensions to consider as RiveScript documents. The default is ``[".rive", ".rs"]``. """ self._say("Loading from directory: " + directory) if ext is None: # Use the default extensions - .rive is preferable. ext = ['.rive', '.rs'] elif type(ext) == str: # Backwards compatibility for ext being a string value.
python
{ "resource": "" }
q1807
RiveScript.load_file
train
def load_file(self, filename): """Load and parse a RiveScript document. :param str filename: The path to a RiveScript file. """ self._say("Loading file: " + filename) fh = codecs.open(filename, 'r', 'utf-8') lines = fh.readlines()
python
{ "resource": "" }
q1808
RiveScript.stream
train
def stream(self, code): """Stream in RiveScript source code dynamically. :param code: Either a string containing RiveScript code or an array of lines of RiveScript code. """
python
{ "resource": "" }
q1809
RiveScript._parse
train
def _parse(self, fname, code): """Parse RiveScript code into memory. :param str fname: The arbitrary file name used for syntax reporting. :param []str code: Lines of RiveScript source code to parse. """ # Get the "abstract syntax tree" ast = self._parser.parse(fname, code) # Get all of the "begin" type variables: global, var, sub, person, ... for kind, data in ast["begin"].items(): internal = getattr(self, "_" + kind) # The internal name for this attribute for name, value in data.items(): if value == "<undef>": del internal[name] else: internal[name] = value # Precompile substitutions. if kind in ["sub", "person"]: self._precompile_substitution(kind, name) # Let the scripts set the debug mode and other special globals. if self._global.get("debug"): self._debug = str(self._global["debug"]).lower() == "true" if self._global.get("depth"): self._depth = int(self._global["depth"])
python
{ "resource": "" }
q1810
RiveScript.deparse
train
def deparse(self): """Dump the in-memory RiveScript brain as a Python data structure. This would be useful, for example, to develop a user interface for editing RiveScript replies without having to edit the RiveScript source code directly. :return dict: JSON-serializable Python data structure containing the contents of all RiveScript replies currently loaded in memory. """ # Data to return. result = { "begin": { "global": {}, "var": {}, "sub": {}, "person": {}, "array": {}, "triggers": [], }, "topics": {}, } # Populate the config fields. if self._debug: result["begin"]["global"]["debug"] = self._debug if self._depth != 50: result["begin"]["global"]["depth"] = 50 # Definitions result["begin"]["var"] = self._var.copy() result["begin"]["sub"] = self._sub.copy() result["begin"]["person"] = self._person.copy() result["begin"]["array"] = self._array.copy() result["begin"]["global"].update(self._global.copy()) # Topic Triggers. for topic in self._topics: dest = None # Where to place the topic info
python
{ "resource": "" }
q1811
RiveScript.write
train
def write(self, fh, deparsed=None): """Write the currently parsed RiveScript data into a file. Pass either a file name (string) or a file handle object. This uses ``deparse()`` to dump a representation of the loaded data and writes it to the destination file. If you provide your own data as the ``deparsed`` argument, it will use that data instead of calling ``deparse()`` itself. This way you can use ``deparse()``, edit the data, and use that to write the RiveScript document (for example, to be used by a user interface for editing RiveScript without writing the code directly). Parameters: fh (str or file): a string or a file-like object. deparsed (dict): a data structure in the same format as what ``deparse()`` returns. If not passed, this value will come from the current in-memory data from ``deparse()``. """ # Passed a string instead of a file handle? if type(fh) is str: fh = codecs.open(fh, "w", "utf-8") # Deparse the loaded data. if deparsed is None: deparsed = self.deparse() # Start at the beginning. fh.write("// Written by rivescript.deparse()\n") fh.write("! version = 2.0\n\n") # Variables of all sorts! for kind in ["global", "var", "sub", "person", "array"]: if len(deparsed["begin"][kind].keys()) == 0: continue for var in sorted(deparsed["begin"][kind].keys()): # Array types need to be separated by either spaces or pipes.
python
{ "resource": "" }
q1812
RiveScript._write_triggers
train
def _write_triggers(self, fh, triggers, indent=""): """Write triggers to a file handle. Parameters: fh (file): file object. triggers (list): list of triggers to write. indent (str): indentation for each line. """ for trig in triggers: fh.write(indent + "+ " + self._write_wrapped(trig["trigger"], indent=indent) + "\n") d = trig if d.get("previous"): fh.write(indent + "% " + self._write_wrapped(d["previous"], indent=indent) + "\n") for cond in
python
{ "resource": "" }
q1813
RiveScript._write_wrapped
train
def _write_wrapped(self, line, sep=" ", indent="", width=78): """Word-wrap a line of RiveScript code for being written to a file. :param str line: The original line of text to word-wrap. :param str sep: The word separator. :param str indent: The indentation to use (as a set of spaces). :param int width: The character width to constrain each line to. :return str: The reformatted line(s).""" words = line.split(sep) lines = [] line = "" buf = [] while len(words): buf.append(words.pop(0)) line = sep.join(buf) if len(line) > width: # Need to word wrap! words.insert(0, buf.pop()) # Undo
python
{ "resource": "" }
q1814
RiveScript.sort_replies
train
def sort_replies(self, thats=False): """Sort the loaded triggers in memory. After you have finished loading your RiveScript code, call this method to populate the various internal sort buffers. This is absolutely necessary for reply matching to work efficiently! """ # (Re)initialize the sort cache. self._sorted["topics"] = {} self._sorted["thats"] = {} self._say("Sorting triggers...") # Loop through all the topics. for topic in self._topics.keys(): self._say("Analyzing topic " + topic) # Collect a list of all the triggers we're going to
python
{ "resource": "" }
q1815
RiveScript.set_handler
train
def set_handler(self, language, obj): """Define a custom language handler for RiveScript objects. Pass in a ``None`` value for the object to delete an existing handler (for example, to prevent Python code from being able to be run by default). Look in the ``eg`` folder of the rivescript-python distribution for an example script that sets up a JavaScript language handler. :param str language: The lowercased name of the programming language. Examples: python, javascript, perl :param class obj: An instance of an implementation class object. It should provide the following interface:: class MyObjectHandler: def __init__(self): pass def load(self, name, code): # name = the name of the object from the RiveScript code
python
{ "resource": "" }
q1816
RiveScript.set_subroutine
train
def set_subroutine(self, name, code): """Define a Python object from your program. This is equivalent to having an object defined in the RiveScript code, except your Python code is defining it instead. :param str name: The name of the object macro. :param def code: A Python function with a method signature of ``(rs, args)`` This method is only available if there is a Python handler set up (which there is by default, unless you've called ``set_handler("python", None)``). """
python
{ "resource": "" }
q1817
RiveScript.set_global
train
def set_global(self, name, value): """Set a global variable. Equivalent to ``! global`` in RiveScript code. :param str name: The name of the variable to set. :param str value: The value of the variable. Set this to ``None`` to delete the variable.
python
{ "resource": "" }
q1818
RiveScript.set_variable
train
def set_variable(self, name, value): """Set a bot variable. Equivalent to ``! var`` in RiveScript code. :param str name: The name of the variable to set. :param str value: The value of the variable. Set this to ``None`` to delete the variable.
python
{ "resource": "" }
q1819
RiveScript.set_substitution
train
def set_substitution(self, what, rep): """Set a substitution. Equivalent to ``! sub`` in RiveScript code. :param str what: The original text to replace. :param str rep: The text to replace it with. Set this to ``None`` to delete the substitution.
python
{ "resource": "" }
q1820
RiveScript.set_person
train
def set_person(self, what, rep): """Set a person substitution. Equivalent to ``! person`` in RiveScript code. :param str what: The original text to replace. :param str rep: The text to replace it with. Set this to ``None`` to delete the substitution.
python
{ "resource": "" }
q1821
RiveScript.set_uservar
train
def set_uservar(self, user, name, value): """Set a variable for a user. This is like the ``<set>`` tag in RiveScript code. :param str user: The user ID to set a variable for.
python
{ "resource": "" }
q1822
RiveScript.set_uservars
train
def set_uservars(self, user, data=None): """Set many variables for a user, or set many variables for many users. This function can be called in two ways:: # Set a dict of variables for a single user. rs.set_uservars(username, vars) # Set a nested dict of variables for many users. rs.set_uservars(many_vars) In the first syntax, ``vars`` is a simple dict of key/value string pairs. In the second syntax, ``many_vars`` is a structure like this:: { "username1": { "key": "value", }, "username2": { "key": "value", }, } This way you can export *all* user variables via ``get_uservars()`` and then re-import them all at once, instead of setting them once per user. :param optional str user: The user ID to set many variables for. Skip this parameter to set many variables for many users instead. :param dict data: The dictionary of key/value pairs for user variables,
python
{ "resource": "" }
q1823
RiveScript.get_uservar
train
def get_uservar(self, user, name): """Get a variable about a user. :param str user: The user ID to look up a variable for. :param str name: The name of the variable to get. :return: The user variable, or ``None`` or ``"undefined"``: * If the user has no data at all,
python
{ "resource": "" }
q1824
RiveScript.trigger_info
train
def trigger_info(self, trigger=None, dump=False): """Get information about a trigger. Pass in a raw trigger to find out what file name and line number it appeared at. This is useful for e.g. tracking down the location of the trigger last matched by the user via ``last_match()``. Returns a list of matching triggers, containing their topics, filenames and line numbers. Returns ``None`` if there weren't any matches found. The keys in the trigger info is as follows: * ``category``: Either 'topic' (for normal) or 'thats' (for %Previous triggers) * ``topic``: The topic name * ``trigger``: The raw trigger text * ``filename``: The filename the trigger was found in. * ``lineno``: The line number the trigger was found on. Pass in a true value for ``dump``, and the entire syntax tracking tree is returned. :param str trigger: The raw trigger text to look up. :param bool dump: Whether to dump the entire syntax tracking tree. :return: A list of matching triggers or ``None`` if no matches. """ if dump: return self._syntax
python
{ "resource": "" }
q1825
RiveScript.current_user
train
def current_user(self): """Retrieve the user ID of the current user talking to your bot. This is mostly useful inside of a Python object macro to get the user ID of the person who caused the object macro to be invoked (i.e. to set a variable for that user from within the
python
{ "resource": "" }
q1826
RiveScript.reply
train
def reply(self, user, msg, errors_as_replies=True): """Fetch a reply from the RiveScript brain. Arguments: user (str): A unique user ID for the person requesting a reply. This could be e.g. a screen name or nickname. It's used internally to store user variables (including topic and history), so if your bot has multiple users each one should have a unique ID. msg (str): The user's message. This is allowed to contain punctuation and such, but any extraneous data such as HTML tags should be removed in advance. errors_as_replies (bool): When errors are encountered (such as a
python
{ "resource": "" }
q1827
RiveScript._precompile_substitution
train
def _precompile_substitution(self, kind, pattern): """Pre-compile the regexp for a substitution pattern. This will speed up the substitutions that happen at the beginning of the reply fetching process. With the default brain, this took the time for _substitute down from 0.08s to 0.02s :param str kind: One of ``sub``, ``person``. :param str pattern: The substitution pattern. """ if pattern not in self._regexc[kind]: qm = re.escape(pattern) self._regexc[kind][pattern] = {
python
{ "resource": "" }
q1828
RiveScript._precompile_regexp
train
def _precompile_regexp(self, trigger): """Precompile the regex for most triggers. If the trigger is non-atomic, and doesn't include dynamic tags like ``<bot>``, ``<get>``, ``<input>/<reply>`` or arrays, it can be precompiled and save time when matching. :param str trigger: The trigger text to attempt to precompile. """ if utils.is_atomic(trigger): return # Don't need a regexp for atomic triggers. # Check for dynamic tags.
python
{ "resource": "" }
q1829
RiveScript._dump
train
def _dump(self): """For debugging, dump the entire data structure.""" pp = pprint.PrettyPrinter(indent=4) print("=== Variables ===") print("-- Globals --") pp.pprint(self._global) print("-- Bot vars --") pp.pprint(self._var) print("-- Substitutions --") pp.pprint(self._sub) print("-- Person Substitutions --") pp.pprint(self._person) print("-- Arrays --") pp.pprint(self._array) print("=== Topic Structure ===") pp.pprint(self._topics) print("=== %Previous Structure ===")
python
{ "resource": "" }
q1830
dump_data
train
def dump_data(request): """Exports data from whole project. """ # Try to grab app_label data app_label = request.GET.get('app_label', []) if app_label: app_label = app_label.split(',')
python
{ "resource": "" }
q1831
dump_model_data
train
def dump_model_data(request, app_label, model_label): """Exports data from a model. """ return dump_to_response(request, '%s.%s' % (app_label,
python
{ "resource": "" }
q1832
timesince
train
def timesince(d, now): """ Taken from django.utils.timesince and modified to simpler requirements. Takes two datetime objects and returns the time between d and now as a nicely formatted string, e.g. "10 minutes". If d occurs after now, then "0 minutes" is returned. Units used are years, months, weeks, days, hours, and minutes. Seconds and microseconds are ignored. Up to two adjacent units will be displayed. For example, "2 weeks, 3 days" and "1 year, 3 months" are possible outputs, but "2 weeks, 3 hours" and "1 year, 5 days" are not. Adapted from http://web.archive.org/web/20060617175230/\ http://blog.natbat.co.uk/archive/2003/Jun/14/time_since """ def pluralize(a, b): def inner(n): if n == 1: return a % n return b % n return inner def ugettext(s): return s chunks = ( (60 * 60 * 24 * 365, pluralize('%d year', '%d years')), (60 * 60 * 24 * 30, pluralize('%d month', '%d months')), (60 * 60 * 24 * 7, pluralize('%d week', '%d weeks')), (60 * 60 * 24, pluralize('%d day', '%d days')), (60 * 60, pluralize('%d hour', '%d hours')), (60, pluralize('%d minute', '%d minutes')), (0, pluralize('%d second', '%d seconds')) ) # Convert datetime.date to datetime.datetime for comparison. if not isinstance(d, datetime.datetime): d = datetime.datetime(d.year, d.month, d.day) if now and not isinstance(now, datetime.datetime): now = datetime.datetime(now.year, now.month,
python
{ "resource": "" }
q1833
respond_to_SIGHUP
train
def respond_to_SIGHUP(signal_number, frame, logger=None): """raise the KeyboardInterrupt which will cause the app to effectively shutdown, closing all it resources. Then, because it sets 'restart' to True, the app will reread all the configuration information, rebuild
python
{ "resource": "" }
q1834
TransactionExecutorWithInfiniteBackoff.backoff_generator
train
def backoff_generator(self): """Generate a series of integers used for the length of the sleep between retries. It produces after exhausting the list, it repeats the last value from the list forever. This generator will never raise the StopIteration exception."""
python
{ "resource": "" }
q1835
as_backfill_cron_app
train
def as_backfill_cron_app(cls): """a class decorator for Crontabber Apps. This decorator embues a CronApp with the parts necessary to be a backfill CronApp. It adds a main method that forces the base class to use a value of False for 'once'.
python
{ "resource": "" }
q1836
with_resource_connection_as_argument
train
def with_resource_connection_as_argument(resource_name): """a class decorator for Crontabber Apps. This decorator will a class a _run_proxy method that passes a databsase connection as a context manager into the CronApp's run method. The connection will automatically be closed when the ConApp's run method ends. In order for this dectorator to function properly, it must be used in conjunction with previous dectorator, "with_transactional_resource" or
python
{ "resource": "" }
q1837
with_single_transaction
train
def with_single_transaction(resource_name): """a class decorator for Crontabber Apps. This decorator will give a class a _run_proxy method that passes a databsase connection as a context manager into the CronApp's 'run' method. The run method may then use the connection at will knowing that after if 'run' exits normally, the connection will automatically be commited. Any abnormal exit from 'run' will result in the connnection being rolledback. In order for this dectorator to function properly, it must be used in conjunction with previous dectorator, "with_transactional_resource" or equivalent.
python
{ "resource": "" }
q1838
with_subprocess
train
def with_subprocess(cls): """a class decorator for Crontabber Apps. This decorator gives the CronApp a _run_proxy method that will execute the cron app as a single PG transaction. Commit and Rollback are automatic. The cron app should do no transaction management of its own. The cron app should be short so that the transaction is not held open too long. """ def run_process(self, command, input=None): """ Run the command and return a tuple of three things. 1. exit code - an integer number 2. stdout - all output that was sent to stdout 2. stderr - all output
python
{ "resource": "" }
q1839
JobStateDatabase.keys
train
def keys(self): """return a list of all app_names""" keys =
python
{ "resource": "" }
q1840
JobStateDatabase.items
train
def items(self): """return all the app_names and their values as tuples""" sql = """ SELECT app_name, next_run, first_run, last_run, last_success, depends_on, error_count, last_error FROM crontabber""" columns = ( 'app_name', 'next_run', 'first_run', 'last_run', 'last_success',
python
{ "resource": "" }
q1841
JobStateDatabase.values
train
def values(self): """return a list of all state values""" values = [] for __, data in
python
{ "resource": "" }
q1842
JobStateDatabase.pop
train
def pop(self, key, default=_marker): """remove the item by key If not default is specified, raise KeyError if nothing could be removed. Return 'default' if specified and nothing could be removed """ try:
python
{ "resource": "" }
q1843
CronTabberBase.reset_job
train
def reset_job(self, description): """remove the job from the state. if means that next time we run, this job will start over from scratch. """ class_list = self.config.crontabber.jobs.class_list class_list = self._reorder_class_list(class_list) for class_name, job_class in class_list: if ( job_class.app_name == description or description == job_class.__module__ + '.' + job_class.__name__ ):
python
{ "resource": "" }
q1844
CronTabberBase.time_to_run
train
def time_to_run(self, class_, time_): """return true if it's time to run the job. This is true if there is no previous information about its last run or if the last time it ran and set its next_run to a date that is now past. """ app_name = class_.app_name try: info = self.job_state_database[app_name] except KeyError: if time_: h, m = [int(x) for x in time_.split(':')] # only run if this hour and minute is < now now = utc_now() if now.hour > h: return True elif now.hour == h and now.minute >= m: return True return False else: # no past information, run now return True
python
{ "resource": "" }
q1845
CronTabberBase.audit_ghosts
train
def audit_ghosts(self): """compare the list of configured jobs with the jobs in the state""" print_header = True for app_name in self._get_ghosts():
python
{ "resource": "" }
q1846
Grammar.export_js
train
def export_js( self, js_module_name=JS_MODULE_NAME, js_template=JS_ES6_IMPORT_EXPORT_TEMPLATE, js_indent=JS_INDENTATION): '''Export the grammar to a JavaScript file which can be used with the js-lrparsing module. Two templates are available: Grammar.JS_WINDOW_TEMPLATE Grammar.JS_ES6_IMPORT_EXPORT_TEMPLATE (default) ''' language = [] refs = [] classes = {'Grammar'} indent = 0 cname = self.__class__.__name__ if 'import ' in js_template else None for name in self._order: elem = getattr(self, name, None) if not isinstance(elem, Element): continue if not hasattr(elem, '_export_js'): continue language.append('{indent}{var} {name} = {value};'.format( indent=js_indent, name=name, var='static' if cname else 'var', value=elem._export_js(js_indent, indent, classes, cname))) for name, ref in self._refs.items(): refs.append( '{pre}{name}.set({value});' .format( pre='{}.'.format(cname) if cname else js_indent, name=name, value=ref._element._export_js( js_indent, -1 if cname else indent, classes,
python
{ "resource": "" }
q1847
Grammar.export_py
train
def export_py( self, py_module_name=PY_MODULE_NAME, py_template=PY_TEMPLATE, py_indent=PY_INDENTATION): '''Export the grammar to a python file which can be used with the pyleri module. This can be useful when python code if used to auto-create a grammar and an export of the final result is required.''' language = [] classes = {'Grammar'} indent = 0 for name in self._order: elem = getattr(self, name, None) if not isinstance(elem, Element): continue if not hasattr(elem, '_export_py'): continue language.append('{indent}{name} = {value}'.format(
python
{ "resource": "" }
q1848
Grammar.export_go
train
def export_go( self, go_template=GO_TEMPLATE, go_indent=GO_INDENTATION, go_package=GO_PACKAGE): '''Export the grammar to a Go file which can be used with the goleri module.''' language = [] enums = set() indent = 0 pattern = self.RE_KEYWORDS.pattern.replace('`', '` + "`" + `') if not pattern.startswith('^'): pattern = '^' + pattern for name in self._order: elem = getattr(self, name, None) if not isinstance(elem, Element): continue if not hasattr(elem, '_export_go'): continue language.append('{indent}{name} := {value}'.format( indent=go_indent, name=camel_case(name), value=elem._export_go(go_indent, indent, enums))) for name, ref in self._refs.items(): language.append( '{indent}{name}.Set({value})' .format(
python
{ "resource": "" }
q1849
Grammar.export_java
train
def export_java( self, java_template=JAVA_TEMPLATE, java_indent=JAVA_INDENTATION, java_package=JAVA_PACKAGE, is_public=True): '''Export the grammar to a Java file which can be used with the jleri module.''' language = [] enums = set() classes = {'jleri.Grammar', 'jleri.Element'} refs = [] indent = 0 pattern = self.RE_KEYWORDS.pattern.replace('\\', '\\\\') if not pattern.startswith('^'): pattern = '^' + pattern for name in self._order: elem = getattr(self, name, None) if not isinstance(elem, Element): continue if not hasattr(elem, '_export_java'): continue language.append( '{indent}private static final Element {name} = {value};' .format( indent=java_indent, name=name.upper(), value=elem._export_java( java_indent, indent, enums, classes))) enum_str = ',\n'.join([ '{indent}{indent}{gid}'.format( indent=java_indent, gid=gid) for gid in sorted(enums)]) for name, ref in self._refs.items(): refs.append( '{indent}{indent}((Ref) {name}).set({value});' .format( indent=java_indent, name=name.upper(), value=ref._element._export_java(
python
{ "resource": "" }
q1850
Grammar.parse
train
def parse(self, string): '''Parse some string to the Grammar. Returns a nodeResult with the following attributes: - is_valid: True when the string is successfully parsed by the Grammar. - pos: position in the string where parsing ended. (this is the end of the string when is_valid is True) - expecting: a list containing possible elements at position 'pos' in the string. - tree: the parse_tree containing a structured result for the given string. ''' self._string = string self._expecting = Expecting() self._cached_kw_match.clear() self._len_string = len(string) self._pos = None tree = Node(self._element, string, 0, self._len_string) node_res = Result(*self._walk( self._element, 0, tree.children, self._element, True)) # get rest if anything rest = self._string[node_res.pos:].lstrip()
python
{ "resource": "" }
q1851
figure_buffer
train
def figure_buffer(figs): '''Extract raw image buffer from matplotlib figure shaped as 1xHxWx3.''' assert len(figs) > 0, 'No figure buffers given. Forgot to return from draw call?' buffers = [] w, h = figs[0].canvas.get_width_height() for f in figs: wf, hf = f.canvas.get_width_height() assert wf ==
python
{ "resource": "" }
q1852
figure_tensor
train
def figure_tensor(func, **tf_pyfunc_kwargs): '''Decorate matplotlib drawing routines. This dectorator is meant to decorate functions that return matplotlib figures. The decorated function has to have the following signature def decorated(*args, **kwargs) -> figure or iterable of figures where `*args` can be any positional argument and `**kwargs` are any keyword arguments. The decorated function returns a tensor of shape `[NumFigures, Height, Width, 3]` of type `tf.uint8`. The drawing code is invoked during running of TensorFlow sessions, at a time when all positional tensor arguments have been evaluated by the session. The decorated function is then passed the tensor values. All non tensor arguments remain unchanged. ''' name = tf_pyfunc_kwargs.pop('name', func.__name__) @wraps(func) def wrapper(*func_args, **func_kwargs): tf_args = PositionalTensorArgs(func_args)
python
{ "resource": "" }
q1853
blittable_figure_tensor
train
def blittable_figure_tensor(func, init_func, **tf_pyfunc_kwargs): '''Decorate matplotlib drawing routines with blitting support. This dectorator is meant to decorate functions that return matplotlib figures. The decorated function has to have the following signature def decorated(*args, **kwargs) -> iterable of artists where `*args` can be any positional argument and `**kwargs` are any keyword arguments. The decorated function returns a tensor of shape `[NumFigures, Height, Width, 3]` of type `tf.uint8`. Besides the actual drawing function, `blittable_figure_tensor` requires a `init_func` argument with the following signature def init(*args, **kwargs) -> iterable of figures, iterable of artists The init function is meant to create and initialize figures, as well as to perform drawing that is meant to be done only once. Any set of artits to be updated in later drawing calls should also be allocated in init. The initialize function must have the same positional and keyword arguments as the decorated function. It is called once before the decorated function is called. The drawing code / init function is invoked during running of TensorFlow sessions, at a time when all positional tensor arguments have been evaluated by the session. The decorated / init function is then passed the tensor values. All non tensor arguments remain unchanged. ''' name = tf_pyfunc_kwargs.pop('name', func.__name__) assert callable(init_func), 'Init function not callable' @wraps(func) def wrapper(*func_args, **func_kwargs): figs = None bgs = None tf_args = PositionalTensorArgs(func_args) def pyfnc_callee(*tensor_values, **unused): try: nonlocal figs, bgs pos_args = tf_args.mix_args(tensor_values) if figs is None: figs, artists = init_func(*pos_args, **func_kwargs) figs = as_list(figs)
python
{ "resource": "" }
q1854
draw_confusion_matrix
train
def draw_confusion_matrix(matrix): '''Draw confusion matrix for MNIST.''' fig = tfmpl.create_figure(figsize=(7,7)) ax = fig.add_subplot(111) ax.set_title('Confusion matrix for MNIST classification') tfmpl.plots.confusion_matrix.draw(
python
{ "resource": "" }
q1855
from_labels_and_predictions
train
def from_labels_and_predictions(labels, predictions, num_classes): '''Compute a confusion matrix from labels and predictions. A drop-in replacement for tf.confusion_matrix that works on CPU data and not tensors. Params ------ labels : array-like 1-D array of real labels for classification
python
{ "resource": "" }
q1856
draw
train
def draw(ax, cm, axis_labels=None, normalize=False): '''Plot a confusion matrix. Inspired by https://stackoverflow.com/questions/41617463/tensorflow-confusion-matrix-in-tensorboard Params ------ ax : axis Axis to plot on cm : NxN array Confusion matrix Kwargs ------ axis_labels : array-like Array of size N containing axis labels normalize : bool Whether to plot counts or ratios. ''' cm = np.asarray(cm) num_classes = cm.shape[0] if normalize: with np.errstate(invalid='ignore', divide='ignore'): cm = cm / cm.sum(1, keepdims=True) cm = np.nan_to_num(cm, copy=True) po = np.get_printoptions() np.set_printoptions(precision=2) ax.imshow(cm, cmap='Oranges') ticks = np.arange(num_classes) ax.set_xlabel('Predicted') ax.set_xticks(ticks) ax.xaxis.set_label_position('bottom') ax.xaxis.tick_bottom() ax.set_ylabel('Actual') ax.set_yticks(ticks) ax.yaxis.set_label_position('left') ax.yaxis.tick_left()
python
{ "resource": "" }
q1857
create_figure
train
def create_figure(*fig_args, **fig_kwargs): '''Create a single figure. Args and Kwargs are passed to `matplotlib.figure.Figure`. This routine is provided in order to avoid usage of pyplot which is stateful and not thread safe. As drawing routines in tf-matplotlib
python
{ "resource": "" }
q1858
create_figures
train
def create_figures(n, *fig_args, **fig_kwargs): '''Create multiple figures. Args and Kwargs are passed to `matplotlib.figure.Figure`. This routine is provided in order to avoid usage of pyplot which is stateful and not thread safe. As drawing routines
python
{ "resource": "" }
q1859
vararg_decorator
train
def vararg_decorator(f): '''Decorator to handle variable argument decorators.''' @wraps(f) def decorator(*args, **kwargs):
python
{ "resource": "" }
q1860
as_list
train
def as_list(x): '''Ensure `x` is of list type.''' if x is None: x = []
python
{ "resource": "" }
q1861
Photo.all
train
def all(self, page=1, per_page=10, order_by="latest"): """ Get a single page from the list of all photos. :param page [integer]: Page number to retrieve. (Optional; default: 1) :param per_page [integer]: Number of items per page. (Optional; default: 10) :param order_by [string]: How to sort the photos. Optional. (Valid values: latest,
python
{ "resource": "" }
q1862
Photo.get
train
def get(self, photo_id, width=None, height=None, rect=None): """ Retrieve a single photo. Note: Supplying the optional w or h parameters will result in the custom photo URL being added to the 'urls' object: :param photo_id [string]: The photo’s ID. Required. :param width [integer]: Image width in pixels. :param height [integer]: Image height in pixels. :param rect [string]: 4 comma-separated integers representing x, y,
python
{ "resource": "" }
q1863
Photo.random
train
def random(self, count=1, **kwargs): """ Retrieve a single random photo, given optional filters. Note: If supplying multiple category ID’s, the resulting photos will be those that match all of the given categories, not ones that match any category. Note: You can’t use the collections and query parameters in the same request Note: When supplying a count parameter - and only then - the response will be an array of photos, even if the value of count is 1. All parameters are optional, and can be combined to narrow the pool of photos from which a random one will be chosen. :param count [integer]: The number of photos to return. (Default: 1; max: 30) :param category: Category ID(‘s) to filter
python
{ "resource": "" }
q1864
Photo.like
train
def like(self, photo_id): """ Like a photo on behalf of the logged-in user. This requires the 'write_likes' scope. Note: This action is idempotent; sending the POST request to a single photo multiple times has no additional effect. :param photo_id [string]: The photo’s ID. Required.
python
{ "resource": "" }
q1865
Search.photos
train
def photos(self, query, page=1, per_page=10): """ Get a single page of photo results for a query. :param query [string]: Search terms. :param page [integer]: Page number to retrieve. (Optional; default: 1) :param per_page [integer]: Number of items per page. (Optional; default: 10) :return: [dict]: {u'total': 0, u'total_pages': 0, u'results': [Photo]}
python
{ "resource": "" }
q1866
Search.collections
train
def collections(self, query, page=1, per_page=10): """ Get a single page of collection results for a query. :param query [string]: Search terms. :param page [integer]: Page number to retrieve. (Optional; default: 1) :param per_page [integer]: Number of items per page. (Optional; default: 10) :return: [dict]: {u'total': 0, u'total_pages': 0, u'results': [Collection]}
python
{ "resource": "" }
q1867
Search.users
train
def users(self, query, page=1, per_page=10): """ Get a single page of user results for a query. :param query [string]: Search terms. :param page [integer]: Page number to retrieve. (Optional; default: 1) :param per_page [integer]: Number of items per page. (Optional; default: 10) :return: [dict]: {u'total': 0, u'total_pages': 0, u'results': [User]}
python
{ "resource": "" }
q1868
Collection.all
train
def all(self, page=1, per_page=10): """ Get a single page from the list of all collections. :param page [integer]: Page number to retrieve. (Optional; default: 1) :param per_page
python
{ "resource": "" }
q1869
Collection.related
train
def related(self, collection_id): """ Retrieve a list of collections related to this one. :param collection_id [string]: The collection’s ID. Required. :return: [Array]: A single page of the Collection list. """
python
{ "resource": "" }
q1870
Collection.create
train
def create(self, title, description=None, private=False): """ Create a new collection. This requires the 'write_collections' scope. :param title [string]: The title of the collection. (Required.) :param description [string]: The collection’s description. (Optional.) :param private [boolean]: Whether to make this collection private. (Optional; default false). :return: [Collection]: The Unsplash Collection.
python
{ "resource": "" }
q1871
Collection.update
train
def update(self, collection_id, title=None, description=None, private=False): """ Update an existing collection belonging to the logged-in user. This requires the 'write_collections' scope. :param collection_id [string]: The collection’s ID. Required. :param title [string]: The title of the collection. (Required.) :param description [string]: The collection’s description. (Optional.) :param private [boolean]: Whether to make this collection private. (Optional; default false).
python
{ "resource": "" }
q1872
Stat.total
train
def total(self): """ Get a list of counts for all of Unsplash :return [Stat]: The Unsplash Stat. """
python
{ "resource": "" }
q1873
Stat.month
train
def month(self): """ Get the overall Unsplash stats for the past 30 days. :return [Stat]: The Unsplash Stat. """
python
{ "resource": "" }
q1874
Auth.refresh_token
train
def refresh_token(self): """ Refreshing the current expired access token """ self.token = self.oauth.refresh_token(self.access_token_url,
python
{ "resource": "" }
q1875
Client.get_auth_header
train
def get_auth_header(self): """ Getting the authorization header according to the authentication procedure :return [dict]: Authorization header
python
{ "resource": "" }
q1876
User.me
train
def me(self): """ Get the currently-logged in user. Note: To access a user’s private data, the user is required to authorize the 'read_user' scope. Without it, this request will return a '403 Forbidden' response. Note: Without a Bearer token (i.e. using a Client-ID token) this request will
python
{ "resource": "" }
q1877
User.update
train
def update(self, **kwargs): """ Update the currently-logged in user. Note: This action requires the write_user scope. Without it, it will return a 403 Forbidden response. All parameters are optional. :param username [string]: Username. :param first_name [string]: First name.
python
{ "resource": "" }
q1878
User.get
train
def get(self, username, width=None, height=None): """ Retrieve public details on a given user. Note: Supplying the optional w or h parameters will result in the 'custom' photo URL being added to the 'profile_image' object: :param username [string]: The user’s username. Required. :param width [integer]: Profile image width in pixels. :param height [integer]: Profile image height in pixels.
python
{ "resource": "" }
q1879
User.photos
train
def photos(self, username, page=1, per_page=10, order_by="latest"): """ Get a list of photos uploaded by a user. :param username [string]: The user’s username. Required. :param page [integer]: Page number to retrieve. (Optional; default: 1) :param per_page [integer]: Number of items per page. (Optional; default: 10) :param order_by [string]: How to sort the photos. Optional. (Valid values: latest,
python
{ "resource": "" }
q1880
User.collections
train
def collections(self, username, page=1, per_page=10): """ Get a list of collections created by the user. :param username [string]: The user’s username. Required. :param page [integer]: Page number to retrieve. (Optional; default: 1) :param per_page [integer]: Number of items per page. (Optional; default: 10) :return: [Array]: A single page of the Collection list.
python
{ "resource": "" }
q1881
ANSIMultiByteString.wrap
train
def wrap(self, width): """Returns a partition of the string based on `width`""" res = [] prev_state = set() part = [] cwidth = 0 for char, _width, state in zip(self._string, self._width, self._state): if cwidth + _width > width: if prev_state: part.append(self.ANSI_RESET) res.append("".join(part)) prev_state = set() part = [] cwidth = 0 cwidth += _width if prev_state == state: pass elif prev_state <= state: part.extend(state - prev_state)
python
{ "resource": "" }
q1882
BeautifulTable._initialize_table
train
def _initialize_table(self, column_count): """Sets the column count of the table. This method is called to set the number of columns for the first time. Parameters ---------- column_count : int number of columns in the table """ header = [''] * column_count alignment = [self.default_alignment] * column_count width = [0] * column_count padding = [self.default_padding] * column_count
python
{ "resource": "" }
q1883
BeautifulTable.set_style
train
def set_style(self, style): """Set the style of the table from a predefined set of styles. Parameters ---------- style: Style It can be one of the following: * beautifulTable.STYLE_DEFAULT * beautifultable.STYLE_NONE * beautifulTable.STYLE_DOTTED * beautifulTable.STYLE_MYSQL * beautifulTable.STYLE_SEPARATED * beautifulTable.STYLE_COMPACT * beautifulTable.STYLE_MARKDOWN * beautifulTable.STYLE_RESTRUCTURED_TEXT * beautifultable.STYLE_BOX * beautifultable.STYLE_BOX_DOUBLED * beautifultable.STYLE_BOX_ROUNDED * beautifultable.STYLE_GRID """ if not isinstance(style, enums.Style): allowed = ("{}.{}".format(type(self).__name__, i.name) for i in enums.Style) error_msg = ("allowed values for style are: "
python
{ "resource": "" }
q1884
BeautifulTable._calculate_column_widths
train
def _calculate_column_widths(self): """Calculate width of column automatically based on data.""" table_width = self.get_table_width() lpw, rpw = self._left_padding_widths, self._right_padding_widths pad_widths = [(lpw[i] + rpw[i]) for i in range(self._column_count)] max_widths = [0 for index in range(self._column_count)] offset = table_width - sum(self._column_widths) + sum(pad_widths) self._max_table_width = max(self._max_table_width, offset + self._column_count) for index, column in enumerate(zip(*self._table)): max_length = 0 for i in column: for j in to_unicode(i).split('\n'): output_str = get_output_str(j, self.detect_numerics, self.numeric_precision, self.sign_mode.value) max_length = max(max_length, termwidth(output_str)) for i in to_unicode(self._column_headers[index]).split('\n'): output_str = get_output_str(i, self.detect_numerics, self.numeric_precision, self.sign_mode.value) max_length = max(max_length, termwidth(output_str)) max_widths[index] += max_length sum_ = sum(max_widths) desired_sum = self._max_table_width - offset # Set flag for columns who are within their fair share temp_sum = 0 flag = [0] * len(max_widths) for i, width in enumerate(max_widths): if width <= int(desired_sum / self._column_count): temp_sum += width flag[i] = 1 else: # Allocate atleast 1 character width to the column temp_sum += 1 avail_space = desired_sum - temp_sum actual_space = sum_ - temp_sum shrinked_columns = {} # Columns which exceed their fair share should be shrinked based on # how much space is left for the table
python
{ "resource": "" }
q1885
BeautifulTable.get_column_index
train
def get_column_index(self, header): """Get index of a column from it's header. Parameters ---------- header: str header of the column. Raises ------ ValueError:
python
{ "resource": "" }
q1886
BeautifulTable.get_column
train
def get_column(self, key): """Return an iterator to a column. Parameters ---------- key : int, str index of the column, or the header of the column. If index is specified, then normal list rules apply. Raises ------ TypeError: If key is not of type `int`, or `str`. Returns ------- iter: Iterator to the specified column. """ if isinstance(key, int):
python
{ "resource": "" }
q1887
BeautifulTable.insert_row
train
def insert_row(self, index, row): """Insert a row before index in the table. Parameters ---------- index : int List index rules apply row : iterable Any iterable of appropriate length. Raises ------ TypeError: If `row` is not an iterable. ValueError: If size of `row`
python
{ "resource": "" }
q1888
BeautifulTable.insert_column
train
def insert_column(self, index, header, column): """Insert a column before `index` in the table. If length of column is bigger than number of rows, lets say `k`, only the first `k` values of `column` is considered. If column is shorter than 'k', ValueError is raised. Note that Table remains in consistent state even if column is too short. Any changes made by this method is rolled back before raising the exception. Parameters ---------- index : int List index rules apply. header : str Title of the column. column : iterable Any iterable of appropriate length. Raises ------ TypeError: If `header` is not of type `str`. ValueError: If length of `column` is shorter than number of rows. """ if self._column_count == 0: self.column_headers = HeaderData(self, [header]) self._table = [RowData(self, [i]) for i in column] else: if not isinstance(header, basestring): raise TypeError("header must be of type str") column_length = 0 for i, (row, new_item) in enumerate(zip(self._table, column)):
python
{ "resource": "" }
q1889
BeautifulTable.append_column
train
def append_column(self, header, column): """Append a column to end of the table. Parameters ---------- header : str Title of the column column : iterable
python
{ "resource": "" }
q1890
BeautifulTable._get_horizontal_line
train
def _get_horizontal_line(self, char, intersect_left, intersect_mid, intersect_right): """Get a horizontal line for the table. Internal method used to actually get all horizontal lines in the table. Column width should be set prior to calling this method. This method detects intersection and handles it according to the values of `intersect_*_*` attributes. Parameters ---------- char : str Character used to draw the line. Returns ------- str String which will be printed as the Top border of the table. """ width = self.get_table_width() try: line = list(char * (int(width/termwidth(char)) + 1))[:width] except ZeroDivisionError: line = [' '] * width if len(line) == 0: return '' # Only if Special Intersection is enabled and horizontal line is # visible if not char.isspace(): # If left border is enabled and it is visible visible_junc = not intersect_left.isspace() if termwidth(self.left_border_char) > 0: if not (self.left_border_char.isspace() and visible_junc): length = min(termwidth(self.left_border_char), termwidth(intersect_left)) for i in range(length): line[i] = intersect_left[i] visible_junc = not intersect_right.isspace() # If right border is enabled and it is visible if termwidth(self.right_border_char) > 0: if not (self.right_border_char.isspace() and visible_junc): length = min(termwidth(self.right_border_char), termwidth(intersect_right))
python
{ "resource": "" }
q1891
BeautifulTable.get_table_width
train
def get_table_width(self): """Get the width of the table as number of characters. Column width should be set prior to calling this method. Returns ------- int Width of the table as number of characters.
python
{ "resource": "" }
q1892
BeautifulTable.get_string
train
def get_string(self, recalculate_width=True): """Get the table as a String. Parameters ---------- recalculate_width : bool, optional If width for each column should be recalculated(default True). Note that width is always calculated if it wasn't set explicitly when this method is called for the first time , regardless of the value of `recalculate_width`. Returns ------- str: Table as a string. """ # Empty table. returning empty string. if len(self._table) == 0: return '' if self.serialno and self.column_count > 0: self.insert_column(0, self.serialno_header, range(1, len(self) + 1)) # Should widths of column be recalculated if recalculate_width or sum(self._column_widths) == 0: self._calculate_column_widths() string_ = [] # Drawing the top border if self.top_border_char: string_.append( self._get_top_border()) # Print headers if not empty or only spaces if ''.join(self._column_headers).strip(): headers = to_unicode(self._column_headers)
python
{ "resource": "" }
q1893
_convert_to_numeric
train
def _convert_to_numeric(item): """ Helper method to convert a string to float or int if possible. If the conversion is not possible, it simply returns the string. """ if PY3: num_types = (int, float) else: # pragma: no cover num_types = (int, long, float) # noqa: F821 # We don't wan't to perform any conversions if item is already a number if isinstance(item, num_types): return item # First try for an int conversion so that strings like "5" are converted # to 5 instead of 5.0 . This is safe as a direct int cast for a non integer # string raises
python
{ "resource": "" }
q1894
get_output_str
train
def get_output_str(item, detect_numerics, precision, sign_value): """Returns the final string which should be displayed""" if detect_numerics: item = _convert_to_numeric(item)
python
{ "resource": "" }
q1895
RowData._get_row_within_width
train
def _get_row_within_width(self, row): """Process a row so that it is clamped by column_width. Parameters ---------- row : array_like A single row. Returns ------- list of list: List representation of the `row` after it has been processed according to width exceed policy. """ table = self._table lpw, rpw = table.left_padding_widths, table.right_padding_widths wep = table.width_exceed_policy list_of_rows = [] if (wep is WidthExceedPolicy.WEP_STRIP or wep is WidthExceedPolicy.WEP_ELLIPSIS): # Let's strip the row delimiter = '' if wep is WidthExceedPolicy.WEP_STRIP else '...' row_item_list = [] for index, row_item in enumerate(row): left_pad = table._column_pad * lpw[index] right_pad = table._column_pad * rpw[index] clmp_str = (left_pad + self._clamp_string(row_item, index, delimiter) + right_pad) row_item_list.append(clmp_str)
python
{ "resource": "" }
q1896
RowData._clamp_string
train
def _clamp_string(self, row_item, column_index, delimiter=''): """Clamp `row_item` to fit in column referred by column_index. This method considers padding and appends the delimiter if `row_item` needs to be truncated. Parameters ---------- row_item: str String which should be clamped. column_index: int Index of the column `row_item` belongs to. delimiter: str String which is to be appended to the clamped string. Returns ------- str The modified string which fits in it's column. """
python
{ "resource": "" }
q1897
ICQBot.send_im
train
def send_im(self, target, message, mentions=None, parse=None, update_msg_id=None, wrap_length=5000): """ Send text message. :param target: Target user UIN or chat ID. :param message: Message text. :param mentions: Iterable with UINs to mention in message. :param parse: Iterable with several values from :class:`icq.constant.MessageParseType` specifying which message items should be parsed by target client (making preview, snippets, etc.). Specify empty iterable to avoid parsing message at target client. By default all types are included. :param update_msg_id: Message ID to update. :param wrap_length: Maximum length of symbols in one message. Text exceeding this length will be sent in several messages. :return: Tuple of HTTP responses. """ try: responses = set() for text in wrap(string=str(message), length=wrap_length): response = self.http_session.post( url="{}/im/sendIM".format(self.api_base_url), data={ "r": uuid.uuid4(), "aimsid": self.token, "t": target, "message": text, "mentions": ( mentions if isinstance(mentions, six.string_types) or not hasattr(mentions, "__iter__")
python
{ "resource": "" }
q1898
render_markdown
train
def render_markdown(text, context=None): """ Turn markdown into HTML. """ if context is None or not isinstance(context, dict): context = {} markdown_html =
python
{ "resource": "" }
q1899
TableProcessor.run
train
def run(self, parent, blocks): """ Parse a table block and build table. """ block = blocks.pop(0).split('\n') header = block[0].strip() seperator = block[1].strip() rows = block[2:] # Get format type (bordered by pipes or not) border = False if header.startswith('|'): border = True # Get alignment of columns align = [] for c in self._split_row(seperator, border):
python
{ "resource": "" }