_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q14400
setup_decoder
train
def setup_decoder(codec, dparams): """Wraps openjp2 library function opj_setup_decoder. Setup the decoder with decompression parameters. Parameters ---------- codec: CODEC_TYPE Codec initialized by create_compress function. dparams: DecompressionParametersType Decompression p...
python
{ "resource": "" }
q14401
setup_encoder
train
def setup_encoder(codec, cparams, image): """Wraps openjp2 library function opj_setup_encoder. Setup the encoder parameters using the current image and using user parameters. Parameters ---------- codec : CODEC_TYPE codec initialized by create_compress function cparams : Compressio...
python
{ "resource": "" }
q14402
start_compress
train
def start_compress(codec, image, stream): """Wraps openjp2 library function opj_start_compress. Start to compress the current image. Parameters ---------- codec : CODEC_TYPE Compressor handle. image : pointer to ImageType Input filled image. stream : STREAM_TYPE_P I...
python
{ "resource": "" }
q14403
stream_create_default_file_stream
train
def stream_create_default_file_stream(fname, isa_read_stream): """Wraps openjp2 library function opj_stream_create_default_vile_stream. Sets the stream to be a file stream. This function is only valid for the 2.1 version of the openjp2 library. Parameters ---------- fname : str Specif...
python
{ "resource": "" }
q14404
stream_destroy
train
def stream_destroy(stream): """Wraps openjp2 library function opj_stream_destroy. Destroys the stream created by create_stream. Parameters ---------- stream : STREAM_TYPE_P The file stream. """ OPENJP2.opj_stream_destroy.argtypes = [STREAM_TYPE_P] OPENJP2.opj_stream_destroy.res...
python
{ "resource": "" }
q14405
write_tile
train
def write_tile(codec, tile_index, data, data_size, stream): """Wraps openjp2 library function opj_write_tile. Write a tile into an image. Parameters ---------- codec : CODEC_TYPE The jpeg2000 codec tile_index : int The index of the tile to write, zero-indexing assumed data ...
python
{ "resource": "" }
q14406
removeZeroLenPadding
train
def removeZeroLenPadding(str, blocksize=AES_blocksize): 'Remove Padding with zeroes + last byte equal to the number of padding bytes' try: pad_len = ord(str[-1]) # last byte contains number of padding bytes except TypeError: pad_len = str[-1] assert pad_len < blocksize, 'padding error' assert pad_len...
python
{ "resource": "" }
q14407
appendNullPadding
train
def appendNullPadding(str, blocksize=AES_blocksize): 'Pad with null bytes' pad_len = paddingLength(len(str), blocksize) padding = '\0'*pad_len return str + padding
python
{ "resource": "" }
q14408
removeNullPadding
train
def removeNullPadding(str, blocksize=AES_blocksize): 'Remove padding with null bytes' pad_len = 0 for char in str[::-1]: # str[::-1] reverses string if char == '\0': pad_len += 1 else: break str = str[:-pad_len] return str
python
{ "resource": "" }
q14409
appendSpacePadding
train
def appendSpacePadding(str, blocksize=AES_blocksize): 'Pad with spaces' pad_len = paddingLength(len(str), blocksize) padding = '\0'*pad_len return str + padding
python
{ "resource": "" }
q14410
removeSpacePadding
train
def removeSpacePadding(str, blocksize=AES_blocksize): 'Remove padding with spaces' pad_len = 0 for char in str[::-1]: # str[::-1] reverses string if char == ' ': pad_len += 1 else: break str = str[:-pad_len] return str
python
{ "resource": "" }
q14411
_default_error_handler
train
def _default_error_handler(msg, _): """Default error handler callback for libopenjp2.""" msg = "OpenJPEG library error: {0}".format(msg.decode('utf-8').rstrip()) opj2.set_error_message(msg)
python
{ "resource": "" }
q14412
_default_warning_handler
train
def _default_warning_handler(library_msg, _): """Default warning handler callback.""" library_msg = library_msg.decode('utf-8').rstrip() msg = "OpenJPEG library warning: {0}".format(library_msg) warnings.warn(msg, UserWarning)
python
{ "resource": "" }
q14413
Jp2k.parse
train
def parse(self): """Parses the JPEG 2000 file. Raises ------ IOError The file was not JPEG 2000. """ self.length = os.path.getsize(self.filename) with open(self.filename, 'rb') as fptr: # Make sure we have a JPEG2000 file. It could be e...
python
{ "resource": "" }
q14414
Jp2k._validate
train
def _validate(self): """Validate the JPEG 2000 outermost superbox. These checks must be done at a file level. """ # A JP2 file must contain certain boxes. The 2nd box must be a file # type box. if not isinstance(self.box[1], FileTypeBox): msg = "{filename} d...
python
{ "resource": "" }
q14415
Jp2k._set_cinema_params
train
def _set_cinema_params(self, cinema_mode, fps): """Populate compression parameters structure for cinema2K. Parameters ---------- params : ctypes struct Corresponds to compression parameters structure used by the library. cinema_mode : {'cinema2k', 'cinema...
python
{ "resource": "" }
q14416
Jp2k._write_openjpeg
train
def _write_openjpeg(self, img_array, verbose=False): """ Write JPEG 2000 file using OpenJPEG 1.5 interface. """ if img_array.ndim == 2: # Force the image to be 3D. Just makes things easier later on. img_array = img_array.reshape(img_array.shape[0], ...
python
{ "resource": "" }
q14417
Jp2k._validate_j2k_colorspace
train
def _validate_j2k_colorspace(self, cparams, colorspace): """ Cannot specify a colorspace with J2K. """ if cparams.codec_fmt == opj2.CODEC_J2K and colorspace is not None: msg = 'Do not specify a colorspace when writing a raw codestream.' raise IOError(msg)
python
{ "resource": "" }
q14418
Jp2k._validate_codeblock_size
train
def _validate_codeblock_size(self, cparams): """ Code block dimensions must satisfy certain restrictions. They must both be a power of 2 and the total area defined by the width and height cannot be either too great or too small for the codec. """ if cparams.cblockw_init ...
python
{ "resource": "" }
q14419
Jp2k._validate_precinct_size
train
def _validate_precinct_size(self, cparams): """ Precinct dimensions must satisfy certain restrictions if specified. They must both be a power of 2 and must both be at least twice the size of their codeblock size counterparts. """ code_block_specified = False if c...
python
{ "resource": "" }
q14420
Jp2k._validate_image_rank
train
def _validate_image_rank(self, img_array): """ Images must be either 2D or 3D. """ if img_array.ndim == 1 or img_array.ndim > 3: msg = "{0}D imagery is not allowed.".format(img_array.ndim) raise IOError(msg)
python
{ "resource": "" }
q14421
Jp2k._validate_image_datatype
train
def _validate_image_datatype(self, img_array): """ Only uint8 and uint16 images are currently supported. """ if img_array.dtype != np.uint8 and img_array.dtype != np.uint16: msg = ("Only uint8 and uint16 datatypes are currently supported " "when writing.") ...
python
{ "resource": "" }
q14422
Jp2k._validate_compression_params
train
def _validate_compression_params(self, img_array, cparams, colorspace): """Check that the compression parameters are valid. Parameters ---------- img_array : ndarray Image data to be written to file. cparams : CompressionParametersType(ctypes.Structure) C...
python
{ "resource": "" }
q14423
Jp2k._determine_colorspace
train
def _determine_colorspace(self, colorspace=None, **kwargs): """Determine the colorspace from the supplied inputs. Parameters ---------- colorspace : str, optional Either 'rgb' or 'gray'. """ if colorspace is None: # Must infer the colorspace from ...
python
{ "resource": "" }
q14424
Jp2k._write_openjp2
train
def _write_openjp2(self, img_array, verbose=False): """ Write JPEG 2000 file using OpenJPEG 2.x interface. """ if img_array.ndim == 2: # Force the image to be 3D. Just makes things easier later on. numrows, numcols = img_array.shape img_array = img_ar...
python
{ "resource": "" }
q14425
Jp2k.append
train
def append(self, box): """Append a JP2 box to the file in-place. Parameters ---------- box : Jp2Box Instance of a JP2 box. Only UUID and XML boxes can currently be appended. """ if self._codec_format == opj2.CODEC_J2K: msg = "Only JP2...
python
{ "resource": "" }
q14426
Jp2k._write_wrapped_codestream
train
def _write_wrapped_codestream(self, ofile, box): """Write wrapped codestream.""" # Codestreams require a bit more care. # Am I a raw codestream? if len(self.box) == 0: # Yes, just write the codestream box header plus all # of myself out to file. ofile....
python
{ "resource": "" }
q14427
Jp2k._get_default_jp2_boxes
train
def _get_default_jp2_boxes(self): """Create a default set of JP2 boxes.""" # Try to create a reasonable default. boxes = [JPEG2000SignatureBox(), FileTypeBox(), JP2HeaderBox(), ContiguousCodestreamBox()] height = self.codestream.segment[...
python
{ "resource": "" }
q14428
Jp2k._remove_ellipsis
train
def _remove_ellipsis(self, index, numrows, numcols, numbands): """ resolve the first ellipsis in the index so that it references the image Parameters ---------- index : tuple tuple of index arguments, presumably one of them is the Ellipsis numrows, numcols, n...
python
{ "resource": "" }
q14429
Jp2k._subsampling_sanity_check
train
def _subsampling_sanity_check(self): """Check for differing subsample factors. """ dxs = np.array(self.codestream.segment[1].xrsiz) dys = np.array(self.codestream.segment[1].yrsiz) if np.any(dxs - dxs[0]) or np.any(dys - dys[0]): msg = ("The read_bands method should b...
python
{ "resource": "" }
q14430
Jp2k._read_openjpeg
train
def _read_openjpeg(self, rlevel=0, verbose=False, area=None): """Read a JPEG 2000 image using libopenjpeg. Parameters ---------- rlevel : int, optional Factor by which to rlevel output resolution. Use -1 to get the lowest resolution thumbnail. verbose : ...
python
{ "resource": "" }
q14431
Jp2k._populate_dparams
train
def _populate_dparams(self, rlevel, tile=None, area=None): """Populate decompression structure with appropriate input parameters. Parameters ---------- rlevel : int Factor by which to rlevel output resolution. area : tuple Specifies decoding image area, ...
python
{ "resource": "" }
q14432
Jp2k._extract_image
train
def _extract_image(self, raw_image): """ Extract unequally-sized image bands. Parameters ---------- raw_image : reference to openjpeg ImageType instance The image structure initialized with image characteristics. Returns ------- list or ndarr...
python
{ "resource": "" }
q14433
Jp2k._component2dtype
train
def _component2dtype(self, component): """Determin the appropriate numpy datatype for an OpenJPEG component. Parameters ---------- component : ctypes pointer to ImageCompType (image_comp_t) single image component structure. Returns ------- builtins.t...
python
{ "resource": "" }
q14434
Jp2k.get_codestream
train
def get_codestream(self, header_only=True): """Retrieve codestream. Parameters ---------- header_only : bool, optional If True, only marker segments in the main header are parsed. Supplying False may impose a large performance penalty. Returns --...
python
{ "resource": "" }
q14435
Jp2k._populate_image_struct
train
def _populate_image_struct(self, image, imgdata): """Populates image struct needed for compression. Parameters ---------- image : ImageType(ctypes.Structure) Corresponds to image_t type in openjp2 headers. img_array : ndarray Image data to be written to f...
python
{ "resource": "" }
q14436
Jp2k._populate_comptparms
train
def _populate_comptparms(self, img_array): """Instantiate and populate comptparms structure. This structure defines the image components. Parameters ---------- img_array : ndarray Image data to be written to file. """ # Only two precisions are possib...
python
{ "resource": "" }
q14437
Jp2k._validate_nonzero_image_size
train
def _validate_nonzero_image_size(self, nrows, ncols, component_index): """The image cannot have area of zero. """ if nrows == 0 or ncols == 0: # Letting this situation continue would segfault openjpeg. msg = "Component {0} has dimensions {1} x {2}" msg = msg.f...
python
{ "resource": "" }
q14438
Jp2k._validate_jp2_box_sequence
train
def _validate_jp2_box_sequence(self, boxes): """Run through series of tests for JP2 box legality. This is non-exhaustive. """ JP2_IDS = ['colr', 'cdef', 'cmap', 'jp2c', 'ftyp', 'ihdr', 'jp2h', 'jP ', 'pclr', 'res ', 'resc', 'resd', 'xml ', 'ulst', ...
python
{ "resource": "" }
q14439
Jp2k._validate_jp2_colr
train
def _validate_jp2_colr(self, boxes): """ Validate JP2 requirements on colour specification boxes. """ lst = [box for box in boxes if box.box_id == 'jp2h'] jp2h = lst[0] for colr in [box for box in jp2h.box if box.box_id == 'colr']: if colr.approximation != 0: ...
python
{ "resource": "" }
q14440
Jp2k._validate_jpx_box_sequence
train
def _validate_jpx_box_sequence(self, boxes): """Run through series of tests for JPX box legality.""" self._validate_label(boxes) self._validate_jpx_compatibility(boxes, boxes[1].compatibility_list) self._validate_singletons(boxes) self._validate_top_level(boxes)
python
{ "resource": "" }
q14441
Jp2k._validate_signature_compatibility
train
def _validate_signature_compatibility(self, boxes): """Validate the file signature and compatibility status.""" # Check for a bad sequence of boxes. # 1st two boxes must be 'jP ' and 'ftyp' if boxes[0].box_id != 'jP ' or boxes[1].box_id != 'ftyp': msg = ("The first box must...
python
{ "resource": "" }
q14442
Jp2k._validate_jp2c
train
def _validate_jp2c(self, boxes): """Validate the codestream box in relation to other boxes.""" # jp2c must be preceeded by jp2h jp2h_lst = [idx for (idx, box) in enumerate(boxes) if box.box_id == 'jp2h'] jp2h_idx = jp2h_lst[0] jp2c_lst = [idx for (idx, box) in...
python
{ "resource": "" }
q14443
Jp2k._validate_jp2h
train
def _validate_jp2h(self, boxes): """Validate the JP2 Header box.""" self._check_jp2h_child_boxes(boxes, 'top-level') jp2h_lst = [box for box in boxes if box.box_id == 'jp2h'] jp2h = jp2h_lst[0] # 1st jp2 header box cannot be empty. if len(jp2h.box) == 0: msg...
python
{ "resource": "" }
q14444
Jp2k._validate_channel_definition
train
def _validate_channel_definition(self, jp2h, colr): """Validate the channel definition box.""" cdef_lst = [j for (j, box) in enumerate(jp2h.box) if box.box_id == 'cdef'] if len(cdef_lst) > 1: msg = ("Only one channel definition box is allowed in the " ...
python
{ "resource": "" }
q14445
Jp2k._check_jp2h_child_boxes
train
def _check_jp2h_child_boxes(self, boxes, parent_box_name): """Certain boxes can only reside in the JP2 header.""" JP2H_CHILDREN = set(['bpcc', 'cdef', 'cmap', 'ihdr', 'pclr']) box_ids = set([box.box_id for box in boxes]) intersection = box_ids.intersection(JP2H_CHILDREN) if len(...
python
{ "resource": "" }
q14446
Jp2k._collect_box_count
train
def _collect_box_count(self, boxes): """Count the occurences of each box type.""" count = Counter([box.box_id for box in boxes]) # Add the counts in the superboxes. for box in boxes: if hasattr(box, 'box'): count.update(self._collect_box_count(box.box)) ...
python
{ "resource": "" }
q14447
Jp2k._validate_singletons
train
def _validate_singletons(self, boxes): """Several boxes can only occur once.""" count = self._collect_box_count(boxes) # Which boxes occur more than once? multiples = [box_id for box_id, bcount in count.items() if bcount > 1] if 'dtbl' in multiples: raise IOError('The...
python
{ "resource": "" }
q14448
Jp2k._validate_jpx_compatibility
train
def _validate_jpx_compatibility(self, boxes, compatibility_list): """ If there is a JPX box then the compatibility list must also contain 'jpx '. """ JPX_IDS = ['asoc', 'nlst'] jpx_cl = set(compatibility_list) for box in boxes: if box.box_id in JPX_IDS...
python
{ "resource": "" }
q14449
Jp2k._validate_label
train
def _validate_label(self, boxes): """ Label boxes can only be inside association, codestream headers, or compositing layer header boxes. """ for box in boxes: if box.box_id != 'asoc': if hasattr(box, 'box'): for boxi in box.box: ...
python
{ "resource": "" }
q14450
KeenApi.fulfill
train
def fulfill(self, method, *args, **kwargs): """ Fulfill an HTTP request to Keen's API. """ return getattr(self.session, method)(*args, **kwargs)
python
{ "resource": "" }
q14451
KeenApi._order_by_is_valid_or_none
train
def _order_by_is_valid_or_none(self, params): """ Validates that a given order_by has proper syntax. :param params: Query params. :return: Returns True if either no order_by is present, or if the order_by is well-formed. """ if not "order_by" in params or not params["ord...
python
{ "resource": "" }
q14452
KeenApi._limit_is_valid_or_none
train
def _limit_is_valid_or_none(self, params): """ Validates that a given limit is not present or is well-formed. :param params: Query params. :return: Returns True if a limit is present or is well-formed. """ if not "limit" in params or not params["limit"]: retu...
python
{ "resource": "" }
q14453
KeenApi.query
train
def query(self, analysis_type, params, all_keys=False): """ Performs a query using the Keen IO analysis API. A read key must be set first. """ if not self._order_by_is_valid_or_none(params): raise ValueError("order_by given is invalid or is missing required group_by.") ...
python
{ "resource": "" }
q14454
KeenApi.delete_events
train
def delete_events(self, event_collection, params): """ Deletes events via the Keen IO API. A master key must be set first. :param event_collection: string, the event collection from which event are being deleted """ url = "{0}/{1}/projects/{2}/events/{3}".format(self.base_url,...
python
{ "resource": "" }
q14455
KeenApi.get_collection
train
def get_collection(self, event_collection): """ Extracts info about a collection using the Keen IO API. A master key must be set first. :param event_collection: the name of the collection to retrieve info for """ url = "{0}/{1}/projects/{2}/events/{3}".format(self.base_url, sel...
python
{ "resource": "" }
q14456
KeenApi._update_access_key_pair
train
def _update_access_key_pair(self, access_key_id, key, val): """ Helper for updating access keys in a DRY fashion. """ # Get current state via HTTPS. current_access_key = self.get_access_key(access_key_id) # Copy and only change the single parameter. payload_dict ...
python
{ "resource": "" }
q14457
KeenApi.add_access_key_permissions
train
def add_access_key_permissions(self, access_key_id, permissions): """ Adds to the existing list of permissions on this key with the contents of this list. Will not remove any existing permissions or modify the remainder of the key. :param access_key_id: the 'key' value of the access key...
python
{ "resource": "" }
q14458
KeenApi.remove_access_key_permissions
train
def remove_access_key_permissions(self, access_key_id, permissions): """ Removes a list of permissions from the existing list of permissions. Will not remove all existing permissions unless all such permissions are included in this list. Not to be confused with key revocation. S...
python
{ "resource": "" }
q14459
KeenApi._error_handling
train
def _error_handling(self, res): """ Helper function to do the error handling :params res: the response from a request """ # making the error handling generic so if an status_code starting with 2 doesn't exist, we raise the error if res.status_code // 100 != 2: ...
python
{ "resource": "" }
q14460
KeenApi._get_response_json
train
def _get_response_json(self, res): """ Helper function to extract the JSON body out of a response OR throw an exception. :param res: the response from a request :return: the JSON body OR throws an exception """ try: error = res.json() except ValueErr...
python
{ "resource": "" }
q14461
CachedDatasetsInterface.all
train
def all(self): """ Fetch all Cached Datasets for a Project. Read key must be set. """ return self._get_json(HTTPMethods.GET, self._cached_datasets_url, self._get_master_key())
python
{ "resource": "" }
q14462
CachedDatasetsInterface.get
train
def get(self, dataset_name): """ Fetch a single Cached Dataset for a Project. Read key must be set. :param dataset_name: Name of Cached Dataset (not `display_name`) """ url = "{0}/{1}".format(self._cached_datasets_url, dataset_name) return self._get_json(HTTPMethods.GET, url, se...
python
{ "resource": "" }
q14463
CachedDatasetsInterface.create
train
def create(self, dataset_name, query, index_by, display_name): """ Create a Cached Dataset for a Project. Master key must be set. """ url = "{0}/{1}".format(self._cached_datasets_url, dataset_name) payload = { "query": query, "index_by": index_by, "dis...
python
{ "resource": "" }
q14464
CachedDatasetsInterface.results
train
def results(self, dataset_name, index_by, timeframe): """ Retrieve results from a Cached Dataset. Read key must be set. """ url = "{0}/{1}/results".format(self._cached_datasets_url, dataset_name) index_by = index_by if isinstance(index_by, str) else json.dumps(index_by) timefram...
python
{ "resource": "" }
q14465
CachedDatasetsInterface.delete
train
def delete(self, dataset_name): """ Delete a Cached Dataset. Master Key must be set. """ url = "{0}/{1}".format(self._cached_datasets_url, dataset_name) self._get_json(HTTPMethods.DELETE, url, self._get_master_key()) return True
python
{ "resource": "" }
q14466
switch.match
train
def match(self, *args): """Whether or not to enter a given case statement""" self.fall = self.fall or not args self.fall = self.fall or (self.value in args) return self.fall
python
{ "resource": "" }
q14467
glymurrc_fname
train
def glymurrc_fname(): """Return the path to the configuration file. Search order: 1) current working directory 2) environ var XDG_CONFIG_HOME 3) $HOME/.config/glymur/glymurrc """ # Current directory. fname = os.path.join(os.getcwd(), 'glymurrc') if os.path.exists(fname)...
python
{ "resource": "" }
q14468
load_library_handle
train
def load_library_handle(libname, path): """Load the library, return the ctypes handle.""" if path is None or path in ['None', 'none']: # Either could not find a library via ctypes or # user-configuration-file, or we could not find it in any of the # default locations, or possibly the us...
python
{ "resource": "" }
q14469
read_config_file
train
def read_config_file(libname): """ Extract library locations from a configuration file. Parameters ---------- libname : str One of either 'openjp2' or 'openjpeg' Returns ------- path : None or str None if no location is specified, otherwise a path to the library """...
python
{ "resource": "" }
q14470
glymur_config
train
def glymur_config(): """ Try to ascertain locations of openjp2, openjpeg libraries. Returns ------- tuple tuple of library handles """ handles = (load_openjpeg_library(x) for x in ['openjp2', 'openjpeg']) handles = tuple(handles) if all(handle is None for handle in handles)...
python
{ "resource": "" }
q14471
get_configdir
train
def get_configdir(): """Return string representing the configuration directory. Default is $HOME/.config/glymur. You can override this with the XDG_CONFIG_HOME environment variable. """ if 'XDG_CONFIG_HOME' in os.environ: return os.path.join(os.environ['XDG_CONFIG_HOME'], 'glymur') if...
python
{ "resource": "" }
q14472
set_option
train
def set_option(key, value): """Set the value of the specified option. Available options: parse.full_codestream print.xml print.codestream print.short Parameters ---------- key : str Name of a single option. value : New value of option. Opti...
python
{ "resource": "" }
q14473
reset_option
train
def reset_option(key): """ Reset one or more options to their default value. Pass "all" as argument to reset all options. Available options: parse.full_codestream print.xml print.codestream print.short Parameter --------- key : str Name of a single...
python
{ "resource": "" }
q14474
set_printoptions
train
def set_printoptions(**kwargs): """Set printing options. These options determine the way JPEG 2000 boxes are displayed. Parameters ---------- short : bool, optional When True, only the box ID, offset, and length are displayed. Useful for displaying only the basic structure or skel...
python
{ "resource": "" }
q14475
get_printoptions
train
def get_printoptions(): """Return the current print options. Returns ------- dict Dictionary of current print options with keys - short : bool - xml : bool - codestream : bool For a full description of these options, see `set_printoptions`. See also ...
python
{ "resource": "" }
q14476
main
train
def main(): """ Entry point for console script jp2dump. """ kwargs = {'description': 'Print JPEG2000 metadata.', 'formatter_class': argparse.ArgumentDefaultsHelpFormatter} parser = argparse.ArgumentParser(**kwargs) parser.add_argument('-x', '--noxml', help...
python
{ "resource": "" }
q14477
CerberusClient._set_token
train
def _set_token(self): """Set the Cerberus token based on auth type""" try: self.token = os.environ['CERBERUS_TOKEN'] if self.verbose: print("Overriding Cerberus token with environment variable.", file=sys.stderr) logger.info("Overriding Cerberus token ...
python
{ "resource": "" }
q14478
CerberusClient.get_role
train
def get_role(self, key): """Return id of named role.""" json_resp = self.get_roles() for item in json_resp: if key in item["name"]: return item["id"] raise CerberusClientException("Key '%s' not found" % key)
python
{ "resource": "" }
q14479
CerberusClient.get_categories
train
def get_categories(self): """ Return a list of categories that a safe deposit box can belong to""" sdb_resp = get_with_retry(self.cerberus_url + '/v1/category', headers=self.HEADERS) throw_if_bad_response(sdb_resp) return sdb_resp.json()
python
{ "resource": "" }
q14480
CerberusClient.create_sdb
train
def create_sdb(self, name, category_id, owner, description="", user_group_permissions=None, iam_principal_permissions=None): """Create a safe deposit box. You need to refresh your token before the iam role is granted permission to the new safe deposit box. Keyword arguments: ...
python
{ "resource": "" }
q14481
CerberusClient.delete_sdb
train
def delete_sdb(self, sdb_id): """ Delete a safe deposit box specified by id Keyword arguments: sdb_id -- this is the id of the safe deposit box, not the path.""" sdb_resp = delete_with_retry(self.cerberus_url + '/v2/safe-deposit-box/' + sdb_id, headers...
python
{ "resource": "" }
q14482
CerberusClient.get_sdb_path
train
def get_sdb_path(self, sdb): """Return the path for a SDB""" sdb_id = self.get_sdb_id(sdb) sdb_resp = get_with_retry( self.cerberus_url + '/v1/safe-deposit-box/' + sdb_id + '/', headers=self.HEADERS ) throw_if_bad_response(sdb_resp) return sdb_re...
python
{ "resource": "" }
q14483
CerberusClient.get_sdb_keys
train
def get_sdb_keys(self, path): """Return the keys for a SDB, which are need for the full secure data path""" list_resp = get_with_retry( self.cerberus_url + '/v1/secret/' + path + '/?list=true', headers=self.HEADERS ) throw_if_bad_response(list_resp) retu...
python
{ "resource": "" }
q14484
CerberusClient.get_sdb_id
train
def get_sdb_id(self, sdb): """ Return the ID for the given safe deposit box. Keyword arguments: sdb -- This is the name of the safe deposit box, not the path""" json_resp = self.get_sdbs() for r in json_resp: if r['name'] == sdb: return str(r['id']) ...
python
{ "resource": "" }
q14485
CerberusClient.get_sdb_id_by_path
train
def get_sdb_id_by_path(self, sdb_path): """ Given the path, return the ID for the given safe deposit box.""" json_resp = self.get_sdbs() # Deal with the supplied path possibly missing an ending slash path = self._add_slash(sdb_path) for r in json_resp: if r['path'] ...
python
{ "resource": "" }
q14486
CerberusClient.get_sdb_by_id
train
def get_sdb_by_id(self, sdb_id): """ Return the details for the given safe deposit box id Keyword arguments: sdb_id -- this is the id of the safe deposit box, not the path. """ sdb_resp = get_with_retry(self.cerberus_url + '/v2/safe-deposit-box/' + sdb_id, ...
python
{ "resource": "" }
q14487
CerberusClient.get_sdb_secret_version_paths
train
def get_sdb_secret_version_paths(self, sdb_id): """ Get SDB secret version paths. This function takes the sdb_id """ sdb_resp = get_with_retry(str.join('', [self.cerberus_url, '/v1/sdb-secret-version-paths/', sdb_id]), headers=self.HEADERS) throw_if_bad_response...
python
{ "resource": "" }
q14488
CerberusClient.list_sdbs
train
def list_sdbs(self): """ Return sdbs by Name """ sdb_raw = self.get_sdbs() sdbs = [] for s in sdb_raw: sdbs.append(s['name']) return sdbs
python
{ "resource": "" }
q14489
CerberusClient.update_sdb
train
def update_sdb(self, sdb_id, owner=None, description=None, user_group_permissions=None, iam_principal_permissions=None): """ Update a safe deposit box. Keyword arguments: owner (string) -- AD group that owns the safe deposit box description (string) -...
python
{ "resource": "" }
q14490
CerberusClient.delete_file
train
def delete_file(self, secure_data_path): """Delete a file at the given secure data path""" secret_resp = delete_with_retry(self.cerberus_url + '/v1/secure-file/' + secure_data_path, headers=self.HEADERS) throw_if_bad_response(secret_resp) return secr...
python
{ "resource": "" }
q14491
CerberusClient.get_file_metadata
train
def get_file_metadata(self, secure_data_path, version=None): """Get just the metadata for a file, not the content""" if not version: version = "CURRENT" payload = {'versionId': str(version)} secret_resp = head_with_retry(str.join('', [self.cerberus_url, '/v1/secure-file/', s...
python
{ "resource": "" }
q14492
CerberusClient._parse_metadata_filename
train
def _parse_metadata_filename(self, metadata): """ Parse the header metadata to pull out the filename and then store it under the key 'filename' """ index = metadata['Content-Disposition'].index('=')+1 metadata['filename'] = metadata['Content-Disposition'][index:].replace('"', '')...
python
{ "resource": "" }
q14493
CerberusClient.get_file_versions
train
def get_file_versions(self, secure_data_path, limit=None, offset=None): """ Get versions of a particular file This is just a shim to get_secret_versions secure_data_path -- full path to the file in the safety deposit box limit -- Default(100), limits how many records to be retur...
python
{ "resource": "" }
q14494
CerberusClient._get_all_file_versions
train
def _get_all_file_versions(self, secure_data_path, limit=None): """ Convenience function that returns a generator yielding the contents of all versions of a file and its version info secure_data_path -- full path to the file in the safety deposit box limit -- Default(100), limit...
python
{ "resource": "" }
q14495
CerberusClient.list_files
train
def list_files(self, secure_data_path, limit=None, offset=None): """Return the list of files in the path. May need to be paginated""" # Make sure that limit and offset are in range. # Set the normal defaults if not limit or limit <= 0: limit = 100 if not offset or ...
python
{ "resource": "" }
q14496
CerberusClient.put_file
train
def put_file(self, secure_data_path, filehandle, content_type=None): """ Upload a file to a secure data path provided Keyword arguments: secure_data_path -- full path in the safety deposit box that contains the file key to store things under filehandle -- Pass an opened filehand...
python
{ "resource": "" }
q14497
CerberusClient.get_secret_versions
train
def get_secret_versions(self, secure_data_path, limit=None, offset=None): """ Get versions of a particular secret key secure_data_path -- full path to the key in the safety deposit box limit -- Default(100), limits how many records to be returned from the api at once. offset -- ...
python
{ "resource": "" }
q14498
CerberusClient.list_secrets
train
def list_secrets(self, secure_data_path): """Return json secrets based on the secure_data_path, this will list keys in a folder""" # Because of the addition of versionId and the way URLs are constructed, secure_data_path should # always end in a '/'. secure_data_path = self._add_slash(...
python
{ "resource": "" }
q14499
AWSAuth._get_v4_signed_headers
train
def _get_v4_signed_headers(self): """Returns V4 signed get-caller-identity request headers""" if self.aws_session is None: boto_session = session.Session() creds = boto_session.get_credentials() else: creds = self.aws_session.get_credentials() if creds...
python
{ "resource": "" }