Search is not available for this dataset
text stringlengths 75 104k |
|---|
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... |
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... |
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_... |
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... |
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:
... |
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 |
def char_field_data(field, **kwargs):
"""
Return random value for CharField
>>> result = any_form_field(forms.CharField(min_length=3, max_length=10))
>>> type(result)
<type 'str'>
"""
min_length = kwargs.get('min_length', 1)
max_length = kwargs.get('max_length', field.max_length or 255) ... |
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... |
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:
... |
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.... |
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... |
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
... |
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
... |
def ipaddress_field_data(field, **kwargs):
"""
Return random value for IPAddressField
>>> result = any_form_field(forms.IPAddressField())
>>> type(result)
<type 'str'>
>>> from django.core.validators import ipv4_re
>>> import re
>>> re.match(ipv4_re, result) is not None
True
... |
def slug_field_data(field, **kwargs):
"""
Return random value for SlugField
>>> result = any_form_field(forms.SlugField())
>>> type(result)
<type 'str'>
>>> from django.core.validators import slug_re
>>> import re
>>> re.match(slug_re, result) is not None
True
"""
min_le... |
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=... |
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_... |
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... |
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) |
def encode_xml(obj, E=None):
""" Encodes an OpenMath object as an XML node.
:param obj: OpenMath object (or related item) to encode as XML.
:type obj: OMAny
:param ns: Namespace prefix to use for
http://www.openmath.org/OpenMath", or None if default namespace.
:type ns: str, None
:ret... |
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) |
def decode_bytes(xml, validator=None, snippet=False):
""" Decodes a stream into an OpenMath object.
:param xml: XML to decode.
:type xml: bytes
:param validator: Validator to use.
:param snippet: Is this an OpenMath snippet, or a full object?
:type snippet: Bool
:rtype: OMAny
"""
... |
def decode_stream(stream, validator=None, snippet=False):
""" Decodes a stream into an OpenMath object.
:param stream: Stream to decode.
:type stream: Any
:param validator: Validator to use.
:param snippet: Is this an OpenMath snippet, or a full object?
:type snippet: Bool
:rtype: OMAny
... |
def decode_xml(elem, _in_bind = False):
""" Decodes an XML element into an OpenMath object.
:param elem: Element to decode.
:type elem: etree._Element
:param _in_bind: Internal flag used to indicate if we should decode within
an OMBind.
:type _in_bind: bool
:rtype: OMAny
"""
obj ... |
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(... |
def tag(version=__version__):
"""Deploy a version tag."""
build = local("git tag {0}".format(version))
if build.succeeded:
local("git push --tags") |
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... |
def any_field_choices(function):
"""
Selection from field.choices
>>> CHOICES = [('YNG', 'Child'), ('OLD', 'Parent')]
>>> result = any_field(models.CharField(max_length=3, choices=CHOICES))
>>> result in ['YNG', 'OLD']
True
"""
def wrapper(field, **kwargs):
if field.ch... |
def any_biginteger_field(field, **kwargs):
"""
Return random value for BigIntegerField
>>> result = any_field(models.BigIntegerField())
>>> type(result)
<type 'long'>
"""
min_value = kwargs.get('min_value', 1)
max_value = kwargs.get('max_value', 10**10)
return long(xunit.a... |
def any_positiveinteger_field(field, **kwargs):
"""
An positive integer
>>> result = any_field(models.PositiveIntegerField())
>>> type(result)
<type 'int'>
>>> result > 0
True
"""
min_value = kwargs.get('min_value', 1)
max_value = kwargs.get('max_value', 9999)
re... |
def any_char_field(field, **kwargs):
"""
Return random value for CharField
>>> result = any_field(models.CharField(max_length=10))
>>> type(result)
<type 'str'>
"""
min_length = kwargs.get('min_length', 1)
max_length = kwargs.get('max_length', field.max_length)
return xuni... |
def any_commaseparatedinteger_field(field, **kwargs):
"""
Return random value for CharField
>>> result = any_field(models.CommaSeparatedIntegerField(max_length=10))
>>> type(result)
<type 'str'>
>>> [int(num) for num in result.split(',')] and 'OK'
'OK'
"""
nums_count = fie... |
def any_date_field(field, **kwargs):
"""
Return random value for DateField,
skips auto_now and auto_now_add fields
>>> result = any_field(models.DateField())
>>> type(result)
<type 'datetime.date'>
"""
if field.auto_now or field.auto_now_add:
return None
from_date... |
def any_datetime_field(field, **kwargs):
"""
Return random value for DateTimeField,
skips auto_now and auto_now_add fields
>>> result = any_field(models.DateTimeField())
>>> type(result)
<type 'datetime.datetime'>
"""
from_date = kwargs.get('from_date', datetime(1990, 1, 1))
... |
def any_decimal_field(field, **kwargs):
"""
Return random value for DecimalField
>>> result = any_field(models.DecimalField(max_digits=5, decimal_places=2))
>>> type(result)
<class 'decimal.Decimal'>
"""
min_value = kwargs.get('min_value', 0)
max_value = kwargs.get('max_value',... |
def any_email_field(field, **kwargs):
"""
Return random value for EmailField
>>> result = any_field(models.EmailField())
>>> type(result)
<type 'str'>
>>> re.match(r"(?:^|\s)[-a-z0-9_.]+@(?:[-a-z0-9]+\.)+[a-z]{2,6}(?:\s|$)", result, re.IGNORECASE) is not None
True
"""
retu... |
def any_float_field(field, **kwargs):
"""
Return random value for FloatField
>>> result = any_field(models.FloatField())
>>> type(result)
<type 'float'>
"""
min_value = kwargs.get('min_value', 1)
max_value = kwargs.get('max_value', 100)
precision = kwargs.get('precision', ... |
def any_file_field(field, **kwargs):
"""
Lookup for nearest existing file
"""
def get_some_file(path):
subdirs, files = field.storage.listdir(path)
if files:
result_file = random.choice(files)
instance = field.storage.open("%s/%s" % (path, result_file)... |
def any_filepath_field(field, **kwargs):
"""
Lookup for nearest existing file
"""
def get_some_file(path):
subdirs, files = [], []
for entry in os.listdir(path):
entry_path = os.path.join(path, entry)
if os.path.isdir(entry_path):
subdir... |
def any_ipaddress_field(field, **kwargs):
"""
Return random value for IPAddressField
>>> result = any_field(models.IPAddressField())
>>> type(result)
<type 'str'>
>>> from django.core.validators import ipv4_re
>>> re.match(ipv4_re, result) is not None
True
"""
nums = [s... |
def any_positivesmallinteger_field(field, **kwargs):
"""
Return random value for PositiveSmallIntegerField
>>> result = any_field(models.PositiveSmallIntegerField())
>>> type(result)
<type 'int'>
>>> result < 256, result > 0
(True, True)
"""
min_value = kwargs.get('min_value... |
def any_slug_field(field, **kwargs):
"""
Return random value for SlugField
>>> result = any_field(models.SlugField())
>>> type(result)
<type 'str'>
>>> from django.core.validators import slug_re
>>> re.match(slug_re, result) is not None
True
"""
letters = ascii_letters ... |
def any_smallinteger_field(field, **kwargs):
"""
Return random value for SmallIntegerValue
>>> result = any_field(models.SmallIntegerField())
>>> type(result)
<type 'int'>
>>> result > -256, result < 256
(True, True)
"""
min_value = kwargs.get('min_value', -255)
max_val... |
def any_integer_field(field, **kwargs):
"""
Return random value for IntegerField
>>> result = any_field(models.IntegerField())
>>> type(result)
<type 'int'>
"""
min_value = kwargs.get('min_value', -10000)
max_value = kwargs.get('max_value', 10000)
return xunit.any_int(min_va... |
def any_url_field(field, **kwargs):
"""
Return random value for URLField
>>> result = any_field(models.URLField())
>>> from django.core.validators import URLValidator
>>> re.match(URLValidator.regex, result) is not None
True
"""
url = kwargs.get('url')
if not url:
... |
def any_time_field(field, **kwargs):
"""
Return random value for TimeField
>>> result = any_field(models.TimeField())
>>> type(result)
<type 'datetime.time'>
"""
return time(
xunit.any_int(min_value=0, max_value=23),
xunit.any_int(min_value=0, max_value=59),
... |
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... |
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... |
def OMSymbol(self, module, name):
r"""
Helper function to build an OMS object
EXAMPLES::
>>> from openmath.convert_pickle import PickleConverter
>>> converter = PickleConverter()
>>> o = converter.OMSymbol(module="foo.bar", name="baz"); o
... |
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... |
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.... |
def OMDict(self, items):
"""
Convert a dictionary (or list of items thereof) of OM objects into an OM object
EXAMPLES::
>>> from openmath import openmath as om
>>> from openmath.convert_pickle import PickleConverter
>>> converter = PickleConverter()
... |
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 <... |
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... |
def _check_currency_format(self, format=None):
"""
Summary.
Args:
format (TYPE, optional): Description
Returns:
name (TYPE): Description
"""
defaults = self.settings['currency']['format']
if hasattr(format, '__call__'):
format... |
def _change_precision(self, val, base=0):
"""
Check and normalise the value of precision (must be positive integer).
Args:
val (INT): must be positive integer
base (INT): Description
Returns:
VAL (INT): Description
"""
if not isinstan... |
def parse(self, value, decimal=None):
"""
Summary.
Takes a string/array of strings, removes all formatting/cruft and
returns the raw float value
Decimal must be included in the regular expression to match floats
(defaults to Accounting.settings.number.decimal),
... |
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(
... |
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... |
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,... |
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... |
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... |
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... |
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() |
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 |
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 |
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"] |
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):
... |
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)
... |
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'... |
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")... |
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])
... |
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() |
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... |
def set_file_handler(self, logfile):
"""Set FileHandler"""
handler = logging.FileHandler(logfile)
handler.setLevel(logging.NOTSET)
handler.setFormatter(Formatter(FORMAT))
self.addHandler(handler) |
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) |
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,
... |
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)
... |
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
... |
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... |
def load_collection(png_filename_base):
"""
Import all files matching the filename base given with `png_filename_base`.
Images are ordered by alphabetical order, which means that you *MUST* 0-pad
your numbers if they span a power of ten (e.g. 0999-1000 or 09-10). This is
handled automatically by its... |
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, ... |
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... |
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... |
def get_xy_slice(self, token, channel,
x_start, x_stop,
y_start, y_stop,
z_index,
resolution=0):
"""
Return a binary-encoded, decompressed 2d image. You should
specify a 'token' and 'channel' pair. For image dat... |
def get_volume(self, token, channel,
x_start, x_stop,
y_start, y_stop,
z_start, z_stop,
resolution=1,
block_size=DEFAULT_BLOCK_SIZE,
neariso=False):
"""
Get a RAMONVolume volumetric cutout f... |
def get_cutout(self, token, channel,
x_start, x_stop,
y_start, y_stop,
z_start, z_stop,
t_start=0, t_stop=1,
resolution=1,
block_size=DEFAULT_BLOCK_SIZE,
neariso=False):
"""
... |
def post_cutout(self, token, channel,
x_start,
y_start,
z_start,
data,
resolution=0):
"""
Post a cutout to the server.
Arguments:
token (str)
channel (str)
x_s... |
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... |
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)
... |
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... |
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... |
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() |
def clone(self, url):
"""Clone repository from url."""
return self.execute("%s branch %s %s" % (self.executable,
url, self.path)) |
def get_version():
"""Get version from package resources."""
requirement = pkg_resources.Requirement.parse("yoda")
provider = pkg_resources.get_provider(requirement)
return provider.version |
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 |
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.'... |
def load(nifti_filename):
"""
Import a nifti file into a numpy array. TODO: Currently only
transfers raw data for compatibility with annotation and ND formats
Arguments:
nifti_filename (str): A string filename of a nifti datafile
Returns:
A numpy array with data from the nifti fi... |
def save(nifti_filename, numpy_data):
"""
Export a numpy array to a nifti file. TODO: currently using dummy
headers and identity matrix affine transform. This can be expanded.
Arguments:
nifti_filename (str): A filename to which to save the nifti data
numpy_data (numpy.ndarray): The nu... |
def ping(self, suffix='public_tokens/'):
"""
Return the status-code of the API (estimated using the public-tokens
lookup page).
Arguments:
suffix (str : 'public_tokens/'): The url endpoint to check
Returns:
int: status code
"""
return sel... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.