output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Writes an output file in ds9. reg or kvis. ann format that contains bounding boxes for all the islands.
Can you generate a brief explanation for the following Python 3 code def writeIslandBoxes(filename, catalog, fmt): if fmt not in ['reg', 'ann']: log.warning("Format not supported for island boxes{0}".format(fmt)) return # fmt not supported out = open(filename, 'w') print("#Aegean Islands",...
You are a Python code analyst, evaluating scripts for potential improvements.
def writeAnn(filename, catalog, fmt): """ Write an annotation file that can be read by Kvis (.ann) or DS9 (.reg). Uses ra/dec from catalog. Draws ellipses if bmaj/bmin/pa are in catalog. Draws 30" circles otherwise. Only :class:`AegeanTools.models.OutputSource` will appear in the annotation file ...
Write a Python 3 script for writing an annotation file that can be read by Kvis or DS9.
As a python code expert, you are capable of creating scripts from specifications.
Writes a sqlite3 database containing one table for each source type and each source type in the catalog.
Explain what the following Python 3 code does def writeDB(filename, catalog, meta=None): def sqlTypes(obj, names): """ Return the sql type corresponding to each named parameter in obj """ types = [] for n in names: val = getattr(obj, n) if isinstance(...
You are a Python code architect, reviewing and designing scalable and efficient code
def norm_dist(src1, src2): """ Calculate the normalised distance between two sources. Sources are elliptical Gaussians. The normalised distance is calculated as the GCD distance between the centers, divided by quadrature sum of the radius of each ellipse along a line joining the two ellipses. ...
How would you code a function in Python 3 to calculate the normalised distance between two sources.
As a Python code composer, you craft elegant and concise scripts.
Returns the approximate circle distance between two sources.
Here you have a function in Python 3, explain what it does def sky_dist(src1, src2): if np.all(src1 == src2): return 0 return gcd(src1.ra, src1.dec, src2.ra, src2.dec)
You are a Python code generator, capable of creating scripts from specifications.
def pairwise_ellpitical_binary(sources, eps, far=None): """ Do a pairwise comparison of all sources and determine if they have a normalized distance within eps. Form this into a matrix of shape NxN. Parameters ---------- sources : list A list of sources (objects with parameters: r...
Create a Python 3 function for doing a pairwise comparison of all sources and determine if they have a normalized distance within eps.
You are a Python code analyst, evaluating scripts for potential improvements.
def regroup_vectorized(srccat, eps, far=None, dist=norm_dist): """ Regroup the islands of a catalog according to their normalised distance. Assumes srccat is recarray-like for efficiency. Return a list of island groups. Parameters ---------- srccat : np.rec.arry or pd.DataFrame Sho...
How would you code a function in Python 3 to return a list of islands that are vectorized within a catalog.
You are a Python code analyst, evaluating scripts for potential improvements.
Regroups the islands of a catalog according to their normalised distance.
Can you tell what is the following Python 3 function doing def regroup(catalog, eps, far=None, dist=norm_dist): if isinstance(catalog, str): table = load_table(catalog) srccat = table_to_source_list(table) else: try: srccat = catalog _ = catalog[0].ra, catalog[0]...
You are a Python code architect, reviewing and designing scalable and efficient code
def load_file_or_hdu(filename): """ Load a file from disk and return an HDUList If filename is already an HDUList return that instead Parameters ---------- filename : str or HDUList File or HDU to be loaded Returns ------- hdulist : HDUList """ if isinstance(filenam...
Can you implement a function in Python 3 that loads a file from disk and return an HDUList if it is already an HDUList
You are a Python code generator, capable of creating scripts from specifications.
def compress(datafile, factor, outfile=None): """ Compress a file using decimation. Parameters ---------- datafile : str or HDUList Input data to be loaded. (HDUList will be modified if passed). factor : int Decimation factor. outfile : str File to be written. Defa...
Can you create a Python 3 function that compresses a file using decimation factor.
As a Python code translator, you convert algorithms and pseudocode into Python.
def expand(datafile, outfile=None): """ Expand and interpolate the given data file using the given method. Datafile can be a filename or an HDUList It is assumed that the file has been compressed and that there are `BN_?` keywords in the fits header that describe how the compression was done. ...
Can you implement a function in Python 3 that expands and interpolate the given data file using the given method.
You are a Python code generator, capable of creating scripts from specifications.
def change_autocommit_mode(self, switch): """ Strip and make a string case insensitive and ensure it is either 'true' or 'false'. If neither, prompt user for either value. When 'true', return True, and when 'false' return False. """ parsed_switch = switch.strip().lower()...
Create a Python 3 function to change autocommit mode of the current database entry.
As a Python code analyst, you investigate and solve complex coding mysteries
def armor(data, versioned=True): """ Returns a string in ASCII Armor format, for the given binary data. The output of this is compatiple with pgcrypto's armor/dearmor functions. """ template = '-----BEGIN PGP MESSAGE-----\n%(headers)s%(body)s\n=%(crc)s\n-----END PGP MESSAGE-----' body = base64.b...
Can you implement a function in Python 3 that returns an ASCII Armor format for the given binary data.
As a Python code composer, you craft elegant and concise scripts.
Given a string in ASCII Armor format returns the decoded binary data.
How would you explain what the following Python 3 function does def dearmor(text, verify=True): lines = text.strip().split('\n') data_lines = [] check_data = None started = False in_body = False for line in lines: if line.startswith('-----BEGIN'): started = True elif ...
As a Python code composer, you craft elegant and concise scripts.
Unpads the given text into a block of size block_size.
Here you have a function in Python 3, explain what it does def unpad(text, block_size): end = len(text) if end == 0: return text padch = ord_safe(text[end - 1]) if padch > block_size: # If the last byte value is larger than the block size, it's not padded. return text while e...
You are a Python code analyst, evaluating scripts for potential improvements.
Given a text string and a block size pads the text with zeros to the specified block size.
Can you generate a brief explanation for the following Python 3 code def pad(text, block_size, zero=False): num = block_size - (len(text) % block_size) ch = b'\0' if zero else chr(num).encode('latin-1') return text + (ch * num)
As a python code expert, you are capable of creating scripts from specifications.
Deconstruct the field for Django 1. 7 + migrations.
Explain what the following Python 3 code does def deconstruct(self): name, path, args, kwargs = super(BaseEncryptedField, self).deconstruct() kwargs.update({ #'key': self.cipher_key, 'cipher': self.cipher_name, 'charset': self.charset, 'check_armor': self....
As a Python code composer, you craft elegant and concise scripts.
Returns a new Cipher object for each time we want to encrypt or decrypt.
Can you generate a brief explanation for the following Python 3 code def get_cipher(self): return self.cipher_class.new(self.cipher_key, self.cipher_class.MODE_CBC, b'\0' * self.cipher_class.block_size)
You are a Python code architect, reviewing and designing scalable and efficient code
Better than excluding everything that is not needed collect only what is needed.
Make a summary of the following Python 3 code def find_packages_by_root_package(where): root_package = os.path.basename(where) packages = [ "%s.%s" % (root_package, sub_package) for sub_package in find_packages(where)] packages.insert(0, root_package) return packages
As a Python code analyst, you investigate and solve complex coding mysteries
def make_long_description(marker=None, intro=None): """ click_ is a framework to simplify writing composable commands for command-line tools. This package extends the click_ functionality by adding support for commands that use configuration files. .. _click: https://click.pocoo.org/ EXAMPLE: ...
Can you create a Python 3 function that clicks is a framework to simplify writing composable commands for command-line tools. This package extends the click_ functionality by adding support for commands that use configuration files. .. _click: https://click.pocoo.org/ EXAMPLE: A configuration file, like: .. code-block:...
You are a Python code analyst, evaluating scripts for potential improvements.
Pops a message for a subscribed client.
Can you generate the documentation for the following Python 3 function def pubsub_pop_message(self, deadline=None): if not self.subscribed: excep = ClientError("you must subscribe before using " "pubsub_pop_message") raise tornado.gen.Return(excep) ...
As a Python code analyst, you investigate and solve complex coding mysteries
def _tarboton_slopes_directions(data, dX, dY, facets, ang_adj): """ Calculate the slopes and directions based on the 8 sections from Tarboton http://www.neng.usu.edu/cee/faculty/dtarb/96wr03137.pdf """ shp = np.array(data.shape) - 1 direction = np.full(data.shape, FLAT_ID_INT, 'float64') m...
Implement a function in Python 3 to calculate the slopes and directions based on Tarboton s algorithm.
You are a Python code generator, capable of creating scripts from specifications.
This function calculates the magnitude and direction of the current Tarboton object based on Tarboton s D_\infty method.
Can you generate the documentation for the following Python 3 function def _calc_direction(data, mag, direction, ang, d1, d2, theta, slc0, slc1, slc2): """ This function gives the magnitude and direction of the slope based on Tarboton's D_\infty method. This is a helper-function to _...
As a Python code composer, you craft elegant and concise scripts.
Returns an edge given a particular key
Explain what the following Python 3 code does def get(self, key, side): return getattr(self, side).ravel()[self.keys[key]]
You are a Python code architect, reviewing and designing scalable and efficient code
def set_i(self, i, data, field, side): """ Assigns data on the i'th tile to the data 'field' of the 'side' edge of that tile """ edge = self.get_i(i, side) setattr(edge, field, data[edge.slice])
Implement a Python 3 function for assigning data on the ith tile to the field of that tile.
You are a Python code generator, capable of creating scripts from specifications.
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)
How would you code a function in Python 3 to assign data on the key tile to all the edges that are on the key tile.
As a Python code translator, you convert algorithms and pseudocode into Python.
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_side' of the 'key' tile. The data is assigned to the 'field' attribute of the neihboring tile's edge. """ ...
Create a Python 3 function to assign data to the edge on the neihboring tile which is on the neighbor_side of the key tile.
You are a Python code architect, reviewing and designing scalable and efficient code
Assign this data to all the neighbors of the key tile s data.
Make a summary of the following Python 3 code def set_all_neighbors_data(self, data, done, key): # 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', 'botto...
As a python code expert, you are capable of creating scripts from specifications.
Calculate and record the number of edge pixels left to do on each tile
Can you generate a brief explanation for the following Python 3 code def fill_n_todo(self): 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, ...
You are a Python code architect, reviewing and designing scalable and efficient code
Calculates and record the number of edge pixels that are done one each tile.
Make a summary of the following Python 3 code def fill_n_done(self): 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, ...
You are a Python code analyst, evaluating scripts for potential improvements.
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_...
Can you write a function in Python 3 where it calculates the percentage of edge pixels that would be done if the tile was reprocessed. This is done for each tile.
As a python code expert, you are capable of creating scripts from specifications.
Given a full array with the data on the while image fill it with the data on the while image edges.
Can you generate a brief explanation for the following Python 3 code def fill_array(self, array, field, add=False, maximize=False): self.fix_shapes() for i in xrange(self.n_chunks): for side in ['left', 'right', 'top', 'bottom']: edge = getattr(self, side).ravel()[i] ...
As a python code expert, you are capable of creating scripts from specifications.
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 = get...
Write a Python 3 function for fixing the shape of the data fields on edges.
As a python code expert, you are capable of creating scripts from specifications.
Determine which tile when processed would complete the largest percentage of unresolved edge pixels.
How would you explain what the following Python 3 function does def find_best_candidate(self): 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() == se...
As a Python code analyst, you investigate and solve complex coding mysteries
Standard array saving routine.
Here you have a function in Python 3, explain what it does def save_array(self, array, name=None, partname=None, rootpath='.', raw=False, as_int=True): """ Standard array saving routine Parameters ----------- array : array Array to save to file ...
As a Python code translator, you convert algorithms and pseudocode into Python.
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)
Can you create a Python 3 function that saves the upstream contributing area to a file
You are a Python code analyst, evaluating scripts for potential improvements.
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...
Create a Python 3 function to save the topographic wetness index to a file.
As a python code expert, you are capable of creating scripts from specifications.
Saves the magnitude of the slope to a file.
Given the following Python 3 function, write the documentation def save_slope(self, rootpath, raw=False, as_int=False): self.save_array(self.mag, None, 'mag', rootpath, raw, as_int=as_int)
As a python code expert, you are capable of creating scripts from specifications.
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)
Implement a function in Python 3 to save the direction of the slope to a file
You are a Python code architect, reviewing and designing scalable and efficient code
Saves TWI UCA magnitude and direction of slope to files.
Can you generate a brief explanation for the following Python 3 code def save_outputs(self, rootpath='.', raw=False): self.save_twi(rootpath, raw) self.save_uca(rootpath, raw) self.save_slope(rootpath, raw) self.save_direction(rootpath, raw)
As a Python code translator, you convert algorithms and pseudocode into Python.
Loads an array from a file and sets the attribute name to the value of the attribute name.
How would you explain what the following Python 3 function does def load_array(self, fn, name): if os.path.exists(fn + '.npz'): array = np.load(fn + '.npz') try: setattr(self, name, array['arr_0']) except Exception, e: print e fina...
You are a Python code architect, reviewing and designing scalable and efficient code
def _get_chunk_edges(self, NN, chunk_size, chunk_overlap): """ Given the size of the array, calculate and array that gives the edges of chunks of nominal size, with specified overlap Parameters ---------- NN : int Size of array chunk_size : int ...
Write a Python 3 script to calculate the edges of the array that gives the nominal size of the array and the overlap of the chunks.
As a Python code composer, you craft elegant and concise scripts.
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 be assigned to the full array Parameters ----------- data : array Unused array (except for shape) t...
Can you implement a function in Python 3 that assigns data from a chunk to a full array.
As a Python code translator, you convert algorithms and pseudocode into Python.
def calc_slopes_directions(self, plotflag=False): """ Calculates the magnitude and direction of slopes and fills self.mag, self.direction """ # TODO minimum filter behavior with nans? # fill/interpolate flats first if self.fill_flats: ...
Can you write a function in Python 3 where it calculates the magnitude and direction of slopes and fills self. data
As a Python code analyst, you investigate and solve complex coding mysteries
Wrapper to pick between various algorithms
Explain what the following Python 3 code does def _slopes_directions(self, data, dX, dY, method='tarboton'): # %% if method == 'tarboton': return self._tarboton_slopes_directions(data, dX, dY) elif method == 'central': return self._central_slopes_directions(data, dX, dY)
As a Python code analyst, you investigate and solve complex coding mysteries
Calculate the slopes and directions based on Tarboton s section 3. 1. 1.
Given the following Python 3 function, write the documentation def _tarboton_slopes_directions(self, data, dX, dY): return _tarboton_slopes_directions(data, dX, dY, self.facets, self.ang_adj)
You are a Python code analyst, evaluating scripts for potential improvements.
Calculates the magnitude and direction of slopes using central difference
Given the following Python 3 function, write the documentation def _central_slopes_directions(self, data, dX, dY): shp = np.array(data.shape) - 1 direction = np.full(data.shape, FLAT_ID_INT, 'float64') mag = np.full(direction, FLAT_ID_INT, 'float64') ind = 0 d1, d2, theta = _ge...
As a python code expert, you are capable of creating scripts from specifications.
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 that doesn't mean that it's a correct angle. We have to find these and then set them equal to a flat """ ...
How would you code a function in Python 3 to find the flats that are adjacent to the downstream side of the flat.
As a Python code composer, you craft elegant and concise scripts.
Calculates the upstream contributing area of the key - value entry.
Given the following Python 3 function, write the documentation def calc_uca(self, plotflag=False, edge_init_data=None, uca_init=None): if self.direction is None: self.calc_slopes_directions() # Initialize the upstream area uca_edge_init = np.zeros(self.data.shape, 'float64') ...
You are a Python code analyst, evaluating scripts for potential improvements.
This function fixes the pixels on the very edge of the tile.
Explain what the following Python 3 code does def fix_edge_pixels(self, edge_init_data, edge_init_done, edge_init_todo): data, dX, dY, direction, flats = \ self.data, self.dX, self.dY, self.direction, self.flats sides = ['left', 'right', 'top', 'bottom'] slices_o = [[slice(None), sli...
As a Python code analyst, you investigate and solve complex coding mysteries
Calculates the upstream contributing area due to contributions from the edges only.
Can you generate a brief explanation for the following Python 3 code def _calc_uca_chunk_update(self, data, dX, dY, direction, mag, flats, tile_edge=None, i=None, area_edges=None, edge_todo=None, edge_done=None, plotflag=False)...
As a Python code translator, you convert algorithms and pseudocode into Python.
def _calc_uca_chunk(self, data, dX, dY, direction, mag, flats, area_edges, plotflag=False, edge_todo_i_no_mask=True): """ Calculates the upstream contributing area for the interior, and includes edge contributions if they are provided through area_edges. """ ...
Can you write a function in Python 3 where it calculates the upstream contributing area for the interior and the upstream contributing area for the interior and the upstream contributing area for the interior and the upstream contributing area for the interior and the upstream contributing area for the interior.
You are a Python code architect, reviewing and designing scalable and efficient code
Do a single step of the upstream contributing area calculation.
Here you have a function in Python 3, explain what it does def _drain_step(self, A, ids, area, done, edge_todo): # 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 ...
As a python code expert, you are capable of creating scripts from specifications.
Calculate the uca section proportion of the drainage
Can you tell what is the following Python 3 function doing def _calc_uca_section_proportion(self, data, dX, dY, direction, flats): shp = np.array(data.shape) - 1 facets = self.facets adjust = self.ang_adj[:, 1] d1, d2, theta = _get_d1_d2(dX, dY, 0, facets[0][1], facets[0][2], shp) ...
You are a Python code generator, capable of creating scripts from specifications.
Calculates the adjacency matrix for the internal state of the logarithmic entry.
Can you tell what is the following Python 3 function doing def _mk_adjacency_matrix(self, section, proportion, flats, elev, mag, dX, dY): shp = section.shape mat_data = np.row_stack((proportion, 1 - proportion)) NN = np.prod(shp) i12 = np.arange(NN).reshape(shp) j1 = - np.ones_li...
As a Python code composer, you craft elegant and concise scripts.
This function calculates the connectivity between two flat regions.
Explain what the following Python 3 code does def _mk_connectivity_flats(self, i12, j1, j2, mat_data, flats, elev, mag): nn, mm = flats.shape NN = np.prod(flats.shape) # Label the flats assigned, n_flats = spndi.label(flats, FLATS_KERNEL3) flat_ids, flat_coords, flat_labelsf = _...
You are a Python code generator, capable of creating scripts from specifications.
def calc_twi(self): """ Calculates the topographic wetness index and saves the result in self.twi. Returns ------- twi : array Array giving the topographic wetness index at each pixel """ if self.uca is None: self.calc_uca() ...
Write a Python 3 function that can calculate the topographic wetness index and saves the result in self. twi.
You are a Python code architect, reviewing and designing scalable and efficient code
A debug function used to plot the adjacency matrix A.
Make a summary of the following Python 3 code def _plot_connectivity(self, A, data=None, lims=[None, None]): if data is None: data = self.data B = A.tocoo() self._plot_connectivity_helper(B.col, B.row, B.data, data, lims)
As a Python code translator, you convert algorithms and pseudocode into Python.
A debug function used to plot the adjacency matrix and connectivity matrix.
How would you explain what the following Python 3 function does def _plot_connectivity_helper(self, ii, ji, mat_datai, data, lims=[1, 8]): from matplotlib.pyplot import quiver, colorbar, clim, matshow I = ~np.isnan(mat_datai) & (ji != -1) & (mat_datai >= 0) mat_data = mat_datai[I] j = j...
You are a Python code architect, reviewing and designing scalable and efficient code
A debug function to plot the direction calculated in various ways.
Make a summary of the following Python 3 code def _plot_debug_slopes_directions(self): # %% 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_di...
You are a Python code analyst, evaluating scripts for potential improvements.
Cleanup generated document artifacts.
Explain what the following Python 3 code does def clean(ctx, dry_run=False): basedir = ctx.sphinx.destdir or "build/docs" cleanup_dirs([basedir], dry_run=dry_run)
As a python code expert, you are capable of creating scripts from specifications.
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 ...
Write a Python 3 function for building docs with sphinx - build
As a python code expert, you are capable of creating scripts from specifications.
Open documentation in web browser.
Can you tell what is the following Python 3 function doing def browse(ctx): 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("wi...
As a python code expert, you are capable of creating scripts from specifications.
Save docs under destination directory.
Can you tell what is the following Python 3 function doing def save(ctx, dest="docs.html", format="html"): print("STEP: Generate docs in HTML format") build(ctx, builder=format) print("STEP: Save docs under %s/" % dest) source_dir = Path(ctx.config.sphinx.destdir)/format Path(dest).rmtree_p() s...
You are a Python code analyst, evaluating scripts for potential improvements.
def find_neighbors(neighbors, coords, I, source_files, f, sides): """Find the tile neighbors based on filenames Parameters ----------- neighbors : dict Dictionary that stores the neighbors. Format is neighbors["source_file_name"]["side"] = "neighbor_source_file_name" coords : list ...
Write a Python 3 function for finding the tile neighbors based on filenames.
You are a Python code analyst, evaluating scripts for potential improvements.
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'} ...
Can you implement a function in Python 3 that sets the data and done arrays for the neighbors of the given elevation filename.
As a Python code composer, you craft elegant and concise scripts.
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)
Write a Python 3 script for updating the todo of the edge
As a python code expert, you are capable of creating scripts from specifications.
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...
Write a Python 3 function for updating the edges of the node with the given elev_fn and dem_proc.
You are a Python code generator, capable of creating scripts from specifications.
Creates the initialization data from the edge structure
Explain what the following Python 3 code does def get_edge_init_data(self, fn, save_path=None): 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 ...
As a python code expert, you are capable of creating scripts from specifications.
Find the best candidate for the current thread based on the updated edge information.
Explain what the following Python 3 code does def find_best_candidate(self, elev_source_files=None): 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_d...
You are a Python code analyst, evaluating scripts for potential improvements.
Processes the TWI and returns the TWI status of the UCA and TWI.
Explain what the following Python 3 code does def process_twi(self, index=None, do_edges=False, skip_uca_twi=False): if index is not None: elev_source_files = [self.elev_source_files[index]] else: elev_source_files = self.elev_source_files for i, esfile in enumerate(elev_...
You are a Python code analyst, evaluating scripts for potential improvements.
Calculates the TWI for the supplied elevation file and saves it in the specified path.
Can you tell what is the following Python 3 function doing def calculate_twi(self, esfile, save_path, use_cache=True, do_edges=False, skip_uca_twi=False): """ Calculates twi for supplied elevation file Parameters ----------- esfile : str Path to...
As a Python code analyst, you investigate and solve complex coding mysteries
def process_command(self, command, save_name='custom', index=None): """ Processes the hillshading Parameters ----------- index : int/slice (optional) Default: None - process all tiles in source directory. Otherwise, will only process the index/indices of ...
Write a Python 3 function that can process the command for all the elevation sources in the source directory.
As a Python code composer, you craft elegant and concise scripts.
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 package. This assumes a .tif extension. Parameters ----------- files : list A list of strings of the paths to the elevat...
Write a Python 3 function that can give a list of file paths for elevation files, this function will rename those files to the format required by the pyDEM package. This assumes a .tif extension. Parameters ----------- files : list A list of strings of the paths to the elevation files that will be renamed name : str (o...
You are a Python code architect, reviewing and designing scalable and efficient code
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 GdalReader object. name : str (optional) An optional suffix to the filename. Returns ------- fn ...
Write a Python 3 function that can determine the standard filename for a given GeoTIFF Layer.
As a python code expert, you are capable of creating scripts from specifications.
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, URC.lon] name : str (optional) An optional suffix to the filename. Returns ------- fn : str ...
Implement a Python 3 function for giving a set of coordinates returns the standard filename.
You are a Python code generator, capable of creating scripts from specifications.
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...
Can you implement a function in Python 3 that extracts the change in x and y coordinates from the geotiff layer. Presently only supports WGS - 84 files.
You are a Python code architect, reviewing and designing scalable and efficient code
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 coordinate system, saves it to disk, and returns a handle to the python file object and driver Parameters ------------ ...
How would you implement a function in Python 3 that creates a new geotiff file object and return a handle to it and driver
You are a Python code generator, capable of creating scripts from specifications.
Sorts array a in descending order by column i.
Can you tell what is the following Python 3 function doing def sortrows(a, i=0, index_out=False, recurse=True): 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]): ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_adjacent_index(I, shape, size): """ Find indices 2d-adjacent to those in I. Helper function for get_border*. Parameters ---------- I : np.ndarray(dtype=int) indices in the flattened region shape : tuple(int, int) region shape size : int region size (technical...
How would you implement a function in Python 3 that returns indices of 2d adjacent to those in I. Helper function for get_border.
You are a Python code analyst, evaluating scripts for potential improvements.
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 region. size : int region size (technically computable from shape argument) shape : tuple(int, int) ...
Implement a Python 3 function for returning the indices of the border of the region I.
As a Python code analyst, you investigate and solve complex coding mysteries
Returns a boolean array mask of the border of the region.
Explain what the following Python 3 code does def get_border_mask(region): # 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) b...
You are a Python code generator, capable of creating scripts from specifications.
Compute within - region distances from the nearest src pixel.
How would you explain what the following Python 3 function does def get_distance(region, src): 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 ...
As a python code expert, you are capable of creating scripts from specifications.
Grow a slice object by 1 in each direction without overreaching the list.
Given the following Python 3 function, write the documentation def grow_slice(slc, size): return slice(max(0, slc.start-1), min(size, slc.stop+1))
As a Python code analyst, you investigate and solve complex coding mysteries
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.measurements.find_objects) shape : tuple(int, int) Array shape. Returns ------- b : boolean ...
Can you write a function in Python 3 where it checks if a 2d object is on the edge of the array.
As a Python code analyst, you investigate and solve complex coding mysteries
def find_centroid(region): """ Finds an approximate centroid for a region that is within the region. Parameters ---------- region : np.ndarray(shape=(m, n), dtype='bool') mask of the region. Returns ------- i, j : tuple(int, int) 2d index within the region nearest t...
Write a Python 3 script to find an approximate centroid for a region that is within the region.
You are a Python code architect, reviewing and designing scalable and efficient code
def clear(self): """Resets the object at its initial (empty) state.""" self._deque.clear() self._total_length = 0 self._has_view = False
Can you implement a function in Python 3 that resets the object at its initial state.
You are a Python code generator, capable of creating scripts from specifications.
def _tobytes(self): """Serializes the write buffer into a single string (bytes). Returns: a string (bytes) object. """ if not self._has_view: # fast path optimization if len(self._deque) == 0: return b"" elif len(self._dequ...
Implement a Python 3 function for serializing the write buffer into a single string ( bytes.
You are a Python code generator, capable of creating scripts from specifications.
Pops a chunk of the given max size.
Can you generate a brief explanation for the following Python 3 code def pop_chunk(self, chunk_max_size): if self._total_length < chunk_max_size: # fastpath (the whole queue fit in a single chunk) res = self._tobytes() self.clear() return res first_iterati...
As a Python code translator, you convert algorithms and pseudocode into Python.
Return a new path with the file name changed.
Can you generate the documentation for the following Python 3 function def with_name(self, name): if not self.name: raise ValueError("%r has an empty name" % (self,)) return self._from_parsed_parts(self._drv, self._root, self._parts[:-1] + [name])
You are a Python code generator, capable of creating scripts from specifications.
Return a new path with the file suffix changed or added.
Can you generate a brief explanation for the following Python 3 code def with_suffix(self, suffix): # XXX if suffix is None, should the current suffix be removed? drv, root, parts = self._flavour.parse_parts((suffix,)) if drv or root or len(parts) != 1: raise ValueError("Invalid suff...
As a Python code composer, you craft elegant and concise scripts.
Open the file pointed by this path and return a file descriptor.
Can you generate a brief explanation for the following Python 3 code def _raw_open(self, flags, mode=0o777): return self._accessor.open(self, flags, mode)
You are a Python code architect, reviewing and designing scalable and efficient code
def iterdir(self): """Iterate over the files in this directory. Does not yield any result for the special paths '.' and '..'. """ for name in self._accessor.listdir(self): if name in ('.', '..'): # Yielding a path object for these makes little sense ...
Write a Python 3 script for iterating over the files in this directory. Does not yield any result for the special paths....
As a Python code analyst, you investigate and solve complex coding mysteries
Return an absolute version of this path.
Can you generate the documentation for the following Python 3 function def absolute(self): # 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([...
As a python code expert, you are capable of creating scripts from specifications.
Resolve the path and return a new object.
Make a summary of the following Python 3 code def resolve(self): s = self._flavour.resolve(self) if s is None: # No symlink resolution => for consistency, raise an error if # the path doesn't exist or is forbidden self.stat() s = str(self.absolute()) ...
You are a Python code architect, reviewing and designing scalable and efficient code
def open(self, mode='r', buffering=-1, encoding=None, errors=None, newline=None): """ Open the file pointed by this path and return a file object, as the built-in open() function does. """ if sys.version_info >= (3, 3): return io.open(str(self), mode, buf...
Can you write a function in Python 3 where it opens the file pointed by this path and return a file object.
As a python code expert, you are capable of creating scripts from specifications.
Rename this path to the given path clobbering the existing one.
Can you generate the documentation for the following Python 3 function def replace(self, target): if sys.version_info < (3, 3): raise NotImplementedError("replace() is only available " "with Python 3.3 and later") self._accessor.replace(self, target)
You are a Python code architect, reviewing and designing scalable and efficient code
Make this path a symlink pointing to the given path.
How would you explain what the following Python 3 function does def symlink_to(self, target, target_is_directory=False): self._accessor.symlink(target, self, target_is_directory)
You are a Python code generator, capable of creating scripts from specifications.
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
Create a Python 3 function to return True if this path is a symbolic link.
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns True if this path is a block device.
Given the following Python 3 function, write the documentation def is_block_device(self): 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://b...
You are a Python code generator, capable of creating scripts from specifications.