output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Load CSV file from path and yield CSV rows
Make a summary of the following Python 3 code def load_csv(path, delimiter=','): try: with open(path, 'rb') as csvfile: reader = DictReader(csvfile, delimiter=delimiter) for row in reader: yield row except (OSError, IOError): raise ClientException("File no...
You are a Python code architect, reviewing and designing scalable and efficient code
def load_json(path): """ Load JSON file from path :param path: file path :return: A Python object (e.g. a dict) """ try: with open(path, 'r') as json_file: return json.load(json_file) except (OSError, IOError): raise ClientException("File not found: {}".format(pat...
Can you write a function in Python 3 where it loads a JSON file from path
As a Python code composer, you craft elegant and concise scripts.
Yield partitions of a payload by a threshold
Make a summary of the following Python 3 code def partition_payload(data, key, thresh): data = data[key] for i in range(0, len(data), thresh): yield {key: data[i:i + thresh]}
As a Python code translator, you convert algorithms and pseudocode into Python.
Search filename in DHIS_HOME or user s home folder and return full path of the file
Can you tell what is the following Python 3 function doing def search_auth_file(filename='dish.json'): if 'DHIS_HOME' in os.environ: return os.path.join(os.environ['DHIS_HOME'], filename) else: home_path = os.path.expanduser(os.path.join('~')) for root, dirs, files in os.walk(home_path):...
You are a Python code generator, capable of creating scripts from specifications.
Convert version info to integer
Here you have a function in Python 3, explain what it does def version_to_int(value): # remove '-SNAPSHOT' value = value.replace('-SNAPSHOT', '') # remove '-RCx' if '-RC' in value: value = value.split('-RC', 1)[0] try: return int(value.split('.')[1]) except (ValueError, IndexErro...
You are a Python code analyst, evaluating scripts for potential improvements.
Create DHIS2 UID matching to Regex ^[A-Za-z][A-Za-z0-9]{10}$ :return: UID string
Can you generate a brief explanation for the following Python 3 code def generate_uid(): # first must be a letter first = random.choice(string.ascii_letters) # rest must be letters or numbers rest = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(10)) return first + rest
As a Python code translator, you convert algorithms and pseudocode into Python.
Check if the given UID is a valid DHIS2 UID.
Make a summary of the following Python 3 code def is_valid_uid(uid): pattern = r'^[A-Za-z][A-Za-z0-9]{10}$' if not isinstance(uid, string_types): return False return bool(re.compile(pattern).match(uid))
As a Python code translator, you convert algorithms and pseudocode into Python.
Print JSON with indentation and colours
Given the following Python 3 function, write the documentation def pretty_json(obj): if isinstance(obj, string_types): try: obj = json.loads(obj) except ValueError: raise ClientException("`obj` is not a json string") json_str = json.dumps(obj, sort_keys=True, indent=2) ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Get all commands of the benchmark category
How would you explain what the following Python 3 function does def commands(self): for child in self._children: with open(osp.join(child, YAML_REPORT_FILE)) as istr: command = yaml.safe_load(istr)['command'] yield ' '.join(map(six.moves.shlex_quote, command))
You are a Python code architect, reviewing and designing scalable and efficient code
def _module_env(self, execution): """Set current process environment according to execution `environment` and `modules` """ env = copy.copy(os.environ) try: for mod in execution.get('modules') or []: Module.load(mod) os.environ.update(execu...
Write a Python 3 script to set current process environment according to execution environment and modules
As a python code expert, you are capable of creating scripts from specifications.
Write a JSON file with the result of every runs xid
Here you have a function in Python 3, explain what it does def gather_metrics(self, runs): for run_dirs in runs.values(): with open(JSON_METRICS_FILE, 'w') as ostr: ostr.write('[\n') for i in range(len(run_dirs)): with open(osp.join(run_dirs[i], YA...
As a Python code translator, you convert algorithms and pseudocode into Python.
Ensure that returned metrics are properly exposed.
How would you explain what the following Python 3 function does def _check_metrics(cls, schema, metrics): for name, value in metrics.items(): metric = schema.get(name) if not metric: message = "Unexpected metric '{}' returned".format(name) raise Exception(...
You are a Python code analyst, evaluating scripts for potential improvements.
A generic function to load object parameters based on a dictionary list.
Given the following Python 3 function, write the documentation def add_inputs_to_object(obj, values): for item in obj.inputs: if hasattr(obj, item): # print(item) setattr(obj, item, values[item])
You are a Python code architect, reviewing and designing scalable and efficient code
def load_sample_data(sss): """ Sample data for the SoilStructureSystem object :param sss: :return: """ load_soil_sample_data(sss.sp) # soil load_foundation_sample_data(sss.fd) # foundation load_structure_sample_data(sss.bd) # structure load_hazard_sample_data(sss.hz)
Can you write a function in Python 3 where it loads sample data for the SoilStructureSystem object.
As a Python code analyst, you investigate and solve complex coding mysteries
Load sample data for the Soil object.
Explain what the following Python 3 code does def load_soil_sample_data(sp): # soil sp.g_mod = 60.0e6 # [Pa] sp.phi = 30 # [degrees] sp.relative_density = .40 # [decimal] sp.gwl = 2. # [m], ground water level sp.unit_dry_weight = 17000 # [N/m3] sp.unit_sat_weight = 18000 # [N/m3] s...
As a Python code translator, you convert algorithms and pseudocode into Python.
def load_foundation_sample_data(fd): """ Sample data for the Foundation object :param fd: Foundation Object :return: """ # foundation fd.width = 16.0 # m fd.length = 18.0 # m fd.depth = 0.0 # m fd.mass = 0.0
Write a Python 3 function for loading the sample data for the Foundation object
As a python code expert, you are capable of creating scripts from specifications.
def load_structure_sample_data(st): """ Sample data for the Structure object :param st: Structure Object :return: """ # structure st.h_eff = 9.0 # m st.mass_eff = 120e3 # kg st.t_eff = 1.0 # s st.mass_ratio = 1.0
Write a Python 3 script for loading the sample data for the structure object
As a Python code composer, you craft elegant and concise scripts.
def load_hazard_sample_data(hz): """ Sample data for the Hazard object :param hz: Hazard Object :return: """ # hazard hz.z_factor = 0.3 # Hazard factor hz.r_factor = 1.0 # Return period factor hz.n_factor = 1.0 # Near-fault factor hz.magnitude = 7.5 # Magnitude of earthquake ...
Implement a function in Python 3 to load sample data for the Hazard object.
As a Python code composer, you craft elegant and concise scripts.
Load the sample data for the Building object.
Make a summary of the following Python 3 code def load_building_sample_data(bd): number_of_storeys = 6 interstorey_height = 3.4 # m masses = 40.0e3 # kg bd.interstorey_heights = interstorey_height * np.ones(number_of_storeys) bd.floor_length = 18.0 # m bd.floor_width = 16.0 # m bd.store...
As a python code expert, you are capable of creating scripts from specifications.
Load the sample data for the BuildingFrame object.
Given the following Python 3 function, write the documentation def load_frame_building_sample_data(): number_of_storeys = 6 interstorey_height = 3.4 # m masses = 40.0e3 # kg n_bays = 3 fb = models.BuildingFrame(number_of_storeys, n_bays) fb.interstorey_heights = interstorey_height * np.ones(n...
As a Python code composer, you craft elegant and concise scripts.
Generate a random FPGA - style list of random FPGA - style values.
Can you tell what is the following Python 3 function doing def _get_random_fp_raw(): ''' 生成随机的原始指纹列表 ''' fp_list = [] fp_list.append(get_random_ua()) # ua fp_list.append('zh-CN') # language fp_list.append('24') # color depth fp_list.append(__get_random_screen_resolution()) fp_...
You are a Python code architect, reviewing and designing scalable and efficient code
def get_fp_raw(): ''' 生成fp_raw_str ''' fp_file_path = os.path.expanduser('~/.xunleipy_fp') fp_list = [] try: with open(fp_file_path, 'r') as fp_file: fp_str = fp_file.readline() if len(fp_str) > 0: fp_list = fp_str.split('###') except IOErr...
Write a Python 3 function that can get the raw version of the FPGA file.
As a Python code translator, you convert algorithms and pseudocode into Python.
def compose(*functions): """Define functions composition like f ∘ g ∘ h :return: callable object that will perform function composition of callables given in argument. """ def _compose2(f, g): # pylint: disable=invalid-name return lambda x: f(g(x)) return functools.reduce(_compose2, f...
How would you implement a function in Python 3 that defines functions composition like f g
You are a Python code generator, capable of creating scripts from specifications.
Split an iterator into chunks with size elements each.
Explain what the following Python 3 code does def chunks(iterator, size): for item in iterator: yield [item] + list(islice(iterator, size - 1))
You are a Python code analyst, evaluating scripts for potential improvements.
def match_subgroup(sequence, pattern): """Yield the sub-group element dictionary that match a regex pattern.""" for element in sequence: match = re.match(pattern, element) if match: yield match.groupdict()
Can you implement a function in Python 3 that yields the sub - group element dictionary that match a regex pattern.
You are a Python code analyst, evaluating scripts for potential improvements.
Decorator for adding regex start and end characters.
Explain what the following Python 3 code does def add_regex_start_end(pattern_function): @wraps(pattern_function) def func_wrapper(*args, **kwargs): return r'^{}$'.format(pattern_function(*args, **kwargs)) return func_wrapper
As a Python code translator, you convert algorithms and pseudocode into Python.
def convert_stress_to_mass(q, width, length, gravity): """ Converts a foundation stress to an equivalent mass. :param q: applied stress [Pa] :param width: foundation width [m] :param length: foundation length [m] :param gravity: applied gravitational acceleration [m/s2] :return: """ ...
How would you implement a function in Python 3 that converts a foundation stress to an equivalent mass.
As a python code expert, you are capable of creating scripts from specifications.
Adds the key - value pairs to an object.
Explain what the following Python 3 code does def add_to_obj(obj, dictionary, objs=None, exceptions=None, verbose=0): if exceptions is None: exceptions = [] for item in dictionary: if item in exceptions: continue if dictionary[item] is not None: if verbose: ...
You are a Python code analyst, evaluating scripts for potential improvements.
Create quantile start and end boundaries.
Explain what the following Python 3 code does def create_quantiles(items: Sequence, lower_bound, upper_bound): interval = (upper_bound - lower_bound) / len(items) quantiles = ((g, (x - interval, x)) for g, x in zip(items, accumulate(repeat(interval, len(items))))) return quantiles
You are a Python code architect, reviewing and designing scalable and efficient code
Cast a single element to a tuple.
Here you have a function in Python 3, explain what it does def tupleize(element, ignore_types=(str, bytes)): if hasattr(element, '__iter__') and not isinstance(element, ignore_types): return element else: return tuple((element,))
As a python code expert, you are capable of creating scripts from specifications.
def dictionize(fields: Sequence, records: Sequence) -> Generator: """Create dictionaries mapping fields to record data.""" return (dict(zip(fields, rec)) for rec in records)
Write a Python 3 script for creating dictionaries mapping fields to record data.
As a Python code translator, you convert algorithms and pseudocode into Python.
def flip_iterable_dict(d: dict) -> dict: """Transform dictionary to unpack values to map to respective key.""" value_keys = disjoint_union((cartesian_product((v, k)) for k, v in d.items())) return dict(value_keys)
How would you code a function in Python 3 to transform dictionary to unpack values to map to respective key.
As a python code expert, you are capable of creating scripts from specifications.
Return the area of a simple polygon.
Here you have a function in Python 3, explain what it does def get_signed_area(self): accum = 0.0 for i in range(len(self.verts)): j = (i + 1) % len(self.verts) accum += ( self.verts[j][0] * self.verts[i][1] - self.verts[i][0] * self.verts[j][1]) ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Calls all child extensions with the given arguments and returns the results of all child extensions.
Can you tell what is the following Python 3 function doing def call_next(self, *args, **kwargs) -> t.List[run.RunInfo]: all_results = [] for ext in self.next_extensions: LOG.debug(" %s ", ext) results = ext(*args, **kwargs) LOG.debug(" %s => %s", ext, results) ...
As a Python code composer, you craft elegant and concise scripts.
def print(self, indent=0): """Print a structural view of the registered extensions.""" LOG.info("%s:: %s", indent * " ", self.__class__) for ext in self.next_extensions: ext.print(indent=indent + 2)
Create a Python 3 function for printing a structural view of the registered extensions.
You are a Python code generator, capable of creating scripts from specifications.
Prints the results of the search.
How would you explain what the following Python 3 function does def print_results(matches): output = "" for n, match in enumerate(matches): matched_text = match[0][:40]+"..." if len(match[0]) > 40 else match[0] search_result = match[1] if search_result.uri==surf.ns.EFRBROO['F10_Person']:...
You are a Python code generator, capable of creating scripts from specifications.
def show_result(resource, verbose=False): """ TODO """ if resource.uri == surf.ns.EFRBROO['F10_Person']: print("\n{} ({})\n".format(unicode(resource), resource.get_urn())) works = resource.get_works() print("Works by {} ({}):\n".format(resource, len(works))) [show_result(...
Write a Python 3 script for printing the result of a resource.
You are a Python code generator, capable of creating scripts from specifications.
def main(): """Define the CLI inteface/commands.""" arguments = docopt(__doc__) cfg_filename = pkg_resources.resource_filename( 'knowledge_base', 'config/virtuoso.ini' ) kb = KnowledgeBase(cfg_filename) # the user has issued a `find` command if arguments["find"]: sea...
Write a Python 3 function for defining the CLI inteface / commands.
As a python code expert, you are capable of creating scripts from specifications.
def is_valid(container, path): """ Checks if a container exists and is unpacked. Args: path: The location where the container is expected. Returns: True if the container is valid, False if the container needs to unpacked or if the path does not exist yet. """ try: ...
Write a Python 3 function that can check if a container exists and is unpacked.
You are a Python code generator, capable of creating scripts from specifications.
Unpack a container usable by uchroot.
Given the following Python 3 function, write the documentation def unpack(container, path): from benchbuild.utils.run import run from benchbuild.utils.uchroot import no_args path = local.path(path) c_filename = local.path(container.filename) name = c_filename.basename if not path.exists(): ...
As a Python code composer, you craft elegant and concise scripts.
Find the current location of a container.
Make a summary of the following Python 3 code def local(self): assert self.name in CFG["container"]["images"].value tmp_dir = local.path(str(CFG["tmp_dir"])) target_dir = tmp_dir / self.name if not target_dir.exists() or not is_valid(self, target_dir): unpack(self, target_di...
As a Python code translator, you convert algorithms and pseudocode into Python.
def src_file(self): """ Get the latest src_uri for a stage 3 tarball. Returns (str): Latest src_uri from gentoo's distfiles mirror. """ try: src_uri = (curl[Gentoo._LATEST_TXT] | tail["-n", "+3"] | cut["-f1", "-d "])().strip() ...
Write a Python 3 script for getting the latest src_uri for a stage 3 tarball.
You are a Python code analyst, evaluating scripts for potential improvements.
Return the build date of the gentoo container.
Can you generate the documentation for the following Python 3 function def version(self): try: _version = (curl[Gentoo._LATEST_TXT] | \ awk['NR==2{print}'] | \ cut["-f2", "-d="])().strip() _version = datetime.utcfromtimestamp(int(_version))\ ...
You are a Python code architect, reviewing and designing scalable and efficient code
def time_indices(npts, dt, start, end, index): """ Determine the new start and end indices of the time series. :param npts: Number of points in original time series :param dt: Time step of original time series :param start: int or float, optional, New start point :param end: int or float, optio...
Write a Python 3 function that can determine the new start and end indices of the time series.
You are a Python code generator, capable of creating scripts from specifications.
def cut(self, start=0, end=-1, index=False): """ The method cuts the time series to reduce its length. :param start: int or float, optional, New start point :param end: int or float, optional, New end point :param index: bool, optional, if False then start and end are considered ...
Write a Python 3 function that can cut the time series to reduce its length.
As a Python code analyst, you investigate and solve complex coding mysteries
Check whether a SLURM job is finished or not
Explain what the following Python 3 code does def finished(cls, jobid): output = subprocess.check_output( [SACCT, '-n', '-X', '-o', "end", '-j', str(jobid)] ) end = output.strip().decode() return end not in {'Unknown', ''}
As a Python code analyst, you investigate and solve complex coding mysteries
def begin_run_group(project): """ Begin a run_group in the database. A run_group groups a set of runs for a given project. This models a series of runs that form a complete binary runtime test. Args: project: The project we begin a new run_group for. Returns: ``(group, session...
Write a Python 3 function for beginning a run_group in the database.
As a Python code composer, you craft elegant and concise scripts.
def end_run_group(group, session): """ End the run_group successfully. Args: group: The run_group we want to complete. session: The database transaction we will finish. """ from datetime import datetime group.end = datetime.now() group.status = 'completed' session.commi...
Can you implement a function in Python 3 that ends the run_group successfully.
You are a Python code analyst, evaluating scripts for potential improvements.
def fail_run_group(group, session): """ End the run_group unsuccessfully. Args: group: The run_group we want to complete. session: The database transaction we will finish. """ from datetime import datetime group.end = datetime.now() group.status = 'failed' session.commi...
Write a Python 3 script to end the run_group unsuccessfully.
You are a Python code analyst, evaluating scripts for potential improvements.
Generate a single exit code from a list of RunInfo objects.
Can you generate the documentation for the following Python 3 function def exit_code_from_run_infos(run_infos: t.List[RunInfo]) -> int: assert run_infos is not None if not hasattr(run_infos, "__iter__"): return run_infos.retcode rcs = [ri.retcode for ri in run_infos] max_rc = max(rcs) min_...
You are a Python code generator, capable of creating scripts from specifications.
def track_execution(cmd, project, experiment, **kwargs): """Guard the execution of the given command. The given command (`cmd`) will be executed inside a database context. As soon as you leave the context we will commit the transaction. Any necessary modifications to the database can be identified insi...
Implement a function in Python 3 to guard the execution of the given command. The given command (`cmd`) will be executed inside a database context. As soon as you leave the context we will commit the transaction. Any necessary modifications to the database can be identified inside the context with the RunInfo object. A...
You are a Python code architect, reviewing and designing scalable and efficient code
Recursively updates the environment of the specified command and all its subcommands.
Can you generate a brief explanation for the following Python 3 code def with_env_recursive(cmd, **envvars): from plumbum.commands.base import BoundCommand, BoundEnvCommand if isinstance(cmd, BoundCommand): cmd.cmd = with_env_recursive(cmd.cmd, **envvars) elif isinstance(cmd, BoundEnvCommand): ...
As a Python code analyst, you investigate and solve complex coding mysteries
Decorator for creating a new build directory in a project phase with a local working directory change.
How would you explain what the following Python 3 function does def in_builddir(sub='.'): from functools import wraps def wrap_in_builddir(func): """Wrap the function for the new build directory.""" @wraps(func) def wrap_in_builddir_func(self, *args, **kwargs): """The actua...
You are a Python code architect, reviewing and designing scalable and efficient code
Decorator for storing the configuration in the project s builddir.
How would you explain what the following Python 3 function does def store_config(func): from functools import wraps @wraps(func) def wrap_store_config(self, *args, **kwargs): """Wrapper that contains the actual storage call for the config.""" CFG.store(local.path(self.builddir) / ".benchbui...
As a python code expert, you are capable of creating scripts from specifications.
Remove the in and out of the container if confirmed by the user.
Given the following Python 3 function, write the documentation def clean_directories(builddir, in_dir=True, out_dir=True): container_in = local.path(builddir) / "container-in" container_out = local.path(builddir) / "container-out" if in_dir and container_in.exists(): if ui.ask("Should I delete '{0}...
You are a Python code architect, reviewing and designing scalable and efficient code
def setup_directories(builddir): """Create the in and out directories of the container.""" build_dir = local.path(builddir) in_dir = build_dir / "container-in" out_dir = build_dir / "container-out" if not in_dir.exists(): in_dir.mkdir() if not out_dir.exists(): out_dir.mkdir()
Can you create a Python 3 function that creates the in and out directories of the container.
You are a Python code architect, reviewing and designing scalable and efficient code
Prepare the container and returns the path where it can be found.
Here you have a function in Python 3, explain what it does def setup_container(builddir, _container): build_dir = local.path(builddir) in_dir = build_dir / "container-in" container_path = local.path(_container) with local.cwd(builddir): container_bin = container_path.basename container_i...
You are a Python code architect, reviewing and designing scalable and efficient code
Runs a given command inside a container.
Can you generate a brief explanation for the following Python 3 code def run_in_container(command, container_dir): container_p = local.path(container_dir) with local.cwd(container_p): uchrt = uchroot.with_mounts() uchrt = uchrt["-E", "-A", "-u", "0", "-g", "0", "-C", "-w", "/", "-r", ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def pack_container(in_container, out_file): """ Pack a container image into a .tar.bz2 archive. Args: in_container (str): Path string to the container image. out_file (str): Output file name. """ container_filename = local.path(out_file).basename out_container = local.cwd / "con...
Implement a Python 3 function for packing a container image into a. tar. bz2 archive.
You are a Python code analyst, evaluating scripts for potential improvements.
Setup a bash environment inside a container.
Make a summary of the following Python 3 code def setup_bash_in_container(builddir, _container, outfile, shell): with local.cwd(builddir): # Switch to bash inside uchroot print("Entering bash inside User-Chroot. Prepare your image and " "type 'exit' when you are done. If bash exits wit...
As a python code expert, you are capable of creating scripts from specifications.
def set_input_container(_container, cfg): """Save the input for the container in the configurations.""" if not _container: return False if _container.exists(): cfg["container"]["input"] = str(_container) return True return False
How would you code a function in Python 3 to save the input for the container in the configurations.
As a Python code composer, you craft elegant and concise scripts.
Setup a gentoo container suitable for PolyJIT.
Can you generate a brief explanation for the following Python 3 code def run(self, context): # Don't do something when running non-interactive. if not sys.stdout.isatty(): return with local.cwd(context.in_container): from benchbuild.projects.gentoo import gentoo ...
You are a Python code analyst, evaluating scripts for potential improvements.
Find the input path of a uchroot container.
Can you tell what is the following Python 3 function doing def input_file(self, _container): p = local.path(_container) if set_input_container(p, CFG): return p = find_hash(CFG["container"]["known"].value, container) if set_input_container(p, CFG): return ...
You are a Python code analyst, evaluating scripts for potential improvements.
Find and writes the output path of a chroot container.
Can you generate a brief explanation for the following Python 3 code def output_file(self, _container): p = local.path(_container) if p.exists(): if not ui.ask("Path '{0}' already exists." " Overwrite?".format(p)): sys.exit(0) CFG["container"...
As a Python code translator, you convert algorithms and pseudocode into Python.
Discretizes the soil profile into slices and stores as dictionary
Here you have a function in Python 3, explain what it does def discretize_soil_profile(sp, incs=None, target=1.0): if incs is None: incs = np.ones(sp.n_layers) * target dd = {} dd["thickness"] = [] dd["unit_mass"] = [] dd["shear_vel"] = [] cum_thickness = 0 for i in range(sp.n_layer...
You are a Python code architect, reviewing and designing scalable and efficient code
Resets all parameters to None
Here you have a function in Python 3, explain what it does def reset_all(self): for item in self.inputs: setattr(self, "_%s" % item, None) self.stack = []
You are a Python code generator, capable of creating scripts from specifications.
def _add_to_stack(self, item, value): """ Add a parameter-value pair to the stack of parameters that have been set. :param item: :param value: :return: """ p_value = (item, value) if p_value not in self.stack: self.stack.append(p_value)
Write a Python 3 function that can add a parameter - value pair to the stack of parameters that have been set.
As a python code expert, you are capable of creating scripts from specifications.
def get_shear_vel(self, saturated): """ Calculate the shear wave velocity :param saturated: bool, if true then use saturated mass :return: """ try: if saturated: return np.sqrt(self.g_mod / self.unit_sat_mass) else: ...
Can you implement a function in Python 3 that calculates the shear wave velocity of the user.
You are a Python code architect, reviewing and designing scalable and efficient code
def saturation(self, value): """Volume of water to volume of voids""" value = clean_float(value) if value is None: return try: unit_moisture_weight = self.unit_moist_weight - self.unit_dry_weight unit_moisture_volume = unit_moisture_weight / self._pw ...
Write a Python 3 script for voluming of water to volume of voids
You are a Python code analyst, evaluating scripts for potential improvements.
Set the relative weight of the solid
Can you tell what is the following Python 3 function doing def specific_gravity(self, value): value = clean_float(value) if value is None: return specific_gravity = self._calc_specific_gravity() if specific_gravity is not None and not ct.isclose(specific_gravity, value, rel_t...
As a python code expert, you are capable of creating scripts from specifications.
Adds a soil to the SoilProfile at a set depth.
How would you explain what the following Python 3 function does def add_layer(self, depth, soil): self._layers[depth] = soil self._sort_layers() if self.hydrostatic: if depth >= self.gwl: soil.saturation = 1.0 else: li = self.get_layer_ind...
As a Python code translator, you convert algorithms and pseudocode into Python.
def _sort_layers(self): """Sort the layers by depth.""" self._layers = OrderedDict(sorted(self._layers.items(), key=lambda t: t[0]))
Implement a Python 3 function for sorting the layers by depth.
You are a Python code generator, capable of creating scripts from specifications.
Get the layer height by layer id number.
Here you have a function in Python 3, explain what it does def layer_height(self, layer_int): if layer_int == self.n_layers: if self.height is None: return None return self.height - self.layer_depth(layer_int) else: return self.layer_depth(layer_int + ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def equivalent_crust_cohesion(self): """ Calculate the equivalent crust cohesion strength according to Karamitros et al. 2013 sett, pg 8 eq. 14 :return: equivalent cohesion [Pa] """ deprecation("Will be moved to a function") if len(self.layers) > 1: crust = s...
Write a Python 3 function that can calculate the equivalent crust cohesion strength according to Karamitros et al. 2013 sett pg 8 eq. 14
You are a Python code generator, capable of creating scripts from specifications.
def get_v_total_stress_at_depth(self, z): """ Determine the vertical total stress at depth z, where z can be a number or an array of numbers. """ if not hasattr(z, "__len__"): return self.one_vertical_total_stress(z) else: sigma_v_effs = [] fo...
Write a Python 3 function for returning the vertical total stress at depth z.
You are a Python code generator, capable of creating scripts from specifications.
Determines the vertical total stress at a single depth z_c.
Can you tell what is the following Python 3 function doing def one_vertical_total_stress(self, z_c): total_stress = 0.0 depths = self.depths end = 0 for layer_int in range(1, len(depths) + 1): l_index = layer_int - 1 if z_c > depths[layer_int - 1]: ...
You are a Python code analyst, evaluating scripts for potential improvements.
Determine the vertical effective stress at a single depth z_c.
Make a summary of the following Python 3 code def get_v_eff_stress_at_depth(self, y_c): sigma_v_c = self.get_v_total_stress_at_depth(y_c) pp = self.get_hydrostatic_pressure_at_depth(y_c) sigma_veff_c = sigma_v_c - pp return sigma_veff_c
You are a Python code generator, capable of creating scripts from specifications.
def shear_vel_at_depth(self, y_c): """ Get the shear wave velocity at a depth. :param y_c: float, depth from surface :return: """ sl = self.get_soil_at_depth(y_c) if y_c <= self.gwl: saturation = False else: saturation = True ...
Implement a function in Python 3 to get the shear wave velocity at a depth.
As a Python code translator, you convert algorithms and pseudocode into Python.
Create the text of the file and write it.
How would you explain what the following Python 3 function does def create_package_file(root, master_package, subroot, py_files, opts, subs): package = os.path.split(root)[-1] text = format_heading(1, '%s Package' % package) # add each package's module for py_file in py_files: if shall_skip(os.p...
As a Python code composer, you craft elegant and concise scripts.
Create the modules toc file.
How would you explain what the following Python 3 function does def create_modules_toc_file(master_package, modules, opts, name='modules'): text = format_heading(1, '%s Modules' % opts.header) text += '.. toctree::\n' text += ' :maxdepth: %s\n\n' % opts.maxdepth modules.sort() prev_module = '' ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def recurse_tree(path, excludes, opts): """ Look for every file in the directory tree and create the corresponding ReST files. """ # use absolute path for root, as relative paths like '../../foo' cause # 'if "/." in root ...' to filter out *all* modules otherwise path = os.path.abspath(path)...
Write a Python 3 script for looking for every file in the directory tree and create the corresponding ReST files.
As a Python code analyst, you investigate and solve complex coding mysteries
Normalize the excluded directory list
Can you tell what is the following Python 3 function doing def normalize_excludes(rootpath, excludes): sep = os.path.sep f_excludes = [] for exclude in excludes: if not os.path.isabs(exclude) and not exclude.startswith(rootpath): exclude = os.path.join(rootpath, exclude) if not e...
As a Python code composer, you craft elegant and concise scripts.
Check if the directory is in the exclude list.
Here you have a function in Python 3, explain what it does def is_excluded(root, excludes): sep = os.path.sep if not root.endswith(sep): root += sep for exclude in excludes: if root.startswith(exclude): return True return False
You are a Python code architect, reviewing and designing scalable and efficient code
Parse and check the command line arguments and run the main function.
Make a summary of the following Python 3 code def main(): parser = optparse.OptionParser(usage="""usage: %prog [options] <package path> [exclude paths, ...] Note: By default this script will not overwrite already created files.""") parser.add_option("-n", "--doc-header", action="store", dest="header", help="Do...
You are a Python code architect, reviewing and designing scalable and efficient code
Return the path to the file
How would you explain what the following Python 3 function does def path(self): if not isinstance(self.ref, str): return None u = parse_app_url(self.ref) if u.inner.proto != 'file': return None return u.path
As a Python code composer, you craft elegant and concise scripts.
The absolute directory of the document
Given the following Python 3 function, write the documentation def doc_dir(self): from os.path import abspath if not self.ref: return None u = parse_app_url(self.ref) return abspath(dirname(u.path))
As a Python code translator, you convert algorithms and pseudocode into Python.
Return a new section
Explain what the following Python 3 code does def new_section(self, name, params=None): self.sections[name.lower()] = SectionTerm(None, name, term_args=params, doc=self) # Set the default arguments s = self.sections[name.lower()] if name.lower() in self.decl_sections: s.arg...
As a Python code composer, you craft elegant and concise scripts.
Create a new section or return an existing one of the same name
Can you generate a brief explanation for the following Python 3 code def get_or_new_section(self, name, params=None): if name not in self.sections: self.sections[name.lower()] = SectionTerm(None, name, term_args=params, doc=self) return self.sections[name.lower()]
As a Python code analyst, you investigate and solve complex coding mysteries
def sort_sections(self, order): """ Sort sections according to the section names in the order list. All remaining sections are added to the end in their original order :param order: Iterable of section names :return: """ order_lc = [e.lower() for e in order] ...
How would you code a function in Python 3 to sort the sections according to the section names in the order list.
As a Python code composer, you craft elegant and concise scripts.
def find(self, term, value=False, section=None, _expand_derived=True, **kwargs): """Return a list of terms, possibly in a particular section. Use joined term notation, such as 'Root.Name' The kwargs arg is used to set term properties, all of which match returned terms, so ``name='foobar'`` will match terms that...
Can you implement a function in Python 3 that returns a list of terms that are in a particular section.
As a Python code translator, you convert algorithms and pseudocode into Python.
def get(self, term, default=None): """Return the first term, returning the default if no term is found""" v = self.find_first(term) if not v: return default else: return v
Write a Python 3 script for returning the first term in the list returning the default if no term is found
You are a Python code generator, capable of creating scripts from specifications.
Return the first value of a term in the specified section.
Can you generate the documentation for the following Python 3 function def get_value(self, term, default=None, section=None): term = self.find_first(term, value=False, section=section) if term is None: return default else: return term.value
As a Python code composer, you craft elegant and concise scripts.
Create a builder from a sequence of terms.
How would you explain what the following Python 3 function does def load_terms(self, terms): #if self.root and len(self.root.children) > 0: # raise MetatabError("Can't run after adding terms to document.") for t in terms: t.doc = self if t.term_is('root.root'): ...
You are a Python code analyst, evaluating scripts for potential improvements.
def cleanse(self): """Clean up some terms, like ensuring that the name is a slug""" from .util import slugify self.ensure_identifier() try: self.update_name() except MetatabError: identifier = self['Root'].find_first('Root.Identifier') name...
Write a Python 3 script for cleaning up some terms like ensuring that the name is a slug
You are a Python code analyst, evaluating scripts for potential improvements.
def update_name(self, force=False, create_term=False, report_unchanged=True): """Generate the Root.Name term from DatasetName, Version, Origin, TIme and Space""" updates = [] self.ensure_identifier() name_term = self.find_first('Root.Name') if not name_term: if cr...
Write a Python 3 script for generating the Root. Name term from DatasetName Version Origin TIme and Space and Create the Term Root. Name and Update the Name term.
As a Python code translator, you convert algorithms and pseudocode into Python.
Iterate link terms and convert to a dict
Can you tell what is the following Python 3 function doing def as_dict(self, replace_value_names=True): # This function is a hack, due to confusion between the root of the document, which # should contain all terms, and the root section, which has only terms that are not # in another section. S...
You are a Python code generator, capable of creating scripts from specifications.
Iterate over all of the rows in the archive
Make a summary of the following Python 3 code def rows(self): for s_name, s in self.sections.items(): # Yield the section header if s.name != 'Root': yield [''] # Unecessary, but makes for nice formatting. Should actually be done just before write yiel...
As a python code expert, you are capable of creating scripts from specifications.
def all_terms(self): """Iterate over all of the terms. The self.terms property has only root level terms. This iterator iterates over all terms""" for s_name, s in self.sections.items(): # Yield the section header if s.name != 'Root': yield s ...
Write a Python 3 function that can iterate over all of the terms in the hierarchy.
You are a Python code generator, capable of creating scripts from specifications.
def as_csv(self): """Return a CSV representation as a string""" from io import StringIO s = StringIO() w = csv.writer(s) for row in self.rows: w.writerow(row) return s.getvalue()
Can you create a Python 3 function that returns a CSV representation as a string
As a Python code translator, you convert algorithms and pseudocode into Python.
Return a Lines representation as a string
Make a summary of the following Python 3 code def as_lines(self): out_lines = [] for t,v in self.lines: # Make the output prettier if t == 'Section': out_lines.append('') out_lines.append('{}: {}'.format(t,v if v is not None else '') ) retu...
You are a Python code generator, capable of creating scripts from specifications.