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...
<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 o...
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 ...
<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.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. ...
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`` u...
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 ``s...
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:: Tra...
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 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 memoized(fn=None, cache=None): """ Memoize a function into an optionally-specificed cache container. If the `cache` container is not specified, then the inst...
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 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 memoized_method(method=None, cache_factory=None): """ Memoize a class's method. Arguments are similar to to `memoized`, except that the cache container is sp...
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,...
<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),...
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 ...
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 e...
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 ``typ...
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`...
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-friend...
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...
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 elem...
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 conv...
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=Fa...
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 w...
# 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: ...
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. ...
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: ...
<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 ...
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>' % (ope...
<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 inclu...
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)...
<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_positio...
<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=se...
<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_packa...
<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: ...
<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.ab...
<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 boole...
<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...
<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...
<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 = No...
<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 matc...
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_d...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encode_properties(parameters): """ Performs encoding of url parameters from dictionary to a string. It does not escape backslash because it is not needed. Se...
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 ...
<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 ...
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...
<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, ...
<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,...
<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: pa...
<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')) ou...
<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 recursi...
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 t...
# 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: ...
<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 ...
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 w...
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) - samegr...
<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-gram...
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 k...
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....
<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...
<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!" % ...
<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 = O...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _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['...
<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 = StringI...
<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_...
<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' rai...
<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...
<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.AuthCode...
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, "scop...
<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...
<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`` containin...
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('u...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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:`o...
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.Authorizati...
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.AccessT...
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_identifi...
<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 `...
if refresh_token not in self.refresh_tokens: raise AccessTokenNotFound return self.refresh_tokens[refresh_token]