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.antmp)
<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.result[0] except KeyError: return list(ns.result.values())[0] return 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 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 returns the criterion. """
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 maintain order. Uses binary search. """
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 using a faster algorithm. Aliased as `unique`. """
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 not _.include(memo, value)): memo.append(value) ns.results.append(ns.array[index]) return memo ret = _.reduce(initial, by) 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 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 remain. """
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) while i < l: if array[i] is item: return self._wrap(i) i += 1 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 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` context. """
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] return self._wrap(memoized)
<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, **kwargs): def later(): ns.timeout = None if ns.more: self.obj(*args, **kwargs) whenDone() if not ns.timeout: ns.timeout = Timer(wait, later) ns.timeout.start() if ns.throttling: ns.more = True else: ns.throttling = True ns.result = self.obj(*args, **kwargs) whenDone() return ns.result return self._wrap(throttled)
<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 after it stops being called for N milliseconds. If `immediate` is passed, trigger the function on the leading edge, instead of the trailing. """
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) debounced.t.start() return self._wrap(debounced)
<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 conditionally execute the original function. """
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 order to perform operations on intermediate results within the chain. """
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(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 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 execute(*args): if len(args) == 1: r = getattr(underscore(args[0]), a)() elif len(args) > 1: rargs = args[1:] r = getattr(underscore(args[0]), a)(*rargs) else: r = getattr(underscore([]), a)() return r return execute _.__setattr__(m, caller(m)) # put the class itself as a parameter so that we can use it on outside _.__setattr__("underscore", underscore) _.templateSettings = {}
<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. called once for each test case). """
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 SSL_VERIFY if app_.config.get('SSL_VERIFY') in ['False', 'FALSE', '0', False, 0]: SSL_VERIFY = False else: SSL_VERIFY = True return app_
<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 def load_user(userid): userid = int(userid) name = names.get(userid) return users.get(name) return users, 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 _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.setLevel(logging.INFO) if 'LOG_FILE' in app.config: logger.addHandler(file_handler) mail_handler = logging.handlers.SMTPHandler( '127.0.0.1', app.config.get('FROM_EMAIL'), app.config.get('ADMINS', []), 'CKAN Service Error') mail_handler.setLevel(logging.ERROR) if 'FROM_EMAIL' in app.config: logger.addHandler(mail_handler)
<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 | events.EVENT_JOB_ERROR) return scheduler
<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() else: error_object = "\n".join(traceback.format_tb(event.traceback) + [repr(event.exception)]) db.mark_job_as_errored(job_id, error_object) else: db.mark_job_as_completed(job_id, event.retval) api_key = db.get_job(job_id)["api_key"] result_ok = send_result(job_id, api_key) if not result_ok: db.mark_job_as_failed_to_post_result(job_id) # Optionally notify tests that job_listener() has finished. if "_TEST_CALLBACK_URL" in app.config: requests.get(app.config["_TEST_CALLBACK_URL"])
<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: Name of the service :type name: string :param stats: Shows stats for jobs in queue :type stats: dictionary ''' job_types = async_types.keys() + sync_types.keys() counts = {} for job_status in job_statuses: counts[job_status] = db.ENGINE.execute( db.JOBS_TABLE.count() .where(db.JOBS_TABLE.c.status == job_status) ).first()[0] return flask.jsonify( version=0.1, job_types=job_types, name=app.config.get('NAME', 'example'), stats=counts )
<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 next = flask.request.args.get('next') auth = flask.request.authorization if flask.request.method == 'POST': username = flask.request.form['username'] password = flask.request.form['password'] if auth and auth.type == 'basic': username = auth.username password = auth.password if not flogin.current_user.is_active: error = 'You have to login with proper credentials' if username and password: if check_auth(username, password): user = _users.get(username) if user: if flogin.login_user(user): return flask.redirect(next or flask.url_for("user")) error = 'Could not log in user.' else: error = 'User not found.' else: error = 'Wrong username or password.' else: error = 'No username or password.' return flask.Response( 'Could not verify your access level for that URL.\n {}'.format(error), 401, {str('WWW-Authenticate'): str('Basic realm="Login Required"')}) 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 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 default user if you are not logged in :type is_anonymous: bool ''' user = flogin.current_user return flask.jsonify({ 'id': user.get_id(), 'name': user.name, 'is_active': user.is_active(), 'is_anonymous': user.is_anonymous })
<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 Also, you can filter the jobs by their metadata. Use the metadata key as parameter key and the value as value. :rtype: A list of job ids ''' args = dict((key, value) for key, value in flask.request.args.items()) limit = args.pop('_limit', 100) offset = args.pop('_offset', 0) select = sql.select( [db.JOBS_TABLE.c.job_id], from_obj=[db.JOBS_TABLE.outerjoin( db.METADATA_TABLE, db.JOBS_TABLE.c.job_id == db.METADATA_TABLE.c.job_id) ]).\ group_by(db.JOBS_TABLE.c.job_id).\ order_by(db.JOBS_TABLE.c.requested_timestamp.desc()).\ limit(limit).offset(offset) status = args.pop('_status', None) if status: select = select.where(db.JOBS_TABLE.c.status == status) ors = [] for key, value in args.iteritems(): # Turn strings into unicode to stop SQLAlchemy # "Unicode type received non-unicode bind param value" warnings. key = unicode(key) ors.append(sql.and_(db.METADATA_TABLE.c.key == key, db.METADATA_TABLE.c.value == value)) if ors: select = select.where(sql.or_(*ors)) select = select.having( sql.func.count(db.JOBS_TABLE.c.job_id) == len(ors) ) result = db.ENGINE.execute(select) listing = [] for (job_id,) in result: listing.append(flask.url_for('job_status', job_id=job_id)) return flask.jsonify(list=listing)
<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 :param job_id: An identifier for the job :type job_id: string :param result_url: Callback url :type result_url: url string :param data: Results from job. :type data: json encodable data :param error: Error raised during job execution :type error: string :param metadata: Metadata provided when submitting job. :type metadata: list of key - value pairs :param requested_timestamp: Time the job started :type requested_timestamp: timestamp :param finished_timestamp: Time the job finished :type finished_timestamp: timestamp :statuscode 200: no error :statuscode 403: not authorized to view the job's data :statuscode 404: job id not found :statuscode 409: an error occurred ''' job_dict = db.get_job(job_id) if not job_dict: return json.dumps({'error': 'job_id not found'}), 404, headers if not ignore_auth and not is_authorized(job_dict): return json.dumps({'error': 'not authorized'}), 403, headers job_dict.pop('api_key', None) if not show_job_key: job_dict.pop('job_key', None) return flask.Response(json.dumps(job_dict, cls=DatetimeJsonEncoder), mimetype='application/json')
<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 occurred ''' conn = db.ENGINE.connect() job = db.get_job(job_id) if not job: return json.dumps({'error': 'job_id not found'}), 404, headers if not is_authorized(job): return json.dumps({'error': 'not authorized'}), 403, headers trans = conn.begin() try: conn.execute(db.JOBS_TABLE.delete().where( db.JOBS_TABLE.c.job_id == job_id)) trans.commit() return json.dumps({'success': True}), 200, headers except Exception, e: trans.rollback() return json.dumps({'error': str(e)}), 409, headers finally: conn.close()
<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({'error': 'not authorized'}), 403, headers days = flask.request.args.get('days', None) return _clear_jobs(days)
<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 :statuscode 409: an error occurred ''' job_dict = db.get_job(job_id) if not job_dict: return json.dumps({'error': 'job_id not found'}), 404, headers if not is_authorized(job_dict): return json.dumps({'error': 'not authorized'}), 403, headers if job_dict['error']: return json.dumps({'error': job_dict['error']}), 409, headers content_type = job_dict['metadata'].get('mimetype') return flask.Response(job_dict['data'], mimetype=content_type)
<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 CKAN API key that is needed to write any data. The key will also be used to administer jobs. If you don't want to use a real API key, you can provide a random string that you keep secure. :type api_key: string :param data: Data that is send to the job as input. (Optional) :type data: json encodable data :param result_url: Callback url that is called once the job has finished. (Optional) :type result_url: url string :param metadata: Data needed for the execution of the job which is not the input data. (Optional) :type metadata: list of key - value pairs **Results:** :rtype: A dictionary with the following keys :param job_id: An identifier for the job :type job_id: string :param job_key: A key that is required to view and administer the job :type job_key: string :statuscode 200: no error :statuscode 409: an error occurred ''' if not job_id: job_id = str(uuid.uuid4()) # key required for job administration job_key = str(uuid.uuid4()) ############# ERROR CHECKING ################ try: input = flask.request.json except werkzeug.exceptions.BadRequest: return json.dumps({"error": "Malformed json"}), 409, headers # Idk why but this is needed for some libraries that # send malformed content types if (not input and 'application/json' in flask.request.content_type.lower()): try: input = json.loads(flask.request.data) except ValueError: pass if not input: return json.dumps({"error": ('Not recognised as json, make ' 'sure content type is application/' 'json')}), 409, headers ACCEPTED_ARGUMENTS = set(['job_type', 'data', 'metadata', 'result_url', 'api_key', 'metadata']) extra_keys = set(input.keys()) - ACCEPTED_ARGUMENTS if extra_keys: return json.dumps({"error": ( 'Too many arguments. Extra keys are {}'.format( ', '.join(extra_keys)))}), 409, headers #check result_url here as good to give warning early. result_url = input.get('result_url') if result_url and not result_url.startswith('http'): return json.dumps({"error": "result_url has to start with http"}), \ 409, headers job_type = input.get('job_type') if not job_type: return json.dumps({"error": "Please specify a job type"}), 409, headers job_types = async_types.keys() + sync_types.keys() if job_type not in job_types: error_string = ( 'Job type {} not available. Available job types are {}' ).format(job_type, ', '.join(job_types)) return json.dumps({"error": error_string}), 409, headers api_key = input.get('api_key') if not api_key: return json.dumps({"error": "Please provide your API key."}), 409, headers metadata = input.get('metadata', {}) if not isinstance(metadata, dict): return json.dumps({"error": "metadata has to be a json object"}), \ 409, headers ############# END CHECKING ################ synchronous_job = sync_types.get(job_type) if synchronous_job: return run_synchronous_job(synchronous_job, job_id, job_key, input) else: asynchronous_job = async_types.get(job_type) return run_asynchronous_job(asynchronous_job, job_id, job_key, input)
<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') if job_key == app.config.get('SECRET_KEY'): return True return job['job_key'] == job_key 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 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 using when posting to the callback URL) # but no callback URL is weird, but it can happen. db.delete_api_key(job_id) return True api_key_from_job = job_dict.pop('api_key', None) if not api_key: api_key = api_key_from_job headers = {'Content-Type': 'application/json'} if api_key: if ':' in api_key: header, key = api_key.split(':') else: header, key = 'Authorization', api_key headers[header] = key try: result = requests.post( result_url, data=json.dumps(job_dict, cls=DatetimeJsonEncoder), headers=headers, verify=SSL_VERIFY) db.delete_api_key(job_id) except requests.ConnectionError: return False return result.status_code == requests.codes.ok
<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. 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 or not to have the sqlalchemy engine log all statements to stdout :type echo: bool """
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.create_all(ENGINE)
<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 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 the job function that will be executed for this job (unicode) "status": The current status of the job, e.g. "pending", "complete", or "error" (unicode) "data": Any output data returned by the job if it has completed successfully. This may be any JSON-serializable type, e.g. None, a string, a dict, etc. "error": If the job failed with an error this will be a dict with a "message" key whose value is a string error message. The dict may also have other keys specific to the particular type of error. If the job did not fail with an error then "error" will be None. "requested_timestamp": The time at which the job was requested (string) "finished_timestamp": The time at which the job finished (string) "sent_data": The input data for the job, provided by the client site. This may be any JSON-serializable type, e.g. None, a string, a dict, etc. "result_url": The callback URL that CKAN Service Provider will post the result to when the job finishes (unicode) "api_key": The API key that CKAN Service Provider will use when posting the job result to the result_url (unicode or None). A None here doesn't mean that there was no API key: CKAN Service Provider deletes the API key from the database after it has posted the result to the result_url. "job_key": The key that users must provide (in the Authorization header of the HTTP request) to be authorized to modify the job (unicode). For example requests to the CKAN Service Provider API need this to get the status or output data of a job or to delete a job. If you login to CKAN Service Provider as an administrator then you can administer any job without providing its job_key. "metadata": Any custom metadata associated with the job (dict) "logs": Any logs associated with the job (list) """
# 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 dictionary representation of the job. result_dict = {} for field in result.keys(): value = getattr(result, field) if value is None: result_dict[field] = value elif field in ('sent_data', 'data', 'error'): result_dict[field] = json.loads(value) elif isinstance(value, datetime.datetime): result_dict[field] = value.isoformat() else: result_dict[field] = unicode(value) result_dict['metadata'] = _get_metadata(job_id) result_dict['logs'] = _get_logs(job_id) return result_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 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: Document and unit test these! :param job_id: a unique identifier for the job, used as the primary key in ckanserviceprovider's "jobs" database table :type job_id: unicode :param job_key: the key required to administer the job via the API :type job_key: unicode :param job_type: the name of the job function that will be executed for this job :type job_key: unicode :param api_key: the client site API key that ckanserviceprovider will use when posting the job result to the result_url :type api_key: unicode :param data: The input data for the job (called sent_data elsewhere) :type data: Any JSON-serializable type :param metadata: A dict of arbitrary (key, value) metadata pairs to be stored along with the job. The keys should be strings, the values can be strings or any JSON-encodable type. :type metadata: dict :param result_url: the callback URL that ckanserviceprovider will post the job result to when the job has finished :type result_url: unicode """
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_url = unicode(result_url) if api_key: api_key = unicode(api_key) if job_key: job_key = unicode(job_key) data = unicode(data) if not metadata: metadata = {} conn = ENGINE.connect() trans = conn.begin() try: conn.execute(JOBS_TABLE.insert().values( job_id=job_id, job_type=job_type, status='pending', requested_timestamp=datetime.datetime.now(), sent_data=data, result_url=result_url, api_key=api_key, job_key=job_key)) # Insert any (key, value) metadata pairs that the job has into the # metadata table. inserts = [] for key, value in metadata.items(): type_ = 'string' if not isinstance(value, basestring): value = json.dumps(value) type_ = 'json' # Turn strings into unicode to stop SQLAlchemy # "Unicode type received non-unicode bind param value" warnings. key = unicode(key) value = unicode(value) inserts.append( {"job_id": job_id, "key": key, "value": value, "type": type_} ) if inserts: conn.execute(METADATA_TABLE.insert(), inserts) trans.commit() except Exception: trans.rollback() raise finally: conn.close()
<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 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 which case a dict like this will be returned: {"message": error_string} - A dict with a "message" key whose value is a string, in which case the dict will be returned unchanged :param error: the error object to validate :raises InvalidErrorObjectError: If the error object doesn't match any of the allowed types """
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( "error['message'] must be a string") except (TypeError, KeyError): raise InvalidErrorObjectError( "error must be either a string or a dict with a message key")
<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 it by calling this helper function. job_dict is a dict with values corresponding to the database columns that should be updated, e.g.: """
# 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 "Unicode type received non-unicode bind param value" # warnings. job_dict["error"] = unicode(job_dict["error"]) # Avoid SQLAlchemy "Unicode type received non-unicode bind param value" # warnings. if "data" in job_dict: job_dict["data"] = unicode(job_dict["data"]) ENGINE.execute( JOBS_TABLE.update() .where(JOBS_TABLE.c.job_id == job_id) .values(**job_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_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) """
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 :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 """
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', sqlalchemy.UnicodeText), sqlalchemy.Column('error', sqlalchemy.UnicodeText), sqlalchemy.Column('requested_timestamp', sqlalchemy.DateTime), sqlalchemy.Column('finished_timestamp', sqlalchemy.DateTime), sqlalchemy.Column('sent_data', sqlalchemy.UnicodeText), # Callback URL: sqlalchemy.Column('result_url', sqlalchemy.UnicodeText), # CKAN API key: sqlalchemy.Column('api_key', sqlalchemy.UnicodeText), # Key to administer job: sqlalchemy.Column('job_key', sqlalchemy.UnicodeText), ) return _jobs_table
<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.Column('value', sqlalchemy.UnicodeText, index=True), sqlalchemy.Column('type', sqlalchemy.UnicodeText), ) return _metadata_table
<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), sqlalchemy.Column('level', sqlalchemy.UnicodeText), sqlalchemy.Column('module', sqlalchemy.UnicodeText), sqlalchemy.Column('funcName', sqlalchemy.UnicodeText), sqlalchemy.Column('lineno', sqlalchemy.Integer) ) return _logs_table
<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'] if row['type'] == 'json': value = json.loads(value) metadata[row['key']] = value return 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_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: result.pop("job_id") return 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 check_node_attributes(pattern, node, *attributes): """ Searches match in attributes against given pattern and if finds the match against any of them returns True. """
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 characters in the texts. :parameter Element node: HTML element in which links density is computed. :parameter string node_text: Text content of given node if it was obtained before. :returns float: Returns value of computed 0 <= density <= 1, where 0 means no links and 1 means that node contains only links. """
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 length for each img. # Tweaking this 50 down a notch should help if we hit false positives. img_bonuses = 50 * len(node.findall(".//img")) links_length = max(0, links_length - img_bonuses) return links_length / text_length
<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 likely list then it might need to be removed. """
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 parent is None: logger.debug("Skipping candidate - parent node is 'None'.") continue grand = parent.getparent() if grand is None: logger.debug("Skipping candidate - grand parent node is 'None'.") continue # if paragraph is < `MIN_HIT_LENTH` characters don't even count it inner_text = node.text_content().strip() if len(inner_text) < MIN_HIT_LENTH: logger.debug( "Skipping candidate - inner text < %d characters.", MIN_HIT_LENTH) continue # initialize readability data for the parent # add parent node if it isn't in the candidate list if parent not in candidates: candidates[parent] = ScoredNode(parent) if grand not in candidates: candidates[grand] = ScoredNode(grand) # add a point for the paragraph itself as a base content_score = 1 if inner_text: # add 0.25 points for any commas within this paragraph commas_count = inner_text.count(",") content_score += commas_count * 0.25 logger.debug("Bonus points for %d commas.", commas_count) # subtract 0.5 points for each double quote within this paragraph double_quotes_count = inner_text.count('"') content_score += double_quotes_count * -0.5 logger.debug( "Penalty points for %d double-quotes.", double_quotes_count) # for every 100 characters in this paragraph, add another point # up to 3 points length_points = len(inner_text) / 100 content_score += min(length_points, 3.0) logger.debug("Bonus points for length of text: %f", length_points) # add the score to the parent logger.debug( "Bonus points for parent %s %r with score %f: %f", parent.tag, parent.attrib, candidates[parent].content_score, content_score) candidates[parent].content_score += content_score # the grand node gets half logger.debug( "Bonus points for grand %s %r with score %f: %f", grand.tag, grand.attrib, candidates[grand].content_score, content_score / 2.0) candidates[grand].content_score += content_score / 2.0 if node not in candidates: candidates[node] = ScoredNode(node) candidates[node].content_score += content_score for candidate in candidates.values(): adjustment = 1.0 - get_link_density(candidate.node) candidate.content_score *= adjustment logger.debug( "Link density adjustment for %s %r: %f", candidate.node.tag, candidate.node.attrib, adjustment) return candidates
<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 and 'I' for a current channel. """
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 getAnalogData and getDigitalData. """
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 self.filehandler = open(filename,'rb') self.DatFileContent = self.filehandler.read() # END READING .dat FILE. self.filehandler.close() # Close file. return 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 getAnalogChannelData(self,ChNumber): """ Returns an array of numbers containing the data values of the channel number "ChNumber". ChNumber is the number of the channal as in .cfg file. """
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 struct module: str_struct = "ii%dh" %(self.A + int(numpy.ceil((float(self.D)/float(16))))) # Number of bytes per sample: NB = 4 + 4 + self.A*2 + int(numpy.ceil((float(self.D)/float(16))))*2 # Number of samples: N = self.getNumberOfSamples() # Empty column vector: values = numpy.empty((N,1)) ch_index = self.An.index(ChNumber) # Reading the values from DatFileContent string: for i in range(N): data = struct.unpack(str_struct,self.DatFileContent[i*NB:(i*NB)+NB]) values[i] = data[ChNumber+1] # The first two number ar the sample index and timestamp values = values * self.a[ch_index] # a factor values = values + self.b[ch_index] # b factor return values
<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] %(levelname)s: %(message)s", "%Y-%m-%d %H:%M:%S") ch.setFormatter(formatter) logger.addHandler(ch)
<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 of '$'-terminated strings to be saved @param fnPrefix - the prefix for the temporary files, creates a prefix+'.seqs.npy' and prefix+'.offsets.npy' file ''' if uniformLength: #first, store the uniform size in our offsets file offsets = np.lib.format.open_memmap(offsetFN, 'w+', '<u8', (1,)) offsets[0] = uniformLength #define a constant character map for now d = {'$':0, 'A':1, 'C':2, 'G':3, 'N':4, 'T':5} dArr = np.add(np.zeros(dtype='<u1', shape=(256,)), len(d.keys())) for c in d.keys(): dArr[ord(c)] = d[c] seqLen = uniformLength b = np.reshape(seqArray, (-1, seqLen)) numSeqs = b.shape[0] t = b.transpose() for i in xrange(0, seqLen): #create a file for this column seqs = np.lib.format.open_memmap(seqFNPrefix+'.'+str(i)+'.npy', 'w+', '<u1', (numSeqs,)) chunkSize = 1000000 j = 0 while chunkSize*j < numSeqs: seqs[chunkSize*j:chunkSize*(j+1)] = dArr[t[-i-1][chunkSize*j:chunkSize*(j+1)]] j += 1 del seqs else: #count how many terminal '$' exist, 36 = '$' lenSums = np.add(1, np.where(seqArray == 36)[0]) numSeqs = lenSums.shape[0] totalLen = lenSums[-1] #track the total length thus far and open the files we plan to fill in seqFN = seqFNPrefix+'.npy' seqs = np.lib.format.open_memmap(seqFN, 'w+', '<u1', (totalLen,)) offsets = np.lib.format.open_memmap(offsetFN, 'w+', '<u8', (numSeqs+1,)) offsets[1:] = lenSums #define a constant character map for now d = {'$':0, 'A':1, 'C':2, 'G':3, 'N':4, 'T':5} dArr = np.add(np.zeros(dtype='<u1', shape=(256,)), len(d.keys())) for c in d.keys(): dArr[ord(c)] = d[c] #copy the values chunkSize = 1000000 i = 0 while chunkSize*i < seqArray.shape[0]: seqs[chunkSize*i:chunkSize*(i+1)] = dArr[seqArray[chunkSize*i:chunkSize*(i+1)]] i += 1 #clear memory del lenSums del seqs del offsets #return the two filenames return (seqFNPrefix, offsetFN)
<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 @param outputFN - the directory for the output decompressed BWT, it can be the same, we don't care @param numProcs - number of processes we're allowed to use @param logger - log all the things! ''' #load it, force it to be a compressed bwt also msbwt = MultiStringBWT.CompressedMSBWT() msbwt.loadMsbwt(inputDir, logger) #make the output file outputFile = np.lib.format.open_memmap(outputDir+'/msbwt.npy', 'w+', '<u1', (msbwt.getTotalSize(),)) del outputFile worksize = 1000000 tups = [None]*(msbwt.getTotalSize()/worksize+1) x = 0 if msbwt.getTotalSize() > worksize: for x in xrange(0, msbwt.getTotalSize()/worksize): tups[x] = (inputDir, outputDir, x*worksize, (x+1)*worksize) tups[-1] = (inputDir, outputDir, (x+1)*worksize, msbwt.getTotalSize()) else: tups[0] = (inputDir, outputDir, 0, msbwt.getTotalSize()) if numProcs > 1: myPool = multiprocessing.Pool(numProcs) rets = myPool.map(decompressBWTPoolProcess, tups) else: rets = [] for tup in tups: rets.append(decompressBWTPoolProcess(tup))
<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(inputDir, None) #open our output outputBwt = np.load(outputDir+'/msbwt.npy', 'r+') outputBwt[startIndex:endIndex] = msbwt.getBWTRange(startIndex, endIndex) return True
<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'): os.remove(dirName+'/totalCounts.p') if os.path.exists(dirName+'/totalCounts.npy'): os.remove(dirName+'/totalCounts.npy') if os.path.exists(dirName+'/fmIndex.npy'): os.remove(dirName+'/fmIndex.npy') if os.path.exists(dirName+'/comp_refIndex.npy'): os.remove(dirName+'/comp_refIndex.npy') if os.path.exists(dirName+'/comp_fmIndex.npy'): os.remove(dirName+'/comp_fmIndex.npy') if os.path.exists(dirName+'/backrefs.npy'): os.remove(dirName+'/backrefs.npy')
<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). :param bool return_fragment: If True only <div> fragment is returned. Otherwise full HTML document is returned. """
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_fragment(fragment, return_fragment)
<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 ads that we removed, etc. """
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 siblings: append = False content_bonus = 0 if sibling is candidate_node.node: append = True # Give a bonus if sibling nodes and top candidates have the example # same class name if candidate_css and sibling.get("class") == candidate_css: content_bonus += candidate_node.content_score * 0.2 if sibling in candidate_list: adjusted_score = \ candidate_list[sibling].content_score + content_bonus if adjusted_score >= sibling_target_score: append = True if sibling.tag == "p": link_density = get_link_density(sibling) content = sibling.text_content() content_length = len(content) if content_length > 80 and link_density < 0.25: append = True elif content_length < 80 and link_density == 0: if ". " in content: append = True if append: logger.debug( "Sibling appended: %s %r", sibling.tag, sibling.attrib) if sibling.tag not in ("div", "p"): # We have a node that isn't a common block level element, like # a form or td tag. Turn it into a div so it doesn't get # filtered out later by accident. sibling.tag = "div" if candidate_node.node != sibling: candidate_node.node.append(sibling) return candidate_node
<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 objects unless it's wanted video if n.tag in ("object", "embed") and not ok_embedded_video(n): logger.debug("Dropping node %s %r", n.tag, n.attrib) to_drop.append(n) # clean headings with bad css or high link density if n.tag in ("h1", "h2", "h3", "h4") and get_class_weight(n) < 0: logger.debug("Dropping <%s>, it's insignificant", n.tag) to_drop.append(n) if n.tag in ("h3", "h4") and get_link_density(n) > 0.33: logger.debug("Dropping <%s>, it's insignificant", n.tag) to_drop.append(n) # drop block element without content and children if n.tag in ("div", "p"): text_content = shrink_text(n.text_content()) if len(text_content) < 5 and not n.getchildren(): logger.debug( "Dropping %s %r without content.", n.tag, n.attrib) to_drop.append(n) # finally try out the conditional cleaning of the target node if clean_conditionally(n): to_drop.append(n) drop_nodes_with_parents(to_drop) return node
<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: logger.debug('Dropping conditional node') logger.debug('Weight + score < 0') return True commas_count = node.text_content().count(',') if commas_count < 10: logger.debug( "There are %d commas so we're processing more.", commas_count) # If there are not very many commas, and the number of # non-paragraph elements is more than paragraphs or other ominous # signs, remove the element. p = len(node.findall('.//p')) img = len(node.findall('.//img')) li = len(node.findall('.//li')) - 100 inputs = len(node.findall('.//input')) embed = 0 embeds = node.findall('.//embed') for e in embeds: if ok_embedded_video(e): embed += 1 link_density = get_link_density(node) content_length = len(node.text_content()) remove_node = False if li > p and node.tag != 'ul' and node.tag != 'ol': logger.debug('Conditional drop: li > p and not ul/ol') remove_node = True elif inputs > p / 3.0: logger.debug('Conditional drop: inputs > p/3.0') remove_node = True elif content_length < 25 and (img == 0 or img > 2): logger.debug('Conditional drop: len < 25 and 0/>2 images') remove_node = True elif weight < 25 and link_density > 0.2: logger.debug('Conditional drop: weight small (%f) and link is dense (%f)', weight, link_density) remove_node = True elif weight >= 25 and link_density > 0.5: logger.debug('Conditional drop: weight big but link heavy') remove_node = True elif (embed == 1 and content_length < 75) or embed > 1: logger.debug( 'Conditional drop: embed w/o much content or many embed') remove_node = True if remove_node: logger.debug('Node will be removed: %s %r %s', node.tag, node.attrib, node.text_content()[:30]) return remove_node return False