output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
m is a positive integer. A tuple s of integers is returned such that m = 2^n and d = 2^n.
Given the following Python 3 function, write the documentation def extractTwos(m): # the problem can be break down to count how many '0's are there in # the end of bin(m). This can be done this way: m & a stretch of '1's # which can be represent as (2 ** n) - 1. assert m >= 0 i = 0 while m & (2 ...
You are a Python code analyst, evaluating scripts for potential improvements.
Convert an integer x to base two.
How would you explain what the following Python 3 function does def int2baseTwo(x): # repeating x >>= 1 and x & 1 will do the trick assert x >= 0 bitInverse = [] while x != 0: bitInverse.append(x & 1) x >>= 1 return bitInverse
As a Python code analyst, you investigate and solve complex coding mysteries
returns a ** d n
Can you generate a brief explanation for the following Python 3 code def modExp(a, d, n): assert d >= 0 assert n >= 0 base2D = int2baseTwo(d) base2DLength = len(base2D) modArray = [] result = 1 for i in range(1, base2DLength + 1): if i == 1: modArray.append(a % n) ...
As a Python code analyst, you investigate and solve complex coding mysteries
Returns True if n is likely a pseudo - prime and False otherwise.
Make a summary of the following Python 3 code def millerRabin(n, k): assert n >= 1 # ensure n is bigger than 1 assert k > 0 # ensure k is a positive integer so everything down here makes sense if n == 2: return True # make sure to return True if n == 2 if n % 2 == 0: return...
As a Python code composer, you craft elegant and concise scripts.
def primeSieve(k): """return a list with length k + 1, showing if list[i] == 1, i is a prime else if list[i] == 0, i is a composite, if list[i] == -1, not defined""" def isPrime(n): """return True is given number n is absolutely prime, return False is otherwise.""" for i in range(2,...
Can you write a function in Python 3 where it returns a list with length k + 1 showing the prime of the archive
As a Python code translator, you convert algorithms and pseudocode into Python.
def findAPrime(a, b, k): """Return a pseudo prime number roughly between a and b, (could be larger than b). Raise ValueError if cannot find a pseudo prime after 10 * ln(x) + 3 tries. """ x = random.randint(a, b) for i in range(0, int(10 * math.log(x) + 3)): if millerRabin(x, k): ...
Can you write a function in Python 3 where it finds a pseudo prime number roughly between a and b. Raise ValueError if cannot find a pseudo prime number.
As a Python code analyst, you investigate and solve complex coding mysteries
Generate public and private keys for RSA encryption.
Explain what the following Python 3 code does def newKey(a, b, k): try: p = findAPrime(a, b, k) while True: q = findAPrime(a, b, k) if q != p: break except: raise ValueError n = p * q m = (p - 1) * (q - 1) while True: e = rand...
As a Python code composer, you craft elegant and concise scripts.
Take a list of integers each between 0 and 127 and generates them into a list of blocks of size n using base 256.
Explain what the following Python 3 code does def numList2blocks(l, n): # Note that ASCII printable characters range is 0x20 - 0x7E returnList = [] toProcess = copy.copy(l) ''' copy message ascii list''' if len(toProcess) % n != 0: for i in range(0, n - len(toProcess) % n): ''' a...
As a Python code analyst, you investigate and solve complex coding mysteries
inverse function of numList2blocks.
Make a summary of the following Python 3 code def blocks2numList(blocks, n): toProcess = copy.copy(blocks) returnList = [] for numBlock in toProcess: inner = [] for i in range(0, n): inner.append(numBlock % 256) numBlock >>= 8 inner.reverse() returnLis...
You are a Python code generator, capable of creating scripts from specifications.
def encrypt(message, modN, e, blockSize): """given a string message, public keys and blockSize, encrypt using RSA algorithms.""" numList = string2numList(message) numBlocks = numList2blocks(numList, blockSize) # only one block message = numBlocks[0] # return [modExp(blocks, e, modN) for blocks ...
Implement a Python 3 function for giving a string message public keys and blockSize encrypt using RSA algorithms.
You are a Python code analyst, evaluating scripts for potential improvements.
def decrypt(secret, modN, d, blockSize): """reverse function of encrypt""" numBlocks = [modExp(blocks, d, modN) for blocks in secret] numList = blocks2numList(numBlocks, blockSize) return numList2string(numList)
Implement a Python 3 function for reversing function of encrypt
As a Python code translator, you convert algorithms and pseudocode into Python.
Yields file name if matches a regular expression pattern.
Explain what the following Python 3 code does def match_files(files, pattern: Pattern): for name in files: if re.match(pattern, name): yield name
You are a Python code generator, capable of creating scripts from specifications.
Match files to a pattern within a zip file s content.
Here you have a function in Python 3, explain what it does def match_zipfile_members(zipfile_path: str, pattern: Pattern): with ZipFile(zipfile_path, mode='r') as zfile: members = zfile.namelist() yield from match_files(members, pattern)
As a python code expert, you are capable of creating scripts from specifications.
Yields the names of all files in a directory.
How would you explain what the following Python 3 function does def directory_files(path): for entry in os.scandir(path): if not entry.name.startswith('.') and entry.is_file(): yield entry.name
As a Python code analyst, you investigate and solve complex coding mysteries
def get_file_listing_sha(listing_paths: Iterable) -> str: """Return sha256 string for group of FTP listings.""" return sha256(''.join(sorted(listing_paths)).encode('utf-8')).hexdigest()
Implement a function in Python 3 to return sha256 string for group of FTP listings.
As a python code expert, you are capable of creating scripts from specifications.
def set_button_map(self, button_map): """Set the finger number to button number mapping for tap-to-click. The default mapping on most devices is to have a 1, 2 and 3 finger tap to map to the left, right and middle button, respectively. A device may permit changing the button mapping but disallow specific maps....
Can you implement a function in Python 3 that sets the finger number to button number mapping for tap - to - click.
As a Python code analyst, you investigate and solve complex coding mysteries
This function applies the 3x3 transformation matrix to absolute device coordinates.
Given the following Python 3 function, write the documentation def set_matrix(self, matrix): matrix = (c_float * 6)(*matrix) return self._libinput.libinput_device_config_calibration_set_matrix( self._handle, matrix)
As a python code expert, you are capable of creating scripts from specifications.
Returns the current calibration matrix for this device.
How would you explain what the following Python 3 function does def matrix(self): matrix = (c_float * 6)() rc = self._libinput.libinput_device_config_calibration_get_matrix( self._handle, matrix) return rc, tuple(matrix)
You are a Python code architect, reviewing and designing scalable and efficient code
The descriptive device name as advertised by the kernel and or the hardware itself.
Explain what the following Python 3 code does def name(self): pchar = self._libinput.libinput_device_get_name(self._handle) return string_at(pchar).decode()
As a Python code composer, you craft elegant and concise scripts.
def set_seat_logical_name(self, seat): """Change the logical seat associated with this device by removing the device and adding it to the new seat. This command is identical to physically unplugging the device, then re-plugging it as a member of the new seat. libinput will generate a :attr:`~libinput.constan...
Create a Python 3 function to change the logical seat name associated with this device.
As a Python code translator, you convert algorithms and pseudocode into Python.
def has_button(self, button): """Check if this device has a given button. Args: button (int): Button to check for, see ``input.h`` for button definitions. Returns: bool: :obj:`True` if the device has this button, :obj:`False` if it does not. Raises: AssertionError """ rc = self._libinput.l...
Write a Python 3 function for checking if this device has a given button.
As a Python code composer, you craft elegant and concise scripts.
def has_key(self, key): """Check if a :attr:`~libinput.constant.DeviceCapability.KEYBOARD` device has a given key. Args: key (int): Key to check for, see ``input.h`` for key definitions. Returns: bool: :obj:`True` if the device has this key, :obj:`False` if it does not. Raises: AssertionError "...
Implement a Python 3 function for checking if a keyboard device has a given key.
You are a Python code generator, capable of creating scripts from specifications.
The number of rings a device with the : attr : ~libinput. constant. DeviceCapability. TABLET_PAD_HAS_RINGS.
Can you generate the documentation for the following Python 3 function def num_rings(self): num = self._libinput.libinput_device_tablet_pad_get_num_rings( self._handle) if num < 0: raise AttributeError('This device is not a tablet pad device') return num
As a Python code composer, you craft elegant and concise scripts.
The number of strips a device with the : attr : ~libinput. DeviceCapability. TABLET_PAD_HAS_STRIPS.
Can you generate a brief explanation for the following Python 3 code def num_strips(self): num = self._libinput.libinput_device_tablet_pad_get_num_strips( self._handle) if num < 0: raise AttributeError('This device is not a tablet pad device') return num
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns the number of mode groups available on this device.
Explain what the following Python 3 code does def num_mode_groups(self): num = self._libinput.libinput_device_tablet_pad_get_num_mode_groups( self._handle) if num < 0: raise AttributeError('This device is not a tablet pad device') return num
You are a Python code analyst, evaluating scripts for potential improvements.
Returns the mode group with the given index or None if the group is invalid.
Can you generate the documentation for the following Python 3 function def get_mode_group(self, group): hmodegroup = self._libinput.libinput_device_tablet_pad_get_mode_group( self._handle, group) if hmodegroup: return TabletPadModeGroup(hmodegroup, self._libinput) return None
You are a Python code generator, capable of creating scripts from specifications.
def logical_name(self): """The logical name of the seat. This is an identifier to group sets of devices within the compositor. Returns: str: The logical name of this seat. """ pchar = self._libinput.libinput_seat_get_logical_name(self._handle) return string_at(pchar).decode()
Write a Python 3 script for returning the logical name of the seat.
As a python code expert, you are capable of creating scripts from specifications.
Load logging configuration from our own defaults.
Here you have a function in Python 3, explain what it does def configure(): log_levels = { 5: logging.NOTSET, 4: logging.DEBUG, 3: logging.INFO, 2: logging.WARNING, 1: logging.ERROR, 0: logging.CRITICAL } logging.captureWarnings(True) root_logger = loggin...
As a Python code translator, you convert algorithms and pseudocode into Python.
Get the number of the ISO - 8601 ISO - 8601 ISO - 8601 ISO - 8601.
How would you explain what the following Python 3 function does def get_number(self): ''' .. versionchanged:: 0.9.2 Add support for float exponent strings (e.g., ``3.435e-7``). Fixes `issue #4 <https://github.com/wheeler-microfluidics/svg-model/issues/4>`. ''' nu...
As a Python code analyst, you investigate and solve complex coding mysteries
Parse the data into a list of tuples.
How would you explain what the following Python 3 function does def to_tuples(self, data): ''' path_data : string, from an svg path tag's 'd' attribute, eg: 'M 46,74 L 35,12 l 53,-13 z' returns the same data collected in a list of tuples, eg: [ ('M', 46, 74), ('L', 35, 12...
As a Python code composer, you craft elegant and concise scripts.
def to_loops(self, commands): ''' commands : list of tuples, as output from to_tuples() method, eg: [('M', 1, 2), ('L', 3, 4), ('L', 5, 6), ('z')] Interprets the command characters at the start of each tuple to return a list of loops, where each loop is a closed list of verts...
Write a Python 3 function that can convert a list of command characters to a list of loops.
As a Python code composer, you craft elegant and concise scripts.
def parse_color(self, color): ''' color : string, eg: '#rrggbb' or 'none' (where rr, gg, bb are hex digits from 00 to ff) returns a triple of unsigned bytes, eg: (0, 128, 255) ''' if color == 'none': return None return ( int(color[1:3], 16)...
Implement a function in Python 3 to parse a color string into a tuple of integers.
You are a Python code analyst, evaluating scripts for potential improvements.
Parses a style string into a color tuple.
Explain what the following Python 3 code does def parse_style(self, style): ''' style : string, eg: fill:#ff2a2a;fill-rule:evenodd;stroke:none;stroke-width:1px; stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1 returns color as a triple of unsigned bytes: (r, g, ...
As a Python code analyst, you investigate and solve complex coding mysteries
def parse(self, tag): ''' returns (id, path) where: 'id' is the path tag's id attribute 'path' is a populated instance of SvgPath >>> from lxml import etree >>> from lxml.builder import E >>> path_tag = etree.XML(""" ... <path id="path0" ...
Write a Python 3 function that can parse the XML tag and returns the id attribute and path attribute of the current level.
As a Python code translator, you convert algorithms and pseudocode into Python.
Validate the response and raise RequestException if not ok
How would you explain what the following Python 3 function does def _validate_response(response): try: response.raise_for_status() except requests.RequestException: raise RequestException( code=response.status_code, url=response.url, ...
You are a Python code analyst, evaluating scripts for potential improvements.
Validate request before calling API
How would you explain what the following Python 3 function does def _validate_request(endpoint, file_type='json', data=None, params=None): if not isinstance(endpoint, string_types) or endpoint.strip() == '': raise ClientException("Must submit `endpoint` for DHIS2 API") if not isinstance(file...
You are a Python code architect, reviewing and designing scalable and efficient code
def _make_request(self, method, endpoint, **kwargs): """ Do the actual request with supplied HTTP method :param method: HTTP method :param endpoint: DHIS2 API endpoint :param kwargs: keyword args :return: response if ok, RequestException if not """ if isin...
Write a Python 3 function that can make a request to DHIS2 API.
You are a Python code analyst, evaluating scripts for potential improvements.
Get from DHIS2 API
Make a summary of the following Python 3 code def get(self, endpoint, file_type='json', params=None, stream=False): return self._make_request('get', endpoint, params=params, file_type=file_type, stream=stream)
You are a Python code generator, capable of creating scripts from specifications.
POST to DHIS2 API endpoint
Given the following Python 3 function, write the documentation def post(self, endpoint, json=None, params=None, **kwargs): json = kwargs['data'] if 'data' in kwargs else json return self._make_request('post', endpoint, data=json, params=params)
As a Python code analyst, you investigate and solve complex coding mysteries
This method is used to put a set of unique identifiers.
Can you generate a brief explanation for the following Python 3 code def put(self, endpoint, json=None, params=None, **kwargs): json = kwargs['data'] if 'data' in kwargs else json return self._make_request('put', endpoint, data=json, params=params)
You are a Python code generator, capable of creating scripts from specifications.
PATCH to DHIS2 API endpoint
Can you tell what is the following Python 3 function doing def patch(self, endpoint, json=None, params=None, **kwargs): json = kwargs['data'] if 'data' in kwargs else json return self._make_request('patch', endpoint, data=json, params=params)
You are a Python code analyst, evaluating scripts for potential improvements.
DELETE from DHIS2 :param endpoint: DHIS2 API endpoint :param json: HTTP payload :param params: HTTP parameters (dict) :return: requests.Response object
Can you generate a brief explanation for the following Python 3 code def delete(self, endpoint, json=None, params=None, **kwargs): json = kwargs['data'] if 'data' in kwargs else json return self._make_request('delete', endpoint, data=json, params=params)
As a Python code translator, you convert algorithms and pseudocode into Python.
Get all DHIS2 objects in a single page.
Can you generate the documentation for the following Python 3 function def get_paged(self, endpoint, params=None, page_size=50, merge=False): try: if not isinstance(page_size, (string_types, int)) or int(page_size) < 1: raise ValueError except ValueError: raise Cl...
As a Python code composer, you craft elegant and concise scripts.
GET SQL View data
Make a summary of the following Python 3 code def get_sqlview(self, uid, execute=False, var=None, criteria=None, merge=False): params = {} sqlview_type = self.get('sqlViews/{}'.format(uid), params={'fields': 'type'}).json().get('type') if sqlview_type == 'QUERY': if not isinstance(va...
As a python code expert, you are capable of creating scripts from specifications.
Post a payload in chunks to prevent Request Entity Too Large Timeout errors
Can you tell what is the following Python 3 function doing def post_partitioned(self, endpoint, json, params=None, thresh=1000): if not isinstance(json, dict): raise ClientException('Parameter `json` must be a dict') if not isinstance(thresh, int) or thresh < 2: raise ClientExce...
You are a Python code generator, capable of creating scripts from specifications.
def get_transform(offset, scale): ''' Parameters ---------- offset : pandas.Series Cartesian ``(x, y)`` coordinate of offset origin. scale : pandas.Series Scaling factor for ``x`` and ``y`` dimensions. Returns ------- pandas.DataFrame 3x3 transformation matrix re...
Can you implement a function in Python 3 that returns a DataFrame with the 3x3 transformation matrix resulting in specified x y and scale.
You are a Python code analyst, evaluating scripts for potential improvements.
def find_shape(self, canvas_x, canvas_y): ''' Look up shape based on canvas coordinates. ''' shape_x, shape_y, w = self.canvas_to_shapes_transform.dot([canvas_x, canvas_y, ...
Implement a function in Python 3 to look up shape based on canvas coordinates.
You are a Python code analyst, evaluating scripts for potential improvements.
def get_shape_areas(df_shapes, shape_i_columns, signed=False): ''' Return a `pandas.Series` indexed by `shape_i_columns` (i.e., each entry corresponds to a single shape/polygon), containing the following columns the area of each shape. If `signed=True`, a positive area value corresponds to a clockw...
How would you code a function in Python 3 to return a pandas. Series indexed by shape_i_columns containing the area of each shape.
As a python code expert, you are capable of creating scripts from specifications.
Return a pandas. DataFrame indexed by shape_i_columns containing the minimum and maximum bounding boxes of the shape.
Can you generate the documentation for the following Python 3 function def get_bounding_boxes(df_shapes, shape_i_columns): ''' Return a `pandas.DataFrame` indexed by `shape_i_columns` (i.e., each row corresponds to a single shape/polygon), containing the following columns: - `width`: The width of the ...
You are a Python code generator, capable of creating scripts from specifications.
def get_shape_infos(df_shapes, shape_i_columns): ''' Return a `pandas.DataFrame` indexed by `shape_i_columns` (i.e., each row corresponds to a single shape/polygon), containing the following columns: - `area`: The area of the shape. - `width`: The width of the widest part of the shape. - `he...
Write a Python 3 function that can return a pandas. DataFrame indexed by shape_i_columns containing the information about the shape.
You are a Python code generator, capable of creating scripts from specifications.
def get_bounding_box(df_points): ''' Calculate the bounding box of all points in a data frame. ''' xy_min = df_points[['x', 'y']].min() xy_max = df_points[['x', 'y']].max() wh = xy_max - xy_min wh.index = 'width', 'height' bbox = pd.concat([xy_min, wh]) bbox.name = 'bounding_box' ...
Can you write a function in Python 3 where it calculates the bounding box of all points in a data frame.
You are a Python code analyst, evaluating scripts for potential improvements.
Decoder for parsing typical objects like uuid s and dates.
Can you generate the documentation for the following Python 3 function def json_decoder_hook(dct, str_decoders=STRING_DECODERS, converters=MappingProxyType(dict())) -> dict: """Decoder for parsing typical objects like uuid's and dates.""" for k, v in dct.items(): if k in converter...
As a python code expert, you are capable of creating scripts from specifications.
Create a JSON decoder hook for typical deserialization scenarios.
Can you tell what is the following Python 3 function doing def make_json_decoder_hook(str_decoders=STRING_DECODERS, extra_str_decoders=tuple(), converters=MappingProxyType(dict())) -> Callable: """Customize JSON string decoder hooks. Object hook for typical...
As a Python code translator, you convert algorithms and pseudocode into Python.
Wait for asynchronous jobs to complete in the given campaign.
Can you tell what is the following Python 3 function doing def wait_for_completion(report, interval=10): for jobid in report.collect('jobid'): try: if not Job.finished(jobid): logging.info('waiting for SLURM job %s', jobid) time.sleep(interval) whi...
You are a Python code architect, reviewing and designing scalable and efficient code
def getColors_Triad(hue=None, sat = 1, val = 1, spread = 60): """ Create a palette with one main color and two opposite color evenly spread apart from the main one. :param hue: A 0-1 float with the starting hue value. :param sat: A 0-1 float with the palette saturation. :param val: A 0-1 float with the palette v...
How would you code a function in Python 3 to return a list of colors with one main color and two opposite color evenly spread apart from the main one.
You are a Python code architect, reviewing and designing scalable and efficient code
Returns the default job name if not already specified in the batch section.
Can you generate a brief explanation for the following Python 3 code def default_job_name(self): name = '' if not self.root.existing_campaign: campaign_file = osp.basename(self.root.campaign_file) campaign = osp.splitext(campaign_file)[0] name += campaign + '/' ...
You are a Python code architect, reviewing and designing scalable and efficient code
def sbatch_template(self): """:return Jinja sbatch template for the current tag""" template = self.sbatch_template_str if template.startswith('#!'): # script is embedded in YAML return jinja_environment.from_string(template) return jinja_environment.get_template(t...
Create a Python 3 function to return the Jinja sbatch template for the current tag
You are a Python code analyst, evaluating scripts for potential improvements.
def sbatch_template_str(self): """:return Jinja sbatch template for the current tag as string""" templates = self.campaign.process.sbatch_template if isinstance(templates, Mapping): # find proper template according to the tag template = templates.get(self.tag) ...
Can you write a function in Python 3 where it returns Jinja sbatch template for the current tag as string
As a python code expert, you are capable of creating scripts from specifications.
Write the SBATCH template to the output stream
Can you generate a brief explanation for the following Python 3 code def _create_sbatch(self, ostr): properties = dict( sbatch_arguments=self.sbatch_args, hpcbench_command=self.hpcbench_cmd ) try: self.sbatch_template.stream(**properties).dump(ostr) except jinja2....
You are a Python code architect, reviewing and designing scalable and efficient code
Execute the SBATCH command and return the job id
Given the following Python 3 function, write the documentation def _execute_sbatch(self): commands = self.campaign.process.get('commands', {}) sbatch = find_executable(commands.get('sbatch', 'sbatch')) sbatch_command = [sbatch, '--parsable', self.sbatch_filename] try: self.lo...
As a Python code analyst, you investigate and solve complex coding mysteries
def partition_ordered(sequence, key=None): """Partition ordered sequence by key. Sequence is expected to already be ordered. Parameters ---------- sequence: iterable data. key: partition key function Yields ------- iterable tuple(s) of partition key, data list pairs. Examples...
How would you code a function in Python 3 to partition ordered sequence by key.
You are a Python code architect, reviewing and designing scalable and efficient code
Use a predicate to partition true and false entries.
Can you tell what is the following Python 3 function doing def partition(predicate, iterable): t1, t2 = tee(iterable) return filterfalse(predicate, t1), filter(predicate, t2)
As a Python code translator, you convert algorithms and pseudocode into Python.
def PortageFactory(name, NAME, DOMAIN, BaseClass=autoportage.AutoPortage): """ Create a new dynamic portage project. Auto-Generated projects can only be used for compilie-time experiments, because there simply is no run-time test defined for it. Therefore, we implement the run symbol as a noop (wit...
Write a Python 3 function that can create a new dynamic portage project.
As a Python code translator, you convert algorithms and pseudocode into Python.
def apply_unitschema(data, uschema, as_quantity=True, raise_outerr=False, convert_base=False, use_wildcards=False, list_of_dicts=False): """ apply the unit schema to the data Parameters ---------- data : dict uschema : dict units schema to apply ...
How would you implement a function in Python 3 that applies the units schema to the data and return the result as a pint. Quantity object
You are a Python code architect, reviewing and designing scalable and efficient code
def split_quantities(data, units='units', magnitude='magnitude', list_of_dicts=False): """ split pint.Quantity objects into <unit,magnitude> pairs Parameters ---------- data : dict units : str name for units key magnitude : str name for magnitude key lis...
Can you create a Python 3 function that splits quantities into a single object
As a Python code translator, you convert algorithms and pseudocode into Python.
Combine quantities into single object.
Here you have a function in Python 3, explain what it does def combine_quantities(data, units='units', magnitude='magnitude', list_of_dicts=False): """ combine <unit,magnitude> pairs into pint.Quantity objects Parameters ---------- data : dict units : str name of unit...
You are a Python code architect, reviewing and designing scalable and efficient code
Returns a version of a project from the cache directory.
Can you tell what is the following Python 3 function doing def get_version_from_cache_dir(src_file): if src_file is None: return None tmp_dir = local.path(str(CFG["tmp_dir"])) if tmp_dir.exists(): cache_file = tmp_dir / src_file dir_hash = get_hash_of_dirs(cache_file) if dir...
As a Python code analyst, you investigate and solve complex coding mysteries
Get the git commit hash of HEAD from a file system url.
Explain what the following Python 3 code does def get_git_hash(from_url): from benchbuild.utils.cmd import git if from_url is None: return "" if not path.exists(from_url): return "" with local.cwd(from_url): return git("rev-parse", "HEAD", retcode=None)
You are a Python code generator, capable of creating scripts from specifications.
Fetch the output of a.
Explain what the following Python 3 code does def fetch_time_output(marker, format_s, ins): from parse import parse timings = [x for x in ins if marker in x] res = [parse(format_s, t) for t in timings] return [_f for _f in res if _f]
You are a Python code generator, capable of creating scripts from specifications.
Conver a path string to a list of path elements.
How would you explain what the following Python 3 function does def path_to_list(pathstr): return [elem for elem in pathstr.split(os.path.pathsep) if elem]
As a Python code composer, you craft elegant and concise scripts.
def determine_path(): """Borrowed from wxglade.py""" root = __file__ if os.path.islink(root): root = os.path.realpath(root) return os.path.dirname(os.path.abspath(root))
Create a Python 3 function to borrow from wxglade. py
As a Python code composer, you craft elegant and concise scripts.
def template_files(path, exts=None): """ Return a list of filenames found at @path. The list of filenames can be filtered by extensions. Arguments: path: Existing filepath we want to list. exts: List of extensions to filter by. Returns: A list of filenames found in the pat...
Create a Python 3 function for returning a list of filenames found at path.
As a Python code translator, you convert algorithms and pseudocode into Python.
def template_str(template): """Read a template file from the resources and return it as str.""" tmpl_file = os.path.join(determine_path(), template) with open(tmpl_file, mode='r') as tmpl_strm: return "".join(tmpl_strm.readlines())
Implement a function in Python 3 to read a template file from the resources and return it as str.
You are a Python code analyst, evaluating scripts for potential improvements.
Create a file inside a uchroot container.
Explain what the following Python 3 code does def mkfile_uchroot(filepath, root="."): from benchbuild.utils.uchroot import no_args, uretry uchroot = no_args() uchroot = uchroot["-E", "-A", "-C", "-w", "/", "-r"] uchroot = uchroot[os.path.abspath(root)] uretry(uchroot["--", "/bin/touch", filepath])
As a Python code composer, you craft elegant and concise scripts.
def mkdir_uchroot(dirpath, root="."): """ Create a file inside a uchroot env. You will want to use this when you need to create a file with apropriate rights inside a uchroot container with subuid/subgid handling enabled. Args: dirpath: The dirpath that should be created. Absol...
Implement a function in Python 3 to create a file inside a uchroot container.
You are a Python code generator, capable of creating scripts from specifications.
def mkdir_interactive(dirpath): """ Create a directory if required. This will query the user for a confirmation. Args: dirname: The path to create. """ from benchbuild.utils.cmd import mkdir if os.path.exists(dirpath): return response = ui.ask( "The directory {...
Can you create a Python 3 function that creates a directory if required.
As a Python code composer, you craft elegant and concise scripts.
From MeasYaps XML root find next sibling of node matching search.
Can you generate a brief explanation for the following Python 3 code def get_val_by_text(root,search): found_flag = False for el in root.iter(): if found_flag: return(el) if el.text == search: # We want the next el found_flag = True
You are a Python code analyst, evaluating scripts for potential improvements.
def readMeasDataVB15(filename, resetFFTscale=False, readOneCoil=False, readPhaseCorInfo=False, readNavigator=False, readTimeStamp=True, nNavEK=False, removeOS=False, ...
Implement a function in Python 3 to read raw data from Siemens MRI scanners with IDEA VB15. Will return an array of measured k-space data from raw data from Siemens MRI scanners using IDEA VB15 (single value). If the option '-I' is used, then image space data will be returned instead. Usage: readMeasDataVB15 filename [...
As a python code expert, you are capable of creating scripts from specifications.
def main(args): '''Function run when called from command line.''' options = { '-rfft': ['resetFFTscale',False], '-r1': ['readOneCoil',False], '-rp': ['readPhaseCorInfo',False], '-rn': ['readNavigator',False], '-skipts': ['readTimeSta...
How would you implement a function in Python 3 that functions run when called from command line.
You are a Python code architect, reviewing and designing scalable and efficient code
def _get_keys_folder(jdir, key_path=None, in_memory=True, ignore_prefix=('.', '_')): """ get json keys from directory structure e.g. jdir sub_dir1 data1.json data2.json sub_dir2 data.json _get_keys_folder(jdir) => ['sub_dir1...
Create a Python 3 function for getting json keys from directory structure
As a Python code composer, you craft elegant and concise scripts.
def jkeys(jfile, key_path=None, in_memory=True, ignore_prefix=('.', '_')): """ get keys for initial json level, or at level after following key_path Parameters ---------- jfile : str, file_like or path_like if str, must be existing file or folder, if file_like, must have 'read' method ...
Write a Python 3 function for getting keys for initial json level or at level after following key_path
As a Python code translator, you convert algorithms and pseudocode into Python.
def _file_with_keys(file_obj, key_path=None, parse_decimal=False): """read json with keys Parameters ---------- file_obj : object object with read method key_path : list[str] key to index befor parsing parse_decimal : bool whether to parse numbers as Decimal instances (r...
Can you implement a function in Python 3 that reads json with keys
As a python code expert, you are capable of creating scripts from specifications.
def _folder_to_json(jdir, key_path=None, in_memory=True, ignore_prefix=('.', '_'), dic={}, parse_decimal=False): """ read in folder structure as json e.g. jdir sub_dir1 data.json sub_dir2 data.json _folder_to_json(jdir) => {'sub_dir1':{'...
Implement a function in Python 3 to read in folder structure as json
You are a Python code generator, capable of creating scripts from specifications.
def to_dict(jfile, key_path=None, in_memory=True, ignore_prefix=('.', '_'), parse_decimal=False): """ input json to dict Parameters ---------- jfile : str, file_like or path_like if str, must be existing file or folder, if file_like, must have 'read' method if path_l...
Write a Python 3 script to input json to dict
As a python code expert, you are capable of creating scripts from specifications.
def chunks(items, chunksize): """Turn generator sequence into sequence of chunks.""" items = iter(items) for first in items: chunk = chain((first,), islice(items, chunksize - 1)) yield chunk deque(chunk, 0)
Implement a function in Python 3 to turn generator sequence into sequence of chunks.
As a Python code analyst, you investigate and solve complex coding mysteries
This function is used to configure the UnionsFS feature.
Can you tell what is the following Python 3 function doing def unionfs(rw='rw', ro=None, union='union'): from functools import wraps def wrap_in_union_fs(func): """ Function that wraps a given function inside the file system. Args: func: The function that needs to be wrappe...
You are a Python code analyst, evaluating scripts for potential improvements.
Updates the list of paths to clean up afterwards.
How would you explain what the following Python 3 function does def __update_cleanup_paths(new_path): cleanup_dirs = settings.CFG["cleanup_paths"].value cleanup_dirs = set(cleanup_dirs) cleanup_dirs.add(new_path) cleanup_dirs = list(cleanup_dirs) settings.CFG["cleanup_paths"] = cleanup_dirs
As a Python code composer, you craft elegant and concise scripts.
def __is_outside_of_builddir(project, path_to_check): """Check if a project lies outside of its expected directory.""" bdir = project.builddir cprefix = os.path.commonprefix([path_to_check, bdir]) return cprefix != bdir
Write a Python 3 function for checking if a project lies outside of its expected directory.
You are a Python code analyst, evaluating scripts for potential improvements.
Setup a unionfs via unionfs - fuse.
How would you explain what the following Python 3 function does def __unionfs_set_up(ro_dir, rw_dir, mount_dir): mount_dir.mkdir() rw_dir.mkdir() if not ro_dir.exists(): LOG.error("Base dir does not exist: '%s'", ro_dir) raise ValueError("Base directory does not exist") from benchbuild....
As a Python code composer, you craft elegant and concise scripts.
Build a regular expression used to extract precision metric from command output
Given the following Python 3 function, write the documentation def get_precision_regex(): expr = re.escape(PRECISION_FORMULA) expr += r'=\s*(\S*)\s.*\s([A-Z]*)' return re.compile(expr)
As a Python code composer, you craft elegant and concise scripts.
def _build_data(self): """Build HPL data from basic parameters""" def baseN(nodes, mpn): return int(math.sqrt(mpn * 0.80 * nodes * 1024 * 1024 / 8)) def nFromNb(baseN, nb): factor = int(baseN / nb) if factor % 2 != 0: factor -= 1 ...
Can you create a Python 3 function that builds HPL data from basic parameters
As a Python code composer, you craft elegant and concise scripts.
Additional options passed as a list to the mpirun command
Can you generate the documentation for the following Python 3 function def mpirun(self): cmd = self.attributes['mpirun'] if cmd and cmd[0] != 'mpirun': cmd = ['mpirun'] return [str(e) for e in cmd]
As a Python code composer, you craft elegant and concise scripts.
def expandvars(s, vars=None): """Perform variable substitution on the given string Supported syntax: * $VARIABLE * ${VARIABLE} * ${#VARIABLE} * ${VARIABLE:-default} :param s: message to expand :type s: str :param vars: dictionary of variables. Default is ``os.environ`` :type v...
How would you implement a function in Python 3 that performs variable substitution on the given string s.
As a Python code translator, you convert algorithms and pseudocode into Python.
def and_(cls, obj, **kwargs): """Query an object :param obj: object to test :param kwargs: query specified in kwargssql :return: `True` if all `kwargs` expression are `True`, `False` otherwise. :rtype: bool """ return cls.__eval_seqexp(obj, ...
Can you implement a function in Python 3 that queries an object and return True if all kwargs are True False otherwise.
As a python code expert, you are capable of creating scripts from specifications.
Query an object :param obj: object to test :param kwargs: query specified in kwargssql :return: `True` if at leat one `kwargs` expression is `True`, `False` otherwise. :rtype: bool
Can you generate the documentation for the following Python 3 function def or_(cls, obj, **kwargs): return cls.__eval_seqexp(obj, operator.or_, **kwargs)
You are a Python code generator, capable of creating scripts from specifications.
Query an object. returns True if exactly one kwargssql is True otherwise False.
How would you explain what the following Python 3 function does def xor(cls, obj, **kwargs): return cls.__eval_seqexp(obj, operator.xor, **kwargs)
You are a Python code architect, reviewing and designing scalable and efficient code
Follow a kwargsql expression starting from a given object and return the deduced object.
Explain what the following Python 3 code does def __resolve_path(cls, obj, path): path = [p for p in path if p] if any(path): pathes = len(path) i = 0 while i < pathes: # _get_obj_attr can supersede `i` because it might # evaluate the e...
As a python code expert, you are capable of creating scripts from specifications.
Apply a kwargsql expression to every item of a sequence and returns it.
Can you generate the documentation for the following Python 3 function def _sequence_map(cls, seq, path): if not any(path): # There is no further kwargsql expression return seq result = [] for item in seq: try: result.append(cls.__resolve_path(...
You are a Python code analyst, evaluating scripts for potential improvements.
def _not(cls, operation): """not operation""" def _wrap(*args, **kwargs): return not operation(*args, **kwargs) return _wrap
Create a Python 3 function to return a function that returns True if the given operation is not met.
You are a Python code generator, capable of creating scripts from specifications.
Populate the list of projects that belong to this experiment.
Make a summary of the following Python 3 code def populate(projects_to_filter=None, group=None): if projects_to_filter is None: projects_to_filter = [] import benchbuild.projects as all_projects all_projects.discover() prjs = ProjectRegistry.projects if projects_to_filter: prjs = {...
You are a Python code analyst, evaluating scripts for potential improvements.