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 sampen(data, emb_dim=2, tolerance=None, dist=rowwise_chebyshev, debug_plot=False, debug_data=False, plot_file=None):
""" Computes the sample entropy of the g... |
data = np.asarray(data)
if tolerance is None:
tolerance = 0.2 * np.std(data)
n = len(data)
# build matrix of "template vectors"
# (all consecutive subsequences of length m)
# x0 x1 x2 x3 ... xm-1
# x1 x2 x3 x4 ... xm
# x2 x3 x4 x5 ... xm+1
# ...
# x_n-m-1 ... xn-1
# since we need t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def binary_n(total_N, min_n=50):
""" Creates a list of values by successively halving the total length total_N until the resulting value is less than min_n. Non-... |
max_exp = np.log2(1.0 * total_N / min_n)
max_exp = int(np.floor(max_exp))
return [int(np.floor(1.0 * total_N / (2**i))) for i in range(1, max_exp + 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 expected_h(nvals, fit="RANSAC"):
""" Uses expected_rs to calculate the expected value for the Hurst exponent h based on the values of n used for the calculat... |
rsvals = [expected_rs(n) for n in nvals]
poly = poly_fit(np.log(nvals), np.log(rsvals), 1, fit=fit)
return poly[0] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def corr_dim(data, emb_dim, rvals=None, dist=rowwise_euclidean, fit="RANSAC", debug_plot=False, debug_data=False, plot_file=None):
""" Calculates the correlation... |
data = np.asarray(data)
# TODO what are good values for r?
# TODO do this for multiple values of emb_dim?
if rvals is None:
sd = np.std(data)
rvals = logarithmic_r(0.1 * sd, 0.5 * sd, 1.03)
n = len(data)
orbit = delay_embedding(data, emb_dim, lag=1)
dists = np.array([dist(orbit, orbit[i]) for 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 check_status(status, expected, path, headers=None, resp_headers=None, body=None, extras=None):
"""Check HTTP response status is expected. Args: status: HTTP ... |
if status in expected:
return
msg = ('Expect status %r from Google Storage. But got status %d.\n'
'Path: %r.\n'
'Request headers: %r.\n'
'Response headers: %r.\n'
'Body: %r.\n'
'Extra info: %r.\n' %
(expected, status, path, headers, resp_headers, body, ext... |
<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_default_retry_params():
"""Get default RetryParams for current request and current thread. Returns: A new instance of the default RetryParams. """ |
default = getattr(_thread_local_settings, 'default_retry_params', None)
if default is None or not default.belong_to_current_request():
return RetryParams()
else:
return copy.copy(default) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _should_retry(resp):
"""Given a urlfetch response, decide whether to retry that request.""" |
return (resp.status_code == httplib.REQUEST_TIMEOUT or
(resp.status_code >= 500 and
resp.status_code < 600)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _eager_tasklet(tasklet):
"""Decorator to turn tasklet to run eagerly.""" |
@utils.wrapping(tasklet)
def eager_wrapper(*args, **kwds):
fut = tasklet(*args, **kwds)
_run_until_rpc()
return fut
return eager_wrapper |
<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, tasklet, **kwds):
"""Run a tasklet with retry. The retry should be transparent to the caller: if no results are successful, the exception or result... |
start_time = time.time()
n = 1
while True:
e = None
result = None
got_result = False
try:
result = yield tasklet(**kwds)
got_result = True
if not self.should_retry(result):
raise ndb.Return(result)
except runtime.DeadlineExceededError:
... |
<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(cls, name, val, can_be_zero=False, val_type=float):
"""Check init arguments. Args: name: name of the argument. For logging purpose. val: value. Value ... |
valid_types = [val_type]
if val_type is float:
valid_types.append(int)
if type(val) not in valid_types:
raise TypeError(
'Expect type %s for parameter %s' % (val_type.__name__, name))
if val < 0:
raise ValueError(
'Value for parameter %s has to be greater than 0' ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delay(self, n, start_time):
"""Calculate delay before the next retry. Args: n: the number of current attempt. The first attempt should be 1. start_time: the ... |
if (n > self.max_retries or
(n > self.min_retries and
time.time() - start_time > self.max_retry_period)):
return -1
return min(
math.pow(self.backoff_factor, n-1) * self.initial_delay,
self.max_delay) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def open(filename, mode='r', content_type=None, options=None, read_buffer_size=storage_api.ReadBuffer.DEFAULT_BUFFER_SIZE, retry_params=None, _account_id=None, of... |
common.validate_file_path(filename)
api = storage_api._get_storage_api(retry_params=retry_params,
account_id=_account_id)
filename = api_utils._quote_filename(filename)
if mode == 'w':
common.validate_options(options)
return storage_api.StreamingBuffer(api, filenam... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(filename, retry_params=None, _account_id=None):
"""Delete a Google Cloud Storage file. Args: filename: A Google Cloud Storage filename of form '/bucke... |
api = storage_api._get_storage_api(retry_params=retry_params,
account_id=_account_id)
common.validate_file_path(filename)
filename = api_utils._quote_filename(filename)
status, resp_headers, content = api.delete_object(filename)
errors.check_status(status, [204], filename... |
<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_location(bucket, retry_params=None, _account_id=None):
"""Returns the location for the given bucket. https://cloud.google.com/storage/docs/bucket-locatio... |
return _get_bucket_attribute(bucket,
'location',
'LocationConstraint',
retry_params=retry_params,
_account_id=_account_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 get_storage_class(bucket, retry_params=None, _account_id=None):
"""Returns the storage class for the given bucket. https://cloud.google.com/storage/docs/stor... |
return _get_bucket_attribute(bucket,
'storageClass',
'StorageClass',
retry_params=retry_params,
_account_id=_account_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 _get_bucket_attribute(bucket, query_param, xml_response_tag, retry_params=None, _account_id=None):
"""Helper method to request a bucket parameter and parse t... |
api = storage_api._get_storage_api(retry_params=retry_params,
account_id=_account_id)
common.validate_bucket_path(bucket)
status, headers, content = api.get_bucket('%s?%s' % (bucket, query_param))
errors.check_status(status, [200], bucket, resp_headers=headers, body=conten... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stat(filename, retry_params=None, _account_id=None):
"""Get GCSFileStat of a Google Cloud storage file. Args: filename: A Google Cloud Storage filename of fo... |
common.validate_file_path(filename)
api = storage_api._get_storage_api(retry_params=retry_params,
account_id=_account_id)
status, headers, content = api.head_object(
api_utils._quote_filename(filename))
errors.check_status(status, [200], filename, resp_headers=headers... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def copy2(src, dst, metadata=None, retry_params=None):
"""Copy the file content from src to dst. Args: src: /bucket/filename dst: /bucket/filename metadata: a di... |
common.validate_file_path(src)
common.validate_file_path(dst)
if metadata is None:
metadata = {}
copy_meta = 'COPY'
else:
copy_meta = 'REPLACE'
metadata.update({'x-goog-copy-source': src,
'x-goog-metadata-directive': copy_meta})
api = storage_api._get_storage_api(retry_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 listbucket(path_prefix, marker=None, prefix=None, max_keys=None, delimiter=None, retry_params=None, _account_id=None):
"""Returns a GCSFileStat iterator over... |
if prefix:
common.validate_bucket_path(path_prefix)
bucket = path_prefix
else:
bucket, prefix = common._process_path_prefix(path_prefix)
if marker and marker.startswith(bucket):
marker = marker[len(bucket) + 1:]
api = storage_api._get_storage_api(retry_params=retry_params,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compose(list_of_files, destination_file, files_metadata=None, content_type=None, retry_params=None, _account_id=None):
"""Runs the GCS Compose on the given f... |
api = storage_api._get_storage_api(retry_params=retry_params,
account_id=_account_id)
if os.getenv('SERVER_SOFTWARE').startswith('Dev'):
def _temp_func(file_list, destination_file, content_type):
bucket = '/' + destination_file.split('/')[1] + '/'
with open(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 _validate_compose_list(destination_file, file_list, files_metadata=None, number_of_files=32):
"""Validates the file_list and merges the file_list, files_meta... |
common.validate_file_path(destination_file)
bucket = destination_file[0:(destination_file.index('/', 1) + 1)]
try:
if isinstance(file_list, types.StringTypes):
raise TypeError
list_len = len(file_list)
except TypeError:
raise TypeError('file_list must be a list')
if list_len > number_of_fi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _next_file_gen(self, root):
"""Generator for next file element in the document. Args: root: root element of the XML tree. Yields: GCSFileStat for the next fi... |
for e in root.getiterator(common._T_CONTENTS):
st_ctime, size, etag, key = None, None, None, None
for child in e.getiterator('*'):
if child.tag == common._T_LAST_MODIFIED:
st_ctime = common.dt_str_to_posix(child.text)
elif child.tag == common._T_ETAG:
etag = child.te... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _next_dir_gen(self, root):
"""Generator for next directory element in the document. Args: root: root element in the XML tree. Yields: GCSFileStat for the nex... |
for e in root.getiterator(common._T_COMMON_PREFIXES):
yield common.GCSFileStat(
self._path + '/' + e.find(common._T_PREFIX).text,
st_size=None, etag=None, st_ctime=None, is_dir=True)
e.clear()
yield 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 _should_get_another_batch(self, content):
"""Whether to issue another GET bucket call. Args: content: response XML. Returns: True if should, also update self... |
if ('max-keys' in self._options and
self._options['max-keys'] <= common._MAX_GET_BUCKET_RESULT):
return False
elements = self._find_elements(
content, set([common._T_IS_TRUNCATED,
common._T_NEXT_MARKER]))
if elements.get(common._T_IS_TRUNCATED, 'false').lower() ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _find_elements(self, result, elements):
"""Find interesting elements from XML. This function tries to only look for specified elements without parsing the en... |
element_mapping = {}
result = StringIO.StringIO(result)
for _, e in ET.iterparse(result, events=('end',)):
if not elements:
break
if e.tag in elements:
element_mapping[e.tag] = e.text
elements.remove(e.tag)
return element_mapping |
<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_file(self, filename):
"""Create a file. The retry_params specified in the open call will override the default retry params for this particular file ha... |
self.response.write('Creating file %s\n' % filename)
write_retry_params = gcs.RetryParams(backoff_factor=1.1)
gcs_file = gcs.open(filename,
'w',
content_type='text/plain',
options={'x-goog-meta-foo': 'foo',
... |
<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_bucket(self, bucket):
"""Create several files and paginate through them. Production apps should set page_size to a practical value. Args: bucket: bucket... |
self.response.write('Listbucket result:\n')
page_size = 1
stats = gcs.listbucket(bucket + '/foo', max_keys=page_size)
while True:
count = 0
for stat in stats:
count += 1
self.response.write(repr(stat))
self.response.write('\n')
if count != page_size or count ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def CreateFile(filename):
"""Create a GCS file with GCS client lib. Args: filename: GCS filename. Returns: The corresponding string blobkey for this GCS file. ""... |
with gcs.open(filename, 'w') as f:
f.write('abcde\n')
blobstore_filename = '/gs' + filename
return blobstore.create_gs_key(blobstore_filename) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _make_token_async(scopes, service_account_id):
"""Get a fresh authentication token. Args: scopes: A list of scopes. service_account_id: Internal-use only. Ra... |
rpc = app_identity.create_rpc()
app_identity.make_get_access_token_call(rpc, scopes, service_account_id)
token, expires_at = yield rpc
raise ndb.Return((token, expires_at)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _make_sync_method(name):
"""Helper to synthesize a synchronous method from an async method name. Used by the @add_sync_methods class decorator below. Args: n... |
def sync_wrapper(self, *args, **kwds):
method = getattr(self, name)
future = method(*args, **kwds)
return future.get_result()
return sync_wrapper |
<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_sync_methods(cls):
"""Class decorator to add synchronous methods corresponding to async methods. This modifies the class in place, adding additional meth... |
for name in cls.__dict__.keys():
if name.endswith('_async'):
sync_name = name[:-6]
if not hasattr(cls, sync_name):
setattr(cls, sync_name, _make_sync_method(name))
return cls |
<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_request_async(self, url, method='GET', headers=None, payload=None, deadline=None, callback=None):
"""Issue one HTTP request. It performs async retries usi... |
retry_wrapper = api_utils._RetryWrapper(
self.retry_params,
retriable_exceptions=api_utils._RETRIABLE_EXCEPTIONS,
should_retry=api_utils._should_retry)
resp = yield retry_wrapper.run(
self.urlfetch_async,
url=url,
method=method,
headers=headers,
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 get_metadata(headers):
"""Get user defined options from HTTP response headers.""" |
return dict((k, v) for k, v in headers.iteritems()
if any(k.lower().startswith(valid) for valid in _GCS_METADATA)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _process_path_prefix(path_prefix):
"""Validate and process a Google Cloud Stoarge path prefix. Args: path_prefix: a Google Cloud Storage path prefix of forma... |
_validate_path(path_prefix)
if not _GCS_PATH_PREFIX_REGEX.match(path_prefix):
raise ValueError('Path prefix should have format /bucket, /bucket/, '
'or /bucket/prefix but got %s.' % path_prefix)
bucket_name_end = path_prefix.find('/', 1)
bucket = path_prefix
prefix = None
if bucket... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _validate_path(path):
"""Basic validation of Google Storage paths. Args: path: a Google Storage path. It should have form '/bucket/filename' or '/bucket'. Ra... |
if not path:
raise ValueError('Path is empty')
if not isinstance(path, basestring):
raise TypeError('Path should be a string but is %s (%s).' %
(path.__class__, 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 validate_options(options):
"""Validate Google Cloud Storage options. Args: options: a str->basestring dict of options to pass to Google Cloud Storage. Raises... |
if not options:
return
for k, v in options.iteritems():
if not isinstance(k, str):
raise TypeError('option %r should be a str.' % k)
if not any(k.lower().startswith(valid) for valid in _GCS_OPTIONS):
raise ValueError('option %s is not supported.' % k)
if not isinstance(v, basestring):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dt_str_to_posix(dt_str):
"""format str to posix. datetime str is of format %Y-%m-%dT%H:%M:%S.%fZ, e.g. 2013-04-12T00:22:27.978Z. According to ISO 8601, T is ... |
parsable, _ = dt_str.split('.')
dt = datetime.datetime.strptime(parsable, _DT_FORMAT)
return calendar.timegm(dt.utctimetuple()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def posix_to_dt_str(posix):
"""Reverse of str_to_datetime. This is used by GCS stub to generate GET bucket XML response. Args: posix: A float of secs from unix e... |
dt = datetime.datetime.utcfromtimestamp(posix)
dt_str = dt.strftime(_DT_FORMAT)
return dt_str + '.000Z' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def local_run():
"""Whether we should hit GCS dev appserver stub.""" |
server_software = os.environ.get('SERVER_SOFTWARE')
if server_software is None:
return True
if 'remote_api' in server_software:
return False
if server_software.startswith(('Development', 'testutil')):
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def memory_usage(method):
"""Log memory usage before and after a method.""" |
def wrapper(*args, **kwargs):
logging.info('Memory before method %s is %s.',
method.__name__, runtime.memory_usage().current())
result = method(*args, **kwargs)
logging.info('Memory after method %s is %s',
method.__name__, runtime.memory_usage().current())
return res... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_storage_api(retry_params, account_id=None):
"""Returns storage_api instance for API methods. Args: retry_params: An instance of api_utils.RetryParams. I... |
api = _StorageApi(_StorageApi.full_control_scope,
service_account_id=account_id,
retry_params=retry_params)
# when running local unit tests, the service account is test@localhost
# from google.appengine.api.app_identity.app_identity_stub.APP_SERVICE_ACCOUNT_NAME
servi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def post_object_async(self, path, **kwds):
"""POST to an object.""" |
return self.do_request_async(self.api_url + path, 'POST', **kwds) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def put_object_async(self, path, **kwds):
"""PUT an object.""" |
return self.do_request_async(self.api_url + path, 'PUT', **kwds) |
<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_object_async(self, path, **kwds):
"""GET an object. Note: No payload argument is supported. """ |
return self.do_request_async(self.api_url + path, 'GET', **kwds) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete_object_async(self, path, **kwds):
"""DELETE an object. Note: No payload argument is supported. """ |
return self.do_request_async(self.api_url + path, 'DELETE', **kwds) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def head_object_async(self, path, **kwds):
"""HEAD an object. Depending on request headers, HEAD returns various object properties, e.g. Content-Length, Last-Mod... |
return self.do_request_async(self.api_url + path, 'HEAD', **kwds) |
<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_bucket_async(self, path, **kwds):
"""GET a bucket.""" |
return self.do_request_async(self.api_url + path, 'GET', **kwds) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compose_object(self, file_list, destination_file, content_type):
"""COMPOSE multiple objects together. Using the given list of files, calls the put object wi... |
xml_setting_list = ['<ComposeRequest>']
for meta_data in file_list:
xml_setting_list.append('<Component>')
for key, val in meta_data.iteritems():
xml_setting_list.append('<%s>%s</%s>' % (key, val, key))
xml_setting_list.append('</Component>')
xml_setting_list.append('</ComposeRe... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def readline(self, size=-1):
"""Read one line delimited by '\n' from the file. A trailing newline character is kept in the string. It may be absent when a file e... |
self._check_open()
if size == 0 or not self._remaining():
return ''
data_list = []
newline_offset = self._buffer.find_newline(size)
while newline_offset < 0:
data = self._buffer.read(size)
size -= len(data)
self._offset += len(data)
data_list.append(data)
if siz... |
<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(self, size=-1):
"""Read data from RAW file. Args: size: Number of bytes to read as integer. Actual number of bytes read is always equal to size unless E... |
self._check_open()
if not self._remaining():
return ''
data_list = []
while True:
remaining = self._buffer.remaining()
if size >= 0 and size < remaining:
data_list.append(self._buffer.read(size))
self._offset += size
break
else:
size -= remaining... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _request_next_buffer(self):
"""Request next buffer. Requires self._offset and self._buffer are in consistent state. """ |
self._buffer_future = None
next_offset = self._offset + self._buffer.remaining()
if next_offset != self._file_size:
self._buffer_future = self._get_segment(next_offset,
self._buffer_size) |
<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_segments(self, start, request_size):
"""Get segments of the file from Google Storage as a list. A large request is broken into segments to avoid hitting... |
if not request_size:
return []
end = start + request_size
futures = []
while request_size > self._max_request_size:
futures.append(self._get_segment(start, self._max_request_size))
request_size -= self._max_request_size
start += self._max_request_size
if 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_segment(self, start, request_size, check_response=True):
"""Get a segment of the file from Google Storage. Args: start: start offset of the segment. Inc... |
end = start + request_size - 1
content_range = '%d-%d' % (start, end)
headers = {'Range': 'bytes=' + content_range}
status, resp_headers, content = yield self._api.get_object_async(
self._path, headers=headers)
def _checker():
errors.check_status(status, [200, 206], self._path, header... |
<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_etag(self, etag):
"""Check if etag is the same across requests to GCS. If self._etag is None, set it. If etag is set, check that the new etag equals t... |
if etag is None:
return
elif self._etag is None:
self._etag = etag
elif self._etag != etag:
raise ValueError('File on GCS has changed while reading.') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def seek(self, offset, whence=os.SEEK_SET):
"""Set the file's current offset. Note if the new offset is out of bound, it is adjusted to either 0 or EOF. Args: of... |
self._check_open()
self._buffer.reset()
self._buffer_future = None
if whence == os.SEEK_SET:
self._offset = offset
elif whence == os.SEEK_CUR:
self._offset += offset
elif whence == os.SEEK_END:
self._offset = self._file_size + offset
else:
raise ValueError('Whence ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_newline(self, size=-1):
"""Search for newline char in buffer starting from current offset. Args: size: number of bytes to search. -1 means all. Returns:... |
if size < 0:
return self._buffer.find('\n', self._offset)
return self._buffer.find('\n', self._offset, self._offset + size) |
<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(self, data):
"""Write some bytes. Args: data: data to write. str. Raises: TypeError: if data is not of type str. """ |
self._check_open()
if not isinstance(data, str):
raise TypeError('Expected str but got %s.' % type(data))
if not data:
return
self._buffer.append(data)
self._buffered += len(data)
self._offset += len(data)
if self._buffered >= self._flushsize:
self._flush() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def close(self):
"""Flush the buffer and finalize the file. When this returns the new file is available for reading. """ |
if not self.closed:
self.closed = True
self._flush(finish=True)
self._buffer = 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 _flush(self, finish=False):
"""Internal API to flush. Buffer is flushed to GCS only when the total amount of buffered data is at least self._blocksize, or to... |
while ((finish and self._buffered >= 0) or
(not finish and self._buffered >= self._blocksize)):
tmp_buffer = []
tmp_buffer_len = 0
excess = 0
while self._buffer:
buf = self._buffer.popleft()
size = len(buf)
self._buffered -= size
tmp_buffer.append... |
<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_data(self, data, start_offset, file_len):
"""Send the block to the storage service. This is a utility method that does not modify self. Args: data: dat... |
headers = {}
end_offset = start_offset + len(data) - 1
if data:
headers['content-range'] = ('bytes %d-%d/%s' %
(start_offset, end_offset, file_len))
else:
headers['content-range'] = ('bytes */%s' % file_len)
status, response_headers, content = self._a... |
<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_offset_from_gcs(self):
"""Get the last offset that has been written to GCS. This is a utility method that does not modify self. Returns: an int of the l... |
headers = {'content-range': 'bytes */*'}
status, response_headers, content = self._api.put_object(
self._path_with_token, headers=headers)
errors.check_status(status, [308], self._path, headers,
response_headers, content,
{'upload_path': self._path_wi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _force_close(self, file_length=None):
"""Close this buffer on file_length. Finalize this upload immediately on file_length. Contents that are still in memory... |
if file_length is None:
file_length = self._get_offset_from_gcs() + 1
self._send_data('', 0, file_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 receive_data(self, data):
"""Add data to our internal recieve buffer. This does not actually do any processing on the data, just stores it. To trigger proces... |
if data:
if self._receive_buffer_closed:
raise RuntimeError(
"received close, then received more data?")
self._receive_buffer += data
else:
self._receive_buffer_closed = 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 next_event(self):
"""Parse the next event out of our receive buffer, update our internal state, and return it. This is a mutating operation -- think of it li... |
if self.their_state is ERROR:
raise RemoteProtocolError(
"Can't receive data when peer state is ERROR")
try:
event = self._extract_next_receive_event()
if event not in [NEED_DATA, PAUSED]:
self._process_event(self.their_role, event)
... |
<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(self, event):
"""Convert a high-level event into bytes that can be sent to the peer, while updating our internal state machine. Args: event: The :ref:`e... |
data_list = self.send_with_data_passthrough(event)
if data_list is None:
return None
else:
return b"".join(data_list) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def adam7_generate(width, height):
""" Generate the coordinates for the reduced scanlines of an Adam7 interlaced image of size `width` by `height` pixels. Yields... |
for xstart, ystart, xstep, ystep in adam7:
if xstart >= width:
continue
yield ((xstart, y, xstep) for y in range(ystart, height, ystep)) |
<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_chunk(outfile, tag, data=b''):
""" Write a PNG chunk to the output file, including length and checksum. """ |
data = bytes(data)
# http://www.w3.org/TR/PNG/#5Chunk-layout
outfile.write(struct.pack("!I", len(data)))
outfile.write(tag)
outfile.write(data)
checksum = zlib.crc32(tag)
checksum = zlib.crc32(data, checksum)
checksum &= 2 ** 32 - 1
outfile.write(struct.pack("!I", checksum)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pack_rows(rows, bitdepth):
"""Yield packed rows that are a byte array. Each byte is packed with the values from several pixels. """ |
assert bitdepth < 8
assert 8 % bitdepth == 0
# samples per byte
spb = int(8 / bitdepth)
def make_byte(block):
"""Take a block of (2, 4, or 8) values,
and pack them into a single byte.
"""
res = 0
for v in block:
res = (res << bitdepth) + v
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unpack_rows(rows):
"""Unpack each row from being 16-bits per value, to being a sequence of bytes. """ |
for row in rows:
fmt = '!%dH' % len(row)
yield bytearray(struct.pack(fmt, *row)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_natural(x):
"""A non-negative integer.""" |
try:
is_integer = int(x) == x
except (TypeError, ValueError):
return False
return is_integer and x >= 0 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def binary_stdout():
""" A sys.stdout that accepts bytes. """ |
# First there is a Python3 issue.
try:
stdout = sys.stdout.buffer
except AttributeError:
# Probably Python 2, where bytes are strings.
stdout = sys.stdout
# On Windows the C runtime file orientation needs changing.
if sys.platform == "win32":
import msvcrt
... |
<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_packed(self, outfile, rows):
""" Write PNG file to `outfile`. `rows` should be an iterator that yields each packed row; a packed row being a sequence o... |
self.write_preamble(outfile)
# http://www.w3.org/TR/PNG/#11IDAT
if self.compression is not None:
compressor = zlib.compressobj(self.compression)
else:
compressor = zlib.compressobj()
# data accumulates bytes to be compressed for the IDAT chunk;
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def array_scanlines_interlace(self, pixels):
""" Generator for interlaced scanlines from an array. `pixels` is the full source image as a single array of values.... |
# http://www.w3.org/TR/PNG/#8InterlaceMethods
# Array type.
fmt = 'BH'[self.bitdepth > 8]
# Value per row
vpr = self.width * self.planes
# Each iteration generates a scanline starting at (x, y)
# and consisting of every xstep pixels.
for lines in adam7_... |
<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(self, file):
"""Write the image to the open file object. See `.save()` if you have a filename. In general, you can only call this method once; after it... |
w = Writer(**self.info)
w.write(file, self.rows) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _deinterlace(self, raw):
""" Read raw pixel data, undo filters, deinterlace, and flatten. Return a single array of values. """ |
# Values per row (of the target image)
vpr = self.width * self.planes
# Values per image
vpi = vpr * self.height
# Interleaving writes to the output array randomly
# (well, not quite), so the entire output array must be in memory.
# Make a result array, and mak... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _bytes_to_values(self, bs, width=None):
"""Convert a packed row of bytes into a row of values. Result will be a freshly allocated object, not shared with the... |
if self.bitdepth == 8:
return bytearray(bs)
if self.bitdepth == 16:
return array('H',
struct.unpack('!%dH' % (len(bs) // 2), bs))
assert self.bitdepth < 8
if width is None:
width = self.width
# Samples per byte
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _iter_straight_packed(self, byte_blocks):
"""Iterator that undoes the effect of filtering; yields each row as a sequence of packed bytes. Assumes input is st... |
# length of row, in bytes
rb = self.row_bytes
a = bytearray()
# The previous (reconstructed) scanline.
# None indicates first line of image.
recon = None
for some_bytes in byte_blocks:
a.extend(some_bytes)
while len(a) >= rb + 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 preamble(self, lenient=False):
""" Extract the image metadata by reading the initial part of the PNG file up to the start of the ``IDAT`` chunk. All the chun... |
self.validate_signature()
while True:
if not self.atchunk:
self.atchunk = self._chunk_len_type()
if self.atchunk is None:
raise FormatError('This PNG file has no IDAT chunks.')
if self.atchunk[1] == b'IDAT':
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 _dehex(s):
"""Liberally convert from hex string to binary string.""" |
import re
import binascii
# Remove all non-hexadecimal digits
s = re.sub(br'[^a-fA-F\d]', b'', s)
# binscii.unhexlify works in Python 2 and Python 3 (unlike
# thing.decode('hex')).
return binascii.unhexlify(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 s15f16l(s):
"""Convert sequence of ICC s15Fixed16 to list of float.""" |
# Note: As long as float has at least 32 bits of mantissa, all
# values are preserved.
n = len(s) // 4
t = struct.unpack('>%dl' % n, s)
return map((2**-16).__mul__, t) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def RDcurv(s):
"""Convert ICC curveType.""" |
# See [ICC 2001] 6.5.3
assert s[0:4] == 'curv'
count, = struct.unpack('>L', s[8:12])
if count == 0:
return dict(gamma=1)
table = struct.unpack('>%dH' % count, s[12:])
if count == 1:
return dict(gamma=table[0] * 2 ** -8)
return table |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def RDvcgt(s):
"""Convert Apple CMVideoCardGammaType.""" |
# See
# http://developer.apple.com/documentation/GraphicsImaging/Reference/ColorSync_Manager/Reference/reference.html#//apple_ref/c/tdef/CMVideoCardGammaType
assert s[0:4] == 'vcgt'
tagtype, = struct.unpack('>L', s[8:12])
if tagtype != 0:
return s[8:]
if tagtype == 0:
# Table.
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def greyInput(self):
"""Adjust ``self.d`` dictionary for greyscale input device. ``profileclass`` is 'scnr', ``colourspace`` is 'GRAY', ``pcs`` is 'XYZ '. """ |
self.d.update(dict(profileclass='scnr',
colourspace='GRAY', pcs='XYZ '))
return 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 write(self, out):
"""Write ICC Profile to the file.""" |
if not self.rawtagtable:
self.rawtagtable = self.rawtagdict.items()
tags = tagblock(self.rawtagtable)
self.writeHeader(out, 128 + len(tags))
out.write(tags)
out.flush()
return 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 writeHeader(self, out, size=999):
"""Add default values to the instance's `d` dictionary, then write a header out onto the file stream. The size of the profi... |
def defaultkey(d, key, value):
"""Add ``[key]==value`` to the dictionary `d`, but only if
it does not have that key already.
"""
if key in d:
return
d[key] = value
z = '\x00' * 4
defaults = dict(preferredCMM=z,
... |
<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(f, output=sys.stdout):
"""Convert Plan 9 file to PNG format. Works with either uncompressed or compressed files. """ |
r = f.read(11)
if r == 'compressed\n':
png(output, *decompress(f))
else:
png(output, *glue(f, 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 bitdepthof(pixel):
"""Return the bitdepth for a Plan9 pixel format string.""" |
maxd = 0
for c in re.findall(r'[a-z]\d*', pixel):
if c[0] != 'x':
maxd = max(maxd, int(c[1:]))
return maxd |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decompress(f):
"""Decompress a Plan 9 image file. Assumes f is already cued past the initial 'compressed\n' string. """ |
r = meta(f.read(60))
return r, decomprest(f, r[4]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decomprest(f, rows):
"""Iterator that decompresses the rest of a file once the metadata have been consumed.""" |
row = 0
while row < rows:
row, o = deblock(f)
yield o |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prepareList(self, listFile=False, noSample=False):
""" Load and filter the server list for only the servers we care about """ |
logging.debug("Loading resolver file")
listFileLocation = self.listLocal if not listFile else listFile
# Resolve the user part of the path
listLocal = os.path.expanduser(listFileLocation)
# Check local file location exists and is writable
assert os.path.isdir(os.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 query(self, domain, recordType, progress=True):
""" Run the query Query spins out multiple thread workers to query each server @param domain: Domain to query... |
# Ignore domain validation, if someone wants to lookup an invalid
# domain let them, just ensure it's a string
assert type(domain) == str, "Domain must be a string"
# Ensure record type is valid, and in our list of allowed records
recordType = recordType.upper()
assert... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def outputSimple(self):
""" Simple output mode """ |
out = []
errors = []
successfulResponses = \
len([True for rsp in self.results if rsp['success']])
out.append("INFO QUERIED {0}".format(
len(self.serverList)))
out.append("INFO SUCCESS {0}".format(
successfulResponses))
out.append("... |
<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):
""" Do a single DNS query against a server """ |
logging.debug("Querying server {0}".format(self.server['ip']))
try:
# Create a DNS resolver query
rsvr = dns.resolver.Resolver()
rsvr.nameservers = [self.server['ip']]
rsvr.lifetime = 5
rsvr.timeout = 5
qry = rsvr.query(self.dom... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def aws_to_unix_id(aws_key_id):
"""Converts a AWS Key ID into a UID""" |
uid_bytes = hashlib.sha256(aws_key_id.encode()).digest()[-2:]
if USING_PYTHON2:
return 2000 + int(from_bytes(uid_bytes) // 2)
else:
return 2000 + (int.from_bytes(uid_bytes, byteorder=sys.byteorder) // 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 _gorg(cls):
"""This function exists for compatibility with old typing versions.""" |
assert isinstance(cls, GenericMeta)
if hasattr(cls, '_gorg'):
return cls._gorg
while cls.__origin__ is not None:
cls = cls.__origin__
return cls |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _eval_args(args):
"""Internal helper for get_args.""" |
res = []
for arg in args:
if not isinstance(arg, tuple):
res.append(arg)
elif is_callable_type(arg[0]):
callable_args = _eval_args(arg[1:])
if len(arg) == 2:
res.append(Callable[[], callable_args[0]])
elif arg[1] is Ellipsis:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on(self, eventName, cb):
""" Subscribe to an igv.js event. :param Name of the event. Currently only "locuschange" is supported. :type str :param cb - callbac... |
self.eventHandlers[eventName] = cb
return self._send({
"id": self.igv_id,
"command": "on",
"eventName": eventName
}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def log_request(request: str, trim_log_values: bool = False, **kwargs: Any) -> None: """Log a request""" |
return log_(request, request_logger, logging.INFO, trim=trim_log_values, **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 log_response(response: str, trim_log_values: bool = False, **kwargs: Any) -> None: """Log a response""" |
return log_(response, response_logger, logging.INFO, trim=trim_log_values, **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 validate(request: Union[Dict, List], schema: dict) -> Union[Dict, List]: """ Wraps jsonschema.validate, returning the same object passed in. Args: request: Th... |
jsonschema_validate(request, schema)
return request |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.