_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q277700
Converter.register_to_openmath
test
def register_to_openmath(self, py_class, converter): """Register a conversion from Python to OpenMath :param py_class: A Python class the conversion is attached to, or None :type py_class: None, type :param converter: A conversion function or an OpenMath object :type converter:...
python
{ "resource": "" }
q277701
Converter._deprecated_register_to_python
test
def _deprecated_register_to_python(self, cd, name, converter=None): """Register a conversion from OpenMath to Python This function has two forms. A three-arguments one: :param cd: A content dictionary name :type cd: str :param name: A symbol name :type name: str ...
python
{ "resource": "" }
q277702
Redis.init_app
test
def init_app(self, app): """ Used to initialize redis with app object """ app.config.setdefault('REDIS_URLS', { 'main': 'redis://localhost:6379/0', 'admin': 'redis://localhost:6379/1', }) app.before_request(self.before_request) self.app ...
python
{ "resource": "" }
q277703
valid_choices
test
def valid_choices(choices): """ Return list of choices's keys """ for key, value in choices: if isinstance(value, (list, tuple)): for key, _ in value: yield key else: yield key
python
{ "resource": "" }
q277704
split_model_kwargs
test
def split_model_kwargs(kw): """ django_any birds language parser """ from collections import defaultdict model_fields = {} fields_agrs = defaultdict(lambda : {}) for key in kw.keys(): if '__' in key: field, _, subfield = key.partition('__') fields_ag...
python
{ "resource": "" }
q277705
ExtensionMethod.register
test
def register(self, field_type, impl=None): """ Register form field data function. Could be used as decorator """ def _wrapper(func): self.registry[field_type] = func return func if impl: return _wrapper(impl) return _w...
python
{ "resource": "" }
q277706
ExtensionMethod._create_value
test
def _create_value(self, *args, **kwargs): """ Lowest value generator. Separated from __call__, because it seems that python cache __call__ reference on module import """ if not len(args): raise TypeError('Object instance is not provided') if self.by_...
python
{ "resource": "" }
q277707
any_form_default
test
def any_form_default(form_cls, **kwargs): """ Returns tuple with form data and files """ form_data = {} form_files = {} form_fields, fields_args = split_model_kwargs(kwargs) for name, field in form_cls.base_fields.iteritems(): if name in form_fields: form_data[name] = k...
python
{ "resource": "" }
q277708
field_required_attribute
test
def field_required_attribute(function): """ Sometimes return None if field is not required >>> result = any_form_field(forms.BooleanField(required=False)) >>> result in ['', 'True', 'False'] True """ def _wrapper(field, **kwargs): if not field.required and random.random < 0.1: ...
python
{ "resource": "" }
q277709
field_choices_attibute
test
def field_choices_attibute(function): """ Selection from field.choices """ def _wrapper(field, **kwargs): if hasattr(field.widget, 'choices'): return random.choice(list(valid_choices(field.widget.choices))) return function(field, **kwargs) return _wrapper
python
{ "resource": "" }
q277710
decimal_field_data
test
def decimal_field_data(field, **kwargs): """ Return random value for DecimalField >>> result = any_form_field(forms.DecimalField(max_value=100, min_value=11, max_digits=4, decimal_places = 2)) >>> type(result) <type 'str'> >>> from decimal import Decimal >>> Decimal(result) >= 11, Decimal(r...
python
{ "resource": "" }
q277711
email_field_data
test
def email_field_data(field, **kwargs): """ Return random value for EmailField >>> result = any_form_field(forms.EmailField(min_length=10, max_length=30)) >>> type(result) <type 'str'> >>> len(result) <= 30, len(result) >= 10 (True, True) """ max_length = 10 if field.max_length: ...
python
{ "resource": "" }
q277712
date_field_data
test
def date_field_data(field, **kwargs): """ Return random value for DateField >>> result = any_form_field(forms.DateField()) >>> type(result) <type 'str'> """ from_date = kwargs.get('from_date', date(1990, 1, 1)) to_date = kwargs.get('to_date', date.today()) date_format = random....
python
{ "resource": "" }
q277713
datetime_field_data
test
def datetime_field_data(field, **kwargs): """ Return random value for DateTimeField >>> result = any_form_field(forms.DateTimeField()) >>> type(result) <type 'str'> """ from_date = kwargs.get('from_date', datetime(1990, 1, 1)) to_date = kwargs.get('to_date', datetime.today()) date_f...
python
{ "resource": "" }
q277714
float_field_data
test
def float_field_data(field, **kwargs): """ Return random value for FloatField >>> result = any_form_field(forms.FloatField(max_value=200, min_value=100)) >>> type(result) <type 'str'> >>> float(result) >=100, float(result) <=200 (True, True) """ min_value = 0 max_value = 100 ...
python
{ "resource": "" }
q277715
integer_field_data
test
def integer_field_data(field, **kwargs): """ Return random value for IntegerField >>> result = any_form_field(forms.IntegerField(max_value=200, min_value=100)) >>> type(result) <type 'str'> >>> int(result) >=100, int(result) <=200 (True, True) """ min_value = 0 max_value = 100 ...
python
{ "resource": "" }
q277716
time_field_data
test
def time_field_data(field, **kwargs): """ Return random value for TimeField >>> result = any_form_field(forms.TimeField()) >>> type(result) <type 'str'> """ time_format = random.choice(field.input_formats or formats.get_format('TIME_INPUT_FORMATS')) return time(xunit.any_int(min_value=...
python
{ "resource": "" }
q277717
choice_field_data
test
def choice_field_data(field, **kwargs): """ Return random value for ChoiceField >>> CHOICES = [('YNG', 'Child'), ('OLD', 'Parent')] >>> result = any_form_field(forms.ChoiceField(choices=CHOICES)) >>> type(result) <type 'str'> >>> result in ['YNG', 'OLD'] True >>> typed_result = any_...
python
{ "resource": "" }
q277718
multiple_choice_field_data
test
def multiple_choice_field_data(field, **kwargs): """ Return random value for MultipleChoiceField >>> CHOICES = [('YNG', 'Child'), ('MIDDLE', 'Parent') ,('OLD', 'GrandParent')] >>> result = any_form_field(forms.MultipleChoiceField(choices=CHOICES)) >>> type(result) <type 'str'> """ if fi...
python
{ "resource": "" }
q277719
model_choice_field_data
test
def model_choice_field_data(field, **kwargs): """ Return one of first ten items for field queryset """ data = list(field.queryset[:10]) if data: return random.choice(data) else: raise TypeError('No %s available in queryset' % field.queryset.model)
python
{ "resource": "" }
q277720
encode_bytes
test
def encode_bytes(obj, nsprefix=None): """ Encodes an OpenMath element into a string. :param obj: Object to encode as string. :type obj: OMAny :rtype: bytes """ node = encode_xml(obj, nsprefix) return etree.tostring(node)
python
{ "resource": "" }
q277721
publish
test
def publish(msg="checkpoint: publish package"): """Deploy the app to PYPI. Args: msg (str, optional): Description """ test = check() if test.succeeded: # clean() # push(msg) sdist = local("python setup.py sdist") if sdist.succeeded: build = local(...
python
{ "resource": "" }
q277722
tag
test
def tag(version=__version__): """Deploy a version tag.""" build = local("git tag {0}".format(version)) if build.succeeded: local("git push --tags")
python
{ "resource": "" }
q277723
any_field_blank
test
def any_field_blank(function): """ Sometimes return None if field could be blank """ def wrapper(field, **kwargs): if kwargs.get('isnull', False): return None if field.blank and random.random < 0.1: return None return function(field, **kwarg...
python
{ "resource": "" }
q277724
load_python_global
test
def load_python_global(module, name): """ Evaluate an OpenMath symbol describing a global Python object EXAMPLES:: >>> from openmath.convert_pickle import to_python >>> from openmath.convert_pickle import load_python_global >>> load_python_global('math', 'sin') <built-in f...
python
{ "resource": "" }
q277725
cls_build
test
def cls_build(inst, state): """ Apply the setstate protocol to initialize `inst` from `state`. INPUT: - ``inst`` -- a raw instance of a class - ``state`` -- the state to restore; typically a dictionary mapping attribute names to their values EXAMPLES:: >>> from openmath.convert_pickl...
python
{ "resource": "" }
q277726
PickleConverter.OMList
test
def OMList(self, l): """ Convert a list of OM objects into an OM object EXAMPLES:: >>> from openmath import openmath as om >>> from openmath.convert_pickle import PickleConverter >>> converter = PickleConverter() >>> o = converter.OMList([om.OMI...
python
{ "resource": "" }
q277727
PickleConverter.OMTuple
test
def OMTuple(self, l): """ Convert a tuple of OM objects into an OM object EXAMPLES:: >>> from openmath import openmath as om >>> from openmath.convert_pickle import PickleConverter >>> converter = PickleConverter() >>> o = converter.OMTuple([om....
python
{ "resource": "" }
q277728
decode
test
def decode(data): """ Decodes a PackBit encoded data. """ data = bytearray(data) # <- python 2/3 compatibility fix result = bytearray() pos = 0 while pos < len(data): header_byte = data[pos] if header_byte > 127: header_byte -= 256 pos += 1 if 0 <...
python
{ "resource": "" }
q277729
encode
test
def encode(data): """ Encodes data using PackBits encoding. """ if len(data) == 0: return data if len(data) == 1: return b'\x00' + data data = bytearray(data) result = bytearray() buf = bytearray() pos = 0 repeat_count = 0 MAX_LENGTH = 127 # we can saf...
python
{ "resource": "" }
q277730
Accounting.to_fixed
test
def to_fixed(self, value, precision): """Implementation that treats floats more like decimals. Fixes binary rounding issues (eg. (0.615).toFixed(2) === "0.61") that present problems for accounting and finance-related software. """ precision = self._change_precision( ...
python
{ "resource": "" }
q277731
Accounting.format
test
def format(self, number, **kwargs): """Format a given number. Format a number, with comma-separated thousands and custom precision/decimal places Localise by overriding the precision and thousand / decimal separators 2nd parameter `precision` can be an object matching `settings...
python
{ "resource": "" }
q277732
Accounting.as_money
test
def as_money(self, number, **options): """Format a number into currency. Usage: accounting.formatMoney(number, symbol, precision, thousandsSep, decimalSep, format) defaults: (0, "$", 2, ",", ".", "%s%v") Localise by overriding the symbol, precision,...
python
{ "resource": "" }
q277733
to_array
test
def to_array(data): """ Import a blosc array into a numpy array. Arguments: data: A blosc packed numpy array Returns: A numpy array with data from a blosc compressed array """ try: numpy_data = blosc.unpack_array(data) except Exception as e: raise ValueError...
python
{ "resource": "" }
q277734
from_array
test
def from_array(array): """ Export a numpy array to a blosc array. Arguments: array: The numpy array to compress to blosc array Returns: Bytes/String. A blosc compressed array """ try: raw_data = blosc.pack_array(array) except Exception as e: raise ValueError...
python
{ "resource": "" }
q277735
Workspace.add
test
def add(self, name, path): """Add a workspace entry in user config file.""" if not (os.path.exists(path)): raise ValueError("Workspace path `%s` doesn't exists." % path) if (self.exists(name)): raise ValueError("Workspace `%s` already exists." % name) self.confi...
python
{ "resource": "" }
q277736
Workspace.remove
test
def remove(self, name): """Remove workspace from config file.""" if not (self.exists(name)): raise ValueError("Workspace `%s` doesn't exists." % name) self.config["workspaces"].pop(name, 0) self.config.write()
python
{ "resource": "" }
q277737
Workspace.list
test
def list(self): """List all available workspaces.""" ws_list = {} for key, value in self.config["workspaces"].items(): ws_list[key] = dict({"name": key}, **value) return ws_list
python
{ "resource": "" }
q277738
Workspace.get
test
def get(self, name): """ Get workspace infos from name. Return None if workspace doesn't exists. """ ws_list = self.list() return ws_list[name] if name in ws_list else None
python
{ "resource": "" }
q277739
Workspace.repository_exists
test
def repository_exists(self, workspace, repo): """Return True if workspace contains repository name.""" if not self.exists(workspace): return False workspaces = self.list() return repo in workspaces[workspace]["repositories"]
python
{ "resource": "" }
q277740
Workspace.sync
test
def sync(self, ws_name): """Synchronise workspace's repositories.""" path = self.config["workspaces"][ws_name]["path"] repositories = self.config["workspaces"][ws_name]["repositories"] logger = logging.getLogger(__name__) color = Color() for r in os.listdir(path): ...
python
{ "resource": "" }
q277741
clone
test
def clone(url, path): """Clone a repository.""" adapter = None if url[:4] == "git@" or url[-4:] == ".git": adapter = Git(path) if url[:6] == "svn://": adapter = Svn(path) if url[:6] == "bzr://": adapter = Bzr(path) if url[:9] == "ssh://hg@": adapter = Hg(path) ...
python
{ "resource": "" }
q277742
check_version
test
def check_version(): """ Tells you if you have an old version of ndio. """ import requests r = requests.get('https://pypi.python.org/pypi/ndio/json').json() r = r['info']['version'] if r != version: print("A newer version of ndio is available. " + "'pip install -U ndio'...
python
{ "resource": "" }
q277743
to_voxels
test
def to_voxels(array): """ Converts an array to its voxel list. Arguments: array (numpy.ndarray): A numpy nd array. This must be boolean! Returns: A list of n-tuples """ if type(array) is not numpy.ndarray: raise ValueError("array argument must be of type numpy.ndarray")...
python
{ "resource": "" }
q277744
from_voxels
test
def from_voxels(voxels): """ Converts a voxel list to an ndarray. Arguments: voxels (tuple[]): A list of coordinates indicating coordinates of populated voxels in an ndarray. Returns: numpy.ndarray The result of the transformation. """ dimensions = len(voxels[0]) ...
python
{ "resource": "" }
q277745
Update.execute
test
def execute(self, args): """Execute update subcommand.""" if args.name is not None: self.print_workspace(args.name) elif args.all is not None: self.print_all()
python
{ "resource": "" }
q277746
Update.print_update
test
def print_update(self, repo_name, repo_path): """Print repository update.""" color = Color() self.logger.info(color.colored( "=> [%s] %s" % (repo_name, repo_path), "green")) try: repo = Repository(repo_path) repo.update() except RepositoryError...
python
{ "resource": "" }
q277747
Logger.set_console_handler
test
def set_console_handler(self, debug=False): """Set Console handler.""" console = logging.StreamHandler() console.setFormatter(Formatter(LFORMAT)) if not debug: console.setLevel(logging.INFO) self.addHandler(console)
python
{ "resource": "" }
q277748
Abstract.execute
test
def execute(self, command, path=None): """Execute command with os.popen and return output.""" logger = logging.getLogger(__name__) self.check_executable() logger.debug("Executing command `%s` (cwd: %s)" % (command, path)) process = subprocess.Popen( command, ...
python
{ "resource": "" }
q277749
load
test
def load(png_filename): """ Import a png file into a numpy array. Arguments: png_filename (str): A string filename of a png datafile Returns: A numpy array with data from the png file """ # Expand filename to be absolute png_filename = os.path.expanduser(png_filename) ...
python
{ "resource": "" }
q277750
save
test
def save(filename, numpy_data): """ Export a numpy array to a png file. Arguments: filename (str): A filename to which to save the png data numpy_data (numpy.ndarray OR str): The numpy array to save to png. OR a string: If a string is provded, it should be a binary png str ...
python
{ "resource": "" }
q277751
save_collection
test
def save_collection(png_filename_base, numpy_data, start_layers_at=1): """ Export a numpy array to a set of png files, with each Z-index 2D array as its own 2D file. Arguments: png_filename_base: A filename template, such as "my-image-*.png" which will lead t...
python
{ "resource": "" }
q277752
Status.print_workspace
test
def print_workspace(self, name): """Print workspace status.""" path_list = find_path(name, self.config) if len(path_list) == 0: self.logger.error("No matches for `%s`" % name) return False for name, path in path_list.items(): self.print_status(name, ...
python
{ "resource": "" }
q277753
Status.print_status
test
def print_status(self, repo_name, repo_path): """Print repository status.""" color = Color() self.logger.info(color.colored( "=> [%s] %s" % (repo_name, repo_path), "green")) try: repo = Repository(repo_path) repo.status() except RepositoryError...
python
{ "resource": "" }
q277754
data.get_block_size
test
def get_block_size(self, token, resolution=None): """ Gets the block-size for a given token at a given resolution. Arguments: token (str): The token to inspect resolution (int : None): The resolution at which to inspect data. If none is specified, uses th...
python
{ "resource": "" }
q277755
data._post_cutout_no_chunking_blosc
test
def _post_cutout_no_chunking_blosc(self, token, channel, x_start, y_start, z_start, data, resolution): """ Accepts data in zyx. !!! """ data = numpy.expand_dims(data, axis=0) blosc_data = blosc.pack_arr...
python
{ "resource": "" }
q277756
load
test
def load(tiff_filename): """ Import a TIFF file into a numpy array. Arguments: tiff_filename: A string filename of a TIFF datafile Returns: A numpy array with data from the TIFF file """ # Expand filename to be absolute tiff_filename = os.path.expanduser(tiff_filename) ...
python
{ "resource": "" }
q277757
save
test
def save(tiff_filename, numpy_data): """ Export a numpy array to a TIFF file. Arguments: tiff_filename: A filename to which to save the TIFF data numpy_data: The numpy array to save to TIFF Returns: String. The expanded filename that now holds the TIFF data """ # E...
python
{ "resource": "" }
q277758
load_tiff_multipage
test
def load_tiff_multipage(tiff_filename, dtype='float32'): """ Load a multipage tiff into a single variable in x,y,z format. Arguments: tiff_filename: Filename of source data dtype: data type to use for the returned tensor Returns: Array containing contents from i...
python
{ "resource": "" }
q277759
Config.write
test
def write(self): """ Write config in configuration file. Data must me a dict. """ file = open(self.config_file, "w+") file.write(yaml.dump(dict(self), default_flow_style=False)) file.close()
python
{ "resource": "" }
q277760
Bzr.clone
test
def clone(self, url): """Clone repository from url.""" return self.execute("%s branch %s %s" % (self.executable, url, self.path))
python
{ "resource": "" }
q277761
get_version
test
def get_version(): """Get version from package resources.""" requirement = pkg_resources.Requirement.parse("yoda") provider = pkg_resources.get_provider(requirement) return provider.version
python
{ "resource": "" }
q277762
mix_and_match
test
def mix_and_match(name, greeting='Hello', yell=False): '''Mixing and matching positional args and keyword options.''' say = '%s, %s' % (greeting, name) if yell: print '%s!' % say.upper() else: print '%s.' % say
python
{ "resource": "" }
q277763
option_decorator
test
def option_decorator(name, greeting, yell): '''Same as mix_and_match, but using the @option decorator.''' # Use the @option decorator when you need more control over the # command line options. say = '%s, %s' % (greeting, name) if yell: print '%s!' % say.upper() else: print '%s.'...
python
{ "resource": "" }
q277764
neuroRemote.reserve_ids
test
def reserve_ids(self, token, channel, quantity): """ Requests a list of next-available-IDs from the server. Arguments: quantity (int): The number of IDs to reserve Returns: int[quantity]: List of IDs you've been granted """ quantity = str(quantit...
python
{ "resource": "" }
q277765
neuroRemote.merge_ids
test
def merge_ids(self, token, channel, ids, delete=False): """ Call the restful endpoint to merge two RAMON objects into one. Arguments: token (str): The token to inspect channel (str): The channel to inspect ids (int[]): the list of the IDs to merge ...
python
{ "resource": "" }
q277766
neuroRemote.propagate
test
def propagate(self, token, channel): """ Kick off the propagate function on the remote server. Arguments: token (str): The token to propagate channel (str): The channel to propagate Returns: boolean: Success """ if self.get_propagate_...
python
{ "resource": "" }
q277767
resources.list_projects
test
def list_projects(self, dataset_name): """ Lists a set of projects related to a dataset. Arguments: dataset_name (str): Dataset name to search projects for Returns: dict: Projects found based on dataset query """ url = self.url() + "/nd/resource/...
python
{ "resource": "" }
q277768
resources.get_dataset
test
def get_dataset(self, name): """ Returns info regarding a particular dataset. Arugments: name (str): Dataset name Returns: dict: Dataset information """ url = self.url() + "/resource/dataset/{}".format(name) req = self.remote_utils.get_ur...
python
{ "resource": "" }
q277769
resources.list_datasets
test
def list_datasets(self, get_global_public): """ Lists datasets in resources. Setting 'get_global_public' to 'True' will retrieve all public datasets in cloud. 'False' will get user's public datasets. Arguments: get_global_public (bool): True if user wants all public ...
python
{ "resource": "" }
q277770
Show.parse
test
def parse(self): """Parse show subcommand.""" parser = self.subparser.add_parser( "show", help="Show workspace details", description="Show workspace details.") group = parser.add_mutually_exclusive_group(required=True) group.add_argument('--all', acti...
python
{ "resource": "" }
q277771
Show.execute
test
def execute(self, args): """Execute show subcommand.""" if args.name is not None: self.show_workspace(slashes2dash(args.name)) elif args.all is not None: self.show_all()
python
{ "resource": "" }
q277772
Show.show_workspace
test
def show_workspace(self, name): """Show specific workspace.""" if not self.workspace.exists(name): raise ValueError("Workspace `%s` doesn't exists." % name) color = Color() workspaces = self.workspace.list() self.logger.info("<== %s workspace ==>" % color.colored(na...
python
{ "resource": "" }
q277773
Show.show_all
test
def show_all(self): """Show details for all workspaces.""" for ws in self.workspace.list().keys(): self.show_workspace(ws) print("\n\n")
python
{ "resource": "" }
q277774
Remote.url
test
def url(self, endpoint=''): """ Get the base URL of the Remote. Arguments: None Returns: `str` base URL """ if not endpoint.startswith('/'): endpoint = "/" + endpoint return self.protocol + "://" + self.hostname + endpoint
python
{ "resource": "" }
q277775
_guess_format_from_extension
test
def _guess_format_from_extension(ext): """ Guess the appropriate data type from file extension. Arguments: ext: The file extension (period optional) Returns: String. The format (without leading period), or False if none was found or couldn't be guessed """ ...
python
{ "resource": "" }
q277776
open
test
def open(in_file, in_fmt=None): """ Reads in a file from disk. Arguments: in_file: The name of the file to read in in_fmt: The format of in_file, if you want to be explicit Returns: numpy.ndarray """ fmt = in_file.split('.')[-1] if in_fmt: fmt = in_fmt f...
python
{ "resource": "" }
q277777
convert
test
def convert(in_file, out_file, in_fmt="", out_fmt=""): """ Converts in_file to out_file, guessing datatype in the absence of in_fmt and out_fmt. Arguments: in_file: The name of the (existing) datafile to read out_file: The name of the file to create with converted data in_f...
python
{ "resource": "" }
q277778
grute.build_graph
test
def build_graph(self, project, site, subject, session, scan, size, email=None, invariants=Invariants.ALL, fiber_file=DEFAULT_FIBER_FILE, atlas_file=None, use_threads=False, callback=None): """ Builds a graph using the graph-services endpoint. ...
python
{ "resource": "" }
q277779
grute.compute_invariants
test
def compute_invariants(self, graph_file, input_format, invariants=Invariants.ALL, email=None, use_threads=False, callback=None): """ Compute invariants from an existing GraphML file using the remote grute graph services. Arguments: ...
python
{ "resource": "" }
q277780
grute.convert_graph
test
def convert_graph(self, graph_file, input_format, output_formats, email=None, use_threads=False, callback=None): """ Convert a graph from one GraphFormat to another. Arguments: graph_file (str): Filename of the file to convert input_format (str): A ...
python
{ "resource": "" }
q277781
to_dict
test
def to_dict(ramons, flatten=False): """ Converts a RAMON object list to a JSON-style dictionary. Useful for going from an array of RAMONs to a dictionary, indexed by ID. Arguments: ramons (RAMON[]): A list of RAMON objects flatten (boolean: False): Not implemented Returns: ...
python
{ "resource": "" }
q277782
AnnotationType.RAMON
test
def RAMON(typ): """ Takes str or int, returns class type """ if six.PY2: lookup = [str, unicode] elif six.PY3: lookup = [str] if type(typ) is int: return _ramon_types[typ] elif type(typ) in lookup: return _ramon_typ...
python
{ "resource": "" }
q277783
neurodata.delete_channel
test
def delete_channel(self, channel_name, project_name, dataset_name): """ Deletes a channel given its name, name of its project , and name of its dataset. Arguments: channel_name (str): Channel name project_name (str): Project name dataset_name (str): D...
python
{ "resource": "" }
q277784
NDIngest.add_dataset
test
def add_dataset(self, dataset_name, imagesize, voxelres, offset=None, timerange=None, scalinglevels=None, scaling=None): """ Add a new dataset to the ingest. Arguments: dataset_name (str): Dataset Name is the overarching name of the research effor...
python
{ "resource": "" }
q277785
NDIngest.nd_json
test
def nd_json(self, dataset, project, channel_list, metadata): """ Genarate ND json object. """ nd_dict = {} nd_dict['dataset'] = self.dataset_dict(*dataset) nd_dict['project'] = self.project_dict(*project) nd_dict['metadata'] = metadata nd_dict['channels'] ...
python
{ "resource": "" }
q277786
NDIngest.dataset_dict
test
def dataset_dict( self, dataset_name, imagesize, voxelres, offset, timerange, scalinglevels, scaling): """Generate the dataset dictionary""" dataset_dict = {} dataset_dict['dataset_name'] = dataset_name dataset_dict['imagesize'] = imagesize dataset_dict['voxel...
python
{ "resource": "" }
q277787
NDIngest.channel_dict
test
def channel_dict(self, channel_name, datatype, channel_type, data_url, file_format, file_type, exceptions, resolution, windowrange, readonly): """ Generate the project dictionary. """ channel_dict = {} channel_dict['channel_name'] = chann...
python
{ "resource": "" }
q277788
NDIngest.project_dict
test
def project_dict(self, project_name, token_name, public): """ Genarate the project dictionary. """ project_dict = {} project_dict['project_name'] = project_name if token_name is not None: if token_name == '': project_dict['token_name'] = projec...
python
{ "resource": "" }
q277789
NDIngest.identify_imagesize
test
def identify_imagesize(self, image_type, image_path='/tmp/img.'): """ Identify the image size using the data location and other parameters """ dims = () try: if (image_type.lower() == 'png'): dims = np.shape(ndpng.load('{}{}'.format( ...
python
{ "resource": "" }
q277790
NDIngest.put_data
test
def put_data(self, data): """ Try to post data to the server. """ URLPath = self.oo.url("autoIngest/") # URLPath = 'https://{}/ca/autoIngest/'.format(self.oo.site_host) try: response = requests.post(URLPath, data=json.dumps(data), ...
python
{ "resource": "" }
q277791
find_path
test
def find_path(name, config, wsonly=False): """Find path for given workspace and|or repository.""" workspace = Workspace(config) config = config["workspaces"] path_list = {} if name.find('/') != -1: wsonly = False try: ws, repo = name.split('/') except ValueError...
python
{ "resource": "" }
q277792
metadata.get_public_tokens
test
def get_public_tokens(self): """ Get a list of public tokens available on this server. Arguments: None Returns: str[]: list of public tokens """ r = self.remote_utils.get_url(self.url() + "public_tokens/") return r.json()
python
{ "resource": "" }
q277793
metadata.get_proj_info
test
def get_proj_info(self, token): """ Return the project info for a given token. Arguments: token (str): Token to return information for Returns: JSON: representation of proj_info """ r = self.remote_utils.get_url(self.url() + "{}/info/".format(tok...
python
{ "resource": "" }
q277794
metadata.set_metadata
test
def set_metadata(self, token, data): """ Insert new metadata into the OCP metadata database. Arguments: token (str): Token of the datum to set data (str): A dictionary to insert as metadata. Include `secret`. Returns: json: Info of the inserted ID (c...
python
{ "resource": "" }
q277795
remote_utils.get_url
test
def get_url(self, url): """ Get a response object for a given url. Arguments: url (str): The url make a get to token (str): The authentication token Returns: obj: The response object """ try: req = requests.get(url, header...
python
{ "resource": "" }
q277796
remote_utils.post_url
test
def post_url(self, url, token='', json=None, data=None, headers=None): """ Returns a post resquest object taking in a url, user token, and possible json information. Arguments: url (str): The url to make post to token (str): The authentication token j...
python
{ "resource": "" }
q277797
remote_utils.delete_url
test
def delete_url(self, url, token=''): """ Returns a delete resquest object taking in a url and user token. Arguments: url (str): The url to make post to token (str): The authentication token Returns: obj: Delete request object """ if (...
python
{ "resource": "" }
q277798
load
test
def load(hdf5_filename): """ Import a HDF5 file into a numpy array. Arguments: hdf5_filename: A string filename of a HDF5 datafile Returns: A numpy array with data from the HDF5 file """ # Expand filename to be absolute hdf5_filename = os.path.expanduser(hdf5_filename) ...
python
{ "resource": "" }
q277799
save
test
def save(hdf5_filename, array): """ Export a numpy array to a HDF5 file. Arguments: hdf5_filename (str): A filename to which to save the HDF5 data array (numpy.ndarray): The numpy array to save to HDF5 Returns: String. The expanded filename that now holds the HDF5 data """ ...
python
{ "resource": "" }