_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
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 =...
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", } } return Response(r"""Usage: curl -i \ -H "Content-Type: application/json" \ ...
python
{ "resource": "" }
q1802
RedisSessionManager._key
train
def _key(self, username, frozen=False): """Translate a username into a key for Redis.""" if frozen: return self.frozen + username return self.prefix + username
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)) if data is None: return None return json.loads(data.decode())
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 ...
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: # Count the words. cword = utils.word_count(ite...
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 `...
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() fh.close() self._sa...
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. """ self._say("Streaming code.") if type(code) in [str, text_type]: code = code.split...
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, co...
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...
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 da...
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....
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). ...
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! """ # (R...
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 rivescrip...
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 fun...
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. """ if val...
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. """ if value i...
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. """ if rep ...
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. """ if ...
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. :param str name: The name of the variable to set. :param str value: The value to set there. """...
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 ...
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, this r...
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...
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 object). ...
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 variabl...
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 ...
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 ...
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 --") ...
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(',') return dump_to_response(request, app_label=app_label, exclude=settings.SMUG...
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, model_label), [], '-'.join((app_label, model_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, 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 all of its structures and resource...
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.""" for x in self....
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'. That means it will do the work of a backfilling app. """...
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 me...
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 '...
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 s...
python
{ "resource": "" }
q1839
JobStateDatabase.keys
train
def keys(self): """return a list of all app_names""" keys = [] for app_name, __ in self.items(): keys.append(app_name) return 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, ...
python
{ "resource": "" }
q1841
JobStateDatabase.values
train
def values(self): """return a list of all state values""" values = [] for __, data in self.items(): values.append(data) return values
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: popped = self[key] del self[key] ...
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 i...
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: ...
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(): if print_header: print_header = False print ( "Found the following in the state dat...
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: ...
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 gr...
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 ...
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 ...
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 th...
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() ...
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 w...
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) ...
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( ax, matrix, axis_labels=['Digit ' + str(x) fo...
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 classi...
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 -...
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 are called from py-funcs in th...
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 in tf-matplotlib are called from py-funcs ...
python
{ "resource": "" }
q1859
vararg_decorator
train
def vararg_decorator(f): '''Decorator to handle variable argument decorators.''' @wraps(f) def decorator(*args, **kwargs): if len(args) == 1 and len(kwargs) == 0 and callable(args[0]): return f(args[0]) else: return lambda realf: f(realf, *args, **kwargs) return...
python
{ "resource": "" }
q1860
as_list
train
def as_list(x): '''Ensure `x` is of list type.''' if x is None: x = [] elif not isinstance(x, Sequence): x = [x] return list(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]:...
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 widt...
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 t...
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 ...
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: ...
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;...
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...
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 [integer]: Number of items per page. (Optional; default: 10) :return: [Array]: A single page of the ...
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. """ url = "/collections/%s/related" % collection_id res...
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.) :par...
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 ...
python
{ "resource": "" }
q1872
Stat.total
train
def total(self): """ Get a list of counts for all of Unsplash :return [Stat]: The Unsplash Stat. """ url = "/stats/total" result = self._get(url) return StatModel.parse(result)
python
{ "resource": "" }
q1873
Stat.month
train
def month(self): """ Get the overall Unsplash stats for the past 30 days. :return [Stat]: The Unsplash Stat. """ url = "/stats/month" result = self._get(url) return StatModel.parse(result)
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, refresh_token=self.get_refresh_token()) self.access_token = self.token.get("access_token")
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 """ if self.api.is_authenticated: return {"Authorization": "Bearer %s" % self.api.access_token} return {"Authorizati...
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 toke...
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]...
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...
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 i...
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...
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: ...
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 = [''] * colum...
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.STY...
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 = ...
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: If no column could be found corresponding to `header`. """ tr...
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: ...
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...
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 T...
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 Any iterable of appropriate length. """ self.insert_column(self._column_count, heade...
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...
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. """ if self.column_count == 0: retu...
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 e...
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...
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) if isinstance(item, float): item = round(item, precision) try: item = '{:{sign}}'.format(item, sign=sign...
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...
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 Str...
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: I...
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 = _transform_markdown_into_html(text) sanitised_markdown_html = _sanitise_markdown_html(markdown_html) return mark_safe(sanitised_...
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 hea...
python
{ "resource": "" }