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 generate(length): """Generates random and valid card number which is returned as a string."""
if not isinstance(length, int) or length < 2: raise TypeError('length must be a positive integer greater than 1.') # first digit cannot be 0 digits = [random.randint(1, 9)] for i in range(length-2): digits.append(random.randint(0, 9)) digits.append(get_check_digit(''.join(map(str,...
<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_backend(): """Get backend."""
backend = getattr(settings, 'SIMDITOR_IMAGE_BACKEND', None) if backend == 'pillow': from simditor.image import pillow_backend as backend else: from simditor.image import dummy_backend as backend return backend
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _rspiral(width, height): """Reversed spiral generator. Parameters width : `int` Spiral width. height : `int` Spiral height. Returns ------- `generator` of (`...
x0 = 0 y0 = 0 x1 = width - 1 y1 = height - 1 while x0 < x1 and y0 < y1: for x in range(x0, x1): yield x, y0 for y in range(y0, y1): yield x1, y for x in range(x1, x0, -1): yield x, y1 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _spiral(width, height): """Spiral generator. Parameters width : `int` Spiral width. height : `int` Spiral height. Returns ------- `generator` of (`int`, `int...
if width == 1: for y in range(height - 1, -1, -1): yield 0, y return if height == 1: for x in range(width - 1, -1, -1): yield x, 0 return if width <= height: x0 = width // 2 if width % 2: ...
<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_point_in_block(cls, x, y, block_idx, block_size): """Get point coordinates in next block. Parameters x : `int` X coordinate in current block. y : `int` Y...
if block_idx == 0: return y, x if block_idx == 1: return x, y + block_size if block_idx == 2: return x + block_size, y + block_size if block_idx == 3: x, y = block_size - 1 - y, block_size - 1 - x return x + block_size, y ...
<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_point(cls, idx, size): """Get curve point coordinates by index. Parameters idx : `int` Point index. size : `int` Curve size. Returns ------- (`int`, `int...
x, y = cls.POSITION[idx % 4] idx //= 4 block_size = 2 while block_size < size: block_idx = idx % 4 x, y = cls.get_point_in_block(x, y, block_idx, block_size) idx //= 4 block_size *= 2 return x, y
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __recur_to_dict(forlist, data_dict, res): """Recursive function that fills up the dictionary """
# First we go through all attrs from the ForList and add respective # keys on the dict. for a in forlist.attrs: a_list = a.split('.') if len(a_list) == 1: res = data_dict[a_list[0]] return res if a_list[0] in data_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 to_dict(for_lists, global_vars, data_dict): """ Construct a dict object from a list of ForList object :param for_lists: list of for_list :param global_vars: ...
res = {} # The first level is a little bit special # Manage global variables for a in global_vars: a_list = a.split('.') tmp = res for i in a_list[:-1]: if not i in tmp: tmp[i] = {} tmp = tmp[i] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def logout(request, redirect_url=settings.LOGOUT_REDIRECT_URL): """ Nothing hilariously hidden here, logs a user out. Strip this out if your application already ...
django_logout(request) return HttpResponseRedirect(request.build_absolute_uri(redirect_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 begin_auth(request): """The view function that initiates the entire handshake. For the most part, this is 100% drag and drop. """
# Instantiate Twython with the first leg of our trip. twitter = Twython(settings.TWITTER_KEY, settings.TWITTER_SECRET) # Request an authorization url to send the user to... callback_url = request.build_absolute_uri(reverse('twython_django_oauth.views.thanks')) auth_props = twitter.get_authenticati...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def thanks(request, redirect_url=settings.LOGIN_REDIRECT_URL): """A user gets redirected here after hitting Twitter and authorizing your app to use their data. T...
# Now that we've got the magic tokens back from Twitter, we need to exchange # for permanent ones and store them... oauth_token = request.session['request_token']['oauth_token'] oauth_token_secret = request.session['request_token']['oauth_token_secret'] twitter = Twython(settings.TWITTER_KEY, setti...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _imgdata(self, width, height, state_size=None, start='', dataset=''): """Generate image pixels. Parameters width : `int` Image width. height : `int` Image he...
size = width * height if size > 0 and start: yield state_to_pixel(start) size -= 1 while size > 0: prev_size = size pixels = self.generate(state_size, start, dataset) pixels = islice(pixels, 0, size) for pixel in pixels:...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _write_imgdata(img, data, tr, x=0, y=0): """Write image data. Parameters img : `PIL.Image.Image` Image. data : `iterable` of `int` Image data. tr : `markovch...
for pixel, (x1, y1) in zip(data, tr): img.putpixel((x + x1, y + y1), pixel) return img
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _channel(self, width, height, state_sizes, start_level, start_image, dataset): """Generate a channel. Parameters width : `int` Image width. height : `int` Im...
ret = start_image for level, state_size in enumerate(state_sizes, start_level + 1): key = dataset + level_dataset(level) if start_image is not None: scale = self.scanner.level_scale[level - 1] width *= scale height *= scale ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ravel(parameter, random_state=None): """ Flatten a ``Parameter``. Parameters parameter: Parameter A ``Parameter`` object Returns ------- flatvalue: ndarray a...
flatvalue = np.ravel(parameter.rvs(random_state=random_state)) flatbounds = [parameter.bounds for _ in range(np.prod(parameter.shape, dtype=int))] return flatvalue, flatbounds
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hstack(tup): """ Horizontally stack a sequence of value bounds pairs. Parameters tup: sequence a sequence of value, ``Bound`` pairs Returns ------- value: nd...
vals, bounds = zip(*tup) stackvalue = np.hstack(vals) stackbounds = list(chain(*bounds)) return stackvalue, stackbounds
<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(self, value): """ Check a value falls within a bound. Parameters value : scalar or ndarray value to test Returns ------- bool: If all values fall withi...
if self.lower: if np.any(value < self.lower): return False if self.upper: if np.any(value > self.upper): return False 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 clip(self, value): """ Clip a value to a bound. Parameters value : scalar or ndarray value to clip Returns ------- scalar or ndarray : of the same shape as v...
if not self.lower and not self.upper: return value return np.clip(value, self.lower, self.upper)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rvs(self, random_state=None): r""" Draw a random value from this Parameter's distribution. If ``value`` was not initialised with a ``scipy.stats`` object, th...
# No sampling distibution if self.dist is None: return self.value # Unconstrained samples rs = check_random_state(random_state) samples = self.dist.rvs(size=self.shape, random_state=rs) # Bound the samples samples = self.bounds.clip(samples) ...
<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_missing_trees(self, path, root_tree): """ Creates missing ``Tree`` objects for the given path. :param path: path given as a string. It may be a path to ...
dirpath = posixpath.split(path)[0] dirs = dirpath.split('/') if not dirs or dirs == ['']: return [] def get_tree_for_dir(tree, dirname): for name, mode, id in tree.iteritems(): if name == dirname: obj = self.repository._repo[i...
<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_list(x): """Convert a value to a list. Parameters x Value. Returns ------- `list` Examples -------- [0] [{'x': 0}] [0, 1, 4] [1, 2, 3] True """
if isinstance(x, list): return x if not isinstance(x, dict): try: return list(x) except TypeError: pass return [x]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fill(xs, length, copy=False): """Convert a value to a list of specified length. If the input is too short, fill it with its last element. Parameters xs Input...
if isinstance(xs, list) and len(xs) == length: return xs if length <= 0: return [] try: xs = list(islice(xs, 0, length)) if not xs: raise ValueError('empty input') except TypeError: xs = [xs] if len(xs) < length: if copy: la...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def int_enum(cls, val): """Get int enum value. Parameters cls : `type` Int enum class. val : `int` or `str` Name or value. Returns ------- `IntEnum` Raises -----...
if isinstance(val, str): val = val.upper() try: return getattr(cls, val) except AttributeError: raise ValueError('{0}.{1}'.format(cls, val)) return cls(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 load(obj, cls, default_factory): """Create or load an object if necessary. Parameters obj : `object` or `dict` or `None` cls : `type` default_factory : `func...
if obj is None: return default_factory() if isinstance(obj, dict): return cls.load(obj) return obj
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def truncate(string, maxlen, end=True): """Truncate a string. Parameters string : `str` String to truncate. maxlen : `int` Maximum string length. end : `boolean`...
if maxlen <= 3: raise ValueError('maxlen <= 3') if len(string) <= maxlen: return string if end: return string[:maxlen - 3] + '...' return '...' + string[3 - maxlen:]
<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_class(cls, *args): """Add classes to the group. Parameters *args : `type` Classes to add. """
for cls2 in args: cls.classes[cls2.__name__] = cls2
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_class(cls, *args): """Remove classes from the group. Parameters *args : `type` Classes to remove. """
for cls2 in args: try: del cls.classes[cls2.__name__] except KeyError: pass
<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(cls, data): """Create an object from JSON data. Parameters data : `dict` JSON data. Returns `object` Created object. Raises ------ KeyError If `data` do...
ret = cls.classes[data['__class__']] data_cls = data['__class__'] del data['__class__'] try: ret = ret(**data) finally: data['__class__'] = data_cls return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_oauth_client(self, consumer_key, consumer_secret): """Sets the oauth_client attribute """
self.oauth_client = oauth1.Client(consumer_key, consumer_secret)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare_request(self, method, url, body=''): """Prepare the request body and headers :returns: headers of the signed request """
headers = { 'Content-type': 'application/json', } # Note: we don't pass body to sign() since it's only for bodies that # are form-urlencoded. Similarly, we don't care about the body that # sign() returns. uri, signed_headers, signed_body = self.oauth_client.s...
<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_error_reason(response): """Extract error reason from the response. It might be either the 'reason' or the entire response """
try: body = response.json() if body and 'reason' in body: return body['reason'] except ValueError: pass return response.content
<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(self, method, url, data=None, expected_status_code=None): """Prepare the headers, encode data, call API and provide data it returns """
kwargs = self.prepare_request(method, url, data) log.debug(json.dumps(kwargs)) response = getattr(requests, method.lower())(url, **kwargs) log.debug(json.dumps(response.content)) if response.status_code >= 400: response.raise_for_status() if (expected_status_...
<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_json(self, method, url, data=None, expected_status_code=None): """Return json decoded data from fetch """
return self.fetch(method, url, data, expected_status_code).json()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def structured_minimizer(minimizer): r""" Allow an optimizer to accept nested sequences of Parameters to optimize. This decorator can intepret the :code:`Paramet...
@wraps(minimizer) def new_minimizer(fun, parameters, jac=True, args=(), nstarts=0, random_state=None, **minimizer_kwargs): (array1d, fbounds), shapes = flatten( parameters, hstack=bt.hstack, shape=bt.shape, ravel=partial(bt.ravel, 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 structured_sgd(sgd): r""" Allow an SGD to accept nested sequences of Parameters to optimize. This decorator can intepret the :code:`Parameter` objects in `bt...
@wraps(sgd) def new_sgd(fun, parameters, data, eval_obj=False, batch_size=10, args=(), random_state=None, nstarts=100, **sgd_kwargs): (array1d, fbounds), shapes = flatten(par...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def logtrick_minimizer(minimizer): r""" Log-Trick decorator for optimizers. This decorator implements the "log trick" for optimizing positive bounded variables. ...
@wraps(minimizer) def new_minimizer(fun, x0, jac=True, bounds=None, **minimizer_kwargs): if bounds is None: return minimizer(fun, x0, jac=jac, bounds=bounds, **minimizer_kwargs) logx, expx, gradx, bounds = _logtrick_gen(bounds) # Intercept gra...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def logtrick_sgd(sgd): r""" Log-Trick decorator for stochastic gradients. This decorator implements the "log trick" for optimizing positive bounded variables usi...
@wraps(sgd) def new_sgd(fun, x0, data, bounds=None, eval_obj=False, **sgd_kwargs): if bounds is None: return sgd(fun, x0, data, bounds=bounds, eval_obj=eval_obj, **sgd_kwargs) logx, expx, gradx, bounds = _logtrick_gen(bounds) if bool(eval_obj): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flatten_grad(func): r""" Decorator to flatten structured gradients. Examples -------- 2 (3,) () array([ 0.125, 0.025, -0.05 ]) True array([ 0.125, 0.025, -0....
@wraps(func) def new_func(*args, **kwargs): return flatten(func(*args, **kwargs), returns_shapes=False) return new_func
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flatten_func_grad(func): r""" Decorator to flatten structured gradients and return objective. Examples -------- True 2 (3,) () array([ 0.125, 0.025, -0.05 ])...
@wraps(func) def new_func(*args, **kwargs): val, grad = func(*args, **kwargs) return val, flatten(grad, returns_shapes=False) return new_func
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flatten_args(shapes): r""" Decorator to flatten structured arguments to a function. Examples -------- True True Some other curious applications array([ 1.86 ...
def flatten_args_dec(func): @wraps(func) def new_func(array1d, *args, **kwargs): args = tuple(unflatten(array1d, shapes)) + args return func(*args, **kwargs) return new_func return flatten_args_dec
<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_starts(fun, parameters, jac, args, nstarts, random_state, data_gen=None): """Generate and evaluate random starts for Parameter objects."""
if nstarts < 1: raise ValueError("nstarts has to be greater than or equal to 1") # Check to see if there are any random parameter types anyrand = any(flatten(map_recursive(lambda p: p.is_random, parameters), returns_shapes=False)) if not anyrand: log.info("No random ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _logtrick_gen(bounds): """Generate warping functions and new bounds for the log trick."""
# Test which parameters we can apply the log trick too ispos = np.array([isinstance(b, bt.Positive) for b in bounds], dtype=bool) nispos = ~ispos # Functions that implement the log trick def logx(x): xwarp = np.empty_like(x) xwarp[ispos] = np.log(x[ispos]) xwarp[nispos] = x...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_url(cls, url): """ Functon will check given url and try to verify if it's a valid link. Sometimes it may happened that mercurial will issue basic auth...
# check first if it's not an local url if os.path.isdir(url) or url.startswith('file:'): return True if('+' in url[:url.find('://')]): url = url[url.find('+') + 1:] handlers = [] test_uri, authinfo = hg_url(url).authinfo() if not test_uri.endsw...
<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_revision(self, revision): """ For git backend we always return integer here. This way we ensure that changset's revision attribute would become integer....
is_null = lambda o: len(o) == revision.count('0') try: self.revisions[0] except (KeyError, IndexError): raise EmptyRepositoryError("There are no changesets yet") if revision in (None, '', 'tip', 'HEAD', 'head', -1): return self.revisions[-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 get_hook_location(self): """ returns absolute path to location where hooks are stored """
loc = os.path.join(self.path, 'hooks') if not self.bare: loc = os.path.join(self.path, '.git', 'hooks') return loc
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clone(self, url, update_after_clone=True, bare=False): """ Tries to clone changes from external location. :param update_after_clone: If set to ``False``, git...
url = self._get_url(url) cmd = ['clone'] if bare: cmd.append('--bare') elif not update_after_clone: cmd.append('--no-checkout') cmd += ['--', '"%s"' % url, '"%s"' % self.path] cmd = ' '.join(cmd) # If error occurs run_git_command raises Re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def annotate_from_changeset(self, changeset): """ Returns full html line for single changeset per annotated line. """
if self.annotate_from_changeset_func: return self.annotate_from_changeset_func(changeset) else: return ''.join((changeset.id, '\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 _obtain_lock_or_raise(self): """Create a lock file as flag for other instances, mark our instance as lock-holder :raise IOError: if a lock was already presen...
if self._has_lock(): return lock_file = self._lock_file_path() if os.path.isfile(lock_file): raise IOError("Lock for file %r did already exist, delete %r in case the lock is illegal" % (self._file_path, lock_file)) try: fd = os.open(lock_file, os.O_W...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def objectify_uri(relative_uri): '''Converts uris from path syntax to a json-like object syntax. In addition, url escaped characters are unescaped, but non-ascii characters a romanized using the unidecode library. Examples: "/blog/3/comments" becomes "blog[3].comments" "car/engine/piston"...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def parse_media_type(media_type): '''Returns type, subtype, parameter tuple from an http media_type. Can be applied to the 'Accept' or 'Content-Type' http header fields. ''' media_type, sep, parameter = str(media_type).partition(';') media_type, sep, subtype = media_type.partition('/') return tu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getpath(d, json_path, default=None, sep='.'): '''Gets a value nested in dictionaries containing dictionaries. Returns the default if any key in the path doesn't exist. ''' for key in json_path.split(sep): try: d = d[key] except (KeyError, TypeError): return de...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getstate(d): '''Deep copies a dict, and returns it without the keys _links and _embedded ''' if not isinstance(d, dict): raise TypeError("Can only get the state of a dictionary") cpd = copy.deepcopy(d) cpd.pop('_links', None) cpd.pop('_embedded', None) return cpd
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def append_with(self, obj, **properties): '''Add an item to the dictionary with the given metadata properties''' for prop, val in properties.items(): val = self.serialize(val) self._meta.setdefault(prop, {}).setdefault(val, []).append(obj) self.append(obj)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_by(self, prop, val, raise_exc=False): '''Retrieve an item from the dictionary with the given metadata properties. If there is no such item, None will be returned, if there are multiple such items, the first will be returned.''' try: val = self.serialize(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 getall_by(self, prop, val): '''Retrieves all items from the dictionary with the given metadata''' try: val = self.serialize(val) return self._meta[prop][val][:] # return a copy of the list except KeyError: 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 do_replace_state_separator(data, old, new): """Replace state separator. Parameters data : `dict` of `dict` of ([`int`, `str`] or [`list` of `int`, `list` of ...
for key, dataset in data.items(): data[key] = dict( (k.replace(old, new), v) for k, v in dataset.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 do_get_dataset(data, key, create=False): """Get a dataset. Parameters data : `None` or `dict` of `dict` of ([`int`, `str`] or [`list` of `int`, `list` of `st...
if data is None: return None try: return data[key] except KeyError: if create: dataset = {} data[key] = dataset return dataset else: 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 add_link(dataset, source, target, count=1): """Add a link. Parameters dataset : `dict` of ([`int`, `str`] or [`list` of `int`, `list` of `str`]) Dataset. sou...
try: node = dataset[source] values, links = node if isinstance(links, list): try: idx = links.index(target) values[idx] += count except ValueError: links.append(target) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def chain_user_names(users, exclude_user, truncate=35): """Tag to return a truncated chain of user names."""
if not users or not isinstance(exclude_user, get_user_model()): return '' return truncatechars( ', '.join(u'{}'.format(u) for u in users.exclude(pk=exclude_user.pk)), truncate)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def url(self, key): """Creates a full URL to the API using urls dict """
return urlunparse((self.protocol, '%s:%s' % (self.domain, self.port), '%s/api/v1%s' % (self.prefix, URLS[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 is_manifest_valid(self, manifest_id): """Check validation shortcut :param: manifest_id (string) id received in :method:`validate_manifest` :returns: * True i...
response = self.get_manifest_validation_result(manifest_id) if response.status_code != 200: raise Exception(response.status_code) content = json.loads(response.content) if not content['processed']: return None if content['valid']: 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 update(self, app_id, data): """Update app identified by app_id with data :params: * app_id (int) id in the marketplace received with :method:`create` * data ...
assert ('name' in data and data['name'] and 'summary' in data and 'categories' in data and data['categories'] and 'support_email' in data and data['support_email'] and 'device_types' in 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_screenshot(self, app_id, filename, position=1): """Add a screenshot to the web app identified by by ``app_id``. Screenshots are ordered by ``position`...
# prepare file for upload with open(filename, 'rb') as s_file: s_content = s_file.read() s_encoded = b64encode(s_content) url = self.url('create_screenshot') % app_id mtype, encoding = mimetypes.guess_type(filename) if mtype is None: mtype = 'ima...
<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_content_ratings(self, app_id, submission_id, security_code): """Add content ratings to the web app identified by by ``app_id``, using the specified submi...
url = self.url('content_ratings') % app_id return self.conn.fetch('POST', url, {'submission_id': '%s' % submission_id, 'security_code': '%s' % security_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(self): """Convert the scanner to JSON. Returns ------- `dict` JSON data. """
data = super().save() data['expr'] = self.expr.pattern data['default_end'] = self.default_end 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 _get_branches(self, closed=False): """ Get's branches for this repository Returns only not closed branches by default :param closed: return also closed branc...
if self._empty: return {} def _branchtags(localrepo): """ Patched version of mercurial branchtags to not return the closed branches :param localrepo: locarepository instance """ bt = {} bt_closed = {} ...
<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_repo(self, create, src_url=None, update_after_clone=False): """ Function will check for mercurial repository in given path and return a localrepo object...
try: if src_url: url = str(self._get_url(src_url)) opts = {} if not update_after_clone: opts.update({'noupdate': True}) try: MercurialRepository._check_url(url) clone(self.ba...
<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_revision(self, revision): """ Get's an ID revision given as str. This will always return a fill 40 char revision number :param revision: str or int or N...
if self._empty: raise EmptyRepositoryError("There are no changesets yet") if revision in [-1, 'tip', None]: revision = 'tip' try: revision = hex(self._repo.lookup(revision)) except (IndexError, ValueError, RepoLookupError, TypeError): 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 get_changeset(self, revision=None): """ Returns ``MercurialChangeset`` object representing repository's changeset at the given ``revision``. """
revision = self._get_revision(revision) changeset = MercurialChangeset(repository=self, revision=revision) return changeset
<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(self, parts): """Format generated text. Parameters parts : `iterable` of `str` Text parts. """
text = self.storage.state_separator.join(parts) return self.formatter(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 generate_replies(self, max_length, state_size, reply_to, dataset): """Generate replies. Parameters max_length : `int` or `None` Maximum sentence length. stat...
state_sets = self.get_reply_states( reply_to, dataset + state_size_dataset(state_size) ) if not state_sets: yield from self.generate_cont(max_length, state_size, None, False, dataset) return rand...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def size(self): """ Returns combined size in bytes for all repository files """
size = 0 try: tip = self.get_changeset() for topnode, dirs, files in tip.walk('/'): for f in files: size += tip.get_file_size(f.path) for dir in dirs: for f in files: size += tip.get...
<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_changesets(self, start=None, end=None, start_date=None, end_date=None, branch_name=None, reverse=False): """ Returns iterator of ``MercurialChangeset`` o...
raise NotImplementedError
<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_chunked_archive(self, **kwargs): """ Returns iterable archive. Tiny wrapper around ``fill_archive`` method. :param chunk_size: extra parameter which cont...
chunk_size = kwargs.pop('chunk_size', 8192) stream = kwargs.get('stream') self.fill_archive(**kwargs) while True: data = stream.read(chunk_size) if not data: break yield 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 as_dict(self): """ Returns dictionary with changeset's attributes and their values. """
data = get_dict_for_attrs(self, ['id', 'raw_id', 'short_id', 'revision', 'date', 'message']) data['author'] = {'name': self.author_name, 'email': self.author_email} data['added'] = [node.path for node in self.added] data['changed'] = [node.path for node in self.changed] ...
<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_ipaths(self): """ Returns generator of paths from nodes marked as added, changed or removed. """
for node in itertools.chain(self.added, self.changed, self.removed): yield node.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 check_integrity(self, parents=None): """ Checks in-memory changeset's integrity. Also, sets parents if not already set. :raises CommitError: if any error occ...
if not self.parents: parents = parents or [] if len(parents) == 0: try: parents = [self.repository.get_changeset(), None] except EmptyRepositoryError: parents = [None, None] elif len(parents) == 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 get_file_content(self, path): """ Returns content of the file at given ``path``. """
id = self._get_id_for_path(path) blob = self.repository._repo[id] return blob.as_pretty_string()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_file_size(self, path): """ Returns size of the file at given ``path``. """
id = self._get_id_for_path(path) blob = self.repository._repo[id] return blob.raw_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 affected_files(self): """ Get's a fast accessible file changes for given changeset """
added, modified, deleted = self._changes_cache return list(added.union(modified).union(deleted))
<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_paths_for_status(self, status): """ Returns sorted list of paths for given ``status``. :param status: one of: *added*, *modified* or *deleted* """
added, modified, deleted = self._changes_cache return sorted({ 'added': list(added), 'modified': list(modified), 'deleted': list(deleted)}[status] )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def added(self): """ Returns list of added ``FileNode`` objects. """
if not self.parents: return list(self._get_file_nodes()) return AddedFileNodesGenerator([n for n in self._get_paths_for_status('added')], self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def changed(self): """ Returns list of modified ``FileNode`` objects. """
if not self.parents: return [] return ChangedFileNodesGenerator([n for n in self._get_paths_for_status('modified')], self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def removed(self): """ Returns list of removed ``FileNode`` objects. """
if not self.parents: return [] return RemovedFileNodesGenerator([n for n in self._get_paths_for_status('deleted')], self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sgd(fun, x0, data, args=(), bounds=None, batch_size=10, maxiter=5000, updater=None, eval_obj=False, random_state=None): """ Stochastic Gradient Descent. Para...
if updater is None: updater = Adam() # Make sure we aren't using a recycled updater updater.reset() N = _len_data(data) x = np.array(x0, copy=True, dtype=float) D = x.shape[0] # Make sure we have a valid batch size batch_size = min(batch_size, N) # Process bounds if ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gen_batch(data, batch_size, maxiter=np.inf, random_state=None): """ Create random batches for Stochastic gradients. Batch index generator for SGD that will y...
perms = endless_permutations(_len_data(data), random_state) it = 0 while it < maxiter: it += 1 ind = np.array([next(perms) for _ in range(batch_size)]) yield _split_data(data, ind)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def normalize_bound(bound): """ Replace ``None`` with + or - inf in bound tuples. Examples -------- (2.6, 7.2) (-inf, 7.2) (2.6, inf) (-inf, inf) This operation ...
min_, max_ = bound if min_ is None: min_ = -float('inf') if max_ is None: max_ = float('inf') return min_, max_
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset(self): """Reset the state of this updater for a new optimisation problem."""
self.__init__(self.alpha, self.beta1, self.beta2, self.epsilon)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def aslist(obj, sep=None, strip=True): """ Returns given string separated by sep as list :param obj: :param sep: :param strip: """
if isinstance(obj, (basestring)): lst = obj.split(sep) if strip: lst = [v.strip() for v in lst] return lst elif isinstance(obj, (list, tuple)): return obj elif obj is None: return [] else: return [obj]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def safe_unicode(str_, from_encoding=None): """ safe unicode function. Does few trick to turn str_ into unicode In case of UnicodeDecode error we try to return i...
if isinstance(str_, unicode): return str_ if not from_encoding: from vcs.conf import settings from_encoding = settings.DEFAULT_ENCODINGS if not isinstance(from_encoding, (list, tuple)): from_encoding = [from_encoding] try: return unicode(str_) except Unico...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def safe_str(unicode_, to_encoding=None): """ safe str function. Does few trick to turn unicode_ into string In case of UnicodeEncodeError we try to return it wi...
# if it's not basestr cast to str if not isinstance(unicode_, basestring): return str(unicode_) if isinstance(unicode_, str): return unicode_ if not to_encoding: from vcs.conf import settings to_encoding = settings.DEFAULT_ENCODINGS if not isinstance(to_encoding,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def author_name(author): """ get name of author, or else username. It'll try to find an email in the author string and just cut it off to get the username """
if not '@' in author: return author else: return author.replace(author_email(author), '').replace('<', '')\ .replace('>', '').strip()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fit(self, X, y): """ Learn the hyperparameters of a Bayesian linear regressor. Parameters X : ndarray (N, d) array input dataset (N samples, d dimensions). y...
X, y = check_X_y(X, y) self.obj_ = -np.inf # Make list of parameters and decorate optimiser to undestand this params = [self.var, self.basis.regularizer, self.basis.params] nmin = structured_minimizer(logtrick_minimizer(minimize)) # Close over objective and learn para...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def predict_moments(self, X): """ Full predictive distribution from Bayesian linear regression. Parameters X : ndarray (N*,d) array query input dataset (N* sampl...
check_is_fitted(self, ['var_', 'regularizer_', 'weights_', 'covariance_', 'hypers_']) X = check_array(X) Phi = self.basis.transform(X, *atleast_list(self.hypers_)) Ey = Phi.dot(self.weights_) Vf = (Phi.dot(self.covariance_) * Phi).sum(axis=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 emit_iana_rels(rels_url): '''Fetches the IANA link relation registry''' text = requests.get(rels_url).text.encode('ascii', 'ignore') xml = objectify.fromstring(text) iana_rels = {str(rec.value): str(rec.description) for rec in xml.registry.record} keys = sorted(iana_rels) pr...
<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_dirs_for_path(*paths): """ Returns list of directories, including intermediate. """
for path in paths: head = path while head: head, tail = os.path.split(head) if head: yield head else: # We don't need to yield empty path 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 get_tables(self): """Get all table names. Returns ------- `set` of `str` """
self.cursor.execute( 'SELECT name FROM sqlite_master WHERE type="table"' ) return set(x[0] for x in self.cursor.fetchall())
<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_node(self, value): """Get node ID by value. If a node with the specified value does not exist, create it and return its ID. Parameters value : `str` Node...
while True: self.cursor.execute( 'SELECT id FROM nodes WHERE value=?', (value,) ) node = self.cursor.fetchone() if node is not None: return node[0] self.cursor.execute( 'INSERT INTO nodes...
<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_main_table(self): """Write generator settings to database. """
data = (json.dumps(self.settings),) self.cursor.execute(''' CREATE TABLE IF NOT EXISTS main ( settings TEXT NOT NULL DEFAULT "{}" ) ''') self.cursor.execute('SELECT * FROM main') if self.cursor.fetchall() == []: self.cursor.exe...
<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_node_tables(self): """Create node and link tables if they don't exist. """
self.cursor.execute('PRAGMA foreign_keys=1') self.cursor.execute(''' CREATE TABLE IF NOT EXISTS datasets ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, key TEXT NOT NULL ) ''') self.cursor.execute(''' CREATE TABLE IF ...