output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Returns a clang that hides CFLAGS and LDFLAGS and returns a complete plumbum command to it.
Explain what the following Python 3 code does def cc(project, detect_project=False): from benchbuild.utils import cmd cc_name = str(CFG["compiler"]["c"]) wrap_cc(cc_name, compiler(cc_name), project, detect_project=detect_project) return cmd["./{}".format(cc_name)]
You are a Python code architect, reviewing and designing scalable and efficient code
def cxx(project, detect_project=False): """ Return a clang++ that hides CFLAGS and LDFLAGS. This will generate a wrapper script in the current directory and return a complete plumbum command to it. Args: cflags: The CFLAGS we want to hide. ldflags: The LDFLAGS we want to hide. ...
Implement a function in Python 3 to return a clang ++ that hides CFLAGS and LDFLAGS and returns a complete plumbum command to it.
As a Python code composer, you craft elegant and concise scripts.
Returns a usable clang ++ plumbum command that executes the specified clang ++ library
Explain what the following Python 3 code does def compiler(name): pinfo = __get_paths() _compiler = local[name] _compiler = _compiler.setenv( PATH=pinfo["path"], LD_LIBRARY_PATH=pinfo["ld_library_path"]) return _compiler
As a python code expert, you are capable of creating scripts from specifications.
Strip prefix from path.
Can you generate the documentation for the following Python 3 function def strip_path_prefix(ipath, prefix): if prefix is None: return ipath return ipath[len(prefix):] if ipath.startswith(prefix) else ipath
As a Python code composer, you craft elegant and concise scripts.
Unpickle a python object from the given path.
Make a summary of the following Python 3 code def unpickle(pickle_file): pickle = None with open(pickle_file, "rb") as pickle_f: pickle = dill.load(pickle_f) if not pickle: LOG.error("Could not load python object from file") return pickle
You are a Python code generator, capable of creating scripts from specifications.
def wrap(name, project, sprefix=None, python=sys.executable): """ Wrap the binary :name: with the runtime extension of the project. This module generates a python tool that replaces :name: The function in runner only accepts the replaced binaries name as argument. We use the cloudpickle package to ...
Can you implement a function in Python 3 that wraps the binary with the runtime extension of the project.
You are a Python code generator, capable of creating scripts from specifications.
Wrap a C ++ compiler command in a new file.
Can you generate the documentation for the following Python 3 function def wrap_cc(filepath, compiler, project, python=sys.executable, detect_project=False): """ Substitute a compiler with a script that hides CFLAGS & LDFLAGS. This will generate a wrapper scr...
As a Python code composer, you craft elegant and concise scripts.
Persist an object in the filesystem.
Can you tell what is the following Python 3 function doing def persist(id_obj, filename=None, suffix=None): if suffix is None: suffix = ".pickle" if hasattr(id_obj, 'id'): ident = id_obj.id else: ident = str(id(id_obj)) if filename is None: filename = "{obj_id}{suffix}"....
You are a Python code architect, reviewing and designing scalable and efficient code
Load a pickled object from the filesystem.
Here you have a function in Python 3, explain what it does def load(filename): if not os.path.exists(filename): LOG.error("load object - File '%s' does not exist.", filename) return None obj = None with open(filename, 'rb') as obj_file: obj = dill.load(obj_file) return obj
You are a Python code analyst, evaluating scripts for potential improvements.
Extend shape or polygon outline away from polygon center point by absolute distance.
Given the following Python 3 function, write the documentation def extend_shapes(df_shapes, axis, distance): ''' Extend shape/polygon outline away from polygon center point by absolute distance. ''' df_shapes_i = df_shapes.copy() offsets = df_shapes_i[axis + '_center_offset'].copy() offsets[...
You are a Python code analyst, evaluating scripts for potential improvements.
def extract_adjacent_shapes(df_shapes, shape_i_column, extend=.5): ''' Generate list of connections between "adjacent" polygon shapes based on geometrical "closeness". Parameters ---------- df_shapes : pandas.DataFrame Table of polygon shape vertices (one row per vertex). Table...
Implement a Python 3 function for returning a list of lists of adjacent electrodes in a single table.
As a Python code composer, you craft elegant and concise scripts.
Extract all connection lines from a layer in a SVG file.
Can you generate a brief explanation for the following Python 3 code def extract_connections(svg_source, shapes_canvas, line_layer='Connections', line_xpath=None, path_xpath=None, namespaces=None): ''' Load all ``<svg:line>`` elements and ``<svg:path>`` elements from a layer of an SV...
You are a Python code analyst, evaluating scripts for potential improvements.
Discover all experiments listed in benchbuild. reports. raw AttributeNames
Explain what the following Python 3 code does def discover(): if CFG["plugins"]["autoload"]: report_plugins = CFG["plugins"]["reports"].value for plugin in report_plugins: try: importlib.import_module(plugin) LOG.debug("Found report: %s", plugin) ...
You are a Python code generator, capable of creating scripts from specifications.
Get Elasticsearch index name associated to the campaign
Can you tell what is the following Python 3 function doing def index_name(self): fmt = self.campaign.export.elasticsearch.index_name fields = dict(date=self.report['date']) return fmt.format(**fields).lower()
As a python code expert, you are capable of creating scripts from specifications.
def remove_index(self): """Remove Elasticsearch index associated to the campaign""" self.index_client.close(self.index_name) self.index_client.delete(self.index_name)
Write a Python 3 script for removing Elasticsearch index associated to the campaign
As a Python code translator, you convert algorithms and pseudocode into Python.
Parses arguments returns options and args.
How would you explain what the following Python 3 function does def parse_args(args=None): from argparse import ArgumentParser if args is None: args = sys.argv parser = ArgumentParser(description='Rename template project with' 'hyphen-separated <new name> (path names an...
You are a Python code generator, capable of creating scripts from specifications.
def extract_build_info(exe_path, elf_section=ELF_SECTION): """Extracts the build information from a given executable. The build information is expected to be in json format, which is parsed and returned as a dictionary. If no build information is found an empty dictionary is returned. This assumes...
Create a Python 3 function for extracting the build information from a given executable.
You are a Python code architect, reviewing and designing scalable and efficient code
def rk_create(self, im, im_type, timeout=60): """ im: 图片字节 im_type: 题目类型 """ params = { 'typeid': im_type, 'timeout': timeout, } params.update(self.base_params) files = {'image': ('check_code.png', im)} r = requests.post('ht...
How would you code a function in Python 3 to create a new entry in the cache.
As a Python code composer, you craft elegant and concise scripts.
def rk_report_error(self, im_id): """ im_id:报错题目的ID """ params = { 'id': im_id, } params.update(self.base_params) r = requests.post('http://api.ruokuai.com/reporterror.json', data=params, headers=self.headers) return r.json()
Implement a Python 3 function for reporting an error to the user.
As a Python code translator, you convert algorithms and pseudocode into Python.
Evaluates the accuracy of a predictive measure of a predictive measure.
Given the following Python 3 function, write the documentation def lc_score(value): rebased = 2 * (value - 0.5) if rebased == 0: return 0 elif rebased > 0: compliment = 1.0 - rebased score = - np.log2(compliment) else: compliment = 1.0 + rebased score = np.log2(c...
As a Python code composer, you craft elegant and concise scripts.
def uchroot(*args, **kwargs): """ Return a customizable uchroot command. Args: args: List of additional arguments for uchroot (typical: mounts) Return: chroot_cmd """ uchroot_cmd = with_mounts(*args, uchroot_cmd_fn=no_llvm, **kwargs) return uchroot_cmd["--"]
How would you implement a function in Python 3 that returns a customizable uchroot command.
As a Python code analyst, you investigate and solve complex coding mysteries
def no_llvm(*args, uid=0, gid=0, **kwargs): """ Return a customizable uchroot command. The command will be executed inside a uchroot environment. Args: args: List of additional arguments for uchroot (typical: mounts) Return: chroot_cmd """ uchroot_cmd = no_args() uchroo...
Write a Python 3 script for returning a customizable uchroot command.
You are a Python code analyst, evaluating scripts for potential improvements.
def no_args(**kwargs): """Return the uchroot command without any customizations.""" from benchbuild.utils.cmd import uchroot as uchrt prefixes = CFG["container"]["prefixes"].value p_paths, p_libs = env(prefixes) uchrt = run.with_env_recursive( uchrt, LD_LIBRARY_PATH=path.list_to_pat...
Write a Python 3 function for returning the uchroot command without any customizations.
As a python code expert, you are capable of creating scripts from specifications.
def with_mounts(*args, uchroot_cmd_fn=no_args, **kwargs): """Return a uchroot command with all mounts enabled.""" mounts = CFG["container"]["mounts"].value prefixes = CFG["container"]["prefixes"].value uchroot_opts, mounts = __mounts__("mnt", mounts) uchroot_cmd = uchroot_cmd_fn(**kwargs) uchro...
Create a Python 3 function to return a uchroot command with all mounts enabled.
As a Python code composer, you craft elegant and concise scripts.
def clean_env(uchroot_cmd, varnames): """Returns a uchroot cmd that runs inside a filtered environment.""" env = uchroot_cmd["/usr/bin/env"] __clean_env = env["-u", ",".join(varnames)] return __clean_env
Can you create a Python 3 function that returns a uchroot cmd that runs inside a filtered environment.
You are a Python code generator, capable of creating scripts from specifications.
Compute the mountpoints of the current user.
Explain what the following Python 3 code does def mounts(prefix, __mounts): i = 0 mntpoints = [] for mount in __mounts: if not isinstance(mount, dict): mntpoint = "{0}/{1}".format(prefix, str(i)) mntpoints.append(mntpoint) i = i + 1 return mntpoints
As a Python code analyst, you investigate and solve complex coding mysteries
def env(mounts): """ Compute the environment of the change root for the user. Args: mounts: The mountpoints of the current user. Return: paths ld_libs """ f_mounts = [m.strip("/") for m in mounts] root = local.path("/") ld_libs = [root / m / "lib" for m in f_mo...
Create a Python 3 function to compute the environment of the change root for the current user.
You are a Python code generator, capable of creating scripts from specifications.
Returns a list of all the abbreviations in the given kb.
Can you tell what is the following Python 3 function doing def get_abbreviations(kb): return {"%s$$n%i" % (author.get_urn(), i): abbrev for author in kb.get_authors() for i, abbrev in enumerate(author.get_abbreviations()) if author.get_urn() is not None}
As a Python code translator, you convert algorithms and pseudocode into Python.
def author_names(self): """ Returns a dictionary like this: { "urn:cts:greekLit:tlg0012$$n1" : "Homer" , "urn:cts:greekLit:tlg0012$$n2" : "Omero" , ... } """ return {"%s$$n%i" % (author.get_urn(), i): name[1] for author...
Write a Python 3 function for returning a dictionary like this :
As a Python code analyst, you investigate and solve complex coding mysteries
Fetch the resource corresponding to the input URN.
Explain what the following Python 3 code does def get_resource_by_urn(self, urn): search_query = """ PREFIX frbroo: <http://erlangen-crm.org/efrbroo/> PREFIX crm: <http://erlangen-crm.org/current/> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> SELECT ?reso...
You are a Python code generator, capable of creating scripts from specifications.
def search(self, search_string): """ Searches for a given string through the resources' labels. :param search_string: :return: an instance of `HucitAuthor` or `HucitWork`. """ query = """ SELECT ?s ?label ?type WHERE { ?s a ?type . ...
Write a Python 3 function for searching for a given string through the resources and returns an instance of HucitAuthor or HucitWork.
You are a Python code analyst, evaluating scripts for potential improvements.
def get_authors(self): """ Returns the authors in the Knowledge Base. :return: a list of `HucitAuthor` instances. """ Person = self._session.get_class(surf.ns.EFRBROO['F10_Person']) return list(Person.all())
Write a Python 3 script to return the authors in the Knowledge Base.
You are a Python code analyst, evaluating scripts for potential improvements.
def get_works(self): """Return the author's works. :return: a list of `HucitWork` instances. """ Work = self._session.get_class(surf.ns.EFRBROO['F1_Work']) return list(Work.all())
Write a Python 3 script for returning the author s works.
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_author_label(self, urn): """Get the label corresponding to the author identified by the CTS URN. try to get an lang=en label (if multiple labels in this lang pick the shortest) try to get a lang=la label (if multiple labels in this lang exist pick the shortest) try to get a lang...
Can you write a function in Python 3 where it gets the label corresponding to the author identified by the CTS URN.
You are a Python code generator, capable of creating scripts from specifications.
def get_statistics(self): """ Gather basic stats about the Knowledge Base and its contents. :return: a dictionary """ statistics = { "number_authors": 0, "number_author_names": 0, "number_author_abbreviations": 0, "number_works": ...
Implement a function in Python 3 to gather basic stats about the Knowledge Base and its contents.
As a python code expert, you are capable of creating scripts from specifications.
Returns the opus maximum of an author.
Explain what the following Python 3 code does def get_opus_maximum_of(self, author_cts_urn): author = self.get_resource_by_urn(author_cts_urn) assert author is not None works = author.get_works() if len(works) > 1: for work in works: if work.is_opus_maximum()...
As a Python code translator, you convert algorithms and pseudocode into Python.
Serialises the content of the KnowledgeBase as JSON.
Can you generate a brief explanation for the following Python 3 code def to_json(self): return json.dumps({ "statistics": self.get_statistics() , "authors": [json.loads(author.to_json()) for author in self.get_authors()] }, indent=2)
You are a Python code analyst, evaluating scripts for potential improvements.
Decorator used in campaign node post - processing
Here you have a function in Python 3, explain what it does def write_yaml_report(func): @wraps(func) def _wrapper(*args, **kwargs): now = datetime.datetime.now() with Timer() as timer: data = func(*args, **kwargs) if isinstance(data, (SEQUENCES, types.GeneratorType)): ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def call_decorator(cls, func): """class function that MUST be specified as decorator to the `__call__` method overriden by sub-classes. """ @wraps(func) def _wrap(self, *args, **kwargs): try: return func(self, *args, **kwargs) except Excep...
Can you create a Python 3 function that classes function that MUST be specified as decorator to the `__call__` method overriden by sub-classes.
As a python code expert, you are capable of creating scripts from specifications.
def traverse(self): """Enumerate children and build associated objects """ builder = self.child_builder for child in self._children: with pushd(str(child)): yield child, builder(child)
Can you implement a function in Python 3 that enumerates children and build associated objects
You are a Python code analyst, evaluating scripts for potential improvements.
Second moment of inertia around the width axis.
Here you have a function in Python 3, explain what it does def i_ww(self): d_values = [] for i in range(self.n_pads_l): d_values.append(self.pad_position_l(i)) d_values = np.array(d_values) - self.length / 2 area_d_sqrd = sum(self.pad_area * d_values ** 2) * self.n_pads_w ...
As a Python code composer, you craft elegant and concise scripts.
Second moment of inertia around the length axis.
How would you explain what the following Python 3 function does def i_ll(self): d_values = [] for i in range(self.n_pads_w): d_values.append(self.pad_position_w(i)) d_values = np.array(d_values) - self.width / 2 area_d_sqrd = sum(self.pad_area * d_values ** 2) * self.n_pads_l...
As a Python code analyst, you investigate and solve complex coding mysteries
def pad_position_l(self, i): """ Determines the position of the ith pad in the length direction. Assumes equally spaced pads. :param i: ith number of pad in length direction (0-indexed) :return: """ if i >= self.n_pads_l: raise ModelError("pad index o...
Can you create a Python 3 function that determines the position of the ith pad in the length direction.
As a python code expert, you are capable of creating scripts from specifications.
def pad_position_w(self, i): """ Determines the position of the ith pad in the width direction. Assumes equally spaced pads. :param i: ith number of pad in width direction (0-indexed) :return: """ if i >= self.n_pads_w: raise ModelError("pad index out...
Write a Python 3 function for determining the position of the ith pad in the width direction.
As a Python code analyst, you investigate and solve complex coding mysteries
def add_to_batch(self, batch): ''' Adds paths to the given batch object. They are all added as GL_TRIANGLES, so the batch will aggregate them all into a single OpenGL primitive. ''' for name in self.paths: svg_path = self.paths[name] svg_path.add_t...
Create a Python 3 function for adding paths to the given batch object.
As a Python code translator, you convert algorithms and pseudocode into Python.
def parse(self, xml_root, on_error=None): ''' Parse all <path> elements from xml_root. Optional on_error arg specifies a callback function to be run when an error occurs during parsing. The specified on_error function must accept 3 arguments: <svg filename>, <path_ta...
Implement a function in Python 3 to parse all path elements from xml_root and return a dict of the attributes.
As a python code expert, you are capable of creating scripts from specifications.
def alphanum_key(s): """Turn a string into a list of string and number chunks. "z23a" -> ["z", 23, "a"] """ return [int(c) if c.isdigit() else c for c in _RE_INT.split(s)]
Write a Python 3 script for turning a string into a list of string and number chunks.
You are a Python code architect, reviewing and designing scalable and efficient code
def discover(): """ Import all experiments listed in PLUGINS_EXPERIMENTS. Tests: >>> from benchbuild.settings import CFG >>> from benchbuild.experiments import discover >>> import logging as lg >>> import sys >>> l = lg.getLogger('benchbuild') >>> lg.getLogge...
Write a Python 3 script for discovering all experiments listed in PLUGINS_EXPERIMENTS.
As a Python code composer, you craft elegant and concise scripts.
def print_projects(projects=None): """ Print a list of projects registered for that experiment. Args: exp: The experiment to print all projects for. """ grouped_by = {} if not projects: print( "Your selection didn't include any projects for this experiment.") ...
Implement a Python 3 function for printing a list of projects registered for that experiment.
As a Python code translator, you convert algorithms and pseudocode into Python.
def _commandline(repositories, port=8000, host="127.0.0.1", debug=False, cache=None, cache_path="./cache", redis=None): """ Run a CTS API from command line. .. warning:: This function should not be used in the production context :param repositories: :param port: :...
Write a Python 3 script to run a CTS API from command line.
You are a Python code architect, reviewing and designing scalable and efficient code
Escape string for LaTeX usage :param text: a plain text message :return: the message escaped to appear correctly in LaTeX
Given the following Python 3 function, write the documentation def tex_escape(text): conv = { '&': r'\&', '%': r'\%', '$': r'\$', '#': r'\#', '_': r'\_', '{': r'\{', '}': r'\}', '~': r'\textasciitilde{}', '^': r'\^{}', '\\': r'\textback...
You are a Python code architect, reviewing and designing scalable and efficient code
def render(template=None, ostr=None, **kwargs): """Generate report from a campaign :param template: Jinja template to use, ``DEFAULT_TEMPLATE`` is used if not specified :param ostr: output file or filename. Default is standard output """ jinja_environment.filters['texscape'] = tex_escape te...
How would you code a function in Python 3 to generate a report from a campaign
As a python code expert, you are capable of creating scripts from specifications.
Returns two -ple containing the two -ple shape space and a pandas. Series mapping each body to avec.
Given the following Python 3 function, write the documentation def get_shapes_pymunk_space(df_convex_shapes, shape_i_columns): ''' Return two-ple containing: - A `pymunk.Space` instance. - A `pandas.Series` mapping each `pymunk.Body` object in the `Space` to a shape index. The `Body` to s...
You are a Python code analyst, evaluating scripts for potential improvements.
Given a json file creates a dictionary of sfsi objects
Can you tell what is the following Python 3 function doing def load_json(ffp, custom=None, verbose=0): data = json.load(open(ffp)) return ecp_dict_to_objects(data, custom, verbose=verbose)
You are a Python code architect, reviewing and designing scalable and efficient code
Given a json string creates a dictionary of sfsi objects
Explain what the following Python 3 code does def loads_json(p_str, custom=None, meta=False, verbose=0): data = json.loads(p_str) if meta: md = {} for item in data: if item != "models": md[item] = data[item] return ecp_dict_to_objects(data, custom, verbose=ver...
As a python code expert, you are capable of creating scripts from specifications.
def ecp_dict_to_objects(ecp_dict, custom_map=None, verbose=0): """ Given an ecp dictionary, build a dictionary of sfsi objects :param ecp_dict: dict, engineering consistency project dictionary :param custom: dict, used to load custom objects, {model type: custom object} :param verbose: int, console...
How would you implement a function in Python 3 that gives an ecp dictionary build a dictionary of sfsi objects.
As a Python code composer, you craft elegant and concise scripts.
Migrates and ECP file to the current version of sfsimodels
Can you generate the documentation for the following Python 3 function def migrate_ecp(in_ffp, out_ffp): objs, meta_data = load_json_and_meta(in_ffp) ecp_output = Output() for m_type in objs: for instance in objs[m_type]: ecp_output.add_to_dict(objs[m_type][instance]) ecp_output.name...
As a Python code composer, you craft elegant and concise scripts.
def add_to_dict(self, an_object, extras=None): """ Convert models to json serialisable output :param an_object: An instance of a model object :param extras: A dictionary of extra variables that should be :return: """ if an_object.id is None: raise Mod...
Implement a Python 3 function for converting an object to a dictionary.
As a Python code analyst, you investigate and solve complex coding mysteries
def add_to_output(self, mtype, m_id, serialisable_dict): """ Can add additional objects or dictionaries to output file that don't conform to standard objects. :param mtype: :param m_id: :param serialisable_dict: :return: """ if mtype not in self.unordered...
Write a Python 3 script to add additional objects or dictionaries to output file that don t conform to standard objects.
You are a Python code analyst, evaluating scripts for potential improvements.
def models(self): """Unhashed""" models_dict = OrderedDict() collected = [] for item in standard_types: if item in self.unordered_models: new_dict, replacement_dict = unhash_dict(self.unordered_models[item]) models_dict[item] = new_dict ...
Write a Python 3 script for returning a dictionary of all the unhashed models in the database.
As a Python code composer, you craft elegant and concise scripts.
Get the number of available CPUs on this system.
Can you tell what is the following Python 3 function doing def available_cpu_count() -> int: # cpuset # cpuset may restrict the number of *available* processors try: match = re.search(r'(?m)^Cpus_allowed:\s*(.*)$', open('/proc/self/status').read()) if match: ...
You are a Python code architect, reviewing and designing scalable and efficient code
Shell - Escape a yaml input string.
Make a summary of the following Python 3 code def escape_yaml(raw_str: str) -> str: escape_list = [char for char in raw_str if char in ['!', '{', '[']] if len(escape_list) == 0: return raw_str str_quotes = '"' i_str_quotes = "'" if str_quotes in raw_str and str_quotes not in raw_str[1:-1]: ...
As a Python code analyst, you investigate and solve complex coding mysteries
def to_yaml(value) -> str: """Convert a given value to a YAML string.""" stream = yaml.io.StringIO() dumper = ConfigDumper(stream, default_flow_style=True, width=sys.maxsize) val = None try: dumper.open() dumper.represent(value) val = stream.getvalue().strip() dumper....
How would you implement a function in Python 3 that converts a given value to a YAML string.
As a Python code analyst, you investigate and solve complex coding mysteries
Converts a value into an environment variable.
Explain what the following Python 3 code does def to_env_var(env_var: str, value) -> str: val = to_yaml(value) ret_val = "%s=%s" % (env_var, escape_yaml(val)) return ret_val
You are a Python code generator, capable of creating scripts from specifications.
Find the path to the default config file.
How would you explain what the following Python 3 function does def find_config(test_file=None, defaults=None, root=os.curdir): if defaults is None: defaults = [".benchbuild.yml", ".benchbuild.yaml"] def walk_rec(cur_path, root): cur_path = local.path(root) / test_file if cur_path.exist...
As a python code expert, you are capable of creating scripts from specifications.
This function will initialize the given configuration object.
Explain what the following Python 3 code does def setup_config(cfg, config_filenames=None, env_var_name=None): if env_var_name is None: env_var_name = "BB_CONFIG_FILE" config_path = os.getenv(env_var_name, None) if not config_path: config_path = find_config(defaults=config_filenames) i...
As a python code expert, you are capable of creating scripts from specifications.
Provide forward migration for configuration files.
Explain what the following Python 3 code does def upgrade(cfg): db_node = cfg["db"] old_db_elems = ["host", "name", "port", "pass", "user", "dialect"] has_old_db_elems = [x in db_node for x in old_db_elems] if any(has_old_db_elems): print("Old database configuration found. " "Conv...
You are a Python code generator, capable of creating scripts from specifications.
def uuid_constructor(loader, node): """" Construct a uuid.UUID object form a scalar YAML node. Tests: >>> yaml.add_constructor("!uuid", uuid_constructor, Loader=yaml.SafeLoader) >>> yaml.safe_load("{'test': !uuid 'cc3702ca-699a-4aa6-8226-4c938f294d9b'}") {'test': UUID('cc3702ca-699a...
Can you write a function in Python 3 where it constructs a uuid. UUID object form a scalar YAML node.
As a Python code analyst, you investigate and solve complex coding mysteries
def uuid_add_implicit_resolver(Loader=ConfigLoader, Dumper=ConfigDumper): """ Attach an implicit pattern resolver for UUID objects. Tests: >>> class TestDumper(yaml.SafeDumper): pass >>> class TestLoader(yaml.SafeLoader): pass >>> TUUID = 'cc3702ca-699a-4aa6-8226-4c938f294d9b' ...
Implement a function in Python 3 to add an implicit pattern resolver for UUID objects.
You are a Python code analyst, evaluating scripts for potential improvements.
def store(self, config_file): """ Store the configuration dictionary to a file.""" selfcopy = copy.deepcopy(self) selfcopy.filter_exports() with open(config_file, 'w') as outf: yaml.dump( selfcopy.node, outf, width=80, ...
Write a Python 3 script for storing the configuration dictionary to a file.
As a Python code analyst, you investigate and solve complex coding mysteries
Load the configuration dictionary from file.
Here you have a function in Python 3, explain what it does def load(self, _from): def load_rec(inode, config): """Recursive part of loading.""" for k in config: if isinstance(config[k], dict) and \ k not in ['value', 'default']: if ...
As a python code expert, you are capable of creating scripts from specifications.
Initialize this node from environment variables.
Make a summary of the following Python 3 code def init_from_env(self): if 'default' in self.node: env_var = self.__to_env_var__().upper() if self.has_value(): env_val = self.node['value'] else: env_val = self.node['default'] env_va...
As a python code expert, you are capable of creating scripts from specifications.
Return the value of the node.
How would you explain what the following Python 3 function does def value(self): def validate(node_value): if hasattr(node_value, 'validate'): node_value.validate() return node_value if 'value' in self.node: return validate(self.node['value']) ...
You are a Python code generator, capable of creating scripts from specifications.
def to_env_dict(self): """Convert configuration object to a flat dictionary.""" entries = {} if self.has_value(): return {self.__to_env_var__(): self.node['value']} if self.has_default(): return {self.__to_env_var__(): self.node['default']} for k in self....
Write a Python 3 script for converting configuration object to a flat dictionary.
As a Python code analyst, you investigate and solve complex coding mysteries
Return a new record with same keys or renamed keys if key found in key_map.
How would you explain what the following Python 3 function does def rename_keys(record: Mapping, key_map: Mapping) -> dict: new_record = dict() for k, v in record.items(): key = key_map[k] if k in key_map else k new_record[key] = v return new_record
As a Python code translator, you convert algorithms and pseudocode into Python.
def replace_keys(record: Mapping, key_map: Mapping) -> dict: """New record with renamed keys including keys only found in key_map.""" return {key_map[k]: v for k, v in record.items() if k in key_map}
Create a Python 3 function to return a new record with renamed keys including keys only found in key_map.
You are a Python code architect, reviewing and designing scalable and efficient code
def inject_nulls(data: Mapping, field_names) -> dict: """Insert None as value for missing fields.""" record = dict() for field in field_names: record[field] = data.get(field, None) return record
Write a Python 3 script for inserting None as value for missing fields.
As a Python code composer, you craft elegant and concise scripts.
def read_struct(fstream): """ Read a likwid struct from the text stream. Args: fstream: Likwid's filestream. Returns (dict(str: str)): A dict containing all likwid's struct info as key/value pairs. """ line = fstream.readline().strip() fragments = line.split(",") fragme...
Write a Python 3 script to read a likwid struct from the text stream.
As a Python code analyst, you investigate and solve complex coding mysteries
Read a likwid table info from the text stream.
Make a summary of the following Python 3 code def read_table(fstream): pos = fstream.tell() line = fstream.readline().strip() fragments = line.split(",") fragments = [x for x in fragments if x is not None] partition = dict() if not len(fragments) >= 4: return None partition["table"]...
As a Python code analyst, you investigate and solve complex coding mysteries
def read_structs(fstream): """ Read all structs from likwid's file stream. Args: fstream: Likwid's output file stream. Returns: A generator that can be used to iterate over all structs in the fstream. """ struct = read_struct(fstream) while struct is not None: ...
Write a Python 3 script for reading all structs from likwid s output file stream.
You are a Python code generator, capable of creating scripts from specifications.
Read all tables from likwid s output file stream.
How would you explain what the following Python 3 function does def read_tables(fstream): table = read_table(fstream) while table is not None: yield table table = read_table(fstream)
As a Python code composer, you craft elegant and concise scripts.
def get_measurements(region, core_info, data, extra_offset=0): """ Get the complete measurement info from likwid's region info. Args: region: The region we took a measurement in. core_info: The core information. data: The raw data. extra_offset (int): default = 0 Return...
Implement a Python 3 function for getting the complete measurement info from likwid s region info.
As a Python code composer, you craft elegant and concise scripts.
Get a complete list of all measurements extracted from likwid s file stream.
How would you explain what the following Python 3 function does def perfcounters(infile): measurements = [] with open(infile, 'r') as in_file: read_struct(in_file) for region_struct in read_structs(in_file): region = region_struct["1"][1] core_info = region_struct["Region...
As a python code expert, you are capable of creating scripts from specifications.
Prepare root logger :param verbose: integer greater than 0 to indicate verbosity level
Given the following Python 3 function, write the documentation def setup_logger(verbose, logfile): level = logging.WARNING if verbose == 1: level = logging.INFO elif verbose > 1: level = logging.DEBUG if logfile: logging.basicConfig(filename=logfile, level=level, format=LOGGING_F...
You are a Python code architect, reviewing and designing scalable and efficient code
def cli_common(doc, **kwargs): """Program initialization for all provided executables """ arguments = docopt(doc, version='hpcbench ' + __version__, **kwargs) setup_logger(arguments['-v'], arguments['--log']) load_components() try: import matplotlib except ImportError: pass ...
Can you create a Python 3 function that programs initialization for all provided executables
As a Python code translator, you convert algorithms and pseudocode into Python.
def shape_path_points(svg_path_d): ''' Parameters ---------- svg_path_d : str ``"d"`` attribute of SVG ``path`` element. Returns ------- list List of coordinates of points found in SVG path. Each point is represented by a dictionary with keys ``x`` and ``y``. ''...
Write a Python 3 script for returning a list of coordinates of points found in SVG path element.
As a Python code composer, you craft elegant and concise scripts.
Convert a SVG file to a pandas. DataFrame.
Can you generate the documentation for the following Python 3 function def svg_shapes_to_df(svg_source, xpath='//svg:path | //svg:polygon', namespaces=INKSCAPE_NSMAP): ''' Construct a data frame with one row per vertex for all shapes in :data:`svg_source``. Arguments --------- ...
You are a Python code analyst, evaluating scripts for potential improvements.
Convert a SVG file to a pandas. DataFrame.
Explain what the following Python 3 code does def svg_polygons_to_df(svg_source, xpath='//svg:polygon', namespaces=INKSCAPE_NSMAP): ''' Construct a data frame with one row per vertex for all shapes (e.g., ``svg:path``, ``svg:polygon``) in :data:`svg_source``. Arguments ------...
You are a Python code architect, reviewing and designing scalable and efficient code
Compute the center point of each polygon shape and the offset of each polygon center point.
Explain what the following Python 3 code does def compute_shape_centers(df_shapes, shape_i_column, inplace=False): ''' Compute the center point of each polygon shape, and the offset of each vertex to the corresponding polygon center point. Parameters ---------- df_shapes : pandas.DataFrame ...
You are a Python code generator, capable of creating scripts from specifications.
Scale the points of the base - of - mass of the input frame by the specified scale.
Can you generate a brief explanation for the following Python 3 code def scale_points(df_points, scale=INKSCAPE_PPmm.magnitude, inplace=False): ''' Translate points such that bounding box is anchored at (0, 0) and scale ``x`` and ``y`` columns of input frame by specified :data:`scale`. Parameters -...
You are a Python code generator, capable of creating scripts from specifications.
Returns a scale factor to fit a_shape into b_shape while a_shape maintaining aspect ratio.
Can you generate a brief explanation for the following Python 3 code def scale_to_fit_a_in_b(a_shape, b_shape): ''' Return scale factor (scalar float) to fit `a_shape` into `b_shape` while maintaining aspect ratio. Arguments --------- a_shape, b_shape : pandas.Series Input shapes contai...
As a Python code composer, you craft elegant and concise scripts.
def fit_points_in_bounding_box(df_points, bounding_box, padding_fraction=0): ''' Return data frame with ``x``, ``y`` columns scaled to fit points from :data:`df_points` to fill :data:`bounding_box` while maintaining aspect ratio. Arguments --------- df_points : pandas.DataFrame A fr...
Write a Python 3 script for fitting the points in a base - box to the given bounding box.
As a Python code analyst, you investigate and solve complex coding mysteries
Fits all points in a base box to a bounding box.
Explain what the following Python 3 code does def fit_points_in_bounding_box_params(df_points, bounding_box, padding_fraction=0): ''' Return offset and scale factor to scale ``x``, ``y`` columns of :data:`df_points` to fill :data:`bounding_box` while maintaining aspect ...
As a Python code composer, you craft elegant and concise scripts.
def remove_layer(svg_source, layer_name): ''' Remove layer(s) from SVG document. Arguments --------- svg_source : str or file-like A file path, URI, or file-like object. layer_name : str or list Layer name or list of layer names to remove from SVG document. Returns ----...
Can you implement a function in Python 3 that removes a layer from SVG document.
As a Python code analyst, you investigate and solve complex coding mysteries
Loader that loads any eggs in sys. path.
Can you generate the documentation for the following Python 3 function def load_eggs(entry_point_name): def _load_eggs(): distributions, errors = working_set.find_plugins(Environment()) for dist in distributions: # pylint: disable=unsupported-membership-test if dist not in w...
As a Python code analyst, you investigate and solve complex coding mysteries
def refsDecl(self): """ ResfDecl expression of the citation scheme :rtype: str :Example: /tei:TEI/tei:text/tei:body/tei:div//tei:l[@n='$1'] """ for refsDecl in self.graph.objects(self.asNode(), RDF_NAMESPACES.TEI.replacementPattern): return str(refsDecl)
Implement a function in Python 3 to return the ResfDecl expression of the citation scheme
You are a Python code generator, capable of creating scripts from specifications.
Sets the file attribute.
Here you have a function in Python 3, explain what it does def file(self, value): if value is not None: assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format("file", value) self.__file = value
As a python code expert, you are capable of creating scripts from specifications.
def directory(self, value): """ Setter for **self.__directory** attribute. :param value: Attribute value. :type value: unicode """ if value is not None: assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format( "d...
Can you write a function in Python 3 where it sets the directory attribute.
You are a Python code architect, reviewing and designing scalable and efficient code
Setter for **self. __require** attribute.
Can you generate the documentation for the following Python 3 function def require(self, value): if value is not None: assert type(value) in (tuple, list), "'{0}' attribute: '{1}' type is not 'tuple' or 'list'!".format( "require", value) self.__require = value
You are a Python code architect, reviewing and designing scalable and efficient code
def module(self, value): """ Setter for **self.__module** attribute. :param value: Attribute value. :type value: ModuleType """ if value is not None: assert type(value) is type(sys), "'{0}' attribute: '{1}' type is not 'module'!".format("module", value) ...
Create a Python 3 function for setting the module attribute.
As a Python code composer, you craft elegant and concise scripts.