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 set_sides(self, key, data, field, local=False): """ Assign data on the 'key' tile to all the edges """
for side in ['left', 'right', 'top', 'bottom']: self.set(key, data, field, side, local)
<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_neighbor_data(self, neighbor_side, data, key, field): """ Assign data from the 'key' tile to the edge on the neighboring tile which is on the 'neighbor_s...
i = self.keys[key] found = False sides = [] if 'left' in neighbor_side: if i % self.n_cols == 0: return None i -= 1 sides.append('right') found = True if 'right' in neighbor_side: if i % self.n_cols == 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 set_all_neighbors_data(self, data, done, key): """ Given they 'key' tile's data, assigns this information to all neighboring tiles """
# The order of this for loop is important because the topleft gets # it's data from the left neighbor, which should have already been # updated... for side in ['left', 'right', 'top', 'bottom', 'topleft', 'topright', 'bottomleft', 'bottomright']: self.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 fill_n_todo(self): """ Calculate and record the number of edge pixels left to do on each tile """
left = self.left right = self.right top = self.top bottom = self.bottom for i in xrange(self.n_chunks): self.n_todo.ravel()[i] = np.sum([left.ravel()[i].n_todo, right.ravel()[i].n_todo, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fill_n_done(self): """ Calculate and record the number of edge pixels that are done one each tile. """
left = self.left right = self.right top = self.top bottom = self.bottom for i in xrange(self.n_chunks): self.n_done.ravel()[i] = np.sum([left.ravel()[i].n_done, right.ravel()[i].n_done, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fill_percent_done(self): """ Calculate the percentage of edge pixels that would be done if the tile was reprocessed. This is done for each tile. """
left = self.left right = self.right top = self.top bottom = self.bottom for i in xrange(self.n_chunks): self.percent_done.ravel()[i] = \ np.sum([left.ravel()[i].percent_done, right.ravel()[i].percent_done, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fix_shapes(self): """ Fixes the shape of the data fields on edges. Left edges should be column vectors, and top edges should be row vectors, for example. """
for i in xrange(self.n_chunks): for side in ['left', 'right', 'top', 'bottom']: edge = getattr(self, side).ravel()[i] if side in ['left', 'right']: shp = [edge.todo.size, 1] else: shp = [1, edge.todo.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 find_best_candidate(self): """ Determine which tile, when processed, would complete the largest percentage of unresolved edge pixels. This is a heuristic fun...
self.fill_percent_done() i_b = np.argmax(self.percent_done.ravel()) if self.percent_done.ravel()[i_b] <= 0: return None # check for ties I = self.percent_done.ravel() == self.percent_done.ravel()[i_b] if I.sum() == 1: return i_b else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_array(self, array, name=None, partname=None, rootpath='.', raw=False, as_int=True): """ Standard array saving routine Parameters array : array Array to ...
if name is None and partname is not None: fnl_file = self.get_full_fn(partname, rootpath) tmp_file = os.path.join(rootpath, partname, self.get_fn(partname + '_tmp')) elif name is not None: fnl_file = name tmp_file = fnl...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_uca(self, rootpath, raw=False, as_int=False): """ Saves the upstream contributing area to a file """
self.save_array(self.uca, None, 'uca', rootpath, raw, as_int=as_int)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_twi(self, rootpath, raw=False, as_int=True): """ Saves the topographic wetness index to a file """
self.twi = np.ma.masked_array(self.twi, mask=self.twi <= 0, fill_value=-9999) # self.twi = self.twi.filled() self.twi[self.flats] = 0 self.twi.mask[self.flats] = True # self.twi = self.flats self.save_array(self.twi, None, 'twi', ro...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_slope(self, rootpath, raw=False, as_int=False): """ Saves the magnitude of the slope to a file """
self.save_array(self.mag, None, 'mag', rootpath, raw, as_int=as_int)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_direction(self, rootpath, raw=False, as_int=False): """ Saves the direction of the slope to a file """
self.save_array(self.direction, None, 'ang', rootpath, raw, as_int=as_int)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_outputs(self, rootpath='.', raw=False): """Saves TWI, UCA, magnitude and direction of slope to files. """
self.save_twi(rootpath, raw) self.save_uca(rootpath, raw) self.save_slope(rootpath, raw) self.save_direction(rootpath, raw)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_array(self, fn, name): """ Can only load files that were saved in the 'raw' format. Loads previously computed field 'name' from file Valid names are 'ma...
if os.path.exists(fn + '.npz'): array = np.load(fn + '.npz') try: setattr(self, name, array['arr_0']) except Exception, e: print e finally: array.close() else: raise RuntimeError("File %s does ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _assign_chunk(self, data, arr1, arr2, te, be, le, re, ovr, add=False): """ Assign data from a chunk to the full array. The data in overlap regions will not b...
if te == 0: i1 = 0 else: i1 = ovr if be == data.shape[0]: i2 = 0 i2b = None else: i2 = -ovr i2b = -ovr if le == 0: j1 = 0 else: j1 = ovr ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _slopes_directions(self, data, dX, dY, method='tarboton'): """ Wrapper to pick between various algorithms """
# %% if method == 'tarboton': return self._tarboton_slopes_directions(data, dX, dY) elif method == 'central': return self._central_slopes_directions(data, dX, dY)
<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_flats_edges(self, data, mag, direction): """ Extend flats 1 square downstream Flats on the downstream side of the flat might find a valid angle, but th...
i12 = np.arange(data.size).reshape(data.shape) flat = mag == FLAT_ID_INT flats, n = spndi.label(flat, structure=FLATS_KERNEL3) objs = spndi.find_objects(flats) f = flat.ravel() d = data.ravel() for i, _obj in enumerate(objs): region = flats[_obj] =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _drain_step(self, A, ids, area, done, edge_todo): """ Does a single step of the upstream contributing area calculation. Here the pixels in ids are drained do...
# Only drain to cells that have a contribution A_todo = A[:, ids.ravel()] colsum = np.array(A_todo.sum(1)).ravel() # Only touch cells that actually receive a contribution # during this stage ids_new = colsum != 0 # Is it possible that I may drain twice from my ow...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _mk_adjacency_matrix(self, section, proportion, flats, elev, mag, dX, dY): """ Calculates the adjacency of connectivity matrix. This matrix tells which pixel...
shp = section.shape mat_data = np.row_stack((proportion, 1 - proportion)) NN = np.prod(shp) i12 = np.arange(NN).reshape(shp) j1 = - np.ones_like(i12) j2 = - np.ones_like(i12) # make the connectivity for the non-flats/pits j1, j2 = self._mk_connectivity(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 calc_twi(self): """ Calculates the topographic wetness index and saves the result in self.twi. Returns ------- twi : array Array giving the topographic wetne...
if self.uca is None: self.calc_uca() gc.collect() # Just in case min_area = self.twi_min_area min_slope = self.twi_min_slope twi = self.uca.copy() if self.apply_twi_limits_on_uca: twi[twi > self.uca_saturation_limit * min_area] = \ ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _plot_debug_slopes_directions(self): """ A debug function to plot the direction calculated in various ways. """
# %% from matplotlib.pyplot import matshow, colorbar, clim, title matshow(self.direction / np.pi * 180); colorbar(); clim(0, 360) title('Direction') mag2, direction2 = self._central_slopes_directions() matshow(direction2 / np.pi * 180.0); colorbar(); clim(0, 360) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clean(ctx, dry_run=False): """Cleanup generated document artifacts."""
basedir = ctx.sphinx.destdir or "build/docs" cleanup_dirs([basedir], dry_run=dry_run)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build(ctx, builder="html", options=""): """Build docs with sphinx-build"""
sourcedir = ctx.config.sphinx.sourcedir destdir = Path(ctx.config.sphinx.destdir or "build")/builder destdir = destdir.abspath() with cd(sourcedir): destdir_relative = Path(".").relpathto(destdir) command = "sphinx-build {opts} -b {builder} {sourcedir} {destdir}" \ ....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def browse(ctx): """Open documentation in web browser."""
page_html = Path(ctx.config.sphinx.destdir)/"html"/"index.html" if not page_html.exists(): build(ctx, builder="html") assert page_html.exists() open_cmd = "open" # -- WORKS ON: MACOSX if sys.platform.startswith("win"): open_cmd = "start" ctx.run("{open} {page_html}".format(ope...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_neighbors(neighbors, coords, I, source_files, f, sides): """Find the tile neighbors based on filenames Parameters neighbors : dict Dictionary that store...
for i, c1 in enumerate(coords): me = source_files[I[i]] # If the left neighbor has already been found... if neighbors[me][sides[0]] != '': continue # could try coords[i:] (+ fixes) for speed if it becomes a problem for j, c2 in enumerate(coords): if 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 set_neighbor_data(self, elev_fn, dem_proc, interp=None): """ From the elevation filename, we can figure out and load the data and done arrays. """
if interp is None: interp = self.build_interpolator(dem_proc) opp = {'top': 'bottom', 'left': 'right'} for key in self.neighbors[elev_fn].keys(): tile = self.neighbors[elev_fn][key] if tile == '': continue oppkey = 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 update_edge_todo(self, elev_fn, dem_proc): """ Can figure out how to update the todo based on the elev filename """
for key in self.edges[elev_fn].keys(): self.edges[elev_fn][key].set_data('todo', data=dem_proc.edge_todo)
<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_edges(self, elev_fn, dem_proc): """ After finishing a calculation, this will update the neighbors and the todo for that tile """
interp = self.build_interpolator(dem_proc) self.update_edge_todo(elev_fn, dem_proc) self.set_neighbor_data(elev_fn, dem_proc, interp)
<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_edge_init_data(self, fn, save_path=None): """ Creates the initialization data from the edge structure """
edge_init_data = {key: self.edges[fn][key].get('data') for key in self.edges[fn].keys()} edge_init_done = {key: self.edges[fn][key].get('done') for key in self.edges[fn].keys()} edge_init_todo = {key: self.edges[fn][key].get('todo') for key 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 find_best_candidate(self, elev_source_files=None): """ Heuristically determines which tile should be recalculated based on updated edge information. Presentl...
self.fill_percent_done() i_b = np.argmax(self.percent_done.values()) if self.percent_done.values()[i_b] <= 0: return None # check for ties I = np.array(self.percent_done.values()) == \ self.percent_done.values()[i_b] if I.sum() == 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 process_command(self, command, save_name='custom', index=None): """ Processes the hillshading Parameters index : int/slice (optional) Default: None - process...
if index is not None: elev_source_files = [self.elev_source_files[index]] else: elev_source_files = self.elev_source_files save_root = os.path.join(self.save_path, save_name) if not os.path.exists(save_root): os.makedirs(save_root) for i, esf...
<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_files(files, name=None): """ Given a list of file paths for elevation files, this function will rename those files to the format required by the pyDEM...
for fil in files: elev_file = GdalReader(file_name=fil) elev, = elev_file.raster_layers fn = get_fn(elev, name) del elev_file del elev fn = os.path.join(os.path.split(fil)[0], fn) os.rename(fil, fn) print "Renamed", fil, "to", fn
<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_fn(fn): """ This parses the file name and returns the coordinates of the tile Parameters fn : str Filename of a GEOTIFF Returns -------- coords = [LLC....
try: parts = os.path.splitext(os.path.split(fn)[-1])[0].replace('o', '.')\ .split('_')[:2] coords = [float(crds) for crds in re.split('[NSEW]', parts[0] + parts[1])[1:]] except: coords = [np.nan] * 4 return 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 get_fn(elev, name=None): """ Determines the standard filename for a given GeoTIFF Layer. Parameters elev : GdalReader.raster_layer A raster layer from the Gd...
gcs = elev.grid_coordinates coords = [gcs.LLC.lat, gcs.LLC.lon, gcs.URC.lat, gcs.URC.lon] return get_fn_from_coords(coords, name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_fn_from_coords(coords, name=None): """ Given a set of coordinates, returns the standard filename. Parameters coords : list [LLC.lat, LLC.lon, URC.lat, UR...
NS1 = ["S", "N"][coords[0] > 0] EW1 = ["W", "E"][coords[1] > 0] NS2 = ["S", "N"][coords[2] > 0] EW2 = ["W", "E"][coords[3] > 0] new_name = "%s%0.3g%s%0.3g_%s%0.3g%s%0.3g" % \ (NS1, coords[0], EW1, coords[1], NS2, coords[2], EW2, coords[3]) if name is not None: new_name += '_' + ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mk_dx_dy_from_geotif_layer(geotif): """ Extracts the change in x and y coordinates from the geotiff file. Presently only supports WGS-84 files. """
ELLIPSOID_MAP = {'WGS84': 'WGS-84'} ellipsoid = ELLIPSOID_MAP[geotif.grid_coordinates.wkt] d = distance(ellipsoid=ellipsoid) dx = geotif.grid_coordinates.x_axis dy = geotif.grid_coordinates.y_axis dX = np.zeros((dy.shape[0]-1)) for j in xrange(len(dX)): dX[j] = d.measure((dy[j+1], 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 mk_geotiff_obj(raster, fn, bands=1, gdal_data_type=gdal.GDT_Float32, lat=[46, 45], lon=[-73, -72]): """ Creates a new geotiff file objects using the WGS84 co...
NNi, NNj = raster.shape driver = gdal.GetDriverByName('GTiff') obj = driver.Create(fn, NNj, NNi, bands, gdal_data_type) pixel_height = -np.abs(lat[0] - lat[1]) / (NNi - 1.0) pixel_width = np.abs(lon[0] - lon[1]) / (NNj - 1.0) obj.SetGeoTransform([lon[0], pixel_width, 0, lat[0], 0, pixel_height]...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sortrows(a, i=0, index_out=False, recurse=True): """ Sorts array "a" by columns i Parameters a : np.ndarray array to be sorted i : int (optional) column to b...
I = np.argsort(a[:, i]) a = a[I, :] # We recursively call sortrows to make sure it is sorted best by every # column if recurse & (len(a[0]) > i + 1): for b in np.unique(a[:, i]): ids = a[:, i] == b colids = range(i) + range(i+1, len(a[0])) a[np.ix_(ids, c...
<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_border_index(I, shape, size): """ Get flattened indices for the border of the region I. Parameters I : np.ndarray(dtype=int) indices in the flattened reg...
J = get_adjacent_index(I, shape, size) # instead of setdiff? # border = np.zeros(size) # border[J] = 1 # border[I] = 0 # J, = np.where(border) return np.setdiff1d(J, 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 get_border_mask(region): """ Get border of the region as a boolean array mask. Parameters region : np.ndarray(shape=(m, n), dtype=bool) mask of the region Re...
# common special case (for efficiency) internal = region[1:-1, 1:-1] if internal.all() and internal.any(): return ~region I, = np.where(region.ravel()) J = get_adjacent_index(I, region.shape, region.size) border = np.zeros(region.size, dtype='bool') border[J] = 1 border[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 get_distance(region, src): """ Compute within-region distances from the src pixels. Parameters region : np.ndarray(shape=(m, n), dtype=bool) mask of the regi...
dmax = float(region.size) d = np.full(region.shape, dmax) d[src] = 0 for n in range(region.size): d_orth = minimum_filter(d, footprint=_ORTH2) + 1 d_diag = minimum_filter(d, (3, 3)) + _SQRT2 d_adj = np.minimum(d_orth[region], d_diag[region]) d[region] = np.minimum(d_adj...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def grow_slice(slc, size): """ Grow a slice object by 1 in each direction without overreaching the list. Parameters slc: slice slice object to grow size: int lis...
return slice(max(0, slc.start-1), min(size, slc.stop+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 is_edge(obj, shape): """ Check if a 2d object is on the edge of the array. Parameters obj : tuple(slice, slice) Pair of slices (e.g. from scipy.ndimage.measu...
if obj[0].start == 0: return True if obj[1].start == 0: return True if obj[0].stop == shape[0]: return True if obj[1].stop == shape[1]: 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 pop_chunk(self, chunk_max_size): """Pops a chunk of the given max size. Optimized to avoid too much string copies. Args: chunk_max_size (int): max size of t...
if self._total_length < chunk_max_size: # fastpath (the whole queue fit in a single chunk) res = self._tobytes() self.clear() return res first_iteration = True while True: try: data = self._deque.popleft() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def absolute(self): """Return an absolute version of this path. This function works even if the path doesn't point to anything. No normalization is done, i.e. al...
# XXX untested yet! if self.is_absolute(): return self # FIXME this must defer to the specific flavour (and, under Windows, # use nt._getfullpathname()) obj = self._from_parts([os.getcwd()] + self._parts, init=False) obj._init(template=self) return ob...
<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_symlink(self): """ Whether this path is a symbolic link. """
try: return S_ISLNK(self.lstat().st_mode) except OSError as e: if e.errno != ENOENT: raise # Path doesn't exist 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 is_block_device(self): """ Whether this path is a block device. """
try: return S_ISBLK(self.stat().st_mode) except OSError as e: if e.errno != ENOENT: raise # Path doesn't exist or is a broken symlink # (see https://bitbucket.org/pitrou/pathlib/issue/12/) 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 is_char_device(self): """ Whether this path is a character device. """
try: return S_ISCHR(self.stat().st_mode) except OSError as e: if e.errno != ENOENT: raise # Path doesn't exist or is a broken symlink # (see https://bitbucket.org/pitrou/pathlib/issue/12/) 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 grid_coords_from_corners(upper_left_corner, lower_right_corner, size): ''' Points are the outer edges of the UL and LR pixels. Size is rows, columns. GC projection type is taken from Points. ''' assert upper_left_corner.wkt == lower_right_corner.wkt geotransform = np.array([upper_left_corner.lon, -(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def intersects(self, other_grid_coordinates): """ returns True if the GC's overlap. """
ogc = other_grid_coordinates # alias # for explanation: http://stackoverflow.com/questions/306316/determine-if-two-rectangles-overlap-each-other # Note the flipped y-coord in this coord system. ax1, ay1, ax2, ay2 = self.ULC.lon, self.ULC.lat, self.LRC.lon, self.LRC.lat bx1, by1...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def raster_to_projection_coords(self, pixel_x, pixel_y): """ Use pixel centers when appropriate. See documentation for the GDAL function GetGeoTransform for deta...
h_px_py = np.array([1, pixel_x, pixel_y]) gt = np.array([[1, 0, 0], self.geotransform[0:3], self.geotransform[3:6]]) arr = np.inner(gt, h_px_py) return arr[2], arr[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 projection_to_raster_coords(self, lat, lon): """ Returns pixel centers. See documentation for the GDAL function GetGeoTransform for details. """
r_px_py = np.array([1, lon, lat]) tg = inv(np.array([[1, 0, 0], self.geotransform[0:3], self.geotransform[3:6]])) return np.inner(tg, r_px_py)[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 reproject_to_grid_coordinates(self, grid_coordinates, interp=gdalconst.GRA_NearestNeighbour): """ Reprojects data in this layer to match that in the GridCoor...
source_dataset = self.grid_coordinates._as_gdal_dataset() dest_dataset = grid_coordinates._as_gdal_dataset() rb = source_dataset.GetRasterBand(1) rb.SetNoDataValue(NO_DATA_VALUE) rb.WriteArray(np.ma.filled(self.raster_data, NO_DATA_VALUE)) gdal.ReprojectImage(source_dat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def inpaint(self): """ Replace masked-out elements in an array using an iterative image inpainting algorithm. """
import inpaint filled = inpaint.replace_nans(np.ma.filled(self.raster_data, np.NAN).astype(np.float32), 3, 0.01, 2) self.raster_data = np.ma.masked_invalid(filled)
<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_connected_client(self): """Gets a connected Client object. If max_size is reached, this method will block until a new client object is available. Returns...
if self.__sem is not None: yield self.__sem.acquire() client = None newly_created, client = self._get_client_from_pool_or_make_it() if newly_created: res = yield client.connect() if not res: LOG.warning("can't connect to %s", client.ti...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connected_client(self): """Returns a ContextManagerFuture to be yielded in a with statement. Returns: A ContextManagerFuture object. Examples: # client is a ...
future = self.get_connected_client() cb = functools.partial(self._connected_client_release_cb, future) return ContextManagerFuture(future, cb)
<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_client(self, client): """Releases a client object to the pool. Args: client: Client object. """
if isinstance(client, Client): if not self._is_expired_client(client): LOG.debug('Client is not expired. Adding back to pool') self.__pool.append(client) elif client.is_connected(): LOG.debug('Client is expired and connected. Disconnecting...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def destroy(self): """Disconnects all pooled client objects."""
while True: try: client = self.__pool.popleft() if isinstance(client, Client): client.disconnect() except IndexError: break
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def select_params_from_section_schema(section_schema, param_class=Param, deep=False): """Selects the parameters of a config section schema. :param section_schema...
# pylint: disable=invalid-name for name, value in inspect.getmembers(section_schema): if name.startswith("__") or value is None: continue # pragma: no cover elif inspect.isclass(value) and deep: # -- CASE: class => SELF-CALL (recursively). # pylint: disabl...
<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_configfile_names(config_files, config_searchpath=None): """Generates all configuration file name combinations to read. .. sourcecode:: # -- ALGORITH...
if config_searchpath is None: config_searchpath = ["."] for config_path in reversed(config_searchpath): for config_basename in reversed(config_files): config_fname = os.path.join(config_path, config_basename) if os.path.isfile(config_fname): # MAYBE: yie...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def matches_section(cls, section_name, supported_section_names=None): """Indicates if this schema can be used for a config section by using the section name. :pa...
if supported_section_names is None: supported_section_names = getattr(cls, "section_names", None) # pylint: disable=invalid-name for supported_section_name_or_pattern in supported_section_names: if fnmatch(section_name, supported_section_name_or_pattern): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cleanup_files(patterns, dry_run=False, workdir="."): """Remove files or files selected by file patterns. Skips removal if file does not exist. :param pattern...
current_dir = Path(workdir) python_basedir = Path(Path(sys.executable).dirname()).joinpath("..").abspath() error_message = None error_count = 0 for file_pattern in patterns: for file_ in path_glob(file_pattern, current_dir): if file_.abspath().startswith(python_basedir): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stack_call(self, *args): """Stacks a redis command inside the object. The syntax is the same than the call() method a Client class. Args: *args: full redis c...
self.pipelined_args.append(args) self.number_of_stacked_calls = self.number_of_stacked_calls + 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 disconnect(self): """Disconnects the object. Safe method (no exception, even if it's already disconnected or if there are some connection errors). """
if not self.is_connected() and not self.is_connecting(): return LOG.debug("disconnecting from %s...", self._redis_server()) self.__periodic_callback.stop() try: self._ioloop.remove_handler(self.__socket_fileno) self._listened_events = 0 except...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def surrogate_escape(error): """ Simulate the Python 3 ``surrogateescape`` handler, but for Python 2 only. """
chars = error.object[error.start:error.end] assert len(chars) == 1 val = ord(chars) val += 0xdc00 return __builtin__.unichr(val), error.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 __gdal_dataset_default(self): """DiskReader implementation."""
if not os.path.exists(self.file_name): return None if os.path.splitext(self.file_name)[1].lower() not in self.file_types: raise RuntimeError('Filename %s does not have extension type %s.' % (self.file_name, self.file_types)) dataset = gdal.OpenShared(self.file_name, gd...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connect(self): """Connects the client object to redis. It's safe to use this method even if you are already connected. Note: this method is useless with auto...
if self.is_connected(): raise tornado.gen.Return(True) cb1 = self._read_callback cb2 = self._close_callback self.__callback_queue = collections.deque() self._reply_list = [] self.__reader = hiredis.Reader(replyError=ClientError) kwargs = self.connecti...
<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_callback(self): """Callback called when redis closed the connection. The callback queue is emptied and we call each callback found with None or with a...
while True: try: callback = self.__callback_queue.popleft() callback(ConnectionError("closed connection")) except IndexError: break if self.subscribed: # pubsub clients self._reply_list.append(ConnectionErro...
<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_callback(self, data=None): """Callback called when some data are read on the socket. The buffer is given to the hiredis parser. If a reply is complete,...
try: if data is not None: self.__reader.feed(data) while True: reply = self.__reader.gets() if reply is not False: try: callback = self.__callback_queue.popleft() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def call(self, *args, **kwargs): """Calls a redis command and returns a Future of the reply. Args: *args: full redis command as variable length argument list or ...
if not self.is_connected(): if self.autoconnect: # We use this method only when we are not contected # to void performance penaly due to gen.coroutine decorator return self._call_with_autoconnect(*args, **kwargs) else: erro...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def async_call(self, *args, **kwargs): """Calls a redis command, waits for the reply and call a callback. Following options are available (not part of the redis ...
def after_autoconnect_callback(future): if self.is_connected(): self._call(*args, **kwargs) else: # FIXME pass if 'callback' not in kwargs: kwargs['callback'] = discard_reply_cb if not self.is_connected(): ...
<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_args_in_redis_protocol(*args): This function makes and returns a string/buffer corresponding to given arguments formated with the redis protocol. inte...
buf = WriteBuffer() l = "*%d\r\n" % len(args) # noqa: E741 if six.PY2: buf.append(l) else: # pragma: no cover buf.append(l.encode('utf-8')) for arg in args: if isinstance(arg, six.text_type): # it's a unicode string in Python2 or a standard (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 _done_callback(self, wrapped): """Internal "done callback" to set the result of the object. The result of the object if forced by the wrapped future. So this...
if wrapped.exception(): self.set_exception(wrapped.exception()) else: self.set_result(wrapped.result())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def result(self): """The result method which returns a context manager Returns: ContextManager: The corresponding context manager """
if self.exception(): raise self.exception() # Otherwise return a context manager that cleans up after the block. @contextlib.contextmanager def f(): try: yield self._wrapped.result() finally: self._exit_callback() ...
<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_url(artist, song): """Create the URL in the LyricWikia format"""
return (__BASE_URL__ + '/wiki/{artist}:{song}'.format(artist=urlize(artist), song=urlize(song)))
<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_lyrics(artist, song, linesep='\n', timeout=None): """Retrieve the lyrics of the song and return the first one in case multiple versions are available."""
return get_all_lyrics(artist, song, linesep, timeout)[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 get_all_lyrics(artist, song, linesep='\n', timeout=None): """Retrieve a list of all the lyrics versions of a song."""
url = create_url(artist, song) response = _requests.get(url, timeout=timeout) soup = _BeautifulSoup(response.content, "html.parser") lyricboxes = soup.findAll('div', {'class': 'lyricbox'}) if not lyricboxes: raise LyricsNotFound('Cannot download lyrics') for lyricbox in lyricboxes: ...
<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_file(name, mode=None, driver=None, libver=None, userblock_size=None, **kwargs): """Open an ARF file, creating as necessary. Use this instead of h5py.Fil...
import sys import os from h5py import h5p from h5py._hl import files try: # If the byte string doesn't match the default # encoding, just pass it on as-is. Note Unicode # objects can always be encoded. name = name.encode(sys.getfilesystemencoding()) except (Uni...
<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_entry(group, name, timestamp, **attributes): """Create a new ARF entry under group, setting required attributes. An entry is an abstract collection of...
# create group using low-level interface to store creation order from h5py import h5p, h5g, _hl try: gcpl = h5p.create(h5p.GROUP_CREATE) gcpl.set_link_creation_order( h5p.CRT_ORDER_TRACKED | h5p.CRT_ORDER_INDEXED) except AttributeError: grp = group.create_group(name)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_dataset(group, name, data, units='', datatype=DataTypes.UNDEFINED, chunks=True, maxshape=None, compression=None, **attributes): """Create an ARF datas...
from numpy import asarray srate = attributes.get('sampling_rate', None) # check data validity before doing anything if not hasattr(data, 'dtype'): data = asarray(data) if data.dtype.kind in ('S', 'O', 'U'): raise ValueError( "data must be in array with numeri...
<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_file_version(file): """Check the ARF version attribute of file for compatibility. Raises DeprecationWarning for backwards-incompatible files, FutureWar...
from distutils.version import StrictVersion as Version try: ver = file.attrs.get('arf_version', None) if ver is None: ver = file.attrs['arf_library_version'] except KeyError: raise UserWarning( "Unable to determine ARF version for {0.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 set_attributes(node, overwrite=True, **attributes): """Set multiple attributes on node. If overwrite is False, and the attribute already exists, does nothing...
aset = node.attrs for k, v in attributes.items(): if not overwrite and k in aset: pass elif v is None: if k in aset: del aset[k] else: aset[k] = 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 keys_by_creation(group): """Returns a sequence of links in group in order of creation. Raises an error if the group was not set to track creation order. """
from h5py import h5 out = [] try: group._id.links.iterate( out.append, idx_type=h5.INDEX_CRT_ORDER, order=h5.ITER_INC) except (AttributeError, RuntimeError): # pre 2.2 shim def f(name): if name.find(b'/', 1) == -1: out.append(name) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_timestamp(obj): """Make an ARF timestamp from an object. Argument can be a datetime.datetime object, a time.struct_time, an integer, a float, or a tu...
import numbers from datetime import datetime from time import mktime, struct_time from numpy import zeros out = zeros(2, dtype='int64') if isinstance(obj, datetime): out[0] = mktime(obj.timetuple()) out[1] = obj.microsecond elif isinstance(obj, struct_time): out[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 set_uuid(obj, uuid=None): """Set the uuid attribute of an HDF5 object. Use this method to ensure correct dtype """
from uuid import uuid4, UUID if uuid is None: uuid = uuid4() elif isinstance(uuid, bytes): if len(uuid) == 16: uuid = UUID(bytes=uuid) else: uuid = UUID(hex=uuid) if "uuid" in obj.attrs: del obj.attrs["uuid"] obj.attrs.create("uuid", str(uuid...
<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_uuid(obj): """Return the uuid for obj, or null uuid if none is set"""
# TODO: deprecate null uuid ret val from uuid import UUID try: uuid = obj.attrs['uuid'] except KeyError: return UUID(int=0) # convert to unicode for python 3 try: uuid = uuid.decode('ascii') except (LookupError, AttributeError): pass return UUID(uuid)
<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_children(obj, type=None): """Return the number of children of obj, optionally restricting by class"""
if type is None: return len(obj) else: # there doesn't appear to be any hdf5 function for getting this # information without inspecting each child, which makes this somewhat # slow return sum(1 for x in obj if obj.get(x, getclass=True) is type)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _todict(cls): """ generate a dict keyed by value """
return dict((getattr(cls, attr), attr) for attr in dir(cls) if not attr.startswith('_'))
<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_singularity_images(image_paths1, image_paths2=None): '''compare_singularity_images is a wrapper for compare_containers to compare singularity containers. If image_paths2 is not defined, pairwise comparison is done with image_paths1 ''' repeat = False if image_paths2 is None: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_image_hashes(image_path, version=None, levels=None): '''get_image_hashes returns the hash for an image across all levels. This is the quickest, easiest way to define a container's reproducibility on each level. ''' if levels is None: levels = get_levels(version=version) hashes = dict...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def add_node(node, parent): '''add_node will add a node to it's parent ''' newNode = dict(node_id=node.id, children=[]) parent["children"].append(newNode) if node.left: add_node(node.left, newNode) if node.right: add_node(node.right, newNode)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def file_counts(container=None, patterns=None, image_package=None, file_list=None): '''file counts will return a list of files that match one or more regular expressions. if no patterns is defined, a default of readme is used. All patterns and files are made ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def include_file(member,file_filter): '''include_file will look at a path and determine if it matches a regular expression from a level ''' member_path = member.name.replace('.','',1) if len(member_path) == 0: return False # Does the filter skip it explicitly? if "skip_files" in 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 assess_content(member,file_filter): '''Determine if the filter wants the file to be read for content. In the case of yes, we would then want to add the content to the hash and not the file object. ''' member_path = member.name.replace('.','',1) if len(member_path) == 0: 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 get_level(level,version=None,include_files=None,skip_files=None): '''get_level returns a single level, with option to customize files added and skipped. ''' levels = get_levels(version=version) level_names = list(levels.keys()) if level.upper() in level_names: level = levels[level]...
<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_levels_set(levels): '''make set efficient will convert all lists of items in levels to a set to speed up operations''' for level_key,level_filters in levels.items(): levels[level_key] = make_level_set(level_filters) return levels
<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_level_set(level): '''make level set will convert one level into a set''' new_level = dict() for key,value in level.items(): if isinstance(value,list): new_level[key] = set(value) else: new_level[key] = value return new_level
<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_guts(image_path, tar, file_filter=None, tag_root=True, include_sizes=True): '''extract the file guts from an in memory tarfile. The file is not closed. This should not be done for large images. ''' if file_filter is None...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_memory_tar(image_path): '''get an in memory tar of an image. Use carefully, not as reliable as get_image_tar ''' byte_array = Client.image.export(image_path) file_object = io.BytesIO(byte_array) tar = tarfile.open(mode="r|*", fileobj=file_object) return (file_object,tar)