code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
e = driver.find_elements_by_locator(locator)
if len(e) == 0:
raise AssertionError("Element at %s was not found" % locator)
assert e.is_displayed() | def assert_visible(self, locator, msg=None) | Hard assert for whether and element is present and visible in the current window/frame
:params locator: the locator of the element to search for
:params msg: (Optional) msg explaining the difference | 3.940244 | 4.30381 | 0.915525 |
try:
self.assert_visible(locator, msg)
except AssertionError, e:
if msg:
m = "%s:\n%s" % (msg, str(e))
else:
m = str(e)
self.verification_erorrs.append(m) | def verify_visible(self, locator, msg=None) | Soft assert for whether and element is present and visible in the current window/frame
:params locator: the locator of the element to search for
:params msg: (Optional) msg explaining the difference | 3.033604 | 3.512952 | 0.863548 |
if self._wrapped is not self.Null:
return self._wrapped
else:
return self.object | def obj(self) | Returns passed object but if chain method is used
returns the last processed result | 10.071054 | 7.848972 | 1.283105 |
if self.chained:
self._wrapped = ret
return self
else:
return ret | def _wrap(self, ret) | Returns result but ig chain method is used
returns the object itself so we can chain | 7.29267 | 4.593509 | 1.587603 |
if self._clean.isTuple():
return tuple(val)
elif self._clean.isList():
return list(val)
elif self._clean.isDict():
return dict(val)
else:
return val | def _toOriginal(self, val) | Pitty attempt to convert itertools result into a real object | 2.977014 | 2.765453 | 1.076502 |
if self._clean.isTuple() or self._clean.isList():
for index, value in enumerate(self.obj):
r = func(value, index, self.obj)
if r is "breaker":
break
else:
for index, key in enumerate(self.obj):
r = func(... | def each(self, func) | iterates through each item of an object
:Param: func iterator function | 3.722819 | 3.738662 | 0.995763 |
ns = self.Namespace()
ns.results = []
def by(value, index, list, *args):
ns.results.append(func(value, index, list))
_(self.obj).each(by)
return self._wrap(ns.results) | def map(self, func) | Return the results of applying the iterator to each element. | 6.822058 | 6.102446 | 1.117922 |
if memo is None:
memo = []
ns = self.Namespace()
ns.initial = True # arguments.length > 2
ns.memo = memo
obj = self.obj
def by(value, index, *args):
if not ns.initial:
ns.memo = value
ns.initial = True
... | def reduce(self, func, memo=None) | **Reduce** builds up a single result from a list of values,
aka `inject`, or foldl | 6.14505 | 6.048188 | 1.016015 |
#foldr = lambda f, i: lambda s: reduce(f, s, i)
x = self.obj[:]
x.reverse()
return self._wrap(functools.reduce(func, x)) | def reduceRight(self, func) | The right-associative version of reduce, also known as `foldr`. | 6.346898 | 5.744263 | 1.104911 |
self.ftmp = None
def test(value, index, list):
if func(value, index, list) is True:
self.ftmp = value
return True
self._clean.any(test)
return self._wrap(self.ftmp) | def find(self, func) | Return the first value which passes a truth test.
Aliased as `detect`. | 6.292248 | 5.563151 | 1.131058 |
return self._wrap(list(filter(func, self.obj))) | def filter(self, func) | Return all the elements that pass a truth test. | 9.369148 | 7.351435 | 1.274465 |
return self._wrap(list(filter(lambda val: not func(val), self.obj))) | def reject(self, func) | Return all the elements for which a truth test fails. | 9.038474 | 6.901012 | 1.309732 |
if func is None:
func = lambda x, *args: x
self.altmp = True
def testEach(value, index, *args):
if func(value, index, *args) is False:
self.altmp = False
self._clean.each(testEach)
return self._wrap(self.altmp) | def all(self, func=None) | Determine whether all of the elements match a truth test. | 5.765222 | 5.341162 | 1.079395 |
if func is None:
func = lambda x, *args: x
self.antmp = False
def testEach(value, index, *args):
if func(value, index, *args) is True:
self.antmp = True
return "breaker"
self._clean.each(testEach)
return self._wra... | def any(self, func=None) | Determine if at least one element in the object
matches a truth test. | 6.33708 | 5.88212 | 1.077346 |
if self._clean.isDict():
return self._wrap(target in self.obj.values())
else:
return self._wrap(target in self.obj) | def include(self, target) | Determine if a given value is included in the
array or object using `is`. | 9.574404 | 7.635115 | 1.253996 |
def inv(value, *ar):
if (
_(method).isFunction() or
_(method).isLambda() or
_(method).isMethod()
):
return method(value, *args)
else:
return getattr(value, method)(*args)
return s... | def invoke(self, method, *args) | Invoke a method (with arguments) on every item in a collection. | 6.28377 | 5.852427 | 1.073703 |
return self._wrap([x.get(key) for x in self.obj]) | def pluck(self, key) | Convenience version of a common use case of
`map`: fetching a property. | 9.358568 | 8.981866 | 1.04194 |
if attrs is None:
return None if first is True else []
method = _.find if first else _.filter
def by(val, *args):
for key, value in attrs.items():
try:
if attrs[key] != val[key]:
return False
... | def where(self, attrs=None, first=False) | Convenience version of a common use case of `filter`:
selecting only objects
containing specific `key:value` pairs. | 5.988352 | 5.466702 | 1.095423 |
return self._wrap(self._clean.where(attrs, True)) | def findWhere(self, attrs=None) | Convenience version of a common use case of `find`:
getting the first object
containing specific `key:value` pairs. | 20.956257 | 17.47064 | 1.199513 |
if(self._clean.isDict()):
return self._wrap(list())
return self._wrap(max(self.obj)) | def max(self) | Return the maximum element or (element-based computation). | 21.004732 | 17.347206 | 1.210842 |
if(self._clean.isDict()):
return self._wrap(list())
return self._wrap(min(self.obj)) | def min(self) | Return the minimum element (or element-based computation). | 21.07571 | 18.145407 | 1.16149 |
if(self._clean.isDict()):
return self._wrap(list())
cloned = self.obj[:]
random.shuffle(cloned)
return self._wrap(cloned) | def shuffle(self) | Shuffle an array. | 16.133789 | 13.650267 | 1.181939 |
if val is not None:
if _(val).isString():
return self._wrap(sorted(self.obj, key=lambda x,
*args: x.get(val)))
else:
return self._wrap(sorted(self.obj, key=val))
else:
return self._wrap(sorted(... | def sortBy(self, val=None) | Sort the object's values by a criterion produced by an iterator. | 3.581129 | 3.468668 | 1.032422 |
if val is None:
return lambda el, *args: el
return val if _.isCallable(val) else lambda obj, *args: obj[val] | def _lookupIterator(self, val) | An internal function to generate lookup iterators. | 9.787201 | 8.560502 | 1.143298 |
ns = self.Namespace()
ns.result = {}
iterator = self._lookupIterator(val)
def e(value, index, *args):
key = iterator(value, index)
behavior(ns.result, key, value)
_.each(obj, e)
if len(ns.result) == 1:
try:
r... | def _group(self, obj, val, behavior) | An internal function used for aggregate "group by" operations. | 4.582375 | 4.410205 | 1.039039 |
def by(result, key, value):
if key not in result:
result[key] = []
result[key].append(value)
res = self._group(self.obj, val, by)
return self._wrap(res) | def groupBy(self, val) | Groups the object's values by a criterion. Pass either a string
attribute to group by, or a function that returns the criterion. | 4.653358 | 4.815334 | 0.966362 |
if val is None:
val = lambda *args: args[0]
def by(result, key, value):
result[key] = value
res = self._group(self.obj, val, by)
return self._wrap(res) | def indexBy(self, val=None) | Indexes the object's values by a criterion, similar to
`groupBy`, but for when you know that your index values will be unique. | 5.323832 | 5.097597 | 1.044381 |
def by(result, key, value):
if key not in result:
result[key] = 0
result[key] += 1
res = self._group(self.obj, val, by)
return self._wrap(res) | def countBy(self, val) | Counts instances of an object that group by a certain criterion. Pass
either a string attribute to count by, or a function that returns the
criterion. | 5.513711 | 5.638828 | 0.977812 |
array = self.obj
value = iterator(obj)
low = 0
high = len(array)
while low < high:
mid = (low + high) >> 1
if iterator(array[mid]) < value:
low = mid + 1
else:
high = mid
return self._wrap(low) | def sortedIndex(self, obj, iterator=lambda x: x) | Use a comparator function to figure out the smallest index at which
an object should be inserted so as to maintain order.
Uses binary search. | 2.35244 | 2.387101 | 0.98548 |
res = self.obj[0:n]
if len(res) is 1:
res = res[0]
return self._wrap(res) | def first(self, n=1) | Get the first element of an array. Passing **n** will return the
first N values in the array. Aliased as `head` and `take`.
The **guard** check allows it to work with `_.map`. | 4.740012 | 4.661485 | 1.016846 |
res = self.obj[-n:]
if len(res) is 1:
res = res[0]
return self._wrap(res) | def last(self, n=1) | Get the last element of an array. Passing **n** will return the last N
values in the array.
The **guard** check allows it to work with `_.map`. | 5.035732 | 5.306141 | 0.949039 |
return self._wrap(self._flatten(self.obj, shallow)) | def flatten(self, shallow=None) | Return a completely flattened version of an array. | 12.87281 | 9.276659 | 1.387656 |
if self._clean.isDict():
newlist = {}
for i, k in enumerate(self.obj):
# if k not in values: # use indexof to check identity
if _(values).indexOf(k) is -1:
newlist.set(k, self.obj[k])
else:
newlist = []
... | def without(self, *values) | Return a version of the array that does not
contain the specified value(s). | 3.945566 | 3.860344 | 1.022076 |
predicate = self._lookupIterator(predicate)
pass_list = []
fail_list = []
def by(elem, index, *args):
(pass_list if predicate(elem) else fail_list).append(elem)
_.each(self.obj, by)
return self._wrap([pass_list, fail_list]) | def partition(self, predicate=None) | Split an array into two arrays: one whose elements all satisfy the given
predicate, and one whose elements all do not satisfy the predicate. | 6.012999 | 5.841487 | 1.029361 |
ns = self.Namespace()
ns.results = []
ns.array = self.obj
initial = self.obj
if iterator is not None:
initial = _(ns.array).map(iterator)
def by(memo, value, index):
if ((_.last(memo) != value or
not len(memo)) if isSorte... | def uniq(self, isSorted=False, iterator=None) | Produce a duplicate-free version of the array. If the array has already
been sorted, you have the option of using a faster algorithm.
Aliased as `unique`. | 6.672964 | 6.458734 | 1.033169 |
# setobj = set(self.obj)
# for i, v in enumerate(args):
# setobj = setobj + set(args[i])
# return self._wrap(self._clean._toOriginal(setobj))
args = list(args)
args.insert(0, self.obj)
return self._wrap(_.uniq(self._flatten(args, True, []))) | def union(self, *args) | Produce an array that contains the union: each distinct element
from all of the passed-in arrays. | 6.208266 | 5.805307 | 1.069412 |
if type(self.obj[0]) is int:
a = self.obj
else:
a = tuple(self.obj[0])
setobj = set(a)
for i, v in enumerate(args):
setobj = setobj & set(args[i])
return self._wrap(list(setobj)) | def intersection(self, *args) | Produce an array that contains every item shared between all the
passed-in arrays. | 3.660952 | 3.711827 | 0.986294 |
setobj = set(self.obj)
for i, v in enumerate(args):
setobj = setobj - set(args[i])
return self._wrap(self._clean._toOriginal(setobj)) | def difference(self, *args) | Take the difference between one array and a number of other arrays.
Only the elements present in just the first array will remain. | 7.454638 | 6.66956 | 1.117711 |
args = list(args)
args.insert(0, self.obj)
maxLen = _(args).chain().collect(lambda x, *args: len(x)).max().value()
for i, v in enumerate(args):
l = len(args[i])
if l < maxLen:
args[i]
for x in range(maxLen - l):
... | def zip(self, *args) | Zip together multiple lists into a single array -- elements that share
an index go together. | 3.90765 | 4.101497 | 0.952738 |
result = {}
keys = self.obj
i = 0
l = len(keys)
while i < l:
result[keys[i]] = values[i]
l = len(keys)
i += 1
return self._wrap(result) | def zipObject(self, values) | Zip together two arrays -- an array of keys and an array
of values -- into a single object. | 3.721939 | 3.628123 | 1.025858 |
array = self.obj
ret = -1
if not (self._clean.isList() or self._clean.isTuple()):
return self._wrap(-1)
if isSorted:
i = _.sortedIndex(array, item)
ret = i if array[i] is item else -1
else:
i = 0
l = len(array... | def indexOf(self, item, isSorted=False) | Return the position of the first occurrence of an
item in an array, or -1 if the item is not included in the array. | 3.602257 | 3.505952 | 1.027469 |
array = self.obj
i = len(array) - 1
if not (self._clean.isList() or self._clean.isTuple()):
return self._wrap(-1)
while i > -1:
if array[i] is item:
return self._wrap(i)
i -= 1
return self._wrap(-1) | def lastIndexOf(self, item) | Return the position of the last occurrence of an
item in an array, or -1 if the item is not included in the array. | 4.077355 | 4.123774 | 0.988744 |
args = list(args)
args.insert(0, self.obj)
return self._wrap(range(*args)) | def range(self, *args) | Generate an integer Array containing an arithmetic progression. | 5.076265 | 5.012343 | 1.012753 |
def part(*args2):
args3 = args + args2
return self.obj(*args3)
return self._wrap(part) | def partial(self, *args) | Partially apply a function by creating a version that has had some of
its arguments pre-filled, without changing its dynamic `this` context. | 9.481196 | 7.660288 | 1.237708 |
ns = self.Namespace()
ns.memo = {}
if hasher is None:
hasher = lambda x: x
def memoized(*args, **kwargs):
key = hasher(*args)
if key not in ns.memo:
ns.memo[key] = self.obj(*args, **kwargs)
return ns.memo[key]
... | def memoize(self, hasher=None) | Memoize an expensive function by storing its results. | 2.682381 | 2.584208 | 1.03799 |
def call_it():
self.obj(*args)
t = Timer((float(wait) / float(1000)), call_it)
t.start()
return self._wrap(self.obj) | def delay(self, wait, *args) | Delays a function for the given number of milliseconds, and then calls
it with the arguments supplied. | 6.642484 | 7.754992 | 0.856543 |
ns = self.Namespace()
ns.timeout = None
ns.throttling = None
ns.more = None
ns.result = None
def done():
ns.more = ns.throttling = False
whenDone = _.debounce(done, wait)
wait = (float(wait) / float(1000))
def throttled(*arg... | def throttle(self, wait) | Returns a function, that, when invoked, will only be triggered
at most once during a given window of time. | 3.337758 | 3.212564 | 1.03897 |
wait = (float(wait) / float(1000))
def debounced(*args, **kwargs):
def call_it():
self.obj(*args, **kwargs)
try:
debounced.t.cancel()
except(AttributeError):
pass
debounced.t = Timer(wait, call_it)
... | def debounce(self, wait, immediate=None) | Returns a function, that, as long as it continues to be invoked,
will not be triggered. The function will be called after it stops
being called for N milliseconds. If `immediate` is passed, trigger
the function on the leading edge, instead of the trailing. | 2.906365 | 2.893073 | 1.004594 |
ns = self.Namespace()
ns.memo = None
ns.run = False
def work_once(*args, **kwargs):
if ns.run is False:
ns.memo = self.obj(*args, **kwargs)
ns.run = True
return ns.memo
return self._wrap(work_once) | def once(self) | Returns a function that will be executed at most one time,
no matter how often you call it. Useful for lazy initialization. | 5.00855 | 4.189365 | 1.195539 |
def wrapped(*args, **kwargs):
if kwargs:
kwargs["object"] = self.obj
else:
args = list(args)
args.insert(0, self.obj)
return wrapper(*args, **kwargs)
return self._wrap(wrapped) | def wrap(self, wrapper) | Returns the first function passed as an argument to the second,
allowing you to adjust arguments, run code before and after, and
conditionally execute the original function. | 3.644989 | 3.983838 | 0.914944 |
args = list(args)
def composed(*ar, **kwargs):
lastRet = self.obj(*ar, **kwargs)
for i in args:
lastRet = i(lastRet)
return lastRet
return self._wrap(composed) | def compose(self, *args) | Returns a function that is the composition of a list of functions, each
consuming the return value of the function that follows. | 5.830822 | 6.255975 | 0.932041 |
ns = self.Namespace()
ns.times = self.obj
if ns.times <= 0:
return func()
def work_after(*args):
if ns.times <= 1:
return func(*args)
ns.times -= 1
return self._wrap(work_after) | def after(self, func) | Returns a function that will only be executed after being
called N times. | 6.188241 | 5.341703 | 1.158477 |
keys = self._clean.keys()
pairs = []
for key in keys:
pairs.append([key, self.obj[key]])
return self._wrap(pairs) | def pairs(self) | Convert an object into a list of `[key, value]` pairs. | 6.716679 | 5.230522 | 1.284132 |
keys = self._clean.keys()
inverted = {}
for key in keys:
inverted[self.obj[key]] = key
return self._wrap(inverted) | def invert(self) | Invert the keys and values of an object.
The values must be serializable. | 7.965394 | 7.003006 | 1.137425 |
names = []
for i, k in enumerate(self.obj):
if _(self.obj[k]).isCallable():
names.append(k)
return self._wrap(sorted(names)) | def functions(self) | Return a sorted list of the function names available on the object. | 7.80991 | 5.746208 | 1.359142 |
args = list(args)
for i in args:
self.obj.update(i)
return self._wrap(self.obj) | def extend(self, *args) | Extend a given object with all the properties in
passed-in object(s). | 5.698836 | 6.250017 | 0.911811 |
ns = self.Namespace()
ns.result = {}
def by(key, *args):
if key in self.obj:
ns.result[key] = self.obj[key]
_.each(self._flatten(args, True, []), by)
return self._wrap(ns.result) | def pick(self, *args) | Return a copy of the object only containing the
whitelisted properties. | 7.017612 | 6.722476 | 1.043903 |
ns = self.Namespace
ns.obj = self.obj
def by(source, *ar):
for i, prop in enumerate(source):
if prop not in ns.obj:
ns.obj[prop] = source[prop]
_.each(args, by)
return self._wrap(ns.obj) | def defaults(self, *args) | Fill in a given object with default properties. | 8.202147 | 6.680414 | 1.22779 |
interceptor(self.obj)
return self._wrap(self.obj) | def tap(self, interceptor) | Invokes interceptor with the obj, and then returns obj.
The primary purpose of this method is to "tap into" a method chain, in
order to perform operations on intermediate results within the chain. | 12.006345 | 14.75617 | 0.813649 |
if self.obj is None:
return True
if self._clean.isString():
ret = self.obj.strip() is ""
elif self._clean.isDict():
ret = len(self.obj.keys()) == 0
else:
ret = len(self.obj) == 0
return self._wrap(ret) | def isEmpty(self) | Is a given array, string, or object empty?
An "empty" object has no enumerable own-properties. | 3.928168 | 3.774388 | 1.040743 |
try:
filetype = file
except NameError:
filetype = io.IOBase
return self._wrap(type(self.obj) is filetype) | def isFile(self) | Check if the given object is a file | 9.194091 | 8.456093 | 1.087274 |
j = glue.join([str(x) for x in self.obj])
return self._wrap(j) | def join(self, glue=" ") | Javascript's join implementation | 5.839747 | 4.582663 | 1.274313 |
def ret(obj, *args):
if self.obj is obj:
return True # avoid comparing an object to itself.
for key in self.obj:
if self.obj[key] != obj[key]:
return False
return True
return self._wrap(ret) | def matches(self) | Returns a predicate for checking whether an object has a given
set of `key:value` pairs. | 6.022213 | 5.304815 | 1.135235 |
n = self.obj
i = 0
while n is not 0:
n -= 1
func(i)
i += 1
return self._wrap(func) | def times(self, func, *args) | Run a function **n** times. | 6.475897 | 5.88789 | 1.099867 |
min_number = self.obj
if max_number is None:
min_number = 0
max_number = self.obj
return random.randrange(min_number, max_number) | def random(self, max_number=None) | Return a random integer between min and max (inclusive). | 3.157543 | 2.812459 | 1.122698 |
if self.obj is None:
return self._wrap(self.obj)
if(hasattr(self.obj, property)):
value = getattr(self.obj, property)
else:
value = self.obj.get(property)
if _.isCallable(value):
return self._wrap(value(*args))
return self... | def result(self, property, *args) | If the value of the named property is a function then invoke it;
otherwise, return it. | 3.269439 | 3.025224 | 1.080726 |
methods = self.obj
for i, k in enumerate(methods):
setattr(underscore, k, methods[k])
self.makeStatic()
return self._wrap(self.obj) | def mixin(self) | Add your own custom functions to the Underscore object, ensuring that
they're correctly added to the OOP wrapper as well. | 11.888329 | 7.679927 | 1.547974 |
_IdCounter.count += 1
id = _IdCounter.count
if prefix:
return self._wrap(prefix + str(id))
else:
return self._wrap(id) | def uniqueId(self, prefix="") | Generate a unique integer id (unique within the entire client session).
Useful for temporary DOM ids. | 4.73683 | 4.730753 | 1.001285 |
# & must be handled first
self.obj = self.obj.replace("&", self._html_escape_table["&"])
for i, k in enumerate(self._html_escape_table):
v = self._html_escape_table[k]
if k is not "&":
self.obj = self.obj.replace(k, v)
return self._wrap(... | def escape(self) | Escape a string for HTML interpolation. | 3.795914 | 3.609578 | 1.051623 |
for i, k in enumerate(self._html_escape_table):
v = self._html_escape_table[k]
self.obj = self.obj.replace(v, k)
return self._wrap(self.obj) | def unescape(self) | Within an interpolation, evaluation, or escaping, remove HTML escaping
that had been previously added. | 4.327175 | 3.868368 | 1.118605 |
if self._wrapped is not self.Null:
return self._wrapped
else:
return self.obj | def value(self) | returns the object instead of instance | 10.900095 | 6.840208 | 1.593533 |
p = lambda value: inspect.ismethod(value) or inspect.isfunction(value)
for eachMethod in inspect.getmembers(underscore,
predicate=p):
m = eachMethod[0]
if not hasattr(_, m):
def caller(a):
d... | def makeStatic() | Provide static access to underscore class | 4.959483 | 4.639063 | 1.06907 |
global _users, _names
_configure_app(app)
_users, _names = _init_login_manager(app)
_configure_logger()
init_scheduler(app.config.get('SQLALCHEMY_DATABASE_URI'))
db.init(app.config.get('SQLALCHEMY_DATABASE_URI')) | def init() | Initialise and configure the app, database, scheduler, etc.
This should be called once at application startup or at tests startup
(and not e.g. called once for each test case). | 4.780658 | 4.786073 | 0.998869 |
app_.url_map.strict_slashes = False
app_.config.from_object(default_settings)
app_.config.from_envvar('JOB_CONFIG', silent=True)
db_url = app_.config.get('SQLALCHEMY_DATABASE_URI')
if not db_url:
raise Exception('No db_url in config')
app_.wsgi_app = ProxyFix(app_.wsgi_app)
glo... | def _configure_app(app_) | Configure the Flask WSGI app. | 2.522508 | 2.49049 | 1.012856 |
login_manager = flogin.LoginManager()
login_manager.setup_app(app_)
login_manager.anonymous_user = Anonymous
login_manager.login_view = "login"
users = {app_.config['USERNAME']: User('Admin', 0)}
names = dict((int(v.get_id()), k) for k, v in users.items())
@login_manager.user_loader
... | def _init_login_manager(app_) | Initialise and configure the login manager. | 3.025921 | 3.015189 | 1.003559 |
stderr_handler = logging.StreamHandler(sys.stderr)
stderr_handler.setLevel(logging.INFO)
if 'STDERR' in app.config:
logger.addHandler(stderr_handler)
file_handler = logging.handlers.RotatingFileHandler(
app.config.get('LOG_FILE'), maxBytes=67108864, backupCount=5)
file_handler.... | def _configure_logger_for_production(logger) | Configure the given logger for production deployment.
Logs to stderr and file, and emails errors to admins. | 2.015167 | 1.939182 | 1.039184 |
if not app.debug:
_configure_logger_for_production(logging.getLogger())
elif not app.testing:
_configure_logger_for_debugging(logging.getLogger()) | def _configure_logger() | Configure the logging module. | 4.000275 | 3.767385 | 1.061817 |
global scheduler
scheduler = apscheduler.Scheduler()
scheduler.misfire_grace_time = 3600
scheduler.add_jobstore(
sqlalchemy_store.SQLAlchemyJobStore(url=db_uri), 'default')
scheduler.add_listener(
job_listener,
events.EVENT_JOB_EXECUTED | events.EVENT_JOB_MISSED
... | def init_scheduler(db_uri) | Initialise and configure the scheduler. | 3.031032 | 2.934035 | 1.03306 |
'''Listens to completed job'''
job_id = event.job.args[0]
if event.code == events.EVENT_JOB_MISSED:
db.mark_job_as_missed(job_id)
elif event.exception:
if isinstance(event.exception, util.JobError):
error_object = event.exception.as_dict()
else:
error_obj... | def job_listener(event) | Listens to completed job | 3.536684 | 3.526605 | 1.002858 |
'''Show version, available job types and name of service.
**Results:**
:rtype: A dictionary with the following keys
:param version: Version of the service provider
:type version: float
:param job_types: Available job types
:type job_types: list of strings
:param name: Name of the servi... | def status() | Show version, available job types and name of service.
**Results:**
:rtype: A dictionary with the following keys
:param version: Version of the service provider
:type version: float
:param job_types: Available job types
:type job_types: list of strings
:param name: Name of the service
... | 4.137797 | 2.323579 | 1.780786 |
'''Log in as administrator
You can use wither basic auth or form based login (via POST).
:param username: The administrator's username
:type username: string
:param password: The administrator's password
:type password: string
'''
username = None
password = None
next = flask.re... | def login() | Log in as administrator
You can use wither basic auth or form based login (via POST).
:param username: The administrator's username
:type username: string
:param password: The administrator's password
:type password: string | 2.988912 | 2.484516 | 1.203016 |
'''Show information about the current user
:rtype: A dictionary with the following keys
:param id: User id
:type id: int
:param name: User name
:type name: string
:param is_active: Whether the user is currently active
:type is_active: bool
:param is_anonymous: The anonymous user is ... | def user() | Show information about the current user
:rtype: A dictionary with the following keys
:param id: User id
:type id: int
:param name: User name
:type name: string
:param is_active: Whether the user is currently active
:type is_active: bool
:param is_anonymous: The anonymous user is the def... | 3.026715 | 1.733129 | 1.746387 |
flogin.logout_user()
next = flask.request.args.get('next')
return flask.redirect(next or flask.url_for("user")) | def logout() | Log out the active user | 4.772773 | 4.639522 | 1.028721 |
'''List all jobs.
:param _limit: maximum number of jobs to show (default 100)
:type _limit: int
:param _offset: how many jobs to skip before showin the first one (default 0)
:type _offset: int
:param _status: filter jobs by status (complete, error)
:type _status: string
Also, you can f... | def job_list() | List all jobs.
:param _limit: maximum number of jobs to show (default 100)
:type _limit: int
:param _offset: how many jobs to skip before showin the first one (default 0)
:type _offset: int
:param _status: filter jobs by status (complete, error)
:type _status: string
Also, you can filter t... | 2.773701 | 2.05644 | 1.348787 |
'''Show a specific job.
**Results:**
:rtype: A dictionary with the following keys
:param status: Status of job (complete, error)
:type status: string
:param sent_data: Input data for job
:type sent_data: json encodable data
:param job_id: An identifier for the job
:type job_id: str... | def job_status(job_id, show_job_key=False, ignore_auth=False) | Show a specific job.
**Results:**
:rtype: A dictionary with the following keys
:param status: Status of job (complete, error)
:type status: string
:param sent_data: Input data for job
:type sent_data: json encodable data
:param job_id: An identifier for the job
:type job_id: string
... | 2.872491 | 1.416461 | 2.027935 |
'''Deletes the job together with its logs and metadata.
:param job_id: An identifier for the job
:type job_id: string
:statuscode 200: no error
:statuscode 403: not authorized to delete the job
:statuscode 404: the job could not be found
:statuscode 409: an error occurred
'''
conn ... | def job_delete(job_id) | Deletes the job together with its logs and metadata.
:param job_id: An identifier for the job
:type job_id: string
:statuscode 200: no error
:statuscode 403: not authorized to delete the job
:statuscode 404: the job could not be found
:statuscode 409: an error occurred | 2.363339 | 1.845605 | 1.280523 |
'''Clear old jobs
:param days: Jobs for how many days should be kept (default: 10)
:type days: integer
:statuscode 200: no error
:statuscode 403: not authorized to delete jobs
:statuscode 409: an error occurred
'''
if not is_authorized():
return json.dumps({'error': 'not author... | def clear_jobs() | Clear old jobs
:param days: Jobs for how many days should be kept (default: 10)
:type days: integer
:statuscode 200: no error
:statuscode 403: not authorized to delete jobs
:statuscode 409: an error occurred | 4.29598 | 2.25971 | 1.90112 |
'''Get the raw data that the job returned. The mimetype
will be the value provided in the metdata for the key ``mimetype``.
**Results:**
:rtype: string
:statuscode 200: no error
:statuscode 403: not authorized to view the job's data
:statuscode 404: job id not found
:statuscode 409: a... | def job_data(job_id) | Get the raw data that the job returned. The mimetype
will be the value provided in the metdata for the key ``mimetype``.
**Results:**
:rtype: string
:statuscode 200: no error
:statuscode 403: not authorized to view the job's data
:statuscode 404: job id not found
:statuscode 409: an error... | 3.009688 | 1.687762 | 1.783242 |
'''Returns true if the request is authorized for the job
if provided. If no job is provided, the user has to be admin
to be authorized.
'''
if flogin.current_user.is_authenticated:
return True
if job:
job_key = flask.request.headers.get('Authorization')
if job_key == app.... | def is_authorized(job=None) | Returns true if the request is authorized for the job
if provided. If no job is provided, the user has to be admin
to be authorized. | 5.140975 | 3.236541 | 1.588417 |
''' Send results to where requested.
If api_key is provided, it is used, otherwiese
the key from the job will be used.
'''
job_dict = db.get_job(job_id)
result_url = job_dict.get('result_url')
if not result_url:
# A job with an API key (for using when posting to the callback URL)
... | def send_result(job_id, api_key=None) | Send results to where requested.
If api_key is provided, it is used, otherwiese
the key from the job will be used. | 3.450896 | 2.824036 | 1.221973 |
global ENGINE, _METADATA, JOBS_TABLE, METADATA_TABLE, LOGS_TABLE
ENGINE = sqlalchemy.create_engine(uri, echo=echo, convert_unicode=True)
_METADATA = sqlalchemy.MetaData(ENGINE)
JOBS_TABLE = _init_jobs_table()
METADATA_TABLE = _init_metadata_table()
LOGS_TABLE = _init_logs_table()
_METAD... | def init(uri, echo=False) | Initialise the database.
Initialise the sqlalchemy engine, metadata and table objects that we use to
connect to the database.
Create the database and the database tables themselves if they don't
already exist.
:param uri: the sqlalchemy database URI
:type uri: string
:param echo: whether... | 2.79402 | 2.757322 | 1.013309 |
# Avoid SQLAlchemy "Unicode type received non-unicode bind param value"
# warnings.
if job_id:
job_id = unicode(job_id)
result = ENGINE.execute(
JOBS_TABLE.select().where(JOBS_TABLE.c.job_id == job_id)).first()
if not result:
return None
# Turn the result into a d... | def get_job(job_id) | Return the job with the given job_id as a dict.
The dict also includes any metadata or logs associated with the job.
Returns None instead of a dict if there's no job with the given job_id.
The keys of a job dict are:
"job_id": The unique identifier for the job (unicode)
"job_type": The name of ... | 2.977315 | 2.861408 | 1.040507 |
if not data:
data = {}
data = json.dumps(data)
# Turn strings into unicode to stop SQLAlchemy
# "Unicode type received non-unicode bind param value" warnings.
if job_id:
job_id = unicode(job_id)
if job_type:
job_type = unicode(job_type)
if result_url:
re... | def add_pending_job(job_id, job_key, job_type, api_key,
data=None, metadata=None, result_url=None) | Add a new job with status "pending" to the jobs table.
All code that adds jobs to the jobs table should go through this function.
Code that adds to the jobs table manually should be refactored to use this
function.
May raise unspecified exceptions from Python core, SQLAlchemy or JSON!
TODO: Docume... | 2.298326 | 2.250992 | 1.021028 |
if error is None:
return None
elif isinstance(error, basestring):
return {"message": error}
else:
try:
message = error["message"]
if isinstance(message, basestring):
return error
else:
raise InvalidErrorObjectEr... | def _validate_error(error) | Validate and return the given error object.
Based on the given error object, return either None or a dict with a
"message" key whose value is a string (the dict may also have any other
keys that it wants).
The given "error" object can be:
- None, in which case None is returned
- A string, in... | 2.729251 | 2.229301 | 1.224263 |
# Avoid SQLAlchemy "Unicode type received non-unicode bind param value"
# warnings.
if job_id:
job_id = unicode(job_id)
if "error" in job_dict:
job_dict["error"] = _validate_error(job_dict["error"])
job_dict["error"] = json.dumps(job_dict["error"])
# Avoid SQLAlchem... | def _update_job(job_id, job_dict) | Update the database row for the given job_id with the given job_dict.
All functions that update rows in the jobs table do it by calling this
helper function.
job_dict is a dict with values corresponding to the database columns that
should be updated, e.g.:
{"status": "complete", "data": ...} | 2.514508 | 2.446085 | 1.027973 |
update_dict = {
"status": "complete",
"data": json.dumps(data),
"finished_timestamp": datetime.datetime.now(),
}
_update_job(job_id, update_dict) | def mark_job_as_completed(job_id, data=None) | Mark a job as completed successfully.
:param job_id: the job_id of the job to be updated
:type job_id: unicode
:param data: the output data returned by the job
:type data: any JSON-serializable type (including None) | 3.354609 | 4.092496 | 0.819698 |
update_dict = {
"status": "error",
"error": error_object,
"finished_timestamp": datetime.datetime.now(),
}
_update_job(job_id, update_dict) | def mark_job_as_errored(job_id, error_object) | Mark a job as failed with an error.
:param job_id: the job_id of the job to be updated
:type job_id: unicode
:param error_object: the error returned by the job
:type error_object: either a string or a dict with a "message" key whose
value is a string | 2.903963 | 3.851664 | 0.75395 |
_jobs_table = sqlalchemy.Table(
'jobs', _METADATA,
sqlalchemy.Column('job_id', sqlalchemy.UnicodeText, primary_key=True),
sqlalchemy.Column('job_type', sqlalchemy.UnicodeText),
sqlalchemy.Column('status', sqlalchemy.UnicodeText, index=True),
sqlalchemy.Column('data', sql... | def _init_jobs_table() | Initialise the "jobs" table in the db. | 2.586735 | 2.541898 | 1.017639 |
_metadata_table = sqlalchemy.Table(
'metadata', _METADATA,
sqlalchemy.Column(
'job_id', sqlalchemy.ForeignKey("jobs.job_id", ondelete="CASCADE"),
nullable=False, primary_key=True),
sqlalchemy.Column('key', sqlalchemy.UnicodeText, primary_key=True),
sqlalc... | def _init_metadata_table() | Initialise the "metadata" table in the db. | 2.492509 | 2.436424 | 1.023019 |
_logs_table = sqlalchemy.Table(
'logs', _METADATA,
sqlalchemy.Column(
'job_id', sqlalchemy.ForeignKey("jobs.job_id", ondelete="CASCADE"),
nullable=False),
sqlalchemy.Column('timestamp', sqlalchemy.DateTime),
sqlalchemy.Column('message', sqlalchemy.Unicode... | def _init_logs_table() | Initialise the "logs" table in the db. | 2.178989 | 2.119252 | 1.028188 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.