output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
def slugify(value): """ Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens.type( """ import re import unicodedata value = str(value) value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('utf8').strip().lower() ...
Implement a function in Python 3 to return a slug of the given string.
As a Python code composer, you craft elegant and concise scripts.
Import an obect as either a fully qualified dotted name
Make a summary of the following Python 3 code def import_name_or_class(name): " Import an obect as either a fully qualified, dotted name, " if isinstance(name, str): # for "a.b.c.d" -> [ 'a.b.c', 'd' ] module_name, object_name = name.rsplit('.',1) # __import__ loads the multi-level of ...
As a Python code composer, you craft elegant and concise scripts.
Return the URL to pip to install HPCBench.
Make a summary of the following Python 3 code def pip_installer_url(version=None): version = version or hpcbench.__version__ version = str(version) if '.dev' in version: git_rev = 'master' if 'TRAVIS_BRANCH' in os.environ: git_rev = version.split('+', 1)[-1] if '.' in...
You are a Python code analyst, evaluating scripts for potential improvements.
def from_file(campaign_file, **kwargs): """Load campaign from YAML file :return: memory representation of the YAML file :rtype: dictionary """ realpath = osp.realpath(campaign_file) if osp.isdir(realpath): campaign_file = osp.join(campaign_file, YAML_CAMPAIGN_FILE) campaign = Config...
Can you create a Python 3 function that loads the campaign from YAML file
As a Python code analyst, you investigate and solve complex coding mysteries
Fill an existing campaign with default values for optional keys
Can you generate a brief explanation for the following Python 3 code def default_campaign( campaign=None, expandcampvars=True, exclude_nodes=None, frozen=True ): """Fill an existing campaign with default values for optional keys :param campaign: dictionary :type campaign: str :param exclude_nod...
You are a Python code generator, capable of creating scripts from specifications.
def get_benchmark_types(campaign): """Get of benchmarks referenced in the configuration :return: benchmarks :rtype: string generator """ for benchmarks in campaign.benchmarks.values(): for name, benchmark in benchmarks.items(): if name != 'sbatch': # exclude special sbatch name...
Write a Python 3 function for getting of benchmarks referenced in the configuration
You are a Python code analyst, evaluating scripts for potential improvements.
Extract metrics from existing campaign
Explain what the following Python 3 code does def get_metrics(campaign, report, top=True): if top and campaign.process.type == 'slurm': for path, _ in report.collect('jobid', with_path=True): for child in ReportNode(path).children.values(): for metrics in get_metrics(campaign, ch...
As a Python code analyst, you investigate and solve complex coding mysteries
def write(self, file): """Write YAML campaign template to the given open file """ render( self.template, file, benchmarks=self.benchmarks, hostname=socket.gethostname(), )
Can you implement a function in Python 3 that writes YAML campaign template to the given open file.
You are a Python code generator, capable of creating scripts from specifications.
Perform node expansion of network section.
Given the following Python 3 function, write the documentation def expand(self): if self.slurm: self._introspect_slurm_cluster() self.network.nodes = self._expand_nodes(self.network.nodes) self._expand_tags()
As a python code expert, you are capable of creating scripts from specifications.
Ensure that the 2 campaigns to merge have been generated from the same campaign. yaml
Here you have a function in Python 3, explain what it does def ensure_has_same_campaigns(self): lhs_yaml = osp.join(self.lhs, 'campaign.yaml') rhs_yaml = osp.join(self.rhs, 'campaign.yaml') assert osp.isfile(lhs_yaml) assert osp.isfile(rhs_yaml) assert filecmp.cmp(lhs_yaml, rhs_y...
You are a Python code architect, reviewing and designing scalable and efficient code
def path_context(self, path): """Build of dictionary of fields extracted from the given path""" prefix = os.path.commonprefix([path, self._path]) relative_path = path[len(prefix) :] relative_path = relative_path.strip(os.sep) attrs = self.CONTEXT_ATTRS for i, elt ...
Write a Python 3 function that can build a dictionary of fields extracted from the given path
You are a Python code generator, capable of creating scripts from specifications.
get children node referenced as children in the report.
Can you generate a brief explanation for the following Python 3 code def children(self): for child in self.data.get('children', []): if osp.exists(osp.join(self.path, child, YAML_REPORT_FILE)): yield child, self.__class__(osp.join(self.path, child))
You are a Python code analyst, evaluating scripts for potential improvements.
Generator function traversing the tree structure to collect values of a specified key.
Can you generate the documentation for the following Python 3 function def collect(self, *keys, **kwargs): if not keys: raise Exception('Missing key') has_values = functools.reduce( operator.__and__, [key in self.data for key in keys], True ) if has_values: ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Same as collect but expects to have only one result.
Can you generate the documentation for the following Python 3 function def collect_one(self, *args, **kwargs): generator = self.collect(*args, **kwargs) try: value = next(generator) except StopIteration: raise Exception("Expected exactly one value don't have any") ...
You are a Python code analyst, evaluating scripts for potential improvements.
def set_beam_prop(self, prop, values, repeat="up"): """ Specify the properties of the beams :param values: :param repeat: if 'up' then duplicate up the structure :return: """ values = np.array(values) if repeat == "up": assert len(values.shape...
Write a Python 3 script to set properties of the beams in the structure.
As a Python code translator, you convert algorithms and pseudocode into Python.
Set the properties of the columns in the structure.
Can you generate a brief explanation for the following Python 3 code def set_column_prop(self, prop, values, repeat="up"): values = np.array(values) if repeat == "up": assert len(values.shape) == 1 values = [values for ss in range(self.n_storeys)] else: assert...
As a Python code translator, you convert algorithms and pseudocode into Python.
def load(self, path): """ Load yaml-formatted config file. Parameters ---------- path : str path to config file """ with open(path) as f: self.config = full_load(f) if self.config is None: sys.stderr.write("War...
Write a Python 3 script to load the config file.
As a python code expert, you are capable of creating scripts from specifications.
def save(self): """ Save current state of config dictionary. """ with open(self.config_file, "w") as f: f.write(dump(self.config, default_flow_style=False))
Create a Python 3 function for saving current state of config dictionary.
As a Python code translator, you convert algorithms and pseudocode into Python.
def register(self, extension, extension_name): """ Register an extension into the Nautilus Router :param extension: Extension :param extension_name: Name of the Extension :return: """ self._extensions[extension_name] = extension self.ROUTES.extend([ t...
Write a Python 3 function for registering an extension into the Nautilus Router
You are a Python code analyst, evaluating scripts for potential improvements.
Set up the Logger for the application.
Make a summary of the following Python 3 code def setLogger(self, logger): self.logger = logger if logger is None: self.logger = logging.getLogger("capitains_nautilus") formatter = logging.Formatter("[%(asctime)s] {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s") ...
You are a Python code architect, reviewing and designing scalable and efficient code
Initiate the extension on the application and return the blueprint for the application that has been registered in app .
Make a summary of the following Python 3 code def init_app(self, app): self.init_blueprint(app) if self.flaskcache is not None: for func, extension_name in self.CACHED: func = getattr(self._extensions[extension_name], func) setattr( self....
As a Python code translator, you convert algorithms and pseudocode into Python.
This method creates the blueprint for the extension and registers routes and filters and connecting the app and the blueprints of the extension.
Can you generate a brief explanation for the following Python 3 code def init_blueprint(self, app): self.blueprint = Blueprint( self.name, self.name, template_folder=resource_filename("capitains_nautilus", "data/templates"), url_prefix=self.prefix ) ...
You are a Python code analyst, evaluating scripts for potential improvements.
def view(self, function_name, extension_name): """ Builds response according to a function name :param function_name: Route name / function name :param extension_name: Name of the extension holding the function :return: Function """ if isinstance(self.Access_Control_Allo...
Write a Python 3 function that can build a response according to a function name and extension name.
As a python code expert, you are capable of creating scripts from specifications.
def script(experiment, projects): """ Prepare a slurm script that executes the experiment for a given project. Args: experiment: The experiment we want to execute projects: All projects we generate an array job for. """ benchbuild_c = local[local.path(sys.argv[0])] slurm_script ...
Implement a Python 3 function for preparing a slurm script that executes the experiment for a given project.
You are a Python code architect, reviewing and designing scalable and efficient code
def fetch_text_structure(urn, endpoint="http://cts.perseids.org/api/cts"): """ Fetches the text structure of a given work from a CTS endpoint. :param urn: the work's CTS URN (at the work-level!, e.g."urn:cts:greekLit:tlg0012.tlg001") :type urn: string :param endpoint: the URL of the CTS end...
Implement a Python 3 function for fetching the text structure of a given work from a CTS endpoint.
As a Python code composer, you craft elegant and concise scripts.
def actions_for_project(self, project): """Execute all actions but don't do anything as extension.""" project.runtime_extension = run.RuntimeExtension(project, self) return self.default_runtime_actions(project)
Implement a Python 3 function for executing all actions but don t do anything as extension.
As a Python code composer, you craft elegant and concise scripts.
Installs erlent and erlent build.
How would you explain what the following Python 3 function does def install_uchroot(_): builddir = local.path(str(CFG["build_dir"].value)) with local.cwd(builddir): erlent_src = local.path('erlent') erlent_git = erlent_src / '.git' erlent_repo = str(CFG['uchroot']['repo']) erlent...
As a Python code translator, you convert algorithms and pseudocode into Python.
def print_summary(num_actions, failed, duration): """ Print a small summary of the executed plan. Args: num_actions (int): Total size of the executed plan. failed (:obj:`list` of :obj:`actions.Step`): List of failed actions. duration: Time we spent executing the plan. """ nu...
Write a Python 3 script to print a small summary of the executed actions.
You are a Python code architect, reviewing and designing scalable and efficient code
Reads the sensor file and stores it as a dictionary.
Given the following Python 3 function, write the documentation def read_json_sensor_file(ffp): sensor_path = ffp si = json.load(open(sensor_path)) for m_type in si: # Convert keys from strings to integers si[m_type] = {int(k): v for k, v in si[m_type].items()} return si
As a Python code composer, you craft elegant and concise scripts.
def get_all_sensor_codes(si, wild_sensor_code): """ Get all sensor sensor_codes that match a wild sensor code :param si: dict, sensor index json dictionary :param wild_sensor_code: str, a sensor code with "*" for wildcards (e.g. ACCX-*-L2C-*) :return: """ mtype_and_ory, x, y, z = wild_senso...
Write a Python 3 script to get all sensor codes that match a wild sensor code
As a Python code translator, you convert algorithms and pseudocode into Python.
Given a sensor number get the full sensor code
Explain what the following Python 3 code does def get_sensor_code_by_number(si, mtype, sensor_number, quiet=False): try: if 'Orientation' in si[mtype][sensor_number]: orientation = si[mtype][sensor_number]['Orientation'] else: orientation = "" return "%s%s-%s-%s-%s" %...
You are a Python code generator, capable of creating scripts from specifications.
Given a sensor code get the motion type and sensor number from the sensor index json dictionary.
How would you explain what the following Python 3 function does def get_mtype_and_number_from_code(si, sensor_code): mtype_and_ory, x, y, z = sensor_code.split("-") if mtype_and_ory[-1] in "XYZ" and "ACCX" not in si: # Need to support old sensor_file.json files. mtype = mtype_and_ory[:-1] else: ...
You are a Python code architect, reviewing and designing scalable and efficient code
Returns a new object of type Extension with the given arguments and keyword arguments.
How would you explain what the following Python 3 function does def PCExtension(*args, **kwargs): vals = {} intercept = { 'build_callbacks': (), # tuple of (callback, args, kwargs) 'link_ext': True, 'build_files': (), 'dist_files': (), # work around stackoverflow.com/questions...
You are a Python code generator, capable of creating scripts from specifications.
def _copy_or_render_source(ext, f, output_dir, render_callback, skip_copy=False): """ Tries to do regex match for each (pattern, target, subsd) tuple in ext.template_regexps for file f. """ # Either render a template or copy the source dirname = os.path.dirname(f) ...
How would you implement a function in Python 3 that copies or render a source file to output_dir.
As a Python code analyst, you investigate and solve complex coding mysteries
Render a python template file to a new location.
Explain what the following Python 3 code does def render_python_template_to(src, dest, subsd, only_update=False, prev_subsd=None, create_dest_dirs=True, logger=None): """ Overload this function if you want to use a template engine such as ...
You are a Python code generator, capable of creating scripts from specifications.
def get_names(self): """ Returns a dict where key is the language and value is the name in that language. Example: {'it':"Sofocle"} """ names = [id for id in self.ecrm_P1_is_identified_by if id.uri == surf.ns.EFRBROO['F12_Name']] self.names = [] for n...
Create a Python 3 function for returning a list of names in that language.
As a Python code composer, you craft elegant and concise scripts.
Adds a new name variant to an author.
Here you have a function in Python 3, explain what it does def add_name(self, name, lang=None): try: assert (lang, name) not in self.get_names() except Exception as e: # TODO: raise a custom exception logger.warning("Duplicate name detected while adding \"%s (lang=%s)...
As a Python code translator, you convert algorithms and pseudocode into Python.
Adds a new name variant to an author.
How would you explain what the following Python 3 function does def add_abbreviation(self, new_abbreviation): try: assert new_abbreviation not in self.get_abbreviations() except Exception as e: # TODO: raise a custom exception logger.warning("Duplicate abbreviation de...
You are a Python code generator, capable of creating scripts from specifications.
def get_abbreviations(self): """ Get abbreviations of the names of the author. :return: a list of strings (empty list if no abbreviations available). """ abbreviations = [] try: type_abbreviation = self.session.get_resource(BASE_URI_TYPES % "abbreviation" ...
Write a Python 3 script for getting abbreviations of the names of the author.
As a python code expert, you are capable of creating scripts from specifications.
Returns the Urn of the HucitAuthor s CTS.
How would you explain what the following Python 3 function does def get_urn(self): # TODO: check type try: type_ctsurn = self.session.get_resource(BASE_URI_TYPES % "CTS_URN" , self.session.get_class(surf.ns.ECRM['E55_Type'])) ur...
As a Python code translator, you convert algorithms and pseudocode into Python.
def set_urn(self,urn): """ Change the CTS URN of the author or adds a new one (if no URN is assigned). """ Type = self.session.get_class(surf.ns.ECRM['E55_Type']) Identifier = self.session.get_class(surf.ns.ECRM['E42_Identifier']) id_uri = "%s/cts_urn"%str(self.subject) ...
Write a Python 3 script for changing the CTS URN of the author or adds a new one.
You are a Python code architect, reviewing and designing scalable and efficient code
Serialises a HucitAuthor to a JSON formatted string.
How would you explain what the following Python 3 function does def to_json(self): names = self.get_names() return json.dumps({ "uri" : self.subject , "urn" : str(self.get_urn()) , "names" : [{"language":lang, "label":label} for lang, label in ...
You are a Python code architect, reviewing and designing scalable and efficient code
def get_titles(self): """TODO""" return [(label.language, unicode(label)) for label in self.efrbroo_P102_has_title.first.rdfs_label]
Write a Python 3 function that can return a list of tuples containing language and title.
As a Python code analyst, you investigate and solve complex coding mysteries
Get the abbreviations of the titles of the work.
How would you explain what the following Python 3 function does def get_abbreviations(self, combine=False): abbreviations = [] try: type_abbreviation = self.session.get_resource(BASE_URI_TYPES % "abbreviation" , self.session.get_class(s...
You are a Python code analyst, evaluating scripts for potential improvements.
def add_text_structure(self, label): """ Adds a citable text structure to the work. """ ts = self.session.get_resource("%s/text_structure" % self.subject , self.session.get_class(surf.ns.HUCIT['TextStructure'])) ts.rdfs_label.append(Literal(...
Implement a Python 3 function for adding a citable text structure to the work.
You are a Python code analyst, evaluating scripts for potential improvements.
Remove any citable text structure from the work.
Given the following Python 3 function, write the documentation def remove_text_structure(self, text_structure): # TODO: delete also TextElements one by one idx = self.hucit_has_structure.index(text_structure) ts = self.hucit_has_structure.pop(idx) ts.remove() self.update() return
As a Python code translator, you convert algorithms and pseudocode into Python.
Instantiate an opus maximum type.
Can you generate a brief explanation for the following Python 3 code def _get_opus_maximum(self): label = """The opux maximum of a given author that is, the only preserved work by that author or the most known one.""" opmax = self.session.get_resource( ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Mark the work as the author s opus maximum.
Here you have a function in Python 3, explain what it does def set_as_opus_maximum(self): # TODO: test if self.is_opus_maximum(): return False else: opmax = self._get_opus_maximum() self.ecrm_P2_has_type = opmax self.update() return True
As a Python code analyst, you investigate and solve complex coding mysteries
def is_opus_maximum(self): """Check whether the work is the author's opus maximum. Two cases: 1. the work is flagged as opus max 2. there is only one work by this author :return: boolean """ opmax = self._get_opus_maximum() types = self.ecrm_P2_has_type ...
Write a Python 3 function for checking whether the work is the author s opus maximum.
As a Python code composer, you craft elegant and concise scripts.
def author(self): """ Returns the author to whom the work is attributed. :return: an instance of `HucitWork` # TODO: check that's the case """ CreationEvent = self.session.get_class(surf.ns.EFRBROO['F27_Work_Conception']) Person = self.session.get_class(surf.ns.EFRBROO['...
Write a Python 3 script to return the author to whom the work is attributed.
You are a Python code generator, capable of creating scripts from specifications.
def to_json(self): """ Serialises a HucitWork to a JSON formatted string. """ titles = self.get_titles() return json.dumps({ "uri" : self.subject , "urn" : str(self.get_urn()) , "titles" : [{"language":lang, "label":label} for lang,...
Can you write a function in Python 3 where it serialises a HucitWork to a JSON formatted string.
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_urn(self): """ TODO """ urn = self.ecrm_P1_is_identified_by.one try: return CTS_URN(urn) except Exception, e: raise e
Write a Python 3 script for getting the ULID of the one - item item.
As a python code expert, you are capable of creating scripts from specifications.
get nodes that belong to a tag
Here you have a function in Python 3, explain what it does def nodes(self, tag): if tag == '*': return sorted(list(set(self.campaign.network.nodes))) definitions = self.campaign.network.tags.get(tag) if definitions is None: return [] nodes = set() for defi...
As a python code expert, you are capable of creating scripts from specifications.
Get execution layer class
Can you tell what is the following Python 3 function doing def execution_cls(self): name = self.campaign.process.type for clazz in [ExecutionDriver, SrunExecutionDriver]: if name == clazz.name: return clazz raise NameError("Unknown execution layer: '%s'" % name)
You are a Python code analyst, evaluating scripts for potential improvements.
Retrieve tags associated to the current node
Can you tell what is the following Python 3 function doing def children(self): tags = {'*'} if self.tag: network_tags = {self.tag: self.campaign.network.tags[self.tag]} else: network_tags = self.campaign.network.tags for tag, configs in network_tags.items(): ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Sets the activated flag.
Here you have a function in Python 3, explain what it does def activated(self, value): if value is not None: assert type(value) is bool, "'{0}' attribute: '{1}' type is not 'bool'!".format("activated", value) self.__activated = value
As a Python code analyst, you investigate and solve complex coding mysteries
def initialized(self, value): """ Setter for **self.__initialized** attribute. :param value: Attribute value. :type value: bool """ if value is not None: assert type(value) is bool, "'{0}' attribute: '{1}' type is not 'bool'!".format("initialized", value) ...
Write a Python 3 function for setting the value of the isSetted attribute.
As a Python code analyst, you investigate and solve complex coding mysteries
Sets Component activation state.
Can you generate the documentation for the following Python 3 function def activate(self): raise NotImplementedError("{0} | '{1}' must be implemented by '{2}' subclasses!".format( self.__class__.__name__, self.activate.__name__, self.__class__.__name__))
As a Python code translator, you convert algorithms and pseudocode into Python.
get nodes of every reservations
Can you generate a brief explanation for the following Python 3 code def reservations(self): command = [SINFO, '--reservation'] output = subprocess.check_output(command, env=SINFO_ENV) output = output.decode() it = iter(output.splitlines()) next(it) for line in it: ...
You are a Python code architect, reviewing and designing scalable and efficient code
Set the object parameters using a dictionary
Given the following Python 3 function, write the documentation def set(self, values): if hasattr(self, "inputs"): for item in self.inputs: if hasattr(self, item): setattr(self, item, values[item])
You are a Python code analyst, evaluating scripts for potential improvements.
def execute_plan(plan): """"Execute the plan. Args: plan (:obj:`list` of :obj:`actions.Step`): The plan we want to execute. Returns: (:obj:`list` of :obj:`actions.Step`): A list of failed actions. """ results = [action() for action in plan] return [result for result in results ...
Write a Python 3 function for executing the plan. Args: plan (:obj:`list` of :obj:`actions.Step`): The plan we want to execute. Returns: (:obj:`list` of :obj:`actions.Step`): A list of failed actions.
As a Python code analyst, you investigate and solve complex coding mysteries
Set log format :param color: Log message is colored :param include_caller: At the end, put a [caller:line-of-code], e.g. [script:123] :return: string of log format
Can you generate a brief explanation for the following Python 3 code def _set_log_format(color, include_caller): level_name = '* %(levelname)1s' time = '%(asctime)s,%(msecs)03d' message = '%(message)s' color_start = '%(color)s' color_end = '%(end_color)s' caller = '[%(module)s:%(lineno)d]' ...
You are a Python code architect, reviewing and designing scalable and efficient code
Format an object s repr method with specific attributes.
Can you tell what is the following Python 3 function doing def format_repr(obj, attributes) -> str: attribute_repr = ', '.join(('{}={}'.format(attr, repr(getattr(obj, attr))) for attr in attributes)) return "{0}({1})".format(obj.__class__.__qualname__, attribute_repr)
As a Python code translator, you convert algorithms and pseudocode into Python.
def build_parameter_descriptions(obj, user_p=None, output="csv", show_none=True, ignore=None, plist=None): """ Creates a list of the decription of all the inputs of an object :param obj: object, that has parameters :param user_p: dict, user defined parameter descriptions :param show_none: if false,...
Write a Python 3 function that can build a list of the decription of all the inputs of an object that have user defined parameters.
As a Python code composer, you craft elegant and concise scripts.
Generates a list of descriptions of all the models
Can you tell what is the following Python 3 function doing def all_descriptions(): para = [] para += build_parameter_descriptions(models.Soil()) + [",,\n"] para += build_parameter_descriptions(models.SoilProfile()) + [",,\n"] para += build_parameter_descriptions(models.Foundation()) + [",,\n"] para ...
You are a Python code architect, reviewing and designing scalable and efficient code
def plot_shapes(df_shapes, shape_i_columns, axis=None, autoxlim=True, autoylim=True, **kwargs): ''' Plot shapes from table/data-frame where each row corresponds to a vertex of a shape. Shape vertices are grouped by `shape_i_columns`. For example, consider the following dataframe: ...
Write a Python 3 script for plotting shapes from table or data frame where each row corresponds to a vertex of .
You are a Python code analyst, evaluating scripts for potential improvements.
def plot_shapes_heat_map(df_shapes, shape_i_columns, values, axis=None, vmin=None, vmax=None, value_formatter=None, color_map=None): ''' Plot polygon shapes, colored based on values mapped onto a colormap. Args ---- df_shapes (pandas.DataFr...
Can you write a function in Python 3 where it plots the polygon shapes colored based on values mapped onto the color map.
You are a Python code architect, reviewing and designing scalable and efficient code
Plots a series of numeric values on a matplotlib axis colored based on values mapped onto the specified color map.
Can you generate the documentation for the following Python 3 function def plot_color_map_bars(values, vmin=None, vmax=None, color_map=None, axis=None, **kwargs): ''' Plot bar for each value in `values`, colored based on values mapped onto the specified color map. Args ---- ...
You are a Python code analyst, evaluating scripts for potential improvements.
Find an executable is a list of directories
Can you generate a brief explanation for the following Python 3 code def find_in_paths(name, paths): for path in paths: file_ = osp.join(path, name) if osp.exists(file_) and not osp.isdir(file_): abs_file = osp.abspath(file_) if os.access(file_, os.X_OK): retu...
As a python code expert, you are capable of creating scripts from specifications.
Utility function to find an executable in PATH
Given the following Python 3 function, write the documentation def find_executable(name, names=None, required=True): path_from_env = os.environ.get(name.upper()) if path_from_env is not None: return path_from_env names = [name] + (names or []) for _name in names: if osp.isabs(_name): ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def physical_cpus(): """Get cpus identifiers, for instance set(["0", "1", "2", "3"]) :return Number of physical CPUs available :rtype: int """ if platform.system() == 'Darwin': ncores = subprocess.check_output( ['/usr/sbin/sysctl', '-n', 'hw.ncpu'], shell=False ) ...
Write a Python 3 script for getting cpus identifiers for instance set([ 0 1 2 3 )
You are a Python code analyst, evaluating scripts for potential improvements.
Shows the single layer.
How would you explain what the following Python 3 function does def showLayer(self, title='', debugText=''): img = PIL.Image.fromarray(self.data, 'RGBA') if debugText!='': draw = PIL.ImageDraw.Draw(img) font = PIL.ImageFont.truetype("DejaVuSansMono.ttf", 24) draw.text((0, 0),debugText,(255,255,255),font=fo...
As a python code expert, you are capable of creating scripts from specifications.
Returns a mapping between data type names and casting functions and or class definitions to convert text into its Python object.
Given the following Python 3 function, write the documentation def make_converters(data_types) -> dict: return {k: TYPE_CASTERS.get(v, v) for k, v in data_types.items()}
As a Python code composer, you craft elegant and concise scripts.
Parses broken JSON that the standard Python JSON module cannot parse.
Explain what the following Python 3 code does def parse_broken_json(json_text: str) -> dict: # Add spacing between Key and Value to prevent parsing error json_text = json_text.replace(":", ": ") json_dict = yaml.load(json_text) return json_dict
As a Python code analyst, you investigate and solve complex coding mysteries
def _executor_script(self): """Create shell-script in charge of executing the benchmark and return its path. """ fd, path = tempfile.mkstemp(suffix='.sh', dir=os.getcwd()) os.close(fd) with open(path, 'w') as ostr: self._write_executor_script(ostr) mod...
Can you write a function in Python 3 where it creates shell - script in charge of executing the benchmark and return its path.
You are a Python code analyst, evaluating scripts for potential improvements.
def _jinja_executor_template(self): """:return Jinja template of the shell-script executor""" template = self.campaign.process.executor_template if template.startswith('#!'): return jinja_environment.from_string(template) else: return jinja_environment.get_templat...
How would you implement a function in Python 3 that returns the Jinja template of the shell - script executor
As a python code expert, you are capable of creating scripts from specifications.
Write the shell script in charge of executing the command
Can you generate a brief explanation for the following Python 3 code def _write_executor_script(self, ostr): environment = self.execution.get('environment') or {} if not isinstance(environment, Mapping): msg = 'Expected mapping for environment but got ' msg += str(type(environmen...
As a Python code analyst, you investigate and solve complex coding mysteries
return command to execute inside the generated shell - script
Make a summary of the following Python 3 code def command(self): exec_prefix = self.parent.parent.parent.config.get('exec_prefix', []) command = self.execution['command'] if isinstance(command, SEQUENCES): command = [arg.format(**self.command_expansion_vars) for arg in command] ...
You are a Python code analyst, evaluating scripts for potential improvements.
get command to execute properly escaped
How would you explain what the following Python 3 function does def command_str(self): if isinstance(self.command, six.string_types): return self.command return ' '.join(map(six.moves.shlex_quote, self.command))
As a Python code analyst, you investigate and solve complex coding mysteries
def popen(self, stdout, stderr): """Build popen object to run :rtype: subprocess.Popen """ self.logger.info('Executing command: %s', self.command_str) return subprocess.Popen([self._executor_script], stdout=stdout, stderr=stderr)
Create a Python 3 function for building popen object to run
You are a Python code architect, reviewing and designing scalable and efficient code
returns a list of dicts with the srun options for a given campaign and configuration
Given the following Python 3 function, write the documentation def srun_cartesian_product(cls, campaign, config): options = copy.copy(cls.common_srun_options(campaign)) options.update(config.get('srun') or {}) options_tuple = [] for k, v in options.items(): if not isinstance(...
You are a Python code architect, reviewing and designing scalable and efficient code
def srun(self): """Get path to srun executable :rtype: string """ commands = self.campaign.process.get('commands', {}) srun = find_executable(commands.get('srun', 'srun')) if six.PY2: srun = srun.encode('utf-8') return srun
How would you implement a function in Python 3 that gets path to srun executable
As a python code expert, you are capable of creating scripts from specifications.
Get options to be given to all srun commands
Given the following Python 3 function, write the documentation def common_srun_options(cls, campaign): default = dict(campaign.process.get('srun') or {}) default.update(output='slurm-%N-%t.stdout', error='slurm-%N-%t.error') return default
As a Python code translator, you convert algorithms and pseudocode into Python.
get command to execute MimeType
Can you tell what is the following Python 3 function doing def command(self): srun_optlist = build_slurm_arguments(self.parent.command.srun or {}) if not isinstance(self.root.network.nodes(self.tag), ConstraintTag): pargs = parse_constraint_in_args(srun_optlist) self.command_expa...
You are a Python code analyst, evaluating scripts for potential improvements.
def srun_nodes(self): """Get list of nodes where to execute the command """ count = self.execution.get('srun_nodes', 0) if isinstance(count, six.string_types): tag = count count = 0 elif isinstance(count, SEQUENCES): return count else: ...
Can you write a function in Python 3 where it gets list of nodes where to execute the command
As a Python code translator, you convert algorithms and pseudocode into Python.
def clear_graph(identifier=None): """ Clean up a graph by removing it :param identifier: Root identifier of the graph :return: """ graph = get_graph() if identifier: graph.destroy(identifier) try: graph.close() except: warn("Unable to close the Graph")
Implement a Python 3 function for cleaning up a graph by removing it
As a Python code translator, you convert algorithms and pseudocode into Python.
Generate a graph and change the global graph to this one
Can you tell what is the following Python 3 function doing def generate_alchemy_graph(alchemy_uri, prefixes=None, identifier="NautilusSparql"): registerplugins() ident = URIRef(identifier) uri = Literal(alchemy_uri) store = plugin.get("SQLAlchemy", Store)(identifier=ident) graph = Graph(store, ident...
You are a Python code analyst, evaluating scripts for potential improvements.
def generate_sleepy_cat_graph(filepath, prefixes=None, identifier="NautilusSparql"): """ Generate a graph and change the global graph to this one :param filepath: A Uri for the graph :param prefixes: A dictionary of prefixes and namespaces to bind to the graph :param identifier: An identifier that will...
Write a Python 3 script for generating a Graph object and bind it to the one we have
As a Python code composer, you craft elegant and concise scripts.
Add the label of the collection in given lang
Can you generate a brief explanation for the following Python 3 code def set_label(self, label, lang): try: self.metadata.add(SKOS.prefLabel, Literal(label, lang=lang)) self.graph.addN([ (self.asNode(), RDFS.label, Literal(label, lang=lang), self.graph), ]) ...
As a Python code composer, you craft elegant and concise scripts.
Returns a list of all the items in the collection.
Can you generate the documentation for the following Python 3 function def members(self): return list( [ self.children_class(child) for child in self.graph.subjects(RDF_NAMESPACES.DTS.parent, self.asNode()) ] )
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns the parent of the current object
Here you have a function in Python 3, explain what it does def parent(self): parent = list(self.graph.objects(self.asNode(), RDF_NAMESPACES.DTS.parent)) if parent: return self.parent_class(parent[0]) return None
You are a Python code analyst, evaluating scripts for potential improvements.
def actions_for_project(self, project): """Compile & Run the experiment with -O3 enabled.""" project.cflags = ["-O3", "-fno-omit-frame-pointer"] project.runtime_extension = time.RunWithTime( run.RuntimeExtension(project, self)) return self.default_runtime_actions(project)
How would you code a function in Python 3 to compile & Run the experiment with - O3 enabled.
As a python code expert, you are capable of creating scripts from specifications.
def to_step_result(func): """Convert a function return to a list of StepResults. All Step subclasses automatically wrap the result of their __call__ method's result with this wrapper. If the result is not a list of StepResult values, one will be generated. result of `[StepResult.OK]`, or conve...
Write a Python 3 script for converting a function return to a list of StepResults.
As a Python code analyst, you investigate and solve complex coding mysteries
def notify_step_begin_end(func): """Print the beginning and the end of a `func`.""" @ft.wraps(func) def wrapper(self, *args, **kwargs): """Wrapper stub.""" cls = self.__class__ on_step_begin = cls.ON_STEP_BEGIN on_step_end = cls.ON_STEP_END for begin_listener in on_...
Implement a function in Python 3 to print the beginning and the end of a `func`.
As a Python code composer, you craft elegant and concise scripts.
def log_before_after(name: str, desc: str): """Log customized stirng before & after running func.""" def func_decorator(f): """Wrapper stub.""" @ft.wraps(f) def wrapper(*args, **kwargs): """Wrapper stub.""" LOG.info("\n%s - %s", name, desc) res = f(*...
Implement a Python 3 function for logging customized stirng before & after running func.
As a python code expert, you are capable of creating scripts from specifications.
Quick view of the MRI data from. hdf5. npz or. dat files.
Can you generate the documentation for the following Python 3 function def quickview(filename, noIFFT=False): ''' Display processed MRI data from `.hdf5`, `.npz`, or `.dat` files. No arguments displays the IFFT of the k-space data. The type of file is guessed by the file extension (i.e., if exte...
As a Python code translator, you convert algorithms and pseudocode into Python.
def euclid(a, b): """returns the Greatest Common Divisor of a and b""" a = abs(a) b = abs(b) if a < b: a, b = b, a while b != 0: a, b = b, a % b return a
Can you implement a function in Python 3 that returns the Greatest Common Divisor of a and b
You are a Python code generator, capable of creating scripts from specifications.
def coPrime(l): """returns 'True' if the values in the list L are all co-prime otherwise, it returns 'False'. """ for i, j in combinations(l, 2): if euclid(i, j) != 1: return False return True
Write a Python 3 script to return True if all the values in the list L are all co - prime otherwise returns False.
As a Python code translator, you convert algorithms and pseudocode into Python.
extendedEuclid returns a tuple of three values x y z such that x is the GCD of a and b is extendedEuclid the GCD of b and x is extendedEuclid the GCD of a and b.
Can you generate the documentation for the following Python 3 function def extendedEuclid(a, b): if a == 0: return b, 0, 1 else: g, y, x = extendedEuclid(b % a, a) return g, x - (b // a) * y, y
As a python code expert, you are capable of creating scripts from specifications.
def modInv(a, m): """returns the multiplicative inverse of a in modulo m as a positive value between zero and m-1""" # notice that a and m need to co-prime to each other. if coPrime([a, m]): linearCombination = extendedEuclid(a, m) return linearCombination[1] % m else: ret...
Can you implement a function in Python 3 that returns the multiplicative inverse of a in modulo m as a positive value between zero and m - 1
You are a Python code generator, capable of creating scripts from specifications.