code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
# Note: this code assumes that docker containers running on ec2 instances
# inherit instances metadata, which they do as of 2016-08-25
global IS_EC2_INSTANCE
if IS_EC2_INSTANCE != -1:
# Returned the cached value
return IS_EC2_INSTANCE
s = socket.socket(socket.AF_INET, socket... | def is_ec2_instance() | Try fetching instance metadata at 'curl http://169.254.169.254/latest/meta-data/'
to see if host is on an ec2 instance | 3.058619 | 2.834038 | 1.079244 |
if isinstance(t, str):
if '+' not in t:
t = t + '+00:00'
t = parser.parse(t)
elif t.tzinfo is None or t.tzinfo.utcoffset(t) is None:
t = t.replace(tzinfo=pytz.timezone('utc'))
t0 = datetime.datetime(1970, 1, 1, 0, 0, 0, 0, pytz.timezone('utc'))
delta = t - t0
... | def to_epoch(t) | Take a datetime, either as a string or a datetime.datetime object,
and return the corresponding epoch | 2.009425 | 1.994355 | 1.007556 |
root_dir = os.path.dirname(os.path.realpath(sys.argv[0]))
version_file = os.path.join(root_dir, 'VERSION')
if os.path.exists(version_file):
with open(version_file) as f:
return f.read()
return '' | def get_container_version() | Return the version of the docker container running the present server,
or '' if not in a container | 1.941097 | 1.956552 | 0.992101 |
conf = get_config()
if is_ec2_instance():
return conf.app_name_live if hasattr(conf, 'app_name_live') else 'PYMACARON_LIVE'
else:
return conf.app_name_dev if hasattr(conf, 'app_name_dev') else 'PYMACARON_DEV' | def get_app_name() | Return a generic name for this app, usefull when reporting to monitoring/logging frameworks | 3.823469 | 3.824921 | 0.99962 |
if seed is not None:
import random
random.seed(seed)
print("Running biggest_multiple.py")
biggest_multiple.run(plot=plot)
print("Running polynomials.py")
polynomials.run(plot=plot)
print("Running travelling_salesman.py")
travelling_salesman.run(plot=plot)
print("... | def run_all(plot=True, seed=None) | Run all examples. | 3.14325 | 2.85679 | 1.100274 |
dna = ''.join([random.choice(cls.GENETIC_MATERIAL_OPTIONS) for _ in range(length)])
return cls(dna, **kwargs) | def create_random(cls, length, **kwargs) | Return a new instance of this gene class with random DNA,
with characters chosen from ``GENETIC_MATERIAL_OPTIONS``.
length: the number of characters in the randomized DNA
**kwargs: forwarded to the ``cls`` constructor | 5.268414 | 2.503096 | 2.104759 |
new_dna = []
for bit in self.dna:
if random.random() < p_mutate:
new_bit = bit
while new_bit == bit:
new_bit = random.choice(self.GENETIC_MATERIAL_OPTIONS)
bit = new_bit
new_dna.append(bit)
s... | def mutate(self, p_mutate) | Simulate mutation against a probability.
p_mutate: probability for mutation to occur | 3.063708 | 3.273948 | 0.935784 |
return type(self)(self.dna, suppressed=self.suppressed, name=self.name) | def copy(self) | Return a new instance of this gene with the same DNA. | 11.288096 | 5.187168 | 2.176158 |
valid_chars = set(self.GENETIC_MATERIAL_OPTIONS)
assert all(char in valid_chars for char in dna) | def _check_dna(self, dna) | Check that a DNA string only contains characters in ``GENETIC_MATERIAL_OPTIONS``. | 7.261474 | 2.743622 | 2.646675 |
new_dna = []
for bit in self.dna:
if random.random() < p_mutate:
bit = '1' if bit == '0' else '0'
new_dna.append(bit)
self.dna = ''.join(new_dna) | def mutate(self, p_mutate) | Check each element for mutation, swapping "0" for "1" and vice-versa. | 2.35626 | 2.193741 | 1.074083 |
if extra is None:
return
for key, value in extra.items():
if value is None:
if key in base:
del base[key]
# If the key represents a dict on both given dicts, merge the sub-dicts
elif isinstance(base.get(key), dict) and isinstance(value, dict):
... | def deep_merge(base, extra) | Deeply merge two dictionaries, overriding existing keys in the base.
:param base: The base dictionary which will be merged into.
:param extra: The dictionary to merge into the base. Keys from this
dictionary will take precedence. | 3.12021 | 3.328526 | 0.937415 |
client_cls = utils.get_client_class('monitoring', api_version, VERSION_MAP)
c = client_cls(
session=session,
service_type=service_type,
endpoint=endpoint,
app_name='monascaclient',
app_version=version.version_string,
)
return c | def make_client(api_version, session=None,
endpoint=None, service_type='monitoring') | Returns an monitoring API client. | 3.780487 | 3.676593 | 1.028258 |
cmd_name = name[3:].replace('_', '-')
callback = getattr(func_module, name)
desc = callback.__doc__ or ''
help = desc.strip().split('\n')[0]
arguments = getattr(callback, 'arguments', [])
body = {
'_args': arguments,
'_callback': staticmethod(callback),
'_descript... | def create_command_class(name, func_module) | Dynamically creates subclass of MigratingCommand.
Method takes name of the function, module it is part of
and builds the subclass of :py:class:`MigratingCommand`.
Having a subclass of :py:class:`cliff.command.Command` is mandatory
for the osc-lib integration.
:param name: name of the function
... | 4.008823 | 3.219193 | 1.245288 |
if 'session' in kwargs:
LOG.debug('Reusing session')
sess = kwargs.get('session')
if not isinstance(sess, k_session.Session):
msg = ('session should be an instance of %s' % k_session.Session)
LOG.error(msg)
raise RuntimeError(msg)
else:
LO... | def _session(kwargs) | Returns or reuses session.
Method takes care of providing instance of
session object for the client.
:param kwargs: all params (without api_version) client was initialized with
:type kwargs: dict
:returns: session object
:rtype keystoneauth1.session.Session | 2.983779 | 3.06312 | 0.974098 |
if path is None:
return cls.load_from_dict({})
else:
d = io.load(path)
return cls.load_from_dict(d) | def load(cls, path) | Loads an instance of the class from a file.
Parameters
----------
path : str
Path to an HDF5 file.
Examples
--------
This is an abstract data type, but let us say that ``Foo`` inherits
from ``Saveable``. To construct an object of this class from a fi... | 3.377086 | 6.049466 | 0.558245 |
def register_decorator(reg_cls):
def name_func(self):
return name
reg_cls.name = property(name_func)
assert issubclass(reg_cls, cls), \
"Must be subclass matching your NamedRegistry class"
cls.REGISTRY[name] = reg_cls
... | def register(cls, name) | Decorator to register a class. | 5.270547 | 4.832482 | 1.09065 |
return cls.REGISTRY[name](*args, **kwargs) | def construct(cls, name, *args, **kwargs) | Constructs an instance of an object given its name. | 7.185369 | 6.502281 | 1.105054 |
conf = ConfigParser()
# Set up defaults
conf.add_section('io')
conf.set('io', 'compression', 'zlib')
conf.read(os.path.expanduser('~/.deepdish.conf'))
return conf | def config() | Loads and returns a ConfigParser from ``~/.deepdish.conf``. | 5.627885 | 3.427413 | 1.642021 |
_import_skimage()
from skimage.transform.pyramids import pyramid_reduce, pyramid_expand
if factor < 1:
return pyramid_reduce(im, downscale=1/factor)
elif factor > 1:
return pyramid_expand(im, upscale=factor)
else:
return im | def resize_by_factor(im, factor) | Resizes the image according to a factor. The image is pre-filtered
with a Gaussian and then resampled with bilinear interpolation.
This function uses scikit-image and essentially combines its
`pyramid_reduce` with `pyramid_expand` into one function.
Returns the same object if factor is 1, not a copy.
... | 2.788313 | 2.799569 | 0.995979 |
if im.ndim == 2:
return im
elif im.ndim == 3 and im.shape[2] in (3, 4):
return im[..., :3].mean(axis=-1)
else:
raise ValueError('Invalid image format') | def asgray(im) | Takes an image and returns its grayscale version by averaging the color
channels. if an alpha channel is present, it will simply be ignored. If a
grayscale image is given, the original image is returned.
Parameters
----------
image : ndarray, ndim 2 or 3
RGB or grayscale image.
Return... | 2.642642 | 2.795419 | 0.945347 |
diff = [im.shape[index] - size[index] for index in (0, 1)]
im2 = im[diff[0]//2:diff[0]//2 + size[0], diff[1]//2:diff[1]//2 + size[1]]
return im2 | def crop(im, size) | Crops an image in the center.
Parameters
----------
size : tuple, (height, width)
Finally size after cropping. | 2.314535 | 2.731582 | 0.847324 |
diff = [im.shape[index] - size[index] for index in (0, 1)]
im2 = im[diff[0]//2:diff[0]//2 + size[0], diff[1]//2:diff[1]//2 + size[1]]
return im2 | def crop_or_pad(im, size, value=0) | Crops an image in the center.
Parameters
----------
size : tuple, (height, width)
Finally size after cropping. | 2.592876 | 2.775433 | 0.934224 |
_import_skimage()
import skimage.io
im = skimage.io.imread(path)
if dtype == np.uint8:
return im
elif dtype in {np.float16, np.float32, np.float64}:
return im.astype(dtype) / 255
else:
raise ValueError('Unsupported dtype') | def load(path, dtype=np.float64) | Loads an image from file.
Parameters
----------
path : str
Path to image file.
dtype : np.dtype
Defaults to ``np.float64``, which means the image will be returned as a
float with values between 0 and 1. If ``np.uint8`` is specified, the
values will be between 0 and 255 a... | 2.857806 | 3.141398 | 0.909724 |
_import_pil()
from PIL import Image
return np.array(Image.open(path)) | def load_raw(path) | Load image using PIL/Pillow without any processing. This is particularly
useful for palette images, which will be loaded using their palette index
values as opposed to `load` which will convert them to RGB.
Parameters
----------
path : str
Path to image file. | 9.005776 | 14.437358 | 0.623783 |
from PIL import Image
if im.dtype == np.uint8:
pil_im = Image.fromarray(im)
else:
pil_im = Image.fromarray((im*255).astype(np.uint8))
pil_im.save(path) | def save(path, im) | Saves an image to file.
If the image is type float, it will assume to have values in [0, 1].
Parameters
----------
path : str
Path to which the image will be saved.
im : ndarray (image)
Image. | 1.866403 | 1.893459 | 0.985711 |
# This line is modified
S = np.zeros(ii.shape[-1])
S += ii[r1, c1]
if (r0 - 1 >= 0) and (c0 - 1 >= 0):
S += ii[r0 - 1, c0 - 1]
if (r0 - 1 >= 0):
S -= ii[r0 - 1, c1]
if (c0 - 1 >= 0):
S -= ii[r1, c0 - 1]
return S | def integrate(ii, r0, c0, r1, c1) | Use an integral image to integrate over a given window.
Parameters
----------
ii : ndarray
Integral image.
r0, c0 : int
Top-left corner of block to be summed.
r1, c1 : int
Bottom-right corner of block to be summed.
Returns
-------
S : int
Integral (sum) ... | 2.501161 | 2.329593 | 1.073647 |
sh = img.shape
if sh == (0, 0):
return img
else:
x = np.empty(sh)
x[:] = fill_value
x[max(offset[0], 0):min(sh[0]+offset[0], sh[0]),
max(offset[1], 0):min(sh[1]+offset[1], sh[1])] = \
img[max(-offset[0], 0):min(sh[0]-offset[0], sh[0]),
... | def offset(img, offset, fill_value=0) | Moves the contents of image without changing the image size. The missing
values are given a specified fill value.
Parameters
----------
img : array
Image.
offset : (vertical_offset, horizontal_offset)
Tuple of length 2, specifying the offset along the two axes.
fill_value : dtyp... | 1.929406 | 1.988698 | 0.970186 |
assert alpha.ndim == 2
# Take the bounding box of the support, with a certain threshold.
supp_axs = [alpha.max(axis=1-i) for i in range(2)]
# Check first and last value of that threshold
bb = [np.where(supp_axs[i] > threshold)[0][[0, -1]] for i in range(2)]
return (bb[0][0], bb[1][0], bb... | def bounding_box(alpha, threshold=0.1) | Returns a bounding box of the support.
Parameters
----------
alpha : ndarray, ndim=2
Any one-channel image where the background has zero or low intensity.
threshold : float
The threshold that divides background from foreground.
Returns
-------
bounding_box : (top, left, bot... | 4.809509 | 4.80703 | 1.000516 |
bb = bounding_box(alpha)
x = np.zeros(alpha.shape, dtype=np.bool_)
x[bb[0]:bb[2], bb[1]:bb[3]] = 1
return x | def bounding_box_as_binary_map(alpha, threshold=0.1) | Similar to `bounding_box`, except returns the bounding box as a
binary map the same size as the input.
Same parameters as `bounding_box`.
Returns
-------
binary_map : ndarray, ndim=2, dtype=np.bool_
Binary map with True if object and False if background. | 2.883978 | 3.036371 | 0.949811 |
rs = np.random.RandomState(seed)
for Xi in itr.cycle(images):
# How many patches could we extract?
w, h = [Xi.shape[i]-patch_shape[i] for i in range(2)]
assert w > 0 and h > 0
# Maybe shuffle an iterator of the indices?
indices = np.asarray(list(itr.product(range(w... | def extract_patches(images, patch_shape, samples_per_image=40, seed=0,
cycle=True) | Takes a set of images and yields randomly chosen patches of specified size.
Parameters
----------
images : iterable
The images have to be iterable, and each element must be a Numpy array
with at least two spatial 2 dimensions as the first and second axis.
patch_shape : tuple, length 2
... | 3.319708 | 4.269689 | 0.777506 |
byte_size = np.prod(arr.shape) * np.dtype(arr.dtype).itemsize
return byte_size | def bytesize(arr) | Returns the memory byte size of a Numpy array as an integer. | 2.673108 | 2.354528 | 1.135305 |
return np.unravel_index(np.argmax(a), np.shape(a)) | def tupled_argmax(a) | Argmax that returns an index tuple. Note that `numpy.argmax` will return a
scalar index as if you had flattened the array.
Parameters
----------
a : array_like
Input array.
Returns
-------
index : tuple
Tuple of index, even if `a` is one-dimensional. Note that this can
... | 2.9176 | 5.469085 | 0.533471 |
start = time.time()
yield
end = time.time()
delta = end - start
if callback is not None:
callback(delta)
elif isinstance(file, np.ndarray) and len(file) == 1:
file[0] = delta
else:
name_str = ' {}'.format(name) if name is not None else ''
print(("[timed]{... | def timed(name=None, file=sys.stdout, callback=None, wall_clock=True) | Context manager to make it easy to time the execution of a piece of code.
This timer will never run your code several times and is meant more for
simple in-production timing, instead of benchmarking. Reports the
wall-clock time (using `time.time`) and not the processor time.
Parameters
----------
... | 3.193256 | 3.258575 | 0.979955 |
data = np.asarray(data)
shape = data.shape
if isinstance(padwidth, int):
padwidth = (padwidth,)*len(shape)
padded_shape = tuple(map(lambda ix: ix[1]+padwidth[ix[0]]*2,
enumerate(shape)))
new_data = np.empty(padded_shape, dtype=data.dtype)
new_data[..., ... | def pad(data, padwidth, value=0.0) | Pad an array with a specific value.
Parameters
----------
data : ndarray
Numpy array of any dimension and type.
padwidth : int or tuple
If int, it will pad using this amount at the beginning and end of all
dimensions. If it is a tuple (of same length as `ndim`), then the
... | 2.653708 | 3.422882 | 0.775285 |
shape = [data.shape[i] if shape[i] == -1 else shape[i]
for i in range(len(shape))]
new_data = np.empty(shape)
new_data[:] = value
II = [slice((shape[i] - data.shape[i])//2,
(shape[i] - data.shape[i])//2 + data.shape[i])
for i in range(len(shape))]
new_data... | def pad_to_size(data, shape, value=0.0) | This is similar to `pad`, except you specify the final shape of the array.
Parameters
----------
data : ndarray
Numpy array of any dimension and type.
shape : tuple
Final shape of padded array. Should be tuple of length ``data.ndim``.
If it has to pad unevenly, it will pad one m... | 2.045453 | 2.921674 | 0.700096 |
data = np.asarray(data)
shape = data.shape
if isinstance(padwidth, int):
padwidth = (padwidth,)*len(shape)
padded_shape = tuple(map(lambda ix: ix[1]+padwidth[ix[0]]*2,
enumerate(shape)))
new_data = np.empty(padded_shape, dtype=data.dtype)
new_data[[sli... | def pad_repeat_border(data, padwidth) | Similar to `pad`, except the border value from ``data`` is used to pad.
Parameters
----------
data : ndarray
Numpy array of any dimension and type.
padwidth : int or tuple
If int, it will pad using this amount at the beginning and end of all
dimensions. If it is a tuple (of same... | 2.081136 | 2.309605 | 0.901079 |
new_data = np.empty(shape)
new_data[[slice(upper) for upper in data.shape]] = data
for i in range(len(shape)):
selection = [slice(None)]*i + [slice(data.shape[i], None)]
selection2 = [slice(None)]*i + [slice(data.shape[i]-1, data.shape[i])]
new_data[selection] = new_data[selecti... | def pad_repeat_border_corner(data, shape) | Similar to `pad_repeat_border`, except the padding is always done on the
upper end of each axis and the target size is specified.
Parameters
----------
data : ndarray
Numpy array of any dimension and type.
shape : tuple
Final shape of padded array. Should be tuple of length ``data.n... | 2.783758 | 3.815439 | 0.729604 |
if len(d) >= 256:
return False
# All keys must be strings
for k in d:
if not isinstance(k, six.string_types):
return False
return True | def _dict_native_ok(d) | This checks if a dictionary can be saved natively as HDF5 groups.
If it can't, it will be pickled. | 3.143836 | 3.407136 | 0.922721 |
if isinstance(level, tables.link.SoftLink):
# this is a link, so see if target is already loaded, return it
pathname = level.target
node = level()
else:
# not a link, but it might be a target that's already been
# loaded ... if so, return it
pathname = level.... | def _load_level(handler, level, pathtable) | Loads level and builds appropriate type, handling softlinks if necessary | 5.372451 | 5.029399 | 1.068209 |
filters = _get_compression_filters(compression)
with tables.open_file(path, mode='w') as h5file:
# If the data is a dictionary, put it flatly in the root
group = h5file.root
group._v_attrs[DEEPDISH_IO_VERSION_STR] = IO_VERSION
idtable = {} # dict to keep track of objects a... | def save(path, data, compression='default') | Save any Python structure to an HDF5 file. It is particularly suited for
Numpy arrays. This function works similar to ``numpy.save``, except if you
save a Python object at the top level, you do not need to issue
``data.flat[0]`` to retrieve it from inside a Numpy array of type
``object``.
Some type... | 3.917304 | 3.991939 | 0.981304 |
with tables.open_file(path, mode='r') as h5file:
pathtable = {} # dict to keep track of objects already loaded
if group is not None:
if isinstance(group, str):
data = _load_specific_level(h5file, h5file, group, sel=sel,
pa... | def load(path, group=None, sel=None, unpack=False) | Loads an HDF5 saved with `save`.
This function requires the `PyTables <http://www.pytables.org/>`_ module to
be installed.
Parameters
----------
path : string
Filename from which to load the data.
group : string or list
Load a specific group in the HDF5 hierarchy. If `group` is... | 3.026497 | 3.06334 | 0.987973 |
all_numeric = all(map(str.isdigit, x))
if all_numeric:
return sorted(x, key=int)
else:
return sorted(x) | def sorted_maybe_numeric(x) | Sorts x with numeric semantics if all keys are nonnegative integers.
Otherwise uses standard string sorting. | 2.806156 | 2.669366 | 1.051244 |
assert maxlength >= 4
skip = False
abbrv = None
i = 0
for j, c in enumerate(s):
if c == '\033':
skip = True
elif skip:
if c == 'm':
skip = False
else:
i += 1
if i == maxlength - 1:
abbrv = s[:j] + '... | def abbreviate(s, maxlength=25) | Color-aware abbreviator | 3.32336 | 3.366111 | 0.9873 |
data = Data.objects.select_related('process').get(pk=data_id)
files[ExecutorFiles.DJANGO_SETTINGS].update({
'USE_TZ': settings.USE_TZ,
'FLOW_EXECUTOR_TOOLS_PATHS': self.get_tools_paths(),
})
files[ExecutorFiles.DATA] = model_to_dict(data)
files[E... | def extend_settings(self, data_id, files, secrets) | Extend the settings the manager will serialize.
:param data_id: The :class:`~resolwe.flow.models.Data` object id
being prepared for.
:param files: The settings dictionary to be serialized. Keys are
filenames, values are the objects that will be serialized
into those ... | 4.372261 | 3.925498 | 1.11381 |
if settings.DEBUG or is_testing():
return list(get_apps_tools().values())
else:
tools_root = settings.FLOW_TOOLS_ROOT
subdirs = next(os.walk(tools_root))[1]
return [os.path.join(tools_root, sdir) for sdir in subdirs] | def get_tools_paths(self) | Get tools' paths. | 4.67138 | 4.532534 | 1.030633 |
if data is None:
return settings.FLOW_EXECUTOR['DATA_DIR']
return data.location.get_path(filename=filename) | def resolve_data_path(self, data=None, filename=None) | Resolve data path for use with the executor.
:param data: Data object instance
:param filename: Filename to resolve
:return: Resolved filename, which can be used to access the
given data file in programs executed using this executor | 8.694289 | 9.542806 | 0.911083 |
if filename is None:
return settings.FLOW_EXECUTOR['UPLOAD_DIR']
return os.path.join(settings.FLOW_EXECUTOR['UPLOAD_DIR'], filename) | def resolve_upload_path(self, filename=None) | Resolve upload path for use with the executor.
:param filename: Filename to resolve
:return: Resolved filename, which can be used to access the
given uploaded file in programs executed using this
executor | 3.729908 | 3.908262 | 0.954365 |
w = AccessPolicyWrapper(access_pyxb)
yield w
if not read_only:
w.get_normalized_pyxb() | def wrap(access_pyxb, read_only=False) | Work with the AccessPolicy in a SystemMetadata PyXB object.
Args:
access_pyxb : AccessPolicy PyXB object
The AccessPolicy to modify.
read_only: bool
Do not update the wrapped AccessPolicy.
When only a single AccessPolicy operation is needed, there's no need to use this
context... | 7.558043 | 6.902958 | 1.094899 |
w = AccessPolicyWrapper(sysmeta_pyxb.accessPolicy)
yield w
if not read_only:
sysmeta_pyxb.accessPolicy = w.get_normalized_pyxb() | def wrap_sysmeta_pyxb(sysmeta_pyxb, read_only=False) | Work with the AccessPolicy in a SystemMetadata PyXB object.
Args:
sysmeta_pyxb : SystemMetadata PyXB object
SystemMetadata containing the AccessPolicy to modify.
read_only: bool
Do not update the wrapped AccessPolicy.
When only a single AccessPolicy operation is needed, there's no... | 4.987467 | 4.871022 | 1.023906 |
pres_perm_set = self._present_perm_set_for_subj(self._perm_dict, subj_str)
return (
None if not pres_perm_set else self._highest_perm_from_iter(pres_perm_set)
) | def get_highest_perm_str(self, subj_str) | Args:
subj_str : str
Subject for which to retrieve the highest permission.
Return:
The highest permission for subject or None if subject does not have any permissions. | 5.546391 | 5.575071 | 0.994856 |
highest_perm_str = self.get_highest_perm_str(subj_str)
if highest_perm_str is None:
return []
return self._equal_or_lower_perm_list(highest_perm_str) | def get_effective_perm_list(self, subj_str) | Args:
subj_str : str
Subject for which to retrieve the effective permissions.
Returns:
list of str: List of permissions up to and including the highest permission for
subject, ordered lower to higher, or empty list if subject does not have any
permissions.
E.g.: If 'write' is... | 3.528431 | 3.874326 | 0.910721 |
self._assert_valid_permission(perm_str)
return {
s
for p in self._equal_or_higher_perm(perm_str)
for s in self._perm_dict.get(p, set())
} | def get_subjects_with_equal_or_higher_perm(self, perm_str) | Args:
perm_str : str
Permission, ``read``, ``write`` or ``changePermission``.
Returns:
set of str : Subj that have perm equal or higher than ``perm_str``.
Since the lowest permission a subject can have is ``read``, passing ``read``
will return all subjects. | 3.836044 | 4.515896 | 0.849454 |
logging.debug('AccessPolicy:')
map(
logging.debug,
[
' {}'.format(s)
for s in pprint.pformat(self.get_normalized_perm_list()).splitlines()
],
) | def dump(self) | Dump the current state to debug level log. | 9.972417 | 9.02643 | 1.104802 |
self._assert_valid_permission(perm_str)
return perm_str in self.get_effective_perm_list(subj_str) | def subj_has_perm(self, subj_str, perm_str) | Returns:
bool: ``True`` if ``subj_str`` has perm equal to or higher than ``perm_str``. | 4.876072 | 4.621505 | 1.055083 |
self.remove_perm(d1_common.const.SUBJECT_PUBLIC, 'read')
self.add_perm(d1_common.const.SUBJECT_AUTHENTICATED, 'read') | def add_authenticated_read(self) | Add ``read`` perm for all authenticated subj.
Public ``read`` is removed if present. | 5.310309 | 4.467201 | 1.188733 |
self.remove_perm(d1_common.const.SUBJECT_PUBLIC, 'read')
self.add_perm(d1_common.const.SUBJECT_VERIFIED, 'read') | def add_verified_read(self) | Add ``read`` perm for all verified subj.
Public ``read`` is removed if present. | 6.034243 | 4.421721 | 1.364682 |
self._assert_valid_permission(perm_str)
self._perm_dict.setdefault(perm_str, set()).add(subj_str) | def add_perm(self, subj_str, perm_str) | Add a permission for a subject.
Args:
subj_str : str
Subject for which to add permission(s)
perm_str : str
Permission to add. Implicitly adds all lower permissions. E.g., ``write``
will also add ``read``. | 3.982166 | 4.248877 | 0.937228 |
self._assert_valid_permission(perm_str)
for perm_str in self._equal_or_higher_perm(perm_str):
self._perm_dict.setdefault(perm_str, set()).discard(subj_str) | def remove_perm(self, subj_str, perm_str) | Remove permission from a subject.
Args:
subj_str : str
Subject for which to remove permission(s)
perm_str : str
Permission to remove. Implicitly removes all higher permissions. E.g., ``write``
will also remove ``changePermission`` if previously granted. | 4.525544 | 4.506077 | 1.00432 |
for subj_set in list(self._perm_dict.values()):
subj_set -= {subj_str} | def remove_subj(self, subj_str) | Remove all permissions for subject.
Args:
subj_str : str
Subject for which to remove all permissions. Since subjects can only be present
in the AccessPolicy when they have one or more permissions, this removes the
subject itself as well.
The subject ma... | 7.262964 | 8.637448 | 0.840869 |
subj_dict = self._subj_dict_from_pyxb(access_pyxb)
return self._perm_dict_from_subj_dict(subj_dict) | def _perm_dict_from_pyxb(self, access_pyxb) | Return dict representation of AccessPolicy PyXB obj. | 2.968164 | 2.921093 | 1.016114 |
perm_dict = {}
for subj_str, perm_set in list(subj_dict.items()):
for perm_str in perm_set:
perm_dict.setdefault(perm_str, set()).add(subj_str)
return perm_dict | def _perm_dict_from_subj_dict(self, subj_dict) | Return dict where keys and values of ``subj_dict`` have been flipped
around. | 2.293969 | 2.309868 | 0.993117 |
norm_perm_list = self._norm_perm_list_from_perm_dict(perm_dict)
return self._pyxb_from_norm_perm_list(norm_perm_list) | def _pyxb_from_perm_dict(self, perm_dict) | Return an AccessPolicy PyXB representation of ``perm_dict``
- If ``norm_perm_list`` is empty, None is returned. The schema does not allow
AccessPolicy to be empty, but in SystemMetadata, it can be left out
altogether. So returning None instead of an empty AccessPolicy allows the
result ... | 2.761267 | 2.436651 | 1.133222 |
# Using accessPolicy() instead of AccessPolicy() and accessRule() instead of
# AccessRule() gives PyXB the type information required for using this as a
# root element.
access_pyxb = d1_common.types.dataoneTypes.accessPolicy()
for perm_str, subj_list in norm_perm_list:
... | def _pyxb_from_norm_perm_list(self, norm_perm_list) | Return an AccessPolicy PyXB representation of ``norm_perm_list`` | 3.847501 | 3.492361 | 1.10169 |
subj_dict = {}
for allow_pyxb in access_pyxb.allow:
perm_set = set()
for perm_pyxb in allow_pyxb.permission:
perm_set.add(perm_pyxb)
for subj_pyxb in allow_pyxb.subject:
subj_dict.setdefault(subj_pyxb.value(), set()).update(per... | def _subj_dict_from_pyxb(self, access_pyxb) | Return a dict representation of ``access_pyxb``, which is an AccessPolicy
PyXB object.
This also remove any duplicate subjects and permissions in the PyXB object. | 2.261196 | 2.05732 | 1.099097 |
highest_perm_dict = copy.copy(perm_dict)
for ordered_str in reversed(ORDERED_PERM_LIST):
for lower_perm in self._lower_perm_list(ordered_str):
highest_perm_dict.setdefault(lower_perm, set())
highest_perm_dict[lower_perm] -= perm_dict.get(ordered_str, ... | def _highest_perm_dict_from_perm_dict(self, perm_dict) | Return a perm_dict where only the highest permission for each subject is
included. | 3.33948 | 3.434361 | 0.972373 |
high_perm_dict = self._highest_perm_dict_from_perm_dict(perm_dict)
return [
[k, list(sorted(high_perm_dict[k]))]
for k in ORDERED_PERM_LIST
if high_perm_dict.get(k, False)
] | def _norm_perm_list_from_perm_dict(self, perm_dict) | Return a minimal, ordered, hashable list of subjects and permissions. | 4.276697 | 3.778087 | 1.131974 |
highest_perm_str = self._highest_perm_from_iter(perm_iter)
return (
self._equal_or_lower_perm_list(highest_perm_str)
if highest_perm_str is not None
else None
) | def _effective_perm_list_from_iter(self, perm_iter) | Return list of effective permissions for for highest permission in
``perm_iter``, ordered lower to higher, or None if ``perm_iter`` is empty. | 4.066045 | 3.48037 | 1.16828 |
return {p for p, s in list(perm_dict.items()) if subj_str in s} | def _present_perm_set_for_subj(self, perm_dict, subj_str) | Return a set containing only the permissions that are present in the
``perm_dict`` for ``subj_str`` | 4.811433 | 4.358605 | 1.103893 |
perm_set = set(perm_iter)
for perm_str in reversed(ORDERED_PERM_LIST):
if perm_str in perm_set:
return perm_str | def _highest_perm_from_iter(self, perm_iter) | Return the highest perm present in ``perm_iter`` or None if ``perm_iter`` is
empty. | 4.425722 | 4.266079 | 1.037421 |
for i, ordered_str in enumerate(ORDERED_PERM_LIST):
if perm_str == ordered_str:
return i | def _ordered_idx_from_perm(self, perm_str) | Return the ordered index of ``perm_str`` or None if ``perm_str`` is not a
valid permission. | 5.026019 | 4.692737 | 1.071021 |
if perm_str not in ORDERED_PERM_LIST:
raise d1_common.types.exceptions.InvalidRequest(
0,
'Permission must be one of {}. perm_str="{}"'.format(
', '.join(ORDERED_PERM_LIST), perm_str
),
) | def _assert_valid_permission(self, perm_str) | Raise D1 exception if ``perm_str`` is not a valid permission. | 3.513553 | 3.089158 | 1.137382 |
exc_type, exc_msgs = sys.exc_info()[:2]
if exc_type.__name__ == "SSLError":
d1_cli.impl.util.print_error(
)
elif exc_type.__name__ == "timeout":
d1_cli.impl.util.print_error(
)
else:
_print_unexpected_exception(max_traceback_levels) | def handle_unexpected_exception(max_traceback_levels=100) | Suppress stack traces for common errors and provide hints for how to resolve
them. | 3.614495 | 3.57252 | 1.011749 |
pid = d1_common.xml.get_req_val(sysmeta_pyxb.identifier)
set_mn_controlled_values(request, sysmeta_pyxb, is_modification=False)
d1_gmn.app.views.assert_db.is_valid_pid_for_create(pid)
d1_gmn.app.views.assert_sysmeta.sanity(request, sysmeta_pyxb)
if _is_proxy_sciobj(request):
sciobj_ur... | def create_sciobj(request, sysmeta_pyxb) | Create object file and database entries for a new native locally stored (non-
proxied) science object.
This method takes a request object and is only called from the views that
handle:
- MNStorage.create()
- MNStorage.update()
Various sanity checking is performed. Raises D1 exceptions that ar... | 3.216118 | 3.238348 | 0.993135 |
sciobj_path = d1_gmn.app.sciobj_store.get_abs_sciobj_file_path_by_pid(pid)
if hasattr(request.FILES['object'], 'temporary_file_path'):
d1_common.utils.filesystem.create_missing_directories_for_file(sciobj_path)
django.core.files.move.file_move_safe(
request.FILES['object'].tempo... | def _save_sciobj_bytes_from_request(request, pid) | Django stores small uploads in memory and streams large uploads directly to disk.
Uploads stored in memory are represented by UploadedFile and on disk,
TemporaryUploadedFile. To store an UploadedFile on disk, it's iterated and saved in
chunks. To store a TemporaryUploadedFile, it's moved from the temporary... | 2.628943 | 2.669637 | 0.984756 |
now_datetime = d1_common.date_time.utc_now()
default_value_list = [
('originMemberNode', django.conf.settings.NODE_IDENTIFIER, True),
('authoritativeMemberNode', django.conf.settings.NODE_IDENTIFIER, True),
('serialVersion', 1, False),
('dateUploaded', now_datetime, False),... | def set_mn_controlled_values(request, sysmeta_pyxb, is_modification) | See the description of TRUST_CLIENT_* in settings.py. | 3.533291 | 3.428753 | 1.030489 |
return [
entity.duplicate(contributor, inherit_collections)
for entity in self
] | def duplicate(self, contributor=None, inherit_collections=False) | Duplicate (make a copy) ``Entity`` objects.
:param contributor: Duplication user
:param inherit_collections: If ``True`` then duplicated
entities will be added to collections the original entity
is part of. Duplicated entities' data objects will also be
added to the ... | 6.362351 | 7.112541 | 0.894526 |
for entity in self:
entity.move_to_collection(source_collection, destination_collection) | def move_to_collection(self, source_collection, destination_collection) | Move entities from source to destination collection. | 3.443277 | 2.615651 | 1.316413 |
duplicate = Entity.objects.get(id=self.id)
duplicate.pk = None
duplicate.slug = None
duplicate.name = 'Copy of {}'.format(self.name)
duplicate.duplicated = now()
if contributor:
duplicate.contributor = contributor
duplicate.save(force_insert=... | def duplicate(self, contributor=None, inherit_collections=False) | Duplicate (make a copy). | 3.086591 | 3.065353 | 1.006928 |
# Remove from collection.
self.collections.remove(source_collection) # pylint: disable=no-member
source_collection.data.remove(*self.data.all()) # pylint: disable=no-member
# Add to collection.
self.collections.add(destination_collection) # pylint: disable=no-member
... | def move_to_collection(self, source_collection, destination_collection) | Move entity from source to destination collection. | 2.488009 | 2.478448 | 1.003858 |
res = s.split('%')
# fastpath
if len(res) == 1:
return s
s = res[0]
for item in res[1:]:
try:
s += _hextochr[item[:2]] + item[2:]
except KeyError:
s += '%' + item
except UnicodeDecodeError:
s += chr(int(item[:2], 16)) + item[2:... | def unquote(s) | unquote('abc%20def') -> 'abc def'. | 2.783437 | 2.726689 | 1.020812 |
res = s.replace('%', '%25')
for c in unsafe:
res = res.replace(c, '%' + (hex(ord(c)).upper())[2:])
return res | def quote(s, unsafe='/') | Pass in a dictionary that has unsafe characters as the keys, and the percent
encoded value as the value. | 3.435973 | 3.486626 | 0.985472 |
# pylint: disable=no-member
return super().get_dependencies() + [
Data.collection_set,
Data.entity_set,
Data.parents,
] | def get_dependencies(self) | Return dependencies, which should trigger updates of this model. | 9.207332 | 7.640549 | 1.205062 |
if scale == MZ and f == 5:
return alphasMZ # nothing to do
_sane(scale, f)
crd = rundec.CRunDec()
if f == 5:
return_value = crd.AlphasExact(alphasMZ, MZ, scale, f, loop)
elif f == 6:
crd.nfMmu.Mth = 170
crd.nfMmu.muth = 170
crd.nfMmu.nf = 6
retur... | def alpha_s(scale, f, alphasMZ=0.1185, loop=3) | 3-loop computation of alpha_s for f flavours
with initial condition alpha_s(MZ) = 0.1185 | 3.041587 | 3.012346 | 1.009707 |
r
if scale == mbmb and f == 5:
return mbmb # nothing to do
_sane(scale, f)
alphas_mb = alpha_s(mbmb, 5, alphasMZ=alphasMZ, loop=loop)
crd = rundec.CRunDec()
if f == 5:
alphas_scale = alpha_s(scale, f, alphasMZ=alphasMZ, loop=loop)
return crd.mMS2mMS(mbmb, alphas_mb, alph... | def m_b(mbmb, scale, f, alphasMZ=0.1185, loop=3) | r"""Get running b quark mass in the MSbar scheme at the scale `scale`
in the theory with `f` dynamical quark flavours starting from $m_b(m_b)$ | 2.589405 | 2.581341 | 1.003124 |
r
if scale == mcmc:
return mcmc # nothing to do
_sane(scale, f)
crd = rundec.CRunDec()
alphas_mc = alpha_s(mcmc, 4, alphasMZ=alphasMZ, loop=loop)
if f == 4:
alphas_scale = alpha_s(scale, f, alphasMZ=alphasMZ, loop=loop)
return crd.mMS2mMS(mcmc, alphas_mc, alphas_scale, f... | def m_c(mcmc, scale, f, alphasMZ=0.1185, loop=3) | r"""Get running c quark mass in the MSbar scheme at the scale `scale`
in the theory with `f` dynamical quark flavours starting from $m_c(m_c)$ | 3.538668 | 3.527739 | 1.003098 |
r
if scale == 2 and f == 3:
return ms2 # nothing to do
_sane(scale, f)
crd = rundec.CRunDec()
alphas_2 = alpha_s(2, 3, alphasMZ=alphasMZ, loop=loop)
if f == 3:
alphas_scale = alpha_s(scale, f, alphasMZ=alphasMZ, loop=loop)
return crd.mMS2mMS(ms2, alphas_2, alphas_scale, ... | def m_s(ms2, scale, f, alphasMZ=0.1185, loop=3) | r"""Get running s quark mass in the MSbar scheme at the scale `scale`
in the theory with `f` dynamical quark flavours starting from $m_s(2 \,\text{GeV})$ | 2.994692 | 2.978213 | 1.005533 |
if self.clear:
action = 'This will DELETE ALL FILES in this location!'
else:
action = 'This will overwrite existing files!'
message = (
"\n"
"You have requested to collect static files at the destination\n"
"location as specif... | def get_confirmation(self) | Get user confirmation to proceed. | 4.399323 | 4.343107 | 1.012944 |
self.stdout.write("Deleting contents of '{}'.".format(self.destination_path))
for filename in os.listdir(self.destination_path):
if os.path.isfile(filename) or os.path.islink(filename):
os.remove(filename)
elif os.path.isdir(filename):
sh... | def clear_dir(self) | Delete contents of the directory on the given path. | 2.303586 | 2.160705 | 1.066127 |
relative_path = os.path.relpath(path, old_prefix)
return os.path.join(new_prefix, app_name, relative_path) | def change_path_prefix(self, path, old_prefix, new_prefix, app_name) | Change path prefix and include app name. | 2.360826 | 2.236479 | 1.0556 |
for app_name, tools_path in get_apps_tools().items():
self.stdout.write("Copying files from '{}'.".format(tools_path))
app_name = app_name.replace('.', '_')
app_destination_path = os.path.join(self.destination_path, app_name)
if not os.path.isdir(app_de... | def collect(self) | Get tools' locations and copy them to a single location. | 1.876549 | 1.769133 | 1.060717 |
self.set_options(**options)
os.makedirs(self.destination_path, exist_ok=True)
if self.interactive and any(os.listdir(self.destination_path)):
self.get_confirmation()
if self.clear:
self.clear_dir()
self.collect() | def handle(self, **options) | Collect tools. | 4.499064 | 4.156454 | 1.082429 |
checksum = hashlib.sha256()
checksum.update(json.dumps(proc_input, sort_keys=True).encode('utf-8'))
checksum.update(proc_slug.encode('utf-8'))
checksum.update(str(proc_version).encode('utf-8'))
return checksum.hexdigest() | def get_data_checksum(proc_input, proc_slug, proc_version) | Compute checksum of processor inputs, name and version. | 1.565274 | 1.509195 | 1.037158 |
if val is None and k == '':
return d
def set_default(dict_or_model, key, default_value):
if isinstance(dict_or_model, models.Model):
if not hasattr(dict_or_model, key):
setattr(dict_or_model, key, default_value)
return getattr(dict_or_model... | def dict_dot(d, k, val=None, default=None) | Get or set value using a dot-notation key in a multilevel dict. | 2.090206 | 2.046353 | 1.02143 |
tools_paths = {}
for app_config in apps.get_app_configs():
proc_path = os.path.join(app_config.path, 'tools')
if os.path.isdir(proc_path):
tools_paths[app_config.name] = proc_path
custom_tools_paths = getattr(settings, 'RESOLWE_CUSTOM_TOOLS_PATHS', [])
if not isinstanc... | def get_apps_tools() | Get applications' tools and their paths.
Return a dict with application names as keys and paths to tools'
directories as values. Applications without tools are omitted. | 2.656798 | 2.665513 | 0.99673 |
if len(data_list) < 2:
return data_list
mapped_ids = {bundle['original'].id: bundle['copy'].id for bundle in data_list}
for bundle in data_list:
updated = False
copy = bundle['copy']
for field_schema, fields in iterate_fields(copy.input, copy.process.input_schema):
... | def rewire_inputs(data_list) | Rewire inputs of provided data objects.
Input parameter is a list of original and copied data object model
instances: ``[{'original': original, 'copy': copy}]``. This
function finds which objects reference other objects (in the list)
on the input and replaces original objects with the copies (mutates
... | 2.879763 | 2.787364 | 1.033149 |
if pyxb.XMLStyle_saxer != pyxb._XMLStyle:
dom = pyxb.utils.domutils.StringToDOM(xml_text)
return CreateFromDOM(dom.documentElement, default_namespace=default_namespace)
if default_namespace is None:
default_namespace = Namespace.fallbackNamespace()
saxer = pyxb.binding.saxer.ma... | def CreateFromDocument(xml_text, default_namespace=None, location_base=None) | Parse the given XML and use the document element to create a Python instance.
@param xml_text An XML document. This should be data (Python 2
str or Python 3 bytes), or a text (Python 2 unicode or Python 3
str) in the L{pyxb._InputEncoding} encoding.
@keyword default_namespace The L{pyxb.Namespace} in... | 1.289562 | 1.431669 | 0.90074 |
if default_namespace is None:
default_namespace = Namespace.fallbackNamespace()
return pyxb.binding.basis.element.AnyCreateFromDOM(node, default_namespace) | def CreateFromDOM(node, default_namespace=None) | Create a Python instance from the given DOM node. The node tag must correspond to
an element declaration in this module.
@deprecated: Forcing use of DOM interface is unnecessary; use L{CreateFromDocument}. | 1.873659 | 3.061509 | 0.612005 |
cmd.Cmd.postloop(self) # Clean up command completion
d1_cli.impl.util.print_info("Exiting...") | def postloop(self) | Take care of any unfinished business.
Despite the claims in the Cmd documentation, Cmd.postloop() is not a stub. | 17.115751 | 12.878232 | 1.329045 |
line = self.prefix + line
self._history += [line.strip()]
return line | def precmd(self, line) | This method is called after the line has been input but before it has been
interpreted.
If you want to modify the input line before execution (for example, variable
substitution) do it here. | 8.791606 | 10.874807 | 0.808438 |
args = self._split_args(line, 0, 99)
d1_cli.impl.util.print_error("Unknown command: {}".format(args[0])) | def default(self, line) | Called on an input line when the command prefix is not recognized. | 8.340094 | 6.657757 | 1.252688 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.