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 compute_cusum_ts(self, ts): """ Compute the Cumulative Sum at each point 't' of the time series. """
mean = np.mean(ts) cusums = np.zeros(len(ts)) cusum[0] = (ts[0] - mean) for i in np.arange(1, len(ts)): cusums[i] = cusums[i - 1] + (ts[i] - mean) assert(np.isclose(cumsum[-1], 0.0)) return cusums
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def detect_mean_shift(self, ts, B=1000): """ Detect mean shift in a time series. B is number of bootstrapped samples to draw. """
x = np.arange(0, len(ts)) stat_ts_func = self.compute_balance_mean_ts null_ts_func = self.shuffle_timeseries stats_ts, pvals, nums = self.get_ts_stats_significance(x, ts, stat_ts_func, null_ts_func, B=B, permute_fast=True) return stats_ts, pvals, nums
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parallelize_func(iterable, func, chunksz=1, n_jobs=16, *args, **kwargs): """ Parallelize a function over each element of an iterable. """
chunker = func chunks = more_itertools.chunked(iterable, chunksz) chunks_results = Parallel(n_jobs=n_jobs, verbose=50)( delayed(chunker)(chunk, *args, **kwargs) for chunk in chunks) results = more_itertools.flatten(chunks_results) return list(results)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ts_stats_significance(ts, ts_stat_func, null_ts_func, B=1000, permute_fast=False): """ Compute the statistical significance of a test statistic at each point...
stats_ts = ts_stat_func(ts) if permute_fast: # Permute it in 1 shot null_ts = map(np.random.permutation, np.array([ts, ] * B)) else: null_ts = np.vstack([null_ts_func(ts) for i in np.arange(0, B)]) stats_null_ts = np.vstack([ts_stat_func(nts) for nts in null_ts]) pvals = [] ...
<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_ci(theta_star, blockratio=1.0): """ Get the confidence interval. """
# get rid of nans while we sort b_star = np.sort(theta_star[~np.isnan(theta_star)]) se = np.std(b_star) * np.sqrt(blockratio) # bootstrap 95% CI based on empirical percentiles ci = [b_star[int(len(b_star) * .025)], b_star[int(len(b_star) * .975)]] return ci
<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_pvalue(value, ci): """ Get the p-value from the confidence interval."""
from scipy.stats import norm se = (ci[1] - ci[0]) / (2.0 * 1.96) z = value / se pvalue = -2 * norm.cdf(-np.abs(z)) return pvalue
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ts_stats_significance_bootstrap(ts, stats_ts, stats_func, B=1000, b=3): """ Compute the statistical significance of a test statistic at each point of the tim...
pvals = [] for tp in np.arange(0, len(stats_ts)): pf = partial(stats_func, t=tp) bs = bootstrap_ts(ts, pf, B=B, b=b) ci = get_ci(bs, blockratio=b / len(stats_ts)) pval = abs(get_pvalue(stats_ts[tp], ci)) pvals.append(pval) return pvals
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def format_traceback(extracted_tb, exc_type, exc_value, cwd='', term=None, function_color=12, dim_color=8, editor='vi', template=DEFAULT_EDITOR_SHORTCUT_TEMPLATE)...
def format_shortcut(editor, path, line_number, function=None): """Return a pretty-printed editor shortcut.""" return template.format(editor=editor, line_number=line_number or 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 extract_relevant_tb(tb, exctype, is_test_failure): """Return extracted traceback frame 4-tuples that aren't unittest ones. This used to be _exc_info_to_strin...
# Skip test runner traceback levels: while tb and _is_unittest_frame(tb): tb = tb.tb_next if is_test_failure: # Skip assert*() traceback levels: length = _count_relevant_tb_levels(tb) return extract_tb(tb, length) return extract_tb(tb)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _unicode_decode_extracted_tb(extracted_tb): """Return a traceback with the string elements translated into Unicode."""
return [(_decode(file), line_number, _decode(function), _decode(text)) for file, line_number, function, text in extracted_tb]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _count_relevant_tb_levels(tb): """Return the number of frames in ``tb`` before all that's left is unittest frames. Unlike its namesake in unittest, this does...
length = contiguous_unittest_frames = 0 while tb: length += 1 if _is_unittest_frame(tb): contiguous_unittest_frames += 1 else: contiguous_unittest_frames = 0 tb = tb.tb_next return length - contiguous_unittest_frames
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cmdloop(self, *args, **kwargs): """Call pdb's cmdloop, making readline work. Patch raw_input so it sees the original stdin and stdout, lest readline refuse t...
def unwrapping_raw_input(*args, **kwargs): """Call raw_input(), making sure it finds an unwrapped stdout.""" wrapped_stdout = sys.stdout sys.stdout = wrapped_stdout.stream ret = orig_raw_input(*args, **kwargs) sys.stdout = wrapped_stdout return ret 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 set_trace(*args, **kwargs): """Call pdb.set_trace, making sure it receives the unwrapped stdout. This is so we don't keep drawing progress bars over debugger...
# There's no stream attr if capture plugin is enabled: out = sys.stdout.stream if hasattr(sys.stdout, 'stream') else None # Python 2.5 can't put an explicit kwarg and **kwargs in the same function # call. kwargs['stdout'] = out debugger = pdb.Pdb(*args, **kwargs) # Ordinarily (and in a si...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def begin(self): """Make some monkeypatches to dodge progress bar. Wrap stderr and stdout to keep other users of them from smearing the progress bar. Wrap some p...
# The calls to begin/finalize end up like this: a call to begin() on # instance A of the plugin, then a paired begin/finalize for each test # on instance B, then a final call to finalize() on instance A. # TODO: Do only if isatty. self._stderr.append(sys.stderr) sys.std...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def finalize(self, result): """Put monkeypatches back as we found them."""
sys.stderr = self._stderr.pop() sys.stdout = self._stdout.pop() pdb.set_trace = self._set_trace.pop() pdb.Pdb.cmdloop = self._cmdloop.pop()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def configure(self, options, conf): """Turn style-forcing on if bar-forcing is on. It'd be messy to position the bar but still have the rest of the terminal capa...
super(ProgressivePlugin, self).configure(options, conf) if (getattr(options, 'verbosity', 0) > 1 and getattr(options, 'enable_plugin_id', False)): # TODO: Can we forcibly disable the ID plugin? print ('Using --with-id and --verbosity=2 or higher with ' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self, test_path, number): """Draw an updated progress bar. At the moment, the graph takes a fixed width, and the test identifier takes the rest of the...
# TODO: Play nicely with absurdly narrow terminals. (OS X's won't even # go small enough to hurt us.) # Figure out graph: GRAPH_WIDTH = 14 # min() is in case we somehow get the total test count wrong. It's tricky. num_filled = int(round(min(1.0, float(number) / self.max...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def erase(self): """White out the progress bar."""
with self._at_last_line(): self.stream.write(self._term.clear_eol) self.stream.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 dodging(bar): """Return a context manager which erases the bar, lets you output things, and then redraws the bar. It's reentrant. """
class ShyProgressBar(object): """Context manager that implements a progress bar that gets out of the way""" def __enter__(self): """Erase the progress bar so bits of disembodied progress bar don't get scrolled up the terminal.""" # My terminal has no sta...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _makeResult(self): """Return a Result that doesn't print dots. Nose's ResultProxy will wrap it, and other plugins can still print stuff---but without smashin...
return ProgressiveResult(self._cwd, self._totalTests, self.stream, config=self.config)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def run(self, test): "Run the given test case or test suite...quietly." # These parts of Nose's pluggability are baked into # nose.core.TextTestRunner. Reproduce them: wrapper = self.config.plugins.prepareTest(test) if wrapper is not None: test = wrapper wrapp...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _printTraceback(self, test, err): """Print a nicely formatted traceback. :arg err: exc_info()-style traceback triple :arg test: the test that precipitated th...
# Don't bind third item to a local var; that can create # circular refs which are expensive to collect. See the # sys.exc_info() docs. exception_type, exception_value = err[:2] # TODO: In Python 3, the traceback is attached to the exception # instance through the __trace...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _printHeadline(self, kind, test, is_failure=True): """Output a 1-line error summary to the stream if appropriate. The line contains the kind of error and the...
if is_failure or self._options.show_advisories: with self.bar.dodging(): self.stream.writeln( '\n' + (self._term.bold if is_failure else '') + '%s: %s' % (kind, nose_selector(test)) + (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 _recordAndPrintHeadline(self, test, error_class, artifact): """Record that an error-like thing occurred, and print a summary. Store ``artifact`` with the rec...
# We duplicate the errorclass handling from super rather than calling # it and monkeying around with showAll flags to keep it from printing # anything. is_error_class = False for cls, (storage, label, is_failure) in self.errorClasses.items(): if isclass(error_class) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addSkip(self, test, reason): """Catch skipped tests in Python 2.7 and above. Though ``addSkip()`` is deprecated in the nose plugin API, it is very much not d...
self._recordAndPrintHeadline(test, SkipTest, reason) # Python 2.7 users get a little bonus: the reason the test was skipped. if isinstance(reason, Exception): reason = getattr(reason, 'message', None) or getattr( reason, 'args')[0] if reason and self._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 printSummary(self, start, stop): """As a final summary, print number of tests, broken down by result."""
def renderResultType(type, number, is_failure): """Return a rendering like '2 failures'. :arg type: A singular label, like "failure" :arg number: The number of tests with a result of that type :arg is_failure: Whether that type counts as a failure "...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nose_selector(test): """Return the string you can pass to nose to run `test`, including argument values if the test was made by a test generator. Return "Unk...
address = test_address(test) if address: file, module, rest = address if module: if rest: try: return '%s:%s%s' % (module, rest, test.test.arg or '') except AttributeError: return '%s:%s' % (module, rest) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def human_path(path, cwd): """Return the most human-readable representation of the given path. If an absolute path is given that's within the current directory, ...
# TODO: Canonicalize the path to remove /kitsune/../kitsune nonsense. path = abspath(path) if cwd and path.startswith(cwd): path = path[len(cwd) + 1:] # Make path relative. Remove leading slash. return 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 know(self, what, confidence): """Know something with the given confidence, and return self for chaining. If confidence is higher than that of what we already...
if confidence > self.confidence: self.best = what self.confidence = confidence 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 _generate_arg_types(coordlist_length, shape_name): """Find coordinate types based on shape name and coordlist length This function returns a list of coordina...
from .ds9_region_parser import ds9_shape_defs from .ds9_attr_parser import ds9_shape_in_comment_defs if shape_name in ds9_shape_defs: shape_def = ds9_shape_defs[shape_name] else: shape_def = ds9_shape_in_comment_defs[shape_name] initial_arg_types = shape_def.args_list arg_repe...
<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_to_imagecoord(shape, header): """Convert the coordlist of `shape` to image coordinates Parameters shape : `pyregion.parser_helper.Shape` The `Shape` ...
arg_types = _generate_arg_types(len(shape.coord_list), shape.name) new_coordlist = [] is_even_distance = True coord_list_iter = iter(zip(shape.coord_list, arg_types)) new_wcs = WCS(header) pixel_scales = proj_plane_pixel_scales(new_wcs) for coordinate, coordinate_type in coord_list_iter:...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_auth_info(): """ Get authentication details to jottacloud. Will first check environment variables, then the .netrc file. """
env_username = os.environ.get('JOTTACLOUD_USERNAME') env_password = os.environ.get('JOTTACLOUD_PASSWORD') netrc_auth = None try: netrc_file = netrc.netrc() netrc_auth = netrc_file.authenticators('jottacloud.com') except IOError: # .netrc file doesn't exist pass 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 calculate_md5(fileobject, size=2**16): """Utility function to calculate md5 hashes while being light on memory usage. By reading the fileobject piece by piec...
fileobject.seek(0) md5 = hashlib.md5() for data in iter(lambda: fileobject.read(size), b''): if not data: break if isinstance(data, six.text_type): data = data.encode('utf-8') # md5 needs a byte string md5.update(data) fileobject.seek(0) # rewind read head 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 deleted(self): 'Return datetime.datetime or None if the file isnt deleted' _d = self.folder.attrib.get('deleted', None) if _d is None: return None return dateutil.parser.parse(str(_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 sync(self): 'Update state of folder from Jottacloud server' log.info("syncing %r" % self.path) self.folder = self.jfs.get(self.path) self.synced = 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 mkdir(self, foldername): 'Create a new subfolder and return the new JFSFolder' #url = '%s?mkDir=true' % posixpath.join(self.path, foldername) url = posixpath.join(self.path, foldername) params = {'mkDir':'true'} r = self.jfs.post(url, params) self.sync() retur...
<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(self): 'Delete this folder and return a deleted JFSFolder' #url = '%s?dlDir=true' % self.path params = {'dlDir':'true'} r = self.jfs.post(self.path, params) self.sync() 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 hard_delete(self): 'Deletes without possibility to restore' url = 'https://www.jottacloud.com/rest/webrest/%s/action/delete' % self.jfs.username data = {'paths[]': self.path.replace(JFS_ROOT, ''), 'web': 'true', 'ts': int(time.time()), 'authTok...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def rename(self, newpath): "Move folder to a new name, possibly a whole new path" # POST https://www.jottacloud.com/jfs/**USERNAME**/Jotta/Sync/Ny%20mappe?mvDir=/**USERNAME**/Jotta/Sync/testFolder #url = '%s?mvDir=/%s%s' % (self.path, self.jfs.username, newpath) params = {'mvDir':'/%s%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 up(self, fileobj_or_path, filename=None, upload_callback=None): 'Upload a file to current folder and return the new JFSFile' close_on_done = False if isinstance(fileobj_or_path, six.string_types): filename = filename or os.path.basename(fileobj_or_path) fileobj_or_pa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def factory(fileobject, jfs, parentpath): # fileobject from lxml.objectify 'Class method to get the correct file class instatiated' if hasattr(fileobject, 'currentRevision'): # a normal file return JFSFile(fileobject, jfs, parentpath) elif str(fileobject.latestRevision.state) == Prot...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def resume(self, data): 'Resume uploading an incomplete file, after a previous upload was interrupted. Returns new file object' if not hasattr(data, 'read'): data = six.BytesIO(data)#StringIO(data) #Check that we actually know from what byte to resume. #If self.size === -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 size(self): """Bytes uploaded of the file so far. Note that we only have the file size if the file was requested directly, not if it's part of a folder listi...
if hasattr(self.f.latestRevision, 'size'): return int(self.f.latestRevision.size) return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def stream(self, chunk_size=64*1024): 'Returns a generator to iterate over the file contents' #return self.jfs.stream(url='%s?mode=bin' % self.path, chunk_size=chunk_size) return self.jfs.stream(url=self.path, params={'mode':'bin'}, chunk_size=chunk_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 restore(self): 'Restore the file' # # # As of 2016-06-15, Jottacloud.com has changed their restore api # To restore, this is what's done # # HTTP POST to https://www.jottacloud.com/web/restore/trash/list # Data: # hash:undefined # ...
<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(self): 'Delete this file and return the new, deleted JFSFile' #url = '%s?dl=true' % self.path r = self.jfs.post(url=self.path, params={'dl':'true'}) 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 thumb(self, size=BIGTHUMB): '''Get a thumbnail as string or None if the file isnt an image size would be one of JFSFile.BIGTHUMB, .MEDIUMTHUMB, .SMALLTHUMB or .XLTHUMB''' if not self.is_image(): return None if not size in (self.BIGTHUMB, self.MEDIUMTHUMB, self.SMALLTHUMB...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def new_mountpoint(self, name): """Create a new mountpoint"""
url = posixpath.join(self.path, name) r = self._jfs.post(url, extra_headers={'content-type': 'application/x-www-form-urlencoded'}) 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 sharedFiles(self): 'iterate over shared files and get their public URI' for f in self.sharing.files.iterchildren(): yield (f.attrib['name'], f.attrib['uuid'], 'https://www.jottacloud.com/p/%s/%s' % (self.jfs.username, f.publicURI.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 files(self): 'iterate over found files' for _f in self.searchresult.files.iterchildren(): yield ProtoFile.factory(_f, jfs=self.jfs, parentpath=unicode(_f.abspath))
<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(self, url, extra_headers=None, params=None): 'Make a GET request for url, with or without caching' if not url.startswith('http'): # relative url url = self.rootpath + url log.debug("getting url: %r, extra_headers=%r, params=%r", url, extra_headers, 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 raw(self, url, extra_headers=None, params=None): 'Make a GET request for url and return whatever content we get' r = self.request(url, extra_headers=extra_headers, params=params) # uncomment to dump raw xml # with open('/tmp/%s.xml' % time.time(), 'wb') as f: # f.write(r....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get(self, url, params=None): 'Make a GET request for url and return the response content as a generic lxml.objectify object' url = self.escapeUrl(url) content = six.BytesIO(self.raw(url, params=params)) # We need to make sure that the xml fits in available memory before we parse ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def devices(self): 'return generator of configured devices' return self.fs is not None and [JFSDevice(d, self, parentpath=self.rootpath) for d in self.fs.devices.iterchildren()] or [x for x in []]
<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(region_string): """Parse DS9 region string into a ShapeList. Parameters region_string : str Region string Returns ------- shapes : `ShapeList` List of ...
rp = RegionParser() ss = rp.parse(region_string) sss1 = rp.convert_attr(ss) sss2 = _check_wcs(sss1) shape_list, comment_list = rp.filter_shape2(sss2) return ShapeList(shape_list, comment_list=comment_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 open(fname): """Open, read and parse DS9 region file. Parameters fname : str Filename Returns ------- shapes : `ShapeList` List of `~pyregion.Shape` """
with _builtin_open(fname) as fh: region_string = fh.read() return parse(region_string)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_region(s): """Read region. Parameters s : str Region string Returns ------- shapes : `ShapeList` List of `~pyregion.Shape` """
rp = RegionParser() ss = rp.parse(s) sss1 = rp.convert_attr(ss) sss2 = _check_wcs(sss1) shape_list = rp.filter_shape(sss2) return ShapeList(shape_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 read_region_as_imagecoord(s, header): """Read region as image coordinates. Parameters s : str Region string header : `~astropy.io.fits.Header` FITS header Re...
rp = RegionParser() ss = rp.parse(s) sss1 = rp.convert_attr(ss) sss2 = _check_wcs(sss1) sss3 = rp.sky_to_image(sss2, header) shape_list = rp.filter_shape(sss3) return ShapeList(shape_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 get_mask(region, hdu, origin=1): """Get mask. Parameters region : `~pyregion.ShapeList` List of `~pyregion.Shape` hdu : `~astropy.io.fits.ImageHDU` FITS imag...
from pyregion.region_to_filter import as_region_filter data = hdu.data region_filter = as_region_filter(region, origin=origin) mask = region_filter.mask(data) return mask
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_imagecoord(self, header): """New shape list in image coordinates. Parameters header : `~astropy.io.fits.Header` FITS header Returns ------- shape_list : `...
comment_list = self._comment_list if comment_list is None: comment_list = cycle([None]) r = RegionParser.sky_to_image(zip(self, comment_list), header) shape_list, comment_list = zip(*list(r)) return ShapeList(shape_list, commen...
<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_mask(self, hdu=None, header=None, shape=None): """Create a 2-d mask. Parameters hdu : `astropy.io.fits.ImageHDU` FITS image HDU header : `~astropy.io.fit...
if hdu and header is None: header = hdu.header if hdu and shape is None: shape = hdu.data.shape region_filter = self.get_filter(header=header) mask = region_filter.mask(shape) return mask
<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, outfile): """Write this shape list to a region file. Parameters outfile : str File name """
if len(self) < 1: print("WARNING: The region list is empty. The region file " "'{:s}' will be empty.".format(outfile)) try: outf = _builtin_open(outfile, 'w') outf.close() return except IOError as e: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def AppConfigFlagHandler(feature=None): """ This is the default handler. It checks for feature flags in the current app's configuration. For example, to have 'un...
if not current_app: log.warn(u"Got a request to check for {feature} but we're outside the request context. Returning False".format(feature=feature)) return False try: return current_app.config[FEATURE_FLAGS_CONFIG][feature] except (AttributeError, KeyError): raise NoFeatureFlagFound()
<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_active(feature): """ Check if a feature is active """
if current_app: feature_flagger = current_app.extensions.get(EXTENSION_NAME) if feature_flagger: return feature_flagger.check(feature) else: raise AssertionError("Oops. This application doesn't have the Flask-FeatureFlag extention installed.") else: log.warn(u"Got a request to check f...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_active_feature(feature, redirect_to=None, redirect=None): """ Decorator for Flask views. If a feature is off, it can either return a 404 or redirect to a ...
def _is_active_feature(func): @wraps(func) def wrapped(*args, **kwargs): if not is_active(feature): url = redirect_to if redirect: url = url_for(redirect) if url: log.debug(u'Feature {feature} is off, redirecting to {url}'.format(feature=feature, url=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 init_app(self, app): """ Add ourselves into the app config and setup, and add a jinja function test """
app.config.setdefault(FEATURE_FLAGS_CONFIG, {}) app.config.setdefault(RAISE_ERROR_ON_MISSING_FEATURES, False) if hasattr(app, "add_template_test"): # flask 0.10 and higher has a proper hook app.add_template_test(self.check, name=self.JINJA_TEST_NAME) else: app.jinja_env.tests[self.J...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check(self, feature): """ Loop through all our feature flag checkers and return true if any of them are true. The order of handlers matters - we will immedia...
found = False for handler in self.handlers: try: if handler(feature): return True except StopCheckingFeatureFlags: return False except NoFeatureFlagFound: pass else: found = True if not found: message = u"No feature flag defined 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 yank_path(self, path): """Clear cache of results from a specific path"""
for func in self._caches: cache = {} for key in self._caches[func].keys(): log.debug("cache key %s for func %s", key, func) if path in key[0]: log.debug("del cache key %s", key) del self._caches[func][key]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def release(self, path, fh): "Run after a read or write operation has finished. This is where we upload on writes" #print "release! inpath:", path in self.__newfiles.keys() # if the path exists in self.__newfiles.keys(), we have a new version to upload try: f = self.__newfile...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def truncate(self, path, length, fh=None): "Download existing path, truncate and reupload" try: f = self._getpath(path) except JFS.JFSError: raise OSError(errno.ENOENT, '') if isinstance(f, (JFS.JFSFile, JFS.JFSFolder)) and f.is_deleted(): raise OSErro...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def commandline_text(bytestring): 'Convert bytestring from command line to unicode, using default file system encoding' if six.PY3: return bytestring unicode_string = bytestring.decode(sys.getfilesystemencoding()) return unicode_string
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sky_to_image(shape_list, header): """Converts a `ShapeList` into shapes with coordinates in image coordinates Parameters shape_list : `pyregion.ShapeList` Th...
for shape, comment in shape_list: if isinstance(shape, Shape) and \ (shape.coord_format not in image_like_coordformats): new_coords = convert_to_imagecoord(shape, header) l1n = copy.copy(shape) l1n.coord_list = new_coords ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _new(self, src_path, dry_run=False, remove_uploaded=False): 'Code to upload' # are we getting a symbolic link? if os.path.islink(src_path): sourcefile = os.path.normpath(os.path.join(self.topdir, os.readlink(src_path))) if not os.path.exists(source...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _estimate_angle(angle, reg_coordinate_frame, header): """Transform an angle into a different frame Parameters angle : float, int The number of degrees, measu...
y_axis_rot = _calculate_rotation_angle(reg_coordinate_frame, header) return angle - y_axis_rot
<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_rotation_angle(reg_coordinate_frame, header): """Calculates the rotation angle from the region to the header's frame This attempts to be compatibl...
new_wcs = WCS(header) region_frame = SkyCoord( '0d 0d', frame=reg_coordinate_frame, obstime='J2000') region_frame = SkyCoord( '0d 0d', frame=reg_coordinate_frame, obstime='J2000', equinox=region_frame.equinox) origin = SkyCoord.from_pixel( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sf(f, dirpath, jottapath): """Create and return a SyncFile tuple from filename. localpath will be a byte string with utf8 code points jottapath will be a uni...
log.debug('Create SyncFile from %s', repr(f)) log.debug('Got encoded filename %r, joining with dirpath %r', _encode_filename_to_filesystem(f), dirpath) return SyncFile(localpath=os.path.join(dirpath, _encode_filename_to_filesystem(f)), jottapath=posixpath.join(_decode_filename_to_unicode(...
<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_jottapath(localtopdir, dirpath, jottamountpoint): """Translate localtopdir to jottapath. Returns unicode string"""
log.debug("get_jottapath %r %r %r", localtopdir, dirpath, jottamountpoint) normpath = posixpath.normpath(posixpath.join(jottamountpoint, posixpath.basename(localtopdir), posixpath.relpath(dirpath, localtopdir))) return _decode_filename_to_unicode(normpath)
<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_file(jottapath, JFS): """Check if a file exists on jottacloud"""
log.debug("is_file %r", jottapath) try: jf = JFS.getObject(jottapath) except JFSNotFoundError: return False return isinstance(jf, JFSFile)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compare(localtopdir, jottamountpoint, JFS, followlinks=False, exclude_patterns=None): """Make a tree of local files and folders and compare it with what's cu...
def excluded(unicodepath, fname): fpath = os.path.join(unicodepath, _decode_filename_to_unicode(fname)) # skip FIFOs, block devices, character devices and the like, see bug#129 mode = os.stat(fpath).st_mode if not (stat.S_ISREG(mode) or stat.S_ISLNK(mode) 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 _decode_filename_to_unicode(f): '''Get bytestring filename and return unicode. First, try to decode from default file system encoding If that fails, use ``chardet`` module to guess encoding. As a last resort, try to decode as utf-8. If the argument already is unicode, return as is''' log.d...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _encode_filename_to_filesystem(f): '''Get a unicode filename and return bytestring, encoded to file system default. If the argument already is a bytestring, return as is''' log.debug('_encode_filename_to_filesystem(%s)', repr(f)) if isinstance(f, str): return f try: return f.enc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resume(localfile, jottafile, JFS): """Continue uploading a new file from local file (already exists on JottaCloud"""
with open(localfile) as lf: _complete = jottafile.resume(lf) return _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 replace_if_changed(localfile, jottapath, JFS): """Compare md5 hash to determine if contents have changed. Upload a file from local disk and replace file on J...
jf = JFS.getObject(jottapath) lf_hash = getxattrhash(localfile) # try to read previous hash, stored in xattr if lf_hash is None: # no valid hash found in xattr, with open(localfile) as lf: lf_hash = calculate_md5(lf) # (re)calculate it if type(jf) == JFSIncompleteFile:...
<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_tree(jottapath, JFS): """Get a tree of of files and folders. use as an iterator, you get something like os.walk"""
filedirlist = JFS.getObject('%s?mode=list' % jottapath) log.debug("got tree: %s", filedirlist) if not isinstance(filedirlist, JFSFileDirList): yield ( '', tuple(), tuple() ) for path in filedirlist.tree: yield 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, filename): """Get size of filename"""
# - Query metadata of one file # - Return a dict with a 'size' key, and a file size value (-1 for not found) # - Retried if an exception is thrown log.Info('Querying size of %s' % filename) from jottalib.JFS import JFSNotFoundError, JFSIncompleteFile remote_path = pos...
<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_drawing(document, container, elem): """Parse drawing element. We don't do much with drawing element. We can find embeded image but we don't do more tha...
_blip = elem.xpath('.//a:blip', namespaces=NAMESPACES) if len(_blip) > 0: blip = _blip[0] _rid = blip.attrib[_name('{{{r}}}embed')] img = doc.Image(_rid) container.elements.append(img)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def parse_footnote(document, container, elem): "Parse the footnote element." _rid = elem.attrib[_name('{{{w}}}id')] foot = doc.Footnote(_rid) container.elements.append(foot)
<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_text(document, container, element): "Parse text element." txt = None alternate = element.find(_name('{{{mc}}}AlternateContent')) if alternate is not None: parse_alternate(document, container, alternate) br = element.find(_name('{{{w}}}br')) if br is not None: if _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 parse_paragraph(document, par): """Parse paragraph element. Some other elements could be found inside of paragraph element (math, links). """
paragraph = doc.Paragraph() paragraph.document = document for elem in par: if elem.tag == _name('{{{w}}}pPr'): parse_paragraph_properties(document, paragraph, elem) if elem.tag == _name('{{{w}}}r'): parse_text(document, paragraph, elem) if elem.tag == _na...
<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_table_properties(doc, table, prop): "Parse table properties." if not table: return style = prop.find(_name('{{{w}}}tblStyle')) if style is not None: table.style_id = style.attrib[_name('{{{w}}}val')] doc.add_style_as_used(table.style_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 parse_table_column_properties(doc, cell, prop): "Parse table column properties." if not cell: return grid = prop.find(_name('{{{w}}}gridSpan')) if grid is not None: cell.grid_span = int(grid.attrib[_name('{{{w}}}val')]) vmerge = prop.find(_name('{{{w}}}vMerge')) if vmerg...
<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_table(document, tbl): "Parse table element." def _change(rows, pos_x): if len(rows) == 1: return rows count_x = 1 for x in rows[-1]: if count_x == pos_x: x.row_span += 1 count_x += x.grid_span return rows tab...
<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_document(xmlcontent): """Parse document with content. Content is placed in file 'document.xml'. """
document = etree.fromstring(xmlcontent) body = document.xpath('.//w:body', namespaces=NAMESPACES)[0] document = doc.Document() for elem in body: if elem.tag == _name('{{{w}}}p'): document.elements.append(parse_paragraph(document, elem)) if elem.tag == _name('{{{w}}}tbl'...
<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_relationship(document, xmlcontent, rel_type): """Parse relationship document. Relationships hold information like external or internal references for l...
doc = etree.fromstring(xmlcontent) for elem in doc: if elem.tag == _name('{{{pr}}}Relationship'): rel = {'target': elem.attrib['Target'], 'type': elem.attrib['Type'], 'target_mode': elem.attrib.get('TargetMode', 'Internal')} document.rela...
<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_style(document, xmlcontent): """Parse styles document. Styles are defined in file 'styles.xml'. """
styles = etree.fromstring(xmlcontent) _r = styles.xpath('.//w:rPrDefault', namespaces=NAMESPACES) if len(_r) > 0: rpr = _r[0].find(_name('{{{w}}}rPr')) if rpr is not None: st = doc.Style() parse_previous_properties(document, st, rpr) document.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 parse_comments(document, xmlcontent): """Parse comments document. Comments are defined in file 'comments.xml' """
comments = etree.fromstring(xmlcontent) document.comments = {} for comment in comments.xpath('.//w:comment', namespaces=NAMESPACES): # w:author # w:id # w: date comment_id = comment.attrib[_name('{{{w}}}id')] comm = doc.CommentContent(comment_id) comm.auth...
<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_footnotes(document, xmlcontent): """Parse footnotes document. Footnotes are defined in file 'footnotes.xml' """
footnotes = etree.fromstring(xmlcontent) document.footnotes = {} for footnote in footnotes.xpath('.//w:footnote', namespaces=NAMESPACES): _type = footnote.attrib.get(_name('{{{w}}}type'), None) # don't know what to do with these now if _type in ['separator', 'continuationSeparato...
<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_endnotes(document, xmlcontent): """Parse endnotes document. Endnotes are defined in file 'endnotes.xml' """
endnotes = etree.fromstring(xmlcontent) document.endnotes = {} for note in endnotes.xpath('.//w:endnote', namespaces=NAMESPACES): paragraphs = [parse_paragraph(document, para) for para in note.xpath('.//w:p', namespaces=NAMESPACES)] document.endnotes[note.attrib[_name('{{{w}}}id')]] = pa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_numbering(document, xmlcontent): """Parse numbering document. Numbering is defined in file 'numbering.xml'. """
numbering = etree.fromstring(xmlcontent) document.abstruct_numbering = {} document.numbering = {} for abstruct_num in numbering.xpath('.//w:abstractNum', namespaces=NAMESPACES): numb = {} for lvl in abstruct_num.xpath('./w:lvl', namespaces=NAMESPACES): ilvl = int(lvl.attr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_from_file(file_object): """Parses existing OOXML file. :Args: - file_object (:class:`ooxml.docx.DOCXFile`): OOXML file object :Returns: Returns parsed...
logger.info('Parsing %s file.', file_object.file_name) # Read the files doc_content = file_object.read_file('document.xml') # Parse the document document = parse_document(doc_content) try: style_content = file_object.read_file('styles.xml') parse_style(document, style_conten...