output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def snipstr(string, width=79, snipat=None, ellipsis='...'):
"""Return string cut to specified length.
>>> snipstr('abcdefghijklmnop', 8)
'abc...op'
"""
if snipat is None:
snipat = 0.5
if ellipsis is None:
if isinstance(string, bytes):
ellipsis = b'...'
else:... | Write a Python 3 script for
returning string cut to specified length. | As a python code expert, you are capable of creating scripts from specifications. |
Return enum member from its name or value. | Explain what the following Python 3 code does
def enumarg(enum, arg):
try:
return enum(arg)
except Exception:
try:
return enum[arg.upper()]
except Exception:
raise ValueError('invalid argument %s' % arg) | As a Python code analyst, you investigate and solve complex coding mysteries |
Parse kwargs and return a dict with keys from keys and values from keyvals. | Here you have a function in Python 3, explain what it does
def parse_kwargs(kwargs, *keys, **keyvalues):
result = {}
for key in keys:
if key in kwargs:
result[key] = kwargs[key]
del kwargs[key]
for key, value in keyvalues.items():
if key in kwargs:
result[... | You are a Python code generator, capable of creating scripts from specifications. |
def update_kwargs(kwargs, **keyvalues):
"""Update dict with keys and values if keys do not already exist.
>>> kwargs = {'one': 1, }
>>> update_kwargs(kwargs, one=None, two=2)
>>> kwargs == {'one': 1, 'two': 2}
True
"""
for key, value in keyvalues.items():
if key not in kwargs:
... | Write a Python 3 function that can
update dict with keys and values if keys do not already exist. | As a Python code analyst, you investigate and solve complex coding mysteries |
Validate TIFF file using JHOVE. | Make a summary of the following Python 3 code
def validate_jhove(filename, jhove=None, ignore=None):
import subprocess # noqa: delayed import
if ignore is None:
ignore = ['More than 50 IFDs']
if jhove is None:
jhove = 'jhove'
out = subprocess.check_output([jhove, filename, '-m', 'TIFF-h... | As a Python code composer, you craft elegant and concise scripts. |
Convert a LSM file to a series of BIN files. | How would you explain what the following Python 3 function does
def lsm2bin(lsmfile, binfile=None, tile=None, verbose=True):
verbose = print_ if verbose else nullfunc
if tile is None:
tile = (256, 256)
if binfile is None:
binfile = lsmfile
elif binfile.lower() == 'none':
binfil... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def imshow(data, photometric=None, planarconfig=None, bitspersample=None,
interpolation=None, cmap=None, vmin=None, vmax=None,
figure=None, title=None, dpi=96, subplot=None, maxdim=None,
**kwargs):
"""Plot n-dimensional images using matplotlib.pyplot.
Return figure, subplot and... | Write a Python 3 function that can
plot n - dimensional images using matplotlib. pyplot. | You are a Python code architect, reviewing and designing scalable and efficient code |
Return file name s from Tkinter s file open dialog. | Can you generate the documentation for the following Python 3 function
def askopenfilename(**kwargs):
try:
from Tkinter import Tk
import tkFileDialog as filedialog
except ImportError:
from tkinter import Tk, filedialog
root = Tk()
root.withdraw()
root.update()
filenames =... | As a python code expert, you are capable of creating scripts from specifications. |
def save(self, data=None, shape=None, dtype=None, returnoffset=False,
photometric=None, planarconfig=None, extrasamples=None, tile=None,
contiguous=True, align=16, truncate=False, compress=0,
rowsperstrip=None, predictor=False, colormap=None,
description=None, datetim... | Implement a Python 3 function for
writing numpy array and tags to TIFF file. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _write_remaining_pages(self):
"""Write outstanding IFDs and tags to file."""
if not self._tags or self._truncate:
return
pageno = self._shape[0] * self._datashape[0] - 1
if pageno < 1:
self._tags = None
self._datadtype = None
self._dat... | Can you write a function in Python 3 where it
writes out the remaining IFDs and tags to file. | As a Python code analyst, you investigate and solve complex coding mysteries |
Write metadata to ImageDescription tag. | Given the following Python 3 function, write the documentation
def _write_image_description(self):
if (not self._datashape or self._datashape[0] == 1 or
self._descriptionoffset <= 0):
return
colormapped = self._colormap is not None
if self._imagej:
isrgb ... | As a Python code composer, you craft elegant and concise scripts. |
def close(self):
"""Write remaining pages and close file handle."""
if not self._truncate:
self._write_remaining_pages()
self._write_image_description()
self._fh.close() | Can you implement a function in Python 3 that
writes remaining pages and close file handle. | As a Python code analyst, you investigate and solve complex coding mysteries |
Close open file handle s. | How would you explain what the following Python 3 function does
def close(self):
for tif in self._files.values():
tif.filehandle.close()
self._files = {} | As a python code expert, you are capable of creating scripts from specifications. |
def asarray(self, key=None, series=None, out=None, validate=True,
maxworkers=None):
"""Return image data from selected TIFF page(s) as numpy array.
By default, the data from the first series is returned.
Parameters
----------
key : int, slice, or sequence of ind... | Implement a Python 3 function for
returning image data from selected TIFF pages as numpy array. | As a python code expert, you are capable of creating scripts from specifications. |
Return related pages as TiffPageSeries. | Can you generate a brief explanation for the following Python 3 code
def series(self):
if not self.pages:
return []
useframes = self.pages.useframes
keyframe = self.pages.keyframe.index
series = []
for name in ('lsm', 'ome', 'imagej', 'shaped', 'fluoview', 'sis',
... | As a Python code composer, you craft elegant and concise scripts. |
def _series_generic(self):
"""Return image series in file.
A series is a sequence of TiffPages with the same hash.
"""
pages = self.pages
pages._clear(False)
pages.useframes = False
if pages.cache:
pages._load()
result = []
keys = []... | How would you implement a function in Python 3 that
returns image series in file. | You are a Python code analyst, evaluating scripts for potential improvements. |
def _series_uniform(self):
"""Return all images in file as single series."""
page = self.pages[0]
shape = page.shape
axes = page.axes
dtype = page.dtype
validate = not (page.is_scanimage or page.is_nih)
pages = self.pages._getlist(validate=validate)
lenpag... | How would you implement a function in Python 3 that
returns all images in file as single series. | You are a Python code generator, capable of creating scripts from specifications. |
Return image series in shaped file. | Can you tell what is the following Python 3 function doing
def _series_shaped(self):
pages = self.pages
pages.useframes = True
lenpages = len(pages)
def append_series(series, pages, axes, shape, reshape, name,
truncated):
page = pages[0]
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return image series in ImageJ file. | Can you generate the documentation for the following Python 3 function
def _series_imagej(self):
# ImageJ's dimension order is always TZCYXS
# TODO: fix loading of color, composite, or palette images
pages = self.pages
pages.useframes = True
pages.keyframe = 0
page = page... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _series_fluoview(self):
"""Return image series in FluoView file."""
pages = self.pages._getlist(validate=False)
mm = self.fluoview_metadata
mmhd = list(reversed(mm['Dimensions']))
axes = ''.join(TIFF.MM_DIMENSIONS.get(i[0].upper(), 'Q')
for i in mmhd i... | Can you implement a function in Python 3 that
returns image series in FluoView file. | As a Python code analyst, you investigate and solve complex coding mysteries |
def _series_mdgel(self):
"""Return image series in MD Gel file."""
# only a single page, scaled according to metadata in second page
self.pages.useframes = False
self.pages.keyframe = 0
md = self.mdgel_metadata
if md['FileTag'] in (2, 128):
dtype = numpy.dtype... | Can you create a Python 3 function that
returns image series in MD Gel file. | As a Python code analyst, you investigate and solve complex coding mysteries |
Return image series in Olympus SIS file. | Make a summary of the following Python 3 code
def _series_sis(self):
pages = self.pages._getlist(validate=False)
page = pages[0]
lenpages = len(pages)
md = self.sis_metadata
if 'shape' in md and 'axes' in md:
shape = md['shape'] + page.shape
axes = md['axe... | You are a Python code generator, capable of creating scripts from specifications. |
Return image series in OME - TIFF file ( s ). | Here you have a function in Python 3, explain what it does
def _series_ome(self):
from xml.etree import cElementTree as etree # delayed import
omexml = self.pages[0].description
try:
root = etree.fromstring(omexml)
except etree.ParseError as exc:
# TODO: test bad... | You are a Python code analyst, evaluating scripts for potential improvements. |
def _series_lsm(self):
"""Return main and thumbnail series in LSM file."""
lsmi = self.lsm_metadata
axes = TIFF.CZ_LSMINFO_SCANTYPE[lsmi['ScanType']]
if self.pages[0].photometric == 2: # RGB; more than one channel
axes = axes.replace('C', '').replace('XY', 'XYC')
if ... | Write a Python 3 script to
return main and thumbnail series in LSM file. | As a Python code composer, you craft elegant and concise scripts. |
Load and fix all pages from LSM file. | How would you explain what the following Python 3 function does
def _lsm_load_pages(self):
# cache all pages to preserve corrected values
pages = self.pages
pages.cache = True
pages.useframes = True
# use first and second page as keyframes
pages.keyframe = 1
pages... | As a python code expert, you are capable of creating scripts from specifications. |
Unwrap strip offsets for LSM files greater than 4 GB. | Make a summary of the following Python 3 code
def _lsm_fix_strip_offsets(self):
if self.filehandle.size < 2**32:
return
pages = self.pages
npages = len(pages)
series = self.series[0]
axes = series.axes
# find positions
positions = 1
for i in ... | As a Python code composer, you craft elegant and concise scripts. |
def _lsm_fix_strip_bytecounts(self):
"""Set databytecounts to size of compressed data.
The StripByteCounts tag in LSM files contains the number of bytes
for the uncompressed data.
"""
pages = self.pages
if pages[0].compression == 1:
return
# sort pag... | Implement a function in Python 3 to
fix the bytecounts of compressed data in LSM files. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def is_mdgel(self):
"""File has MD Gel format."""
# TODO: this likely reads the second page from file
try:
ismdgel = self.pages[0].is_mdgel or self.pages[1].is_mdgel
if ismdgel:
self.is_uniform = False
return ismdgel
except IndexError:
... | Create a Python 3 function to
check if the file has MD Gel format. | You are a Python code generator, capable of creating scripts from specifications. |
def is_uniform(self):
"""Return if file contains a uniform series of pages."""
# the hashes of IFDs 0, 7, and -1 are the same
pages = self.pages
page = pages[0]
if page.is_scanimage or page.is_nih:
return True
try:
useframes = pages.useframes
... | Implement a function in Python 3 to
return if file contains a uniform series of pages. | You are a Python code analyst, evaluating scripts for potential improvements. |
Return if pages can be appended to file without corrupting. | How would you explain what the following Python 3 function does
def is_appendable(self):
# TODO: check other formats
return not (self.is_lsm or self.is_stk or self.is_imagej or
self.is_fluoview or self.is_micromanager) | As a Python code composer, you craft elegant and concise scripts. |
Return tifffile metadata from JSON descriptions as dicts. | Can you generate a brief explanation for the following Python 3 code
def shaped_metadata(self):
if not self.is_shaped:
return None
return tuple(json_description_metadata(s.pages[0].is_shaped)
for s in self.series if s.kind.lower() == 'shaped') | As a python code expert, you are capable of creating scripts from specifications. |
Return STK metadata from UIC tags as dict. | Make a summary of the following Python 3 code
def stk_metadata(self):
if not self.is_stk:
return None
page = self.pages[0]
tags = page.tags
result = {}
result['NumberPlanes'] = tags['UIC2tag'].count
if page.description:
result['PlaneDescriptions'] ... | As a python code expert, you are capable of creating scripts from specifications. |
def imagej_metadata(self):
"""Return consolidated ImageJ metadata as dict."""
if not self.is_imagej:
return None
page = self.pages[0]
result = imagej_description_metadata(page.is_imagej)
if 'IJMetadata' in page.tags:
try:
result.update(page... | Implement a Python 3 function for
returning consolidated ImageJ metadata as dict. | As a Python code composer, you craft elegant and concise scripts. |
Return consolidated FluoView metadata as dict. | How would you explain what the following Python 3 function does
def fluoview_metadata(self):
if not self.is_fluoview:
return None
result = {}
page = self.pages[0]
result.update(page.tags['MM_Header'].value)
# TODO: read stamps from all pages
result['Stamp'] = ... | As a python code expert, you are capable of creating scripts from specifications. |
def fei_metadata(self):
"""Return FEI metadata from SFEG or HELIOS tags as dict."""
if not self.is_fei:
return None
tags = self.pages[0].tags
if 'FEI_SFEG' in tags:
return tags['FEI_SFEG'].value
if 'FEI_HELIOS' in tags:
return tags['FEI_HELIOS'... | Write a Python 3 function for
returning FEI metadata from SFEG or HELIOS tags as dict. | You are a Python code analyst, evaluating scripts for potential improvements. |
Return Olympus SIS metadata from SIS and INI tags as dict. | How would you explain what the following Python 3 function does
def sis_metadata(self):
if not self.is_sis:
return None
tags = self.pages[0].tags
result = {}
try:
result.update(tags['OlympusINI'].value)
except Exception:
pass
try:
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Return consolidated metadata from MD GEL tags as dict. | Given the following Python 3 function, write the documentation
def mdgel_metadata(self):
for page in self.pages[:2]:
if 'MDFileTag' in page.tags:
tags = page.tags
break
else:
return None
result = {}
for code in range(33445, 33453):
... | As a python code expert, you are capable of creating scripts from specifications. |
def micromanager_metadata(self):
"""Return consolidated MicroManager metadata as dict."""
if not self.is_micromanager:
return None
# from file header
result = read_micromanager_metadata(self._fh)
# from tag
result.update(self.pages[0].tags['MicroManagerMetadat... | Implement a Python 3 function for
returning consolidated MicroManager metadata as dict. | As a python code expert, you are capable of creating scripts from specifications. |
def scanimage_metadata(self):
"""Return ScanImage non-varying frame and ROI metadata as dict."""
if not self.is_scanimage:
return None
result = {}
try:
framedata, roidata = read_scanimage_metadata(self._fh)
result['FrameData'] = framedata
r... | How would you code a function in Python 3 to
return ScanImage non - varying frame and ROI metadata as dict. | As a python code expert, you are capable of creating scripts from specifications. |
def cache(self, value):
"""Enable or disable caching of pages/frames. Clear cache if False."""
value = bool(value)
if self._cache and not value:
self._clear()
self._cache = value | Create a Python 3 function for
enabling or disable caching of pages or frames. Clear cache if False. | You are a Python code generator, capable of creating scripts from specifications. |
Set current keyframe. Load TiffPage from file if necessary. | Here you have a function in Python 3, explain what it does
def keyframe(self, index):
index = int(index)
if index < 0:
index %= len(self)
if self._keyframe.index == index:
return
if index == 0:
self._keyframe = self.pages[0]
return
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _load(self, keyframe=True):
"""Read all remaining pages from file."""
if self._cached:
return
pages = self.pages
if not pages:
return
if not self._indexed:
self._seek(-1)
if not self._cache:
return
fh = self.pare... | Create a Python 3 function for
reading all remaining pages from file. | You are a Python code analyst, evaluating scripts for potential improvements. |
Delete all but first page from cache. Set keyframe to first page. | Make a summary of the following Python 3 code
def _clear(self, fully=True):
pages = self.pages
if not pages:
return
self._keyframe = pages[0]
if fully:
# delete all but first TiffPage/TiffFrame
for i, page in enumerate(pages[1:]):
if no... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _seek(self, index, maxpages=None):
"""Seek file to offset of page specified by index."""
pages = self.pages
lenpages = len(pages)
if lenpages == 0:
raise IndexError('index out of range')
fh = self.parent.filehandle
if fh.closed:
raise ValueErr... | Implement a function in Python 3 to
seek file to offset of page specified by index. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return specified pages as list of TiffPages or TiffFrames. | Can you tell what is the following Python 3 function doing
def _getlist(self, key=None, useframes=True, validate=True):
getitem = self._getitem
_useframes = self.useframes
if key is None:
key = iter(range(len(self)))
elif isinstance(key, Iterable):
key = iter(key... | You are a Python code generator, capable of creating scripts from specifications. |
Return specified page from cache or file. | Can you generate the documentation for the following Python 3 function
def _getitem(self, key, validate=False):
key = int(key)
pages = self.pages
if key < 0:
key %= len(self)
elif self._indexed and key >= len(pages):
raise IndexError('index out of range')
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def asarray(self, out=None, squeeze=True, lock=None, reopen=True,
maxsize=None, maxworkers=None, validate=True):
"""Read image data from file and return as numpy array.
Raise ValueError if format is unsupported.
Parameters
----------
out : numpy.ndarray, str, or... | How would you implement a function in Python 3 that
reads image data from file and return as numpy array. | You are a Python code generator, capable of creating scripts from specifications. |
Return image data as RGB. | Explain what the following Python 3 code does
def asrgb(self, uint8=False, alpha=None, colormap=None,
dmin=None, dmax=None, **kwargs):
"""Return image data as RGB(A).
Work in progress.
"""
data = self.asarray(**kwargs)
self = self.keyframe # self or keyframe
... | As a Python code composer, you craft elegant and concise scripts. |
def _gettags(self, codes=None, lock=None):
"""Return list of (code, TiffTag)."""
tags = []
for tag in self.tags.values():
code = tag.code
if not codes or code in codes:
tags.append((code, tag))
return tags | Can you implement a function in Python 3 that
returns list of ( code TiffTag | As a Python code composer, you craft elegant and concise scripts. |
Return checksum to identify pages in same series. | How would you explain what the following Python 3 function does
def hash(self):
return hash(
self._shape + (
self.tilewidth, self.tilelength, self.tiledepth,
self.bitspersample, self.fillorder, self.predictor,
self.extrasamples, self.photometric, self.... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _offsetscounts(self):
"""Return simplified offsets and bytecounts."""
if self.is_contiguous:
offset, bytecount = self.is_contiguous
return [offset], [bytecount]
if self.is_tiled:
return self.dataoffsets, self.databytecounts
return clean_offsetscoun... | Write a Python 3 function for
returning simplified offsets and bytecounts. | You are a Python code analyst, evaluating scripts for potential improvements. |
Return offset and size of contiguous data else None. | Can you generate the documentation for the following Python 3 function
def is_contiguous(self):
if (self.compression != 1
or self.bitspersample not in (8, 16, 32, 64)):
return None
if 'TileWidth' in self.tags:
if (self.imagewidth != self.tilewidth or
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def is_final(self):
"""Return if page's image data are stored in final form.
Excludes byte-swapping.
"""
return (self.is_contiguous and self.fillorder == 1 and
self.predictor == 1 and not self.is_subsampled) | Implement a function in Python 3 to
return True if page s image data are stored in final form. | As a Python code composer, you craft elegant and concise scripts. |
def is_memmappable(self):
"""Return if page's image data in file can be memory-mapped."""
return (self.parent.filehandle.is_file and self.is_final and
# (self.bitspersample == 8 or self.parent.isnative) and
self.is_contiguous[0] % self.dtype.itemsize == 0) | Create a Python 3 function for
returning if page s image data in file can be memory - mapped. | As a python code expert, you are capable of creating scripts from specifications. |
def flags(self):
"""Return set of flags."""
return set((name.lower() for name in sorted(TIFF.FILE_FLAGS)
if getattr(self, 'is_' + name))) | Can you implement a function in Python 3 that
returns set of flags. | As a Python code composer, you craft elegant and concise scripts. |
Return consolidated metadata from Andor tags as dict. | Explain what the following Python 3 code does
def andor_tags(self):
if not self.is_andor:
return None
tags = self.tags
result = {'Id': tags['AndorId'].value}
for tag in list(self.tags.values()):
code = tag.code
if not 4864 < code < 5031:
... | You are a Python code generator, capable of creating scripts from specifications. |
Return consolidated metadata from EPICS areaDetector tags as dict. | Can you generate the documentation for the following Python 3 function
def epics_tags(self):
if not self.is_epics:
return None
result = {}
tags = self.tags
for tag in list(self.tags.values()):
code = tag.code
if not 65000 <= code < 65500:
... | You are a Python code generator, capable of creating scripts from specifications. |
def ndpi_tags(self):
"""Return consolidated metadata from Hamamatsu NDPI as dict."""
if not self.is_ndpi:
return None
tags = self.tags
result = {}
for name in ('Make', 'Model', 'Software'):
result[name] = tags[name].value
for code, name in TIFF.NDP... | Can you write a function in Python 3 where it
returns consolidated metadata from Hamamatsu NDPI as dict. | As a Python code composer, you craft elegant and concise scripts. |
def geotiff_tags(self):
"""Return consolidated metadata from GeoTIFF tags as dict."""
if not self.is_geotiff:
return None
tags = self.tags
gkd = tags['GeoKeyDirectoryTag'].value
if gkd[0] != 1:
log.warning('GeoTIFF tags: invalid GeoKeyDirectoryTag')
... | Write a Python 3 script for
returning consolidated metadata from GeoTIFF tags as dict. | You are a Python code generator, capable of creating scripts from specifications. |
def is_imagej(self):
"""Return ImageJ description if exists, else None."""
for description in (self.description, self.description1):
if not description:
return None
if description[:7] == 'ImageJ=':
return description
return None | Write a Python 3 function that can
return ImageJ description if exists else None. | As a Python code analyst, you investigate and solve complex coding mysteries |
def is_shaped(self):
"""Return description containing array shape if exists, else None."""
for description in (self.description, self.description1):
if not description:
return None
if description[:1] == '{' and '"shape":' in description:
return des... | Create a Python 3 function to
return description containing array shape if exists else None. | As a python code expert, you are capable of creating scripts from specifications. |
def is_metaseries(self):
"""Page contains MDS MetaSeries metadata in ImageDescription tag."""
if self.index > 1 or self.software != 'MetaSeries':
return False
d = self.description
return d.startswith('<MetaData>') and d.endswith('</MetaData>') | Write a Python 3 script to
return True if the page contains MDS MetaSeries metadata in ImageDescription tag. | You are a Python code architect, reviewing and designing scalable and efficient code |
def is_ome(self):
"""Page contains OME-XML in ImageDescription tag."""
if self.index > 1 or not self.description:
return False
d = self.description
return d[:14] == '<?xml version=' and d[-6:] == '</OME>' | Write a Python 3 function that can
return True if the page contains OME - XML in ImageDescription tag. | As a Python code analyst, you investigate and solve complex coding mysteries |
Return True if the page contains Leica SCN XML in ImageDescription tag. | Here you have a function in Python 3, explain what it does
def is_scn(self):
if self.index > 1 or not self.description:
return False
d = self.description
return d[:14] == '<?xml version=' and d[-6:] == '</scn>' | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _gettags(self, codes=None, lock=None):
"""Return list of (code, TiffTag) from file."""
fh = self.parent.filehandle
tiff = self.parent.tiff
unpack = struct.unpack
lock = NullContext() if lock is None else lock
tags = []
with lock:
fh.seek(self.offs... | Write a Python 3 function that can
return list of ( code TiffTag ) from file. | You are a Python code generator, capable of creating scripts from specifications. |
Return a TiffPage from file. | Here you have a function in Python 3, explain what it does
def aspage(self):
if self.offset is None:
raise ValueError('cannot return virtual frame as page.')
self.parent.filehandle.seek(self.offset)
return TiffPage(self.parent, index=self.index) | As a python code expert, you are capable of creating scripts from specifications. |
Read image data from file and return as numpy array. | How would you explain what the following Python 3 function does
def asarray(self, *args, **kwargs):
# TODO: fix TypeError on Python 2
# "TypeError: unbound method asarray() must be called with TiffPage
# instance as first argument (got TiffFrame instance instead)"
if self._keyframe i... | You are a Python code generator, capable of creating scripts from specifications. |
Read image data from file and return RGB image as numpy array. | Can you generate a brief explanation for the following Python 3 code
def asrgb(self, *args, **kwargs):
if self._keyframe is None:
raise RuntimeError('keyframe not set')
kwargs['validate'] = False
return TiffPage.asrgb(self, *args, **kwargs) | As a python code expert, you are capable of creating scripts from specifications. |
def is_contiguous(self):
"""Return offset and size of contiguous data, else None."""
if self._keyframe is None:
raise RuntimeError('keyframe not set')
if self._keyframe.is_contiguous:
return self._offsetscounts[0][0], self._keyframe.is_contiguous[1]
return None | Create a Python 3 function for
returning offset and size of contiguous data else None. | You are a Python code architect, reviewing and designing scalable and efficient code |
Return name of tag from TIFF. TAGS registry. | Make a summary of the following Python 3 code
def name(self):
try:
return TIFF.TAGS[self.code]
except KeyError:
return str(self.code) | As a python code expert, you are capable of creating scripts from specifications. |
Correct the LSM bitspersample tag. | Make a summary of the following Python 3 code
def _fix_lsm_bitspersample(self, parent):
if self.code != 258 or self.count != 2:
return
# TODO: test this case; need example file
log.warning('TiffTag %i: correcting LSM bitspersample tag', self.code)
value = struct.pack('<HH', *... | You are a Python code generator, capable of creating scripts from specifications. |
def asarray(self, out=None):
"""Return image data from series of TIFF pages as numpy array."""
if self.parent:
result = self.parent.asarray(series=self, out=out)
if self.transform is not None:
result = self.transform(result)
return result
retur... | Write a Python 3 script for
returning image data from series of TIFF pages as numpy array. | As a Python code composer, you craft elegant and concise scripts. |
def offset(self):
"""Return offset to series data in file, if any."""
if not self._pages:
return None
pos = 0
for page in self._pages:
if page is None:
return None
if not page.is_final:
return None
if not po... | Implement a function in Python 3 to
return offset to series data in file if any. | As a Python code analyst, you investigate and solve complex coding mysteries |
Return specified page of series from cache or file. | Here you have a function in Python 3, explain what it does
def _getitem(self, key):
key = int(key)
if key < 0:
key %= self._len
if len(self._pages) == 1 and 0 < key < self._len:
index = self._pages[0].index
return self.parent.pages._getitem(index + key)
... | As a python code expert, you are capable of creating scripts from specifications. |
def asarray(self, file=None, out=None, **kwargs):
"""Read image data from files and return as numpy array.
The kwargs parameters are passed to the imread function.
Raise IndexError or ValueError if image shapes do not match.
"""
if file is not None:
if isinstance(f... | Implement a Python 3 function for
reading image data from files and return as numpy array. | As a python code expert, you are capable of creating scripts from specifications. |
def _parse(self):
"""Get axes and shape from file names."""
if not self.pattern:
raise TiffSequence.ParseError('invalid pattern')
pattern = re.compile(self.pattern, re.IGNORECASE | re.VERBOSE)
matches = pattern.findall(os.path.split(self.files[0])[-1])
if not matches:... | How would you implement a function in Python 3 that
parses the file names and return a tuple of axes and shape. | You are a Python code architect, reviewing and designing scalable and efficient code |
Open or re - open file. | How would you explain what the following Python 3 function does
def open(self):
if self._fh:
return # file is open
if isinstance(self._file, pathlib.Path):
self._file = str(self._file)
if isinstance(self._file, basestring):
# file name
self._file... | As a python code expert, you are capable of creating scripts from specifications. |
Read size bytes from file. | Make a summary of the following Python 3 code
def read(self, size=-1):
if size < 0 and self._offset:
size = self._size
return self._fh.read(size) | As a Python code composer, you craft elegant and concise scripts. |
Return numpy. memmap of data stored in file. | How would you explain what the following Python 3 function does
def memmap_array(self, dtype, shape, offset=0, mode='r', order='C'):
if not self.is_file:
raise ValueError('Cannot memory-map file without fileno')
return numpy.memmap(self._fh, dtype=dtype, mode=mode,
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Return numpy array from file in native byte order. | Make a summary of the following Python 3 code
def read_array(self, dtype, count=-1, out=None):
fh = self._fh
dtype = numpy.dtype(dtype)
if count < 0:
size = self._size if out is None else out.nbytes
count = size // dtype.itemsize
else:
size = count * ... | You are a Python code analyst, evaluating scripts for potential improvements. |
def read_record(self, dtype, shape=1, byteorder=None):
"""Return numpy record from file."""
rec = numpy.rec
try:
record = rec.fromfile(self._fh, dtype, shape, byteorder=byteorder)
except Exception:
dtype = numpy.dtype(dtype)
if shape is None:
... | Can you create a Python 3 function that
returns numpy record from file. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def write_empty(self, size):
"""Append size bytes to file. Position must be at end of file."""
if size < 1:
return
self._fh.seek(size-1, 1)
self._fh.write(b'\x00') | Write a Python 3 script to
append size bytes to file. | You are a Python code generator, capable of creating scripts from specifications. |
Write numpy array to binary file. | Here you have a function in Python 3, explain what it does
def write_array(self, data):
try:
data.tofile(self._fh)
except Exception:
# BytesIO
self._fh.write(data.tostring()) | You are a Python code architect, reviewing and designing scalable and efficient code |
def seek(self, offset, whence=0):
"""Set file's current position."""
if self._offset:
if whence == 0:
self._fh.seek(self._offset + offset, whence)
return
if whence == 2 and self._size > 0:
self._fh.seek(self._offset + self._size + o... | Implement a Python 3 function for
setting file s current position. | As a Python code analyst, you investigate and solve complex coding mysteries |
def open(self, filehandle):
"""Re-open file if necessary."""
with self.lock:
if filehandle in self.files:
self.files[filehandle] += 1
elif filehandle.closed:
filehandle.open()
self.files[filehandle] = 1
self.past.app... | How would you code a function in Python 3 to
re-open file if necessary. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Close openend file if no longer used. | Can you generate a brief explanation for the following Python 3 code
def close(self, filehandle):
with self.lock:
if filehandle in self.files:
self.files[filehandle] -= 1
# trim the file cache
index = 0
size = len(self.past)
... | You are a Python code generator, capable of creating scripts from specifications. |
def clear(self):
"""Close all opened files if not in use."""
with self.lock:
for filehandle, refcount in list(self.files.items()):
if refcount == 0:
filehandle.close()
del self.files[filehandle]
del self.past[self.pa... | Can you create a Python 3 function that
closes all opened files if not in use. | As a Python code analyst, you investigate and solve complex coding mysteries |
Parse a literal from the template | Can you generate a brief explanation for the following Python 3 code
def grab_literal(template, l_del):
global _CURRENT_LINE
try:
# Look for the next tag and move the template to it
literal, template = template.split(l_del, 1)
_CURRENT_LINE += literal.count('\n')
return (litera... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def l_sa_check(template, literal, is_standalone):
"""Do a preliminary check to see if a tag could be a standalone"""
# If there is a newline, or the previous tag was a standalone
if literal.find('\n') != -1 or is_standalone:
padding = literal.split('\n')[-1]
# If all the characters since t... | Implement a Python 3 function for
doing a preliminary check to see if a tag could be a standalone | You are a Python code generator, capable of creating scripts from specifications. |
def r_sa_check(template, tag_type, is_standalone):
"""Do a final checkto see if a tag could be a standalone"""
# Check right side if we might be a standalone
if is_standalone and tag_type not in ['variable', 'no escape']:
on_newline = template.split('\n', 1)
# If the stuff to the right of ... | Implement a Python 3 function for
doing a final checkto see if a tag could be a standalone | You are a Python code architect, reviewing and designing scalable and efficient code |
Parse a tag from a template | Explain what the following Python 3 code does
def parse_tag(template, l_del, r_del):
global _CURRENT_LINE
global _LAST_TAG_LINE
tag_types = {
'!': 'comment',
'#': 'section',
'^': 'inverted section',
'/': 'end',
'>': 'partial',
'=': 'set delimiter?',
'... | You are a Python code analyst, evaluating scripts for potential improvements. |
Tokenizes a mustache template in a generator fashion. | Can you generate a brief explanation for the following Python 3 code
def tokenize(template, def_ldel='{{', def_rdel='}}'):
global _CURRENT_LINE, _LAST_TAG_LINE
_CURRENT_LINE = 1
_LAST_TAG_LINE = None
# If the template is a file-like object then read it
try:
template = template.read()
ex... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def cli_main():
"""Render mustache templates using json files"""
import argparse
import os
def is_file_or_pipe(arg):
if not os.path.exists(arg) or os.path.isdir(arg):
parser.error('The file {0} does not exist!'.format(arg))
else:
return arg
def is_dir(arg):
... | Implement a Python 3 function for
rendering mustache templates using json files | As a Python code analyst, you investigate and solve complex coding mysteries |
HTML escape all of these & < > | Can you tell what is the following Python 3 function doing
def _html_escape(string):
html_codes = {
'"': '"',
'<': '<',
'>': '>',
}
# & must be handled first
string = string.replace('&', '&')
for char in html_codes:
string = string.replace(char, html_... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Get a key from the current scope | Can you tell what is the following Python 3 function doing
def _get_key(key, scopes):
# If the key is a dot
if key == '.':
# Then just return the current scope
return scopes[0]
# Loop through the scopes
for scope in scopes:
try:
# For every dot seperated key
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _get_partial(name, partials_dict, partials_path, partials_ext):
"""Load a partial"""
try:
# Maybe the partial is in the dictionary
return partials_dict[name]
except KeyError:
# Nope...
try:
# Maybe it's in the file system
path_ext = ('.' + partials... | How would you implement a function in Python 3 that
loads a partial from the dictionary | As a Python code composer, you craft elegant and concise scripts. |
def render(template='', data={}, partials_path='.', partials_ext='mustache',
partials_dict={}, padding='', def_ldel='{{', def_rdel='}}',
scopes=None):
"""Render a mustache template.
Renders a mustache template with a data scope and partial capability.
Given the file structure...
╷... | Write a Python 3 function for
rendering a mustache template. | You are a Python code architect, reviewing and designing scalable and efficient code |
Bulk add a new item to the user s list
| Here you have a function in Python 3, explain what it does
def bulk_add(
self, item_id, ref_id=None, tags=None, time=None, title=None,
url=None, wait=True
):
'''
Add a new item to the user's list
http://getpocket.com/developer/docs/v3/modify#action_add
''' | As a python code expert, you are capable of creating scripts from specifications. |
def get_request_token(
cls, consumer_key, redirect_uri='http://example.com/', state=None
):
'''
Returns the request token that can be used to fetch the access token
'''
headers = {
'X-Accept': 'application/json',
}
url = 'https://getpocket.com/v3/... | Create a Python 3 function to
return the request token that can be used to fetch the access token | As a Python code composer, you craft elegant and concise scripts. |
def get_credentials(cls, consumer_key, code):
'''
Fetches access token from using the request token and consumer key
'''
headers = {
'X-Accept': 'application/json',
}
url = 'https://getpocket.com/v3/oauth/authorize'
payload = {
'consumer_k... | Implement a function in Python 3 to
fetch access token from using the request token and consumer key and code. | As a Python code composer, you craft elegant and concise scripts. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.