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 create_mypassword(self, data):
"""Create my password.""" |
# http://teampasswordmanager.com/docs/api-my-passwords/#create_password
log.info('Create MyPassword with %s' % data)
NewID = self.post('my_passwords.json', data).get('id')
log.info('MyPassword has been created with %s' % NewID)
return NewID |
<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_mypassword(self, ID, data):
"""Update my password.""" |
# http://teampasswordmanager.com/docs/api-my-passwords/#update_password
log.info('Update MyPassword %s with %s' % (ID, data))
self.put('my_passwords/%s.json' % ID, 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 create_user(self, data):
"""Create a User.""" |
# http://teampasswordmanager.com/docs/api-users/#create_user
log.info('Create user with %s' % data)
NewID = self.post('users.json', data).get('id')
log.info('User has been created with ID %s' % NewID)
return NewID |
<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_user(self, ID, data):
"""Update a User.""" |
# http://teampasswordmanager.com/docs/api-users/#update_user
log.info('Update user %s with %s' % (ID, data))
self.put('users/%s.json' % ID, 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 change_user_password(self, ID, data):
"""Change password of a User.""" |
# http://teampasswordmanager.com/docs/api-users/#change_password
log.info('Change user %s password' % ID)
self.put('users/%s/change_password.json' % ID, 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 convert_user_to_ldap(self, ID, DN):
"""Convert a normal user to a LDAP user.""" |
# http://teampasswordmanager.com/docs/api-users/#convert_to_ldap
data = {'login_dn': DN}
log.info('Convert User %s to LDAP DN %s' % (ID, DN))
self.put('users/%s/convert_to_ldap.json' % ID, 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 create_group(self, data):
"""Create a Group.""" |
# http://teampasswordmanager.com/docs/api-groups/#create_group
log.info('Create group with %s' % data)
NewID = self.post('groups.json', data).get('id')
log.info('Group has been created with ID %s' % NewID)
return NewID |
<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_group(self, ID, data):
"""Update a Group.""" |
# http://teampasswordmanager.com/docs/api-groups/#update_group
log.info('Update group %s with %s' % (ID, data))
self.put('groups/%s.json' % ID, 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 add_user_to_group(self, GroupID, UserID):
"""Add a user to a group.""" |
# http://teampasswordmanager.com/docs/api-groups/#add_user
log.info('Add User %s to Group %s' % (UserID, GroupID))
self.put('groups/%s/add_user/%s.json' % (GroupID, UserID)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete_user_from_group(self, GroupID, UserID):
"""Delete a user from a group.""" |
# http://teampasswordmanager.com/docs/api-groups/#del_user
log.info('Delete user %s from group %s' % (UserID, GroupID))
self.put('groups/%s/delete_user/%s.json' % (GroupID, UserID)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def up_to_date(self):
"""Check if Team Password Manager is up to date.""" |
VersionInfo = self.get_latest_version()
CurrentVersion = VersionInfo.get('version')
LatestVersion = VersionInfo.get('latest_version')
if CurrentVersion == LatestVersion:
log.info('TeamPasswordManager is up-to-date!')
log.debug('Current Version: {} Latest Version: {}'.format(LatestVersion, LatestVersion))
return True
else:
log.warning('TeamPasswordManager is not up-to-date!')
log.debug('Current Version: {} Latest Version: {}'.format(LatestVersion, LatestVersion))
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 truncate_datetime(t, resolution):
""" Given a datetime ``t`` and a ``resolution``, flatten the precision beyond the given resolution. ``resolution`` can be one of: year, month, day, hour, minute, second, microsecond Example:: datetime.datetime(2000, 1, 2, 0, 0) '2000-01-02T00:00:00' datetime.datetime(2000, 1, 2, 3, 4) '2000-01-02T03:04:00' """ |
resolutions = ['year', 'month', 'day', 'hour', 'minute', 'second', 'microsecond']
if resolution not in resolutions:
raise KeyError("Resolution is not valid: {0}".format(resolution))
args = []
for r in resolutions:
args += [getattr(t, r)]
if r == resolution:
break
return datetime.datetime(*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 to_timezone(dt, timezone):
""" Return an aware datetime which is ``dt`` converted to ``timezone``. If ``dt`` is naive, it is assumed to be UTC. For example, if ``dt`` is "06:00 UTC+0000" and ``timezone`` is "EDT-0400", then the result will be "02:00 EDT-0400". This method follows the guidelines in http://pytz.sourceforge.net/ """ |
if dt.tzinfo is None:
dt = dt.replace(tzinfo=_UTC)
return timezone.normalize(dt.astimezone(timezone)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def now(timezone=None):
""" Return a naive datetime object for the given ``timezone``. A ``timezone`` is any pytz- like or datetime.tzinfo-like timezone object. If no timezone is given, then UTC is assumed. This method is best used with pytz installed:: pip install pytz """ |
d = datetime.datetime.utcnow()
if not timezone:
return d
return to_timezone(d, timezone).replace(tzinfo=None) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def enumerate_query_by_limit(q, limit=1000):
""" Enumerate over SQLAlchemy query object ``q`` and yield individual results fetched in batches of size ``limit`` using SQL LIMIT and OFFSET. """ |
for offset in count(0, limit):
r = q.offset(offset).limit(limit).all()
for row in r:
yield row
if len(r) < limit:
break |
<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_many(d, schema):
"""Validate a dictionary of data against the provided schema. Returns a list of values positioned in the same order as given in ``schema``, each value is validated with the corresponding validator. Raises formencode.Invalid if validation failed. Similar to get_many but using formencode validation. :param d: A dictionary of data to read values from. :param schema: A list of (key, validator) tuples. The key will be used to fetch a value from ``d`` and the validator will be applied to it. Example:: from formencode import validators email, password, password_confirm = validate_many(request.params, [ ('email', validators.Email(not_empty=True)), ('password', validators.String(min=4)), ('password_confirm', validators.String(min=4)), ]) """ |
return [validator.to_python(d.get(key), state=key) for key,validator in schema] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def assert_hashable(*args, **kw):
""" Verify that each argument is hashable. Passes silently if successful. Raises descriptive TypeError otherwise. Example:: Traceback (most recent call last):
TypeError: Argument in position 1 is not hashable: [] Traceback (most recent call last):
TypeError: Keyword argument 'bar' is not hashable: [] """ |
try:
for i, arg in enumerate(args):
hash(arg)
except TypeError:
raise TypeError('Argument in position %d is not hashable: %r' % (i, arg))
try:
for key, val in iterate_items(kw):
hash(val)
except TypeError:
raise TypeError('Keyword argument %r is not hashable: %r' % (key, 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 memoized(fn=None, cache=None):
""" Memoize a function into an optionally-specificed cache container. If the `cache` container is not specified, then the instance container is accessible from the wrapped function's `memoize_cache` property. Example:: Not cached. Not cached. Example with a specific cache container (in this case, the ``RecentlyUsedContainer``, which will only store the ``maxsize`` most recently accessed items):
: Not cached. Not cached. Not cached. Not cached. """ |
if fn:
# This is a hack to support both @memoize and @memoize(...)
return memoized(cache=cache)(fn)
if cache is None:
cache = {}
def decorator(fn):
wrapped = wraps(fn)(partial(_memoized_call, fn, cache))
wrapped.memoize_cache = cache
return wrapped
return decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def memoized_method(method=None, cache_factory=None):
""" Memoize a class's method. Arguments are similar to to `memoized`, except that the cache container is specified with `cache_factory`: a function called with no arguments to create the caching container for the instance. Note that, unlike `memoized`, the result cache will be stored on the instance, so cached results will be deallocated along with the instance. Example:: Calling get_name on 'shazow' 'shazow' 'shazow' {((), ()):
'shazow'} Example with a specific cache container:: Calling add with 1 and 1 2 2 Calling add with 2 and 2 4 Calling add with 3 and 3 6 Calling add with 1 and 1 2 """ |
if method is None:
return lambda f: memoized_method(f, cache_factory=cache_factory)
cache_factory = cache_factory or dict
@wraps(method)
def memoized_method_property(self):
cache = cache_factory()
cache_attr = "_%s_cache" %(method.__name__, )
setattr(self, cache_attr, cache)
result = partial(
_memoized_call,
partial(method, self),
cache
)
result.memoize_cache = cache
return result
return memoized_property(memoized_method_property) |
<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_count(i, key=None, force_keys=None):
""" Aggregate iterator values into buckets based on how frequently the values appear. Example:: [(1, 3), (2, 1), (3, 1)] """ |
counter = defaultdict(lambda: 0)
if not key:
key = lambda o: o
for k in i:
counter[key(k)] += 1
if force_keys:
for k in force_keys:
counter[k] += 0
return counter.items() |
<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_iterable(maybe_iter, unless=(string_types, dict)):
""" Return whether ``maybe_iter`` is an iterable, unless it's an instance of one of the base class, or tuple of base classes, given in ``unless``. Example:: False True False True """ |
try:
iter(maybe_iter)
except TypeError:
return False
return not isinstance(maybe_iter, unless) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def iterate(maybe_iter, unless=(string_types, dict)):
""" Always return an iterable. Returns ``maybe_iter`` if it is an iterable, otherwise it returns a single element iterable containing ``maybe_iter``. By default, strings and dicts are treated as non-iterable. This can be overridden by passing in a type or tuple of types for ``unless``. :param maybe_iter: A value to return as an iterable. :param unless: A type or tuple of types (same as ``isinstance``) to be treated as non-iterable. Example:: ['foo'] ['foo'] [['foo']] [0, 1, 2, 3, 4] """ |
if is_iterable(maybe_iter, unless=unless):
return maybe_iter
return [maybe_iter] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def iterate_chunks(i, size=10):
""" Iterate over an iterator ``i`` in ``size`` chunks, yield chunks. Similar to pagination. Example:: [[1, 2], [3, 4]] """ |
accumulator = []
for n, i in enumerate(i):
accumulator.append(i)
if (n+1) % size == 0:
yield accumulator
accumulator = []
if accumulator:
yield accumulator |
<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_subclass(o, bases):
""" Similar to the ``issubclass`` builtin, but does not raise a ``TypeError`` if either ``o`` or ``bases`` is not an instance of ``type``. Example:: True False False True False """ |
try:
return _issubclass(o, bases)
except TypeError:
pass
if not isinstance(o, type):
return False
if not isinstance(bases, tuple):
return False
bases = tuple(b for b in bases if isinstance(b, type))
return _issubclass(o, bases) |
<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_many(d, required=[], optional=[], one_of=[]):
""" Returns a predictable number of elements out of ``d`` in a list for auto-expanding. Keys in ``required`` will raise KeyError if not found in ``d``. Keys in ``optional`` will return None if not found in ``d``. Keys in ``one_of`` will raise KeyError if none exist, otherwise return the first in ``d``. Example:: uid, action, limit, offset = get_many(request.params, required=['uid', 'action'], optional=['limit', 'offset']) Note: This function has been added to the webhelpers package. """ |
d = d or {}
r = [d[k] for k in required]
r += [d.get(k)for k in optional]
if one_of:
for k in (k for k in one_of if k in d):
return r + [d[k]]
raise KeyError("Missing a one_of value.")
return r |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def random_string(length=6, alphabet=string.ascii_letters+string.digits):
""" Return a random string of given length and alphabet. Default alphabet is url-friendly (base62). """ |
return ''.join([random.choice(alphabet) for i in xrange(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 number_to_string(n, alphabet):
""" Given an non-negative integer ``n``, convert it to a string composed of the given ``alphabet`` mapping, where the position of each element in ``alphabet`` is its radix value. Examples:: '101111000110000101001110' 'babbbbaaabbaaaababaabbba' 'ZXP0' 'one two three four five ' """ |
result = ''
base = len(alphabet)
current = int(n)
if current < 0:
raise ValueError("invalid n (must be non-negative): %s", n)
while current:
result = alphabet[current % base] + result
current = current // base
return 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 string_to_number(s, alphabet):
""" Given a string ``s``, convert it to an integer composed of the given ``alphabet`` mapping, where the position of each element in ``alphabet`` is its radix value. Examples:: 12345678 12345678 12345678 """ |
base = len(alphabet)
inverse_alphabet = dict(zip(alphabet, xrange(0, base)))
n = 0
exp = 0
for i in reversed(s):
n += inverse_alphabet[i] * (base ** exp)
exp += 1
return 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 number_to_bytes(n, endian='big'):
""" Convert an integer to a corresponding string of bytes.. :param n: Integer to convert. :param endian: Byte order to convert into ('big' or 'little' endian-ness, default 'big') Assumes bytes are 8 bits. This is a special-case version of number_to_string with a full base-256 ASCII alphabet. It is the reverse of ``bytes_to_number(b)``. Examples:: b'*' b'\\xff' b'\\x01\\x00' b'\\x00\\x01' """ |
res = []
while n:
n, ch = divmod(n, 256)
if PY3:
res.append(ch)
else:
res.append(chr(ch))
if endian == 'big':
res.reverse()
if PY3:
return bytes(res)
else:
return ''.join(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 to_float(s, default=0.0, allow_nan=False):
""" Return input converted into a float. If failed, then return ``default``. Note that, by default, ``allow_nan=False``, so ``to_float`` will not return ``nan``, ``inf``, or ``-inf``. Examples:: 1.5 1.0 0.0 0.0 0.0 -inf 0.0 0.0 'Empty' """ |
try:
f = float(s)
except (TypeError, ValueError):
return default
if not allow_nan:
if f != f or f in _infs:
return default
return f |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dollars_to_cents(s, allow_negative=False):
""" Given a string or integer representing dollars, return an integer of equivalent cents, in an input-resilient way. This works by stripping any non-numeric characters before attempting to cast the value. Examples:: 100 100 100 10000 -100 100 """ |
# TODO: Implement cents_to_dollars
if not s:
return
if isinstance(s, string_types):
s = ''.join(RE_NUMBER.findall(s))
dollars = int(round(float(s) * 100))
if not allow_negative and dollars < 0:
raise ValueError('Negative values not permitted.')
return dollars |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def slugify(s, delimiter='-'):
""" Normalize `s` into ASCII and replace non-word characters with `delimiter`. """ |
s = unicodedata.normalize('NFKD', to_unicode(s)).encode('ascii', 'ignore').decode('ascii')
return RE_SLUG.sub(delimiter, s).strip(delimiter).lower() |
<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_cache_buster(src_path, method='importtime'):
""" Return a string that can be used as a parameter for cache-busting URLs for this asset. :param src_path: Filesystem path to the file we're generating a cache-busting value for. :param method: Method for cache-busting. Supported values: importtime, mtime, md5 The default is 'importtime', because it requires the least processing. Note that the mtime and md5 cache busting methods' results are cached on the src_path. Example:: True True True """ |
try:
fn = _BUST_METHODS[method]
except KeyError:
raise KeyError('Unsupported busting method value: %s' % method)
return fn(src_path) |
<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_dom_attrs(attrs, allow_no_value=True):
""" Yield compiled DOM attribute key-value strings. If the value is `True`, then it is treated as no-value. If `None`, then it is skipped. """ |
for attr in iterate_items(attrs):
if isinstance(attr, basestring):
attr = (attr, True)
key, value = attr
if value is None:
continue
if value is True and not allow_no_value:
value = key # E.g. <option checked="true" />
if value is True:
yield True # E.g. <option checked />
else:
yield '%s="%s"' % (key, value.replace('"', '\\"')) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tag(tagname, content='', attrs=None):
""" Helper for programmatically building HTML tags. Note that this barely does any escaping, and will happily spit out dangerous user input if used as such. :param tagname: Tag name of the DOM element we want to return. :param content: Optional content of the DOM element. If `None`, then the element is self-closed. By default, the content is an empty string. Supports iterables like generators. :param attrs: Optional dictionary-like collection of attributes for the DOM element. Example:: u'<div>Hello, world.</div>' u'<script src="/static/js/core.js"></script>' u'<script src="/static/js/core.js" type="text/javascript"></script>' u'<meta content="\\\\"quotedquotes\\\\"" />' u'<ul><li>0</li><li>1</li><li>2</li></ul>' """ |
attrs_str = attrs and ' '.join(_generate_dom_attrs(attrs))
open_tag = tagname
if attrs_str:
open_tag += ' ' + attrs_str
if content is None:
return literal('<%s />' % open_tag)
content = ''.join(iterate(content, unless=(basestring, literal)))
return literal('<%s>%s</%s>' % (open_tag, content, tagname)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def javascript_link(src_url, src_path=None, cache_bust=None, content='', extra_attrs=None):
""" Helper for programmatically building HTML JavaScript source include links, with optional cache busting. :param src_url: :param src_path: Optional filesystem path to the source file, used when `cache_bust` is enabled. :param content: Optional content of the DOM element. If `None`, then the element is self-closed. :param cache_bust: Optional method to use for cache busting. Can be one of: importtime, md5, or mtime. If the value is md5 or mtime, then `src_path` must be supplied. Example:: u'<script src="/static/js/core.js" type="text/javascript"></script>' """ |
if cache_bust:
append_suffix = get_cache_buster(src_path=src_path, method=cache_bust)
delim = '&' if '?' in src_url else '?'
src_url += delim + append_suffix
attrs = {
'src': src_url,
'type': 'text/javascript',
}
if extra_attrs:
attrs.update(extra_attrs)
return tag('script', content=content, attrs=attrs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def create_subscriptions(config, profile_name):
''' Adds supported subscriptions '''
if 'kinesis' in config.subscription.keys():
data = config.subscription['kinesis']
function_name = config.name
stream_name = data['stream']
batch_size = data['batch_size']
starting_position = data['starting_position']
starting_position_ts = None
if starting_position == 'AT_TIMESTAMP':
ts = data.get('starting_position_timestamp')
starting_position_ts = datetime.strptime(ts, '%Y-%m-%dT%H:%M:%SZ')
s = KinesisSubscriber(config, profile_name,
function_name, stream_name, batch_size,
starting_position,
starting_position_ts=starting_position_ts)
s.subscribe() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def subscribe(self):
''' Subscribes the lambda to the Kinesis stream '''
try:
LOG.debug('Creating Kinesis subscription')
if self.starting_position_ts:
self._lambda_client \
.create_event_source_mapping(
EventSourceArn=self.stream_name,
FunctionName=self.function_name,
BatchSize=self.batch_size,
StartingPosition=self.starting_position,
StartingPositionTimestamp=self.starting_position_ts)
else:
self._lambda_client \
.create_event_source_mapping(
EventSourceArn=self.stream_name,
FunctionName=self.function_name,
BatchSize=self.batch_size,
StartingPosition=self.starting_position)
LOG.debug('Subscription created')
except botocore.exceptions.ClientError as ex:
response_code = ex.response['Error']['Code']
if response_code == 'ResourceConflictException':
LOG.debug('Subscription exists. Updating ...')
resp = self._lambda_client\
.list_event_source_mappings(
FunctionName=self.function_name,
EventSourceArn=self.stream_name)
uuid = resp['EventSourceMappings'][0]['UUID']
self._lambda_client \
.update_event_source_mapping(
UUID=uuid,
FunctionName=self.function_name,
Enabled=True,
BatchSize=self.batch_size)
else:
LOG.error('Subscription failed, error=%s' % str(ex))
raise ex |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _upload_s3(self, zip_file):
'''
Uploads the lambda package to s3
'''
s3_client = self._aws_session.client('s3')
transfer = boto3.s3.transfer.S3Transfer(s3_client)
transfer.upload_file(zip_file, self._config.s3_bucket,
self._config.s3_package_name()) |
<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_package(path, requires, virtualenv=None, ignore=None,
extra_files=None, zipfile_name=ZIPFILE_NAME,
pyexec=None):
'''Builds the zip file and creates the package with it'''
pkg = Package(path, zipfile_name, pyexec)
if extra_files:
for fil in extra_files:
pkg.extra_file(fil)
if virtualenv is not None:
pkg.virtualenv(virtualenv)
pkg.requirements(requires)
pkg.build(ignore)
return pkg |
<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(self, ignore=None):
'''Calls all necessary methods to build the Lambda Package'''
self._prepare_workspace()
self.install_dependencies()
self.package(ignore) |
<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_workspace(self):
'''Clean up the temporary workspace if one exists'''
if os.path.isdir(self._temp_workspace):
shutil.rmtree(self._temp_workspace) |
<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_zipfile(self):
'''remove existing zipfile'''
if os.path.isfile(self.zip_file):
os.remove(self.zip_file) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def requirements(self, requires):
'''
Sets the requirements for the package.
It will take either a valid path to a requirements file or
a list of requirements.
'''
if requires:
if isinstance(requires, basestring) and \
os.path.isfile(os.path.abspath(requires)):
self._requirements_file = os.path.abspath(requires)
else:
if isinstance(self._requirements, basestring):
requires = requires.split()
self._requirements_file = None
self._requirements = requires
else:
# If the default requirements file is found use that
if os.path.isfile(self._requirements_file):
return
self._requirements, self._requirements_file = None, None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def virtualenv(self, virtualenv):
'''
Sets the virtual environment for the lambda package
If this is not set then package_dependencies will create a new one.
Takes a path to a virtualenv or a boolean if the virtualenv creation
should be skipped.
'''
# If a boolean is passed then set the internal _skip_virtualenv flag
if isinstance(virtualenv, bool):
self._skip_virtualenv = virtualenv
else:
self._virtualenv = virtualenv
if not os.path.isdir(self._virtualenv):
raise Exception("virtualenv %s not found" % self._virtualenv)
LOG.info("Using existing virtualenv at %s" % self._virtualenv)
# use supplied virtualenv path
self._pkg_venv = self._virtualenv
self._skip_virtualenv = 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 install_dependencies(self):
''' Creates a virtualenv and installs requirements '''
# If virtualenv is set to skip then do nothing
if self._skip_virtualenv:
LOG.info('Skip Virtualenv set ... nothing to do')
return
has_reqs = _isfile(self._requirements_file) or self._requirements
if self._virtualenv is None and has_reqs:
LOG.info('Building new virtualenv and installing requirements')
self._build_new_virtualenv()
self._install_requirements()
elif self._virtualenv is None and not has_reqs:
LOG.info('No requirements found, so no virtualenv will be made')
self._pkg_venv = False
else:
raise Exception('Cannot determine what to do about virtualenv') |
<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_new_virtualenv(self):
'''Build a new virtualenvironment if self._virtualenv is set to None'''
if self._virtualenv is None:
# virtualenv was "None" which means "do default"
self._pkg_venv = os.path.join(self._temp_workspace, 'venv')
self._venv_pip = 'bin/pip'
if sys.platform == 'win32' or sys.platform == 'cygwin':
self._venv_pip = 'Scripts\pip.exe'
python_exe = self._python_executable()
proc = Popen(["virtualenv", "-p", python_exe,
self._pkg_venv], stdout=PIPE, stderr=PIPE)
stdout, stderr = proc.communicate()
LOG.debug("Virtualenv stdout: %s" % stdout)
LOG.debug("Virtualenv stderr: %s" % stderr)
if proc.returncode is not 0:
raise Exception('virtualenv returned unsuccessfully')
else:
raise Exception('cannot build a new virtualenv when asked to omit') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _install_requirements(self):
'''
Create a new virtualenvironment and install requirements
if there are any.
'''
if not hasattr(self, '_pkg_venv'):
err = 'Must call build_new_virtualenv before install_requirements'
raise Exception(err)
cmd = None
if self._requirements:
LOG.debug("Installing requirements found %s in config"
% self._requirements)
cmd = [os.path.join(self._pkg_venv, self._venv_pip),
'install'] + self._requirements
elif _isfile(self._requirements_file):
# Pip install
LOG.debug("Installing requirements from requirements.txt file")
cmd = [os.path.join(self._pkg_venv, self._venv_pip),
"install", "-r",
self._requirements_file]
if cmd is not None:
prc = Popen(cmd, stdout=PIPE, stderr=PIPE)
stdout, stderr = prc.communicate()
LOG.debug("Pip stdout: %s" % stdout)
LOG.debug("Pip stderr: %s" % stderr)
if prc.returncode is not 0:
raise Exception('pip returned unsuccessfully') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def package(self, ignore=None):
""" Create a zip file of the lambda script and its dependencies. :param list ignore: a list of regular expression strings to match paths of files in the source of the lambda script against and ignore those files when creating the zip file. The paths to be matched are local to the source root. """ |
ignore = ignore or []
package = os.path.join(self._temp_workspace, 'lambda_package')
# Copy site packages into package base
LOG.info('Copying site packages')
if hasattr(self, '_pkg_venv') and self._pkg_venv:
lib_dir = 'lib/python*/site-packages'
lib64_dir = 'lib64/python*/site-packages'
if sys.platform == 'win32' or sys.platform == 'cygwin':
lib_dir = 'lib\\site-packages'
lib64_dir = 'lib64\\site-packages'
# Look for the site packages
lib_site_list = glob.glob(os.path.join(
self._pkg_venv, lib_dir))
if lib_site_list:
utils.copy_tree(lib_site_list[0], package)
else:
LOG.debug("no lib site packages found")
lib64_site_list = glob.glob(os.path.join(
self._pkg_venv, lib64_dir))
if lib64_site_list:
lib64_site_packages = lib64_site_list[0]
if not os.path.islink(lib64_site_packages):
LOG.info('Copying lib64 site packages')
utils.copy_tree(lib64_site_packages, package)
lib64_site_packages = lib64_site_list[0]
else:
LOG.debug("no lib64 site packages found")
# Append the temp workspace to the ignore list:
ignore.append(r"^%s/.*" % re.escape(TEMP_WORKSPACE_NAME))
utils.copy_tree(self._path, package, ignore)
# Add extra files
for p in self._extra_files:
LOG.info('Copying extra %s into package' % p)
ignore.append(re.escape(p))
if os.path.isdir(p):
utils.copy_tree(p, package, ignore=ignore, include_parent=True)
else:
shutil.copy(p, package)
self._create_zip(package) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def encode_properties(parameters):
""" Performs encoding of url parameters from dictionary to a string. It does not escape backslash because it is not needed. See: http://www.jfrog.com/confluence/display/RTF/Artifactory+REST+API#ArtifactoryRESTAPI-SetItemProperties """ |
result = []
for param in iter(sorted(parameters)):
if isinstance(parameters[param], (list, tuple)):
value = ','.join([escape_chars(x) for x in parameters[param]])
else:
value = escape_chars(parameters[param])
result.append("%s=%s" % (param, value))
return '|'.join(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 rest_get(self, url, params=None, headers=None, auth=None, verify=True, cert=None):
""" Perform a GET request to url with optional authentication """ |
res = requests.get(url, params=params, headers=headers, auth=auth, verify=verify,
cert=cert)
return res.text, res.status_code |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rest_del(self, url, params=None, auth=None, verify=True, cert=None):
""" Perform a DELETE request to url with optional authentication """ |
res = requests.delete(url, params=params, auth=auth, verify=verify, cert=cert)
return res.text, res.status_code |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rest_get_stream(self, url, auth=None, verify=True, cert=None):
""" Perform a chunked GET request to url with optional authentication This is specifically to download files. """ |
res = requests.get(url, auth=auth, stream=True, verify=verify, cert=cert)
return res.raw, res.status_code |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deploy(self, pathobj, fobj, md5=None, sha1=None, parameters=None):
""" Uploads a given file-like object HTTP chunked encoding will be attempted """ |
if isinstance(fobj, urllib3.response.HTTPResponse):
fobj = HTTPResponseWrapper(fobj)
url = str(pathobj)
if parameters:
url += ";%s" % encode_matrix_parameters(parameters)
headers = {}
if md5:
headers['X-Checksum-Md5'] = md5
if sha1:
headers['X-Checksum-Sha1'] = sha1
text, code = self.rest_put_stream(url,
fobj,
headers=headers,
auth=pathobj.auth,
verify=pathobj.verify,
cert=pathobj.cert)
if code not in [200, 201]:
raise RuntimeError("%s" % text) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def move(self, src, dst):
""" Move artifact from src to dst """ |
url = '/'.join([src.drive,
'api/move',
str(src.relative_to(src.drive)).rstrip('/')])
params = {'to': str(dst.relative_to(dst.drive)).rstrip('/')}
text, code = self.rest_post(url,
params=params,
auth=src.auth,
verify=src.verify,
cert=src.cert)
if code not in [200, 201]:
raise RuntimeError("%s" % text) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_properties(self, pathobj, props, recursive):
""" Set artifact properties """ |
url = '/'.join([pathobj.drive,
'api/storage',
str(pathobj.relative_to(pathobj.drive)).strip('/')])
params = {'properties': encode_properties(props)}
if not recursive:
params['recursive'] = '0'
text, code = self.rest_put(url,
params=params,
auth=pathobj.auth,
verify=pathobj.verify,
cert=pathobj.cert)
if code == 404 and "Unable to find item" in text:
raise OSError(2, "No such file or directory: '%s'" % url)
if code != 204:
raise RuntimeError(text) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def del_properties(self, pathobj, props, recursive):
""" Delete artifact properties """ |
if isinstance(props, str):
props = (props,)
url = '/'.join([pathobj.drive,
'api/storage',
str(pathobj.relative_to(pathobj.drive)).strip('/')])
params = {'properties': ','.join(sorted(props))}
if not recursive:
params['recursive'] = '0'
text, code = self.rest_del(url,
params=params,
auth=pathobj.auth,
verify=pathobj.verify,
cert=pathobj.cert)
if code == 404 and "Unable to find item" in text:
raise OSError(2, "No such file or directory: '%s'" % url)
if code != 204:
raise RuntimeError(text) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lowstrip(term):
"""Convert to lowercase and strip spaces""" |
term = re.sub('\s+', ' ', term)
term = term.lower()
return term |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main(left_path, left_column, right_path, right_column, outfile, titles, join, minscore, count, warp):
"""Perform the similarity join""" |
right_file = csv.reader(open(right_path, 'r'))
if titles:
right_header = next(right_file)
index = NGram((tuple(r) for r in right_file),
threshold=minscore,
warp=warp, key=lambda x: lowstrip(x[right_column]))
left_file = csv.reader(open(left_path, 'r'))
out = csv.writer(open(outfile, 'w'), lineterminator='\n')
if titles:
left_header = next(left_file)
out.writerow(left_header + ["Rank", "Similarity"] + right_header)
for row in left_file:
if not row: continue # skip blank lines
row = tuple(row)
results = index.search(lowstrip(row[left_column]), threshold=minscore)
if results:
if count > 0:
results = results[:count]
for rank, result in enumerate(results, 1):
out.writerow(row + (rank, result[1]) + result[0])
elif join == "outer":
out.writerow(row) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def copy(self, items=None):
"""Return a new NGram object with the same settings, and referencing the same items. Copy is shallow in that each item is not recursively copied. Optionally specify alternate items to populate the copy. ['eggs', 'spam'] ['eggs', 'ham', 'spam'] ['bar', 'foo'] """ |
return NGram(items if items is not None else self,
self.threshold, self.warp, self._key,
self.N, self._pad_len, self._pad_char) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def items_sharing_ngrams(self, query):
"""Retrieve the subset of items that share n-grams the query string. :param query: look up items that share N-grams with this string. :return: mapping from matched string to the number of shared N-grams. [('ham', 2), ('spam', 2)] """ |
# From matched string to number of N-grams shared with query string
shared = {}
# Dictionary mapping n-gram to string to number of occurrences of that
# ngram in the string that remain to be matched.
remaining = {}
for ngram in self.split(query):
try:
for match, count in self._grams[ngram].items():
remaining.setdefault(ngram, {}).setdefault(match, count)
# match as many occurrences as exist in matched string
if remaining[ngram][match] > 0:
remaining[ngram][match] -= 1
shared.setdefault(match, 0)
shared[match] += 1
except KeyError:
pass
return shared |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def searchitem(self, item, threshold=None):
"""Search the index for items whose key exceeds the threshold similarity to the key of the given item. :return: list of pairs of (item, similarity) by decreasing similarity. [((0, 'SPAM'), 0.375), ((1, 'SPAN'), 0.375)] """ |
return self.search(self.key(item), threshold) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def search(self, query, threshold=None):
"""Search the index for items whose key exceeds threshold similarity to the query string. :param query: returned items will have at least `threshold` \ similarity to the query string. :return: list of pairs of (item, similarity) by decreasing similarity. [((0, 'SPAM'), 0.375), ((1, 'SPAN'), 0.375)] [((0, 'SPAM'), 0.125)] [((2, 'EG'), 1.0)] """ |
threshold = threshold if threshold is not None else self.threshold
results = []
# Identify possible results
for match, samegrams in self.items_sharing_ngrams(query).items():
allgrams = (len(self.pad(query))
+ self.length[match] - (2 * self.N) - samegrams + 2)
similarity = self.ngram_similarity(samegrams, allgrams, self.warp)
if similarity >= threshold:
results.append((match, similarity))
# Sort results by decreasing similarity
results.sort(key=lambda x: x[1], reverse=True)
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 finditem(self, item, threshold=None):
"""Return most similar item to the provided one, or None if nothing exceeds the threshold. (1, 'Ham') (2, 'Eggsy') """ |
results = self.searchitem(item, threshold)
if results:
return results[0][0]
else:
return None |
<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, query, threshold=None):
"""Simply return the best match to the query, None on no match. 'Ham' 'Spam' """ |
results = self.search(query, threshold)
if results:
return results[0][0]
else:
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ngram_similarity(samegrams, allgrams, warp=1.0):
"""Similarity for two sets of n-grams. :note: ``similarity = (a**e - d**e)/a**e`` where `a` is \ "all n-grams", `d` is "different n-grams" and `e` is the warp. :param samegrams: number of n-grams shared by the two strings. :param allgrams: total of the distinct n-grams across the two strings. :return: similarity in the range 0.0 to 1.0. 0.5 0.75 0.875 0.75 0.75 """ |
if abs(warp - 1.0) < 1e-9:
similarity = float(samegrams) / allgrams
else:
diffgrams = float(allgrams - samegrams)
similarity = ((allgrams ** warp - diffgrams ** warp)
/ (allgrams ** warp))
return similarity |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compare(s1, s2, **kwargs):
"""Compares two strings and returns their similarity. :param s1: first string :param s2: second string :param kwargs: additional keyword arguments passed to __init__. :return: similarity between 0.0 and 1.0. 0.375 0.25 0.375 0.5 """ |
if s1 is None or s2 is None:
if s1 == s2:
return 1.0
return 0.0
try:
return NGram([s1], **kwargs).search(s2)[0][1]
except IndexError:
return 0.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 clear(self):
"""Remove all elements from this set. ['eggs', 'spam'] [] """ |
super(NGram, self).clear()
self._grams = {}
self.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 union(self, *others):
"""Return the union of two or more sets as a new set. ['eggs', 'ham', 'spam'] """ |
return self.copy(super(NGram, self).union(*others)) |
<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, *others):
"""Return the difference of two or more sets as a new set. ['eggs'] """ |
return self.copy(super(NGram, self).difference(*others)) |
<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, *others):
"""Return the intersection of two or more sets as a new set. ['spam'] """ |
return self.copy(super(NGram, self).intersection(*others)) |
<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_update(self, *others):
"""Update the set with the intersection of itself and other sets. ['spam'] """ |
self.difference_update(super(NGram, self).difference(*others)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def symmetric_difference(self, other):
"""Return the symmetric difference of two sets as a new set. ['eggs', 'ham'] """ |
return self.copy(super(NGram, self).symmetric_difference(other)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def symmetric_difference_update(self, other):
"""Update the set with the symmetric difference of itself and `other`. ['eggs', 'ham'] """ |
intersection = super(NGram, self).intersection(other)
self.update(other) # add items present in other
self.difference_update(intersection) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sub(value, arg):
"""Subtract the arg from the value.""" |
try:
nvalue, narg = handle_float_decimal_combinations(
valid_numeric(value), valid_numeric(arg), '-')
return nvalue - narg
except (ValueError, TypeError):
try:
return value - arg
except Exception:
return '' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def absolute(value):
"""Return the absolute value.""" |
try:
return abs(valid_numeric(value))
except (ValueError, TypeError):
try:
return abs(value)
except Exception:
return '' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cli(config, server, api_key, all, credentials, project):
"""Create the cli command line.""" |
# Check first for the pybossa.rc file to configure server and api-key
home = expanduser("~")
if os.path.isfile(os.path.join(home, '.pybossa.cfg')):
config.parser.read(os.path.join(home, '.pybossa.cfg'))
config.server = config.parser.get(credentials,'server')
config.api_key = config.parser.get(credentials, 'apikey')
try:
config.all = config.parser.get(credentials, 'all')
except ConfigParser.NoOptionError:
config.all = None
if server:
config.server = server
if api_key:
config.api_key = api_key
if all:
config.all = all
try:
config.project = json.loads(project.read())
except JSONDecodeError as e:
click.secho("Error: invalid JSON format in project.json:", fg='red')
if e.msg == 'Expecting value':
e.msg += " (if string enclose it with double quotes)"
click.echo("%s\n%s: line %s column %s" % (e.doc, e.msg, e.lineno, e.colno))
raise click.Abort()
try:
project_schema = {
"type": "object",
"properties": {
"name": {"type": "string"},
"short_name": {"type": "string"},
"description": {"type": "string"}
}
}
jsonschema.validate(config.project, project_schema)
except jsonschema.exceptions.ValidationError as e:
click.secho("Error: invalid type in project.json", fg='red')
click.secho("'%s': %s" % (e.path[0], e.message), fg='yellow')
click.echo("'%s' must be a %s" % (e.path[0], e.validator_value))
raise click.Abort()
config.pbclient = pbclient
config.pbclient.set('endpoint', config.server)
config.pbclient.set('api_key', config.api_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 version():
"""Show pbs version.""" |
try:
import pkg_resources
click.echo(pkg_resources.get_distribution('pybossa-pbs').version)
except ImportError:
click.echo("pybossa-pbs package 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 update_project(config, task_presenter, results, long_description, tutorial, watch):
# pragma: no cover """Update project templates and information.""" |
if watch:
res = _update_project_watch(config, task_presenter, results,
long_description, tutorial)
else:
res = _update_project(config, task_presenter, results,
long_description, tutorial)
click.echo(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 update_task_redundancy(config, task_id, redundancy):
"""Update task redudancy for a project.""" |
if task_id is None:
msg = ("Are you sure you want to update all the tasks redundancy?")
if click.confirm(msg):
res = _update_tasks_redundancy(config, task_id, redundancy)
click.echo(res)
else:
click.echo("Aborting.")
else:
res = _update_tasks_redundancy(config, task_id, redundancy)
click.echo(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 _create_project(config):
"""Create a project in a PyBossa server.""" |
try:
response = config.pbclient.create_project(config.project['name'],
config.project['short_name'],
config.project['description'])
check_api_error(response)
return ("Project: %s created!" % config.project['short_name'])
except exceptions.ConnectionError:
return("Connection Error! The server %s is not responding" % config.server)
except (ProjectNotFound, TaskNotFound):
raise |
<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_project_watch(config, task_presenter, results, long_description, tutorial):
# pragma: no cover """Update a project in a loop.""" |
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
path = os.getcwd()
event_handler = PbsHandler(config, task_presenter, results,
long_description, tutorial)
observer = Observer()
# We only want the current folder, not sub-folders
observer.schedule(event_handler, path, recursive=False)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join() |
<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_task_presenter_bundle_js(project):
"""Append to template a distribution bundle js.""" |
if os.path.isfile ('bundle.min.js'):
with open('bundle.min.js') as f:
js = f.read()
project.info['task_presenter'] += "<script>\n%s\n</script>" % js
return
if os.path.isfile ('bundle.js'):
with open('bundle.js') as f:
js = f.read()
project.info['task_presenter'] += "<script>\n%s\n</script>" % js |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _load_data(data_file, data_type):
|
raw_data = data_file.read()
if data_type is None:
data_type = data_file.name.split('.')[-1]
# Data list to process
data = []
# JSON type
if data_type == 'json':
data = json.loads(raw_data)
return data
# CSV type
elif data_type == 'csv':
csv_data = StringIO(raw_data)
reader = csv.DictReader(csv_data, delimiter=',')
for line in reader:
data.append(line)
return data
elif data_type in ['xlsx', 'xlsm', 'xltx', 'xltm']:
excel_data = StringIO(raw_data)
wb = openpyxl.load_workbook(excel_data)
ws = wb.active
# First headers
headers = []
for row in ws.iter_rows(max_row=1):
for cell in row:
tmp = '_'.join(cell.value.split(" ")).lower()
headers.append(tmp)
# Simulate DictReader
for row in ws.iter_rows(row_offset=1):
values = []
for cell in row:
values.append(cell.value)
tmp = dict(itertools.izip(headers, values))
if len(values) == len(headers) and not row_empty(values):
data.append(tmp)
return data
# PO type
elif data_type == 'po':
po = polib.pofile(raw_data)
for entry in po.untranslated_entries():
data.append(entry.__dict__)
return data
# PROPERTIES type (used in Java and Firefox extensions)
elif data_type == 'properties':
lines = raw_data.split('\n')
for l in lines:
if l:
var_id, string = l.split('=')
tmp = dict(var_id=var_id, string=string)
data.append(tmp)
return data
else:
return 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 _update_tasks_redundancy(config, task_id, redundancy, limit=300, offset=0):
"""Update tasks redundancy from a project.""" |
try:
project = find_project_by_short_name(config.project['short_name'],
config.pbclient,
config.all)
if task_id:
response = config.pbclient.find_tasks(project.id, id=task_id)
check_api_error(response)
task = response[0]
task.n_answers = redundancy
response = config.pbclient.update_task(task)
check_api_error(response)
msg = "Task.id = %s redundancy has been updated to %s" % (task_id,
redundancy)
return msg
else:
limit = limit
offset = offset
tasks = config.pbclient.get_tasks(project.id, limit, offset)
with click.progressbar(tasks, label="Updating Tasks") as pgbar:
while len(tasks) > 0:
for t in pgbar:
t.n_answers = redundancy
response = config.pbclient.update_task(t)
check_api_error(response)
# Check if for the data we have to auto-throttle task update
sleep, msg = enable_auto_throttling(config, tasks)
# If auto-throttling enabled, sleep for sleep seconds
if sleep: # pragma: no cover
time.sleep(sleep)
offset += limit
tasks = config.pbclient.get_tasks(project.id, limit, offset)
return "All tasks redundancy have been updated"
except exceptions.ConnectionError:
return ("Connection Error! The server %s is not responding" % config.server)
except (ProjectNotFound, TaskNotFound):
raise |
<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_project_by_short_name(short_name, pbclient, all=None):
"""Return project by short_name.""" |
try:
response = pbclient.find_project(short_name=short_name, all=all)
check_api_error(response)
if (len(response) == 0):
msg = '%s not found! You can use the all=1 argument to \
search in all the server.'
error = 'Project Not Found'
raise ProjectNotFound(msg, error)
return response[0]
except exceptions.ConnectionError:
raise
except ProjectNotFound:
raise |
<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_api_error(api_response):
print(api_response) """Check if returned API response contains an error.""" |
if type(api_response) == dict and 'code' in api_response and api_response['code'] <> 200:
print("Server response code: %s" % api_response['code'])
print("Server response: %s" % api_response)
raise exceptions.HTTPError('Unexpected response', response=api_response)
if type(api_response) == dict and (api_response.get('status') == 'failed'):
if 'ProgrammingError' in api_response.get('exception_cls'):
raise DatabaseError(message='PyBossa database error.',
error=api_response)
if ('DBIntegrityError' in api_response.get('exception_cls') and
'project' in api_response.get('target')):
msg = 'PyBossa project already exists.'
raise ProjectAlreadyExists(message=msg, error=api_response)
if 'project' in api_response.get('target'):
raise ProjectNotFound(message='PyBossa Project not found',
error=api_response)
if 'task' in api_response.get('target'):
raise TaskNotFound(message='PyBossa Task not found',
error=api_response)
else:
print("Server response: %s" % api_response)
raise exceptions.HTTPError('Unexpected response', response=api_response) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_error(module, error):
"""Format the error for the given module.""" |
logging.error(module)
# Beautify JSON error
print error.message
print json.dumps(error.error, sort_keys=True, indent=4, separators=(',', ': '))
exit(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 create_task_info(task):
"""Create task_info field.""" |
task_info = None
if task.get('info'):
task_info = task['info']
else:
task_info = task
return task_info |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_helping_material_info(helping):
"""Create helping_material_info field.""" |
helping_info = None
file_path = None
if helping.get('info'):
helping_info = helping['info']
else:
helping_info = helping
if helping_info.get('file_path'):
file_path = helping_info.get('file_path')
del helping_info['file_path']
return helping_info, file_path |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch_by_code(self, code):
""" Returns data belonging to an authorization code from redis or ``None`` if no data was found. See :class:`oauth2.store.AuthCodeStore`. """ |
code_data = self.read(code)
if code_data is None:
raise AuthCodeNotFound
return AuthorizationCode(**code_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 save_code(self, authorization_code):
""" Stores the data belonging to an authorization code token in redis. See :class:`oauth2.store.AuthCodeStore`. """ |
self.write(authorization_code.code,
{"client_id": authorization_code.client_id,
"code": authorization_code.code,
"expires_at": authorization_code.expires_at,
"redirect_uri": authorization_code.redirect_uri,
"scopes": authorization_code.scopes,
"data": authorization_code.data,
"user_id": authorization_code.user_id}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_token(self, access_token):
""" Stores the access token and additional data in redis. See :class:`oauth2.store.AccessTokenStore`. """ |
self.write(access_token.token, access_token.__dict__)
unique_token_key = self._unique_token_key(access_token.client_id,
access_token.grant_type,
access_token.user_id)
self.write(unique_token_key, access_token.__dict__)
if access_token.refresh_token is not None:
self.write(access_token.refresh_token, access_token.__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 create_access_token_data(self, grant_type):
""" Create data needed by an access token. :param grant_type: :type grant_type: str :return: A ``dict`` containing he ``access_token`` and the ``token_type``. If the value of ``TokenGenerator.expires_in`` is larger than 0, a ``refresh_token`` will be generated too. :rtype: dict """ |
result = {"access_token": self.generate(), "token_type": "Bearer"}
if self.expires_in.get(grant_type, 0) > 0:
result["refresh_token"] = self.generate()
result["expires_in"] = self.expires_in[grant_type]
return 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 _display_token(self):
""" Display token information or redirect to login prompt if none is available. """ |
if self.token is None:
return "301 Moved", "", {"Location": "/login"}
return ("200 OK",
self.TOKEN_TEMPLATE.format(
access_token=self.token["access_token"]),
{"Content-Type": "text/html"}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _request_token(self, env):
""" Retrieves a new access token from the OAuth2 server. """ |
params = {}
content = env['wsgi.input'].read(int(env['CONTENT_LENGTH']))
post_params = parse_qs(content)
# Convert to dict for easier access
for param, value in post_params.items():
decoded_param = param.decode('utf-8')
decoded_value = value[0].decode('utf-8')
if decoded_param == "username" or decoded_param == "password":
params[decoded_param] = decoded_value
params["grant_type"] = "password"
params["client_id"] = self.client_id
params["client_secret"] = self.client_secret
# Request an access token by POSTing a request to the auth server.
try:
response = urllib2.urlopen(self.token_endpoint, urlencode(params))
except HTTPError, he:
if he.code == 400:
error_body = json.loads(he.read())
body = self.SERVER_ERROR_TEMPLATE\
.format(error_type=error_body["error"],
error_description=error_body["error_description"])
return "400 Bad Request", body, {"Content-Type": "text/html"}
if he.code == 401:
return "302 Found", "", {"Location": "/login?failed=1"}
self.token = json.load(response)
return "301 Moved", "", {"Location": "/"} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch_by_client_id(self, client_id):
""" Retrieve a client by its identifier. :param client_id: Identifier of a client app. :return: An instance of :class:`oauth2.Client`. :raises: ClientNotFoundError """ |
if client_id not in self.clients:
raise ClientNotFoundError
return self.clients[client_id] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch_by_code(self, code):
""" Returns an AuthorizationCode. :param code: The authorization code. :return: An instance of :class:`oauth2.datatype.AuthorizationCode`. :raises: :class:`AuthCodeNotFound` if no data could be retrieved for given code. """ |
if code not in self.auth_codes:
raise AuthCodeNotFound
return self.auth_codes[code] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_token(self, access_token):
""" Stores an access token and additional data in memory. :param access_token: An instance of :class:`oauth2.datatype.AccessToken`. """ |
self.access_tokens[access_token.token] = access_token
unique_token_key = self._unique_token_key(access_token.client_id,
access_token.grant_type,
access_token.user_id)
self.unique_token_identifier[unique_token_key] = access_token.token
if access_token.refresh_token is not None:
self.refresh_tokens[access_token.refresh_token] = access_token
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 fetch_by_refresh_token(self, refresh_token):
""" Find an access token by its refresh token. :param refresh_token: The refresh token that was assigned to an ``AccessToken``. :return: The :class:`oauth2.datatype.AccessToken`. :raises: :class:`oauth2.error.AccessTokenNotFound` """ |
if refresh_token not in self.refresh_tokens:
raise AccessTokenNotFound
return self.refresh_tokens[refresh_token] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.