output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Returns a generator that returns all the sets of results from Entrez. | Can you generate the documentation for the following Python 3 function
def entrez_sets_of_results(url, retstart=False, retmax=False, count=False) -> Optional[List[requests.Response]]:
if not retstart:
retstart = 0
if not retmax:
retmax = 500
if not count:
count = retmax
retmax... | As a Python code analyst, you investigate and solve complex coding mysteries |
Print all rows in this result query. | Make a summary of the following Python 3 code
def print_runs(query):
if query is None:
return
for tup in query:
print(("{0} @ {1} - {2} id: {3} group: {4}".format(
tup.end, tup.experiment_name, tup.project_name,
tup.experiment_group, tup.run_group))) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_svg_layers(svg_sources):
'''
Collect layers from input svg sources.
Args:
svg_sources (list) : A list of file-like objects, each containing
one or more XML layers.
Returns
-------
(width, height), layers : (int, int), list
The first item in the tuple is the... | How would you implement a function in Python 3 that
returns a list of layers from input SVG sources. | You are a Python code generator, capable of creating scripts from specifications. |
def merge_svg_layers(svg_sources, share_transform=True):
'''
Merge layers from input svg sources into a single XML document.
Args:
svg_sources (list) : A list of file-like objects, each containing
one or more XML layers.
share_transform (bool) : If exactly one layer has a trans... | Can you implement a function in Python 3 that
merges layers from input SVG sources into a single XML document. | You are a Python code analyst, evaluating scripts for potential improvements. |
ben - ub entry point | Explain what the following Python 3 code does
def main(argv=None):
arguments = cli_common(__doc__, argv=argv)
driver = CampaignDriver(arguments['CAMPAIGN-DIR'], expandcampvars=False)
driver(no_exec=True)
if argv is not None:
return driver | As a Python code analyst, you investigate and solve complex coding mysteries |
def count_by(records: Sequence[Dict], field_name: str) -> defaultdict:
"""
Frequency each value occurs in a record sequence for a given field name.
"""
counter = defaultdict(int)
for record in records:
name = record[field_name]
counter[name] += 1
return counter | Implement a Python 3 function for
counting the number of times each value occurs in a record sequence for a given field name. | As a Python code analyst, you investigate and solve complex coding mysteries |
Generate a huge. csv file for the current experiment. | Can you generate the documentation for the following Python 3 function
def generate(self):
exp_name = self.exp_name()
fname = os.path.basename(self.out_path)
fname = "{exp}_{prefix}_{name}{ending}".format(
exp=exp_name,
prefix=os.path.splitext(fname)[0],
endi... | As a Python code composer, you craft elegant and concise scripts. |
def doc(self):
"""Return the metatab document for the URL"""
from metatab import MetatabDoc
t = self.get_resource().get_target()
return MetatabDoc(t.inner) | Write a Python 3 function for
returning the metatab document for the URL | You are a Python code architect, reviewing and designing scalable and efficient code |
ben - doc entry point | Can you tell what is the following Python 3 function doing
def main(argv=None):
arguments = cli_common(__doc__, argv=argv)
campaign_path = arguments['CAMPAIGN-DIR']
driver = CampaignDriver(campaign_path, expandcampvars=False)
with pushd(campaign_path):
render(
template=arguments['--t... | As a python code expert, you are capable of creating scripts from specifications. |
get class string from object | Make a summary of the following Python 3 code
def class_to_str(obj):
mod_str = obj.__module__
name_str = obj.__name__
if mod_str == '__main__':
return name_str
else:
return '.'.join([mod_str, name_str]) | As a Python code translator, you convert algorithms and pseudocode into Python. |
return a directory path to a module | How would you explain what the following Python 3 function does
def get_module_path(module):
return pathlib.Path(
os.path.dirname(os.path.abspath(inspect.getfile(module)))) | As a Python code composer, you craft elegant and concise scripts. |
returns a directory path to data within a module | Can you generate the documentation for the following Python 3 function
def get_data_path(data, module, check_exists=True):
basepath = os.path.dirname(os.path.abspath(inspect.getfile(module)))
if isinstance(data, basestring):
data = [data]
dirpath = os.path.join(basepath, *data)
if check_exist... | As a python code expert, you are capable of creating scripts from specifications. |
return memory usage of python process in MB
| Given the following Python 3 function, write the documentation
def memory_usage():
try:
import psutil
import os
except ImportError:
return _memory_usage_ps()
process = psutil.Process(os.getpid())
mem = process.memory_info()[0] / float(2 ** 20)
return mem | As a python code expert, you are capable of creating scripts from specifications. |
def _memory_usage_ps():
"""return memory usage of python process in MB
>>> isinstance(_memory_usage_ps(),float)
True
"""
out = subprocess.Popen(
['ps', 'v', '-p', str(os.getpid())],
stdout=subprocess.PIPE).communicate()[0].split(b'\n')
vsz_index = out[0].split().index(b'RSS')
... | How would you code a function in Python 3 to
return memory usage of python process in MB >>> is_memory_usage_ps(),float | You are a Python code generator, capable of creating scripts from specifications. |
def load_memit():
"""load memory usage ipython magic,
require memory_profiler package to be installed
to get usage: %memit?
Author: Vlad Niculae <vlad@vene.ro>
Makes use of memory_profiler from Fabian Pedregosa
available at https://github.com/fabianp/memory_profiler
"""
from IPython.co... | Can you create a Python 3 function that
loads memory usage ipython magic and magics class | You are a Python code generator, capable of creating scripts from specifications. |
def parse_tree_from_dict(node, locs):
"""Processes key locations.
Parameters
----------
node: xml.etree.ElementTree.ElementTree.element
Current node.
locs: dict
A dictionary mapping key to a tuple. The tuple can either be 2 or 3
elements long. The first element maps to the l... | Write a Python 3 function that can
process key locations in the xml. etree. ElementTree. elementTree object node. | You are a Python code analyst, evaluating scripts for potential improvements. |
Parse XML into an ElemeTree object. | Can you generate the documentation for the following Python 3 function
def xml_to_root(xml: Union[str, IO]) -> ElementTree.Element:
if isinstance(xml, str):
if '<' in xml:
return ElementTree.fromstring(xml)
else:
with open(xml) as fh:
xml_to_root(fh)
tree ... | You are a Python code analyst, evaluating scripts for potential improvements. |
Creates a new layer and set it as the active. | Can you generate the documentation for the following Python 3 function
def newLayer(self, effect=''):
self.layers.append(Layer(effect = effect))
self.activeLayer = len(self.layers)-1 | As a python code expert, you are capable of creating scripts from specifications. |
def duplicateActiveLayer(self):
"""
Duplicates the current active :py:class:`Layer`.
:rtype: Nothing.
"""
activeLayer = self.layers[self.activeLayer]
newLayer = Layer(data=activeLayer.data, effect=activeLayer.effect)
self.layers.append(newLayer)
self.activeLayer = len(self.layers)-1 | Implement a Python 3 function for
duplicating the current active layer. | You are a Python code architect, reviewing and designing scalable and efficient code |
Merge all the layers together. | Can you generate a brief explanation for the following Python 3 code
def mergeAllLayers(self):
start = time.time()
while(len(self.layers)>1):
self.mergeBottomLayers()
print('merge time:'+str(time.time()-start))
return self.layers[0] | You are a Python code analyst, evaluating scripts for potential improvements. |
Return a dict of term synonyms | Can you tell what is the following Python 3 function doing
def synonyms(self):
syns = {}
for k, v in self._declared_terms.items():
k = k.strip()
if v.get('synonym'):
syns[k.lower()] = v['synonym']
if not '.' in k:
syns[ROOT_TE... | You are a Python code analyst, evaluating scripts for potential improvements. |
Return a dictionary mapping term names to their super terms | Can you generate the documentation for the following Python 3 function
def super_terms(self):
# If the doc already has super terms, we've already parsed something, so
# assume we parsed the declaration, and can use re-use the old decls.
if self.doc and self.doc.super_terms:
return s... | As a Python code analyst, you investigate and solve complex coding mysteries |
Return the declared sections terms and synonyms as a dict | Can you generate the documentation for the following Python 3 function
def declare_dict(self):
# Run the parser, if it has not been run yet.
if not self.root:
for _ in self: pass
return {
'sections': self._declared_sections,
'terms': self._declared_terms,
... | As a Python code composer, you craft elegant and concise scripts. |
def substitute_synonym(self, nt):
"""
Replace the record_term and parent_term with a synonym
:param nt:
:return:
"""
if nt.join_lc in self.synonyms:
nt.parent_term, nt.record_term = Term.split_term_lower(self.synonyms[nt.join_lc]); | Create a Python 3 function for
replacing the record_term and parent_term with a synonym | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return parse errors as a dict | How would you explain what the following Python 3 function does
def errors_as_dict(self):
errors = []
for e in self.errors:
errors.append({
'file': e.term.file_name,
'row': e.term.row if e.term else '<unknown>',
'col': e.term.col if e.term el... | You are a Python code architect, reviewing and designing scalable and efficient code |
Given a name try to resolve it to a path or URL to a declaration document. | Can you generate a brief explanation for the following Python 3 code
def find_declare_doc(self, d, name):
path = None
while True:
if exists(name):
path =name
break
try:
# Look for a local document
path = declaratio... | You are a Python code architect, reviewing and designing scalable and efficient code |
Resolve a name or path for an include doc to an absolute path or url | How would you explain what the following Python 3 function does
def find_include_doc(self, d, name):
from metatab import parse_app_url
include_ref = name.strip('/')
if include_ref.startswith('http'):
path = include_ref
else:
if not d:
raise Inclu... | You are a Python code architect, reviewing and designing scalable and efficient code |
Generates a generator that yields term objects handling includes and argument
children. | Here you have a function in Python 3, explain what it does
def generate_terms(self, ref, root, file_type=None):
last_section = root
t = None
if isinstance(ref, Source):
row_gen = ref
ref_path = row_gen.__class__.__name__
else:
row_gen = get_generator... | As a Python code analyst, you investigate and solve complex coding mysteries |
def inherited_children(self, t):
"""Generate inherited children based on a terms InhertsFrom property.
The input term must have both an InheritsFrom property and a defined Section
:param t: A subclassed terms -- has an InheritsFrom value
"""
if not t.get('inheritsfrom'):
... | How would you code a function in Python 3 to
yield the inherited children of the input term | As a python code expert, you are capable of creating scripts from specifications. |
Get remote peer list. | Can you tell what is the following Python 3 function doing
def get_remote_peer_list(self):
'''
listPeer 返回列表
{
"rtn":0,
"peerList": [{
"category": "",
"status": 0,
"name": "GUNNER_HOME",
"vodPort": 43566,
... | As a Python code composer, you craft elegant and concise scripts. |
Get remote task list. | Can you generate a brief explanation for the following Python 3 code
def get_remote_task_list(
self, peer_id, list_type=ListType.downloading, pos=0, number=10):
'''
list 返回列表
{
"recycleNum": 0,
"serverFailNum": 0,
"rtn": 0,
"completeNum... | You are a Python code architect, reviewing and designing scalable and efficient code |
Check if a URL is in the list of URLs. | Here you have a function in Python 3, explain what it does
def check_url(self, pid, url_list):
'''
urlCheck 返回数据
{
"rtn": 0,
"taskInfo": {
"failCode": 0,
"name": ".HDTVrip.1024X576.mkv",
"url": "ed2k://|file|%E6%B0%",
... | You are a Python code generator, capable of creating scripts from specifications. |
def add_tasks_to_remote(self, pid, path='C:/TDDOWNLOAD/', task_list=[]):
'''
post data:
{
"path":"C:/TDDOWNLOAD/",
"tasks":[{
"url":"ed2k://|file|%E6%B0%B8%E6%81%92.Forever...",
"name":"永恒.Forever.S01E02.中英字幕.WEB-HR.mkv",
"g... | Implement a Python 3 function for
adding tasks to remote | As a Python code analyst, you investigate and solve complex coding mysteries |
Read text and get there reffs | Can you generate a brief explanation for the following Python 3 code
def read_levels(text):
x = []
for i in range(0, len(NAUTILUSRESOLVER.getMetadata(text).citation)):
x.append(NAUTILUSRESOLVER.getReffs(text, level=i))
return x | As a Python code translator, you convert algorithms and pseudocode into Python. |
def FlaskNautilusManager(resolver, flask_nautilus):
""" Provides a manager for flask scripts to perform specific maintenance operations
:param resolver: Nautilus Extension Instance
:type resolver: NautilusCtsResolver
:param flask_nautilus: Flask Application
:type flask_nautilus: FlaskNautilus
:... | Write a Python 3 function for
providing a manager for flask scripts to perform specific maintenance operations :param resolver: Nautilus Extension Instance :type resolver: NautilusCtsResolver :param flask_nautilus: Flask Application :type flask_nautilus: FlaskNautilus :return: CLI :rtype: click.group Import with .. cod... | You are a Python code architect, reviewing and designing scalable and efficient code |
test if object is a list or tuple | How would you explain what the following Python 3 function does
def is_iter_non_string(obj):
if isinstance(obj, list) or isinstance(obj, tuple):
return True
return False | As a Python code translator, you convert algorithms and pseudocode into Python. |
def is_dict_like(obj, attr=('keys', 'items')):
"""test if object is dict like"""
for a in attr:
if not hasattr(obj, a):
return False
return True | Create a Python 3 function for
testing if object is dict like | You are a Python code generator, capable of creating scripts from specifications. |
def is_list_of_dict_like(obj, attr=('keys', 'items')):
"""test if object is a list only containing dict like items """
try:
if len(obj) == 0:
return False
return all([is_dict_like(i, attr) for i in obj])
except Exception:
return False | Create a Python 3 function to
test if object is a list containing dict like items | As a python code expert, you are capable of creating scripts from specifications. |
test if object is pathlib. Path like | Here you have a function in Python 3, explain what it does
def is_path_like(obj, attr=('name', 'is_file', 'is_dir', 'iterdir')):
for a in attr:
if not hasattr(obj, a):
return False
return True | As a Python code translator, you convert algorithms and pseudocode into Python. |
def convert_type(d, intype, outtype, convert_list=True, in_place=True):
""" convert all values of one type to another
Parameters
----------
d : dict
intype : type_class
outtype : type_class
convert_list : bool
whether to convert instances inside lists and tuples
in_place : bool
... | How would you implement a function in Python 3 that
converts all values of one type to another type | As a python code expert, you are capable of creating scripts from specifications. |
Pretty print a nested dict in readable format | Explain what the following Python 3 code does
def pprint(d, lvlindent=2, initindent=0, delim=':',
max_width=80, depth=3, no_values=False,
align_vals=True, print_func=None,
keycolor=None, compress_lists=None,
round_floats=None, _dlist=False):
""" print a nested dict in rea... | As a python code expert, you are capable of creating scripts from specifications. |
extract section of dictionary d | Given the following Python 3 function, write the documentation
def extract(d, path=None):
path = [] if path is None else path
d_new = copy.deepcopy(d)
d_sub = d_new
for key in path[:-1]:
d_sub = d_sub[key]
key = path[-1]
d_extract = {key: d_sub[key]}
d_sub.pop(key)
return d_ne... | You are a Python code analyst, evaluating scripts for potential improvements. |
def indexes(dic, keys=None):
""" index dictionary by multiple keys
Parameters
----------
dic : dict
keys : list
Examples
--------
>>> d = {1:{"a":"A"},2:{"b":"B"}}
>>> indexes(d,[1,'a'])
'A'
"""
keys = [] if keys is None else keys
assert hasattr(dic, 'keys')
... | Write a Python 3 script for
indexing dictionary by multiple keys | As a Python code translator, you convert algorithms and pseudocode into Python. |
def flatten(d, key_as_tuple=True, sep='.', list_of_dicts=None, all_iters=None):
""" get nested dict as flat {key:val,...},
where key is tuple/string of all nested keys
Parameters
----------
d : object
key_as_tuple : bool
whether keys are list of nested keys or delimited string of nested... | Write a Python 3 script for
getting nested dict as flat dict | You are a Python code analyst, evaluating scripts for potential improvements. |
merges a into b | Given the following Python 3 function, write the documentation
def _single_merge(a, b, error_path=None, overwrite=False,
append=False, list_of_dicts=False):
"""merges b into a
"""
if error_path is None:
error_path = []
if list_of_dicts and is_list_of_dict_like(a) and is_list_o... | As a python code expert, you are capable of creating scripts from specifications. |
Merge dicts into a single base base. | Explain what the following Python 3 code does
def merge(dicts, overwrite=False, append=False, list_of_dicts=False):
outdict = copy.deepcopy(dicts[0])
def single_merge(a, b):
return _single_merge(a, b, overwrite=overwrite, append=append,
list_of_dicts=list_of_dicts)
red... | As a Python code composer, you craft elegant and concise scripts. |
get nested dict as dict where key is tuple or delimited string of all - n levels of nested keys or list of dicts with delimiter | Explain what the following Python 3 code does
def flattennd(d, levels=0, key_as_tuple=True, delim='.',
list_of_dicts=None):
""" get nested dict as {key:dict,...},
where key is tuple/string of all-n levels of nested keys
Parameters
----------
d : dict
levels : int
the numbe... | You are a Python code generator, capable of creating scripts from specifications. |
get nested dict as dict where key is tuple or delimited string of all - 1 nested keys | Make a summary of the following Python 3 code
def flatten2d(d, key_as_tuple=True, delim='.',
list_of_dicts=None):
""" get nested dict as {key:dict,...},
where key is tuple/string of all-1 nested keys
NB: is same as flattennd(d,1,key_as_tuple,delim)
Parameters
----------
d : dict
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
remove certain keys from nested dict retaining preceeding paths | Can you generate a brief explanation for the following Python 3 code
def remove_keys(d, keys=None, use_wildcards=True,
list_of_dicts=False, deepcopy=True):
"""remove certain keys from nested dict, retaining preceeding paths
Parameters
----------
keys: list
use_wildcards : bool
... | You are a Python code architect, reviewing and designing scalable and efficient code |
remove paths with at least one branch leading
to certain keyvals from dict d | Make a summary of the following Python 3 code
def remove_keyvals(d, keyvals=None, list_of_dicts=False, deepcopy=True):
keyvals = [] if keyvals is None else keyvals
list_of_dicts = '__list__' if list_of_dicts else None
if hasattr(keyvals, 'items'):
keyvals = [(k, v) for k, v in keyvals.items()]
... | As a Python code composer, you craft elegant and concise scripts. |
def remove_paths(d, keys, list_of_dicts=False, deepcopy=True):
""" remove paths containing certain keys from dict
Parameters
----------
d: dict
keys : list
list of keys to find and remove path
list_of_dicts: bool
treat list of dicts as additional branches
deepcopy: bool
... | Can you create a Python 3 function that
removes paths containing certain keys from dict d | You are a Python code analyst, evaluating scripts for potential improvements. |
def filter_values(d, vals=None, list_of_dicts=False, deepcopy=True):
""" filters leaf nodes of nested dictionary
Parameters
----------
d : dict
vals : list
values to filter by
list_of_dicts: bool
treat list of dicts as additional branches
deepcopy: bool
deepcopy valu... | Implement a Python 3 function for
filtering leaf nodes of nested dictionary d by values vals | As a Python code analyst, you investigate and solve complex coding mysteries |
Filters the nested dictionary d by the given keyvals. | Here you have a function in Python 3, explain what it does
def filter_keyvals(d, keyvals, logic="OR", keep_siblings=False,
list_of_dicts=False, deepcopy=True):
""" filters leaf nodes key:value pairs of nested dictionary
Parameters
----------
d : dict
keyvals : dict or list[tuple]... | You are a Python code architect, reviewing and designing scalable and efficient code |
filter dict by certain keys | Can you generate a brief explanation for the following Python 3 code
def filter_keys(d, keys, use_wildcards=False,
list_of_dicts=False, deepcopy=True):
""" filter dict by certain keys
Parameters
----------
d : dict
keys: list
use_wildcards : bool
if true, can use * (matc... | You are a Python code generator, capable of creating scripts from specifications. |
filter dict by certain paths containing key sets | Can you generate the documentation for the following Python 3 function
def filter_paths(d, paths, list_of_dicts=False, deepcopy=True):
list_of_dicts = '__list__' if list_of_dicts else None
all_keys = [x for y in paths if isinstance(y, tuple) for x in y]
all_keys += [x for x in paths if not isinstance(x, tu... | You are a Python code architect, reviewing and designing scalable and efficient code |
def rename_keys(d, keymap=None, list_of_dicts=False, deepcopy=True):
""" rename keys in dict
Parameters
----------
d : dict
keymap : dict
dictionary of key name mappings
list_of_dicts: bool
treat list of dicts as additional branches
deepcopy: bool
deepcopy values
... | Create a Python 3 function for
renaming keys in dict | As a Python code analyst, you investigate and solve complex coding mysteries |
split an existing key into multiple levels | How would you explain what the following Python 3 function does
def split_key(d, key, new_keys, before=True,
list_of_dicts=False, deepcopy=True):
""" split an existing key(s) into multiple levels
Parameters
----------
d : dict
or dict like
key: str
existing key value
... | You are a Python code generator, capable of creating scripts from specifications. |
def apply(d, leaf_key, func, new_name=None, remove_lkey=True,
list_of_dicts=False, unflatten_level=0, deepcopy=True, **kwargs):
""" apply a function to all values with a certain leaf (terminal) key
Parameters
----------
d : dict
leaf_key : str
name of leaf key
func : callable
... | Can you write a function in Python 3 where it
applies a function to all values with a certain leaf key. | You are a Python code analyst, evaluating scripts for potential improvements. |
combine values with certain leaf keys by a function | How would you explain what the following Python 3 function does
def combine_apply(d, leaf_keys, func, new_name,
unflatten_level=1, remove_lkeys=True, overwrite=False,
list_of_dicts=False, deepcopy=True, **kwargs):
""" combine values with certain leaf (terminal) keys by a function... | As a Python code translator, you convert algorithms and pseudocode into Python. |
split_lists key = list pairs into dicts for each item in the lists
| How would you explain what the following Python 3 function does
def split_lists(d, split_keys, new_name='split',
check_length=True, deepcopy=True):
"""split_lists key:list pairs into dicts for each item in the lists
NB: will only split if all split_keys are present
Parameters
----------... | You are a Python code architect, reviewing and designing scalable and efficient code |
def combine_lists(d, keys=None, deepcopy=True):
"""combine lists of dicts
Parameters
----------
d : dict or list[dict]
keys : list
keys to combine (all if None)
deepcopy: bool
deepcopy values
Example
-------
>>> from pprint import pprint
>>> d = {'path_key': {'a... | Write a Python 3 script to
combine lists of dicts | You are a Python code architect, reviewing and designing scalable and efficient code |
convert a list of dicts to a dict with root keys | Here you have a function in Python 3, explain what it does
def list_to_dict(lst, key=None, remove_key=True):
assert all([is_dict_like(d) for d in lst])
if key is not None:
assert all([key in d for d in lst])
new_dict = {}
for i, d in enumerate(lst):
d = unflatten(flatten(d))
if ... | As a python code expert, you are capable of creating scripts from specifications. |
Returns the difference between two dict_like objects | Here you have a function in Python 3, explain what it does
def diff(new_dict, old_dict, iter_prefix='__iter__',
np_allclose=False, **kwargs):
""" return the difference between two dict_like objects
Parameters
----------
new_dict: dict
old_dict: dict
iter_prefix: str
prefix to u... | As a Python code composer, you craft elegant and concise scripts. |
def to_json(dct, jfile, overwrite=False, dirlevel=0, sort_keys=True, indent=2,
default_name='root.json', **kwargs):
""" output dict to json
Parameters
----------
dct : dict
jfile : str or file_like
if file_like, must have write method
overwrite : bool
whether to over... | Implement a function in Python 3 to
output dict to json | As a python code expert, you are capable of creating scripts from specifications. |
dump dict to json | Can you tell what is the following Python 3 function doing
def dump(dct, jfile, overwrite=False, dirlevel=0, sort_keys=True,
indent=2, default_name='root.json', **kwargs):
""" output dict to json
Parameters
----------
dct : dict
jfile : str or file_like
if file_like, must have writ... | As a Python code analyst, you investigate and solve complex coding mysteries |
def expand_collection_in_dict(d, key, new_items, no_duplicates=True):
"""
Parameters
d: dict
dict in which a key will be inserted/expanded
key: hashable
key in d
new_items: iterable
d[key] will be extended with items in new_items
no_duplicates: bool
avoid insertin... | Can you write a function in Python 3 where it
expands a collection of items in a dict in which a key will be inserted or expanded. | As a Python code composer, you craft elegant and concise scripts. |
def copy(src, dst, only_update=False, copystat=True, cwd=None,
dest_is_dir=False, create_dest_dirs=False, logger=None):
"""
Augmented shutil.copy with extra options and slightly
modified behaviour
Parameters
==========
src: string
path to source file
dst: string
pat... | Implement a function in Python 3 to
augment shutil. copy with extra options and slightly slightly CTYPE modified behaviour | As a Python code translator, you convert algorithms and pseudocode into Python. |
def md5_of_file(path, nblocks=128):
"""
Computes the md5 hash of a file.
Parameters
==========
path: string
path to file to compute hash of
Returns
=======
hashlib md5 hash object. Use .digest() or .hexdigest()
on returned object to get binary or hex encoded string.
"""... | Implement a Python 3 function for
computing the md5 hash of a file. | As a python code expert, you are capable of creating scripts from specifications. |
Returns True if path is non - existant or older than other_path. | Can you tell what is the following Python 3 function doing
def missing_or_other_newer(path, other_path, cwd=None):
cwd = cwd or '.'
path = get_abspath(path, cwd=cwd)
other_path = get_abspath(other_path, cwd=cwd)
if not os.path.exists(path):
return True
if os.path.getmtime(other_path) - 1e-6 ... | As a python code expert, you are capable of creating scripts from specifications. |
def import_module_from_file(filename, only_if_newer_than=None):
"""
Imports (cython generated) shared object file (.so)
Provide a list of paths in `only_if_newer_than` to check
timestamps of dependencies. import_ raises an ImportError
if any is newer.
Word of warning: Python's caching or the O... | Write a Python 3 script to
import a module from a file. | You are a Python code generator, capable of creating scripts from specifications. |
def find_binary_of_command(candidates):
"""
Calls `find_executable` from distuils for
provided candidates and returns first hit.
If no candidate mathces, a RuntimeError is raised
"""
from distutils.spawn import find_executable
for c in candidates:
binary_path = find_executable(c)
... | Implement a function in Python 3 to
find the first binary that can be used for the given list of candidates. | As a Python code analyst, you investigate and solve complex coding mysteries |
def pyx_is_cplus(path):
"""
Inspect a Cython source file (.pyx) and look for comment line like:
# distutils: language = c++
Returns True if such a file is present in the file, else False.
"""
for line in open(path, 'rt'):
if line.startswith('#') and '=' in line:
splitted = ... | Write a Python 3 function that can
check if a Cython source file is a C ++ file. | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_from_metadata_file(cls, dirpath, key):
"""
Get value of key in metadata file dict.
"""
fullpath = os.path.join(dirpath, cls.metadata_filename)
if os.path.exists(fullpath):
d = pickle.load(open(fullpath, 'rb'))
return d[key]
else:
... | Write a Python 3 function that can
get value of key in metadata file dict. | As a python code expert, you are capable of creating scripts from specifications. |
def save_to_metadata_file(cls, dirpath, key, value):
"""
Store `key: value` in metadata file dict.
"""
fullpath = os.path.join(dirpath, cls.metadata_filename)
if os.path.exists(fullpath):
d = pickle.load(open(fullpath, 'rb'))
d.update({key: value})
... | Write a Python 3 function for
saving key value in metadata file dict. | As a Python code translator, you convert algorithms and pseudocode into Python. |
returns a view of the plugin minimal class attribute interface | Can you generate a brief explanation for the following Python 3 code
def view_interfaces(category=None):
if category is not None:
return sorted(_plugins_interface[category][:])
else:
return {k: v[:] for k, v in _plugins_interface.items()} | You are a Python code generator, capable of creating scripts from specifications. |
def view_plugins(category=None):
""" return a view of the loaded plugin names and descriptions
Parameters
----------
category : None or str
if str, apply for single plugin category
Examples
--------
>>> from pprint import pprint
>>> pprint(view_plugins())
{'decoders': {}, ... | Implement a Python 3 function for
returning a view of the loaded plugin names and descriptions for a single plugin category | As a Python code analyst, you investigate and solve complex coding mysteries |
def unload_plugin(name, category=None):
""" remove single plugin
Parameters
----------
name : str
plugin name
category : str
plugin category
Examples
--------
>>> from pprint import pprint
>>> pprint(view_plugins())
{'decoders': {}, 'encoders': {}, 'parsers': {... | How would you implement a function in Python 3 that
unloads a single plugin from the _all_plugins list. | You are a Python code architect, reviewing and designing scalable and efficient code |
def load_plugin_classes(classes, category=None, overwrite=False):
""" load plugins from class objects
Parameters
----------
classes: list
list of classes
category : None or str
if str, apply for single plugin category
overwrite : bool
if True, allow existing plugins to b... | Write a Python 3 function for
loading all plugins from a list of classes. | As a Python code analyst, you investigate and solve complex coding mysteries |
context manager to load plugin classes then unload on exit | How would you explain what the following Python 3 function does
def plugins_context(classes, category=None):
original = {cat: list(_all_plugins[cat].keys()) for cat in _all_plugins}
load_plugin_classes(classes, category, overwrite=True)
# if errors:
# for cat in _all_plugins:
# for name,... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def load_plugins_dir(path, category=None, overwrite=False):
""" load plugins from a directory
Parameters
----------
path : str or path_like
category : None or str
if str, apply for single plugin category
overwrite : bool
if True, allow existing plugins to be overwritten
"""... | Create a Python 3 function for
loading plugins from a directory. | As a Python code analyst, you investigate and solve complex coding mysteries |
load plugins from builtin directories | Make a summary of the following Python 3 code
def load_builtin_plugins(category=None, overwrite=False):
load_errors = []
for cat, path in _plugins_builtin.items():
if cat != category and category is not None:
continue
load_errors += load_plugins_dir(path, cat, overwrite=overwrite)
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Encodes the object obj to a new type in the specified outtype. | Can you tell what is the following Python 3 function doing
def encode(obj, outtype='json', raise_error=False):
for encoder in get_plugins('encoders').values():
if (isinstance(obj, encoder.objclass)
and hasattr(encoder, 'to_{}'.format(outtype))):
return getattr(encoder, 'to_{}'.fo... | As a python code expert, you are capable of creating scripts from specifications. |
decode dict objects via decoder plugins to new type
| Given the following Python 3 function, write the documentation
def decode(dct, intype='json', raise_error=False):
for decoder in get_plugins('decoders').values():
if (set(list(decoder.dict_signature)).issubset(dct.keys())
and hasattr(decoder, 'from_{}'.format(intype))
and getattr... | You are a Python code generator, capable of creating scripts from specifications. |
def parser_available(fpath):
""" test if parser plugin available for fpath
Examples
--------
>>> load_builtin_plugins('parsers')
[]
>>> test_file = StringIO('{"a":[1,2,3.4]}')
>>> test_file.name = 'test.json'
>>> parser_available(test_file)
True
>>> test_file.name = 'test.other... | Can you implement a function in Python 3 that
tests if parser plugin available for fpath | You are a Python code analyst, evaluating scripts for potential improvements. |
def parse(fpath, **kwargs):
""" parse file contents, via parser plugins, to dict like object
NB: the longest file regex will be used from plugins
Parameters
----------
fpath : file_like
string, object with 'open' and 'name' attributes, or
object with 'readline' and 'name' attribut... | Can you create a Python 3 function that
parses file contents via parser plugins to dict like object | You are a Python code architect, reviewing and designing scalable and efficient code |
Colorize text.
Available text colors:
red, green, yellow, blue, magenta, cyan, white.
Available text highlights:
on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan, on_white.
Available attributes:
bold, dark, underline, blink, reverse, concealed.
Examples
--------
... | Make a summary of the following Python 3 code
def colortxt(text, color=None, on_color=None, attrs=None):
_RESET = '\033[0m'
__ISON = True
if __ISON and os.getenv('ANSI_COLORS_DISABLED') is None:
fmt_str = '\033[%dm%s'
if color is not None:
text = fmt_str % (_COLORS[color], text)
... | As a python code expert, you are capable of creating scripts from specifications. |
def from_zipfile(cls, path, filename, encoding, dialect, fields, converters):
"""Read delimited text from zipfile."""
stream = ZipReader(path, filename).readlines(encoding)
return cls(stream, dialect, fields, converters) | Write a Python 3 script for
reading delimited text from zipfile. | As a Python code composer, you craft elegant and concise scripts. |
Read delimited text from a text file. | How would you explain what the following Python 3 function does
def from_file(cls, path, encoding, dialect, fields, converters, field_index):
return cls(open(path, 'r', encoding=encoding), dialect, fields, converters, field_index) | As a Python code composer, you craft elegant and concise scripts. |
def read_bytes(self):
"""Read content into byte string."""
with ZipFile(self.path, mode='r') as archive:
return archive.read(self.filename) | How would you code a function in Python 3 to
read content into byte string. | You are a Python code generator, capable of creating scripts from specifications. |
def readlines_bytes(self):
"""Read content into byte str line iterator."""
with open_zipfile_archive(self.path, self.filename) as file:
for line in file:
yield line.rstrip(b'\r\n') | Can you implement a function in Python 3 that
reads content into byte str line iterator. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def xmlparse(self, file):
""" Parse a XML file
:param file: Opened File
:return: Tree
"""
if self.CACHE_FULL_TEI is True:
return self.get_or(
_cache_key("Nautilus", self.name, "File", "Tree", file.name),
super(ProtoNautilusCtsResolver,... | Write a Python 3 function for
parsing a XML file into a Tree object. | As a Python code composer, you craft elegant and concise scripts. |
Get or set the cache using callback and arguments
| Can you generate the documentation for the following Python 3 function
def get_or(self, cache_key, callback, *args, **kwargs):
cached = self.cache.get(cache_key)
if cached is not None:
return cached
else:
try:
output = callback(*args, **kwargs)
... | As a Python code composer, you craft elegant and concise scripts. |
def read(self, identifier, path=None):
""" Read a text object given an identifier and a path
:param identifier: Identifier of the text
:param path: Path of the text files
:return: Text
"""
if self.CACHE_FULL_TEI is True:
o = self.cache.get(_cache_key(self.tex... | How would you implement a function in Python 3 that
reads a text object given an identifier and a path. | As a Python code composer, you craft elegant and concise scripts. |
Parse a list of directories ans
| Given the following Python 3 function, write the documentation
def parse(self, resource=None):
if resource is None:
resource = self.__resources__
self.inventory = self.dispatcher.collection
try:
self._parse(resource)
except MyCapytain.errors.UndispatchedTextErro... | As a python code expert, you are capable of creating scripts from specifications. |
def getReffs(self, textId, level=1, subreference=None):
""" Retrieve the siblings of a textual node
:param textId: PrototypeText Identifier
:type textId: str
:param level: Depth for retrieval
:type level: int
:param subreference: Passage Reference
:type subrefere... | Write a Python 3 script to
retrieve the siblings of a textual node. | You are a Python code generator, capable of creating scripts from specifications. |
Retrieve a text node from the API and return it | How would you explain what the following Python 3 function does
def getTextualNode(self, textId, subreference=None, prevnext=False, metadata=False):
key = _cache_key("Nautilus", self.name, "Passage", textId, subreference)
o = self.cache.get(key)
if o is not None:
return o
tex... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Retrieve the siblings of a textual node. | How would you explain what the following Python 3 function does
def getSiblings(self, textId, subreference):
key = _cache_key("Nautilus", self.name, "Siblings", textId, subreference)
o = self.cache.get(key)
if o is not None:
return o
passage = self.getTextualNode(textId, subr... | As a Python code analyst, you investigate and solve complex coding mysteries |
Request metadata about a text or a collection of objects. | Here you have a function in Python 3, explain what it does
def getMetadata(self, objectId=None, **filters):
return self.get_or(
_cache_key("Nautilus", self.name, "GetMetadata", objectId),
super(ProtoNautilusCtsResolver, self).getMetadata, objectId
) | You are a Python code architect, reviewing and designing scalable and efficient code |
Dispatches the object in the given directory to the appropriate handler | Given the following Python 3 function, write the documentation
def _dispatch(self, textgroup, directory):
self.dispatcher.dispatch(textgroup, path=directory) | You are a Python code analyst, evaluating scripts for potential improvements. |
def ask(question, default_answer=False, default_answer_str="no"):
"""
Ask for user input.
This asks a yes/no question with a preset default.
You can bypass the user-input and fetch the default answer, if
you set
Args:
question: The question to ask on stdout.
default_answer: The... | Implement a function in Python 3 to
ask for user input. | You are a Python code generator, capable of creating scripts from specifications. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.