output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Update the relevant filters with provided arguments. | Can you generate a brief explanation for the following Python 3 code
def filter(self, **filters):
for flt, val in self._flt.items():
self._flt[flt] = filters.pop(flt, val)
if filters:
raise error.UnknownFiltersError(filters.keys())
return self | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return the time series data. | Here you have a function in Python 3, explain what it does
def tseries(self):
if self._stagdat['tseries'] is UNDETERMINED:
timefile = self.filename('TimeSeries.h5')
self._stagdat['tseries'] = stagyyparsers.time_series_h5(
timefile, list(phyvars.TIME.keys()))
i... | As a Python code analyst, you investigate and solve complex coding mysteries |
Set of found binary files output by StagYY. | Given the following Python 3 function, write the documentation
def files(self):
if self._rundir['ls'] is UNDETERMINED:
out_stem = pathlib.Path(self.par['ioin']['output_file_stem'] + '_')
out_dir = self.path / out_stem.parent
if out_dir.is_dir():
self._rundir['... | You are a Python code analyst, evaluating scripts for potential improvements. |
def walk(self):
"""Return view on configured steps slice.
Other Parameters:
conf.core.snapshots: the slice of snapshots.
conf.core.timesteps: the slice of timesteps.
"""
if conf.core.snapshots is not None:
return self.snaps[conf.core.snapshots]
... | Write a Python 3 script for
returning view on configured steps slice. | As a Python code composer, you craft elegant and concise scripts. |
def scale(self, data, unit):
"""Scales quantity to obtain dimensionful quantity.
Args:
data (numpy.array): the quantity that should be scaled.
dim (str): the dimension of data as defined in phyvars.
Return:
(float, str): scaling factor and unit string.
... | Implement a Python 3 function for
scaling the data array to obtain dimensionful quantity. | As a Python code composer, you craft elegant and concise scripts. |
Return a pandas. DataFrame containing the time series data between the requested times. | Can you generate a brief explanation for the following Python 3 code
def tseries_between(self, tstart=None, tend=None):
if self.tseries is None:
return None
ndat = self.tseries.shape[0]
if tstart is None:
istart = 0
else:
igm = 0
igp = nd... | You are a Python code analyst, evaluating scripts for potential improvements. |
Return the name of the StagYY output file. | Explain what the following Python 3 code does
def filename(self, fname, timestep=None, suffix='', force_legacy=False):
if timestep is not None:
fname += '{:05d}'.format(timestep)
fname += suffix
if not force_legacy and self.hdf5:
fpath = self.hdf5 / fname
else:
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def binfiles_set(self, isnap):
"""Set of existing binary files at a given snap.
Args:
isnap (int): snapshot index.
Returns:
set of pathlib.Path: the set of output files available for this
snapshot number.
"""
possible_files = set(self.filename... | Write a Python 3 function that can
return a set of existing binary files at a given snapshot number. | You are a Python code analyst, evaluating scripts for potential improvements. |
def _tidy_names(names, nnames, extra_names=None):
"""Truncate or extend names so that its len is nnames.
The list is modified, this function returns nothing.
Args:
names (list): list of names.
nnames (int): desired number of names.
extra_names (list of str): list of names to be use... | Write a Python 3 function for
truncating or extend names so that its len is nnames. | You are a Python code architect, reviewing and designing scalable and efficient code |
Read temporal series text file. | Here you have a function in Python 3, explain what it does
def time_series(timefile, colnames):
if not timefile.is_file():
return None
data = pd.read_csv(timefile, delim_whitespace=True, dtype=str,
header=None, skiprows=1, index_col=0,
engine='c', memory_map... | As a Python code composer, you craft elegant and concise scripts. |
Read temporal series HDF5 file. | Can you generate the documentation for the following Python 3 function
def time_series_h5(timefile, colnames):
if not timefile.is_file():
return None
with h5py.File(timefile, 'r') as h5f:
dset = h5f['tseries']
_, ncols = dset.shape
ncols -= 1 # first is istep
h5names = m... | As a Python code analyst, you investigate and solve complex coding mysteries |
Extract istep and compute list of rows to delete | Explain what the following Python 3 code does
def _extract_rsnap_isteps(rproffile):
step_regex = re.compile(r'^\*+step:\s*(\d+) ; time =\s*(\S+)')
isteps = [] # list of (istep, time, nz)
rows_to_del = set()
line = ' '
with rproffile.open() as stream:
while line[0] != '*':
line =... | You are a Python code generator, capable of creating scripts from specifications. |
def rprof(rproffile, colnames):
"""Extract radial profiles data
If :data:`colnames` is too long, it will be truncated. If it is too short,
additional numeric column names from 0 to N-1 will be attributed to the N
extra columns present in :data:`timefile`.
Args:
rproffile (:class:`pathlib.P... | Implement a function in Python 3 to
extract radial profiles data from a. rprof file. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Extract radial profiles data from a hdf5 file. | Make a summary of the following Python 3 code
def rprof_h5(rproffile, colnames):
if not rproffile.is_file():
return None, None
isteps = []
with h5py.File(rproffile) as h5f:
dnames = sorted(dname for dname in h5f.keys()
if dname.startswith('rprof_'))
ncols = h5... | As a Python code composer, you craft elegant and concise scripts. |
Read n words of 4 or 8 bytes with fmt format. | Can you tell what is the following Python 3 function doing
def _readbin(fid, fmt='i', nwords=1, file64=False, unpack=True):
if fmt in 'if':
fmt += '8' if file64 else '4'
elts = np.fromfile(fid, fmt, nwords)
if unpack and len(elts) == 1:
elts = elts[0]
return elts | As a python code expert, you are capable of creating scripts from specifications. |
Extract fields data from a binary field file. | Can you generate the documentation for the following Python 3 function
def fields(fieldfile, only_header=False, only_istep=False):
# something to skip header?
if not fieldfile.is_file():
return None
header = {}
with fieldfile.open('rb') as fid:
readbin = partial(_readbin, fid)
ma... | You are a Python code architect, reviewing and designing scalable and efficient code |
def tracers(tracersfile):
"""Extract tracers data.
Args:
tracersfile (:class:`pathlib.Path`): path of the binary tracers file.
Returns:
dict of list of numpy.array:
Tracers data organized by attribute and block.
"""
if not tracersfile.is_file():
return None
... | Write a Python 3 script for
extracting tracers data. Args: tracersfile (:class:`pathlib.Path`): path of the binary tracers file. Returns: dict of list of numpy.array: Tracers data organized by attribute and block. | As a python code expert, you are capable of creating scripts from specifications. |
Read the content of a group from a hdf5 file. | Can you tell what is the following Python 3 function doing
def _read_group_h5(filename, groupname):
with h5py.File(filename, 'r') as h5f:
data = h5f[groupname][()]
return data | As a Python code composer, you craft elegant and concise scripts. |
def _make_3d(field, twod):
"""Add a dimension to field if necessary.
Args:
field (numpy.array): the field that need to be 3d.
twod (str): 'XZ', 'YZ' or None depending on what is relevant.
Returns:
numpy.array: reshaped field.
"""
shp = list(field.shape)
if twod and 'X' i... | Write a Python 3 function that can
add a dimension to the field if necessary. | As a Python code composer, you craft elegant and concise scripts. |
Compute number of cores in each direction. | Can you tell what is the following Python 3 function doing
def _ncores(meshes, twod):
nnpb = len(meshes) # number of nodes per block
nns = [1, 1, 1] # number of nodes in x, y, z directions
if twod is None or 'X' in twod:
while (nnpb > 1 and
meshes[nns[0]]['X'][0, 0, 0] ==
... | As a Python code composer, you craft elegant and concise scripts. |
def _conglomerate_meshes(meshin, header):
"""Conglomerate meshes from several cores into one."""
meshout = {}
npc = header['nts'] // header['ncs']
shp = [val + 1 if val != 1 else 1 for val in header['nts']]
x_p = int(shp[0] != 1)
y_p = int(shp[1] != 1)
for coord in meshin[0]:
meshout... | How would you implement a function in Python 3 that
conglomerates meshes from several cores into one. | As a Python code composer, you craft elegant and concise scripts. |
Read all coord hdf5 files of a snapshot. | Can you generate a brief explanation for the following Python 3 code
def _read_coord_h5(files, shapes, header, twod):
meshes = []
for h5file, shape in zip(files, shapes):
meshes.append({})
with h5py.File(h5file, 'r') as h5f:
for coord, mesh in h5f.items():
# for some ... | As a python code expert, you are capable of creating scripts from specifications. |
Extract field from data item. | Here you have a function in Python 3, explain what it does
def _get_field(xdmf_file, data_item):
shp = _get_dim(data_item)
h5file, group = data_item.text.strip().split(':/', 1)
icore = int(group.split('_')[-2]) - 1
fld = _read_group_h5(xdmf_file.parent / h5file, group).reshape(shp)
return icore, fld | You are a Python code analyst, evaluating scripts for potential improvements. |
def _maybe_get(elt, item, info, conversion=None):
"""Extract and convert info if item is present."""
maybe_item = elt.find(item)
if maybe_item is not None:
maybe_item = maybe_item.get(info)
if conversion is not None:
maybe_item = conversion(maybe_item)
return maybe_item | Write a Python 3 script for
extracting and convert info if item is present. | As a python code expert, you are capable of creating scripts from specifications. |
Extract geometry information from hdf5 files. | Can you generate the documentation for the following Python 3 function
def read_geom_h5(xdmf_file, snapshot):
header = {}
xdmf_root = xmlET.parse(str(xdmf_file)).getroot()
if snapshot is None:
return None, xdmf_root
# Domain, Temporal Collection, Snapshot
# should check that this is indeed ... | As a Python code composer, you craft elegant and concise scripts. |
def _to_spherical(flds, header):
"""Convert vector field to spherical."""
cth = np.cos(header['t_mesh'][:, :, :-1])
sth = np.sin(header['t_mesh'][:, :, :-1])
cph = np.cos(header['p_mesh'][:, :, :-1])
sph = np.sin(header['p_mesh'][:, :, :-1])
fout = np.copy(flds)
fout[0] = cth * cph * flds[0]... | How would you implement a function in Python 3 that
converts vector field to spherical. | As a Python code analyst, you investigate and solve complex coding mysteries |
Compute shape of flds variable. | Can you tell what is the following Python 3 function doing
def _flds_shape(fieldname, header):
shp = list(header['nts'])
shp.append(header['ntb'])
# probably a better way to handle this
if fieldname == 'Velocity':
shp.insert(0, 3)
# extra points
header['xp'] = int(header['nts'][0... | As a Python code analyst, you investigate and solve complex coding mysteries |
def _post_read_flds(flds, header):
"""Process flds to handle sphericity."""
if flds.shape[0] >= 3 and header['rcmb'] > 0:
# spherical vector
header['p_mesh'] = np.roll(
np.arctan2(header['y_mesh'], header['x_mesh']), -1, 1)
for ibk in range(header['ntb']):
flds[..... | How would you code a function in Python 3 to
process flds to handle sphericity. | You are a Python code generator, capable of creating scripts from specifications. |
def read_field_h5(xdmf_file, fieldname, snapshot, header=None):
"""Extract field data from hdf5 files.
Args:
xdmf_file (:class:`pathlib.Path`): path of the xdmf file.
fieldname (str): name of field to extract.
snapshot (int): snapshot number.
header (dict): geometry information.... | Create a Python 3 function for
extracting field data from hdf5 files. | You are a Python code architect, reviewing and designing scalable and efficient code |
def read_tracers_h5(xdmf_file, infoname, snapshot, position):
"""Extract tracers data from hdf5 files.
Args:
xdmf_file (:class:`pathlib.Path`): path of the xdmf file.
infoname (str): name of information to extract.
snapshot (int): snapshot number.
position (bool): whether to ext... | Create a Python 3 function for
extracting tracers data from hdf5 files. | As a python code expert, you are capable of creating scripts from specifications. |
def read_time_h5(h5folder):
"""Iterate through (isnap, istep) recorded in h5folder/'time_botT.h5'.
Args:
h5folder (:class:`pathlib.Path`): directory of HDF5 output files.
Yields:
tuple of int: (isnap, istep).
"""
with h5py.File(h5folder / 'time_botT.h5', 'r') as h5f:
for nam... | Implement a Python 3 function for
iterating through the time_botT. h5 files in the directory h5folder. | As a python code expert, you are capable of creating scripts from specifications. |
def _init_shape(self):
"""Determine shape of geometry"""
shape = self._par['geometry']['shape'].lower()
aspect = self._header['aspect']
if self.rcmb is not None and self.rcmb >= 0:
# curvilinear
self._shape['cyl'] = self.twod_xz and (shape == 'cylindrical' or
... | How would you implement a function in Python 3 that
determines shape of geometry | As a python code expert, you are capable of creating scripts from specifications. |
Find file holding data and return its content. | Given the following Python 3 function, write the documentation
def _get_raw_data(self, name):
# try legacy first, then hdf5
filestem = ''
for filestem, list_fvar in self._files.items():
if name in list_fvar:
break
fieldfile = self.step.sdat.filename(filestem, ... | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns the geometry information. | How would you explain what the following Python 3 function does
def geom(self):
if self._header is UNDETERMINED:
binfiles = self.step.sdat.binfiles_set(self.step.isnap)
if binfiles:
self._header = stagyyparsers.fields(binfiles.pop(),
... | As a python code expert, you are capable of creating scripts from specifications. |
Return the time series data of the time step. | Given the following Python 3 function, write the documentation
def timeinfo(self):
if self.istep not in self.sdat.tseries.index:
return None
return self.sdat.tseries.loc[self.istep] | You are a Python code analyst, evaluating scripts for potential improvements. |
def rprof(self):
"""Radial profiles data of the time step.
Set to None if no radial profiles data is available for this time step.
"""
if self.istep not in self.sdat.rprof.index.levels[0]:
return None
return self.sdat.rprof.loc[self.istep] | Create a Python 3 function for
returning the radial profiles data for this time step. | You are a Python code generator, capable of creating scripts from specifications. |
def isnap(self):
"""Snapshot index corresponding to time step.
It is set to None if no snapshot exists for the time step.
"""
if self._isnap is UNDETERMINED:
istep = None
isnap = -1
# could be more efficient if do 0 and -1 then bisection
#... | Can you implement a function in Python 3 that
returns the index of the current snapshot. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def convert_v1_to_v2(
dict # type: Dict[str, Any]
):
# type: (...) -> Dict[str, Any]
"""
Convert v1 schema dict to v2 schema dict.
:param dict: v1 schema dict
:return: v2 schema dict
"""
version = dict['version']
if version != 1:
raise ValueError('Version {} not 1'.f... | Write a Python 3 function that can
convert v1 schema dict to v2 schema dict. | As a Python code composer, you craft elegant and concise scripts. |
def from_json_dict(dct, validate=True):
# type: (Dict[str, Any], bool) -> Schema
""" Create a Schema for v1 or v2 according to dct
:param dct: This dictionary must have a `'features'`
key specifying the columns of the dataset. It must have
a `'version'` key containing the master sch... | Write a Python 3 function for
creating a new schema from a dictionary. | As a Python code composer, you craft elegant and concise scripts. |
def from_json_file(schema_file, validate=True):
# type: (TextIO, bool) -> Schema
""" Load a Schema object from a json file.
:param schema_file: A JSON file containing the schema.
:param validate: (default True) Raise an exception if the
schema does not conform to the master schema.
... | Can you create a Python 3 function that
loads a Schema object from a json file containing the master schema. | You are a Python code architect, reviewing and designing scalable and efficient code |
def _get_master_schema(version):
# type: (Hashable) -> bytes
""" Loads the master schema of given version as bytes.
:param version: The version of the master schema whose path we
wish to retrieve.
:raises SchemaError: When the schema version is unknown. This
usually mean... | Create a Python 3 function for
loading the master schema of given version as bytes. | You are a Python code generator, capable of creating scripts from specifications. |
def validate_schema_dict(schema):
# type: (Dict[str, Any]) -> None
""" Validate the schema.
This raises iff either the schema or the master schema are
invalid. If it's successful, it returns nothing.
:param schema: The schema to validate, as parsed by `json`.
:raises SchemaErro... | Can you create a Python 3 function that
validates the master schema. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Deserialize a base 64 encoded string to a bitarray | How would you explain what the following Python 3 function does
def deserialize_bitarray(ser):
# type: (str) -> bitarray
"""Deserialize a base 64 encoded string to a bitarray (bloomfilter)
"""
ba = bitarray()
ba.frombytes(base64.b64decode(ser.encode(encoding='UTF-8', errors='strict')))
retu... | You are a Python code generator, capable of creating scripts from specifications. |
Given input image returns the results of specified image apis. | Can you tell what is the following Python 3 function doing
def analyze_image(image, apis=DEFAULT_APIS, **kwargs):
cloud = kwargs.pop('cloud', None)
batch = kwargs.pop('batch', False)
api_key = kwargs.pop('api_key', None)
return multi(
data=data_preprocess(image, batch=batch),
dat... | As a Python code analyst, you investigate and solve complex coding mysteries |
Create CLKs from PII_CSV and JSON - formatted CLKs. | Explain what the following Python 3 code does
def hash(pii_csv, keys, schema, clk_json, quiet, no_header, check_header, validate):
schema_object = clkhash.schema.from_json_file(schema_file=schema)
header = True
if not check_header:
header = 'ignore'
if no_header:
header = False
try... | You are a Python code architect, reviewing and designing scalable and efficient code |
def status(server, output, verbose):
"""Connect to an entity matching server and check the service status.
Use "-" to output status to stdout.
"""
if verbose:
log("Connecting to Entity Matching Server: {}".format(server))
service_status = server_get_status(server)
if verbose:
l... | Can you create a Python 3 function that
connects to an entity matching server and check the service status. | You are a Python code analyst, evaluating scripts for potential improvements. |
def create_project(type, schema, server, name, output, verbose):
"""Create a new project on an entity matching server.
See entity matching service documentation for details on mapping type and schema
Returns authentication details for the created project.
"""
if verbose:
log("Entity Matchin... | How would you code a function in Python 3 to
create a new project on an entity matching server. | You are a Python code architect, reviewing and designing scalable and efficient code |
Create a new run on an entity matching server. | Explain what the following Python 3 code does
def create(server, name, project, apikey, output, threshold, verbose):
if verbose:
log("Entity Matching Server: {}".format(server))
if threshold is None:
raise ValueError("Please provide a threshold")
# Create a new run
try:
respons... | As a Python code analyst, you investigate and solve complex coding mysteries |
def upload(clk_json, project, apikey, server, output, verbose):
"""Upload CLK data to entity matching server.
Given a json file containing hashed clk data as CLK_JSON, upload to
the entity resolution service.
Use "-" to read from stdin.
"""
if verbose:
log("Uploading CLK data from {}".... | Can you implement a function in Python 3 that
uploads CLK data to entity matching server. | You are a Python code generator, capable of creating scripts from specifications. |
def results(project, apikey, run, watch, server, output):
"""
Check to see if results are available for a particular mapping
and if so download.
Authentication is carried out using the --apikey option which
must be provided. Depending on the server operating mode this
may return a mask, a linka... | Can you write a function in Python 3 where it
downloads and return the results of a particular run. | You are a Python code analyst, evaluating scripts for potential improvements. |
def generate(size, output, schema):
"""Generate fake PII data for testing"""
pii_data = randomnames.NameList(size)
if schema is not None:
raise NotImplementedError
randomnames.save_csv(
pii_data.names,
[f.identifier for f in pii_data.SCHEMA.fields],
output) | Can you create a Python 3 function that
generates fake PII data for testing | As a Python code translator, you convert algorithms and pseudocode into Python. |
def generate_default_schema(output):
"""Get default schema for fake PII"""
original_path = os.path.join(os.path.dirname(__file__),
'data',
'randomnames-schema.json')
shutil.copyfile(original_path, output) | Write a Python 3 script for
generating default schema for fake PII | As a Python code translator, you convert algorithms and pseudocode into Python. |
def docx_extraction(docx, cloud=None, batch=False, api_key=None, version=None, **kwargs):
"""
Given a .docx file, returns the raw text associated with the given .docx file.
The .docx file may be provided as base64 encoded data or as a filepath.
Example usage:
.. code-block:: python
>>> fro... | Create a Python 3 function to
give a. docx file returns the raw text associated with the given. docx file. | As a Python code composer, you craft elegant and concise scripts. |
Returns a list of 48 dimensional feature vectors explaining that face. | Make a summary of the following Python 3 code
def facial_features(image, cloud=None, batch=False, api_key=None, version=None, **kwargs):
image = data_preprocess(image, batch=batch, size=None if kwargs.get("detect") else (48, 48))
url_params = {"batch": batch, "api_key": api_key, "version": version}
retur... | As a Python code analyst, you investigate and solve complex coding mysteries |
Monitor a linkage run and return the final status updates. | Make a summary of the following Python 3 code
def wait_for_run(server, project, run, apikey, timeout=None, update_period=1):
for status in watch_run_status(server, project, run, apikey, timeout, update_period):
pass
return status | You are a Python code analyst, evaluating scripts for potential improvements. |
Monitor a run and yield status updates. | Make a summary of the following Python 3 code
def watch_run_status(server, project, run, apikey, timeout=None, update_period=1):
start_time = time.time()
status = old_status = run_get_status(server, project, run, apikey)
yield status
def time_not_up():
return (
(timeout is None) or
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def docx_preprocess(docx, batch=False):
"""
Load docx files from local filepath if not already b64 encoded
"""
if batch:
return [docx_preprocess(doc, batch=False) for doc in docx]
if os.path.isfile(docx):
# a filepath is provided, read and encode
return b64encode(open(docx, ... | Can you create a Python 3 function that
loads docx files from local filepath if not already b64 encoded Load docx files from local filepath if not already b64 encoded Load docx files from local filepath if not already b64 encoded Load docx files from local filepath if not already b64 encoded | As a Python code translator, you convert algorithms and pseudocode into Python. |
def relevance(data, queries, cloud=None, batch=False, api_key=None, version=None, **kwargs):
"""
Given input text and a list of query terms / phrases, returns how relevant the query is
to the input text.
Example usage:
.. code-block:: python
>>> import indicoio
>>> text = 'On Monday... | Write a Python 3 script for
giving input text and a list of query terms / phrases, returns how relevant the query is to the input text. Example usage: .. code-block:: python >>> import indicoio >>> text = 'On Monday, president Barack Obama will be giving his keynote address at...' >>> relevance = indicoio.relevance(tex... | You are a Python code architect, reviewing and designing scalable and efficient code |
This is a custom assignment implementation that handles the assignments of type aliases. | Make a summary of the following Python 3 code
def ASSIGN(self, node):
if not isinstance(self.scope, ModuleScope):
return super().ASSIGN(node)
for target in node.targets:
self.handleNode(target, node)
self.deferHandleNode(node.value, node) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def ANNASSIGN(self, node):
"""
Annotated assignments don't have annotations evaluated on function
scope, hence the custom implementation. Compared to the pyflakes
version, we defer evaluation of the annotations (and values on
module level).
"""
if node.value:
... | Implement a function in Python 3 to
handle an assignment node. | As a Python code analyst, you investigate and solve complex coding mysteries |
This is a hack to handle the LAMBDA function. | How would you explain what the following Python 3 function does
def LAMBDA(self, node):
self.handleNode, self.deferHandleNode = self.deferHandleNode, self.handleNode
super().LAMBDA(node)
self.handleNode, self.deferHandleNode = self.deferHandleNode, self.handleNode | As a Python code translator, you convert algorithms and pseudocode into Python. |
def double_hash_encode_ngrams(ngrams, # type: Iterable[str]
keys, # type: Sequence[bytes]
ks, # type: Sequence[int]
l, # type: int
encoding # type: str
... | How would you code a function in Python 3 to
compute the double hash encoding of the ngrams with the given keys. Using the method from: Schnell, R., Bachteler, T., & Reiher, J. (2011). A Novel Error-Tolerant Anonymous Linking Code. http://grlc.german-microsimulation.de/wp-content/uploads/2017/05/downloadwp-grlc-2011-02... | As a python code expert, you are capable of creating scripts from specifications. |
This function computes the double hash encoding of the n - grams with the given keys and the given l. | Can you generate the documentation for the following Python 3 function
def double_hash_encode_ngrams_non_singular(ngrams, # type: Iterable[str]
keys, # type: Sequence[bytes]
ks, # type: Sequence[int]
... | You are a Python code architect, reviewing and designing scalable and efficient code |
This function encodes the n - grams in the n - grams list using the BLAKE2 hash function. | Can you tell what is the following Python 3 function doing
def blake_encode_ngrams(ngrams, # type: Iterable[str]
keys, # type: Sequence[bytes]
ks, # type: Sequence[int]
l, # type: int
encoding # type: str... | You are a Python code generator, capable of creating scripts from specifications. |
Returns the hashing function for the given field hashing properties. | How would you explain what the following Python 3 function does
def hashing_function_from_properties(
fhp # type: FieldHashingProperties
):
# type: (...) -> Callable[[Iterable[str], Sequence[bytes], Sequence[int], int, str], bitarray]
""" Get the hashing function for this field
:param f... | You are a Python code analyst, evaluating scripts for potential improvements. |
def fold_xor(bloomfilter, # type: bitarray
folds # type: int
):
# type: (...) -> bitarray
""" Performs XOR folding on a Bloom filter.
If the length of the original Bloom filter is n and we perform
r folds, then the length of the resulting filter is n / 2 ** r.... | How would you code a function in Python 3 to
perform XOR folding on a Bloom filter. | You are a Python code generator, capable of creating scripts from specifications. |
Computes the composite Bloom filter encoding of a record. | Given the following Python 3 function, write the documentation
def crypto_bloom_filter(record, # type: Sequence[Text]
tokenizers, # type: List[Callable[[Text, Optional[Text]], Iterable[Text]]]
schema, # type: Schema
keys # type: ... | As a python code expert, you are capable of creating scripts from specifications. |
Generates composite Bloom filters for every record in an iterable dataset. | Can you generate a brief explanation for the following Python 3 code
def stream_bloom_filters(dataset, # type: Iterable[Sequence[Text]]
keys, # type: Sequence[Sequence[bytes]]
schema # type: Schema
):
# type: (...) -> Iterable[Tuple[... | As a Python code analyst, you investigate and solve complex coding mysteries |
Create compiled regular expression such that it matches the entire string of the ISO - 8601 language. | Given the following Python 3 function, write the documentation
def re_compile_full(pattern, flags=0):
# type: (AnyStr, int) -> Pattern
""" Create compiled regular expression such that it matches the
entire string. Calling re.match on the output of this function
is equivalent to calling re.fullma... | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns an iterator over the Unicode data in a CSV file. | Can you tell what is the following Python 3 function doing
def _p2_unicode_reader(unicode_csv_data, dialect=csv.excel, **kwargs):
# Encode temporarily as UTF-8:
utf8_csv_data = _utf_8_encoder(unicode_csv_data)
# Now we can parse!
csv_reader = csv.reader(utf8_csv_data, dialect=dialect, **kwargs)
# ... | As a python code expert, you are capable of creating scripts from specifications. |
def file_exists(filename):
"""
Check if a file exists (and don't error out on unicode inputs)
"""
try:
return os.path.isfile(filename)
except (UnicodeDecodeError, UnicodeEncodeError, ValueError):
return False | Write a Python 3 function for
checking if a file exists in the current directory. | As a python code expert, you are capable of creating scripts from specifications. |
Takes data and prepares it for sending to the api including resizing and image data and structure standardizing. | Can you generate a brief explanation for the following Python 3 code
def data_preprocess(data, size=None, min_axis=None, batch=False):
if batch:
return [data_preprocess(el, size=size, min_axis=min_axis, batch=False) for el in data]
if isinstance(data, string_types):
if file_exists(data):
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_list_dimensions(_list):
"""
Takes a nested list and returns the size of each dimension followed
by the element type in the list
"""
if isinstance(_list, list) or isinstance(_list, tuple):
return [len(_list)] + get_list_dimensions(_list[0])
return [] | Implement a Python 3 function for
taking a nested list and returns the size of each dimension followed by the element type in the nested list | As a python code expert, you are capable of creating scripts from specifications. |
Given the dimensions of a nested list and the list returns the type of the elements in the inner list. | Here you have a function in Python 3, explain what it does
def get_element_type(_list, dimens):
elem = _list
for _ in range(len(dimens)):
elem = elem[0]
return type(elem) | As a Python code composer, you craft elegant and concise scripts. |
Given an input image returns a dictionary of image classifications with associated scores | Here you have a function in Python 3, explain what it does
def image_recognition(image, cloud=None, batch=False, api_key=None, version=None, **kwargs):
image = data_preprocess(image, batch=batch, size=144, min_axis=True)
url_params = {"batch": batch, "api_key": api_key, "version": version}
return api_handle... | You are a Python code generator, capable of creating scripts from specifications. |
Helper function to make a single request to the server. | Can you tell what is the following Python 3 function doing
def multi(data, datatype, apis, accepted_apis, batch=False,**kwargs):
# Client side api name checking - strictly only accept func name api
invalid_apis = [api for api in apis if api not in accepted_apis or api in MULTIAPI_NOT_SUPPORTED]
if invali... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Given input text returns the results of specified text apis. | Can you generate the documentation for the following Python 3 function
def analyze_text(input_text, apis=DEFAULT_APIS, **kwargs):
cloud = kwargs.pop('cloud', None)
batch = kwargs.pop('batch', False)
api_key = kwargs.pop('api_key', None)
return multi(
data=input_text,
datatype="te... | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns a FieldHashingProperties object from a dictionary. | Can you generate the documentation for the following Python 3 function
def fhp_from_json_dict(
json_dict # type: Dict[str, Any]
):
# type: (...) -> FieldHashingProperties
"""
Make a :class:`FieldHashingProperties` object from a dictionary.
:param dict json_dict:
The diction... | As a python code expert, you are capable of creating scripts from specifications. |
Turns a dictionary into an instance of the appropriate FieldSpec subclass. | Given the following Python 3 function, write the documentation
def spec_from_json_dict(
json_dict # type: Dict[str, Any]
):
# type: (...) -> FieldSpec
""" Turns a dictionary into the appropriate object.
:param dict json_dict: A dictionary with properties.
:returns: An initialised insta... | You are a Python code analyst, evaluating scripts for potential improvements. |
provide a k value for each ngram in the field value. | Here you have a function in Python 3, explain what it does
def ks(self, num_ngrams):
# type (int) -> [int]
"""
Provide a k for each ngram in the field value.
:param num_ngrams: number of ngrams in the field value
:return: [ k, ... ] a k value for each of num_ngrams such that the ... | As a Python code composer, you craft elegant and concise scripts. |
def replace_missing_value(self, str_in):
# type: (Text) -> Text
""" returns 'str_in' if it is not equals to the 'sentinel' as
defined in the missingValue section of
the schema. Else it will return the 'replaceWith' value.
:param str_in:
:return: str_in or the missingValu... | Create a Python 3 function to
replace the missingValue value with the value in the missingValue section of the schema. | You are a Python code generator, capable of creating scripts from specifications. |
def from_json_dict(cls,
json_dict # type: Dict[str, Any]
):
# type: (...) -> StringSpec
""" Make a StringSpec object from a dictionary containing its
properties.
:param dict json_dict: This dictionary must contain an
... | Create a Python 3 function to
make a StringSpec object from a dictionary containing its aniso - formatted version of its base - level properties. | As a Python code analyst, you investigate and solve complex coding mysteries |
Validates an entry in the field. | Can you tell what is the following Python 3 function doing
def validate(self, str_in):
# type: (Text) -> None
""" Validates an entry in the field.
Raises `InvalidEntryError` iff the entry is invalid.
An entry is invalid iff (1) a pattern is part of the
specification... | You are a Python code architect, reviewing and designing scalable and efficient code |
def from_json_dict(cls,
json_dict # type: Dict[str, Any]
):
# type: (...) -> IntegerSpec
""" Make a IntegerSpec object from a dictionary containing its
properties.
:param dict json_dict: This dictionary may contain
`... | Implement a function in Python 3 to
make a IntegerSpec object from a dictionary containing its properties. | You are a Python code analyst, evaluating scripts for potential improvements. |
def validate(self, str_in):
# type: (Text) -> None
""" Validates an entry in the field.
Raises `InvalidEntryError` iff the entry is invalid.
An entry is invalid iff (1) the string does not represent a
base-10 integer; (2) the integer is not between
`self... | Can you create a Python 3 function that
validates an entry in the field. | You are a Python code architect, reviewing and designing scalable and efficient code |
Make a DateSpec object from a dictionary containing its
properties. | Can you generate a brief explanation for the following Python 3 code
def from_json_dict(cls,
json_dict # type: Dict[str, Any]
):
# type: (...) -> DateSpec
""" Make a DateSpec object from a dictionary containing its
properties.
:param dict json_dict: T... | As a Python code analyst, you investigate and solve complex coding mysteries |
Validates an entry in the field. | Make a summary of the following Python 3 code
def validate(self, str_in):
# type: (Text) -> None
""" Validates an entry in the field.
Raises `InvalidEntryError` iff the entry is invalid.
An entry is invalid iff (1) the string does not represent a
date in the correct... | As a Python code analyst, you investigate and solve complex coding mysteries |
def _format_regular_value(self, str_in):
# type: (Text) -> Text
""" we overwrite default behaviour as we want to hash the numbers
only, no fillers like '-', or '/'
:param str str_in: date string
:return: str date string with format DateSpec.OUTPUT_FORMAT
"""
try:... | Write a Python 3 script to
format regular value of the log entry | You are a Python code architect, reviewing and designing scalable and efficient code |
def from_json_dict(cls,
json_dict # type: Dict[str, Any]
):
# type: (...) -> EnumSpec
""" Make a EnumSpec object from a dictionary containing its
properties.
:param dict json_dict: This dictionary must contain an
`'e... | Write a Python 3 function for
making an EnumSpec object from a dictionary containing its properties. | You are a Python code architect, reviewing and designing scalable and efficient code |
Validates an entry in the field. | Given the following Python 3 function, write the documentation
def validate(self, str_in):
# type: (Text) -> None
""" Validates an entry in the field.
Raises `InvalidEntryError` iff the entry is invalid.
An entry is invalid iff it is not one of the permitted
values.... | As a Python code analyst, you investigate and solve complex coding mysteries |
def batched(iterable, size):
"""
Split an iterable into constant sized chunks
Recipe from http://stackoverflow.com/a/8290514
"""
length = len(iterable)
for batch_start in range(0, length, size):
yield iterable[batch_start:batch_start+size] | Write a Python 3 function for
splitting an iterable into chunks of size size | As a Python code analyst, you investigate and solve complex coding mysteries |
Standardize the input data for the indico API. | Can you tell what is the following Python 3 function doing
def standardize_input_data(data):
if type(data) == bytes:
data = data.decode('utf-8')
if type(data) == list:
data = [
el.decode('utf-8') if type(data) == bytes else el
for el in data
]
return data | As a Python code composer, you craft elegant and concise scripts. |
This function handles the finalization of an indico - internal node - based API request. | Can you tell what is the following Python 3 function doing
def api_handler(input_data, cloud, api, url_params=None, batch_size=None, **kwargs):
url_params = url_params or {}
input_data = standardize_input_data(input_data)
cloud = cloud or config.cloud
host = "%s.indico.domains" % cloud if cloud else co... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Collect the results from an API call. | Can you generate the documentation for the following Python 3 function
def collect_api_results(input_data, url, headers, api, batch_size, kwargs):
if batch_size:
results = []
for batch in batched(input_data, size=batch_size):
try:
result = send_request(batch, api, url, he... | As a python code expert, you are capable of creating scripts from specifications. |
def send_request(input_data, api, url, headers, kwargs):
"""
Use the requests library to send of an HTTP call to the indico servers
"""
data = {}
if input_data != None:
data['data'] = input_data
# request that the API respond with a msgpack encoded result
serializer = kwargs.pop("se... | Create a Python 3 function to
send a request to the indico servers | As a Python code analyst, you investigate and solve complex coding mysteries |
def create_url(url_protocol, host, api, url_params):
"""
Generate the proper url for sending off data for analysis
"""
is_batch = url_params.pop("batch", None)
apis = url_params.pop("apis", None)
version = url_params.pop("version", None) or url_params.pop("v", None)
method = url_params.pop('... | Write a Python 3 function that can
generate the proper url for sending off data for analysis | You are a Python code analyst, evaluating scripts for potential improvements. |
def keywords(text, cloud=None, batch=False, api_key=None, version=2, batch_size=None, **kwargs):
"""
Given input text, returns series of keywords and associated scores
Example usage:
.. code-block:: python
>>> import indicoio
>>> import numpy as np
>>> text = 'Monday: Delightful ... | Create a Python 3 function to
give input text returns series of keywords and associated scores | As a python code expert, you are capable of creating scripts from specifications. |
Returns the authors likelihood of being 16 different personality objects in a dictionary. | Can you generate the documentation for the following Python 3 function
def personas(text, cloud=None, batch=False, api_key=None, version=None, **kwargs):
url_params = {"batch": batch, "api_key": api_key, "version": version}
kwargs['persona'] = True
return api_handler(text, cloud=cloud, api="personality", ur... | You are a Python code generator, capable of creating scripts from specifications. |
def pdf_extraction(pdf, cloud=None, batch=False, api_key=None, version=None, **kwargs):
"""
Given a pdf, returns the text and metadata associated with the given pdf.
PDFs may be provided as base64 encoded data or as a filepath.
Base64 image data and formatted table is optionally returned by setting
... | Write a Python 3 function that can
give a pdf returns the text and metadata associated with the given pdf. | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_tokenizer(fhp # type: Optional[field_formats.FieldHashingProperties]
):
# type: (...) -> Callable[[Text, Optional[Text]], Iterable[Text]]
""" Get tokeniser function from the hash settings.
This function takes a FieldHashingProperties object. It returns a
function that... | Implement a Python 3 function for
returning a tokenizer function that returns a list of n - grams for the given word and optional field_formats. FieldHashingProperties object. | As a python code expert, you are 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.