code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if dump:
return self._syntax
response = None
# Search the syntax tree for the trigger.
for category in self._syntax:
for topic in self._syntax[category]:
if trigger in self._syntax[category][topic]:
# We got a match!
... | 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... | 3.743914 | 3.103739 | 1.206259 |
if self._brain._current_user is None:
# They're doing it wrong.
self._warn("current_user() is meant to be used from within a Python object macro!")
return self._brain._current_user | 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).
This will return ``None`` if use... | 13.326059 | 8.11742 | 1.641662 |
return self._brain.reply(user, msg, errors_as_replies) | 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
bo... | 5.514036 | 8.82148 | 0.625069 |
if pattern not in self._regexc[kind]:
qm = re.escape(pattern)
self._regexc[kind][pattern] = {
"qm": qm,
"sub1": re.compile(r'^' + qm + r'$'),
"sub2": re.compile(r'^' + qm + r'(\W+)'),
"sub3": re.compile(r'(\W+)' + q... | 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``.
:... | 2.454272 | 2.77286 | 0.885105 |
if utils.is_atomic(trigger):
return # Don't need a regexp for atomic triggers.
# Check for dynamic tags.
for tag in ["@", "<bot", "<get", "<input", "<reply"]:
if tag in trigger:
return # Can't precompile this trigger.
self._regexc["tri... | 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. | 11.210259 | 7.253312 | 1.545537 |
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 --... | def _dump(self) | For debugging, dump the entire data structure. | 3.623852 | 3.479818 | 1.041391 |
app_label = app_label or []
exclude = exclude
try:
filename = '%s.%s' % (datetime.now().isoformat(),
settings.SMUGGLER_FORMAT)
if filename_prefix:
filename = '%s_%s' % (filename_prefix, filename)
if not isinstance(app_label, list):
... | def dump_to_response(request, app_label=None, exclude=None,
filename_prefix=None) | Utility function that dumps the given app/model to an HttpResponse. | 2.888133 | 2.930256 | 0.985625 |
# 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) | def dump_data(request) | Exports data from whole project. | 4.893456 | 4.951038 | 0.98837 |
return dump_to_response(request, '%s.%s' % (app_label, model_label),
[], '-'.join((app_label, model_label))) | def dump_model_data(request, app_label, model_label) | Exports data from a model. | 4.758761 | 4.997913 | 0.95215 |
# 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_in_deps = functoo... | def toposort(data) | 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. | 2.714868 | 2.492408 | 1.089255 |
jobs = collections.defaultdict(list)
map_ = {}
_count_roots = 0
for each in sequence:
name = name_getter(each)
depends_on = depends_getter(each)
if depends_on is None:
depends_on = []
elif isinstance(depends_on, tuple):
depends_on = list(depe... | def reorder_dag(sequence,
depends_getter=lambda x: x.depends_on,
name_getter=lambda x: x.app_name,
impatience_max=100) | 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... | 2.706104 | 2.813505 | 0.961826 |
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 FrequencyDefinitionError(unit)
return number | def convert_frequency(frequency) | 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 | 2.534315 | 2.459907 | 1.030249 |
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', '... | 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.... | 2.110136 | 2.098289 | 1.005646 |
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] | def connection(self, name=None) | 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 - ... | 2.483235 | 2.629522 | 0.944367 |
if force:
try:
connection.close()
except self.operational_exceptions:
self.config.logger.error('ConnectionFactory - failed closing')
for name, conn in self.pool.iteritems():
if conn is connection:
br... | def close_connection(self, connection, force=False) | 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. | 5.9142 | 5.98591 | 0.98802 |
global restart
restart = True
if logger:
logger.info('detected SIGHUP')
raise KeyboardInterrupt | 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 resources and start running again | 7.558013 | 6.842933 | 1.104499 |
for x in self.config.backoff_delays:
yield x
while True:
yield self.config.backoff_delays[-1] | 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. | 4.036766 | 3.789641 | 1.065211 |
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)
)
self.quit_check()
... | def responsive_sleep(self, seconds, wait_reason='') | Sleep for the specified number of seconds, logging every
'wait_log_interval' seconds with progress info. | 4.191318 | 3.695032 | 1.134312 |
#----------------------------------------------------------------------
def main(self, function=None):
return super(cls, self).main(
function=function,
once=False,
)
cls.main = main
cls._is_backfill_app = True
return cls | 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. | 7.099938 | 4.8677 | 1.458582 |
def class_decorator(cls):
if not issubclass(cls, RequiredConfig):
raise Exception(
'%s must have RequiredConfig as a base class' % cls
)
new_req = cls.get_required_config()
new_req.namespace(resource_name)
new_req[resource_name].add_option... | def with_transactional_resource(
transactional_resource_class,
resource_name,
reference_value_from=None
) | 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 ... | 2.580955 | 2.177986 | 1.185019 |
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:
try:
self.run(conn... | 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 properl... | 2.874081 | 2.507461 | 1.146212 |
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,
**kwargs
)
cls... | 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 automa... | 3.743179 | 3.203236 | 1.168562 |
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,
stderr=subprocess.PIPE
... | 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 ... | 2.458455 | 2.598838 | 0.945983 |
# -------------------------------------------------------------------------
def class_list_converter(class_list_str):
if isinstance(class_list_str, basestring):
class_str_list = list_splitter_fn(class_list_str)
else:
raise TypeError('must be derivative of a... | 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 -
... | 4.868441 | 4.607664 | 1.056596 |
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) | def check_time(value) | check that it's a value like 03:45 or 1:1 | 2.749581 | 2.574566 | 1.067978 |
keys = []
for app_name, __ in self.items():
keys.append(app_name)
return keys | def keys(self) | return a list of all app_names | 6.593217 | 3.648228 | 1.807238 |
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):
row = dict(zip... | def items(self) | return all the app_names and their values as tuples | 5.719155 | 5.131842 | 1.114445 |
values = []
for __, data in self.items():
values.append(data)
return values | def values(self) | return a list of all state values | 7.302443 | 6.575048 | 1.11063 |
try:
popped = self[key]
del self[key]
return popped
except KeyError:
if default == _marker:
raise
return default | 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 | 2.552719 | 2.772981 | 0.920568 |
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 not info.get('error_count', 0):
... | def nagios(self, stream=sys.stdout) | 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. | 3.607468 | 3.204964 | 1.125588 |
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.__na... | 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. | 4.066773 | 4.050658 | 1.003978 |
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()
... | 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. | 7.192078 | 6.620088 | 1.086402 |
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:"
)
... | def audit_ghosts(self) | compare the list of configured jobs with the jobs in the state | 7.962033 | 6.37208 | 1.249519 |
'''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 = {'Gra... | 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) | 4.014184 | 3.2656 | 1.229233 |
'''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 nam... | 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. | 3.848473 | 2.732591 | 1.40836 |
'''Export the grammar to a c (source and header) file which can be
used with the libcleri module.'''
language = []
indent = 0
enums = set()
for name in self._order:
elem = getattr(self, name, None)
if not isinstance(elem, Element):
... | def export_c(self, target=C_TARGET, c_indent=C_INDENTATION, headerf=None) | Export the grammar to a c (source and header) file which can be
used with the libcleri module. | 3.316917 | 2.905909 | 1.141439 |
'''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 ... | 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. | 3.866647 | 3.453638 | 1.119587 |
'''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... | 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. | 3.604568 | 3.310352 | 1.088878 |
'''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 ... | 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... | 5.614425 | 3.186542 | 1.761918 |
'''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 == w and hf =... | def figure_buffer(figs) | Extract raw image buffer from matplotlib figure shaped as 1xHxWx3. | 3.494088 | 2.786145 | 1.254094 |
'''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 a... | 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 `**k... | 5.83558 | 2.360308 | 2.472381 |
'''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 positiona... | 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 argum... | 4.775105 | 1.940716 | 2.460487 |
'''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) for x in range(10)],
normaliz... | def draw_confusion_matrix(matrix) | Draw confusion matrix for MNIST. | 4.339793 | 4.262045 | 1.018242 |
'''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 predicte... | 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
predicitions: array-like
1-D array of predicted label... | 4.259282 | 1.479334 | 2.879188 |
'''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 s... | 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 c... | 2.21572 | 1.771724 | 1.250602 |
'''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 py... | 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 their respective thread, avoid usage
of pyplot wh... | 11.363073 | 1.978555 | 5.743117 |
'''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 p... | 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 in their respective thread, avoid usage
of pyplot w... | 10.301718 | 1.639459 | 6.283608 |
'''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 decorator | def vararg_decorator(f) | Decorator to handle variable argument decorators. | 2.267784 | 2.191112 | 1.034993 |
'''Ensure `x` is of list type.'''
if x is None:
x = []
elif not isinstance(x, Sequence):
x = [x]
return list(x) | def as_list(x) | Ensure `x` is of list type. | 4.752945 | 3.880027 | 1.224977 |
return self._all("/photos", page=page, per_page=per_page, order_by=order_by) | 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, oldest, p... | 3.62319 | 4.668186 | 0.776145 |
return self._all("/photos/curated", page=page, per_page=per_page, order_by=order_by) | def curated(self, page=1, per_page=10, order_by="latest") | 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... | 3.533393 | 4.194048 | 0.842478 |
url = "/photos/%s" % photo_id
params = {
"w": width,
"h": height,
"rect": rect
}
result = self._get(url, params=params)
return PhotoModel.parse(result) | 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... | 2.624439 | 3.082208 | 0.85148 |
if orientation and orientation not in self.orientation_values:
raise Exception()
params = {
"query": query,
"category": category,
"orientation": orientation,
"page": page,
"per_page": per_page
}
url = "/phot... | def search(self, query, category=None, orientation=None, page=1, per_page=10) | 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... | 2.585784 | 2.874911 | 0.899431 |
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)
return PhotoModel.parse_list(r... | 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
... | 4.799821 | 5.443544 | 0.881746 |
url = "/photos/%s/stats" % photo_id
result = self._get(url)
return StatModel.parse(result) | def stats(self, photo_id) | Retrieve a single photo’s stats.
:param photo_id [string]: The photo’s ID. Required.
:return: [Stat]: The Unsplash Stat. | 4.845396 | 5.605718 | 0.864367 |
url = "/photos/%s/like" % photo_id
result = self._post(url)
return PhotoModel.parse(result) | 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.
:return: [Photo]: The Un... | 4.827891 | 6.127779 | 0.78787 |
url = "/photos/%s/like" % photo_id
result = self._delete(url)
return PhotoModel.parse(result) | def unlike(self, photo_id) | 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. | 5.439919 | 6.538984 | 0.831921 |
url = "/search/photos"
data = self._search(url, query, page=page, per_page=per_page)
data["results"] = PhotoModel.parse_list(data.get("results"))
return data | 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're... | 3.635824 | 4.303938 | 0.844767 |
url = "/search/collections"
data = self._search(url, query, page=page, per_page=per_page)
data["results"] = CollectionModel.parse_list(data.get("results"))
return data | 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,... | 3.495455 | 4.367547 | 0.800324 |
url = "/search/users"
data = self._search(url, query, page=page, per_page=per_page)
data["results"] = UserModel.parse_list(data.get("results"))
return data | 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'res... | 3.530472 | 4.319467 | 0.81734 |
url = "/collections"
result = self._all(url, page=page, per_page=per_page)
return CollectionModel.parse_list(result) | 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 Collection list. | 4.78857 | 7.701532 | 0.621769 |
url = "/collections/%s" % collection_id
result = self._get(url)
return CollectionModel.parse(result) | def get(self, collection_id) | 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. | 4.250257 | 5.862103 | 0.72504 |
url = "/collections/curated/%s" % collection_id
result = self._get(url)
return CollectionModel.parse(result) | def get_curated(self, collection_id) | 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. | 4.822125 | 5.827289 | 0.827507 |
url = "/collections/%s/photos" % collection_id
result = self._all(url, page=page, per_page=per_page)
return PhotoModel.parse_list(result) | def photos(self, collection_id, page=1, per_page=10) | 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 ... | 3.285038 | 4.497841 | 0.730359 |
url = "/collections/%s/related" % collection_id
result = self._get(url)
return CollectionModel.parse_list(result) | 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. | 4.184189 | 5.304809 | 0.788754 |
url = "/collections"
data = {
"title": title,
"description": description,
"private": private
}
result = self._post(url, data=data)
return CollectionModel.parse(result) | 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; defa... | 2.924744 | 3.069819 | 0.952742 |
url = "/collections/%s" % collection_id
data = {
"title": title,
"description": description,
"private": private
}
result = self._put(url, data=data)
return CollectionModel.parse(result) | 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 descrip... | 2.457472 | 2.842366 | 0.864587 |
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")), PhotoModel.parse(result.get("photo")) | def add_photo(self, collection_id, photo_id) | 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.
... | 3.192271 | 3.225418 | 0.989723 |
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("collection")), PhotoModel.parse(result.get("photo")... | def remove_photo(self, collection_id, photo_id) | 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 | 3.432508 | 3.401023 | 1.009258 |
url = "/stats/total"
result = self._get(url)
return StatModel.parse(result) | def total(self) | Get a list of counts for all of Unsplash
:return [Stat]: The Unsplash Stat. | 10.275427 | 8.343451 | 1.231556 |
url = "/stats/month"
result = self._get(url)
return StatModel.parse(result) | def month(self) | Get the overall Unsplash stats for the past 30 days.
:return [Stat]: The Unsplash Stat. | 11.911716 | 8.637425 | 1.379082 |
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_token") | def get_access_token(self, code) | Getting access token
:param code [string]: The authorization code supplied to the callback by Unsplash.
:return [string]: access token | 2.005922 | 2.04579 | 0.980512 |
self.token = self.oauth.refresh_token(self.access_token_url, refresh_token=self.get_refresh_token())
self.access_token = self.token.get("access_token") | def refresh_token(self) | Refreshing the current expired access token | 2.895343 | 2.656019 | 1.090106 |
results = ResultSet()
data = data or []
for obj in data:
if obj:
results.append(cls.parse(obj))
return results | def parse_list(cls, data) | Parse a list of JSON objects into a result set of model instances. | 5.257157 | 4.021045 | 1.307411 |
if self.api.is_authenticated:
return {"Authorization": "Bearer %s" % self.api.access_token}
return {"Authorization": "Client-ID %s" % self.api.client_id} | def get_auth_header(self) | Getting the authorization header according to the authentication procedure
:return [dict]: Authorization header | 3.073715 | 3.443369 | 0.892648 |
url = "/me"
result = self._get(url)
return UserModel.parse(result) | 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 retur... | 8.278644 | 10.771361 | 0.768579 |
url = "/me"
result = self._put(url, data=kwargs)
return UserModel.parse(result) | 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.
:param last_name [string]:... | 7.966214 | 10.506416 | 0.758224 |
url = "/users/{username}".format(username=username)
params = {
"w": width,
"h": height
}
result = self._get(url, params=params)
return UserModel.parse(result) | 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.
... | 2.817073 | 3.643486 | 0.773181 |
url = "/users/{username}/portfolio".format(username=username)
result = self._get(url)
return LinkModel.parse(result) | def portfolio(self, username) | Retrieve a single user’s portfolio link.
:param username [string]: The user’s username. Required.
:return: [Link]: The Unsplash Link. | 5.693296 | 5.241553 | 1.086185 |
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) | 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... | 2.72764 | 4.06399 | 0.671173 |
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) | 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 ... | 2.321783 | 2.892109 | 0.802799 |
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("".... | def wrap(self, width) | Returns a partition of the string based on `width` | 2.506304 | 2.435035 | 1.029268 |
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,
offset + se... | def max_table_width(self) | 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. | 3.389705 | 3.485853 | 0.972417 |
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 = HeaderData(self, header)
self._column_ali... | 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 | 2.684822 | 2.811851 | 0.954824 |
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 ValueError(error_msg)
... | 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.... | 1.62127 | 1.650234 | 0.982448 |
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_width... | def _calculate_column_widths(self) | Calculate width of column automatically based on data. | 2.996078 | 2.976904 | 1.006441 |
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(index), reverse=reverse) | def sort(self, key, reverse=False) | 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. | 2.766126 | 2.770911 | 0.998273 |
try:
index = self._column_headers.index(header)
return index
except ValueError:
raise_suppressed(KeyError(("'{}' is not a header for any "
"column").format(header))) | 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`. | 5.565202 | 5.879187 | 0.946594 |
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 iter(map(o... | 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`... | 2.91275 | 2.879068 | 1.011699 |
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 {}").format(type(index).__name__))
... | def pop_column(self, index=-1) | 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... | 3.043366 | 3.136164 | 0.97041 |
row = self._validate_row(row)
row_obj = RowData(self, row)
self._table.insert(index, row_obj) | 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:
... | 4.917278 | 5.927687 | 0.829544 |
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 value:
row_ = self... | def update_row(self, key, value) | 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... | 2.871011 | 2.793744 | 1.027657 |
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 | def update_column(self, header, column) | 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... | 3.798776 | 4.248832 | 0.894075 |
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_lengt... | 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 ... | 3.031164 | 2.906493 | 1.042894 |
self.insert_column(self._column_count, header, column) | 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. | 5.962851 | 7.82809 | 0.761725 |
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 li... | 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.
Parameter... | 2.489995 | 2.505764 | 0.993707 |
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.right_border_char)
ret... | 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. | 3.324996 | 3.415832 | 0.973408 |
# 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 recal... | 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 ,... | 3.138922 | 3.050878 | 1.028858 |
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 a... | 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. | 4.26362 | 4.263642 | 0.999995 |
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
return to_unicode(item) | def get_output_str(item, detect_numerics, precision, sign_value) | Returns the final string which should be displayed | 3.001793 | 2.919426 | 1.028213 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.