_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q251500 | FlexFieldsSerializerMixin._get_expand_input | train | def _get_expand_input(self, passed_settings):
"""
If expand value is explicitliy passed, just return it.
If parsing from request, ensure that the value complies with
the "permitted_expands" list passed into the context from the
FlexFieldsMixin.
"""
... | python | {
"resource": ""
} |
q251501 | is_expanded | train | def is_expanded(request, key):
""" Examines request object to return boolean of whether
passed field is expanded.
"""
expand = request.query_params.get("expand", "")
expand_fields = []
for e in | python | {
"resource": ""
} |
q251502 | color_replace | train | def color_replace(image, color):
"""Replace black with other color
:color: custom color (r,g,b,a)
:image: image to replace color
:returns: TODO
"""
pixels = image.load()
size = image.size[0]
for width in range(size):
for height in range(size):
| python | {
"resource": ""
} |
q251503 | wrap_in_ndarray | train | def wrap_in_ndarray(value):
"""Wraps the argument in a numpy.ndarray.
If value is a scalar, it is converted in a list first.
If value is array-like, the shape is conserved.
| python | {
"resource": ""
} |
q251504 | coefficients_non_uni | train | def coefficients_non_uni(deriv, acc, coords, idx):
"""
Calculates the finite difference coefficients for given derivative order and accuracy order.
Assumes that the underlying grid is non-uniform.
:param deriv: int > 0: The derivative order.
:param acc: even int > 0: The accuracy order.
... | python | {
"resource": ""
} |
q251505 | _build_matrix | train | def _build_matrix(p, q, deriv):
"""Constructs the equation system matrix for the finite difference coefficients"""
A = [([1 for _ in range(-p, q+1)])]
for i | python | {
"resource": ""
} |
q251506 | _build_rhs | train | def _build_rhs(p, q, deriv):
"""The right hand side of the equation system matrix""" | python | {
"resource": ""
} |
q251507 | _build_matrix_non_uniform | train | def _build_matrix_non_uniform(p, q, coords, k):
"""Constructs the equation matrix for the finite difference coefficients of non-uniform grids at location k"""
A = [[1] * (p+q+1)]
for i in range(1, p + q + 1):
line = | python | {
"resource": ""
} |
q251508 | FinDiff.set_accuracy | train | def set_accuracy(self, acc):
""" Sets the accuracy order of the finite difference scheme.
If the FinDiff object is not a raw partial derivative but a composition of derivatives
| python | {
"resource": ""
} |
q251509 | FinDiff.diff | train | def diff(self, y, h, deriv, dim, coefs):
"""The core function to take a partial derivative on a uniform grid.
"""
try:
npts = y.shape[dim]
except AttributeError as err:
raise ValueError("FinDiff objects can only be applied to arrays or evaluated(!) functions retu... | python | {
"resource": ""
} |
q251510 | FinDiff.diff_non_uni | train | def diff_non_uni(self, y, coords, dim, coefs):
"""The core function to take a partial derivative on a non-uniform grid"""
yd = np.zeros_like(y)
ndims = len(y.shape)
multi_slice = [slice(None, None)] * ndims
ref_multi_slice = [slice(None, None)] * ndims
for i, x in enum... | python | {
"resource": ""
} |
q251511 | FinDiff._apply_to_array | train | def _apply_to_array(self, yd, y, weights, off_slices, ref_slice, dim):
"""Applies the finite differences only to slices along a given axis"""
ndims = len(y.shape)
all = slice(None, None, 1)
ref_multi_slice = [all] * ndims
ref_multi_slice[dim] = ref_slice
for w, s in z... | python | {
"resource": ""
} |
q251512 | get_current_user_info | train | def get_current_user_info(anchore_auth):
"""
Return the metadata about the current user as supplied by the anchore.io service. Includes permissions and tier access.
:return: Dict of user metadata
"""
user_url = anchore_auth['client_info_url'] + '/' | python | {
"resource": ""
} |
q251513 | show | train | def show(details):
"""
Show list of Anchore data policies.
"""
ecode = 0
try:
policymeta = anchore_policy.load_policymeta()
if details:
anchore_print(policymeta, do_formatting=True)
else:
output = {}
name = policymeta['name']
| python | {
"resource": ""
} |
q251514 | extended_help_option | train | def extended_help_option(extended_help=None, *param_decls, **attrs):
"""
Based on the click.help_option code.
Adds a ``--extended-help`` option which immediately ends the program
printing out the extended extended-help page. Defaults to using the
callback's doc string, but can be given an explicit ... | python | {
"resource": ""
} |
q251515 | anchore_print | train | def anchore_print(msg, do_formatting=False):
"""
Print to stdout using the proper formatting for the command.
:param msg: output to be printed, either an object or a string. Objects will be serialized according to config
| python | {
"resource": ""
} |
q251516 | build_image_list | train | def build_image_list(config, image, imagefile, all_local, include_allanchore, dockerfile=None, exclude_file=None):
"""Given option inputs from the cli, construct a list of image ids. Includes all found with no exclusion logic"""
if not image and not (imagefile or all_local):
raise click.BadOptionUsage(... | python | {
"resource": ""
} |
q251517 | init_output_formatters | train | def init_output_formatters(output_verbosity='normal', stderr=sys.stderr, logfile=None, debug_logfile=None):
"""
Initialize the CLI logging scheme.
:param output_verbosity: 'quiet','normal','verbose', or 'debug' controls the output to stdout and its format
:param stderr: stream for stderr output, defaul... | python | {
"resource": ""
} |
q251518 | main_entry | train | def main_entry(ctx, verbose, debug, quiet, json, plain, html, config_override):
"""
Anchore is a tool to analyze, query, and curate container images. The options at this top level
control stdout and stderr verbosity and format.
After installation, the first command run should be: 'anchore feeds
lis... | python | {
"resource": ""
} |
q251519 | get_user_agent | train | def get_user_agent():
"""
Construct and informative user-agent string.
Includes OS version and docker version info
Not thread-safe
:return:
"""
global user_agent_string
if user_agent_string is None:
# get OS type
try:
sysinfo = subprocess.check_output('lsb_r... | python | {
"resource": ""
} |
q251520 | normalize_headers | train | def normalize_headers(headers):
"""
Convert useful headers to a normalized type and return in a new dict
Only processes content-type, content-length, etag, and last-modified
:param headers:
:return:
"""
for (k, v) in headers.items():
headers.pop(k)
headers[k.lower()] = v
... | python | {
"resource": ""
} |
q251521 | get_resource_retriever | train | def get_resource_retriever(url):
"""
Get the appropriate retriever object for the specified url based on url scheme.
Makes assumption that HTTP urls do not require any special authorization.
For HTTP urls: returns HTTPResourceRetriever
For s3:// urls returns S3ResourceRetriever
:param url: url... | python | {
"resource": ""
} |
q251522 | ResourceCache.get | train | def get(self, url):
"""
Lookup the given url and return an entry if found. Else return None.
The returned entry is a dict with metadata about the content and a 'content' key with a file path value
| python | {
"resource": ""
} |
q251523 | ResourceCache._load | train | def _load(self, url):
"""
Load from remote, but check local file content to identify duplicate content. If local file is found with
same hash then it is used with metadata from remote object to avoid fetching full content.
:param url:
:return:
"""
self._logger.de... | python | {
"resource": ""
} |
q251524 | calc_file_md5 | train | def calc_file_md5(filepath, chunk_size=None):
"""
Calculate a file's md5 checksum. Use the specified chunk_size for IO or the
default 256KB
:param filepath:
:param chunk_size:
:return:
"""
if chunk_size is None:
chunk_size = 256 * 1024
md5sum = hashlib.md5()
with io.open... | python | {
"resource": ""
} |
q251525 | toolbox | train | def toolbox(anchore_config, ctx, image, imageid):
"""
A collection of tools for operating on images and containers and building anchore modules.
Subcommands operate on the specified image passed in as --image <imgid>
"""
global config, imagelist, nav
config = anchore_config
ecode = 0
... | python | {
"resource": ""
} |
q251526 | unpack | train | def unpack(destdir):
"""Unpack and Squash image to local filesystem"""
if not nav:
sys.exit(1)
ecode = 0
try:
anchore_print("Unpacking images: " + ' '.join(nav.get_images()))
result = nav.unpack(destdir=destdir)
if not result:
anchore_print_err("no images un... | python | {
"resource": ""
} |
q251527 | show_analyzer_status | train | def show_analyzer_status():
"""Show analyzer status for specified image"""
ecode = 0
try:
image=contexts['anchore_allimages'][imagelist[0]]
analyzer_status = contexts['anchore_db'].load_analyzer_manifest(image.meta['imageId'])
result = {image.meta['imageId']:{'result':{'header':['An... | python | {
"resource": ""
} |
q251528 | export | train | def export(outfile):
"""Export image anchore data to a JSON file."""
if not nav:
sys.exit(1)
ecode = 0
savelist = list()
for imageId in imagelist:
try:
record = {}
record['image'] = {}
record['image']['imageId'] = imageId
record['ima... | python | {
"resource": ""
} |
q251529 | image_import | train | def image_import(infile, force):
"""Import image anchore data from a JSON file."""
ecode = 0
try:
with open(infile, 'r') as FH:
savelist = json.loads(FH.read())
except Exception as err:
anchore_print_err("could not load input file: " + str(err))
ecode = 1
if... | python | {
"resource": ""
} |
q251530 | status | train | def status(conf):
"""
Show anchore system status.
"""
ecode = 0
try:
if conf:
if config.cliargs['json']:
anchore_print(config.data, do_formatting=True)
else:
anchore_print(yaml.safe_dump(config.data, indent=True, default_flow_style=Fal... | python | {
"resource": ""
} |
q251531 | show_schemas | train | def show_schemas(schemaname):
"""
Show anchore document schemas.
"""
ecode = 0
try:
schemas = {}
schema_dir = os.path.join(contexts['anchore_config']['pkg_dir'], 'schemas')
for f in os.listdir(schema_dir):
sdata = {}
try:
with open(os.... | python | {
"resource": ""
} |
q251532 | backup | train | def backup(outputdir):
"""
Backup an anchore installation to a tarfile.
"""
ecode = 0
try:
anchore_print('Backing up anchore system to directory '+str(outputdir)+' ...')
backupfile = config.backup(outputdir)
| python | {
"resource": ""
} |
q251533 | restore | train | def restore(inputfile, destination_root):
"""
Restore an anchore installation from a previously backed up tar file.
"""
ecode = 0
try:
anchore_print('Restoring anchore system from backup file %s ...' % (str(inputfile.name)))
restoredir = | python | {
"resource": ""
} |
q251534 | exportdb | train | def exportdb(outdir):
"""Export all anchore images to JSON files"""
ecode = 0
try:
imgdir = os.path.join(outdir, "images")
feeddir = os.path.join(outdir, "feeds")
storedir = os.path.join(outdir, "storedfiles")
for d in [outdir, imgdir, feeddir, storedir]:
if not ... | python | {
"resource": ""
} |
q251535 | next_token | train | def next_token(expected_type, data):
"""
Based on the expected next type, consume the next token returning the type found and an updated buffer with the found token
removed
:param expected_type:
:param data:
:return: (TokenType, str) tuple where TokenType is the type of the next token expected
... | python | {
"resource": ""
} |
q251536 | show | train | def show(feed):
"""
Show detailed feed information
"""
ecode = 0
try:
feedmeta = anchore_feeds.load_anchore_feedmeta()
if feed in feedmeta:
result = {}
groups = feedmeta[feed].get('groups',{}).values()
result['name'] = feed
result['acc... | python | {
"resource": ""
} |
q251537 | list | train | def list(showgroups):
"""
Show list of Anchore data feeds.
"""
ecode = 0
try:
result = {}
subscribed = {}
available = {}
unavailable = {}
current_user_data = contexts['anchore_auth']['user_info']
feedmeta = anchore_feeds.load_anchore_feedmeta()
... | python | {
"resource": ""
} |
q251538 | SelectionStrategy.evaluate_familytree | train | def evaluate_familytree(self, family_tree, image_set):
"""
Evaluate strategy for the given family tree and return a dict of images to analyze that match the strategy
:param family_tree: the family tree to traverse and evaluate
:param image_set: list of all images in the context
... | python | {
"resource": ""
} |
q251539 | logout | train | def logout(anchore_config):
"""
Log out of Anchore service
"""
ecode = 0
try:
aa = contexts['anchore_auth']
if aa:
anchore_auth.anchore_auth_invalidate(aa)
if 'auth_file' in aa:
os.remove(aa['auth_file'])
| python | {
"resource": ""
} |
q251540 | Instance.connect | train | async def connect(self):
"""
Get an connection for the self instance
"""
if isinstance(self.connection, dict):
# a dict like {'host': 'localhost', 'port': 6379,
# 'db': 0, 'password': 'pass'}
kwargs = self.connection.copy()
ad... | python | {
"resource": ""
} |
q251541 | Instance.close | train | async def close(self):
"""
Closes connection and resets pool
"""
if self._pool is not None and not isinstance(self.connection, aioredis.Redis):
| python | {
"resource": ""
} |
q251542 | Redis.set_lock | train | async def set_lock(self, resource, lock_identifier):
"""
Tries to set the lock to all the redis instances
:param resource: The resource string name to lock
:param lock_identifier: The id of the lock. A unique string
:return float: The elapsed time that took to lock the instances... | python | {
"resource": ""
} |
q251543 | Redis.unset_lock | train | async def unset_lock(self, resource, lock_identifier):
"""
Tries to unset the lock to all the redis instances
:param resource: The resource string name to lock
:param lock_identifier: The id of the lock. A unique string
:return float: The elapsed time that took to lock the insta... | python | {
"resource": ""
} |
q251544 | _clean | train | def _clean(value):
""" Convert numpy numeric types to their python equivalents. """
if isinstance(value, np.ndarray):
if value.dtype.kind == 'S':
return np.char.decode(value).tolist()
else:
return value.tolist()
elif type(value).__module__ == np.__name__:
# h5... | python | {
"resource": ""
} |
q251545 | Basecall2DTools.get_prior_alignment | train | def get_prior_alignment(self):
""" Return the prior alignment that was used for 2D basecalling.
:return: Alignment data table.
"""
| python | {
"resource": ""
} |
q251546 | Basecall2DTools.get_2d_call_alignment | train | def get_2d_call_alignment(self):
""" Return the alignment and model_states from the 2D basecall.
:return: Alignment data table.
"""
| python | {
"resource": ""
} |
q251547 | AlignmentTools.get_results | train | def get_results(self):
""" Get details about the alignments that have been performed.
:return: A dict of dicts.
The keys of the top level are 'template', 'complement' and '2d'.
Each of these dicts contains the following fields:
* status: Can be 'no data', 'no match found',... | python | {
"resource": ""
} |
q251548 | AlignmentTools.calculate_speed | train | def calculate_speed(self, section, alignment_results=None):
""" Calculate speed using alignment information.
:param section: The section (template or complement) we're calculating
speed for.
:param alignment_results: Optional dictionary of the alignment summary,
so that ... | python | {
"resource": ""
} |
q251549 | Fast5Read.add_raw_data | train | def add_raw_data(self, data, attrs):
""" Add raw data for a read.
:param data: The raw data DAQ values (16 bit integers).
The read must already exist in the file. It must not already
have raw data.
"""
self.assert_writeable()
if "Raw" | python | {
"resource": ""
} |
q251550 | Fast5Read.add_channel_info | train | def add_channel_info(self, attrs, clear=False):
""" Add channel info data to the channel_id group.
:param data: A dictionary of key/value pairs. Keys must be strings.
Values can be strings or numeric values.
:param clear: If set, any existing channel info data will be removed.
... | python | {
"resource": ""
} |
q251551 | Fast5Read.add_analysis | train | def add_analysis(self, component, group_name, attrs, config=None):
""" Add a new analysis group to the file.
:param component: The component name.
:param group_name: The name to use for the group. Must not already
exist in the file e.g. 'Test_000'.
:param attrs: A dictionary... | python | {
"resource": ""
} |
q251552 | Fast5Writer.write_strand | train | def write_strand(self, strand):
""" Writes a Strand object to the stream. """
if strand['channel'] != self._current_channel \
or self._strand_counter == self._reads_per_file:
self._start_new_file(strand)
fname = self._write_strand(strand)
self._index.write('{}\t{}\... | python | {
"resource": ""
} |
q251553 | AbstractFast5File.close | train | def close(self):
""" Closes the object.
"""
if self._is_open:
self.mode = None
if self.handle:
self.handle.close()
| python | {
"resource": ""
} |
q251554 | Fast5File.add_chain | train | def add_chain(self, group_name, component_map):
"""
Adds the component chain to ``group_name`` in the fast5.
These are added as attributes to the group.
:param group_name: The group name you wish to add chaining data to,
e.g. ``Test_000``
:param component_map: The se... | python | {
"resource": ""
} |
q251555 | Fast5File.add_read | train | def add_read(self, read_number, read_id, start_time, duration, mux, median_before):
""" Add a new read to the file.
:param read_number: The read number to assign to the read.
:param read_id: The unique read-id for the read.
:param start_time: The start time (in samples) of the read.
... | python | {
"resource": ""
} |
q251556 | Fast5File.set_summary_data | train | def set_summary_data(self, group_name, section_name, data):
""" Set the summary data for an analysis group.
:param group_name: The name of the analysis group.
:param section_name: The analysis step. This will become a
subfolder in the Summary section.
:param data: A dictiona... | python | {
"resource": ""
} |
q251557 | Fast5File.get_analysis_config | train | def get_analysis_config(self, group_name):
""" Gets any config data saved for the analysis.
:param group_name: The name of the analysis group.
:returns: A dictionary of dictionaries. Each key represents
an analysis step. Each value is a dictionary containing the
analysis... | python | {
"resource": ""
} |
q251558 | Fast5File.read_summary_data | train | def read_summary_data(fname, component):
""" Read summary data suitable to encode as a json packet.
:param fname: The fast5 file to pull the summary data from.
:param component: The component name to pull summary data for.
:returns: A dictionary containing the summary data.
"""... | python | {
"resource": ""
} |
q251559 | BaseTransportMixin.get_conn_info | train | def get_conn_info(self):
"""Return `ConnectionInfo` object from current transport"""
return session.ConnectionInfo(self.request.remote_ip,
self.request.cookies,
| python | {
"resource": ""
} |
q251560 | SessionContainer.remove | train | def remove(self, session_id):
"""Remove session object from the container
`session_id`
Session identifier
"""
session = self._items.get(session_id, None)
if session is not None:
session.promoted = -1
| python | {
"resource": ""
} |
q251561 | StreamingTransportBase.send_complete | train | def send_complete(self):
"""
Verify if connection should be closed based on amount of data that was sent.
"""
self.active = True
if self.should_finish():
self._detach()
# Avoid race condition when waiting for write callback and | python | {
"resource": ""
} |
q251562 | SockJSConnection.send | train | def send(self, message, binary=False):
"""Send message to the client.
`message`
| python | {
"resource": ""
} |
q251563 | StatsCollector.dump | train | def dump(self):
"""Return dictionary with current statistical information"""
data = dict(
# Sessions
sessions_active=self.sess_active,
# Connections
connections_active=self.conn_active,
connections_ps=self.conn_ps.last_average,
# ... | python | {
"resource": ""
} |
q251564 | BaseHandler.finish | train | def finish(self, chunk=None):
"""Tornado `finish` handler"""
self._log_disconnect() | python | {
"resource": ""
} |
q251565 | BaseHandler.handle_session_cookie | train | def handle_session_cookie(self):
"""Handle JSESSIONID cookie logic"""
# If JSESSIONID support is disabled in the settings, ignore cookie logic
if not self.server.settings['jsessionid']:
return
cookie = self.cookies.get('JSESSIONID')
| python | {
"resource": ""
} |
q251566 | PreflightHandler.options | train | def options(self, *args, **kwargs):
"""XHR cross-domain OPTIONS handler"""
self.enable_cache()
self.handle_session_cookie()
self.preflight()
if self.verify_origin():
allowed_methods = getattr(self, | python | {
"resource": ""
} |
q251567 | PreflightHandler.preflight | train | def preflight(self):
"""Handles request authentication"""
origin = self.request.headers.get('Origin', '*')
self.set_header('Access-Control-Allow-Origin', origin)
| python | {
"resource": ""
} |
q251568 | ConnectionInfo.get_argument | train | def get_argument(self, name):
"""Return single argument by name"""
val = self.arguments.get(name)
| python | {
"resource": ""
} |
q251569 | BaseSession.verify_state | train | def verify_state(self):
"""Verify if session was not yet opened. If it is, open it and call connections `on_open`"""
if self.state == CONNECTING:
| python | {
"resource": ""
} |
q251570 | BaseSession.delayed_close | train | def delayed_close(self):
"""Delayed close - won't close immediately, but | python | {
"resource": ""
} |
q251571 | Session.on_delete | train | def on_delete(self, forced):
"""Session expiration callback
`forced`
If session item explicitly deleted, forced will be set to True. If
item expired, will be set to False.
"""
# Do not remove connection if it was not forced and there's running | python | {
"resource": ""
} |
q251572 | Session.remove_handler | train | def remove_handler(self, handler):
"""Detach active handler from the session
`handler`
| python | {
"resource": ""
} |
q251573 | WebsocketHandler.on_open | train | def on_open(self, info):
"""sockjs-tornado on_open handler"""
# Store some properties
self.ip = info.ip
| python | {
"resource": ""
} |
q251574 | GenericContentsManager._notebook_model_from_path | train | def _notebook_model_from_path(self, path, content=False, format=None):
"""
Build a notebook model from database record.
"""
model = base_model(path)
model["type"] = "notebook"
if self.fs.isfile(path):
model["last_modified"] = model["created"] = self.fs.lstat(p... | python | {
"resource": ""
} |
q251575 | GenericContentsManager._file_model_from_path | train | def _file_model_from_path(self, path, content=False, format=None):
"""
Build a file model from database record.
"""
model = base_model(path)
model["type"] = "file"
if self.fs.isfile(path):
model["last_modified"] = model["created"] = self.fs.lstat(path)["ST_MTI... | python | {
"resource": ""
} |
q251576 | GenericContentsManager._convert_file_records | train | def _convert_file_records(self, paths):
"""
Applies _notebook_model_from_s3_path or _file_model_from_s3_path to each entry of `paths`,
depending on the result of `guess_type`.
"""
ret = []
for path in paths:
# path = self.fs.remove_prefix(path, self.prefix) #... | python | {
"resource": ""
} |
q251577 | GenericContentsManager.save | train | def save(self, model, path):
"""Save a file or directory model to path.
"""
self.log.debug("S3contents.GenericManager: save %s: '%s'", model, path)
if "type" not in model:
self.do_error("No model type provided", 400)
if "content" not in model and model["type"] != "dir... | python | {
"resource": ""
} |
q251578 | GenericContentsManager.rename_file | train | def rename_file(self, old_path, new_path):
"""Rename a file or directory.
NOTE: This method is unfortunately named on the base class. It
actually moves a file or a directory.
"""
self.log.debug("S3contents.GenericManager: Init rename of '%s' to '%s'", old_path, new_path)
... | python | {
"resource": ""
} |
q251579 | GenericContentsManager.delete_file | train | def delete_file(self, path):
"""Delete the file or directory at path.
"""
self.log.debug("S3contents.GenericManager: delete_file '%s'", path)
| python | {
"resource": ""
} |
q251580 | GCSFS.path | train | def path(self, *path):
"""Utility to join paths including the bucket and prefix"""
path = list(filter(None, path))
path = | python | {
"resource": ""
} |
q251581 | RestClient.get | train | def get(url, params={}):
"""Invoke an HTTP GET request on a url
Args:
url (string): URL endpoint to request
params (dict): Dictionary of url parameters
Returns:
dict: JSON response as a dictionary
| python | {
"resource": ""
} |
q251582 | QueryBuilder.find | train | def find(self, id):
"""Get a resource by its id
Args:
id (string): Resource id
Returns:
object: Instance of the resource type
"""
| python | {
"resource": ""
} |
q251583 | QueryBuilder.find_many | train | def find_many(self, url, type, resource):
"""Get a list of resources
Args:
url (string): URL to invoke
type (class): Class type
resource (string): The REST Resource
Returns:
| python | {
"resource": ""
} |
q251584 | QueryBuilder.iter | train | def iter(self):
"""Gets all resources, automating paging through data
Returns:
iterable of object: Iterable of resource objects
"""
page = 1
fetch_all = True
url = "{}/{}".format(__endpoint__, self.type.RESOURCE)
if 'page' in self.params:
... | python | {
"resource": ""
} |
q251585 | QueryBuilder.array | train | def array(self):
"""Get all resources and return the result as an array
Returns:
array of str: Array of resources
"""
| python | {
"resource": ""
} |
q251586 | make2d | train | def make2d(array, cols=None, dtype=None):
'''
Make a 2D array from an array of arrays. The `cols' and `dtype'
arguments can be omitted if the array is not empty.
'''
if not len(array):
if cols is None or dtype is None:
| python | {
"resource": ""
} |
q251587 | PlyData._parse_header | train | def _parse_header(stream):
'''
Parse a PLY header from a readable file-like stream.
'''
parser = _PlyHeaderParser()
while parser.consume(stream.readline()):
pass
return PlyData(
| python | {
"resource": ""
} |
q251588 | PlyData.read | train | def read(stream):
'''
Read PLY data from a readable file-like object or filename.
'''
(must_close, stream) = _open_stream(stream, 'read')
try:
data = PlyData._parse_header(stream)
| python | {
"resource": ""
} |
q251589 | PlyData.write | train | def write(self, stream):
'''
Write PLY data to a writeable file-like object or filename.
'''
(must_close, stream) = _open_stream(stream, 'write')
try:
stream.write(self.header.encode('ascii'))
stream.write(b'\n')
| python | {
"resource": ""
} |
q251590 | PlyData.header | train | def header(self):
'''
Provide PLY-formatted metadata for the instance.
'''
lines = ['ply']
if self.text:
lines.append('format ascii 1.0')
else:
lines.append('format ' +
_byte_order_reverse[self.byte_order] +
... | python | {
"resource": ""
} |
q251591 | PlyElement.describe | train | def describe(data, name, len_types={}, val_types={},
comments=[]):
'''
Construct a PlyElement from an array's metadata.
len_types and val_types can be given as mappings from list
property names to type strings (like 'u1', 'f4', etc., or
'int8', 'float32', etc.).... | python | {
"resource": ""
} |
q251592 | PlyElement._read | train | def _read(self, stream, text, byte_order):
'''
Read the actual data from a PLY file.
'''
dtype = self.dtype(byte_order)
if text:
self._read_txt(stream)
elif _can_mmap(stream) and not self._have_list:
# Loading the data is straightforward. We will... | python | {
"resource": ""
} |
q251593 | PlyElement._write | train | def _write(self, stream, text, byte_order):
'''
Write the data to a PLY file.
'''
if text:
self._write_txt(stream)
else:
if self._have_list:
# There are list properties, so serialization is
# slightly complicated.
... | python | {
"resource": ""
} |
q251594 | PlyElement._read_txt | train | def _read_txt(self, stream):
'''
Load a PLY element from an ASCII-format PLY file. The element
may contain list properties.
'''
self._data = _np.empty(self.count, dtype=self.dtype())
k = 0
for line in _islice(iter(stream.readline, b''), self.count):
... | python | {
"resource": ""
} |
q251595 | PlyElement._write_txt | train | def _write_txt(self, stream):
'''
Save a PLY element to an ASCII-format PLY file. The element may
contain list properties.
'''
for rec in self.data:
fields = []
| python | {
"resource": ""
} |
q251596 | PlyElement._read_bin | train | def _read_bin(self, stream, byte_order):
'''
Load a PLY element from a binary PLY file. The element may
contain list properties.
'''
self._data = _np.empty(self.count, dtype=self.dtype(byte_order))
for k in _range(self.count):
for prop in self.properties:
... | python | {
"resource": ""
} |
q251597 | PlyElement._write_bin | train | def _write_bin(self, stream, byte_order):
'''
Save a PLY element to a binary PLY file. The element may
contain list properties.
'''
for rec in self.data:
| python | {
"resource": ""
} |
q251598 | PlyElement.header | train | def header(self):
'''
Format this element's metadata as it would appear in a PLY
header.
'''
lines = ['element %s %d' % (self.name, self.count)]
# Some information is lost here, since all comments are placed
# between the 'element' line and the first property de... | python | {
"resource": ""
} |
q251599 | PlyProperty._from_fields | train | def _from_fields(self, fields):
'''
Parse from generator. Raise StopIteration if the property could
not be read.
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.