text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def obj(self):
""" Returns passed object but if chain method is used returns the last processed result """ |
if self._wrapped is not self.Null:
return self._wrapped
else:
return self.object |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _wrap(self, ret):
""" Returns result but ig chain method is used returns the object itself so we can chain """ |
if self.chained:
self._wrapped = ret
return self
else:
return ret |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _toOriginal(self, val):
""" Pitty attempt to convert itertools result into a real object """ |
if self._clean.isTuple():
return tuple(val)
elif self._clean.isList():
return list(val)
elif self._clean.isDict():
return dict(val)
else:
return val |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def map(self, func):
""" Return the results of applying the iterator to each element. """ |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reduceRight(self, func):
""" The right-associative version of reduce, also known as `foldr`. """ |
#foldr = lambda f, i: lambda s: reduce(f, s, i)
x = self.obj[:]
x.reverse()
return self._wrap(functools.reduce(func, x)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find(self, func):
""" Return the first value which passes a truth test. Aliased as `detect`. """ |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def filter(self, func):
""" Return all the elements that pass a truth test. """ |
return self._wrap(list(filter(func, self.obj))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reject(self, func):
""" Return all the elements for which a truth test fails. """ |
return self._wrap(list(filter(lambda val: not func(val), self.obj))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def all(self, func=None):
""" Determine whether all of the elements match a truth test. """ |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def any(self, func=None):
""" Determine if at least one element in the object matches a truth test. """ |
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._wrap(self.a... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def include(self, target):
""" Determine if a given value is included in the array or object using `is`. """ |
if self._clean.isDict():
return self._wrap(target in self.obj.values())
else:
return self._wrap(target in self.obj) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def shuffle(self):
""" Shuffle an array. """ |
if(self._clean.isDict()):
return self._wrap(list())
cloned = self.obj[:]
random.shuffle(cloned)
return self._wrap(cloned) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sortBy(self, val=None):
""" Sort the object's values by a criterion produced by an iterator. """ |
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(self.obj... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _lookupIterator(self, val):
""" An internal function to generate lookup iterators. """ |
if val is None:
return lambda el, *args: el
return val if _.isCallable(val) else lambda obj, *args: obj[val] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _group(self, obj, val, behavior):
""" An internal function used for aggregate "group by" operations. """ |
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:
return ns... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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. """ |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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. "... |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 retur... |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 m... |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def flatten(self, shallow=None):
""" Return a completely flattened version of an array. """ |
return self._wrap(self._flatten(self.obj, shallow)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 us... |
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 isSorted else n... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def intersection(self, *args):
""" Produce an array that contains every item shared between all the passed-in arrays. """ |
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)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 remai... |
setobj = set(self.obj)
for i, v in enumerate(args):
setobj = setobj - set(args[i])
return self._wrap(self._clean._toOriginal(setobj)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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. ... |
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)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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. """ |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def range(self, *args):
""" Generate an integer Array containing an arithmetic progression. """ |
args = list(args)
args.insert(0, self.obj)
return self._wrap(range(*args)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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`... |
def part(*args2):
args3 = args + args2
return self.obj(*args3)
return self._wrap(part) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def memoize(self, hasher=None):
""" Memoize an expensive function by storing its results. """ |
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]
ret... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delay(self, wait, *args):
""" Delays a function for the given number of milliseconds, and then calls it with the arguments supplied. """ |
def call_it():
self.obj(*args)
t = Timer((float(wait) / float(1000)), call_it)
t.start()
return self._wrap(self.obj) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def throttle(self, wait):
""" Returns a function, that, when invoked, will only be triggered at most once during a given window of time. """ |
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(*args, **kwa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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... |
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)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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. """ |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 con... |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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. ""... |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def after(self, func):
""" Returns a function that will only be executed after being called N times. """ |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def invert(self):
""" Invert the keys and values of an object. The values must be serializable. """ |
keys = self._clean.keys()
inverted = {}
for key in keys:
inverted[self.obj[key]] = key
return self._wrap(inverted) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def functions(self):
""" Return a sorted list of the function names available on the object. """ |
names = []
for i, k in enumerate(self.obj):
if _(self.obj[k]).isCallable():
names.append(k)
return self._wrap(sorted(names)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pick(self, *args):
""" Return a copy of the object only containing the whitelisted properties. """ |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def defaults(self, *args):
""" Fill in a given object with default properties. """ |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 or... |
interceptor(self.obj)
return self._wrap(self.obj) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def isEmpty(self):
""" Is a given array, string, or object empty? An "empty" object has no enumerable own-properties. """ |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def isFile(self):
""" Check if the given object is a file """ |
try:
filetype = file
except NameError:
filetype = io.IOBase
return self._wrap(type(self.obj) is filetype) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def join(self, glue=" "):
""" Javascript's join implementation """ |
j = glue.join([str(x) for x in self.obj])
return self._wrap(j) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def result(self, property, *args):
""" If the value of the named property is a function then invoke it; otherwise, return it. """ |
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._wrap(v... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mixin(self):
""" Add your own custom functions to the Underscore object, ensuring that they're correctly added to the OOP wrapper as well. """ |
methods = self.obj
for i, k in enumerate(methods):
setattr(underscore, k, methods[k])
self.makeStatic()
return self._wrap(self.obj) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def escape(self):
""" Escape a string for HTML interpolation. """ |
# & 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(self.obj... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unescape(self):
""" Within an interpolation, evaluation, or escaping, remove HTML escaping that had been previously added. """ |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def value(self):
""" returns the object instead of instance """ |
if self._wrapped is not self.Null:
return self._wrapped
else:
return self.obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def makeStatic():
""" Provide static access to underscore class """ |
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):
def execu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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. ca... |
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')) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _configure_app(app_):
"""Configure the Flask WSGI app.""" |
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)
global ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _init_login_manager(app_):
"""Initialise and configure the login manager.""" |
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
d... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _configure_logger_for_production(logger):
"""Configure the given logger for production deployment. Logs to stderr and file, and emails errors to admins. """ |
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.setL... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _configure_logger():
"""Configure the logging module.""" |
if not app.debug:
_configure_logger_for_production(logging.getLogger())
elif not app.testing:
_configure_logger_for_debugging(logging.getLogger()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_scheduler(db_uri):
"""Initialise and configure the scheduler.""" |
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
| ev... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def job_listener(event):
'''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()
el... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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: Nam... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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
'''
username = None
password = None
ne... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 anonym... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def logout():
""" Log out the active user """ |
flogin.logout_user()
next = flask.request.args.get('next')
return flask.redirect(next or flask.url_for("user")) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 oc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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
'''
if not is_authorized():
return json.dumps({'e... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def job(job_id=None):
'''Submit a job. If no id is provided, a random id will be generated.
:param job_type: Which kind of job should be run. Has to be one of the
available job types.
:type job_type: string
:param api_key: An API key that is needed to execute the job. This could
be a CK... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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.
'''
if flogin.current_user.is_authenticated:
return True
if job:
job_key = flask.request.headers.get('Authorization... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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.
'''
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 u... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init(uri, echo=False):
"""Initialise the database. Initialise the sqlalchemy engine, metadata and table objects that we use to connect to the database. Creat... |
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()
_METADATA.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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... |
# 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 dicti... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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... |
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:
result... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 who... |
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 InvalidErrorObjectError(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 i... |
# 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 SQLAlchemy "U... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 :... |
update_dict = {
"status": "complete",
"data": json.dumps(data),
"finished_timestamp": datetime.datetime.now(),
}
_update_job(job_id, update_dict) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 :p... |
update_dict = {
"status": "error",
"error": error_object,
"finished_timestamp": datetime.datetime.now(),
}
_update_job(job_id, update_dict) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _init_jobs_table():
"""Initialise the "jobs" table in the db.""" |
_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', sqlalch... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _init_metadata_table():
"""Initialise the "metadata" table in the db.""" |
_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),
sqlalchemy... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _init_logs_table():
"""Initialise the "logs" table in the db.""" |
_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.UnicodeText... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_metadata(job_id):
"""Return any metadata for the given job_id from the metadata table.""" |
# Avoid SQLAlchemy "Unicode type received non-unicode bind param value"
# warnings.
job_id = unicode(job_id)
results = ENGINE.execute(
METADATA_TABLE.select().where(
METADATA_TABLE.c.job_id == job_id)).fetchall()
metadata = {}
for row in results:
value = row['value'... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_logs(job_id):
"""Return any logs for the given job_id from the logs table.""" |
# Avoid SQLAlchemy "Unicode type received non-unicode bind param value"
# warnings.
job_id = unicode(job_id)
results = ENGINE.execute(
LOGS_TABLE.select().where(LOGS_TABLE.c.job_id == job_id)).fetchall()
results = [dict(result) for result in results]
for result in results:
re... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_node_attributes(pattern, node, *attributes):
""" Searches match in attributes against given pattern and if finds the match against any of them returns ... |
for attribute_name in attributes:
attribute = node.get(attribute_name)
if attribute is not None and pattern.search(attribute):
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_hash_id(node):
""" Generates a hash_id for the node in question. :param node: lxml etree node """ |
try:
content = tostring(node)
except Exception:
logger.exception("Generating of hash failed")
content = to_bytes(repr(node))
hash_id = md5(content).hexdigest()
return hash_id[:8] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_link_density(node, node_text=None):
""" Computes the ratio for text in given node and text in links contained in the node. It is computed from number of ... |
if node_text is None:
node_text = node.text_content()
node_text = normalize_whitespace(node_text.strip())
text_length = len(node_text)
if text_length == 0:
return 0.0
links_length = sum(map(_get_normalized_text_length, node.findall(".//a")))
# Give 50 bonus chars worth of leng... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_unlikely_node(node):
""" Short helper for checking unlikely status. If the class or id are in the unlikely list, and there's not also a class/id in the li... |
unlikely = check_node_attributes(CLS_UNLIKELY, node, "class", "id")
maybe = check_node_attributes(CLS_MAYBE, node, "class", "id")
return bool(unlikely and not maybe and node.tag != "body") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def score_candidates(nodes):
"""Given a list of potential nodes, find some initial scores to start""" |
MIN_HIT_LENTH = 25
candidates = {}
for node in nodes:
logger.debug("* Scoring candidate %s %r", node.tag, node.attrib)
# if the node has no parent it knows of then it ends up creating a
# body & html tag to parent the html fragment
parent = node.getparent()
if pare... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getTime(self):
""" Actually, this function creates a time stamp vector based on the number of samples and sample rate. """ |
T = 1/float(self.samp[self.nrates-1])
endtime = self.endsamp[self.nrates-1] * T
t = numpy.linspace(0,endtime,self.endsamp[self.nrates-1])
return t |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getAnalogID(self,num):
""" Returns the COMTRADE ID of a given channel number. The number to be given is the same of the COMTRADE header. """ |
listidx = self.An.index(num) # Get the position of the channel number.
return self.Ach_id[listidx] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getDigitalID(self,num):
""" Reads the COMTRADE ID of a given channel number. The number to be given is the same of the COMTRADE header. """ |
listidx = self.Dn.index(num) # Get the position of the channel number.
return self.Dch_id[listidx] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getAnalogType(self,num):
""" Returns the type of the channel 'num' based on its unit stored in the Comtrade header file. Returns 'V' for a voltage channel an... |
listidx = self.An.index(num)
unit = self.uu[listidx]
if unit == 'kV' or unit == 'V':
return 'V'
elif unit == 'A' or unit == 'kA':
return 'I'
else:
print 'Unknown channel type'
return 0 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ReadDataFile(self):
""" Reads the contents of the Comtrade .dat file and store them in a private variable. For accessing a specific channel data, see methods... |
if os.path.isfile(self.filename[0:-4] + '.dat'):
filename = self.filename[0:-4] + '.dat'
elif os.path.isfile(self.filename[0:-4] + '.DAT'):
filename = self.filename[0:-4] + '.DAT'
else:
print "Data file File not found."
return 0
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getAnalogChannelData(self,ChNumber):
""" Returns an array of numbers containing the data values of the channel number "ChNumber". ChNumber is the number of t... |
if not self.DatFileContent:
print "No data file content. Use the method ReadDataFile first"
return 0
if (ChNumber > self.A):
print "Channel number greater than the total number of channels."
return 0
# Fomating string for st... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def initLogger():
'''
This code taken from Matt's Suspenders for initializing a logger
'''
global logger
logger = logging.getLogger('root')
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.INFO)
formatter = logging.Formatter("[%(asctime)s] %(l... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def writeSeqsToFiles(seqArray, seqFNPrefix, offsetFN, uniformLength):
'''
This function takes a seqArray and saves the values to a memmap file that can be accessed for multi-processing.
Additionally, it saves some offset indices in a numpy file for quicker string access.
@param seqArray - the list o... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def decompressBWT(inputDir, outputDir, numProcs, logger):
'''
This is called for taking a BWT and decompressing it back out to it's original form. While unusual to do,
it's included in this package for completion purposes.
@param inputDir - the directory of the compressed BWT we plan on decompressing
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def decompressBWTPoolProcess(tup):
'''
Individual process for decompression
'''
(inputDir, outputDir, startIndex, endIndex) = tup
if startIndex == endIndex:
return True
#load the thing we'll be extracting from
msbwt = MultiStringBWT.CompressedMSBWT()
msbwt.loadMsbwt(inp... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def clearAuxiliaryData(dirName):
'''
This function removes auxiliary files associated with a given filename
'''
if dirName != None:
if os.path.exists(dirName+'/auxiliary.npy'):
os.remove(dirName+'/auxiliary.npy')
if os.path.exists(dirName+'/totalCounts.p'):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_base_document(dom, return_fragment=True):
""" Builds a base document with the body as root. :param dom: Parsed lxml tree (Document Object Model). :para... |
body_element = dom.find(".//body")
if body_element is None:
fragment = fragment_fromstring('<div id="readabilityBody"/>')
fragment.append(dom)
else:
body_element.tag = "div"
body_element.set("id", "readabilityBody")
fragment = body_element
return document_from_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_siblings(candidate_node, candidate_list):
""" Looks through siblings for content that might also be related. Things like preambles, content split by ad... |
candidate_css = candidate_node.node.get("class")
potential_target = candidate_node.content_score * 0.2
sibling_target_score = potential_target if potential_target > 10 else 10
parent = candidate_node.node.getparent()
siblings = parent.getchildren() if parent is not None else []
for sibling in ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clean_document(node):
"""Cleans up the final document we return as the readable article.""" |
if node is None or len(node) == 0:
return None
logger.debug("\n\n-------------- CLEANING DOCUMENT -----------------")
to_drop = []
for n in node.iter():
# clean out any in-line style properties
if "style" in n.attrib:
n.set("style", "")
# remove embended o... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clean_conditionally(node):
"""Remove the clean_el if it looks like bad content based on rules.""" |
if node.tag not in ('form', 'table', 'ul', 'div', 'p'):
return # this is not the tag we are looking for
weight = get_class_weight(node)
# content_score = LOOK up the content score for this node we found
# before else default to 0
content_score = 0
if weight + content_score < 0:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.