func_code_string
stringlengths
52
1.94M
func_documentation_string
stringlengths
1
47.2k
def _dump(self): 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 ...
For debugging, dump the entire data structure.
def parse(self, filename, code): # Eventual returned structure ("abstract syntax tree" but not really) ast = { "begin": { "global": {}, "var": {}, "sub": {}, "person": {}, "array": {}, }, ...
Read and parse a RiveScript document. Returns a data structure that represents all of the useful contents of the document, in this format:: { "begin": { # "begin" data "global": {}, # map of !global vars "var": {}, # bot !var's ...
def check_syntax(self, cmd, line): # Run syntax checks based on the type of command. if cmd == '!': # ! Definition # - Must be formatted like this: # ! type name = value # OR # ! type = value match = re.match(...
Syntax check a line of RiveScript code. Args: str cmd: The command symbol for the line of code, such as one of ``+``, ``-``, ``*``, ``>``, etc. str line: The remainder of the line of code, such as the text of a trigger or reply. Return: ...
def dump_to_response(request, app_label=None, exclude=None, filename_prefix=None): app_label = app_label or [] exclude = exclude try: filename = '%s.%s' % (datetime.now().isoformat(), settings.SMUGGLER_FORMAT) if filename_prefix: ...
Utility function that dumps the given app/model to an HttpResponse.
def dump_data(request): # 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.SMUGGLER_EXCLUDE_LIST)
Exports data from whole project.
def dump_model_data(request, app_label, model_label): return dump_to_response(request, '%s.%s' % (app_label, model_label), [], '-'.join((app_label, model_label)))
Exports data from a model.
def toposort(data): # Special case empty input. if len(data) == 0: return # Copy the input so as to leave it unmodified. data = data.copy() # Ignore self dependencies. for k, v in data.items(): v.discard(k) # Find all items that don't depend on anything. extra_items_...
Dependencies are expressed as a dictionary whose keys are items and whose values are a set of dependent items. Output is a list of sets in topological order. The first set consists of items with no dependences, each subsequent set consists of items that depend upon items in the preceeding sets.
def reorder_dag(sequence, depends_getter=lambda x: x.depends_on, name_getter=lambda x: x.app_name, impatience_max=100): jobs = collections.defaultdict(list) map_ = {} _count_roots = 0 for each in sequence: name = name_getter(each) depe...
DAG = Directed Acyclic Graph If we have something like: C depends on B B depends on A A doesn't depend on any Given the order of [C, B, A] expect it to return [A, B, C] parameters: :sequence: some sort of iterable list :depends_getter: a callable that extracts the...
def convert_frequency(frequency): number = int(re.findall('\d+', frequency)[0]) unit = re.findall('[^\d]+', frequency)[0] if unit == 'h': number *= 60 * 60 elif unit == 'm': number *= 60 elif unit == 'd': number *= 60 * 60 * 24 elif unit: raise FrequencyDefin...
return the number of seconds that a certain frequency string represents. For example: `1d` means 1 day which means 60 * 60 * 24 seconds. The recognized formats are: 10d : 10 days 3m : 3 minutes 12h : 12 hours
def timesince(d, now): 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, pl...
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....
def connection(self, name=None): if not name: name = self._get_default_connection_name() if name in self.pool: return self.pool[name] self.pool[name] = psycopg2.connect(self.dsn) return self.pool[name]
return a named connection. This function will return a named connection by either finding one in its pool by the name or creating a new one. If no name is given, it will use the name of the current executing thread as the name of the connection. parameters: name - ...
def close_connection(self, connection, force=False): if force: try: connection.close() except self.operational_exceptions: self.config.logger.error('ConnectionFactory - failed closing') for name, conn in self.pool.iteritems(): ...
overriding the baseclass function, this routine will decline to close a connection at the end of a transaction context. This allows for reuse of connections.
def respond_to_SIGHUP(signal_number, frame, logger=None): global restart restart = True if logger: logger.info('detected SIGHUP') raise KeyboardInterrupt
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 resources and start running again
def backoff_generator(self): for x in self.config.backoff_delays: yield x while True: yield self.config.backoff_delays[-1]
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.
def responsive_sleep(self, seconds, wait_reason=''): for x in xrange(int(seconds)): if (self.config.wait_log_interval and not x % self.config.wait_log_interval): self.config.logger.debug( '%s: %dsec of %dsec' % (wait_reason, x, seconds...
Sleep for the specified number of seconds, logging every 'wait_log_interval' seconds with progress info.
def as_backfill_cron_app(cls): #---------------------------------------------------------------------- def main(self, function=None): return super(cls, self).main( function=function, once=False, ) cls.main = main cls._is_backfill_app = True return 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.
def with_transactional_resource( transactional_resource_class, resource_name, reference_value_from=None ): def class_decorator(cls): if not issubclass(cls, RequiredConfig): raise Exception( '%s must have RequiredConfig as a base class' % cls ) ...
a class decorator for Crontabber Apps. This decorator will give access to a resource connection source. Configuration will be automatically set up and the cron app can expect to have attributes: self.{resource_name}_connection_factory self.{resource_name}_transaction_executor available to ...
def with_resource_connection_as_argument(resource_name): connection_factory_attr_name = '%s_connection_factory' % resource_name def class_decorator(cls): def _run_proxy(self, *args, **kwargs): factory = getattr(self, connection_factory_attr_name) with factory() as connection...
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 properl...
def with_single_transaction(resource_name): transaction_executor_attr_name = "%s_transaction_executor" % resource_name def class_decorator(cls): def _run_proxy(self, *args, **kwargs): getattr(self, transaction_executor_attr_name)( self.run, *args, ...
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 automa...
def with_subprocess(cls): def run_process(self, command, input=None): if isinstance(command, (tuple, list)): command = ' '.join('"%s"' % x for x in command) proc = subprocess.Popen( command, shell=True, stdout=subprocess.PIPE, ...
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 ...
def classes_in_namespaces_converter_with_compression( reference_namespace={}, template_for_namespace="class-%(name)s", list_splitter_fn=_default_list_splitter, class_extractor=_default_class_extractor, extra_extractor=_default_extra_extractor): # ------------------------...
parameters: template_for_namespace - a template for the names of the namespaces that will contain the classes and their associated required config options. There are two template variables available: %(name)s - ...
def check_time(value): try: h, m = value.split(':') h = int(h) m = int(m) if h >= 24 or h < 0: raise ValueError if m >= 60 or m < 0: raise ValueError except ValueError: raise TimeDefinitionError("Invalid definition of time %r" % value)
check that it's a value like 03:45 or 1:1
def keys(self): keys = [] for app_name, __ in self.items(): keys.append(app_name) return keys
return a list of all app_names
def items(self): sql = columns = ( 'app_name', 'next_run', 'first_run', 'last_run', 'last_success', 'depends_on', 'error_count', 'last_error' ) items = [] for record in self.transaction_executor(execute_query_fetchall, sql): ...
return all the app_names and their values as tuples
def values(self): values = [] for __, data in self.items(): values.append(data) return values
return a list of all state values
def pop(self, key, default=_marker): try: popped = self[key] del self[key] return popped except KeyError: if default == _marker: raise return default
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
def nagios(self, stream=sys.stdout): warnings = [] criticals = [] for class_name, job_class in self.config.crontabber.jobs.class_list: if job_class.app_name in self.job_state_database: info = self.job_state_database.get(job_class.app_name) if ...
return 0 (OK) if there are no errors in the state. return 1 (WARNING) if a backfill app only has 1 error. return 2 (CRITICAL) if a backfill app has > 1 error. return 2 (CRITICAL) if a non-backfill app has 1 error.
def reset_job(self, description): 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...
remove the job from the state. if means that next time we run, this job will start over from scratch.
def time_to_run(self, class_, time_): 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 ...
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.
def audit_ghosts(self): print_header = True for app_name in self._get_ghosts(): if print_header: print_header = False print ( "Found the following in the state database but not " "available as a configured job:"...
compare the list of configured jobs with the jobs in the state
def export_js( self, js_module_name=JS_MODULE_NAME, js_template=JS_ES6_IMPORT_EXPORT_TEMPLATE, js_indent=JS_INDENTATION): language = [] refs = [] classes = {'Grammar'} indent = 0 cname = self.__class__.__name__ if 'import '...
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)
def export_py( self, py_module_name=PY_MODULE_NAME, py_template=PY_TEMPLATE, py_indent=PY_INDENTATION): language = [] classes = {'Grammar'} indent = 0 for name in self._order: elem = getattr(self, name, None) ...
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.
def export_c(self, target=C_TARGET, c_indent=C_INDENTATION, headerf=None): language = [] indent = 0 enums = set() for name in self._order: elem = getattr(self, name, None) if not isinstance(elem, Element): continue if not hasat...
Export the grammar to a c (source and header) file which can be used with the libcleri module.
def export_go( self, go_template=GO_TEMPLATE, go_indent=GO_INDENTATION, go_package=GO_PACKAGE): language = [] enums = set() indent = 0 pattern = self.RE_KEYWORDS.pattern.replace('`', '` + "`" + `') if not pattern.startswith...
Export the grammar to a Go file which can be used with the goleri module.
def export_java( self, java_template=JAVA_TEMPLATE, java_indent=JAVA_INDENTATION, java_package=JAVA_PACKAGE, is_public=True): language = [] enums = set() classes = {'jleri.Grammar', 'jleri.Element'} refs = [] in...
Export the grammar to a Java file which can be used with the jleri module.
def parse(self, 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( s...
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...
def figure_buffer(figs): 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 == w and hf == h, 'All canvas objects need to have same size...
Extract raw image buffer from matplotlib figure shaped as 1xHxWx3.
def figure_tensor(func, **tf_pyfunc_kwargs): name = tf_pyfunc_kwargs.pop('name', func.__name__) @wraps(func) def wrapper(*func_args, **func_kwargs): tf_args = PositionalTensorArgs(func_args) def pyfnc_callee(*tensor_values, **unused): try: figs = as_...
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 `**k...
def blittable_figure_tensor(func, init_func, **tf_pyfunc_kwargs): 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 = PositionalTenso...
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 argum...
def draw_confusion_matrix(matrix): 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) for x in range(10)], normalize=T...
Draw confusion matrix for MNIST.
def from_labels_and_predictions(labels, predictions, num_classes): assert len(labels) == len(predictions) cm = np.zeros((num_classes, num_classes), dtype=np.int32) for i in range(len(labels)): cm[labels[i], predictions[i]] += 1 return cm
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 predicitions: array-like 1-D array of predicted label...
def draw(ax, cm, axis_labels=None, normalize=False): 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() ...
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 c...
def create_figure(*fig_args, **fig_kwargs): fig = Figure(*fig_args, **fig_kwargs) # Attach canvas FigureCanvas(fig) return fig
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 their respective thread, avoid usage of pyplot wh...
def create_figures(n, *fig_args, **fig_kwargs): return [create_figure(*fig_args, **fig_kwargs) for _ in range(n)]
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 in their respective thread, avoid usage of pyplot w...
def vararg_decorator(f): @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 decorator
Decorator to handle variable argument decorators.
def as_list(x): if x is None: x = [] elif not isinstance(x, Sequence): x = [x] return list(x)
Ensure `x` is of list type.
def all(self, page=1, per_page=10, order_by="latest"): return self._all("/photos", page=page, per_page=per_page, order_by=order_by)
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, oldest, p...
def curated(self, page=1, per_page=10, order_by="latest"): return self._all("/photos/curated", page=page, per_page=per_page, order_by=order_by)
Get a single page from the list of the curated photos (front-page’s 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. (V...
def get(self, photo_id, width=None, height=None, rect=None): url = "/photos/%s" % photo_id params = { "w": width, "h": height, "rect": rect } result = self._get(url, params=params) return PhotoModel.parse(result)
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...
def search(self, query, category=None, orientation=None, page=1, per_page=10): if orientation and orientation not in self.orientation_values: raise Exception() params = { "query": query, "category": category, "orientation": orientation, ...
Get a single page from a photo search. Optionally limit your search to a set of categories by supplying the category ID’s. 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. :pa...
def random(self, count=1, **kwargs): kwargs.update({"count": count}) orientation = kwargs.get("orientation", None) if orientation and orientation not in self.orientation_values: raise Exception() url = "/photos/random" result = self._get(url, params=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 ...
def stats(self, photo_id): url = "/photos/%s/stats" % photo_id result = self._get(url) return StatModel.parse(result)
Retrieve a single photo’s stats. :param photo_id [string]: The photo’s ID. Required. :return: [Stat]: The Unsplash Stat.
def like(self, photo_id): url = "/photos/%s/like" % photo_id result = self._post(url) return PhotoModel.parse(result)
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. :return: [Photo]: The Un...
def unlike(self, photo_id): url = "/photos/%s/like" % photo_id result = self._delete(url) return PhotoModel.parse(result)
Remove a user’s like of a photo. Note: This action is idempotent; sending the DELETE request to a single photo multiple times has no additional effect. :param photo_id [string]: The photo’s ID. Required. :return: [Photo]: The Unsplash Photo.
def photos(self, query, page=1, per_page=10): url = "/search/photos" data = self._search(url, query, page=page, per_page=per_page) data["results"] = PhotoModel.parse_list(data.get("results")) return data
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're...
def collections(self, query, page=1, per_page=10): url = "/search/collections" data = self._search(url, query, page=page, per_page=per_page) data["results"] = CollectionModel.parse_list(data.get("results")) return data
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,...
def users(self, query, page=1, per_page=10): url = "/search/users" data = self._search(url, query, page=page, per_page=per_page) data["results"] = UserModel.parse_list(data.get("results")) return data
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'res...
def all(self, page=1, per_page=10): url = "/collections" result = self._all(url, page=page, per_page=per_page) return CollectionModel.parse_list(result)
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 Collection list.
def get(self, collection_id): url = "/collections/%s" % collection_id result = self._get(url) return CollectionModel.parse(result)
Retrieve a single collection. To view a user’s private collections, the 'read_collections' scope is required. :param collection_id [string]: The collections’s ID. Required. :return: [Collection]: The Unsplash Collection.
def get_curated(self, collection_id): url = "/collections/curated/%s" % collection_id result = self._get(url) return CollectionModel.parse(result)
Retrieve a single curated collection. To view a user’s private collections, the 'read_collections' scope is required. :param collection_id [string]: The collections’s ID. Required. :return: [Collection]: The Unsplash Collection.
def photos(self, collection_id, page=1, per_page=10): url = "/collections/%s/photos" % collection_id result = self._all(url, page=page, per_page=per_page) return PhotoModel.parse_list(result)
Retrieve a collection’s photos. :param collection_id [string]: The collection’s ID. 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 Photo ...
def related(self, collection_id): url = "/collections/%s/related" % collection_id result = self._get(url) return CollectionModel.parse_list(result)
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.
def create(self, title, description=None, private=False): url = "/collections" data = { "title": title, "description": description, "private": private } result = self._post(url, data=data) return CollectionModel.parse(result)
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; defa...
def update(self, collection_id, title=None, description=None, private=False): url = "/collections/%s" % collection_id data = { "title": title, "description": description, "private": private } result = self._put(url, data=data) return C...
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 descrip...
def add_photo(self, collection_id, photo_id): url = "/collections/%s/add" % collection_id data = { "collection_id": collection_id, "photo_id": photo_id } result = self._post(url, data=data) or {} return CollectionModel.parse(result.get("collection...
Add a photo to one of the logged-in user’s collections. Requires the 'write_collections' scope. Note: If the photo is already in the collection, this acion has no effect. :param collection_id [string]: The collection’s ID. Required. :param photo_id [string]: The photo’s ID. Required. ...
def remove_photo(self, collection_id, photo_id): url = "/collections/%s/remove" % collection_id data = { "collection_id": collection_id, "photo_id": photo_id } result = self._delete(url, data=data) or {} return CollectionModel.parse(result.get("co...
Remove a photo from one of the logged-in user’s collections. Requires the 'write_collections' scope. :param collection_id [string]: The collection’s ID. Required. :param photo_id [string]: The photo’s ID. Required. :return: [Tuple]: The Unsplash Collection and Photo
def total(self): url = "/stats/total" result = self._get(url) return StatModel.parse(result)
Get a list of counts for all of Unsplash :return [Stat]: The Unsplash Stat.
def month(self): url = "/stats/month" result = self._get(url) return StatModel.parse(result)
Get the overall Unsplash stats for the past 30 days. :return [Stat]: The Unsplash Stat.
def get_access_token(self, code): self.token = self.oauth.fetch_token( token_url=self.access_token_url, client_id=self.client_id, client_secret=self.client_secret, scope=self.scope, code=code ) return self.token.get("access_tok...
Getting access token :param code [string]: The authorization code supplied to the callback by Unsplash. :return [string]: access token
def refresh_token(self): self.token = self.oauth.refresh_token(self.access_token_url, refresh_token=self.get_refresh_token()) self.access_token = self.token.get("access_token")
Refreshing the current expired access token
def parse_list(cls, data): results = ResultSet() data = data or [] for obj in data: if obj: results.append(cls.parse(obj)) return results
Parse a list of JSON objects into a result set of model instances.
def get_auth_header(self): if self.api.is_authenticated: return {"Authorization": "Bearer %s" % self.api.access_token} return {"Authorization": "Client-ID %s" % self.api.client_id}
Getting the authorization header according to the authentication procedure :return [dict]: Authorization header
def me(self): url = "/me" result = self._get(url) return UserModel.parse(result)
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 retur...
def update(self, **kwargs): url = "/me" result = self._put(url, data=kwargs) return UserModel.parse(result)
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. :param last_name [string]:...
def get(self, username, width=None, height=None): url = "/users/{username}".format(username=username) params = { "w": width, "h": height } result = self._get(url, params=params) return UserModel.parse(result)
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. ...
def portfolio(self, username): url = "/users/{username}/portfolio".format(username=username) result = self._get(url) return LinkModel.parse(result)
Retrieve a single user’s portfolio link. :param username [string]: The user’s username. Required. :return: [Link]: The Unsplash Link.
def photos(self, username, page=1, per_page=10, order_by="latest"): url = "/users/{username}/photos".format(username=username) result = self._photos(url, username, page=page, per_page=per_page, order_by=order_by) return PhotoModel.parse_list(result)
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...
def collections(self, username, page=1, per_page=10): url = "/users/{username}/collections".format(username=username) params = { "page": page, "per_page": per_page } result = self._get(url, params=params) return CollectionModel.parse_list(result)
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 ...
def wrap(self, 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) ...
Returns a partition of the string based on `width`
def max_table_width(self): offset = ((self._column_count - 1) * termwidth(self.column_separator_char)) offset += termwidth(self.left_border_char) offset += termwidth(self.right_border_char) self._max_table_width = max(self._max_table_width, ...
get/set the maximum width of the table. The width of the table is guaranteed to not exceed this value. If it is not possible to print a given table with the width provided, this value will automatically adjust.
def _initialize_table(self, column_count): header = [''] * column_count alignment = [self.default_alignment] * column_count width = [0] * column_count padding = [self.default_padding] * column_count self._column_count = column_count self._column_headers = HeaderD...
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
def set_style(self, style): 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: " + ', '.join(allowed)) raise V...
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....
def _calculate_column_widths(self): 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 = ...
Calculate width of column automatically based on data.
def sort(self, key, reverse=False): if isinstance(key, int): index = key elif isinstance(key, basestring): index = self.get_column_index(key) else: raise TypeError("'key' must either be 'int' or 'str'") self._table.sort(key=operator.itemgetter...
Stable sort of the table *IN-PLACE* with respect to a column. Parameters ---------- key: int, str index or header of the column. Normal list rules apply. reverse : bool If `True` then table is sorted as if each comparison was reversed.
def get_column_index(self, header): try: index = self._column_headers.index(header) return index except ValueError: raise_suppressed(KeyError(("'{}' is not a header for any " "column").format(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`.
def get_column(self, key): if isinstance(key, int): index = key elif isinstance(key, basestring): index = self.get_column_index(key) else: raise TypeError(("key must be an int or str, " "not {}").format(type(key).__name__)...
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`...
def pop_column(self, index=-1): if isinstance(index, int): pass elif isinstance(index, basestring): index = self.get_column_index(index) else: raise TypeError(("column index must be an integer or a string, " "not {}").form...
Remove and return row at index (default last). Parameters ---------- index : int, str index of the column, or the header of the column. If index is specified, then normal list rules apply. Raises ------ TypeError: If index is not an i...
def insert_row(self, index, row): row = self._validate_row(row) row_obj = RowData(self, row) self._table.insert(index, row_obj)
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: ...
def update_row(self, key, value): if isinstance(key, int): row = self._validate_row(value, init_table_if_required=False) row_obj = RowData(self, row) self._table[key] = row_obj elif isinstance(key, slice): row_obj_list = [] for row in ...
Update a column named `header` in the table. If length of column is smaller than number of rows, lets say `k`, only the first `k` values in the column is updated. Parameters ---------- key : int or slice index of the row, or a slice object. value : iterable...
def update_column(self, header, column): index = self.get_column_index(header) if not isinstance(header, basestring): raise TypeError("header must be of type str") for row, new_item in zip(self._table, column): row[index] = new_item
Update a column named `header` in the table. If length of column is smaller than number of rows, lets say `k`, only the first `k` values in the column is updated. Parameters ---------- header : str Header of the column column : iterable Any iter...
def insert_column(self, index, header, column): 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("heade...
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 ...
def append_column(self, header, column): self.insert_column(self._column_count, header, column)
Append a column to end of the table. Parameters ---------- header : str Title of the column column : iterable Any iterable of appropriate length.
def _get_horizontal_line(self, char, intersect_left, intersect_mid, intersect_right): width = self.get_table_width() try: line = list(char * (int(width/termwidth(char)) + 1))[:width] except ZeroDivisionError: line = [' '] * width ...
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. Parameter...
def get_table_width(self): if self.column_count == 0: return 0 width = sum(self._column_widths) width += ((self._column_count - 1) * termwidth(self.column_separator_char)) width += termwidth(self.left_border_char) width += termwidth(self.rig...
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.
def get_string(self, recalculate_width=True): # 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)...
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 ,...
def _convert_to_numeric(item): 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): ret...
Helper method to convert a string to float or int if possible. If the conversion is not possible, it simply returns the string.
def get_output_str(item, detect_numerics, precision, sign_value): if detect_numerics: item = _convert_to_numeric(item) if isinstance(item, float): item = round(item, precision) try: item = '{:{sign}}'.format(item, sign=sign_value) except (ValueError, TypeError): pass...
Returns the final string which should be displayed
def _get_row_within_width(self, row): 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): ...
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.
def _clamp_string(self, row_item, column_index, delimiter=''): width = (self._table.column_widths[column_index] - self._table.left_padding_widths[column_index] - self._table.right_padding_widths[column_index]) if termwidth(row_item) <= width: return...
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 ...
def send_im(self, target, message, mentions=None, parse=None, update_msg_id=None, wrap_length=5000): try: responses = set() for text in wrap(string=str(message), length=wrap_length): response = self.http_session.post( url="{}/im/sendIM".format...
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...