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 crps_gaussian(x, mu, sig, grad=False):
""" Computes the CRPS of observations x relative to normally distributed forecasts with mean, mu, and standard deviati... |
x = np.asarray(x)
mu = np.asarray(mu)
sig = np.asarray(sig)
# standadized x
sx = (x - mu) / sig
# some precomputations to speed up the gradient
pdf = _normpdf(sx)
cdf = _normcdf(sx)
pi_inv = 1. / np.sqrt(np.pi)
# the actual crps
crps = sig * (sx * (2 * cdf - 1) + 2 * pdf - p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _discover_bounds(cdf, tol=1e-7):
""" Uses scipy's general continuous distribution methods which compute the ppf from the cdf, then use the ppf to find the lo... |
class DistFromCDF(stats.distributions.rv_continuous):
def cdf(self, x):
return cdf(x)
dist = DistFromCDF()
# the ppf is the inverse cdf
lower = dist.ppf(tol)
upper = dist.ppf(1. - tol)
return lower, 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 _crps_cdf_single(x, cdf_or_dist, xmin=None, xmax=None, tol=1e-6):
""" See crps_cdf for docs. """ |
# TODO: this function is pretty slow. Look for clever ways to speed it up.
# allow for directly passing in scipy.stats distribution objects.
cdf = getattr(cdf_or_dist, 'cdf', cdf_or_dist)
assert callable(cdf)
# if bounds aren't given, discover them
if xmin is None or xmax is 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 _crps_ensemble_vectorized(observations, forecasts, weights=1):
""" An alternative but simpler implementation of CRPS for testing purposes This implementation... |
observations = np.asarray(observations)
forecasts = np.asarray(forecasts)
weights = np.asarray(weights)
if weights.ndim > 0:
weights = np.where(~np.isnan(forecasts), weights, np.nan)
weights = weights / np.nanmean(weights, axis=-1, keepdims=True)
if observations.ndim == forecasts.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 clear(self):
"""Deletes the history""" |
self._points = _np.empty( (self.prealloc,self.dim) )
self._slice_for_run_nr = []
self.memleft = self.prealloc |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dispatch(self, request, *args, **kwargs):
"""Dispatch all HTTP methods to the proxy.""" |
self.request = DownstreamRequest(request)
self.args = args
self.kwargs = kwargs
self._verify_config()
self.middleware = MiddlewareSet(self.proxy_middleware)
return self.proxy() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def proxy(self):
"""Retrieve the upstream content and build an HttpResponse.""" |
headers = self.request.headers.filter(self.ignored_request_headers)
qs = self.request.query_string if self.pass_query_string else ''
# Fix for django 1.10.0 bug https://code.djangoproject.com/ticket/27005
if (self.request.META.get('CONTENT_LENGTH', None) == '' and
get_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 shell_out(cmd, stderr=STDOUT, cwd=None):
"""Friendlier version of check_output.""" |
if cwd is None:
from os import getcwd
cwd = getcwd() # TODO do I need to normalize this on Windows
out = check_output(cmd, cwd=cwd, stderr=stderr, universal_newlines=True)
return _clean_output(out) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def shell_out_ignore_exitcode(cmd, stderr=STDOUT, cwd=None):
"""Same as shell_out but doesn't raise if the cmd exits badly.""" |
try:
return shell_out(cmd, stderr=stderr, cwd=cwd)
except CalledProcessError as c:
return _clean_output(c.output) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def from_dir(cwd):
"Context manager to ensure in the cwd directory."
import os
curdir = os.getcwd()
try:
os.chdir(cwd)
yield
finally:
os.chdir(curdir) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def text_filter(regex_base, value):
""" A text-filter helper, used in ``markdown_thumbnails``-filter and ``html_thumbnails``-filter. It can be used to build cust... |
from thumbnails import get_thumbnail
regex = regex_base % {
'caption': '[a-zA-Z0-9\.\,:;/_ \(\)\-\!\?\"]+',
'image': '[a-zA-Z0-9\.:/_\-\% ]+'
}
images = re.findall(regex, value)
for i in images:
image_url = i[1]
image = get_thumbnail(
image_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 eat(self, argv=None):
""" Eat the guacamole. :param argv: Command line arguments or None. None means that sys.argv is used :return: Whatever is returned by t... |
# The setup phase, here KeyboardInterrupt is a silent sign to exit the
# application. Any error that happens here will result in a raw
# backtrace being printed to the user.
try:
self.context.argv = argv
self._added()
self._build_early_parser()
... |
<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):
"""Delete the history.""" |
self.sampler.clear()
self.samples_list = self._comm.gather(self.sampler.samples, root=0)
if hasattr(self.sampler, 'weights'):
self.weights_list = self._comm.gather(self.sampler.weights, root=0)
else:
self.weights_list = 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 path(self, path):
""" Creates a path based on the location attribute of the backend and the path argument of the function. If the path argument is an absolut... |
if os.path.isabs(path):
return path
return os.path.join(self.location, 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 run(self, eps=1e-4, kill=True, max_steps=50, verbose=False):
r"""Perform the clustering on the input components updating the initial guess. The result is ava... |
old_distance = np.finfo(np.float64).max
new_distance = np.finfo(np.float64).max
if verbose:
print('Starting hierarchical clustering with %d components.' % len(self.g.components))
converged = False
for step in range(1, max_steps + 1):
self._cleanup(kill, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def eventdata(payload):
""" Parse a Supervisor event. """ |
headerinfo, data = payload.split('\n', 1)
headers = get_headers(headerinfo)
return headers, 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 supervisor_events(stdin, stdout):
""" An event stream from Supervisor. """ |
while True:
stdout.write('READY\n')
stdout.flush()
line = stdin.readline()
headers = get_headers(line)
payload = stdin.read(int(headers['len']))
event_headers, event_data = eventdata(payload)
yield event_headers, event_data
stdout.write('RESULT 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 main():
""" Main application loop. """ |
env = os.environ
try:
host = env['SYSLOG_SERVER']
port = int(env['SYSLOG_PORT'])
socktype = socket.SOCK_DGRAM if env['SYSLOG_PROTO'] == 'udp' \
else socket.SOCK_STREAM
except KeyError:
sys.exit("SYSLOG_SERVER, SYSLOG_PORT and SYSLOG_PROTO are required.")
h... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def formatTime(self, record, datefmt=None):
""" Format time, including milliseconds. """ |
formatted = super(PalletFormatter, self).formatTime(
record, datefmt=datefmt)
return formatted + '.%03dZ' % record.msecs |
<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_diff(original, fixed, file_name, original_label='original', fixed_label='fixed'):
"""Return text of unified diff between original and fixed.""" |
original, fixed = original.splitlines(True), fixed.splitlines(True)
newline = '\n'
from difflib import unified_diff
diff = unified_diff(original, fixed,
os.path.join(original_label, file_name),
os.path.join(fixed_label, file_name),
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def run(self, N=1):
'''Run the chain and store the history of visited points into
the member variable ``self.samples``. Returns the number of
accepted points during the run.
.. seealso::
:py:class:`pypmc.tools.History`
:param N:
An int which defines the... |
<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_adapt_params(self, *args, **kwargs):
r"""Sets variables for covariance adaptation. When :meth:`.adapt` is called, the proposal's covariance matrix is ada... |
if args != (): raise TypeError('keyword args only; try set_adapt_parameters(keyword = value)')
self.covar_scale_multiplier = kwargs.pop('covar_scale_multiplier' , self.covar_scale_multiplier)
self.covar_scale_factor = kwargs.pop('covar_scale_factor' , self.covar_scale_factor )
... |
<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_scale_factor(self, accept_rate):
'''Private function.
Updates the covariance scaling factor ``covar_scale_factor``
according to its limits
'''
if accept_rate > self.force_acceptance_max and self.covar_scale_factor < self.covar_scale_factor_max:
self.covar... |
<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(self, original, size, crop, options=None):
""" Creates a thumbnail. It loads the image, scales it and crops it. :param original: :param size: :param c... |
if options is None:
options = self.evaluate_options()
image = self.engine_load_image(original)
image = self.scale(image, size, crop, options)
crop = self.parse_crop(crop, self.get_image_size(image), size)
image = self.crop(image, size, crop, options)
image = ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def scale(self, image, size, crop, options):
""" Wrapper for ``engine_scale``, checks if the scaling factor is below one or that scale_up option is set to True b... |
original_size = self.get_image_size(image)
factor = self._calculate_scaling_factor(original_size, size, crop is not None)
if factor < 1 or options['scale_up']:
width = int(original_size[0] * factor)
height = int(original_size[1] * factor)
image = self.engine... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def crop(self, image, size, crop, options):
""" Wrapper for ``engine_crop``, will return without calling ``engine_crop`` if crop is None. :param image: :param si... |
if not crop:
return image
return self.engine_crop(image, size, crop, options) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def colormode(self, image, options):
""" Wrapper for ``engine_colormode``. :param image: :param options: :return: """ |
mode = options['colormode']
return self.engine_colormode(image, mode) |
<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_size(size):
""" Parses size string into a tuple :param size: String on the form '100', 'x100 or '100x200' :return: Tuple of two integers for width and ... |
if size.startswith('x'):
return None, int(size.replace('x', ''))
if 'x' in size:
return int(size.split('x')[0]), int(size.split('x')[1])
return int(size), 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 parse_crop(self, crop, original_size, size):
""" Parses crop into a tuple usable by the crop function. :param crop: String with the crop settings. :param ori... |
if crop is None:
return None
crop = crop.split(' ')
if len(crop) == 1:
crop = crop[0]
x_crop = 50
y_crop = 50
if crop in CROP_ALIASES['x']:
x_crop = CROP_ALIASES['x'][crop]
elif crop in CROP_ALIASES['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 calculate_offset(percent, original_length, length):
""" Calculates crop offset based on percentage. :param percent: A percentage representing the size of the... |
return int(
max(
0,
min(percent * original_length / 100.0, original_length - length / 2) - length / 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 main():
"""Main function for pyfttt command line tool""" |
args = parse_arguments()
if args.key is None:
print("Error: Must provide IFTTT secret key.")
sys.exit(1)
try:
res = pyfttt.send_event(api_key=args.key, event=args.event,
value1=args.value1, value2=args.value2,
value3=... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def plot_responsibility(data, responsibility,
cmap='nipy_spectral'):
'''Classify the 2D ``data`` according to the ``responsibility`` and
make a scatter plot of each data point with the color of the
component it is most likely from. The ``responsibility`` is
normalized internally ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def import_string(dotted_path):
""" Import a dotted module path. Returns the attribute/class designated by the last name in the path. Raises ImportError if the i... |
try:
module_path, class_name = dotted_path.rsplit('.', 1)
except ValueError:
raise ImportError('%s doesn\'t look like a valid path' % dotted_path)
module = __import__(module_path, fromlist=[class_name])
try:
return getattr(module, class_name)
except AttributeError:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def ball(center, radius=1., bdy=True):
'''Returns the indicator function of a ball.
:param center:
A vector-like numpy array, defining the center of the ball.\n
len(center) fixes the dimension.
:param radius:
Float or int, the radius of the ball
:param bdy:
Bool, Wh... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def hyperrectangle(lower, upper, bdy=True):
'''Returns the indicator function of a hyperrectangle.
:param lower:
Vector-like numpy array, defining the lower boundary of the hyperrectangle.\n
len(lower) fixes the dimension.
:param upper:
Vector-like numpy array, defining the 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 get_thumbnail(original, size, **options):
""" Creates or gets an already created thumbnail for the given image with the given size and options. :param origin... |
engine = get_engine()
cache = get_cache_backend()
original = SourceFile(original)
crop = options.get('crop', None)
options = engine.evaluate_options(options)
thumbnail_name = generate_filename(original, size, crop)
if settings.THUMBNAIL_DUMMY:
engine = DummyEngine()
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 argsort_indices(a, axis=-1):
"""Like argsort, but returns an index suitable for sorting the the original array even if that array is multidimensional """ |
a = np.asarray(a)
ind = list(np.ix_(*[np.arange(d) for d in a.shape]))
ind[axis] = a.argsort(axis)
return tuple(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 send_event(api_key, event, value1=None, value2=None, value3=None):
"""Send an event to the IFTTT maker channel Parameters: api_key : string Your IFTTT API ke... |
url = 'https://maker.ifttt.com/trigger/{e}/with/key/{k}/'.format(e=event,
k=api_key)
payload = {'value1': value1, 'value2': value2, 'value3': value3}
return requests.post(url, data=payload) |
<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_localized_docstring(obj, domain):
"""Get a cleaned-up, localized copy of docstring of this class.""" |
if obj.__class__.__doc__ is not None:
return inspect.cleandoc(
gettext.dgettext(domain, obj.__class__.__doc__)) |
<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_cmd_help(self):
""" Get the single-line help of this command. :returns: ``self.help``, if defined :returns: The first line of the docstring, without the ... |
try:
return self.help
except AttributeError:
pass
try:
return get_localized_docstring(
self, self.get_gettext_domain()
).splitlines()[0].rstrip('.').lower()
except (AttributeError, IndexError, ValueError):
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 get_cmd_description(self):
""" Get the leading, multi-line description of this command. :returns: ``self.description``, if defined :returns: A substring of t... |
try:
return self.description
except AttributeError:
pass
try:
return '\n'.join(
get_localized_docstring(
self, self.get_gettext_domain()
).splitlines()[1:]
).split('@EPILOG@', 1)[0].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 get_cmd_epilog(self):
""" Get the trailing, multi-line description of this command. :returns: ``self.epilog``, if defined :returns: A substring of the class ... |
try:
return self.source.epilog
except AttributeError:
pass
try:
return '\n'.join(
get_localized_docstring(
self, self.get_gettext_domain()
).splitlines()[1:]
).split('@EPILOG@', 1)[1].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 main(self, argv=None, exit=True):
""" Shortcut for running a command. See :meth:`guacamole.recipes.Recipe.main()` for details. """ |
return CommandRecipe(self).main(argv, exit) |
<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_ingredients(self):
"""Get a list of ingredients for guacamole.""" |
return [
cmdtree.CommandTreeBuilder(self.command),
cmdtree.CommandTreeDispatcher(),
argparse.AutocompleteIngredient(),
argparse.ParserIngredient(),
crash.VerboseCrashHandler(),
ansi.ANSIIngredient(),
log.Logging(),
] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_arguments(self, parser):
""" Guacamole method used by the argparse ingredient. :param parser: Argument parser (from :mod:`argparse`) specific to thi... |
parser.add_argument('x', type=int, help='the first value')
parser.add_argument('y', type=int, help='the second value') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def invoked(self, ctx):
"""Method called when the command is invoked.""" |
if not ctx.ansi.is_enabled:
print("You need color support to use this demo")
else:
print(ctx.ansi.cmd('erase_display'))
self._demo_fg_color(ctx)
self._demo_bg_color(ctx)
self._demo_bg_indexed(ctx)
self._demo_rgb(ctx)
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 get(self, thumbnail_name):
""" Wrapper for ``_get``, which converts the thumbnail_name to String if necessary before calling ``_get`` :rtype: Thumbnail """ |
if isinstance(thumbnail_name, list):
thumbnail_name = '/'.join(thumbnail_name)
return self._get(thumbnail_name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse(dsn, parse_class=ParseResult, **defaults):
""" parse a dsn to parts similar to parseurl :param dsn: string, the dsn to parse :param parse_class: ParseR... |
r = parse_class(dsn, **defaults)
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 setdefault(self, key, val):
""" set a default value for key this is different than dict's setdefault because it will set default either if the key doesn't ex... |
if not getattr(self, key, None):
setattr(self, key, val) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def geturl(self):
"""return the dsn back into url form""" |
return urlparse.urlunparse((
self.scheme,
self.netloc,
self.path,
self.params,
self.query_str,
self.fragment,
)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def preparse(self, context):
""" Parse a portion of command line arguments with the early parser. This method relies on ``context.argv`` and ``context.early_pars... |
context.early_args, unused = (
context.early_parser.parse_known_args(context.argv)) |
<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_parser(self, context):
""" Create the final argument parser. This method creates the non-early (full) argparse argument parser. Unlike the early counte... |
context.parser, context.max_level = self._create_parser(context) |
<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(self, context):
""" Optionally trigger argument completion in the invoking shell. This method is called to see if bash argument completion is requested... |
try:
import argcomplete
except ImportError:
return
try:
parser = context.parser
except AttributeError:
raise RecipeError(
"""
The context doesn't have the parser attribute.
The auto-complete... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ansi_cmd(cmd, *args):
"""Get ANSI command code by name.""" |
try:
obj = getattr(ANSI, str('cmd_{}'.format(cmd)))
except AttributeError:
raise ValueError(
"incorrect command: {!r}".format(cmd))
if isinstance(obj, type("")):
return obj
else:
return obj(*args) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_visible_color(color):
"""Get the visible counter-color.""" |
if isinstance(color, (str, type(""))):
try:
return getattr(_Visible, str('{}'.format(color)))
except AttributeError:
raise ValueError("incorrect color: {!r}".format(color))
elif isinstance(color, tuple):
return (0x80 ^ color[0], 0x80 ^ color[1], 0x80 ^ color[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 using_git(cwd):
"""Test whether the directory cwd is contained in a git repository.""" |
try:
git_log = shell_out(["git", "log"], cwd=cwd)
return True
except (CalledProcessError, OSError): # pragma: no cover
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def using_hg(cwd):
"""Test whether the directory cwd is contained in a mercurial repository.""" |
try:
hg_log = shell_out(["hg", "log"], cwd=cwd)
return True
except (CalledProcessError, OSError):
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def using_bzr(cwd):
"""Test whether the directory cwd is contained in a bazaar repository.""" |
try:
bzr_log = shell_out(["bzr", "log"], cwd=cwd)
return True
except (CalledProcessError, OSError):
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def which(cwd=None):
# pragma: no cover """Try to find which version control system contains the cwd directory. Returns the VersionControl superclass e.g. Git, i... |
if cwd is None:
cwd = os.getcwd()
for (k, using_vc) in globals().items():
if k.startswith('using_') and using_vc(cwd=cwd):
return VersionControl.from_string(k[6:])
# Not supported (yet)
raise NotImplementedError("Unknown version control system, "... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def modified_lines(self, r, file_name):
"""Returns the line numbers of a file which have been changed.""" |
cmd = self.file_diff_cmd(r, file_name)
diff = shell_out_ignore_exitcode(cmd, cwd=self.root)
return list(self.modified_lines_from_diff(diff)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def modified_lines_from_diff(self, diff):
"""Returns the changed lines in a diff. - Potentially this is vc specific (if not using udiff). Note: this returns the ... |
from pep8radius.diff import modified_lines_from_udiff
for start, end in modified_lines_from_udiff(diff):
yield start, end |
<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_filenames_diff(self, r):
"""Get the py files which have been changed since rev.""" |
cmd = self.filenames_diff_cmd(r)
diff_files = shell_out_ignore_exitcode(cmd, cwd=self.root)
diff_files = self.parse_diff_filenames(diff_files)
return set(f for f in diff_files if f.endswith('.py')) |
<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_diff_filenames(diff_files):
"""Parse the output of filenames_diff_cmd.""" |
# ? .gitignore
# M 0.txt
files = []
for line in diff_files.splitlines():
line = line.strip()
fn = re.findall('[^ ]+\s+(.*.py)', line)
if fn and not line.startswith('?'):
files.append(fn[0])
return 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 data(self):
""" Helper class for parsing JSON POST data into a Python object. """ |
if self.request.method == 'GET':
return self.request.GET
else:
assert self.request.META['CONTENT_TYPE'].startswith('application/json')
charset = self.request.encoding or settings.DEFAULT_CHARSET
return json.loads(self.request.body.decode(charset)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def options(self, request, *args, **kwargs):
""" Implements a OPTIONS HTTP method function returning all allowed HTTP methods. """ |
allow = []
for method in self.http_method_names:
if hasattr(self, method):
allow.append(method.upper())
r = self.render_to_response(None)
r['Allow'] = ','.join(allow)
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 main(args=None, vc=None, cwd=None, apply_config=False):
"""PEP8 clean only the parts of the files touched since the last commit, a previous commit or branch.... |
import signal
try: # pragma: no cover
# Exit on broken pipe.
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
except AttributeError: # pragma: no cover
# SIGPIPE is not available on Windows.
pass
try:
if args is None:
args = []
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 parse_args(arguments=None, root=None, apply_config=False):
"""Parse the arguments from the CLI. If apply_config then we first look up and apply configs using... |
if arguments is None:
arguments = []
parser = create_parser()
args = parser.parse_args(arguments)
if apply_config:
parser = apply_config_defaults(parser, args, root=root)
args = parser.parse_args(arguments)
# sanity check args (from autopep8)
if args.max_line_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 read_vint32(self):
""" This seems to be a variable length integer ala utf-8 style """ |
result = 0
count = 0
while True:
if count > 4:
raise ValueError("Corrupt VarInt32")
b = self.read_byte()
result = result | (b & 0x7F) << (7 * count)
count += 1
if not b & 0x80:
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 read_message(self, message_type, compressed=False, read_size=True):
""" Read a protobuf message """ |
if read_size:
size = self.read_vint32()
b = self.read(size)
else:
b = self.read()
if compressed:
b = snappy.decompress(b)
m = message_type()
m.ParseFromString(b)
return m |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run_hooks(self, packet):
""" Run any additional functions that want to process this type of packet. These can be internal parser hooks, or external hooks tha... |
if packet.__class__ in self.internal_hooks:
self.internal_hooks[packet.__class__](packet)
if packet.__class__ in self.hooks:
self.hooks[packet.__class__](packet) |
<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_string_table(self, tables):
""" Need to pull out player information from string table """ |
self.info("String table: %s" % (tables.tables, ))
for table in tables.tables:
if table.table_name == "userinfo":
for item in table.items:
if len(item.data) > 0:
if len(item.data) == 140:
p = PlayerInfo(... |
<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_game_event(self, event):
""" So CSVCMsg_GameEventList is a list of all events that can happen. A game event has an eventid which maps to a type of even... |
if event.eventid in self.event_lookup:
#Bash this into a nicer data format to work with
event_type = self.event_lookup[event.eventid]
ge = GameEvent(event_type.name)
for i, key in enumerate(event.keys):
key_type = event_type.keys[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 parse(self):
""" Parse a replay """ |
self.important("Parsing demo file '%s'" % (self.filename, ))
with open(self.filename, 'rb') as f:
reader = Reader(StringIO(f.read()))
filestamp = reader.read(8)
offset = reader.read_int32()
if filestamp != "PBUFDEM\x00":
raise ValueErr... |
<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(data):
""" Convert from unicode to native ascii """ |
try:
st = basestring
except NameError:
st = str
if isinstance(data, st):
return str(data)
elif isinstance(data, Mapping):
return dict(map(convert, data.iteritems()))
elif isinstance(data, Iterable):
return type(data)(map(convert, data))
else:
retu... |
<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_type_by_schema(self, schema_obj, schema_type):
""" Set property type by schema object Schema will create, if it doesn't exists in collection :param dict ... |
schema_id = self._get_object_schema_id(schema_obj, schema_type)
if not self.storage.contains(schema_id):
schema = self.storage.create_schema(
schema_obj, self.name, schema_type, root=self.root)
assert schema.schema_id == schema_id
self._type = schema_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 tablib_export_action(modeladmin, request, queryset, file_type="xls"):
""" Allow the user to download the current filtered list of items :param file_type: One... |
dataset = SimpleDataset(queryset, headers=None)
filename = '{0}.{1}'.format(
smart_str(modeladmin.model._meta.verbose_name_plural), file_type)
response_kwargs = {
'content_type': get_content_type(file_type)
}
response = HttpResponse(getattr(dataset, file_type), **response_kwargs)... |
<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_type_properties(self, property_obj, name, additional_prop=False):
""" Extend parents 'Get internal properties of property'-method """ |
property_type, property_format, property_dict = \
super(Schema, self).get_type_properties(property_obj, name, additional_prop=additional_prop)
_schema = self.storage.get(property_type)
if _schema and ('additionalProperties' in property_obj):
_property_type, _property_for... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generic_export(request, model_name=None):
""" Generic view configured through settings.TABLIB_MODELS Usage: 1. Add the view to ``urlpatterns`` in ``urls.py``... |
if model_name not in settings.TABLIB_MODELS:
raise Http404()
model = get_model(*model_name.split(".", 2))
if not model:
raise ImproperlyConfigured(
"Model {0} is in settings.TABLIB_MODELS but"
" could not be loaded".format(model_name))
qs = model._default_mana... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sorted(collection):
""" sorting dict by key, schema-collection by schema-name operations by id """ |
if len(collection) < 1:
return collection
if isinstance(collection, dict):
return sorted(collection.items(), key=lambda x: x[0])
if isinstance(list(collection)[0], Operation):
key = lambda x: x.operation_id
elif isinstance(list(collection)[0], 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 pre_save(self, instance, add):
""" Updates the edtf value from the value of the display_field. If there's a valid edtf, then set the date values. """ |
if not self.natural_text_field or self.attname not in instance.__dict__:
return
edtf = getattr(instance, self.attname)
# Update EDTF field based on latest natural text value, if any
natural_text = getattr(instance, self.natural_text_field)
if natural_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 apply_delta(op, time_struct, delta):
""" Apply a `relativedelta` to a `struct_time` data structure. `op` is an operator function, probably always `add` or `s... |
if not delta:
return time_struct # No work to do
try:
dt_result = op(datetime(*time_struct[:6]), delta)
return dt_to_struct_time(dt_result)
except (OverflowError, ValueError):
# Year is not within supported 1 to 9999 AD range
pass
# Here we fake the year to on... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _strict_date(self, lean):
""" Return a `time.struct_time` representation of the date. """ |
return struct_time(
(
self._precise_year(lean),
self._precise_month(lean),
self._precise_day(lean),
) + tuple(TIME_EMPTY_TIME) + tuple(TIME_EMPTY_EXTRAS)
) |
<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):
"""Packages lambda data for deployment into a zip""" |
logger.info('Packaging lambda {}'.format(self.lambda_name))
zfh = io.BytesIO()
if os.path.exists(os.path.join(self.lambda_dir, '.env')):
logger.warn(
'A .env file exists in your Lambda directory - be '
'careful that it does not contain any secrets yo... |
<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, *lambdas):
"""Deploys lambdas to AWS""" |
if not self.role:
logger.error('Missing AWS Role')
raise ArgumentsError('Role required')
logger.debug('Deploying lambda {}'.format(self.lambda_name))
zfh = self.package()
if self.lambda_name in self.get_function_names():
logger.info('Updating {} 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 list(self):
"""Lists already deployed lambdas""" |
for function in self.client.list_functions().get('Functions', []):
lines = json.dumps(function, indent=4, sort_keys=True).split('\n')
for line in lines:
logger.info(line) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def date_to_jd(year,month,day):
""" Convert a date to Julian Day. Algorithm from 'Practical Astronomy with your Calculator or Spreadsheet', 4th ed., Duffet-Smith... |
if month == 1 or month == 2:
yearp = year - 1
monthp = month + 12
else:
yearp = year
monthp = month
# this checks where we are in relation to October 15, 1582, the beginning
# of the Gregorian calendar.
if ((year < 1582) or
(year == 1582 and month < 10) 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 jd_to_date(jd):
""" Convert Julian Day to date. Algorithm from 'Practical Astronomy with your Calculator or Spreadsheet', 4th ed., Duffet-Smith and Zwart, 20... |
jd = jd + 0.5
F, I = math.modf(jd)
I = int(I)
A = math.trunc((I - 1867216.25)/36524.25)
if I > 2299160:
B = I + 1 + A - math.trunc(A / 4.)
else:
B = I
C = B + 1524
D = math.trunc((C - 122.1) / 365.25)
E = math.trunc(365.25 * D)
G = math.trunc((C - E) / 30.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hmsm_to_days(hour=0,min=0,sec=0,micro=0):
""" Convert hours, minutes, seconds, and microseconds to fractional days. Parameters hour : int, optional Hour numb... |
days = sec + (micro / 1.e6)
days = min + (days / 60.)
days = hour + (days / 60.)
return days / 24. |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def days_to_hmsm(days):
""" Convert fractional days to hours, minutes, seconds, and microseconds. Precision beyond microseconds is rounded to the nearest microse... |
hours = days * 24.
hours, hour = math.modf(hours)
mins = hours * 60.
mins, min = math.modf(mins)
secs = mins * 60.
secs, sec = math.modf(secs)
micro = round(secs * 1.e6)
return int(hour), int(min), int(sec), int(micro) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def datetime_to_jd(date):
""" Convert a `datetime.datetime` object to Julian Day. Parameters date : `datetime.datetime` instance Returns ------- jd : float Julia... |
days = date.day + hmsm_to_days(date.hour,date.minute,date.second,date.microsecond)
return date_to_jd(date.year,date.month,days) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def jd_to_datetime(jd):
""" Convert a Julian Day to an `jdutil.datetime` object. Parameters jd : float Julian day. Returns ------- dt : `jdutil.datetime` object ... |
year, month, day = jd_to_date(jd)
frac_days,day = math.modf(day)
day = int(day)
hour,min,sec,micro = days_to_hmsm(frac_days)
return datetime(year,month,day,hour,min,sec,micro) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def timedelta_to_days(td):
""" Convert a `datetime.timedelta` object to a total number of days. Parameters td : `datetime.timedelta` instance Returns ------- day... |
seconds_in_day = 24. * 3600.
days = td.days + (td.seconds + (td.microseconds * 10.e6)) / seconds_in_day
return days |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_schema(cls, obj, name, schema_type, root):
""" Create Schema object :param dict obj: swagger schema object :param str name: schema name :param str sch... |
if schema_type == SchemaTypes.MAPPED:
schema = SchemaMapWrapper(obj, storage=cls, name=name, root=root)
else:
schema = Schema(obj, schema_type, storage=cls, name=name, root=root)
cls.add_schema(schema)
return 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 get_schemas(cls, schema_types=None, sort=True):
""" Get schemas by type. If ``schema_type`` is None, return all schemas :param schema_types: list of schema t... |
result = filter(lambda x: not x.is_inline_array, cls._schemas.values())
if schema_types:
result = filter(lambda x: x.schema_type in schema_types, result)
if sort:
result = sorted(result, key=attrgetter('name'))
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 trim_struct_time(st, strip_time=False):
""" Return a `struct_time` based on the one provided but with the extra fields `tm_wday`, `tm_yday`, and `tm_isdst` r... |
if strip_time:
return struct_time(list(st[:3]) + TIME_EMPTY_TIME + TIME_EMPTY_EXTRAS)
else:
return struct_time(list(st[:6]) + TIME_EMPTY_EXTRAS) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def struct_time_to_jd(st):
""" Return a float number representing the Julian Date for the given `struct_time`. NOTE: extra fields `tm_wday`, `tm_yday`, and `tm_i... |
year, month, day = st[:3]
hours, minutes, seconds = st[3:6]
# Convert time of day to fraction of day
day += jdutil.hmsm_to_days(hours, minutes, seconds)
return jdutil.date_to_jd(year, month, day) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def jd_to_struct_time(jd):
""" Return a `struct_time` converted from a Julian Date float number. WARNING: Conversion to then from Julian Date value to `struct_ti... |
year, month, day = jdutil.jd_to_date(jd)
# Convert time of day from fraction of day
day_fraction = day - int(day)
hour, minute, second, ms = jdutil.days_to_hmsm(day_fraction)
day = int(day)
# This conversion can return negative values for items we do not want to be
# negative: month, day,... |
<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_example_by_schema(cls, schema, ignored_schemas=None, paths=None, name=''):
""" Get example by schema object :param Schema schema: current schema :param l... |
if schema.schema_example:
return schema.schema_example
if ignored_schemas is None:
ignored_schemas = []
if paths is None:
paths = []
if name:
paths = list(map(lambda path: '.'.join((path, name)), paths))
if schema.ref_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 get_body_example(cls, operation):
""" Get example for body parameter example by operation :param Operation operation: operation object """ |
path = "#/paths/'{0.path}'/{0.method}/parameters/{name}".format(
operation, name=operation.body.name or 'body')
return cls.get_example_by_schema(operation.body, paths=[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 get_response_example(cls, operation, response):
""" Get example for response object by operation object :param Operation operation: operation object :param R... |
path = "#/paths/'{}'/{}/responses/{}".format(
operation.path, operation.method, response.name)
kwargs = dict(paths=[path])
if response.type in PRIMITIVE_TYPES:
result = cls.get_example_value_for_primitive_type(
response.type, response.properties, respons... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.