repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
pyviz/param | param/__init__.py | ObjectSelector._validate | def _validate(self, val):
"""
val must be None or one of the objects in self.objects.
"""
if not self.check_on_set:
self._ensure_value_is_in_objects(val)
return
if not (val in self.objects or (self.allow_None and val is None)):
# CEBALERT: can be called before __init__ has called
# super's __init__, i.e. before attrib_name has been set.
try:
attrib_name = self.name
except AttributeError:
attrib_name = ""
items = []
limiter = ']'
length = 0
for item in self.objects:
string = str(item)
length += len(string)
if length < 200:
items.append(string)
else:
limiter = ', ...]'
break
items = '[' + ', '.join(items) + limiter
raise ValueError("%s not in Parameter %s's list of possible objects, "
"valid options include %s"%(val,attrib_name, items)) | python | def _validate(self, val):
"""
val must be None or one of the objects in self.objects.
"""
if not self.check_on_set:
self._ensure_value_is_in_objects(val)
return
if not (val in self.objects or (self.allow_None and val is None)):
# CEBALERT: can be called before __init__ has called
# super's __init__, i.e. before attrib_name has been set.
try:
attrib_name = self.name
except AttributeError:
attrib_name = ""
items = []
limiter = ']'
length = 0
for item in self.objects:
string = str(item)
length += len(string)
if length < 200:
items.append(string)
else:
limiter = ', ...]'
break
items = '[' + ', '.join(items) + limiter
raise ValueError("%s not in Parameter %s's list of possible objects, "
"valid options include %s"%(val,attrib_name, items)) | [
"def",
"_validate",
"(",
"self",
",",
"val",
")",
":",
"if",
"not",
"self",
".",
"check_on_set",
":",
"self",
".",
"_ensure_value_is_in_objects",
"(",
"val",
")",
"return",
"if",
"not",
"(",
"val",
"in",
"self",
".",
"objects",
"or",
"(",
"self",
".",
"allow_None",
"and",
"val",
"is",
"None",
")",
")",
":",
"# CEBALERT: can be called before __init__ has called",
"# super's __init__, i.e. before attrib_name has been set.",
"try",
":",
"attrib_name",
"=",
"self",
".",
"name",
"except",
"AttributeError",
":",
"attrib_name",
"=",
"\"\"",
"items",
"=",
"[",
"]",
"limiter",
"=",
"']'",
"length",
"=",
"0",
"for",
"item",
"in",
"self",
".",
"objects",
":",
"string",
"=",
"str",
"(",
"item",
")",
"length",
"+=",
"len",
"(",
"string",
")",
"if",
"length",
"<",
"200",
":",
"items",
".",
"append",
"(",
"string",
")",
"else",
":",
"limiter",
"=",
"', ...]'",
"break",
"items",
"=",
"'['",
"+",
"', '",
".",
"join",
"(",
"items",
")",
"+",
"limiter",
"raise",
"ValueError",
"(",
"\"%s not in Parameter %s's list of possible objects, \"",
"\"valid options include %s\"",
"%",
"(",
"val",
",",
"attrib_name",
",",
"items",
")",
")"
] | val must be None or one of the objects in self.objects. | [
"val",
"must",
"be",
"None",
"or",
"one",
"of",
"the",
"objects",
"in",
"self",
".",
"objects",
"."
] | 8f0dafa78defa883247b40635f96cc6d5c1b3481 | https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/__init__.py#L1206-L1235 | train |
pyviz/param | param/__init__.py | ObjectSelector._ensure_value_is_in_objects | def _ensure_value_is_in_objects(self,val):
"""
Make sure that the provided value is present on the objects list.
Subclasses can override if they support multiple items on a list,
to check each item instead.
"""
if not (val in self.objects):
self.objects.append(val) | python | def _ensure_value_is_in_objects(self,val):
"""
Make sure that the provided value is present on the objects list.
Subclasses can override if they support multiple items on a list,
to check each item instead.
"""
if not (val in self.objects):
self.objects.append(val) | [
"def",
"_ensure_value_is_in_objects",
"(",
"self",
",",
"val",
")",
":",
"if",
"not",
"(",
"val",
"in",
"self",
".",
"objects",
")",
":",
"self",
".",
"objects",
".",
"append",
"(",
"val",
")"
] | Make sure that the provided value is present on the objects list.
Subclasses can override if they support multiple items on a list,
to check each item instead. | [
"Make",
"sure",
"that",
"the",
"provided",
"value",
"is",
"present",
"on",
"the",
"objects",
"list",
".",
"Subclasses",
"can",
"override",
"if",
"they",
"support",
"multiple",
"items",
"on",
"a",
"list",
"to",
"check",
"each",
"item",
"instead",
"."
] | 8f0dafa78defa883247b40635f96cc6d5c1b3481 | https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/__init__.py#L1237-L1244 | train |
pyviz/param | param/__init__.py | ClassSelector._validate | def _validate(self,val):
"""val must be None, an instance of self.class_ if self.is_instance=True or a subclass of self_class if self.is_instance=False"""
if isinstance(self.class_, tuple):
class_name = ('(%s)' % ', '.join(cl.__name__ for cl in self.class_))
else:
class_name = self.class_.__name__
if self.is_instance:
if not (isinstance(val,self.class_)) and not (val is None and self.allow_None):
raise ValueError(
"Parameter '%s' value must be an instance of %s, not '%s'" %
(self.name, class_name, val))
else:
if not (val is None and self.allow_None) and not (issubclass(val,self.class_)):
raise ValueError(
"Parameter '%s' must be a subclass of %s, not '%s'" %
(val.__name__, class_name, val.__class__.__name__)) | python | def _validate(self,val):
"""val must be None, an instance of self.class_ if self.is_instance=True or a subclass of self_class if self.is_instance=False"""
if isinstance(self.class_, tuple):
class_name = ('(%s)' % ', '.join(cl.__name__ for cl in self.class_))
else:
class_name = self.class_.__name__
if self.is_instance:
if not (isinstance(val,self.class_)) and not (val is None and self.allow_None):
raise ValueError(
"Parameter '%s' value must be an instance of %s, not '%s'" %
(self.name, class_name, val))
else:
if not (val is None and self.allow_None) and not (issubclass(val,self.class_)):
raise ValueError(
"Parameter '%s' must be a subclass of %s, not '%s'" %
(val.__name__, class_name, val.__class__.__name__)) | [
"def",
"_validate",
"(",
"self",
",",
"val",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"class_",
",",
"tuple",
")",
":",
"class_name",
"=",
"(",
"'(%s)'",
"%",
"', '",
".",
"join",
"(",
"cl",
".",
"__name__",
"for",
"cl",
"in",
"self",
".",
"class_",
")",
")",
"else",
":",
"class_name",
"=",
"self",
".",
"class_",
".",
"__name__",
"if",
"self",
".",
"is_instance",
":",
"if",
"not",
"(",
"isinstance",
"(",
"val",
",",
"self",
".",
"class_",
")",
")",
"and",
"not",
"(",
"val",
"is",
"None",
"and",
"self",
".",
"allow_None",
")",
":",
"raise",
"ValueError",
"(",
"\"Parameter '%s' value must be an instance of %s, not '%s'\"",
"%",
"(",
"self",
".",
"name",
",",
"class_name",
",",
"val",
")",
")",
"else",
":",
"if",
"not",
"(",
"val",
"is",
"None",
"and",
"self",
".",
"allow_None",
")",
"and",
"not",
"(",
"issubclass",
"(",
"val",
",",
"self",
".",
"class_",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"Parameter '%s' must be a subclass of %s, not '%s'\"",
"%",
"(",
"val",
".",
"__name__",
",",
"class_name",
",",
"val",
".",
"__class__",
".",
"__name__",
")",
")"
] | val must be None, an instance of self.class_ if self.is_instance=True or a subclass of self_class if self.is_instance=False | [
"val",
"must",
"be",
"None",
"an",
"instance",
"of",
"self",
".",
"class_",
"if",
"self",
".",
"is_instance",
"=",
"True",
"or",
"a",
"subclass",
"of",
"self_class",
"if",
"self",
".",
"is_instance",
"=",
"False"
] | 8f0dafa78defa883247b40635f96cc6d5c1b3481 | https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/__init__.py#L1303-L1318 | train |
pyviz/param | param/__init__.py | ClassSelector.get_range | def get_range(self):
"""
Return the possible types for this parameter's value.
(I.e. return {name: <class>} for all classes that are
concrete_descendents() of self.class_.)
Only classes from modules that have been imported are added
(see concrete_descendents()).
"""
classes = concrete_descendents(self.class_)
d=OrderedDict((name,class_) for name,class_ in classes.items())
if self.allow_None:
d['None']=None
return d | python | def get_range(self):
"""
Return the possible types for this parameter's value.
(I.e. return {name: <class>} for all classes that are
concrete_descendents() of self.class_.)
Only classes from modules that have been imported are added
(see concrete_descendents()).
"""
classes = concrete_descendents(self.class_)
d=OrderedDict((name,class_) for name,class_ in classes.items())
if self.allow_None:
d['None']=None
return d | [
"def",
"get_range",
"(",
"self",
")",
":",
"classes",
"=",
"concrete_descendents",
"(",
"self",
".",
"class_",
")",
"d",
"=",
"OrderedDict",
"(",
"(",
"name",
",",
"class_",
")",
"for",
"name",
",",
"class_",
"in",
"classes",
".",
"items",
"(",
")",
")",
"if",
"self",
".",
"allow_None",
":",
"d",
"[",
"'None'",
"]",
"=",
"None",
"return",
"d"
] | Return the possible types for this parameter's value.
(I.e. return {name: <class>} for all classes that are
concrete_descendents() of self.class_.)
Only classes from modules that have been imported are added
(see concrete_descendents()). | [
"Return",
"the",
"possible",
"types",
"for",
"this",
"parameter",
"s",
"value",
"."
] | 8f0dafa78defa883247b40635f96cc6d5c1b3481 | https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/__init__.py#L1321-L1335 | train |
pyviz/param | param/__init__.py | List._validate | def _validate(self, val):
"""
Checks that the list is of the right length and has the right contents.
Otherwise, an exception is raised.
"""
if self.allow_None and val is None:
return
if not isinstance(val, list):
raise ValueError("List '%s' must be a list."%(self.name))
if self.bounds is not None:
min_length,max_length = self.bounds
l=len(val)
if min_length is not None and max_length is not None:
if not (min_length <= l <= max_length):
raise ValueError("%s: list length must be between %s and %s (inclusive)"%(self.name,min_length,max_length))
elif min_length is not None:
if not min_length <= l:
raise ValueError("%s: list length must be at least %s."%(self.name,min_length))
elif max_length is not None:
if not l <= max_length:
raise ValueError("%s: list length must be at most %s."%(self.name,max_length))
self._check_type(val) | python | def _validate(self, val):
"""
Checks that the list is of the right length and has the right contents.
Otherwise, an exception is raised.
"""
if self.allow_None and val is None:
return
if not isinstance(val, list):
raise ValueError("List '%s' must be a list."%(self.name))
if self.bounds is not None:
min_length,max_length = self.bounds
l=len(val)
if min_length is not None and max_length is not None:
if not (min_length <= l <= max_length):
raise ValueError("%s: list length must be between %s and %s (inclusive)"%(self.name,min_length,max_length))
elif min_length is not None:
if not min_length <= l:
raise ValueError("%s: list length must be at least %s."%(self.name,min_length))
elif max_length is not None:
if not l <= max_length:
raise ValueError("%s: list length must be at most %s."%(self.name,max_length))
self._check_type(val) | [
"def",
"_validate",
"(",
"self",
",",
"val",
")",
":",
"if",
"self",
".",
"allow_None",
"and",
"val",
"is",
"None",
":",
"return",
"if",
"not",
"isinstance",
"(",
"val",
",",
"list",
")",
":",
"raise",
"ValueError",
"(",
"\"List '%s' must be a list.\"",
"%",
"(",
"self",
".",
"name",
")",
")",
"if",
"self",
".",
"bounds",
"is",
"not",
"None",
":",
"min_length",
",",
"max_length",
"=",
"self",
".",
"bounds",
"l",
"=",
"len",
"(",
"val",
")",
"if",
"min_length",
"is",
"not",
"None",
"and",
"max_length",
"is",
"not",
"None",
":",
"if",
"not",
"(",
"min_length",
"<=",
"l",
"<=",
"max_length",
")",
":",
"raise",
"ValueError",
"(",
"\"%s: list length must be between %s and %s (inclusive)\"",
"%",
"(",
"self",
".",
"name",
",",
"min_length",
",",
"max_length",
")",
")",
"elif",
"min_length",
"is",
"not",
"None",
":",
"if",
"not",
"min_length",
"<=",
"l",
":",
"raise",
"ValueError",
"(",
"\"%s: list length must be at least %s.\"",
"%",
"(",
"self",
".",
"name",
",",
"min_length",
")",
")",
"elif",
"max_length",
"is",
"not",
"None",
":",
"if",
"not",
"l",
"<=",
"max_length",
":",
"raise",
"ValueError",
"(",
"\"%s: list length must be at most %s.\"",
"%",
"(",
"self",
".",
"name",
",",
"max_length",
")",
")",
"self",
".",
"_check_type",
"(",
"val",
")"
] | Checks that the list is of the right length and has the right contents.
Otherwise, an exception is raised. | [
"Checks",
"that",
"the",
"list",
"is",
"of",
"the",
"right",
"length",
"and",
"has",
"the",
"right",
"contents",
".",
"Otherwise",
"an",
"exception",
"is",
"raised",
"."
] | 8f0dafa78defa883247b40635f96cc6d5c1b3481 | https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/__init__.py#L1357-L1381 | train |
pyviz/param | param/parameterized.py | logging_level | def logging_level(level):
"""
Temporarily modify param's logging level.
"""
level = level.upper()
levels = [DEBUG, INFO, WARNING, ERROR, CRITICAL, VERBOSE]
level_names = ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL', 'VERBOSE']
if level not in level_names:
raise Exception("Level %r not in %r" % (level, levels))
param_logger = get_logger()
logging_level = param_logger.getEffectiveLevel()
param_logger.setLevel(levels[level_names.index(level)])
try:
yield None
finally:
param_logger.setLevel(logging_level) | python | def logging_level(level):
"""
Temporarily modify param's logging level.
"""
level = level.upper()
levels = [DEBUG, INFO, WARNING, ERROR, CRITICAL, VERBOSE]
level_names = ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL', 'VERBOSE']
if level not in level_names:
raise Exception("Level %r not in %r" % (level, levels))
param_logger = get_logger()
logging_level = param_logger.getEffectiveLevel()
param_logger.setLevel(levels[level_names.index(level)])
try:
yield None
finally:
param_logger.setLevel(logging_level) | [
"def",
"logging_level",
"(",
"level",
")",
":",
"level",
"=",
"level",
".",
"upper",
"(",
")",
"levels",
"=",
"[",
"DEBUG",
",",
"INFO",
",",
"WARNING",
",",
"ERROR",
",",
"CRITICAL",
",",
"VERBOSE",
"]",
"level_names",
"=",
"[",
"'DEBUG'",
",",
"'INFO'",
",",
"'WARNING'",
",",
"'ERROR'",
",",
"'CRITICAL'",
",",
"'VERBOSE'",
"]",
"if",
"level",
"not",
"in",
"level_names",
":",
"raise",
"Exception",
"(",
"\"Level %r not in %r\"",
"%",
"(",
"level",
",",
"levels",
")",
")",
"param_logger",
"=",
"get_logger",
"(",
")",
"logging_level",
"=",
"param_logger",
".",
"getEffectiveLevel",
"(",
")",
"param_logger",
".",
"setLevel",
"(",
"levels",
"[",
"level_names",
".",
"index",
"(",
"level",
")",
"]",
")",
"try",
":",
"yield",
"None",
"finally",
":",
"param_logger",
".",
"setLevel",
"(",
"logging_level",
")"
] | Temporarily modify param's logging level. | [
"Temporarily",
"modify",
"param",
"s",
"logging",
"level",
"."
] | 8f0dafa78defa883247b40635f96cc6d5c1b3481 | https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/parameterized.py#L69-L86 | train |
pyviz/param | param/parameterized.py | batch_watch | def batch_watch(parameterized, run=True):
"""
Context manager to batch watcher events on a parameterized object.
The context manager will queue any events triggered by setting a
parameter on the supplied parameterized object and dispatch them
all at once when the context manager exits. If run=False the
queued events are not dispatched and should be processed manually.
"""
BATCH_WATCH = parameterized.param._BATCH_WATCH
parameterized.param._BATCH_WATCH = True
try:
yield
finally:
parameterized.param._BATCH_WATCH = BATCH_WATCH
if run and not BATCH_WATCH:
parameterized.param._batch_call_watchers() | python | def batch_watch(parameterized, run=True):
"""
Context manager to batch watcher events on a parameterized object.
The context manager will queue any events triggered by setting a
parameter on the supplied parameterized object and dispatch them
all at once when the context manager exits. If run=False the
queued events are not dispatched and should be processed manually.
"""
BATCH_WATCH = parameterized.param._BATCH_WATCH
parameterized.param._BATCH_WATCH = True
try:
yield
finally:
parameterized.param._BATCH_WATCH = BATCH_WATCH
if run and not BATCH_WATCH:
parameterized.param._batch_call_watchers() | [
"def",
"batch_watch",
"(",
"parameterized",
",",
"run",
"=",
"True",
")",
":",
"BATCH_WATCH",
"=",
"parameterized",
".",
"param",
".",
"_BATCH_WATCH",
"parameterized",
".",
"param",
".",
"_BATCH_WATCH",
"=",
"True",
"try",
":",
"yield",
"finally",
":",
"parameterized",
".",
"param",
".",
"_BATCH_WATCH",
"=",
"BATCH_WATCH",
"if",
"run",
"and",
"not",
"BATCH_WATCH",
":",
"parameterized",
".",
"param",
".",
"_batch_call_watchers",
"(",
")"
] | Context manager to batch watcher events on a parameterized object.
The context manager will queue any events triggered by setting a
parameter on the supplied parameterized object and dispatch them
all at once when the context manager exits. If run=False the
queued events are not dispatched and should be processed manually. | [
"Context",
"manager",
"to",
"batch",
"watcher",
"events",
"on",
"a",
"parameterized",
"object",
".",
"The",
"context",
"manager",
"will",
"queue",
"any",
"events",
"triggered",
"by",
"setting",
"a",
"parameter",
"on",
"the",
"supplied",
"parameterized",
"object",
"and",
"dispatch",
"them",
"all",
"at",
"once",
"when",
"the",
"context",
"manager",
"exits",
".",
"If",
"run",
"=",
"False",
"the",
"queued",
"events",
"are",
"not",
"dispatched",
"and",
"should",
"be",
"processed",
"manually",
"."
] | 8f0dafa78defa883247b40635f96cc6d5c1b3481 | https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/parameterized.py#L90-L105 | train |
pyviz/param | param/parameterized.py | get_all_slots | def get_all_slots(class_):
"""
Return a list of slot names for slots defined in class_ and its
superclasses.
"""
# A subclass's __slots__ attribute does not contain slots defined
# in its superclass (the superclass' __slots__ end up as
# attributes of the subclass).
all_slots = []
parent_param_classes = [c for c in classlist(class_)[1::]]
for c in parent_param_classes:
if hasattr(c,'__slots__'):
all_slots+=c.__slots__
return all_slots | python | def get_all_slots(class_):
"""
Return a list of slot names for slots defined in class_ and its
superclasses.
"""
# A subclass's __slots__ attribute does not contain slots defined
# in its superclass (the superclass' __slots__ end up as
# attributes of the subclass).
all_slots = []
parent_param_classes = [c for c in classlist(class_)[1::]]
for c in parent_param_classes:
if hasattr(c,'__slots__'):
all_slots+=c.__slots__
return all_slots | [
"def",
"get_all_slots",
"(",
"class_",
")",
":",
"# A subclass's __slots__ attribute does not contain slots defined",
"# in its superclass (the superclass' __slots__ end up as",
"# attributes of the subclass).",
"all_slots",
"=",
"[",
"]",
"parent_param_classes",
"=",
"[",
"c",
"for",
"c",
"in",
"classlist",
"(",
"class_",
")",
"[",
"1",
":",
":",
"]",
"]",
"for",
"c",
"in",
"parent_param_classes",
":",
"if",
"hasattr",
"(",
"c",
",",
"'__slots__'",
")",
":",
"all_slots",
"+=",
"c",
".",
"__slots__",
"return",
"all_slots"
] | Return a list of slot names for slots defined in class_ and its
superclasses. | [
"Return",
"a",
"list",
"of",
"slot",
"names",
"for",
"slots",
"defined",
"in",
"class_",
"and",
"its",
"superclasses",
"."
] | 8f0dafa78defa883247b40635f96cc6d5c1b3481 | https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/parameterized.py#L136-L149 | train |
pyviz/param | param/parameterized.py | get_occupied_slots | def get_occupied_slots(instance):
"""
Return a list of slots for which values have been set.
(While a slot might be defined, if a value for that slot hasn't
been set, then it's an AttributeError to request the slot's
value.)
"""
return [slot for slot in get_all_slots(type(instance))
if hasattr(instance,slot)] | python | def get_occupied_slots(instance):
"""
Return a list of slots for which values have been set.
(While a slot might be defined, if a value for that slot hasn't
been set, then it's an AttributeError to request the slot's
value.)
"""
return [slot for slot in get_all_slots(type(instance))
if hasattr(instance,slot)] | [
"def",
"get_occupied_slots",
"(",
"instance",
")",
":",
"return",
"[",
"slot",
"for",
"slot",
"in",
"get_all_slots",
"(",
"type",
"(",
"instance",
")",
")",
"if",
"hasattr",
"(",
"instance",
",",
"slot",
")",
"]"
] | Return a list of slots for which values have been set.
(While a slot might be defined, if a value for that slot hasn't
been set, then it's an AttributeError to request the slot's
value.) | [
"Return",
"a",
"list",
"of",
"slots",
"for",
"which",
"values",
"have",
"been",
"set",
"."
] | 8f0dafa78defa883247b40635f96cc6d5c1b3481 | https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/parameterized.py#L152-L161 | train |
pyviz/param | param/parameterized.py | all_equal | def all_equal(arg1,arg2):
"""
Return a single boolean for arg1==arg2, even for numpy arrays
using element-wise comparison.
Uses all(arg1==arg2) for sequences, and arg1==arg2 otherwise.
If both objects have an '_infinitely_iterable' attribute, they are
not be zipped together and are compared directly instead.
"""
if all(hasattr(el, '_infinitely_iterable') for el in [arg1,arg2]):
return arg1==arg2
try:
return all(a1 == a2 for a1, a2 in zip(arg1, arg2))
except TypeError:
return arg1==arg2 | python | def all_equal(arg1,arg2):
"""
Return a single boolean for arg1==arg2, even for numpy arrays
using element-wise comparison.
Uses all(arg1==arg2) for sequences, and arg1==arg2 otherwise.
If both objects have an '_infinitely_iterable' attribute, they are
not be zipped together and are compared directly instead.
"""
if all(hasattr(el, '_infinitely_iterable') for el in [arg1,arg2]):
return arg1==arg2
try:
return all(a1 == a2 for a1, a2 in zip(arg1, arg2))
except TypeError:
return arg1==arg2 | [
"def",
"all_equal",
"(",
"arg1",
",",
"arg2",
")",
":",
"if",
"all",
"(",
"hasattr",
"(",
"el",
",",
"'_infinitely_iterable'",
")",
"for",
"el",
"in",
"[",
"arg1",
",",
"arg2",
"]",
")",
":",
"return",
"arg1",
"==",
"arg2",
"try",
":",
"return",
"all",
"(",
"a1",
"==",
"a2",
"for",
"a1",
",",
"a2",
"in",
"zip",
"(",
"arg1",
",",
"arg2",
")",
")",
"except",
"TypeError",
":",
"return",
"arg1",
"==",
"arg2"
] | Return a single boolean for arg1==arg2, even for numpy arrays
using element-wise comparison.
Uses all(arg1==arg2) for sequences, and arg1==arg2 otherwise.
If both objects have an '_infinitely_iterable' attribute, they are
not be zipped together and are compared directly instead. | [
"Return",
"a",
"single",
"boolean",
"for",
"arg1",
"==",
"arg2",
"even",
"for",
"numpy",
"arrays",
"using",
"element",
"-",
"wise",
"comparison",
"."
] | 8f0dafa78defa883247b40635f96cc6d5c1b3481 | https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/parameterized.py#L164-L179 | train |
pyviz/param | param/parameterized.py | output | def output(func, *output, **kw):
"""
output allows annotating a method on a Parameterized class to
declare that it returns an output of a specific type. The outputs
of a Parameterized class can be queried using the
Parameterized.param.outputs method. By default the output will
inherit the method name but a custom name can be declared by
expressing the Parameter type using a keyword argument. Declaring
multiple return types using keywords is only supported in Python >= 3.6.
The simplest declaration simply declares the method returns an
object without any type guarantees, e.g.:
@output()
If a specific parameter type is specified this is a declaration
that the method will return a value of that type, e.g.:
@output(param.Number())
To override the default name of the output the type may be declared
as a keyword argument, e.g.:
@output(custom_name=param.Number())
Multiple outputs may be declared using keywords mapping from
output name to the type for Python >= 3.6 or using tuples of the
same format, which is supported for earlier versions, i.e. these
two declarations are equivalent:
@output(number=param.Number(), string=param.String())
@output(('number', param.Number()), ('string', param.String()))
output also accepts Python object types which will be upgraded to
a ClassSelector, e.g.:
@output(int)
"""
if output:
outputs = []
for i, out in enumerate(output):
i = i if len(output) > 1 else None
if isinstance(out, tuple) and len(out) == 2 and isinstance(out[0], str):
outputs.append(out+(i,))
elif isinstance(out, str):
outputs.append((out, Parameter(), i))
else:
outputs.append((None, out, i))
elif kw:
py_major = sys.version_info.major
py_minor = sys.version_info.minor
if (py_major < 3 or (py_major == 3 and py_minor < 6)) and len(kw) > 1:
raise ValueError('Multiple output declaration using keywords '
'only supported in Python >= 3.6.')
# (requires keywords to be kept ordered, which was not true in previous versions)
outputs = [(name, otype, i if len(kw) > 1 else None)
for i, (name, otype) in enumerate(kw.items())]
else:
outputs = [(None, Parameter(), None)]
names, processed = [], []
for name, otype, i in outputs:
if isinstance(otype, type):
if issubclass(otype, Parameter):
otype = otype()
else:
from .import ClassSelector
otype = ClassSelector(class_=otype)
elif isinstance(otype, tuple) and all(isinstance(t, type) for t in otype):
from .import ClassSelector
otype = ClassSelector(class_=otype)
if not isinstance(otype, Parameter):
raise ValueError('output type must be declared with a Parameter class, '
'instance or a Python object type.')
processed.append((name, otype, i))
names.append(name)
if len(set(names)) != len(names):
raise ValueError('When declaring multiple outputs each value '
'must be unique.')
_dinfo = getattr(func, '_dinfo', {})
_dinfo.update({'outputs': processed})
@wraps(func)
def _output(*args,**kw):
return func(*args,**kw)
_output._dinfo = _dinfo
return _output | python | def output(func, *output, **kw):
"""
output allows annotating a method on a Parameterized class to
declare that it returns an output of a specific type. The outputs
of a Parameterized class can be queried using the
Parameterized.param.outputs method. By default the output will
inherit the method name but a custom name can be declared by
expressing the Parameter type using a keyword argument. Declaring
multiple return types using keywords is only supported in Python >= 3.6.
The simplest declaration simply declares the method returns an
object without any type guarantees, e.g.:
@output()
If a specific parameter type is specified this is a declaration
that the method will return a value of that type, e.g.:
@output(param.Number())
To override the default name of the output the type may be declared
as a keyword argument, e.g.:
@output(custom_name=param.Number())
Multiple outputs may be declared using keywords mapping from
output name to the type for Python >= 3.6 or using tuples of the
same format, which is supported for earlier versions, i.e. these
two declarations are equivalent:
@output(number=param.Number(), string=param.String())
@output(('number', param.Number()), ('string', param.String()))
output also accepts Python object types which will be upgraded to
a ClassSelector, e.g.:
@output(int)
"""
if output:
outputs = []
for i, out in enumerate(output):
i = i if len(output) > 1 else None
if isinstance(out, tuple) and len(out) == 2 and isinstance(out[0], str):
outputs.append(out+(i,))
elif isinstance(out, str):
outputs.append((out, Parameter(), i))
else:
outputs.append((None, out, i))
elif kw:
py_major = sys.version_info.major
py_minor = sys.version_info.minor
if (py_major < 3 or (py_major == 3 and py_minor < 6)) and len(kw) > 1:
raise ValueError('Multiple output declaration using keywords '
'only supported in Python >= 3.6.')
# (requires keywords to be kept ordered, which was not true in previous versions)
outputs = [(name, otype, i if len(kw) > 1 else None)
for i, (name, otype) in enumerate(kw.items())]
else:
outputs = [(None, Parameter(), None)]
names, processed = [], []
for name, otype, i in outputs:
if isinstance(otype, type):
if issubclass(otype, Parameter):
otype = otype()
else:
from .import ClassSelector
otype = ClassSelector(class_=otype)
elif isinstance(otype, tuple) and all(isinstance(t, type) for t in otype):
from .import ClassSelector
otype = ClassSelector(class_=otype)
if not isinstance(otype, Parameter):
raise ValueError('output type must be declared with a Parameter class, '
'instance or a Python object type.')
processed.append((name, otype, i))
names.append(name)
if len(set(names)) != len(names):
raise ValueError('When declaring multiple outputs each value '
'must be unique.')
_dinfo = getattr(func, '_dinfo', {})
_dinfo.update({'outputs': processed})
@wraps(func)
def _output(*args,**kw):
return func(*args,**kw)
_output._dinfo = _dinfo
return _output | [
"def",
"output",
"(",
"func",
",",
"*",
"output",
",",
"*",
"*",
"kw",
")",
":",
"if",
"output",
":",
"outputs",
"=",
"[",
"]",
"for",
"i",
",",
"out",
"in",
"enumerate",
"(",
"output",
")",
":",
"i",
"=",
"i",
"if",
"len",
"(",
"output",
")",
">",
"1",
"else",
"None",
"if",
"isinstance",
"(",
"out",
",",
"tuple",
")",
"and",
"len",
"(",
"out",
")",
"==",
"2",
"and",
"isinstance",
"(",
"out",
"[",
"0",
"]",
",",
"str",
")",
":",
"outputs",
".",
"append",
"(",
"out",
"+",
"(",
"i",
",",
")",
")",
"elif",
"isinstance",
"(",
"out",
",",
"str",
")",
":",
"outputs",
".",
"append",
"(",
"(",
"out",
",",
"Parameter",
"(",
")",
",",
"i",
")",
")",
"else",
":",
"outputs",
".",
"append",
"(",
"(",
"None",
",",
"out",
",",
"i",
")",
")",
"elif",
"kw",
":",
"py_major",
"=",
"sys",
".",
"version_info",
".",
"major",
"py_minor",
"=",
"sys",
".",
"version_info",
".",
"minor",
"if",
"(",
"py_major",
"<",
"3",
"or",
"(",
"py_major",
"==",
"3",
"and",
"py_minor",
"<",
"6",
")",
")",
"and",
"len",
"(",
"kw",
")",
">",
"1",
":",
"raise",
"ValueError",
"(",
"'Multiple output declaration using keywords '",
"'only supported in Python >= 3.6.'",
")",
"# (requires keywords to be kept ordered, which was not true in previous versions)",
"outputs",
"=",
"[",
"(",
"name",
",",
"otype",
",",
"i",
"if",
"len",
"(",
"kw",
")",
">",
"1",
"else",
"None",
")",
"for",
"i",
",",
"(",
"name",
",",
"otype",
")",
"in",
"enumerate",
"(",
"kw",
".",
"items",
"(",
")",
")",
"]",
"else",
":",
"outputs",
"=",
"[",
"(",
"None",
",",
"Parameter",
"(",
")",
",",
"None",
")",
"]",
"names",
",",
"processed",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"name",
",",
"otype",
",",
"i",
"in",
"outputs",
":",
"if",
"isinstance",
"(",
"otype",
",",
"type",
")",
":",
"if",
"issubclass",
"(",
"otype",
",",
"Parameter",
")",
":",
"otype",
"=",
"otype",
"(",
")",
"else",
":",
"from",
".",
"import",
"ClassSelector",
"otype",
"=",
"ClassSelector",
"(",
"class_",
"=",
"otype",
")",
"elif",
"isinstance",
"(",
"otype",
",",
"tuple",
")",
"and",
"all",
"(",
"isinstance",
"(",
"t",
",",
"type",
")",
"for",
"t",
"in",
"otype",
")",
":",
"from",
".",
"import",
"ClassSelector",
"otype",
"=",
"ClassSelector",
"(",
"class_",
"=",
"otype",
")",
"if",
"not",
"isinstance",
"(",
"otype",
",",
"Parameter",
")",
":",
"raise",
"ValueError",
"(",
"'output type must be declared with a Parameter class, '",
"'instance or a Python object type.'",
")",
"processed",
".",
"append",
"(",
"(",
"name",
",",
"otype",
",",
"i",
")",
")",
"names",
".",
"append",
"(",
"name",
")",
"if",
"len",
"(",
"set",
"(",
"names",
")",
")",
"!=",
"len",
"(",
"names",
")",
":",
"raise",
"ValueError",
"(",
"'When declaring multiple outputs each value '",
"'must be unique.'",
")",
"_dinfo",
"=",
"getattr",
"(",
"func",
",",
"'_dinfo'",
",",
"{",
"}",
")",
"_dinfo",
".",
"update",
"(",
"{",
"'outputs'",
":",
"processed",
"}",
")",
"@",
"wraps",
"(",
"func",
")",
"def",
"_output",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
"_output",
".",
"_dinfo",
"=",
"_dinfo",
"return",
"_output"
] | output allows annotating a method on a Parameterized class to
declare that it returns an output of a specific type. The outputs
of a Parameterized class can be queried using the
Parameterized.param.outputs method. By default the output will
inherit the method name but a custom name can be declared by
expressing the Parameter type using a keyword argument. Declaring
multiple return types using keywords is only supported in Python >= 3.6.
The simplest declaration simply declares the method returns an
object without any type guarantees, e.g.:
@output()
If a specific parameter type is specified this is a declaration
that the method will return a value of that type, e.g.:
@output(param.Number())
To override the default name of the output the type may be declared
as a keyword argument, e.g.:
@output(custom_name=param.Number())
Multiple outputs may be declared using keywords mapping from
output name to the type for Python >= 3.6 or using tuples of the
same format, which is supported for earlier versions, i.e. these
two declarations are equivalent:
@output(number=param.Number(), string=param.String())
@output(('number', param.Number()), ('string', param.String()))
output also accepts Python object types which will be upgraded to
a ClassSelector, e.g.:
@output(int) | [
"output",
"allows",
"annotating",
"a",
"method",
"on",
"a",
"Parameterized",
"class",
"to",
"declare",
"that",
"it",
"returns",
"an",
"output",
"of",
"a",
"specific",
"type",
".",
"The",
"outputs",
"of",
"a",
"Parameterized",
"class",
"can",
"be",
"queried",
"using",
"the",
"Parameterized",
".",
"param",
".",
"outputs",
"method",
".",
"By",
"default",
"the",
"output",
"will",
"inherit",
"the",
"method",
"name",
"but",
"a",
"custom",
"name",
"can",
"be",
"declared",
"by",
"expressing",
"the",
"Parameter",
"type",
"using",
"a",
"keyword",
"argument",
".",
"Declaring",
"multiple",
"return",
"types",
"using",
"keywords",
"is",
"only",
"supported",
"in",
"Python",
">",
"=",
"3",
".",
"6",
"."
] | 8f0dafa78defa883247b40635f96cc6d5c1b3481 | https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/parameterized.py#L293-L384 | train |
pyviz/param | param/parameterized.py | Parameters._setup_params | def _setup_params(self_,**params):
"""
Initialize default and keyword parameter values.
First, ensures that all Parameters with 'instantiate=True'
(typically used for mutable Parameters) are copied directly
into each object, to ensure that there is an independent copy
(to avoid suprising aliasing errors). Then sets each of the
keyword arguments, warning when any of them are not defined as
parameters.
Constant Parameters can be set during calls to this method.
"""
self = self_.param.self
## Deepcopy all 'instantiate=True' parameters
# (build a set of names first to avoid redundantly instantiating
# a later-overridden parent class's parameter)
params_to_instantiate = {}
for class_ in classlist(type(self)):
if not issubclass(class_, Parameterized):
continue
for (k,v) in class_.__dict__.items():
# (avoid replacing name with the default of None)
if isinstance(v,Parameter) and v.instantiate and k!="name":
params_to_instantiate[k]=v
for p in params_to_instantiate.values():
self.param._instantiate_param(p)
## keyword arg setting
for name,val in params.items():
desc = self.__class__.get_param_descriptor(name)[0] # pylint: disable-msg=E1101
if not desc:
self.param.warning("Setting non-parameter attribute %s=%s using a mechanism intended only for parameters",name,val)
# i.e. if not desc it's setting an attribute in __dict__, not a Parameter
setattr(self,name,val) | python | def _setup_params(self_,**params):
"""
Initialize default and keyword parameter values.
First, ensures that all Parameters with 'instantiate=True'
(typically used for mutable Parameters) are copied directly
into each object, to ensure that there is an independent copy
(to avoid suprising aliasing errors). Then sets each of the
keyword arguments, warning when any of them are not defined as
parameters.
Constant Parameters can be set during calls to this method.
"""
self = self_.param.self
## Deepcopy all 'instantiate=True' parameters
# (build a set of names first to avoid redundantly instantiating
# a later-overridden parent class's parameter)
params_to_instantiate = {}
for class_ in classlist(type(self)):
if not issubclass(class_, Parameterized):
continue
for (k,v) in class_.__dict__.items():
# (avoid replacing name with the default of None)
if isinstance(v,Parameter) and v.instantiate and k!="name":
params_to_instantiate[k]=v
for p in params_to_instantiate.values():
self.param._instantiate_param(p)
## keyword arg setting
for name,val in params.items():
desc = self.__class__.get_param_descriptor(name)[0] # pylint: disable-msg=E1101
if not desc:
self.param.warning("Setting non-parameter attribute %s=%s using a mechanism intended only for parameters",name,val)
# i.e. if not desc it's setting an attribute in __dict__, not a Parameter
setattr(self,name,val) | [
"def",
"_setup_params",
"(",
"self_",
",",
"*",
"*",
"params",
")",
":",
"self",
"=",
"self_",
".",
"param",
".",
"self",
"## Deepcopy all 'instantiate=True' parameters",
"# (build a set of names first to avoid redundantly instantiating",
"# a later-overridden parent class's parameter)",
"params_to_instantiate",
"=",
"{",
"}",
"for",
"class_",
"in",
"classlist",
"(",
"type",
"(",
"self",
")",
")",
":",
"if",
"not",
"issubclass",
"(",
"class_",
",",
"Parameterized",
")",
":",
"continue",
"for",
"(",
"k",
",",
"v",
")",
"in",
"class_",
".",
"__dict__",
".",
"items",
"(",
")",
":",
"# (avoid replacing name with the default of None)",
"if",
"isinstance",
"(",
"v",
",",
"Parameter",
")",
"and",
"v",
".",
"instantiate",
"and",
"k",
"!=",
"\"name\"",
":",
"params_to_instantiate",
"[",
"k",
"]",
"=",
"v",
"for",
"p",
"in",
"params_to_instantiate",
".",
"values",
"(",
")",
":",
"self",
".",
"param",
".",
"_instantiate_param",
"(",
"p",
")",
"## keyword arg setting",
"for",
"name",
",",
"val",
"in",
"params",
".",
"items",
"(",
")",
":",
"desc",
"=",
"self",
".",
"__class__",
".",
"get_param_descriptor",
"(",
"name",
")",
"[",
"0",
"]",
"# pylint: disable-msg=E1101",
"if",
"not",
"desc",
":",
"self",
".",
"param",
".",
"warning",
"(",
"\"Setting non-parameter attribute %s=%s using a mechanism intended only for parameters\"",
",",
"name",
",",
"val",
")",
"# i.e. if not desc it's setting an attribute in __dict__, not a Parameter",
"setattr",
"(",
"self",
",",
"name",
",",
"val",
")"
] | Initialize default and keyword parameter values.
First, ensures that all Parameters with 'instantiate=True'
(typically used for mutable Parameters) are copied directly
into each object, to ensure that there is an independent copy
(to avoid suprising aliasing errors). Then sets each of the
keyword arguments, warning when any of them are not defined as
parameters.
Constant Parameters can be set during calls to this method. | [
"Initialize",
"default",
"and",
"keyword",
"parameter",
"values",
"."
] | 8f0dafa78defa883247b40635f96cc6d5c1b3481 | https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/parameterized.py#L1094-L1129 | train |
pyviz/param | param/parameterized.py | Parameters.deprecate | def deprecate(cls, fn):
"""
Decorator to issue warnings for API moving onto the param
namespace and to add a docstring directing people to the
appropriate method.
"""
def inner(*args, **kwargs):
if cls._disable_stubs:
raise AssertionError('Stubs supporting old API disabled')
elif cls._disable_stubs is None:
pass
elif cls._disable_stubs is False:
get_logger(name=args[0].__class__.__name__).log(
WARNING, 'Use method %r via param namespace ' % fn.__name__)
return fn(*args, **kwargs)
inner.__doc__= "Inspect .param.%s method for the full docstring" % fn.__name__
return inner | python | def deprecate(cls, fn):
"""
Decorator to issue warnings for API moving onto the param
namespace and to add a docstring directing people to the
appropriate method.
"""
def inner(*args, **kwargs):
if cls._disable_stubs:
raise AssertionError('Stubs supporting old API disabled')
elif cls._disable_stubs is None:
pass
elif cls._disable_stubs is False:
get_logger(name=args[0].__class__.__name__).log(
WARNING, 'Use method %r via param namespace ' % fn.__name__)
return fn(*args, **kwargs)
inner.__doc__= "Inspect .param.%s method for the full docstring" % fn.__name__
return inner | [
"def",
"deprecate",
"(",
"cls",
",",
"fn",
")",
":",
"def",
"inner",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"cls",
".",
"_disable_stubs",
":",
"raise",
"AssertionError",
"(",
"'Stubs supporting old API disabled'",
")",
"elif",
"cls",
".",
"_disable_stubs",
"is",
"None",
":",
"pass",
"elif",
"cls",
".",
"_disable_stubs",
"is",
"False",
":",
"get_logger",
"(",
"name",
"=",
"args",
"[",
"0",
"]",
".",
"__class__",
".",
"__name__",
")",
".",
"log",
"(",
"WARNING",
",",
"'Use method %r via param namespace '",
"%",
"fn",
".",
"__name__",
")",
"return",
"fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"inner",
".",
"__doc__",
"=",
"\"Inspect .param.%s method for the full docstring\"",
"%",
"fn",
".",
"__name__",
"return",
"inner"
] | Decorator to issue warnings for API moving onto the param
namespace and to add a docstring directing people to the
appropriate method. | [
"Decorator",
"to",
"issue",
"warnings",
"for",
"API",
"moving",
"onto",
"the",
"param",
"namespace",
"and",
"to",
"add",
"a",
"docstring",
"directing",
"people",
"to",
"the",
"appropriate",
"method",
"."
] | 8f0dafa78defa883247b40635f96cc6d5c1b3481 | https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/parameterized.py#L1132-L1149 | train |
pyviz/param | param/parameterized.py | Parameters.print_param_defaults | def print_param_defaults(self_):
"""Print the default values of all cls's Parameters."""
cls = self_.cls
for key,val in cls.__dict__.items():
if isinstance(val,Parameter):
print(cls.__name__+'.'+key+ '='+ repr(val.default)) | python | def print_param_defaults(self_):
"""Print the default values of all cls's Parameters."""
cls = self_.cls
for key,val in cls.__dict__.items():
if isinstance(val,Parameter):
print(cls.__name__+'.'+key+ '='+ repr(val.default)) | [
"def",
"print_param_defaults",
"(",
"self_",
")",
":",
"cls",
"=",
"self_",
".",
"cls",
"for",
"key",
",",
"val",
"in",
"cls",
".",
"__dict__",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"val",
",",
"Parameter",
")",
":",
"print",
"(",
"cls",
".",
"__name__",
"+",
"'.'",
"+",
"key",
"+",
"'='",
"+",
"repr",
"(",
"val",
".",
"default",
")",
")"
] | Print the default values of all cls's Parameters. | [
"Print",
"the",
"default",
"values",
"of",
"all",
"cls",
"s",
"Parameters",
"."
] | 8f0dafa78defa883247b40635f96cc6d5c1b3481 | https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/parameterized.py#L1188-L1193 | train |
pyviz/param | param/parameterized.py | Parameters.set_default | def set_default(self_,param_name,value):
"""
Set the default value of param_name.
Equivalent to setting param_name on the class.
"""
cls = self_.cls
setattr(cls,param_name,value) | python | def set_default(self_,param_name,value):
"""
Set the default value of param_name.
Equivalent to setting param_name on the class.
"""
cls = self_.cls
setattr(cls,param_name,value) | [
"def",
"set_default",
"(",
"self_",
",",
"param_name",
",",
"value",
")",
":",
"cls",
"=",
"self_",
".",
"cls",
"setattr",
"(",
"cls",
",",
"param_name",
",",
"value",
")"
] | Set the default value of param_name.
Equivalent to setting param_name on the class. | [
"Set",
"the",
"default",
"value",
"of",
"param_name",
"."
] | 8f0dafa78defa883247b40635f96cc6d5c1b3481 | https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/parameterized.py#L1196-L1203 | train |
pyviz/param | param/parameterized.py | Parameters._add_parameter | def _add_parameter(self_, param_name,param_obj):
"""
Add a new Parameter object into this object's class.
Supposed to result in a Parameter equivalent to one declared
in the class's source code.
"""
# CEBALERT: can't we just do
# setattr(cls,param_name,param_obj)? The metaclass's
# __setattr__ is actually written to handle that. (Would also
# need to do something about the params() cache. That cache
# is a pain, but it definitely improved the startup time; it
# would be worthwhile making sure no method except for one
# "add_param()" method has to deal with it (plus any future
# remove_param() method.)
cls = self_.cls
type.__setattr__(cls,param_name,param_obj)
ParameterizedMetaclass._initialize_parameter(cls,param_name,param_obj)
# delete cached params()
try:
delattr(cls,'_%s__params'%cls.__name__)
except AttributeError:
pass | python | def _add_parameter(self_, param_name,param_obj):
"""
Add a new Parameter object into this object's class.
Supposed to result in a Parameter equivalent to one declared
in the class's source code.
"""
# CEBALERT: can't we just do
# setattr(cls,param_name,param_obj)? The metaclass's
# __setattr__ is actually written to handle that. (Would also
# need to do something about the params() cache. That cache
# is a pain, but it definitely improved the startup time; it
# would be worthwhile making sure no method except for one
# "add_param()" method has to deal with it (plus any future
# remove_param() method.)
cls = self_.cls
type.__setattr__(cls,param_name,param_obj)
ParameterizedMetaclass._initialize_parameter(cls,param_name,param_obj)
# delete cached params()
try:
delattr(cls,'_%s__params'%cls.__name__)
except AttributeError:
pass | [
"def",
"_add_parameter",
"(",
"self_",
",",
"param_name",
",",
"param_obj",
")",
":",
"# CEBALERT: can't we just do",
"# setattr(cls,param_name,param_obj)? The metaclass's",
"# __setattr__ is actually written to handle that. (Would also",
"# need to do something about the params() cache. That cache",
"# is a pain, but it definitely improved the startup time; it",
"# would be worthwhile making sure no method except for one",
"# \"add_param()\" method has to deal with it (plus any future",
"# remove_param() method.)",
"cls",
"=",
"self_",
".",
"cls",
"type",
".",
"__setattr__",
"(",
"cls",
",",
"param_name",
",",
"param_obj",
")",
"ParameterizedMetaclass",
".",
"_initialize_parameter",
"(",
"cls",
",",
"param_name",
",",
"param_obj",
")",
"# delete cached params()",
"try",
":",
"delattr",
"(",
"cls",
",",
"'_%s__params'",
"%",
"cls",
".",
"__name__",
")",
"except",
"AttributeError",
":",
"pass"
] | Add a new Parameter object into this object's class.
Supposed to result in a Parameter equivalent to one declared
in the class's source code. | [
"Add",
"a",
"new",
"Parameter",
"object",
"into",
"this",
"object",
"s",
"class",
"."
] | 8f0dafa78defa883247b40635f96cc6d5c1b3481 | https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/parameterized.py#L1206-L1228 | train |
pyviz/param | param/parameterized.py | Parameters.set_param | def set_param(self_, *args,**kwargs):
"""
For each param=value keyword argument, sets the corresponding
parameter of this object or class to the given value.
For backwards compatibility, also accepts
set_param("param",value) for a single parameter value using
positional arguments, but the keyword interface is preferred
because it is more compact and can set multiple values.
"""
BATCH_WATCH = self_.self_or_cls.param._BATCH_WATCH
self_.self_or_cls.param._BATCH_WATCH = True
self_or_cls = self_.self_or_cls
if args:
if len(args) == 2 and not args[0] in kwargs and not kwargs:
kwargs[args[0]] = args[1]
else:
self_.self_or_cls.param._BATCH_WATCH = False
raise ValueError("Invalid positional arguments for %s.set_param" %
(self_or_cls.name))
for (k, v) in kwargs.items():
if k not in self_or_cls.param:
self_.self_or_cls.param._BATCH_WATCH = False
raise ValueError("'%s' is not a parameter of %s" % (k, self_or_cls.name))
try:
setattr(self_or_cls, k, v)
except:
self_.self_or_cls.param._BATCH_WATCH = False
raise
self_.self_or_cls.param._BATCH_WATCH = BATCH_WATCH
if not BATCH_WATCH:
self_._batch_call_watchers() | python | def set_param(self_, *args,**kwargs):
"""
For each param=value keyword argument, sets the corresponding
parameter of this object or class to the given value.
For backwards compatibility, also accepts
set_param("param",value) for a single parameter value using
positional arguments, but the keyword interface is preferred
because it is more compact and can set multiple values.
"""
BATCH_WATCH = self_.self_or_cls.param._BATCH_WATCH
self_.self_or_cls.param._BATCH_WATCH = True
self_or_cls = self_.self_or_cls
if args:
if len(args) == 2 and not args[0] in kwargs and not kwargs:
kwargs[args[0]] = args[1]
else:
self_.self_or_cls.param._BATCH_WATCH = False
raise ValueError("Invalid positional arguments for %s.set_param" %
(self_or_cls.name))
for (k, v) in kwargs.items():
if k not in self_or_cls.param:
self_.self_or_cls.param._BATCH_WATCH = False
raise ValueError("'%s' is not a parameter of %s" % (k, self_or_cls.name))
try:
setattr(self_or_cls, k, v)
except:
self_.self_or_cls.param._BATCH_WATCH = False
raise
self_.self_or_cls.param._BATCH_WATCH = BATCH_WATCH
if not BATCH_WATCH:
self_._batch_call_watchers() | [
"def",
"set_param",
"(",
"self_",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"BATCH_WATCH",
"=",
"self_",
".",
"self_or_cls",
".",
"param",
".",
"_BATCH_WATCH",
"self_",
".",
"self_or_cls",
".",
"param",
".",
"_BATCH_WATCH",
"=",
"True",
"self_or_cls",
"=",
"self_",
".",
"self_or_cls",
"if",
"args",
":",
"if",
"len",
"(",
"args",
")",
"==",
"2",
"and",
"not",
"args",
"[",
"0",
"]",
"in",
"kwargs",
"and",
"not",
"kwargs",
":",
"kwargs",
"[",
"args",
"[",
"0",
"]",
"]",
"=",
"args",
"[",
"1",
"]",
"else",
":",
"self_",
".",
"self_or_cls",
".",
"param",
".",
"_BATCH_WATCH",
"=",
"False",
"raise",
"ValueError",
"(",
"\"Invalid positional arguments for %s.set_param\"",
"%",
"(",
"self_or_cls",
".",
"name",
")",
")",
"for",
"(",
"k",
",",
"v",
")",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"k",
"not",
"in",
"self_or_cls",
".",
"param",
":",
"self_",
".",
"self_or_cls",
".",
"param",
".",
"_BATCH_WATCH",
"=",
"False",
"raise",
"ValueError",
"(",
"\"'%s' is not a parameter of %s\"",
"%",
"(",
"k",
",",
"self_or_cls",
".",
"name",
")",
")",
"try",
":",
"setattr",
"(",
"self_or_cls",
",",
"k",
",",
"v",
")",
"except",
":",
"self_",
".",
"self_or_cls",
".",
"param",
".",
"_BATCH_WATCH",
"=",
"False",
"raise",
"self_",
".",
"self_or_cls",
".",
"param",
".",
"_BATCH_WATCH",
"=",
"BATCH_WATCH",
"if",
"not",
"BATCH_WATCH",
":",
"self_",
".",
"_batch_call_watchers",
"(",
")"
] | For each param=value keyword argument, sets the corresponding
parameter of this object or class to the given value.
For backwards compatibility, also accepts
set_param("param",value) for a single parameter value using
positional arguments, but the keyword interface is preferred
because it is more compact and can set multiple values. | [
"For",
"each",
"param",
"=",
"value",
"keyword",
"argument",
"sets",
"the",
"corresponding",
"parameter",
"of",
"this",
"object",
"or",
"class",
"to",
"the",
"given",
"value",
"."
] | 8f0dafa78defa883247b40635f96cc6d5c1b3481 | https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/parameterized.py#L1259-L1292 | train |
pyviz/param | param/parameterized.py | Parameters.objects | def objects(self_, instance=True):
"""
Returns the Parameters of this instance or class
If instance=True and called on a Parameterized instance it
will create instance parameters for all Parameters defined on
the class. To force class parameters to be returned use
instance=False. Since classes avoid creating instance
parameters unless necessary you may also request only existing
instance parameters to be returned by setting
instance='existing'.
"""
cls = self_.cls
# CB: we cache the parameters because this method is called often,
# and parameters are rarely added (and cannot be deleted)
try:
pdict = getattr(cls, '_%s__params' % cls.__name__)
except AttributeError:
paramdict = {}
for class_ in classlist(cls):
for name, val in class_.__dict__.items():
if isinstance(val, Parameter):
paramdict[name] = val
# We only want the cache to be visible to the cls on which
# params() is called, so we mangle the name ourselves at
# runtime (if we were to mangle it now, it would be
# _Parameterized.__params for all classes).
setattr(cls, '_%s__params' % cls.__name__, paramdict)
pdict = paramdict
if instance and self_.self is not None:
if instance == 'existing':
if self_.self._instance__params:
return dict(pdict, **self_.self._instance__params)
return pdict
else:
return {k: self_.self.param[k] for k in pdict}
return pdict | python | def objects(self_, instance=True):
"""
Returns the Parameters of this instance or class
If instance=True and called on a Parameterized instance it
will create instance parameters for all Parameters defined on
the class. To force class parameters to be returned use
instance=False. Since classes avoid creating instance
parameters unless necessary you may also request only existing
instance parameters to be returned by setting
instance='existing'.
"""
cls = self_.cls
# CB: we cache the parameters because this method is called often,
# and parameters are rarely added (and cannot be deleted)
try:
pdict = getattr(cls, '_%s__params' % cls.__name__)
except AttributeError:
paramdict = {}
for class_ in classlist(cls):
for name, val in class_.__dict__.items():
if isinstance(val, Parameter):
paramdict[name] = val
# We only want the cache to be visible to the cls on which
# params() is called, so we mangle the name ourselves at
# runtime (if we were to mangle it now, it would be
# _Parameterized.__params for all classes).
setattr(cls, '_%s__params' % cls.__name__, paramdict)
pdict = paramdict
if instance and self_.self is not None:
if instance == 'existing':
if self_.self._instance__params:
return dict(pdict, **self_.self._instance__params)
return pdict
else:
return {k: self_.self.param[k] for k in pdict}
return pdict | [
"def",
"objects",
"(",
"self_",
",",
"instance",
"=",
"True",
")",
":",
"cls",
"=",
"self_",
".",
"cls",
"# CB: we cache the parameters because this method is called often,",
"# and parameters are rarely added (and cannot be deleted)",
"try",
":",
"pdict",
"=",
"getattr",
"(",
"cls",
",",
"'_%s__params'",
"%",
"cls",
".",
"__name__",
")",
"except",
"AttributeError",
":",
"paramdict",
"=",
"{",
"}",
"for",
"class_",
"in",
"classlist",
"(",
"cls",
")",
":",
"for",
"name",
",",
"val",
"in",
"class_",
".",
"__dict__",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"val",
",",
"Parameter",
")",
":",
"paramdict",
"[",
"name",
"]",
"=",
"val",
"# We only want the cache to be visible to the cls on which",
"# params() is called, so we mangle the name ourselves at",
"# runtime (if we were to mangle it now, it would be",
"# _Parameterized.__params for all classes).",
"setattr",
"(",
"cls",
",",
"'_%s__params'",
"%",
"cls",
".",
"__name__",
",",
"paramdict",
")",
"pdict",
"=",
"paramdict",
"if",
"instance",
"and",
"self_",
".",
"self",
"is",
"not",
"None",
":",
"if",
"instance",
"==",
"'existing'",
":",
"if",
"self_",
".",
"self",
".",
"_instance__params",
":",
"return",
"dict",
"(",
"pdict",
",",
"*",
"*",
"self_",
".",
"self",
".",
"_instance__params",
")",
"return",
"pdict",
"else",
":",
"return",
"{",
"k",
":",
"self_",
".",
"self",
".",
"param",
"[",
"k",
"]",
"for",
"k",
"in",
"pdict",
"}",
"return",
"pdict"
] | Returns the Parameters of this instance or class
If instance=True and called on a Parameterized instance it
will create instance parameters for all Parameters defined on
the class. To force class parameters to be returned use
instance=False. Since classes avoid creating instance
parameters unless necessary you may also request only existing
instance parameters to be returned by setting
instance='existing'. | [
"Returns",
"the",
"Parameters",
"of",
"this",
"instance",
"or",
"class"
] | 8f0dafa78defa883247b40635f96cc6d5c1b3481 | https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/parameterized.py#L1295-L1333 | train |
pyviz/param | param/parameterized.py | Parameters.trigger | def trigger(self_, *param_names):
"""
Trigger watchers for the given set of parameter names. Watchers
will be triggered whether or not the parameter values have
actually changed.
"""
events = self_.self_or_cls.param._events
watchers = self_.self_or_cls.param._watchers
self_.self_or_cls.param._events = []
self_.self_or_cls.param._watchers = []
param_values = dict(self_.get_param_values())
params = {name: param_values[name] for name in param_names}
self_.self_or_cls.param._TRIGGER = True
self_.set_param(**params)
self_.self_or_cls.param._TRIGGER = False
self_.self_or_cls.param._events = events
self_.self_or_cls.param._watchers = watchers | python | def trigger(self_, *param_names):
"""
Trigger watchers for the given set of parameter names. Watchers
will be triggered whether or not the parameter values have
actually changed.
"""
events = self_.self_or_cls.param._events
watchers = self_.self_or_cls.param._watchers
self_.self_or_cls.param._events = []
self_.self_or_cls.param._watchers = []
param_values = dict(self_.get_param_values())
params = {name: param_values[name] for name in param_names}
self_.self_or_cls.param._TRIGGER = True
self_.set_param(**params)
self_.self_or_cls.param._TRIGGER = False
self_.self_or_cls.param._events = events
self_.self_or_cls.param._watchers = watchers | [
"def",
"trigger",
"(",
"self_",
",",
"*",
"param_names",
")",
":",
"events",
"=",
"self_",
".",
"self_or_cls",
".",
"param",
".",
"_events",
"watchers",
"=",
"self_",
".",
"self_or_cls",
".",
"param",
".",
"_watchers",
"self_",
".",
"self_or_cls",
".",
"param",
".",
"_events",
"=",
"[",
"]",
"self_",
".",
"self_or_cls",
".",
"param",
".",
"_watchers",
"=",
"[",
"]",
"param_values",
"=",
"dict",
"(",
"self_",
".",
"get_param_values",
"(",
")",
")",
"params",
"=",
"{",
"name",
":",
"param_values",
"[",
"name",
"]",
"for",
"name",
"in",
"param_names",
"}",
"self_",
".",
"self_or_cls",
".",
"param",
".",
"_TRIGGER",
"=",
"True",
"self_",
".",
"set_param",
"(",
"*",
"*",
"params",
")",
"self_",
".",
"self_or_cls",
".",
"param",
".",
"_TRIGGER",
"=",
"False",
"self_",
".",
"self_or_cls",
".",
"param",
".",
"_events",
"=",
"events",
"self_",
".",
"self_or_cls",
".",
"param",
".",
"_watchers",
"=",
"watchers"
] | Trigger watchers for the given set of parameter names. Watchers
will be triggered whether or not the parameter values have
actually changed. | [
"Trigger",
"watchers",
"for",
"the",
"given",
"set",
"of",
"parameter",
"names",
".",
"Watchers",
"will",
"be",
"triggered",
"whether",
"or",
"not",
"the",
"parameter",
"values",
"have",
"actually",
"changed",
"."
] | 8f0dafa78defa883247b40635f96cc6d5c1b3481 | https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/parameterized.py#L1336-L1352 | train |
pyviz/param | param/parameterized.py | Parameters._update_event_type | def _update_event_type(self_, watcher, event, triggered):
"""
Returns an updated Event object with the type field set appropriately.
"""
if triggered:
event_type = 'triggered'
else:
event_type = 'changed' if watcher.onlychanged else 'set'
return Event(what=event.what, name=event.name, obj=event.obj, cls=event.cls,
old=event.old, new=event.new, type=event_type) | python | def _update_event_type(self_, watcher, event, triggered):
"""
Returns an updated Event object with the type field set appropriately.
"""
if triggered:
event_type = 'triggered'
else:
event_type = 'changed' if watcher.onlychanged else 'set'
return Event(what=event.what, name=event.name, obj=event.obj, cls=event.cls,
old=event.old, new=event.new, type=event_type) | [
"def",
"_update_event_type",
"(",
"self_",
",",
"watcher",
",",
"event",
",",
"triggered",
")",
":",
"if",
"triggered",
":",
"event_type",
"=",
"'triggered'",
"else",
":",
"event_type",
"=",
"'changed'",
"if",
"watcher",
".",
"onlychanged",
"else",
"'set'",
"return",
"Event",
"(",
"what",
"=",
"event",
".",
"what",
",",
"name",
"=",
"event",
".",
"name",
",",
"obj",
"=",
"event",
".",
"obj",
",",
"cls",
"=",
"event",
".",
"cls",
",",
"old",
"=",
"event",
".",
"old",
",",
"new",
"=",
"event",
".",
"new",
",",
"type",
"=",
"event_type",
")"
] | Returns an updated Event object with the type field set appropriately. | [
"Returns",
"an",
"updated",
"Event",
"object",
"with",
"the",
"type",
"field",
"set",
"appropriately",
"."
] | 8f0dafa78defa883247b40635f96cc6d5c1b3481 | https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/parameterized.py#L1355-L1364 | train |
pyviz/param | param/parameterized.py | Parameters._call_watcher | def _call_watcher(self_, watcher, event):
"""
Invoke the given the watcher appropriately given a Event object.
"""
if self_.self_or_cls.param._TRIGGER:
pass
elif watcher.onlychanged and (not self_._changed(event)):
return
if self_.self_or_cls.param._BATCH_WATCH:
self_._events.append(event)
if watcher not in self_._watchers:
self_._watchers.append(watcher)
elif watcher.mode == 'args':
with batch_watch(self_.self_or_cls, run=False):
watcher.fn(self_._update_event_type(watcher, event, self_.self_or_cls.param._TRIGGER))
else:
with batch_watch(self_.self_or_cls, run=False):
event = self_._update_event_type(watcher, event, self_.self_or_cls.param._TRIGGER)
watcher.fn(**{event.name: event.new}) | python | def _call_watcher(self_, watcher, event):
"""
Invoke the given the watcher appropriately given a Event object.
"""
if self_.self_or_cls.param._TRIGGER:
pass
elif watcher.onlychanged and (not self_._changed(event)):
return
if self_.self_or_cls.param._BATCH_WATCH:
self_._events.append(event)
if watcher not in self_._watchers:
self_._watchers.append(watcher)
elif watcher.mode == 'args':
with batch_watch(self_.self_or_cls, run=False):
watcher.fn(self_._update_event_type(watcher, event, self_.self_or_cls.param._TRIGGER))
else:
with batch_watch(self_.self_or_cls, run=False):
event = self_._update_event_type(watcher, event, self_.self_or_cls.param._TRIGGER)
watcher.fn(**{event.name: event.new}) | [
"def",
"_call_watcher",
"(",
"self_",
",",
"watcher",
",",
"event",
")",
":",
"if",
"self_",
".",
"self_or_cls",
".",
"param",
".",
"_TRIGGER",
":",
"pass",
"elif",
"watcher",
".",
"onlychanged",
"and",
"(",
"not",
"self_",
".",
"_changed",
"(",
"event",
")",
")",
":",
"return",
"if",
"self_",
".",
"self_or_cls",
".",
"param",
".",
"_BATCH_WATCH",
":",
"self_",
".",
"_events",
".",
"append",
"(",
"event",
")",
"if",
"watcher",
"not",
"in",
"self_",
".",
"_watchers",
":",
"self_",
".",
"_watchers",
".",
"append",
"(",
"watcher",
")",
"elif",
"watcher",
".",
"mode",
"==",
"'args'",
":",
"with",
"batch_watch",
"(",
"self_",
".",
"self_or_cls",
",",
"run",
"=",
"False",
")",
":",
"watcher",
".",
"fn",
"(",
"self_",
".",
"_update_event_type",
"(",
"watcher",
",",
"event",
",",
"self_",
".",
"self_or_cls",
".",
"param",
".",
"_TRIGGER",
")",
")",
"else",
":",
"with",
"batch_watch",
"(",
"self_",
".",
"self_or_cls",
",",
"run",
"=",
"False",
")",
":",
"event",
"=",
"self_",
".",
"_update_event_type",
"(",
"watcher",
",",
"event",
",",
"self_",
".",
"self_or_cls",
".",
"param",
".",
"_TRIGGER",
")",
"watcher",
".",
"fn",
"(",
"*",
"*",
"{",
"event",
".",
"name",
":",
"event",
".",
"new",
"}",
")"
] | Invoke the given the watcher appropriately given a Event object. | [
"Invoke",
"the",
"given",
"the",
"watcher",
"appropriately",
"given",
"a",
"Event",
"object",
"."
] | 8f0dafa78defa883247b40635f96cc6d5c1b3481 | https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/parameterized.py#L1366-L1385 | train |
pyviz/param | param/parameterized.py | Parameters._batch_call_watchers | def _batch_call_watchers(self_):
"""
Batch call a set of watchers based on the parameter value
settings in kwargs using the queued Event and watcher objects.
"""
while self_.self_or_cls.param._events:
event_dict = OrderedDict([((event.name, event.what), event)
for event in self_.self_or_cls.param._events])
watchers = self_.self_or_cls.param._watchers[:]
self_.self_or_cls.param._events = []
self_.self_or_cls.param._watchers = []
for watcher in watchers:
events = [self_._update_event_type(watcher, event_dict[(name, watcher.what)],
self_.self_or_cls.param._TRIGGER)
for name in watcher.parameter_names
if (name, watcher.what) in event_dict]
with batch_watch(self_.self_or_cls, run=False):
if watcher.mode == 'args':
watcher.fn(*events)
else:
watcher.fn(**{c.name:c.new for c in events}) | python | def _batch_call_watchers(self_):
"""
Batch call a set of watchers based on the parameter value
settings in kwargs using the queued Event and watcher objects.
"""
while self_.self_or_cls.param._events:
event_dict = OrderedDict([((event.name, event.what), event)
for event in self_.self_or_cls.param._events])
watchers = self_.self_or_cls.param._watchers[:]
self_.self_or_cls.param._events = []
self_.self_or_cls.param._watchers = []
for watcher in watchers:
events = [self_._update_event_type(watcher, event_dict[(name, watcher.what)],
self_.self_or_cls.param._TRIGGER)
for name in watcher.parameter_names
if (name, watcher.what) in event_dict]
with batch_watch(self_.self_or_cls, run=False):
if watcher.mode == 'args':
watcher.fn(*events)
else:
watcher.fn(**{c.name:c.new for c in events}) | [
"def",
"_batch_call_watchers",
"(",
"self_",
")",
":",
"while",
"self_",
".",
"self_or_cls",
".",
"param",
".",
"_events",
":",
"event_dict",
"=",
"OrderedDict",
"(",
"[",
"(",
"(",
"event",
".",
"name",
",",
"event",
".",
"what",
")",
",",
"event",
")",
"for",
"event",
"in",
"self_",
".",
"self_or_cls",
".",
"param",
".",
"_events",
"]",
")",
"watchers",
"=",
"self_",
".",
"self_or_cls",
".",
"param",
".",
"_watchers",
"[",
":",
"]",
"self_",
".",
"self_or_cls",
".",
"param",
".",
"_events",
"=",
"[",
"]",
"self_",
".",
"self_or_cls",
".",
"param",
".",
"_watchers",
"=",
"[",
"]",
"for",
"watcher",
"in",
"watchers",
":",
"events",
"=",
"[",
"self_",
".",
"_update_event_type",
"(",
"watcher",
",",
"event_dict",
"[",
"(",
"name",
",",
"watcher",
".",
"what",
")",
"]",
",",
"self_",
".",
"self_or_cls",
".",
"param",
".",
"_TRIGGER",
")",
"for",
"name",
"in",
"watcher",
".",
"parameter_names",
"if",
"(",
"name",
",",
"watcher",
".",
"what",
")",
"in",
"event_dict",
"]",
"with",
"batch_watch",
"(",
"self_",
".",
"self_or_cls",
",",
"run",
"=",
"False",
")",
":",
"if",
"watcher",
".",
"mode",
"==",
"'args'",
":",
"watcher",
".",
"fn",
"(",
"*",
"events",
")",
"else",
":",
"watcher",
".",
"fn",
"(",
"*",
"*",
"{",
"c",
".",
"name",
":",
"c",
".",
"new",
"for",
"c",
"in",
"events",
"}",
")"
] | Batch call a set of watchers based on the parameter value
settings in kwargs using the queued Event and watcher objects. | [
"Batch",
"call",
"a",
"set",
"of",
"watchers",
"based",
"on",
"the",
"parameter",
"value",
"settings",
"in",
"kwargs",
"using",
"the",
"queued",
"Event",
"and",
"watcher",
"objects",
"."
] | 8f0dafa78defa883247b40635f96cc6d5c1b3481 | https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/parameterized.py#L1388-L1409 | train |
pyviz/param | param/parameterized.py | Parameters.set_dynamic_time_fn | def set_dynamic_time_fn(self_,time_fn,sublistattr=None):
"""
Set time_fn for all Dynamic Parameters of this class or
instance object that are currently being dynamically
generated.
Additionally, sets _Dynamic_time_fn=time_fn on this class or
instance object, so that any future changes to Dynamic
Parmeters can inherit time_fn (e.g. if a Number is changed
from a float to a number generator, the number generator will
inherit time_fn).
If specified, sublistattr is the name of an attribute of this
class or instance that contains an iterable collection of
subobjects on which set_dynamic_time_fn should be called. If
the attribute sublistattr is present on any of the subobjects,
set_dynamic_time_fn() will be called for those, too.
"""
self_or_cls = self_.self_or_cls
self_or_cls._Dynamic_time_fn = time_fn
if isinstance(self_or_cls,type):
a = (None,self_or_cls)
else:
a = (self_or_cls,)
for n,p in self_or_cls.param.objects('existing').items():
if hasattr(p, '_value_is_dynamic'):
if p._value_is_dynamic(*a):
g = self_or_cls.param.get_value_generator(n)
g._Dynamic_time_fn = time_fn
if sublistattr:
try:
sublist = getattr(self_or_cls,sublistattr)
except AttributeError:
sublist = []
for obj in sublist:
obj.param.set_dynamic_time_fn(time_fn,sublistattr) | python | def set_dynamic_time_fn(self_,time_fn,sublistattr=None):
"""
Set time_fn for all Dynamic Parameters of this class or
instance object that are currently being dynamically
generated.
Additionally, sets _Dynamic_time_fn=time_fn on this class or
instance object, so that any future changes to Dynamic
Parmeters can inherit time_fn (e.g. if a Number is changed
from a float to a number generator, the number generator will
inherit time_fn).
If specified, sublistattr is the name of an attribute of this
class or instance that contains an iterable collection of
subobjects on which set_dynamic_time_fn should be called. If
the attribute sublistattr is present on any of the subobjects,
set_dynamic_time_fn() will be called for those, too.
"""
self_or_cls = self_.self_or_cls
self_or_cls._Dynamic_time_fn = time_fn
if isinstance(self_or_cls,type):
a = (None,self_or_cls)
else:
a = (self_or_cls,)
for n,p in self_or_cls.param.objects('existing').items():
if hasattr(p, '_value_is_dynamic'):
if p._value_is_dynamic(*a):
g = self_or_cls.param.get_value_generator(n)
g._Dynamic_time_fn = time_fn
if sublistattr:
try:
sublist = getattr(self_or_cls,sublistattr)
except AttributeError:
sublist = []
for obj in sublist:
obj.param.set_dynamic_time_fn(time_fn,sublistattr) | [
"def",
"set_dynamic_time_fn",
"(",
"self_",
",",
"time_fn",
",",
"sublistattr",
"=",
"None",
")",
":",
"self_or_cls",
"=",
"self_",
".",
"self_or_cls",
"self_or_cls",
".",
"_Dynamic_time_fn",
"=",
"time_fn",
"if",
"isinstance",
"(",
"self_or_cls",
",",
"type",
")",
":",
"a",
"=",
"(",
"None",
",",
"self_or_cls",
")",
"else",
":",
"a",
"=",
"(",
"self_or_cls",
",",
")",
"for",
"n",
",",
"p",
"in",
"self_or_cls",
".",
"param",
".",
"objects",
"(",
"'existing'",
")",
".",
"items",
"(",
")",
":",
"if",
"hasattr",
"(",
"p",
",",
"'_value_is_dynamic'",
")",
":",
"if",
"p",
".",
"_value_is_dynamic",
"(",
"*",
"a",
")",
":",
"g",
"=",
"self_or_cls",
".",
"param",
".",
"get_value_generator",
"(",
"n",
")",
"g",
".",
"_Dynamic_time_fn",
"=",
"time_fn",
"if",
"sublistattr",
":",
"try",
":",
"sublist",
"=",
"getattr",
"(",
"self_or_cls",
",",
"sublistattr",
")",
"except",
"AttributeError",
":",
"sublist",
"=",
"[",
"]",
"for",
"obj",
"in",
"sublist",
":",
"obj",
".",
"param",
".",
"set_dynamic_time_fn",
"(",
"time_fn",
",",
"sublistattr",
")"
] | Set time_fn for all Dynamic Parameters of this class or
instance object that are currently being dynamically
generated.
Additionally, sets _Dynamic_time_fn=time_fn on this class or
instance object, so that any future changes to Dynamic
Parmeters can inherit time_fn (e.g. if a Number is changed
from a float to a number generator, the number generator will
inherit time_fn).
If specified, sublistattr is the name of an attribute of this
class or instance that contains an iterable collection of
subobjects on which set_dynamic_time_fn should be called. If
the attribute sublistattr is present on any of the subobjects,
set_dynamic_time_fn() will be called for those, too. | [
"Set",
"time_fn",
"for",
"all",
"Dynamic",
"Parameters",
"of",
"this",
"class",
"or",
"instance",
"object",
"that",
"are",
"currently",
"being",
"dynamically",
"generated",
"."
] | 8f0dafa78defa883247b40635f96cc6d5c1b3481 | https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/parameterized.py#L1412-L1451 | train |
pyviz/param | param/parameterized.py | Parameters.get_param_values | def get_param_values(self_,onlychanged=False):
"""
Return a list of name,value pairs for all Parameters of this
object.
When called on an instance with onlychanged set to True, will
only return values that are not equal to the default value
(onlychanged has no effect when called on a class).
"""
self_or_cls = self_.self_or_cls
# CEB: we'd actually like to know whether a value has been
# explicitly set on the instance, but I'm not sure that's easy
# (would need to distinguish instantiation of default from
# user setting of value).
vals = []
for name,val in self_or_cls.param.objects('existing').items():
value = self_or_cls.param.get_value_generator(name)
# (this is pointless for cls)
if not onlychanged or not all_equal(value,val.default):
vals.append((name,value))
vals.sort(key=itemgetter(0))
return vals | python | def get_param_values(self_,onlychanged=False):
"""
Return a list of name,value pairs for all Parameters of this
object.
When called on an instance with onlychanged set to True, will
only return values that are not equal to the default value
(onlychanged has no effect when called on a class).
"""
self_or_cls = self_.self_or_cls
# CEB: we'd actually like to know whether a value has been
# explicitly set on the instance, but I'm not sure that's easy
# (would need to distinguish instantiation of default from
# user setting of value).
vals = []
for name,val in self_or_cls.param.objects('existing').items():
value = self_or_cls.param.get_value_generator(name)
# (this is pointless for cls)
if not onlychanged or not all_equal(value,val.default):
vals.append((name,value))
vals.sort(key=itemgetter(0))
return vals | [
"def",
"get_param_values",
"(",
"self_",
",",
"onlychanged",
"=",
"False",
")",
":",
"self_or_cls",
"=",
"self_",
".",
"self_or_cls",
"# CEB: we'd actually like to know whether a value has been",
"# explicitly set on the instance, but I'm not sure that's easy",
"# (would need to distinguish instantiation of default from",
"# user setting of value).",
"vals",
"=",
"[",
"]",
"for",
"name",
",",
"val",
"in",
"self_or_cls",
".",
"param",
".",
"objects",
"(",
"'existing'",
")",
".",
"items",
"(",
")",
":",
"value",
"=",
"self_or_cls",
".",
"param",
".",
"get_value_generator",
"(",
"name",
")",
"# (this is pointless for cls)",
"if",
"not",
"onlychanged",
"or",
"not",
"all_equal",
"(",
"value",
",",
"val",
".",
"default",
")",
":",
"vals",
".",
"append",
"(",
"(",
"name",
",",
"value",
")",
")",
"vals",
".",
"sort",
"(",
"key",
"=",
"itemgetter",
"(",
"0",
")",
")",
"return",
"vals"
] | Return a list of name,value pairs for all Parameters of this
object.
When called on an instance with onlychanged set to True, will
only return values that are not equal to the default value
(onlychanged has no effect when called on a class). | [
"Return",
"a",
"list",
"of",
"name",
"value",
"pairs",
"for",
"all",
"Parameters",
"of",
"this",
"object",
"."
] | 8f0dafa78defa883247b40635f96cc6d5c1b3481 | https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/parameterized.py#L1453-L1475 | train |
pyviz/param | param/parameterized.py | Parameters.force_new_dynamic_value | def force_new_dynamic_value(self_, name): # pylint: disable-msg=E0213
"""
Force a new value to be generated for the dynamic attribute
name, and return it.
If name is not dynamic, its current value is returned
(i.e. equivalent to getattr(name).
"""
cls_or_slf = self_.self_or_cls
param_obj = cls_or_slf.param.objects('existing').get(name)
if not param_obj:
return getattr(cls_or_slf, name)
cls, slf = None, None
if isinstance(cls_or_slf,type):
cls = cls_or_slf
else:
slf = cls_or_slf
if not hasattr(param_obj,'_force'):
return param_obj.__get__(slf, cls)
else:
return param_obj._force(slf, cls) | python | def force_new_dynamic_value(self_, name): # pylint: disable-msg=E0213
"""
Force a new value to be generated for the dynamic attribute
name, and return it.
If name is not dynamic, its current value is returned
(i.e. equivalent to getattr(name).
"""
cls_or_slf = self_.self_or_cls
param_obj = cls_or_slf.param.objects('existing').get(name)
if not param_obj:
return getattr(cls_or_slf, name)
cls, slf = None, None
if isinstance(cls_or_slf,type):
cls = cls_or_slf
else:
slf = cls_or_slf
if not hasattr(param_obj,'_force'):
return param_obj.__get__(slf, cls)
else:
return param_obj._force(slf, cls) | [
"def",
"force_new_dynamic_value",
"(",
"self_",
",",
"name",
")",
":",
"# pylint: disable-msg=E0213",
"cls_or_slf",
"=",
"self_",
".",
"self_or_cls",
"param_obj",
"=",
"cls_or_slf",
".",
"param",
".",
"objects",
"(",
"'existing'",
")",
".",
"get",
"(",
"name",
")",
"if",
"not",
"param_obj",
":",
"return",
"getattr",
"(",
"cls_or_slf",
",",
"name",
")",
"cls",
",",
"slf",
"=",
"None",
",",
"None",
"if",
"isinstance",
"(",
"cls_or_slf",
",",
"type",
")",
":",
"cls",
"=",
"cls_or_slf",
"else",
":",
"slf",
"=",
"cls_or_slf",
"if",
"not",
"hasattr",
"(",
"param_obj",
",",
"'_force'",
")",
":",
"return",
"param_obj",
".",
"__get__",
"(",
"slf",
",",
"cls",
")",
"else",
":",
"return",
"param_obj",
".",
"_force",
"(",
"slf",
",",
"cls",
")"
] | Force a new value to be generated for the dynamic attribute
name, and return it.
If name is not dynamic, its current value is returned
(i.e. equivalent to getattr(name). | [
"Force",
"a",
"new",
"value",
"to",
"be",
"generated",
"for",
"the",
"dynamic",
"attribute",
"name",
"and",
"return",
"it",
"."
] | 8f0dafa78defa883247b40635f96cc6d5c1b3481 | https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/parameterized.py#L1478-L1501 | train |
pyviz/param | param/parameterized.py | Parameters.get_value_generator | def get_value_generator(self_,name): # pylint: disable-msg=E0213
"""
Return the value or value-generating object of the named
attribute.
For most parameters, this is simply the parameter's value
(i.e. the same as getattr()), but Dynamic parameters have
their value-generating object returned.
"""
cls_or_slf = self_.self_or_cls
param_obj = cls_or_slf.param.objects('existing').get(name)
if not param_obj:
value = getattr(cls_or_slf,name)
# CompositeParameter detected by being a Parameter and having 'attribs'
elif hasattr(param_obj,'attribs'):
value = [cls_or_slf.param.get_value_generator(a) for a in param_obj.attribs]
# not a Dynamic Parameter
elif not hasattr(param_obj,'_value_is_dynamic'):
value = getattr(cls_or_slf,name)
# Dynamic Parameter...
else:
internal_name = "_%s_param_value"%name
if hasattr(cls_or_slf,internal_name):
# dealing with object and it's been set on this object
value = getattr(cls_or_slf,internal_name)
else:
# dealing with class or isn't set on the object
value = param_obj.default
return value | python | def get_value_generator(self_,name): # pylint: disable-msg=E0213
"""
Return the value or value-generating object of the named
attribute.
For most parameters, this is simply the parameter's value
(i.e. the same as getattr()), but Dynamic parameters have
their value-generating object returned.
"""
cls_or_slf = self_.self_or_cls
param_obj = cls_or_slf.param.objects('existing').get(name)
if not param_obj:
value = getattr(cls_or_slf,name)
# CompositeParameter detected by being a Parameter and having 'attribs'
elif hasattr(param_obj,'attribs'):
value = [cls_or_slf.param.get_value_generator(a) for a in param_obj.attribs]
# not a Dynamic Parameter
elif not hasattr(param_obj,'_value_is_dynamic'):
value = getattr(cls_or_slf,name)
# Dynamic Parameter...
else:
internal_name = "_%s_param_value"%name
if hasattr(cls_or_slf,internal_name):
# dealing with object and it's been set on this object
value = getattr(cls_or_slf,internal_name)
else:
# dealing with class or isn't set on the object
value = param_obj.default
return value | [
"def",
"get_value_generator",
"(",
"self_",
",",
"name",
")",
":",
"# pylint: disable-msg=E0213",
"cls_or_slf",
"=",
"self_",
".",
"self_or_cls",
"param_obj",
"=",
"cls_or_slf",
".",
"param",
".",
"objects",
"(",
"'existing'",
")",
".",
"get",
"(",
"name",
")",
"if",
"not",
"param_obj",
":",
"value",
"=",
"getattr",
"(",
"cls_or_slf",
",",
"name",
")",
"# CompositeParameter detected by being a Parameter and having 'attribs'",
"elif",
"hasattr",
"(",
"param_obj",
",",
"'attribs'",
")",
":",
"value",
"=",
"[",
"cls_or_slf",
".",
"param",
".",
"get_value_generator",
"(",
"a",
")",
"for",
"a",
"in",
"param_obj",
".",
"attribs",
"]",
"# not a Dynamic Parameter",
"elif",
"not",
"hasattr",
"(",
"param_obj",
",",
"'_value_is_dynamic'",
")",
":",
"value",
"=",
"getattr",
"(",
"cls_or_slf",
",",
"name",
")",
"# Dynamic Parameter...",
"else",
":",
"internal_name",
"=",
"\"_%s_param_value\"",
"%",
"name",
"if",
"hasattr",
"(",
"cls_or_slf",
",",
"internal_name",
")",
":",
"# dealing with object and it's been set on this object",
"value",
"=",
"getattr",
"(",
"cls_or_slf",
",",
"internal_name",
")",
"else",
":",
"# dealing with class or isn't set on the object",
"value",
"=",
"param_obj",
".",
"default",
"return",
"value"
] | Return the value or value-generating object of the named
attribute.
For most parameters, this is simply the parameter's value
(i.e. the same as getattr()), but Dynamic parameters have
their value-generating object returned. | [
"Return",
"the",
"value",
"or",
"value",
"-",
"generating",
"object",
"of",
"the",
"named",
"attribute",
"."
] | 8f0dafa78defa883247b40635f96cc6d5c1b3481 | https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/parameterized.py#L1504-L1537 | train |
pyviz/param | param/parameterized.py | Parameters.inspect_value | def inspect_value(self_,name): # pylint: disable-msg=E0213
"""
Return the current value of the named attribute without modifying it.
Same as getattr() except for Dynamic parameters, which have their
last generated value returned.
"""
cls_or_slf = self_.self_or_cls
param_obj = cls_or_slf.param.objects('existing').get(name)
if not param_obj:
value = getattr(cls_or_slf,name)
elif hasattr(param_obj,'attribs'):
value = [cls_or_slf.param.inspect_value(a) for a in param_obj.attribs]
elif not hasattr(param_obj,'_inspect'):
value = getattr(cls_or_slf,name)
else:
if isinstance(cls_or_slf,type):
value = param_obj._inspect(None,cls_or_slf)
else:
value = param_obj._inspect(cls_or_slf,None)
return value | python | def inspect_value(self_,name): # pylint: disable-msg=E0213
"""
Return the current value of the named attribute without modifying it.
Same as getattr() except for Dynamic parameters, which have their
last generated value returned.
"""
cls_or_slf = self_.self_or_cls
param_obj = cls_or_slf.param.objects('existing').get(name)
if not param_obj:
value = getattr(cls_or_slf,name)
elif hasattr(param_obj,'attribs'):
value = [cls_or_slf.param.inspect_value(a) for a in param_obj.attribs]
elif not hasattr(param_obj,'_inspect'):
value = getattr(cls_or_slf,name)
else:
if isinstance(cls_or_slf,type):
value = param_obj._inspect(None,cls_or_slf)
else:
value = param_obj._inspect(cls_or_slf,None)
return value | [
"def",
"inspect_value",
"(",
"self_",
",",
"name",
")",
":",
"# pylint: disable-msg=E0213",
"cls_or_slf",
"=",
"self_",
".",
"self_or_cls",
"param_obj",
"=",
"cls_or_slf",
".",
"param",
".",
"objects",
"(",
"'existing'",
")",
".",
"get",
"(",
"name",
")",
"if",
"not",
"param_obj",
":",
"value",
"=",
"getattr",
"(",
"cls_or_slf",
",",
"name",
")",
"elif",
"hasattr",
"(",
"param_obj",
",",
"'attribs'",
")",
":",
"value",
"=",
"[",
"cls_or_slf",
".",
"param",
".",
"inspect_value",
"(",
"a",
")",
"for",
"a",
"in",
"param_obj",
".",
"attribs",
"]",
"elif",
"not",
"hasattr",
"(",
"param_obj",
",",
"'_inspect'",
")",
":",
"value",
"=",
"getattr",
"(",
"cls_or_slf",
",",
"name",
")",
"else",
":",
"if",
"isinstance",
"(",
"cls_or_slf",
",",
"type",
")",
":",
"value",
"=",
"param_obj",
".",
"_inspect",
"(",
"None",
",",
"cls_or_slf",
")",
"else",
":",
"value",
"=",
"param_obj",
".",
"_inspect",
"(",
"cls_or_slf",
",",
"None",
")",
"return",
"value"
] | Return the current value of the named attribute without modifying it.
Same as getattr() except for Dynamic parameters, which have their
last generated value returned. | [
"Return",
"the",
"current",
"value",
"of",
"the",
"named",
"attribute",
"without",
"modifying",
"it",
"."
] | 8f0dafa78defa883247b40635f96cc6d5c1b3481 | https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/parameterized.py#L1539-L1561 | train |
pyviz/param | param/parameterized.py | Parameters.outputs | def outputs(self_):
"""
Returns a mapping between any declared outputs and a tuple
of the declared Parameter type, the output method, and the
index into the output if multiple outputs are returned.
"""
outputs = {}
for cls in classlist(self_.cls):
for name in dir(cls):
method = getattr(self_.self_or_cls, name)
dinfo = getattr(method, '_dinfo', {})
if 'outputs' not in dinfo:
continue
for override, otype, idx in dinfo['outputs']:
if override is not None:
name = override
outputs[name] = (otype, method, idx)
return outputs | python | def outputs(self_):
"""
Returns a mapping between any declared outputs and a tuple
of the declared Parameter type, the output method, and the
index into the output if multiple outputs are returned.
"""
outputs = {}
for cls in classlist(self_.cls):
for name in dir(cls):
method = getattr(self_.self_or_cls, name)
dinfo = getattr(method, '_dinfo', {})
if 'outputs' not in dinfo:
continue
for override, otype, idx in dinfo['outputs']:
if override is not None:
name = override
outputs[name] = (otype, method, idx)
return outputs | [
"def",
"outputs",
"(",
"self_",
")",
":",
"outputs",
"=",
"{",
"}",
"for",
"cls",
"in",
"classlist",
"(",
"self_",
".",
"cls",
")",
":",
"for",
"name",
"in",
"dir",
"(",
"cls",
")",
":",
"method",
"=",
"getattr",
"(",
"self_",
".",
"self_or_cls",
",",
"name",
")",
"dinfo",
"=",
"getattr",
"(",
"method",
",",
"'_dinfo'",
",",
"{",
"}",
")",
"if",
"'outputs'",
"not",
"in",
"dinfo",
":",
"continue",
"for",
"override",
",",
"otype",
",",
"idx",
"in",
"dinfo",
"[",
"'outputs'",
"]",
":",
"if",
"override",
"is",
"not",
"None",
":",
"name",
"=",
"override",
"outputs",
"[",
"name",
"]",
"=",
"(",
"otype",
",",
"method",
",",
"idx",
")",
"return",
"outputs"
] | Returns a mapping between any declared outputs and a tuple
of the declared Parameter type, the output method, and the
index into the output if multiple outputs are returned. | [
"Returns",
"a",
"mapping",
"between",
"any",
"declared",
"outputs",
"and",
"a",
"tuple",
"of",
"the",
"declared",
"Parameter",
"type",
"the",
"output",
"method",
"and",
"the",
"index",
"into",
"the",
"output",
"if",
"multiple",
"outputs",
"are",
"returned",
"."
] | 8f0dafa78defa883247b40635f96cc6d5c1b3481 | https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/parameterized.py#L1568-L1585 | train |
pyviz/param | param/parameterized.py | Parameters.unwatch | def unwatch(self_,watcher):
"""
Unwatch watchers set either with watch or watch_values.
"""
try:
self_._watch('remove',watcher)
except:
self_.warning('No such watcher {watcher} to remove.'.format(watcher=watcher)) | python | def unwatch(self_,watcher):
"""
Unwatch watchers set either with watch or watch_values.
"""
try:
self_._watch('remove',watcher)
except:
self_.warning('No such watcher {watcher} to remove.'.format(watcher=watcher)) | [
"def",
"unwatch",
"(",
"self_",
",",
"watcher",
")",
":",
"try",
":",
"self_",
".",
"_watch",
"(",
"'remove'",
",",
"watcher",
")",
"except",
":",
"self_",
".",
"warning",
"(",
"'No such watcher {watcher} to remove.'",
".",
"format",
"(",
"watcher",
"=",
"watcher",
")",
")"
] | Unwatch watchers set either with watch or watch_values. | [
"Unwatch",
"watchers",
"set",
"either",
"with",
"watch",
"or",
"watch_values",
"."
] | 8f0dafa78defa883247b40635f96cc6d5c1b3481 | https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/parameterized.py#L1645-L1652 | train |
pyviz/param | param/parameterized.py | Parameters.print_param_values | def print_param_values(self_):
"""Print the values of all this object's Parameters."""
self = self_.self
for name,val in self.param.get_param_values():
print('%s.%s = %s' % (self.name,name,val)) | python | def print_param_values(self_):
"""Print the values of all this object's Parameters."""
self = self_.self
for name,val in self.param.get_param_values():
print('%s.%s = %s' % (self.name,name,val)) | [
"def",
"print_param_values",
"(",
"self_",
")",
":",
"self",
"=",
"self_",
".",
"self",
"for",
"name",
",",
"val",
"in",
"self",
".",
"param",
".",
"get_param_values",
"(",
")",
":",
"print",
"(",
"'%s.%s = %s'",
"%",
"(",
"self",
".",
"name",
",",
"name",
",",
"val",
")",
")"
] | Print the values of all this object's Parameters. | [
"Print",
"the",
"values",
"of",
"all",
"this",
"object",
"s",
"Parameters",
"."
] | 8f0dafa78defa883247b40635f96cc6d5c1b3481 | https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/parameterized.py#L1706-L1710 | train |
pyviz/param | param/parameterized.py | Parameters.warning | def warning(self_, msg,*args,**kw):
"""
Print msg merged with args as a warning, unless module variable
warnings_as_exceptions is True, then raise an Exception
containing the arguments.
See Python's logging module for details of message formatting.
"""
if not warnings_as_exceptions:
global warning_count
warning_count+=1
self_.__db_print(WARNING,msg,*args,**kw)
else:
raise Exception("Warning: " + msg % args) | python | def warning(self_, msg,*args,**kw):
"""
Print msg merged with args as a warning, unless module variable
warnings_as_exceptions is True, then raise an Exception
containing the arguments.
See Python's logging module for details of message formatting.
"""
if not warnings_as_exceptions:
global warning_count
warning_count+=1
self_.__db_print(WARNING,msg,*args,**kw)
else:
raise Exception("Warning: " + msg % args) | [
"def",
"warning",
"(",
"self_",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"if",
"not",
"warnings_as_exceptions",
":",
"global",
"warning_count",
"warning_count",
"+=",
"1",
"self_",
".",
"__db_print",
"(",
"WARNING",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"Warning: \"",
"+",
"msg",
"%",
"args",
")"
] | Print msg merged with args as a warning, unless module variable
warnings_as_exceptions is True, then raise an Exception
containing the arguments.
See Python's logging module for details of message formatting. | [
"Print",
"msg",
"merged",
"with",
"args",
"as",
"a",
"warning",
"unless",
"module",
"variable",
"warnings_as_exceptions",
"is",
"True",
"then",
"raise",
"an",
"Exception",
"containing",
"the",
"arguments",
"."
] | 8f0dafa78defa883247b40635f96cc6d5c1b3481 | https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/parameterized.py#L1712-L1725 | train |
pyviz/param | param/parameterized.py | Parameters.message | def message(self_,msg,*args,**kw):
"""
Print msg merged with args as a message.
See Python's logging module for details of message formatting.
"""
self_.__db_print(INFO,msg,*args,**kw) | python | def message(self_,msg,*args,**kw):
"""
Print msg merged with args as a message.
See Python's logging module for details of message formatting.
"""
self_.__db_print(INFO,msg,*args,**kw) | [
"def",
"message",
"(",
"self_",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"self_",
".",
"__db_print",
"(",
"INFO",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")"
] | Print msg merged with args as a message.
See Python's logging module for details of message formatting. | [
"Print",
"msg",
"merged",
"with",
"args",
"as",
"a",
"message",
"."
] | 8f0dafa78defa883247b40635f96cc6d5c1b3481 | https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/parameterized.py#L1727-L1733 | train |
pyviz/param | param/parameterized.py | Parameters.verbose | def verbose(self_,msg,*args,**kw):
"""
Print msg merged with args as a verbose message.
See Python's logging module for details of message formatting.
"""
self_.__db_print(VERBOSE,msg,*args,**kw) | python | def verbose(self_,msg,*args,**kw):
"""
Print msg merged with args as a verbose message.
See Python's logging module for details of message formatting.
"""
self_.__db_print(VERBOSE,msg,*args,**kw) | [
"def",
"verbose",
"(",
"self_",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"self_",
".",
"__db_print",
"(",
"VERBOSE",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")"
] | Print msg merged with args as a verbose message.
See Python's logging module for details of message formatting. | [
"Print",
"msg",
"merged",
"with",
"args",
"as",
"a",
"verbose",
"message",
"."
] | 8f0dafa78defa883247b40635f96cc6d5c1b3481 | https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/parameterized.py#L1735-L1741 | train |
pyviz/param | param/parameterized.py | Parameters.debug | def debug(self_,msg,*args,**kw):
"""
Print msg merged with args as a debugging statement.
See Python's logging module for details of message formatting.
"""
self_.__db_print(DEBUG,msg,*args,**kw) | python | def debug(self_,msg,*args,**kw):
"""
Print msg merged with args as a debugging statement.
See Python's logging module for details of message formatting.
"""
self_.__db_print(DEBUG,msg,*args,**kw) | [
"def",
"debug",
"(",
"self_",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"self_",
".",
"__db_print",
"(",
"DEBUG",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")"
] | Print msg merged with args as a debugging statement.
See Python's logging module for details of message formatting. | [
"Print",
"msg",
"merged",
"with",
"args",
"as",
"a",
"debugging",
"statement",
"."
] | 8f0dafa78defa883247b40635f96cc6d5c1b3481 | https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/parameterized.py#L1743-L1749 | train |
pyviz/param | param/parameterized.py | ParameterizedMetaclass.__class_docstring_signature | def __class_docstring_signature(mcs, max_repr_len=15):
"""
Autogenerate a keyword signature in the class docstring for
all available parameters. This is particularly useful in the
IPython Notebook as IPython will parse this signature to allow
tab-completion of keywords.
max_repr_len: Maximum length (in characters) of value reprs.
"""
processed_kws, keyword_groups = set(), []
for cls in reversed(mcs.mro()):
keyword_group = []
for (k,v) in sorted(cls.__dict__.items()):
if isinstance(v, Parameter) and k not in processed_kws:
param_type = v.__class__.__name__
keyword_group.append("%s=%s" % (k, param_type))
processed_kws.add(k)
keyword_groups.append(keyword_group)
keywords = [el for grp in reversed(keyword_groups) for el in grp]
class_docstr = "\n"+mcs.__doc__ if mcs.__doc__ else ''
signature = "params(%s)" % (", ".join(keywords))
description = param_pager(mcs) if (docstring_describe_params and param_pager) else ''
mcs.__doc__ = signature + class_docstr + '\n' + description | python | def __class_docstring_signature(mcs, max_repr_len=15):
"""
Autogenerate a keyword signature in the class docstring for
all available parameters. This is particularly useful in the
IPython Notebook as IPython will parse this signature to allow
tab-completion of keywords.
max_repr_len: Maximum length (in characters) of value reprs.
"""
processed_kws, keyword_groups = set(), []
for cls in reversed(mcs.mro()):
keyword_group = []
for (k,v) in sorted(cls.__dict__.items()):
if isinstance(v, Parameter) and k not in processed_kws:
param_type = v.__class__.__name__
keyword_group.append("%s=%s" % (k, param_type))
processed_kws.add(k)
keyword_groups.append(keyword_group)
keywords = [el for grp in reversed(keyword_groups) for el in grp]
class_docstr = "\n"+mcs.__doc__ if mcs.__doc__ else ''
signature = "params(%s)" % (", ".join(keywords))
description = param_pager(mcs) if (docstring_describe_params and param_pager) else ''
mcs.__doc__ = signature + class_docstr + '\n' + description | [
"def",
"__class_docstring_signature",
"(",
"mcs",
",",
"max_repr_len",
"=",
"15",
")",
":",
"processed_kws",
",",
"keyword_groups",
"=",
"set",
"(",
")",
",",
"[",
"]",
"for",
"cls",
"in",
"reversed",
"(",
"mcs",
".",
"mro",
"(",
")",
")",
":",
"keyword_group",
"=",
"[",
"]",
"for",
"(",
"k",
",",
"v",
")",
"in",
"sorted",
"(",
"cls",
".",
"__dict__",
".",
"items",
"(",
")",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"Parameter",
")",
"and",
"k",
"not",
"in",
"processed_kws",
":",
"param_type",
"=",
"v",
".",
"__class__",
".",
"__name__",
"keyword_group",
".",
"append",
"(",
"\"%s=%s\"",
"%",
"(",
"k",
",",
"param_type",
")",
")",
"processed_kws",
".",
"add",
"(",
"k",
")",
"keyword_groups",
".",
"append",
"(",
"keyword_group",
")",
"keywords",
"=",
"[",
"el",
"for",
"grp",
"in",
"reversed",
"(",
"keyword_groups",
")",
"for",
"el",
"in",
"grp",
"]",
"class_docstr",
"=",
"\"\\n\"",
"+",
"mcs",
".",
"__doc__",
"if",
"mcs",
".",
"__doc__",
"else",
"''",
"signature",
"=",
"\"params(%s)\"",
"%",
"(",
"\", \"",
".",
"join",
"(",
"keywords",
")",
")",
"description",
"=",
"param_pager",
"(",
"mcs",
")",
"if",
"(",
"docstring_describe_params",
"and",
"param_pager",
")",
"else",
"''",
"mcs",
".",
"__doc__",
"=",
"signature",
"+",
"class_docstr",
"+",
"'\\n'",
"+",
"description"
] | Autogenerate a keyword signature in the class docstring for
all available parameters. This is particularly useful in the
IPython Notebook as IPython will parse this signature to allow
tab-completion of keywords.
max_repr_len: Maximum length (in characters) of value reprs. | [
"Autogenerate",
"a",
"keyword",
"signature",
"in",
"the",
"class",
"docstring",
"for",
"all",
"available",
"parameters",
".",
"This",
"is",
"particularly",
"useful",
"in",
"the",
"IPython",
"Notebook",
"as",
"IPython",
"will",
"parse",
"this",
"signature",
"to",
"allow",
"tab",
"-",
"completion",
"of",
"keywords",
"."
] | 8f0dafa78defa883247b40635f96cc6d5c1b3481 | https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/parameterized.py#L1830-L1853 | train |
pyviz/param | param/parameterized.py | ParameterizedMetaclass.__param_inheritance | def __param_inheritance(mcs,param_name,param):
"""
Look for Parameter values in superclasses of this
Parameterized class.
Ordinarily, when a Python object is instantiated, attributes
not given values in the constructor will inherit the value
given in the object's class, or in its superclasses. For
Parameters owned by Parameterized classes, we have implemented
an additional level of default lookup, should this ordinary
lookup return only None.
In such a case, i.e. when no non-None value was found for a
Parameter by the usual inheritance mechanisms, we explicitly
look for Parameters with the same name in superclasses of this
Parameterized class, and use the first such value that we
find.
The goal is to be able to set the default value (or other
slots) of a Parameter within a Parameterized class, just as we
can set values for non-Parameter objects in Parameterized
classes, and have the values inherited through the
Parameterized hierarchy as usual.
Note that instantiate is handled differently: if there is a
parameter with the same name in one of the superclasses with
instantiate set to True, this parameter will inherit
instatiate=True.
"""
# get all relevant slots (i.e. slots defined in all
# superclasses of this parameter)
slots = {}
for p_class in classlist(type(param))[1::]:
slots.update(dict.fromkeys(p_class.__slots__))
# note for some eventual future: python 3.6+ descriptors grew
# __set_name__, which could replace this and _set_names
setattr(param,'owner',mcs)
del slots['owner']
# backwards compatibility (see Composite parameter)
if 'objtype' in slots:
setattr(param,'objtype',mcs)
del slots['objtype']
# instantiate is handled specially
for superclass in classlist(mcs)[::-1]:
super_param = superclass.__dict__.get(param_name)
if isinstance(super_param, Parameter) and super_param.instantiate is True:
param.instantiate=True
del slots['instantiate']
for slot in slots.keys():
superclasses = iter(classlist(mcs)[::-1])
# Search up the hierarchy until param.slot (which has to
# be obtained using getattr(param,slot)) is not None, or
# we run out of classes to search.
while getattr(param,slot) is None:
try:
param_super_class = next(superclasses)
except StopIteration:
break
new_param = param_super_class.__dict__.get(param_name)
if new_param is not None and hasattr(new_param,slot):
# (slot might not be there because could be a more
# general type of Parameter)
new_value = getattr(new_param,slot)
setattr(param,slot,new_value) | python | def __param_inheritance(mcs,param_name,param):
"""
Look for Parameter values in superclasses of this
Parameterized class.
Ordinarily, when a Python object is instantiated, attributes
not given values in the constructor will inherit the value
given in the object's class, or in its superclasses. For
Parameters owned by Parameterized classes, we have implemented
an additional level of default lookup, should this ordinary
lookup return only None.
In such a case, i.e. when no non-None value was found for a
Parameter by the usual inheritance mechanisms, we explicitly
look for Parameters with the same name in superclasses of this
Parameterized class, and use the first such value that we
find.
The goal is to be able to set the default value (or other
slots) of a Parameter within a Parameterized class, just as we
can set values for non-Parameter objects in Parameterized
classes, and have the values inherited through the
Parameterized hierarchy as usual.
Note that instantiate is handled differently: if there is a
parameter with the same name in one of the superclasses with
instantiate set to True, this parameter will inherit
instatiate=True.
"""
# get all relevant slots (i.e. slots defined in all
# superclasses of this parameter)
slots = {}
for p_class in classlist(type(param))[1::]:
slots.update(dict.fromkeys(p_class.__slots__))
# note for some eventual future: python 3.6+ descriptors grew
# __set_name__, which could replace this and _set_names
setattr(param,'owner',mcs)
del slots['owner']
# backwards compatibility (see Composite parameter)
if 'objtype' in slots:
setattr(param,'objtype',mcs)
del slots['objtype']
# instantiate is handled specially
for superclass in classlist(mcs)[::-1]:
super_param = superclass.__dict__.get(param_name)
if isinstance(super_param, Parameter) and super_param.instantiate is True:
param.instantiate=True
del slots['instantiate']
for slot in slots.keys():
superclasses = iter(classlist(mcs)[::-1])
# Search up the hierarchy until param.slot (which has to
# be obtained using getattr(param,slot)) is not None, or
# we run out of classes to search.
while getattr(param,slot) is None:
try:
param_super_class = next(superclasses)
except StopIteration:
break
new_param = param_super_class.__dict__.get(param_name)
if new_param is not None and hasattr(new_param,slot):
# (slot might not be there because could be a more
# general type of Parameter)
new_value = getattr(new_param,slot)
setattr(param,slot,new_value) | [
"def",
"__param_inheritance",
"(",
"mcs",
",",
"param_name",
",",
"param",
")",
":",
"# get all relevant slots (i.e. slots defined in all",
"# superclasses of this parameter)",
"slots",
"=",
"{",
"}",
"for",
"p_class",
"in",
"classlist",
"(",
"type",
"(",
"param",
")",
")",
"[",
"1",
":",
":",
"]",
":",
"slots",
".",
"update",
"(",
"dict",
".",
"fromkeys",
"(",
"p_class",
".",
"__slots__",
")",
")",
"# note for some eventual future: python 3.6+ descriptors grew",
"# __set_name__, which could replace this and _set_names",
"setattr",
"(",
"param",
",",
"'owner'",
",",
"mcs",
")",
"del",
"slots",
"[",
"'owner'",
"]",
"# backwards compatibility (see Composite parameter)",
"if",
"'objtype'",
"in",
"slots",
":",
"setattr",
"(",
"param",
",",
"'objtype'",
",",
"mcs",
")",
"del",
"slots",
"[",
"'objtype'",
"]",
"# instantiate is handled specially",
"for",
"superclass",
"in",
"classlist",
"(",
"mcs",
")",
"[",
":",
":",
"-",
"1",
"]",
":",
"super_param",
"=",
"superclass",
".",
"__dict__",
".",
"get",
"(",
"param_name",
")",
"if",
"isinstance",
"(",
"super_param",
",",
"Parameter",
")",
"and",
"super_param",
".",
"instantiate",
"is",
"True",
":",
"param",
".",
"instantiate",
"=",
"True",
"del",
"slots",
"[",
"'instantiate'",
"]",
"for",
"slot",
"in",
"slots",
".",
"keys",
"(",
")",
":",
"superclasses",
"=",
"iter",
"(",
"classlist",
"(",
"mcs",
")",
"[",
":",
":",
"-",
"1",
"]",
")",
"# Search up the hierarchy until param.slot (which has to",
"# be obtained using getattr(param,slot)) is not None, or",
"# we run out of classes to search.",
"while",
"getattr",
"(",
"param",
",",
"slot",
")",
"is",
"None",
":",
"try",
":",
"param_super_class",
"=",
"next",
"(",
"superclasses",
")",
"except",
"StopIteration",
":",
"break",
"new_param",
"=",
"param_super_class",
".",
"__dict__",
".",
"get",
"(",
"param_name",
")",
"if",
"new_param",
"is",
"not",
"None",
"and",
"hasattr",
"(",
"new_param",
",",
"slot",
")",
":",
"# (slot might not be there because could be a more",
"# general type of Parameter)",
"new_value",
"=",
"getattr",
"(",
"new_param",
",",
"slot",
")",
"setattr",
"(",
"param",
",",
"slot",
",",
"new_value",
")"
] | Look for Parameter values in superclasses of this
Parameterized class.
Ordinarily, when a Python object is instantiated, attributes
not given values in the constructor will inherit the value
given in the object's class, or in its superclasses. For
Parameters owned by Parameterized classes, we have implemented
an additional level of default lookup, should this ordinary
lookup return only None.
In such a case, i.e. when no non-None value was found for a
Parameter by the usual inheritance mechanisms, we explicitly
look for Parameters with the same name in superclasses of this
Parameterized class, and use the first such value that we
find.
The goal is to be able to set the default value (or other
slots) of a Parameter within a Parameterized class, just as we
can set values for non-Parameter objects in Parameterized
classes, and have the values inherited through the
Parameterized hierarchy as usual.
Note that instantiate is handled differently: if there is a
parameter with the same name in one of the superclasses with
instantiate set to True, this parameter will inherit
instatiate=True. | [
"Look",
"for",
"Parameter",
"values",
"in",
"superclasses",
"of",
"this",
"Parameterized",
"class",
"."
] | 8f0dafa78defa883247b40635f96cc6d5c1b3481 | https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/parameterized.py#L1940-L2011 | train |
pyviz/param | param/parameterized.py | ParamOverrides._check_params | def _check_params(self,params):
"""
Print a warning if params contains something that is not a
Parameter of the overridden object.
"""
overridden_object_params = list(self._overridden.param)
for item in params:
if item not in overridden_object_params:
self.param.warning("'%s' will be ignored (not a Parameter).",item) | python | def _check_params(self,params):
"""
Print a warning if params contains something that is not a
Parameter of the overridden object.
"""
overridden_object_params = list(self._overridden.param)
for item in params:
if item not in overridden_object_params:
self.param.warning("'%s' will be ignored (not a Parameter).",item) | [
"def",
"_check_params",
"(",
"self",
",",
"params",
")",
":",
"overridden_object_params",
"=",
"list",
"(",
"self",
".",
"_overridden",
".",
"param",
")",
"for",
"item",
"in",
"params",
":",
"if",
"item",
"not",
"in",
"overridden_object_params",
":",
"self",
".",
"param",
".",
"warning",
"(",
"\"'%s' will be ignored (not a Parameter).\"",
",",
"item",
")"
] | Print a warning if params contains something that is not a
Parameter of the overridden object. | [
"Print",
"a",
"warning",
"if",
"params",
"contains",
"something",
"that",
"is",
"not",
"a",
"Parameter",
"of",
"the",
"overridden",
"object",
"."
] | 8f0dafa78defa883247b40635f96cc6d5c1b3481 | https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/parameterized.py#L2653-L2661 | train |
pyviz/param | param/parameterized.py | ParamOverrides._extract_extra_keywords | def _extract_extra_keywords(self,params):
"""
Return any items in params that are not also
parameters of the overridden object.
"""
extra_keywords = {}
overridden_object_params = list(self._overridden.param)
for name, val in params.items():
if name not in overridden_object_params:
extra_keywords[name]=val
# CEBALERT: should we remove name from params
# (i.e. del params[name]) so that it's only available
# via extra_keywords()?
return extra_keywords | python | def _extract_extra_keywords(self,params):
"""
Return any items in params that are not also
parameters of the overridden object.
"""
extra_keywords = {}
overridden_object_params = list(self._overridden.param)
for name, val in params.items():
if name not in overridden_object_params:
extra_keywords[name]=val
# CEBALERT: should we remove name from params
# (i.e. del params[name]) so that it's only available
# via extra_keywords()?
return extra_keywords | [
"def",
"_extract_extra_keywords",
"(",
"self",
",",
"params",
")",
":",
"extra_keywords",
"=",
"{",
"}",
"overridden_object_params",
"=",
"list",
"(",
"self",
".",
"_overridden",
".",
"param",
")",
"for",
"name",
",",
"val",
"in",
"params",
".",
"items",
"(",
")",
":",
"if",
"name",
"not",
"in",
"overridden_object_params",
":",
"extra_keywords",
"[",
"name",
"]",
"=",
"val",
"# CEBALERT: should we remove name from params",
"# (i.e. del params[name]) so that it's only available",
"# via extra_keywords()?",
"return",
"extra_keywords"
] | Return any items in params that are not also
parameters of the overridden object. | [
"Return",
"any",
"items",
"in",
"params",
"that",
"are",
"not",
"also",
"parameters",
"of",
"the",
"overridden",
"object",
"."
] | 8f0dafa78defa883247b40635f96cc6d5c1b3481 | https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/parameterized.py#L2663-L2676 | train |
pyviz/param | param/parameterized.py | ParameterizedFunction.instance | def instance(self_or_cls,**params):
"""
Return an instance of this class, copying parameters from any
existing instance provided.
"""
if isinstance (self_or_cls,ParameterizedMetaclass):
cls = self_or_cls
else:
p = params
params = dict(self_or_cls.get_param_values())
params.update(p)
params.pop('name')
cls = self_or_cls.__class__
inst=Parameterized.__new__(cls)
Parameterized.__init__(inst,**params)
if 'name' in params: inst.__name__ = params['name']
else: inst.__name__ = self_or_cls.name
return inst | python | def instance(self_or_cls,**params):
"""
Return an instance of this class, copying parameters from any
existing instance provided.
"""
if isinstance (self_or_cls,ParameterizedMetaclass):
cls = self_or_cls
else:
p = params
params = dict(self_or_cls.get_param_values())
params.update(p)
params.pop('name')
cls = self_or_cls.__class__
inst=Parameterized.__new__(cls)
Parameterized.__init__(inst,**params)
if 'name' in params: inst.__name__ = params['name']
else: inst.__name__ = self_or_cls.name
return inst | [
"def",
"instance",
"(",
"self_or_cls",
",",
"*",
"*",
"params",
")",
":",
"if",
"isinstance",
"(",
"self_or_cls",
",",
"ParameterizedMetaclass",
")",
":",
"cls",
"=",
"self_or_cls",
"else",
":",
"p",
"=",
"params",
"params",
"=",
"dict",
"(",
"self_or_cls",
".",
"get_param_values",
"(",
")",
")",
"params",
".",
"update",
"(",
"p",
")",
"params",
".",
"pop",
"(",
"'name'",
")",
"cls",
"=",
"self_or_cls",
".",
"__class__",
"inst",
"=",
"Parameterized",
".",
"__new__",
"(",
"cls",
")",
"Parameterized",
".",
"__init__",
"(",
"inst",
",",
"*",
"*",
"params",
")",
"if",
"'name'",
"in",
"params",
":",
"inst",
".",
"__name__",
"=",
"params",
"[",
"'name'",
"]",
"else",
":",
"inst",
".",
"__name__",
"=",
"self_or_cls",
".",
"name",
"return",
"inst"
] | Return an instance of this class, copying parameters from any
existing instance provided. | [
"Return",
"an",
"instance",
"of",
"this",
"class",
"copying",
"parameters",
"from",
"any",
"existing",
"instance",
"provided",
"."
] | 8f0dafa78defa883247b40635f96cc6d5c1b3481 | https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/parameterized.py#L2702-L2721 | train |
pyviz/param | param/parameterized.py | ParameterizedFunction.script_repr | def script_repr(self,imports=[],prefix=" "):
"""
Same as Parameterized.script_repr, except that X.classname(Y
is replaced with X.classname.instance(Y
"""
return self.pprint(imports,prefix,unknown_value='',qualify=True,
separator="\n") | python | def script_repr(self,imports=[],prefix=" "):
"""
Same as Parameterized.script_repr, except that X.classname(Y
is replaced with X.classname.instance(Y
"""
return self.pprint(imports,prefix,unknown_value='',qualify=True,
separator="\n") | [
"def",
"script_repr",
"(",
"self",
",",
"imports",
"=",
"[",
"]",
",",
"prefix",
"=",
"\" \"",
")",
":",
"return",
"self",
".",
"pprint",
"(",
"imports",
",",
"prefix",
",",
"unknown_value",
"=",
"''",
",",
"qualify",
"=",
"True",
",",
"separator",
"=",
"\"\\n\"",
")"
] | Same as Parameterized.script_repr, except that X.classname(Y
is replaced with X.classname.instance(Y | [
"Same",
"as",
"Parameterized",
".",
"script_repr",
"except",
"that",
"X",
".",
"classname",
"(",
"Y",
"is",
"replaced",
"with",
"X",
".",
"classname",
".",
"instance",
"(",
"Y"
] | 8f0dafa78defa883247b40635f96cc6d5c1b3481 | https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/parameterized.py#L2742-L2748 | train |
pyviz/param | param/parameterized.py | ParameterizedFunction.pprint | def pprint(self, imports=None, prefix="\n ",unknown_value='<?>',
qualify=False, separator=""):
"""
Same as Parameterized.pprint, except that X.classname(Y
is replaced with X.classname.instance(Y
"""
r = Parameterized.pprint(self,imports,prefix,
unknown_value=unknown_value,
qualify=qualify,separator=separator)
classname=self.__class__.__name__
return r.replace(".%s("%classname,".%s.instance("%classname) | python | def pprint(self, imports=None, prefix="\n ",unknown_value='<?>',
qualify=False, separator=""):
"""
Same as Parameterized.pprint, except that X.classname(Y
is replaced with X.classname.instance(Y
"""
r = Parameterized.pprint(self,imports,prefix,
unknown_value=unknown_value,
qualify=qualify,separator=separator)
classname=self.__class__.__name__
return r.replace(".%s("%classname,".%s.instance("%classname) | [
"def",
"pprint",
"(",
"self",
",",
"imports",
"=",
"None",
",",
"prefix",
"=",
"\"\\n \"",
",",
"unknown_value",
"=",
"'<?>'",
",",
"qualify",
"=",
"False",
",",
"separator",
"=",
"\"\"",
")",
":",
"r",
"=",
"Parameterized",
".",
"pprint",
"(",
"self",
",",
"imports",
",",
"prefix",
",",
"unknown_value",
"=",
"unknown_value",
",",
"qualify",
"=",
"qualify",
",",
"separator",
"=",
"separator",
")",
"classname",
"=",
"self",
".",
"__class__",
".",
"__name__",
"return",
"r",
".",
"replace",
"(",
"\".%s(\"",
"%",
"classname",
",",
"\".%s.instance(\"",
"%",
"classname",
")"
] | Same as Parameterized.pprint, except that X.classname(Y
is replaced with X.classname.instance(Y | [
"Same",
"as",
"Parameterized",
".",
"pprint",
"except",
"that",
"X",
".",
"classname",
"(",
"Y",
"is",
"replaced",
"with",
"X",
".",
"classname",
".",
"instance",
"(",
"Y"
] | 8f0dafa78defa883247b40635f96cc6d5c1b3481 | https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/parameterized.py#L2751-L2761 | train |
sass/libsass-python | sassutils/builder.py | Manifest.resolve_filename | def resolve_filename(self, package_dir, filename):
"""Gets a proper full relative path of Sass source and
CSS source that will be generated, according to ``package_dir``
and ``filename``.
:param package_dir: the path of package directory
:type package_dir: :class:`str`, :class:`basestring`
:param filename: the filename of Sass/SCSS source to compile
:type filename: :class:`str`, :class:`basestring`
:returns: a pair of (sass, css) path
:rtype: :class:`tuple`
"""
sass_path = os.path.join(package_dir, self.sass_path, filename)
if self.strip_extension:
filename, _ = os.path.splitext(filename)
css_filename = filename + '.css'
css_path = os.path.join(package_dir, self.css_path, css_filename)
return sass_path, css_path | python | def resolve_filename(self, package_dir, filename):
"""Gets a proper full relative path of Sass source and
CSS source that will be generated, according to ``package_dir``
and ``filename``.
:param package_dir: the path of package directory
:type package_dir: :class:`str`, :class:`basestring`
:param filename: the filename of Sass/SCSS source to compile
:type filename: :class:`str`, :class:`basestring`
:returns: a pair of (sass, css) path
:rtype: :class:`tuple`
"""
sass_path = os.path.join(package_dir, self.sass_path, filename)
if self.strip_extension:
filename, _ = os.path.splitext(filename)
css_filename = filename + '.css'
css_path = os.path.join(package_dir, self.css_path, css_filename)
return sass_path, css_path | [
"def",
"resolve_filename",
"(",
"self",
",",
"package_dir",
",",
"filename",
")",
":",
"sass_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"package_dir",
",",
"self",
".",
"sass_path",
",",
"filename",
")",
"if",
"self",
".",
"strip_extension",
":",
"filename",
",",
"_",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"css_filename",
"=",
"filename",
"+",
"'.css'",
"css_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"package_dir",
",",
"self",
".",
"css_path",
",",
"css_filename",
")",
"return",
"sass_path",
",",
"css_path"
] | Gets a proper full relative path of Sass source and
CSS source that will be generated, according to ``package_dir``
and ``filename``.
:param package_dir: the path of package directory
:type package_dir: :class:`str`, :class:`basestring`
:param filename: the filename of Sass/SCSS source to compile
:type filename: :class:`str`, :class:`basestring`
:returns: a pair of (sass, css) path
:rtype: :class:`tuple` | [
"Gets",
"a",
"proper",
"full",
"relative",
"path",
"of",
"Sass",
"source",
"and",
"CSS",
"source",
"that",
"will",
"be",
"generated",
"according",
"to",
"package_dir",
"and",
"filename",
"."
] | fde5b18bc761f0253e71685ee5489e4beb8a403e | https://github.com/sass/libsass-python/blob/fde5b18bc761f0253e71685ee5489e4beb8a403e/sassutils/builder.py#L181-L199 | train |
sass/libsass-python | sassutils/builder.py | Manifest.unresolve_filename | def unresolve_filename(self, package_dir, filename):
"""Retrieves the probable source path from the output filename. Pass
in a .css path to get out a .scss path.
:param package_dir: the path of the package directory
:type package_dir: :class:`str`
:param filename: the css filename
:type filename: :class:`str`
:returns: the scss filename
:rtype: :class:`str`
"""
filename, _ = os.path.splitext(filename)
if self.strip_extension:
for ext in ('.scss', '.sass'):
test_path = os.path.join(
package_dir, self.sass_path, filename + ext,
)
if os.path.exists(test_path):
return filename + ext
else: # file not found, let it error with `.scss` extension
return filename + '.scss'
else:
return filename | python | def unresolve_filename(self, package_dir, filename):
"""Retrieves the probable source path from the output filename. Pass
in a .css path to get out a .scss path.
:param package_dir: the path of the package directory
:type package_dir: :class:`str`
:param filename: the css filename
:type filename: :class:`str`
:returns: the scss filename
:rtype: :class:`str`
"""
filename, _ = os.path.splitext(filename)
if self.strip_extension:
for ext in ('.scss', '.sass'):
test_path = os.path.join(
package_dir, self.sass_path, filename + ext,
)
if os.path.exists(test_path):
return filename + ext
else: # file not found, let it error with `.scss` extension
return filename + '.scss'
else:
return filename | [
"def",
"unresolve_filename",
"(",
"self",
",",
"package_dir",
",",
"filename",
")",
":",
"filename",
",",
"_",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"if",
"self",
".",
"strip_extension",
":",
"for",
"ext",
"in",
"(",
"'.scss'",
",",
"'.sass'",
")",
":",
"test_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"package_dir",
",",
"self",
".",
"sass_path",
",",
"filename",
"+",
"ext",
",",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"test_path",
")",
":",
"return",
"filename",
"+",
"ext",
"else",
":",
"# file not found, let it error with `.scss` extension",
"return",
"filename",
"+",
"'.scss'",
"else",
":",
"return",
"filename"
] | Retrieves the probable source path from the output filename. Pass
in a .css path to get out a .scss path.
:param package_dir: the path of the package directory
:type package_dir: :class:`str`
:param filename: the css filename
:type filename: :class:`str`
:returns: the scss filename
:rtype: :class:`str` | [
"Retrieves",
"the",
"probable",
"source",
"path",
"from",
"the",
"output",
"filename",
".",
"Pass",
"in",
"a",
".",
"css",
"path",
"to",
"get",
"out",
"a",
".",
"scss",
"path",
"."
] | fde5b18bc761f0253e71685ee5489e4beb8a403e | https://github.com/sass/libsass-python/blob/fde5b18bc761f0253e71685ee5489e4beb8a403e/sassutils/builder.py#L201-L223 | train |
sass/libsass-python | sass.py | _validate_importers | def _validate_importers(importers):
"""Validates the importers and decorates the callables with our output
formatter.
"""
# They could have no importers, that's chill
if importers is None:
return None
def _to_importer(priority, func):
assert isinstance(priority, int), priority
assert callable(func), func
return (priority, _importer_callback_wrapper(func))
# Our code assumes tuple of tuples
return tuple(_to_importer(priority, func) for priority, func in importers) | python | def _validate_importers(importers):
"""Validates the importers and decorates the callables with our output
formatter.
"""
# They could have no importers, that's chill
if importers is None:
return None
def _to_importer(priority, func):
assert isinstance(priority, int), priority
assert callable(func), func
return (priority, _importer_callback_wrapper(func))
# Our code assumes tuple of tuples
return tuple(_to_importer(priority, func) for priority, func in importers) | [
"def",
"_validate_importers",
"(",
"importers",
")",
":",
"# They could have no importers, that's chill",
"if",
"importers",
"is",
"None",
":",
"return",
"None",
"def",
"_to_importer",
"(",
"priority",
",",
"func",
")",
":",
"assert",
"isinstance",
"(",
"priority",
",",
"int",
")",
",",
"priority",
"assert",
"callable",
"(",
"func",
")",
",",
"func",
"return",
"(",
"priority",
",",
"_importer_callback_wrapper",
"(",
"func",
")",
")",
"# Our code assumes tuple of tuples",
"return",
"tuple",
"(",
"_to_importer",
"(",
"priority",
",",
"func",
")",
"for",
"priority",
",",
"func",
"in",
"importers",
")"
] | Validates the importers and decorates the callables with our output
formatter. | [
"Validates",
"the",
"importers",
"and",
"decorates",
"the",
"callables",
"with",
"our",
"output",
"formatter",
"."
] | fde5b18bc761f0253e71685ee5489e4beb8a403e | https://github.com/sass/libsass-python/blob/fde5b18bc761f0253e71685ee5489e4beb8a403e/sass.py#L218-L232 | train |
sass/libsass-python | sass.py | and_join | def and_join(strings):
"""Join the given ``strings`` by commas with last `' and '` conjuction.
>>> and_join(['Korea', 'Japan', 'China', 'Taiwan'])
'Korea, Japan, China, and Taiwan'
:param strings: a list of words to join
:type string: :class:`collections.abc.Sequence`
:returns: a joined string
:rtype: :class:`str`, :class:`basestring`
"""
last = len(strings) - 1
if last == 0:
return strings[0]
elif last < 0:
return ''
iterator = enumerate(strings)
return ', '.join('and ' + s if i == last else s for i, s in iterator) | python | def and_join(strings):
"""Join the given ``strings`` by commas with last `' and '` conjuction.
>>> and_join(['Korea', 'Japan', 'China', 'Taiwan'])
'Korea, Japan, China, and Taiwan'
:param strings: a list of words to join
:type string: :class:`collections.abc.Sequence`
:returns: a joined string
:rtype: :class:`str`, :class:`basestring`
"""
last = len(strings) - 1
if last == 0:
return strings[0]
elif last < 0:
return ''
iterator = enumerate(strings)
return ', '.join('and ' + s if i == last else s for i, s in iterator) | [
"def",
"and_join",
"(",
"strings",
")",
":",
"last",
"=",
"len",
"(",
"strings",
")",
"-",
"1",
"if",
"last",
"==",
"0",
":",
"return",
"strings",
"[",
"0",
"]",
"elif",
"last",
"<",
"0",
":",
"return",
"''",
"iterator",
"=",
"enumerate",
"(",
"strings",
")",
"return",
"', '",
".",
"join",
"(",
"'and '",
"+",
"s",
"if",
"i",
"==",
"last",
"else",
"s",
"for",
"i",
",",
"s",
"in",
"iterator",
")"
] | Join the given ``strings`` by commas with last `' and '` conjuction.
>>> and_join(['Korea', 'Japan', 'China', 'Taiwan'])
'Korea, Japan, China, and Taiwan'
:param strings: a list of words to join
:type string: :class:`collections.abc.Sequence`
:returns: a joined string
:rtype: :class:`str`, :class:`basestring` | [
"Join",
"the",
"given",
"strings",
"by",
"commas",
"with",
"last",
"and",
"conjuction",
"."
] | fde5b18bc761f0253e71685ee5489e4beb8a403e | https://github.com/sass/libsass-python/blob/fde5b18bc761f0253e71685ee5489e4beb8a403e/sass.py#L741-L759 | train |
dbkaplan/dry-rest-permissions | dry_rest_permissions/generics.py | allow_staff_or_superuser | def allow_staff_or_superuser(func):
"""
This decorator is used to abstract common is_staff and is_superuser functionality
out of permission checks. It determines which parameter is the request based on name.
"""
is_object_permission = "has_object" in func.__name__
@wraps(func)
def func_wrapper(*args, **kwargs):
request = args[0]
# use second parameter if object permission
if is_object_permission:
request = args[1]
if request.user.is_staff or request.user.is_superuser:
return True
return func(*args, **kwargs)
return func_wrapper | python | def allow_staff_or_superuser(func):
"""
This decorator is used to abstract common is_staff and is_superuser functionality
out of permission checks. It determines which parameter is the request based on name.
"""
is_object_permission = "has_object" in func.__name__
@wraps(func)
def func_wrapper(*args, **kwargs):
request = args[0]
# use second parameter if object permission
if is_object_permission:
request = args[1]
if request.user.is_staff or request.user.is_superuser:
return True
return func(*args, **kwargs)
return func_wrapper | [
"def",
"allow_staff_or_superuser",
"(",
"func",
")",
":",
"is_object_permission",
"=",
"\"has_object\"",
"in",
"func",
".",
"__name__",
"@",
"wraps",
"(",
"func",
")",
"def",
"func_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"request",
"=",
"args",
"[",
"0",
"]",
"# use second parameter if object permission",
"if",
"is_object_permission",
":",
"request",
"=",
"args",
"[",
"1",
"]",
"if",
"request",
".",
"user",
".",
"is_staff",
"or",
"request",
".",
"user",
".",
"is_superuser",
":",
"return",
"True",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"func_wrapper"
] | This decorator is used to abstract common is_staff and is_superuser functionality
out of permission checks. It determines which parameter is the request based on name. | [
"This",
"decorator",
"is",
"used",
"to",
"abstract",
"common",
"is_staff",
"and",
"is_superuser",
"functionality",
"out",
"of",
"permission",
"checks",
".",
"It",
"determines",
"which",
"parameter",
"is",
"the",
"request",
"based",
"on",
"name",
"."
] | b2d4d3c76041f6c405e2537bea9639657b75b90e | https://github.com/dbkaplan/dry-rest-permissions/blob/b2d4d3c76041f6c405e2537bea9639657b75b90e/dry_rest_permissions/generics.py#L269-L288 | train |
dbkaplan/dry-rest-permissions | dry_rest_permissions/generics.py | authenticated_users | def authenticated_users(func):
"""
This decorator is used to abstract common authentication checking functionality
out of permission checks. It determines which parameter is the request based on name.
"""
is_object_permission = "has_object" in func.__name__
@wraps(func)
def func_wrapper(*args, **kwargs):
request = args[0]
# use second parameter if object permission
if is_object_permission:
request = args[1]
if not(request.user and request.user.is_authenticated):
return False
return func(*args, **kwargs)
return func_wrapper | python | def authenticated_users(func):
"""
This decorator is used to abstract common authentication checking functionality
out of permission checks. It determines which parameter is the request based on name.
"""
is_object_permission = "has_object" in func.__name__
@wraps(func)
def func_wrapper(*args, **kwargs):
request = args[0]
# use second parameter if object permission
if is_object_permission:
request = args[1]
if not(request.user and request.user.is_authenticated):
return False
return func(*args, **kwargs)
return func_wrapper | [
"def",
"authenticated_users",
"(",
"func",
")",
":",
"is_object_permission",
"=",
"\"has_object\"",
"in",
"func",
".",
"__name__",
"@",
"wraps",
"(",
"func",
")",
"def",
"func_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"request",
"=",
"args",
"[",
"0",
"]",
"# use second parameter if object permission",
"if",
"is_object_permission",
":",
"request",
"=",
"args",
"[",
"1",
"]",
"if",
"not",
"(",
"request",
".",
"user",
"and",
"request",
".",
"user",
".",
"is_authenticated",
")",
":",
"return",
"False",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"func_wrapper"
] | This decorator is used to abstract common authentication checking functionality
out of permission checks. It determines which parameter is the request based on name. | [
"This",
"decorator",
"is",
"used",
"to",
"abstract",
"common",
"authentication",
"checking",
"functionality",
"out",
"of",
"permission",
"checks",
".",
"It",
"determines",
"which",
"parameter",
"is",
"the",
"request",
"based",
"on",
"name",
"."
] | b2d4d3c76041f6c405e2537bea9639657b75b90e | https://github.com/dbkaplan/dry-rest-permissions/blob/b2d4d3c76041f6c405e2537bea9639657b75b90e/dry_rest_permissions/generics.py#L291-L310 | train |
dbkaplan/dry-rest-permissions | dry_rest_permissions/generics.py | DRYPermissionFiltersBase.filter_queryset | def filter_queryset(self, request, queryset, view):
"""
This method overrides the standard filter_queryset method.
This method will check to see if the view calling this is from
a list type action. This function will also route the filter
by action type if action_routing is set to True.
"""
# Check if this is a list type request
if view.lookup_field not in view.kwargs:
if not self.action_routing:
return self.filter_list_queryset(request, queryset, view)
else:
method_name = "filter_{action}_queryset".format(action=view.action)
return getattr(self, method_name)(request, queryset, view)
return queryset | python | def filter_queryset(self, request, queryset, view):
"""
This method overrides the standard filter_queryset method.
This method will check to see if the view calling this is from
a list type action. This function will also route the filter
by action type if action_routing is set to True.
"""
# Check if this is a list type request
if view.lookup_field not in view.kwargs:
if not self.action_routing:
return self.filter_list_queryset(request, queryset, view)
else:
method_name = "filter_{action}_queryset".format(action=view.action)
return getattr(self, method_name)(request, queryset, view)
return queryset | [
"def",
"filter_queryset",
"(",
"self",
",",
"request",
",",
"queryset",
",",
"view",
")",
":",
"# Check if this is a list type request",
"if",
"view",
".",
"lookup_field",
"not",
"in",
"view",
".",
"kwargs",
":",
"if",
"not",
"self",
".",
"action_routing",
":",
"return",
"self",
".",
"filter_list_queryset",
"(",
"request",
",",
"queryset",
",",
"view",
")",
"else",
":",
"method_name",
"=",
"\"filter_{action}_queryset\"",
".",
"format",
"(",
"action",
"=",
"view",
".",
"action",
")",
"return",
"getattr",
"(",
"self",
",",
"method_name",
")",
"(",
"request",
",",
"queryset",
",",
"view",
")",
"return",
"queryset"
] | This method overrides the standard filter_queryset method.
This method will check to see if the view calling this is from
a list type action. This function will also route the filter
by action type if action_routing is set to True. | [
"This",
"method",
"overrides",
"the",
"standard",
"filter_queryset",
"method",
".",
"This",
"method",
"will",
"check",
"to",
"see",
"if",
"the",
"view",
"calling",
"this",
"is",
"from",
"a",
"list",
"type",
"action",
".",
"This",
"function",
"will",
"also",
"route",
"the",
"filter",
"by",
"action",
"type",
"if",
"action_routing",
"is",
"set",
"to",
"True",
"."
] | b2d4d3c76041f6c405e2537bea9639657b75b90e | https://github.com/dbkaplan/dry-rest-permissions/blob/b2d4d3c76041f6c405e2537bea9639657b75b90e/dry_rest_permissions/generics.py#L35-L49 | train |
dbkaplan/dry-rest-permissions | dry_rest_permissions/generics.py | DRYPermissions.has_permission | def has_permission(self, request, view):
"""
Overrides the standard function and figures out methods to call for global permissions.
"""
if not self.global_permissions:
return True
serializer_class = view.get_serializer_class()
assert serializer_class.Meta.model is not None, (
"global_permissions set to true without a model "
"set on the serializer for '%s'" % view.__class__.__name__
)
model_class = serializer_class.Meta.model
action_method_name = None
if hasattr(view, 'action'):
action = self._get_action(view.action)
action_method_name = "has_{action}_permission".format(action=action)
# If the specific action permission exists then use it, otherwise use general.
if hasattr(model_class, action_method_name):
return getattr(model_class, action_method_name)(request)
if request.method in permissions.SAFE_METHODS:
assert hasattr(model_class, 'has_read_permission'), \
self._get_error_message(model_class, 'has_read_permission', action_method_name)
return model_class.has_read_permission(request)
else:
assert hasattr(model_class, 'has_write_permission'), \
self._get_error_message(model_class, 'has_write_permission', action_method_name)
return model_class.has_write_permission(request) | python | def has_permission(self, request, view):
"""
Overrides the standard function and figures out methods to call for global permissions.
"""
if not self.global_permissions:
return True
serializer_class = view.get_serializer_class()
assert serializer_class.Meta.model is not None, (
"global_permissions set to true without a model "
"set on the serializer for '%s'" % view.__class__.__name__
)
model_class = serializer_class.Meta.model
action_method_name = None
if hasattr(view, 'action'):
action = self._get_action(view.action)
action_method_name = "has_{action}_permission".format(action=action)
# If the specific action permission exists then use it, otherwise use general.
if hasattr(model_class, action_method_name):
return getattr(model_class, action_method_name)(request)
if request.method in permissions.SAFE_METHODS:
assert hasattr(model_class, 'has_read_permission'), \
self._get_error_message(model_class, 'has_read_permission', action_method_name)
return model_class.has_read_permission(request)
else:
assert hasattr(model_class, 'has_write_permission'), \
self._get_error_message(model_class, 'has_write_permission', action_method_name)
return model_class.has_write_permission(request) | [
"def",
"has_permission",
"(",
"self",
",",
"request",
",",
"view",
")",
":",
"if",
"not",
"self",
".",
"global_permissions",
":",
"return",
"True",
"serializer_class",
"=",
"view",
".",
"get_serializer_class",
"(",
")",
"assert",
"serializer_class",
".",
"Meta",
".",
"model",
"is",
"not",
"None",
",",
"(",
"\"global_permissions set to true without a model \"",
"\"set on the serializer for '%s'\"",
"%",
"view",
".",
"__class__",
".",
"__name__",
")",
"model_class",
"=",
"serializer_class",
".",
"Meta",
".",
"model",
"action_method_name",
"=",
"None",
"if",
"hasattr",
"(",
"view",
",",
"'action'",
")",
":",
"action",
"=",
"self",
".",
"_get_action",
"(",
"view",
".",
"action",
")",
"action_method_name",
"=",
"\"has_{action}_permission\"",
".",
"format",
"(",
"action",
"=",
"action",
")",
"# If the specific action permission exists then use it, otherwise use general.",
"if",
"hasattr",
"(",
"model_class",
",",
"action_method_name",
")",
":",
"return",
"getattr",
"(",
"model_class",
",",
"action_method_name",
")",
"(",
"request",
")",
"if",
"request",
".",
"method",
"in",
"permissions",
".",
"SAFE_METHODS",
":",
"assert",
"hasattr",
"(",
"model_class",
",",
"'has_read_permission'",
")",
",",
"self",
".",
"_get_error_message",
"(",
"model_class",
",",
"'has_read_permission'",
",",
"action_method_name",
")",
"return",
"model_class",
".",
"has_read_permission",
"(",
"request",
")",
"else",
":",
"assert",
"hasattr",
"(",
"model_class",
",",
"'has_write_permission'",
")",
",",
"self",
".",
"_get_error_message",
"(",
"model_class",
",",
"'has_write_permission'",
",",
"action_method_name",
")",
"return",
"model_class",
".",
"has_write_permission",
"(",
"request",
")"
] | Overrides the standard function and figures out methods to call for global permissions. | [
"Overrides",
"the",
"standard",
"function",
"and",
"figures",
"out",
"methods",
"to",
"call",
"for",
"global",
"permissions",
"."
] | b2d4d3c76041f6c405e2537bea9639657b75b90e | https://github.com/dbkaplan/dry-rest-permissions/blob/b2d4d3c76041f6c405e2537bea9639657b75b90e/dry_rest_permissions/generics.py#L97-L128 | train |
dbkaplan/dry-rest-permissions | dry_rest_permissions/generics.py | DRYPermissions.has_object_permission | def has_object_permission(self, request, view, obj):
"""
Overrides the standard function and figures out methods to call for object permissions.
"""
if not self.object_permissions:
return True
serializer_class = view.get_serializer_class()
model_class = serializer_class.Meta.model
action_method_name = None
if hasattr(view, 'action'):
action = self._get_action(view.action)
action_method_name = "has_object_{action}_permission".format(action=action)
# If the specific action permission exists then use it, otherwise use general.
if hasattr(obj, action_method_name):
return getattr(obj, action_method_name)(request)
if request.method in permissions.SAFE_METHODS:
assert hasattr(obj, 'has_object_read_permission'), \
self._get_error_message(model_class, 'has_object_read_permission', action_method_name)
return obj.has_object_read_permission(request)
else:
assert hasattr(obj, 'has_object_write_permission'), \
self._get_error_message(model_class, 'has_object_write_permission', action_method_name)
return obj.has_object_write_permission(request) | python | def has_object_permission(self, request, view, obj):
"""
Overrides the standard function and figures out methods to call for object permissions.
"""
if not self.object_permissions:
return True
serializer_class = view.get_serializer_class()
model_class = serializer_class.Meta.model
action_method_name = None
if hasattr(view, 'action'):
action = self._get_action(view.action)
action_method_name = "has_object_{action}_permission".format(action=action)
# If the specific action permission exists then use it, otherwise use general.
if hasattr(obj, action_method_name):
return getattr(obj, action_method_name)(request)
if request.method in permissions.SAFE_METHODS:
assert hasattr(obj, 'has_object_read_permission'), \
self._get_error_message(model_class, 'has_object_read_permission', action_method_name)
return obj.has_object_read_permission(request)
else:
assert hasattr(obj, 'has_object_write_permission'), \
self._get_error_message(model_class, 'has_object_write_permission', action_method_name)
return obj.has_object_write_permission(request) | [
"def",
"has_object_permission",
"(",
"self",
",",
"request",
",",
"view",
",",
"obj",
")",
":",
"if",
"not",
"self",
".",
"object_permissions",
":",
"return",
"True",
"serializer_class",
"=",
"view",
".",
"get_serializer_class",
"(",
")",
"model_class",
"=",
"serializer_class",
".",
"Meta",
".",
"model",
"action_method_name",
"=",
"None",
"if",
"hasattr",
"(",
"view",
",",
"'action'",
")",
":",
"action",
"=",
"self",
".",
"_get_action",
"(",
"view",
".",
"action",
")",
"action_method_name",
"=",
"\"has_object_{action}_permission\"",
".",
"format",
"(",
"action",
"=",
"action",
")",
"# If the specific action permission exists then use it, otherwise use general.",
"if",
"hasattr",
"(",
"obj",
",",
"action_method_name",
")",
":",
"return",
"getattr",
"(",
"obj",
",",
"action_method_name",
")",
"(",
"request",
")",
"if",
"request",
".",
"method",
"in",
"permissions",
".",
"SAFE_METHODS",
":",
"assert",
"hasattr",
"(",
"obj",
",",
"'has_object_read_permission'",
")",
",",
"self",
".",
"_get_error_message",
"(",
"model_class",
",",
"'has_object_read_permission'",
",",
"action_method_name",
")",
"return",
"obj",
".",
"has_object_read_permission",
"(",
"request",
")",
"else",
":",
"assert",
"hasattr",
"(",
"obj",
",",
"'has_object_write_permission'",
")",
",",
"self",
".",
"_get_error_message",
"(",
"model_class",
",",
"'has_object_write_permission'",
",",
"action_method_name",
")",
"return",
"obj",
".",
"has_object_write_permission",
"(",
"request",
")"
] | Overrides the standard function and figures out methods to call for object permissions. | [
"Overrides",
"the",
"standard",
"function",
"and",
"figures",
"out",
"methods",
"to",
"call",
"for",
"object",
"permissions",
"."
] | b2d4d3c76041f6c405e2537bea9639657b75b90e | https://github.com/dbkaplan/dry-rest-permissions/blob/b2d4d3c76041f6c405e2537bea9639657b75b90e/dry_rest_permissions/generics.py#L130-L154 | train |
dbkaplan/dry-rest-permissions | dry_rest_permissions/generics.py | DRYPermissions._get_action | def _get_action(self, action):
"""
Utility function that consolidates actions if necessary.
"""
return_action = action
if self.partial_update_is_update and action == 'partial_update':
return_action = 'update'
return return_action | python | def _get_action(self, action):
"""
Utility function that consolidates actions if necessary.
"""
return_action = action
if self.partial_update_is_update and action == 'partial_update':
return_action = 'update'
return return_action | [
"def",
"_get_action",
"(",
"self",
",",
"action",
")",
":",
"return_action",
"=",
"action",
"if",
"self",
".",
"partial_update_is_update",
"and",
"action",
"==",
"'partial_update'",
":",
"return_action",
"=",
"'update'",
"return",
"return_action"
] | Utility function that consolidates actions if necessary. | [
"Utility",
"function",
"that",
"consolidates",
"actions",
"if",
"necessary",
"."
] | b2d4d3c76041f6c405e2537bea9639657b75b90e | https://github.com/dbkaplan/dry-rest-permissions/blob/b2d4d3c76041f6c405e2537bea9639657b75b90e/dry_rest_permissions/generics.py#L156-L163 | train |
dbkaplan/dry-rest-permissions | dry_rest_permissions/generics.py | DRYPermissions._get_error_message | def _get_error_message(self, model_class, method_name, action_method_name):
"""
Get assertion error message depending if there are actions permissions methods defined.
"""
if action_method_name:
return "'{}' does not have '{}' or '{}' defined.".format(model_class, method_name, action_method_name)
else:
return "'{}' does not have '{}' defined.".format(model_class, method_name) | python | def _get_error_message(self, model_class, method_name, action_method_name):
"""
Get assertion error message depending if there are actions permissions methods defined.
"""
if action_method_name:
return "'{}' does not have '{}' or '{}' defined.".format(model_class, method_name, action_method_name)
else:
return "'{}' does not have '{}' defined.".format(model_class, method_name) | [
"def",
"_get_error_message",
"(",
"self",
",",
"model_class",
",",
"method_name",
",",
"action_method_name",
")",
":",
"if",
"action_method_name",
":",
"return",
"\"'{}' does not have '{}' or '{}' defined.\"",
".",
"format",
"(",
"model_class",
",",
"method_name",
",",
"action_method_name",
")",
"else",
":",
"return",
"\"'{}' does not have '{}' defined.\"",
".",
"format",
"(",
"model_class",
",",
"method_name",
")"
] | Get assertion error message depending if there are actions permissions methods defined. | [
"Get",
"assertion",
"error",
"message",
"depending",
"if",
"there",
"are",
"actions",
"permissions",
"methods",
"defined",
"."
] | b2d4d3c76041f6c405e2537bea9639657b75b90e | https://github.com/dbkaplan/dry-rest-permissions/blob/b2d4d3c76041f6c405e2537bea9639657b75b90e/dry_rest_permissions/generics.py#L165-L172 | train |
dbkaplan/dry-rest-permissions | dry_rest_permissions/generics.py | DRYPermissionsField.bind | def bind(self, field_name, parent):
"""
Check the model attached to the serializer to see what methods are defined and save them.
"""
assert parent.Meta.model is not None, \
"DRYPermissions is used on '{}' without a model".format(parent.__class__.__name__)
for action in self.actions:
if not self.object_only:
global_method_name = "has_{action}_permission".format(action=action)
if hasattr(parent.Meta.model, global_method_name):
self.action_method_map[action] = {'global': global_method_name}
if not self.global_only:
object_method_name = "has_object_{action}_permission".format(action=action)
if hasattr(parent.Meta.model, object_method_name):
if self.action_method_map.get(action, None) is None:
self.action_method_map[action] = {}
self.action_method_map[action]['object'] = object_method_name
super(DRYPermissionsField, self).bind(field_name, parent) | python | def bind(self, field_name, parent):
"""
Check the model attached to the serializer to see what methods are defined and save them.
"""
assert parent.Meta.model is not None, \
"DRYPermissions is used on '{}' without a model".format(parent.__class__.__name__)
for action in self.actions:
if not self.object_only:
global_method_name = "has_{action}_permission".format(action=action)
if hasattr(parent.Meta.model, global_method_name):
self.action_method_map[action] = {'global': global_method_name}
if not self.global_only:
object_method_name = "has_object_{action}_permission".format(action=action)
if hasattr(parent.Meta.model, object_method_name):
if self.action_method_map.get(action, None) is None:
self.action_method_map[action] = {}
self.action_method_map[action]['object'] = object_method_name
super(DRYPermissionsField, self).bind(field_name, parent) | [
"def",
"bind",
"(",
"self",
",",
"field_name",
",",
"parent",
")",
":",
"assert",
"parent",
".",
"Meta",
".",
"model",
"is",
"not",
"None",
",",
"\"DRYPermissions is used on '{}' without a model\"",
".",
"format",
"(",
"parent",
".",
"__class__",
".",
"__name__",
")",
"for",
"action",
"in",
"self",
".",
"actions",
":",
"if",
"not",
"self",
".",
"object_only",
":",
"global_method_name",
"=",
"\"has_{action}_permission\"",
".",
"format",
"(",
"action",
"=",
"action",
")",
"if",
"hasattr",
"(",
"parent",
".",
"Meta",
".",
"model",
",",
"global_method_name",
")",
":",
"self",
".",
"action_method_map",
"[",
"action",
"]",
"=",
"{",
"'global'",
":",
"global_method_name",
"}",
"if",
"not",
"self",
".",
"global_only",
":",
"object_method_name",
"=",
"\"has_object_{action}_permission\"",
".",
"format",
"(",
"action",
"=",
"action",
")",
"if",
"hasattr",
"(",
"parent",
".",
"Meta",
".",
"model",
",",
"object_method_name",
")",
":",
"if",
"self",
".",
"action_method_map",
".",
"get",
"(",
"action",
",",
"None",
")",
"is",
"None",
":",
"self",
".",
"action_method_map",
"[",
"action",
"]",
"=",
"{",
"}",
"self",
".",
"action_method_map",
"[",
"action",
"]",
"[",
"'object'",
"]",
"=",
"object_method_name",
"super",
"(",
"DRYPermissionsField",
",",
"self",
")",
".",
"bind",
"(",
"field_name",
",",
"parent",
")"
] | Check the model attached to the serializer to see what methods are defined and save them. | [
"Check",
"the",
"model",
"attached",
"to",
"the",
"serializer",
"to",
"see",
"what",
"methods",
"are",
"defined",
"and",
"save",
"them",
"."
] | b2d4d3c76041f6c405e2537bea9639657b75b90e | https://github.com/dbkaplan/dry-rest-permissions/blob/b2d4d3c76041f6c405e2537bea9639657b75b90e/dry_rest_permissions/generics.py#L229-L250 | train |
toastdriven/restless | restless/resources.py | skip_prepare | def skip_prepare(func):
"""
A convenience decorator for indicating the raw data should not be prepared.
"""
@wraps(func)
def _wrapper(self, *args, **kwargs):
value = func(self, *args, **kwargs)
return Data(value, should_prepare=False)
return _wrapper | python | def skip_prepare(func):
"""
A convenience decorator for indicating the raw data should not be prepared.
"""
@wraps(func)
def _wrapper(self, *args, **kwargs):
value = func(self, *args, **kwargs)
return Data(value, should_prepare=False)
return _wrapper | [
"def",
"skip_prepare",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"_wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"value",
"=",
"func",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"Data",
"(",
"value",
",",
"should_prepare",
"=",
"False",
")",
"return",
"_wrapper"
] | A convenience decorator for indicating the raw data should not be prepared. | [
"A",
"convenience",
"decorator",
"for",
"indicating",
"the",
"raw",
"data",
"should",
"not",
"be",
"prepared",
"."
] | 661593b7b43c42d1bc508dec795356297991255e | https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/resources.py#L12-L20 | train |
toastdriven/restless | restless/resources.py | Resource.build_error | def build_error(self, err):
"""
When an exception is encountered, this generates a JSON error message
for display to the user.
:param err: The exception seen. The message is exposed to the user, so
beware of sensitive data leaking.
:type err: Exception
:returns: A response object
"""
data = {
'error': err.args[0],
}
if self.is_debug():
# Add the traceback.
data['traceback'] = format_traceback(sys.exc_info())
body = self.serializer.serialize(data)
status = getattr(err, 'status', 500)
return self.build_response(body, status=status) | python | def build_error(self, err):
"""
When an exception is encountered, this generates a JSON error message
for display to the user.
:param err: The exception seen. The message is exposed to the user, so
beware of sensitive data leaking.
:type err: Exception
:returns: A response object
"""
data = {
'error': err.args[0],
}
if self.is_debug():
# Add the traceback.
data['traceback'] = format_traceback(sys.exc_info())
body = self.serializer.serialize(data)
status = getattr(err, 'status', 500)
return self.build_response(body, status=status) | [
"def",
"build_error",
"(",
"self",
",",
"err",
")",
":",
"data",
"=",
"{",
"'error'",
":",
"err",
".",
"args",
"[",
"0",
"]",
",",
"}",
"if",
"self",
".",
"is_debug",
"(",
")",
":",
"# Add the traceback.",
"data",
"[",
"'traceback'",
"]",
"=",
"format_traceback",
"(",
"sys",
".",
"exc_info",
"(",
")",
")",
"body",
"=",
"self",
".",
"serializer",
".",
"serialize",
"(",
"data",
")",
"status",
"=",
"getattr",
"(",
"err",
",",
"'status'",
",",
"500",
")",
"return",
"self",
".",
"build_response",
"(",
"body",
",",
"status",
"=",
"status",
")"
] | When an exception is encountered, this generates a JSON error message
for display to the user.
:param err: The exception seen. The message is exposed to the user, so
beware of sensitive data leaking.
:type err: Exception
:returns: A response object | [
"When",
"an",
"exception",
"is",
"encountered",
"this",
"generates",
"a",
"JSON",
"error",
"message",
"for",
"display",
"to",
"the",
"user",
"."
] | 661593b7b43c42d1bc508dec795356297991255e | https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/resources.py#L192-L213 | train |
toastdriven/restless | restless/resources.py | Resource.deserialize | def deserialize(self, method, endpoint, body):
"""
A convenience method for deserializing the body of a request.
If called on a list-style endpoint, this calls ``deserialize_list``.
Otherwise, it will call ``deserialize_detail``.
:param method: The HTTP method of the current request
:type method: string
:param endpoint: The endpoint style (``list`` or ``detail``)
:type endpoint: string
:param body: The body of the current request
:type body: string
:returns: The deserialized data
:rtype: ``list`` or ``dict``
"""
if endpoint == 'list':
return self.deserialize_list(body)
return self.deserialize_detail(body) | python | def deserialize(self, method, endpoint, body):
"""
A convenience method for deserializing the body of a request.
If called on a list-style endpoint, this calls ``deserialize_list``.
Otherwise, it will call ``deserialize_detail``.
:param method: The HTTP method of the current request
:type method: string
:param endpoint: The endpoint style (``list`` or ``detail``)
:type endpoint: string
:param body: The body of the current request
:type body: string
:returns: The deserialized data
:rtype: ``list`` or ``dict``
"""
if endpoint == 'list':
return self.deserialize_list(body)
return self.deserialize_detail(body) | [
"def",
"deserialize",
"(",
"self",
",",
"method",
",",
"endpoint",
",",
"body",
")",
":",
"if",
"endpoint",
"==",
"'list'",
":",
"return",
"self",
".",
"deserialize_list",
"(",
"body",
")",
"return",
"self",
".",
"deserialize_detail",
"(",
"body",
")"
] | A convenience method for deserializing the body of a request.
If called on a list-style endpoint, this calls ``deserialize_list``.
Otherwise, it will call ``deserialize_detail``.
:param method: The HTTP method of the current request
:type method: string
:param endpoint: The endpoint style (``list`` or ``detail``)
:type endpoint: string
:param body: The body of the current request
:type body: string
:returns: The deserialized data
:rtype: ``list`` or ``dict`` | [
"A",
"convenience",
"method",
"for",
"deserializing",
"the",
"body",
"of",
"a",
"request",
"."
] | 661593b7b43c42d1bc508dec795356297991255e | https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/resources.py#L310-L332 | train |
toastdriven/restless | restless/resources.py | Resource.serialize | def serialize(self, method, endpoint, data):
"""
A convenience method for serializing data for a response.
If called on a list-style endpoint, this calls ``serialize_list``.
Otherwise, it will call ``serialize_detail``.
:param method: The HTTP method of the current request
:type method: string
:param endpoint: The endpoint style (``list`` or ``detail``)
:type endpoint: string
:param data: The body for the response
:type data: string
:returns: A serialized version of the data
:rtype: string
"""
if endpoint == 'list':
# Create is a special-case, because you POST it to the collection,
# not to a detail.
if method == 'POST':
return self.serialize_detail(data)
return self.serialize_list(data)
return self.serialize_detail(data) | python | def serialize(self, method, endpoint, data):
"""
A convenience method for serializing data for a response.
If called on a list-style endpoint, this calls ``serialize_list``.
Otherwise, it will call ``serialize_detail``.
:param method: The HTTP method of the current request
:type method: string
:param endpoint: The endpoint style (``list`` or ``detail``)
:type endpoint: string
:param data: The body for the response
:type data: string
:returns: A serialized version of the data
:rtype: string
"""
if endpoint == 'list':
# Create is a special-case, because you POST it to the collection,
# not to a detail.
if method == 'POST':
return self.serialize_detail(data)
return self.serialize_list(data)
return self.serialize_detail(data) | [
"def",
"serialize",
"(",
"self",
",",
"method",
",",
"endpoint",
",",
"data",
")",
":",
"if",
"endpoint",
"==",
"'list'",
":",
"# Create is a special-case, because you POST it to the collection,",
"# not to a detail.",
"if",
"method",
"==",
"'POST'",
":",
"return",
"self",
".",
"serialize_detail",
"(",
"data",
")",
"return",
"self",
".",
"serialize_list",
"(",
"data",
")",
"return",
"self",
".",
"serialize_detail",
"(",
"data",
")"
] | A convenience method for serializing data for a response.
If called on a list-style endpoint, this calls ``serialize_list``.
Otherwise, it will call ``serialize_detail``.
:param method: The HTTP method of the current request
:type method: string
:param endpoint: The endpoint style (``list`` or ``detail``)
:type endpoint: string
:param data: The body for the response
:type data: string
:returns: A serialized version of the data
:rtype: string | [
"A",
"convenience",
"method",
"for",
"serializing",
"data",
"for",
"a",
"response",
"."
] | 661593b7b43c42d1bc508dec795356297991255e | https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/resources.py#L362-L388 | train |
toastdriven/restless | restless/tnd.py | _method | def _method(self, *args, **kwargs):
"""
the body of those http-methods used in tornado.web.RequestHandler
"""
yield self.resource_handler.handle(self.__resource_view_type__, *args, **kwargs) | python | def _method(self, *args, **kwargs):
"""
the body of those http-methods used in tornado.web.RequestHandler
"""
yield self.resource_handler.handle(self.__resource_view_type__, *args, **kwargs) | [
"def",
"_method",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"yield",
"self",
".",
"resource_handler",
".",
"handle",
"(",
"self",
".",
"__resource_view_type__",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | the body of those http-methods used in tornado.web.RequestHandler | [
"the",
"body",
"of",
"those",
"http",
"-",
"methods",
"used",
"in",
"tornado",
".",
"web",
".",
"RequestHandler"
] | 661593b7b43c42d1bc508dec795356297991255e | https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/tnd.py#L36-L40 | train |
toastdriven/restless | restless/tnd.py | TornadoResource.as_view | def as_view(cls, view_type, *init_args, **init_kwargs):
"""
Return a subclass of tornado.web.RequestHandler and
apply required setting.
"""
global _method
new_cls = type(
cls.__name__ + '_' + _BridgeMixin.__name__ + '_restless',
(_BridgeMixin, cls._request_handler_base_,),
dict(
__resource_cls__=cls,
__resource_args__=init_args,
__resource_kwargs__=init_kwargs,
__resource_view_type__=view_type)
)
"""
Add required http-methods to the newly created class
We need to scan through MRO to find what functions users declared,
and then add corresponding http-methods used by Tornado.
"""
bases = inspect.getmro(cls)
bases = bases[0:bases.index(Resource)-1]
for k, v in cls.http_methods[view_type].items():
if any(v in base_cls.__dict__ for base_cls in bases):
setattr(new_cls, k.lower(), _method)
return new_cls | python | def as_view(cls, view_type, *init_args, **init_kwargs):
"""
Return a subclass of tornado.web.RequestHandler and
apply required setting.
"""
global _method
new_cls = type(
cls.__name__ + '_' + _BridgeMixin.__name__ + '_restless',
(_BridgeMixin, cls._request_handler_base_,),
dict(
__resource_cls__=cls,
__resource_args__=init_args,
__resource_kwargs__=init_kwargs,
__resource_view_type__=view_type)
)
"""
Add required http-methods to the newly created class
We need to scan through MRO to find what functions users declared,
and then add corresponding http-methods used by Tornado.
"""
bases = inspect.getmro(cls)
bases = bases[0:bases.index(Resource)-1]
for k, v in cls.http_methods[view_type].items():
if any(v in base_cls.__dict__ for base_cls in bases):
setattr(new_cls, k.lower(), _method)
return new_cls | [
"def",
"as_view",
"(",
"cls",
",",
"view_type",
",",
"*",
"init_args",
",",
"*",
"*",
"init_kwargs",
")",
":",
"global",
"_method",
"new_cls",
"=",
"type",
"(",
"cls",
".",
"__name__",
"+",
"'_'",
"+",
"_BridgeMixin",
".",
"__name__",
"+",
"'_restless'",
",",
"(",
"_BridgeMixin",
",",
"cls",
".",
"_request_handler_base_",
",",
")",
",",
"dict",
"(",
"__resource_cls__",
"=",
"cls",
",",
"__resource_args__",
"=",
"init_args",
",",
"__resource_kwargs__",
"=",
"init_kwargs",
",",
"__resource_view_type__",
"=",
"view_type",
")",
")",
"\"\"\"\n Add required http-methods to the newly created class\n We need to scan through MRO to find what functions users declared,\n and then add corresponding http-methods used by Tornado.\n \"\"\"",
"bases",
"=",
"inspect",
".",
"getmro",
"(",
"cls",
")",
"bases",
"=",
"bases",
"[",
"0",
":",
"bases",
".",
"index",
"(",
"Resource",
")",
"-",
"1",
"]",
"for",
"k",
",",
"v",
"in",
"cls",
".",
"http_methods",
"[",
"view_type",
"]",
".",
"items",
"(",
")",
":",
"if",
"any",
"(",
"v",
"in",
"base_cls",
".",
"__dict__",
"for",
"base_cls",
"in",
"bases",
")",
":",
"setattr",
"(",
"new_cls",
",",
"k",
".",
"lower",
"(",
")",
",",
"_method",
")",
"return",
"new_cls"
] | Return a subclass of tornado.web.RequestHandler and
apply required setting. | [
"Return",
"a",
"subclass",
"of",
"tornado",
".",
"web",
".",
"RequestHandler",
"and",
"apply",
"required",
"setting",
"."
] | 661593b7b43c42d1bc508dec795356297991255e | https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/tnd.py#L95-L123 | train |
toastdriven/restless | restless/tnd.py | TornadoResource.handle | def handle(self, endpoint, *args, **kwargs):
"""
almost identical to Resource.handle, except
the way we handle the return value of view_method.
"""
method = self.request_method()
try:
if not method in self.http_methods.get(endpoint, {}):
raise MethodNotImplemented(
"Unsupported method '{}' for {} endpoint.".format(
method,
endpoint
)
)
if not self.is_authenticated():
raise Unauthorized()
self.data = self.deserialize(method, endpoint, self.request_body())
view_method = getattr(self, self.http_methods[endpoint][method])
data = view_method(*args, **kwargs)
if is_future(data):
# need to check if the view_method is a generator or not
data = yield data
serialized = self.serialize(method, endpoint, data)
except Exception as err:
raise gen.Return(self.handle_error(err))
status = self.status_map.get(self.http_methods[endpoint][method], OK)
raise gen.Return(self.build_response(serialized, status=status)) | python | def handle(self, endpoint, *args, **kwargs):
"""
almost identical to Resource.handle, except
the way we handle the return value of view_method.
"""
method = self.request_method()
try:
if not method in self.http_methods.get(endpoint, {}):
raise MethodNotImplemented(
"Unsupported method '{}' for {} endpoint.".format(
method,
endpoint
)
)
if not self.is_authenticated():
raise Unauthorized()
self.data = self.deserialize(method, endpoint, self.request_body())
view_method = getattr(self, self.http_methods[endpoint][method])
data = view_method(*args, **kwargs)
if is_future(data):
# need to check if the view_method is a generator or not
data = yield data
serialized = self.serialize(method, endpoint, data)
except Exception as err:
raise gen.Return(self.handle_error(err))
status = self.status_map.get(self.http_methods[endpoint][method], OK)
raise gen.Return(self.build_response(serialized, status=status)) | [
"def",
"handle",
"(",
"self",
",",
"endpoint",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"method",
"=",
"self",
".",
"request_method",
"(",
")",
"try",
":",
"if",
"not",
"method",
"in",
"self",
".",
"http_methods",
".",
"get",
"(",
"endpoint",
",",
"{",
"}",
")",
":",
"raise",
"MethodNotImplemented",
"(",
"\"Unsupported method '{}' for {} endpoint.\"",
".",
"format",
"(",
"method",
",",
"endpoint",
")",
")",
"if",
"not",
"self",
".",
"is_authenticated",
"(",
")",
":",
"raise",
"Unauthorized",
"(",
")",
"self",
".",
"data",
"=",
"self",
".",
"deserialize",
"(",
"method",
",",
"endpoint",
",",
"self",
".",
"request_body",
"(",
")",
")",
"view_method",
"=",
"getattr",
"(",
"self",
",",
"self",
".",
"http_methods",
"[",
"endpoint",
"]",
"[",
"method",
"]",
")",
"data",
"=",
"view_method",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"is_future",
"(",
"data",
")",
":",
"# need to check if the view_method is a generator or not",
"data",
"=",
"yield",
"data",
"serialized",
"=",
"self",
".",
"serialize",
"(",
"method",
",",
"endpoint",
",",
"data",
")",
"except",
"Exception",
"as",
"err",
":",
"raise",
"gen",
".",
"Return",
"(",
"self",
".",
"handle_error",
"(",
"err",
")",
")",
"status",
"=",
"self",
".",
"status_map",
".",
"get",
"(",
"self",
".",
"http_methods",
"[",
"endpoint",
"]",
"[",
"method",
"]",
",",
"OK",
")",
"raise",
"gen",
".",
"Return",
"(",
"self",
".",
"build_response",
"(",
"serialized",
",",
"status",
"=",
"status",
")",
")"
] | almost identical to Resource.handle, except
the way we handle the return value of view_method. | [
"almost",
"identical",
"to",
"Resource",
".",
"handle",
"except",
"the",
"way",
"we",
"handle",
"the",
"return",
"value",
"of",
"view_method",
"."
] | 661593b7b43c42d1bc508dec795356297991255e | https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/tnd.py#L147-L177 | train |
toastdriven/restless | restless/preparers.py | FieldsPreparer.prepare | def prepare(self, data):
"""
Handles transforming the provided data into the fielded data that should
be exposed to the end user.
Uses the ``lookup_data`` method to traverse dotted paths.
Returns a dictionary of data as the response.
"""
result = {}
if not self.fields:
# No fields specified. Serialize everything.
return data
for fieldname, lookup in self.fields.items():
if isinstance(lookup, SubPreparer):
result[fieldname] = lookup.prepare(data)
else:
result[fieldname] = self.lookup_data(lookup, data)
return result | python | def prepare(self, data):
"""
Handles transforming the provided data into the fielded data that should
be exposed to the end user.
Uses the ``lookup_data`` method to traverse dotted paths.
Returns a dictionary of data as the response.
"""
result = {}
if not self.fields:
# No fields specified. Serialize everything.
return data
for fieldname, lookup in self.fields.items():
if isinstance(lookup, SubPreparer):
result[fieldname] = lookup.prepare(data)
else:
result[fieldname] = self.lookup_data(lookup, data)
return result | [
"def",
"prepare",
"(",
"self",
",",
"data",
")",
":",
"result",
"=",
"{",
"}",
"if",
"not",
"self",
".",
"fields",
":",
"# No fields specified. Serialize everything.",
"return",
"data",
"for",
"fieldname",
",",
"lookup",
"in",
"self",
".",
"fields",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"lookup",
",",
"SubPreparer",
")",
":",
"result",
"[",
"fieldname",
"]",
"=",
"lookup",
".",
"prepare",
"(",
"data",
")",
"else",
":",
"result",
"[",
"fieldname",
"]",
"=",
"self",
".",
"lookup_data",
"(",
"lookup",
",",
"data",
")",
"return",
"result"
] | Handles transforming the provided data into the fielded data that should
be exposed to the end user.
Uses the ``lookup_data`` method to traverse dotted paths.
Returns a dictionary of data as the response. | [
"Handles",
"transforming",
"the",
"provided",
"data",
"into",
"the",
"fielded",
"data",
"that",
"should",
"be",
"exposed",
"to",
"the",
"end",
"user",
"."
] | 661593b7b43c42d1bc508dec795356297991255e | https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/preparers.py#L42-L63 | train |
toastdriven/restless | restless/preparers.py | FieldsPreparer.lookup_data | def lookup_data(self, lookup, data):
"""
Given a lookup string, attempts to descend through nested data looking for
the value.
Can work with either dictionary-alikes or objects (or any combination of
those).
Lookups should be a string. If it is a dotted path, it will be split on
``.`` & it will traverse through to find the final value. If not, it will
simply attempt to find either a key or attribute of that name & return it.
Example::
>>> data = {
... 'type': 'message',
... 'greeting': {
... 'en': 'hello',
... 'fr': 'bonjour',
... 'es': 'hola',
... },
... 'person': Person(
... name='daniel'
... )
... }
>>> lookup_data('type', data)
'message'
>>> lookup_data('greeting.en', data)
'hello'
>>> lookup_data('person.name', data)
'daniel'
"""
value = data
parts = lookup.split('.')
if not parts or not parts[0]:
return value
part = parts[0]
remaining_lookup = '.'.join(parts[1:])
if callable(getattr(data, 'keys', None)) and hasattr(data, '__getitem__'):
# Dictionary enough for us.
value = data[part]
elif data is not None:
# Assume it's an object.
value = getattr(data, part)
# Call if it's callable except if it's a Django DB manager instance
# We check if is a manager by checking the db_manager (duck typing)
if callable(value) and not hasattr(value, 'db_manager'):
value = value()
if not remaining_lookup:
return value
# There's more to lookup, so dive in recursively.
return self.lookup_data(remaining_lookup, value) | python | def lookup_data(self, lookup, data):
"""
Given a lookup string, attempts to descend through nested data looking for
the value.
Can work with either dictionary-alikes or objects (or any combination of
those).
Lookups should be a string. If it is a dotted path, it will be split on
``.`` & it will traverse through to find the final value. If not, it will
simply attempt to find either a key or attribute of that name & return it.
Example::
>>> data = {
... 'type': 'message',
... 'greeting': {
... 'en': 'hello',
... 'fr': 'bonjour',
... 'es': 'hola',
... },
... 'person': Person(
... name='daniel'
... )
... }
>>> lookup_data('type', data)
'message'
>>> lookup_data('greeting.en', data)
'hello'
>>> lookup_data('person.name', data)
'daniel'
"""
value = data
parts = lookup.split('.')
if not parts or not parts[0]:
return value
part = parts[0]
remaining_lookup = '.'.join(parts[1:])
if callable(getattr(data, 'keys', None)) and hasattr(data, '__getitem__'):
# Dictionary enough for us.
value = data[part]
elif data is not None:
# Assume it's an object.
value = getattr(data, part)
# Call if it's callable except if it's a Django DB manager instance
# We check if is a manager by checking the db_manager (duck typing)
if callable(value) and not hasattr(value, 'db_manager'):
value = value()
if not remaining_lookup:
return value
# There's more to lookup, so dive in recursively.
return self.lookup_data(remaining_lookup, value) | [
"def",
"lookup_data",
"(",
"self",
",",
"lookup",
",",
"data",
")",
":",
"value",
"=",
"data",
"parts",
"=",
"lookup",
".",
"split",
"(",
"'.'",
")",
"if",
"not",
"parts",
"or",
"not",
"parts",
"[",
"0",
"]",
":",
"return",
"value",
"part",
"=",
"parts",
"[",
"0",
"]",
"remaining_lookup",
"=",
"'.'",
".",
"join",
"(",
"parts",
"[",
"1",
":",
"]",
")",
"if",
"callable",
"(",
"getattr",
"(",
"data",
",",
"'keys'",
",",
"None",
")",
")",
"and",
"hasattr",
"(",
"data",
",",
"'__getitem__'",
")",
":",
"# Dictionary enough for us.",
"value",
"=",
"data",
"[",
"part",
"]",
"elif",
"data",
"is",
"not",
"None",
":",
"# Assume it's an object.",
"value",
"=",
"getattr",
"(",
"data",
",",
"part",
")",
"# Call if it's callable except if it's a Django DB manager instance",
"# We check if is a manager by checking the db_manager (duck typing)",
"if",
"callable",
"(",
"value",
")",
"and",
"not",
"hasattr",
"(",
"value",
",",
"'db_manager'",
")",
":",
"value",
"=",
"value",
"(",
")",
"if",
"not",
"remaining_lookup",
":",
"return",
"value",
"# There's more to lookup, so dive in recursively.",
"return",
"self",
".",
"lookup_data",
"(",
"remaining_lookup",
",",
"value",
")"
] | Given a lookup string, attempts to descend through nested data looking for
the value.
Can work with either dictionary-alikes or objects (or any combination of
those).
Lookups should be a string. If it is a dotted path, it will be split on
``.`` & it will traverse through to find the final value. If not, it will
simply attempt to find either a key or attribute of that name & return it.
Example::
>>> data = {
... 'type': 'message',
... 'greeting': {
... 'en': 'hello',
... 'fr': 'bonjour',
... 'es': 'hola',
... },
... 'person': Person(
... name='daniel'
... )
... }
>>> lookup_data('type', data)
'message'
>>> lookup_data('greeting.en', data)
'hello'
>>> lookup_data('person.name', data)
'daniel' | [
"Given",
"a",
"lookup",
"string",
"attempts",
"to",
"descend",
"through",
"nested",
"data",
"looking",
"for",
"the",
"value",
"."
] | 661593b7b43c42d1bc508dec795356297991255e | https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/preparers.py#L65-L123 | train |
toastdriven/restless | restless/preparers.py | CollectionSubPreparer.prepare | def prepare(self, data):
"""
Handles passing each item in the collection data to the configured
subpreparer.
Uses a loop and the ``get_inner_data`` method to provide the correct
item of the data.
Returns a list of data as the response.
"""
result = []
for item in self.get_inner_data(data):
result.append(self.preparer.prepare(item))
return result | python | def prepare(self, data):
"""
Handles passing each item in the collection data to the configured
subpreparer.
Uses a loop and the ``get_inner_data`` method to provide the correct
item of the data.
Returns a list of data as the response.
"""
result = []
for item in self.get_inner_data(data):
result.append(self.preparer.prepare(item))
return result | [
"def",
"prepare",
"(",
"self",
",",
"data",
")",
":",
"result",
"=",
"[",
"]",
"for",
"item",
"in",
"self",
".",
"get_inner_data",
"(",
"data",
")",
":",
"result",
".",
"append",
"(",
"self",
".",
"preparer",
".",
"prepare",
"(",
"item",
")",
")",
"return",
"result"
] | Handles passing each item in the collection data to the configured
subpreparer.
Uses a loop and the ``get_inner_data`` method to provide the correct
item of the data.
Returns a list of data as the response. | [
"Handles",
"passing",
"each",
"item",
"in",
"the",
"collection",
"data",
"to",
"the",
"configured",
"subpreparer",
"."
] | 661593b7b43c42d1bc508dec795356297991255e | https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/preparers.py#L201-L216 | train |
toastdriven/restless | restless/dj.py | DjangoResource.build_url_name | def build_url_name(cls, name, name_prefix=None):
"""
Given a ``name`` & an optional ``name_prefix``, this generates a name
for a URL.
:param name: The name for the URL (ex. 'detail')
:type name: string
:param name_prefix: (Optional) A prefix for the URL's name (for
resolving). The default is ``None``, which will autocreate a prefix
based on the class name. Ex: ``BlogPostResource`` ->
``api_blog_post_list``
:type name_prefix: string
:returns: The final name
:rtype: string
"""
if name_prefix is None:
name_prefix = 'api_{}'.format(
cls.__name__.replace('Resource', '').lower()
)
name_prefix = name_prefix.rstrip('_')
return '_'.join([name_prefix, name]) | python | def build_url_name(cls, name, name_prefix=None):
"""
Given a ``name`` & an optional ``name_prefix``, this generates a name
for a URL.
:param name: The name for the URL (ex. 'detail')
:type name: string
:param name_prefix: (Optional) A prefix for the URL's name (for
resolving). The default is ``None``, which will autocreate a prefix
based on the class name. Ex: ``BlogPostResource`` ->
``api_blog_post_list``
:type name_prefix: string
:returns: The final name
:rtype: string
"""
if name_prefix is None:
name_prefix = 'api_{}'.format(
cls.__name__.replace('Resource', '').lower()
)
name_prefix = name_prefix.rstrip('_')
return '_'.join([name_prefix, name]) | [
"def",
"build_url_name",
"(",
"cls",
",",
"name",
",",
"name_prefix",
"=",
"None",
")",
":",
"if",
"name_prefix",
"is",
"None",
":",
"name_prefix",
"=",
"'api_{}'",
".",
"format",
"(",
"cls",
".",
"__name__",
".",
"replace",
"(",
"'Resource'",
",",
"''",
")",
".",
"lower",
"(",
")",
")",
"name_prefix",
"=",
"name_prefix",
".",
"rstrip",
"(",
"'_'",
")",
"return",
"'_'",
".",
"join",
"(",
"[",
"name_prefix",
",",
"name",
"]",
")"
] | Given a ``name`` & an optional ``name_prefix``, this generates a name
for a URL.
:param name: The name for the URL (ex. 'detail')
:type name: string
:param name_prefix: (Optional) A prefix for the URL's name (for
resolving). The default is ``None``, which will autocreate a prefix
based on the class name. Ex: ``BlogPostResource`` ->
``api_blog_post_list``
:type name_prefix: string
:returns: The final name
:rtype: string | [
"Given",
"a",
"name",
"&",
"an",
"optional",
"name_prefix",
"this",
"generates",
"a",
"name",
"for",
"a",
"URL",
"."
] | 661593b7b43c42d1bc508dec795356297991255e | https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/dj.py#L90-L113 | train |
toastdriven/restless | restless/fl.py | FlaskResource.build_endpoint_name | def build_endpoint_name(cls, name, endpoint_prefix=None):
"""
Given a ``name`` & an optional ``endpoint_prefix``, this generates a name
for a URL.
:param name: The name for the URL (ex. 'detail')
:type name: string
:param endpoint_prefix: (Optional) A prefix for the URL's name (for
resolving). The default is ``None``, which will autocreate a prefix
based on the class name. Ex: ``BlogPostResource`` ->
``api_blogpost_list``
:type endpoint_prefix: string
:returns: The final name
:rtype: string
"""
if endpoint_prefix is None:
endpoint_prefix = 'api_{}'.format(
cls.__name__.replace('Resource', '').lower()
)
endpoint_prefix = endpoint_prefix.rstrip('_')
return '_'.join([endpoint_prefix, name]) | python | def build_endpoint_name(cls, name, endpoint_prefix=None):
"""
Given a ``name`` & an optional ``endpoint_prefix``, this generates a name
for a URL.
:param name: The name for the URL (ex. 'detail')
:type name: string
:param endpoint_prefix: (Optional) A prefix for the URL's name (for
resolving). The default is ``None``, which will autocreate a prefix
based on the class name. Ex: ``BlogPostResource`` ->
``api_blogpost_list``
:type endpoint_prefix: string
:returns: The final name
:rtype: string
"""
if endpoint_prefix is None:
endpoint_prefix = 'api_{}'.format(
cls.__name__.replace('Resource', '').lower()
)
endpoint_prefix = endpoint_prefix.rstrip('_')
return '_'.join([endpoint_prefix, name]) | [
"def",
"build_endpoint_name",
"(",
"cls",
",",
"name",
",",
"endpoint_prefix",
"=",
"None",
")",
":",
"if",
"endpoint_prefix",
"is",
"None",
":",
"endpoint_prefix",
"=",
"'api_{}'",
".",
"format",
"(",
"cls",
".",
"__name__",
".",
"replace",
"(",
"'Resource'",
",",
"''",
")",
".",
"lower",
"(",
")",
")",
"endpoint_prefix",
"=",
"endpoint_prefix",
".",
"rstrip",
"(",
"'_'",
")",
"return",
"'_'",
".",
"join",
"(",
"[",
"endpoint_prefix",
",",
"name",
"]",
")"
] | Given a ``name`` & an optional ``endpoint_prefix``, this generates a name
for a URL.
:param name: The name for the URL (ex. 'detail')
:type name: string
:param endpoint_prefix: (Optional) A prefix for the URL's name (for
resolving). The default is ``None``, which will autocreate a prefix
based on the class name. Ex: ``BlogPostResource`` ->
``api_blogpost_list``
:type endpoint_prefix: string
:returns: The final name
:rtype: string | [
"Given",
"a",
"name",
"&",
"an",
"optional",
"endpoint_prefix",
"this",
"generates",
"a",
"name",
"for",
"a",
"URL",
"."
] | 661593b7b43c42d1bc508dec795356297991255e | https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/fl.py#L59-L82 | train |
toastdriven/restless | restless/pyr.py | PyramidResource.build_routename | def build_routename(cls, name, routename_prefix=None):
"""
Given a ``name`` & an optional ``routename_prefix``, this generates a
name for a URL.
:param name: The name for the URL (ex. 'detail')
:type name: string
:param routename_prefix: (Optional) A prefix for the URL's name (for
resolving). The default is ``None``, which will autocreate a prefix
based on the class name. Ex: ``BlogPostResource`` ->
``api_blogpost_list``
:type routename_prefix: string
:returns: The final name
:rtype: string
"""
if routename_prefix is None:
routename_prefix = 'api_{}'.format(
cls.__name__.replace('Resource', '').lower()
)
routename_prefix = routename_prefix.rstrip('_')
return '_'.join([routename_prefix, name]) | python | def build_routename(cls, name, routename_prefix=None):
"""
Given a ``name`` & an optional ``routename_prefix``, this generates a
name for a URL.
:param name: The name for the URL (ex. 'detail')
:type name: string
:param routename_prefix: (Optional) A prefix for the URL's name (for
resolving). The default is ``None``, which will autocreate a prefix
based on the class name. Ex: ``BlogPostResource`` ->
``api_blogpost_list``
:type routename_prefix: string
:returns: The final name
:rtype: string
"""
if routename_prefix is None:
routename_prefix = 'api_{}'.format(
cls.__name__.replace('Resource', '').lower()
)
routename_prefix = routename_prefix.rstrip('_')
return '_'.join([routename_prefix, name]) | [
"def",
"build_routename",
"(",
"cls",
",",
"name",
",",
"routename_prefix",
"=",
"None",
")",
":",
"if",
"routename_prefix",
"is",
"None",
":",
"routename_prefix",
"=",
"'api_{}'",
".",
"format",
"(",
"cls",
".",
"__name__",
".",
"replace",
"(",
"'Resource'",
",",
"''",
")",
".",
"lower",
"(",
")",
")",
"routename_prefix",
"=",
"routename_prefix",
".",
"rstrip",
"(",
"'_'",
")",
"return",
"'_'",
".",
"join",
"(",
"[",
"routename_prefix",
",",
"name",
"]",
")"
] | Given a ``name`` & an optional ``routename_prefix``, this generates a
name for a URL.
:param name: The name for the URL (ex. 'detail')
:type name: string
:param routename_prefix: (Optional) A prefix for the URL's name (for
resolving). The default is ``None``, which will autocreate a prefix
based on the class name. Ex: ``BlogPostResource`` ->
``api_blogpost_list``
:type routename_prefix: string
:returns: The final name
:rtype: string | [
"Given",
"a",
"name",
"&",
"an",
"optional",
"routename_prefix",
"this",
"generates",
"a",
"name",
"for",
"a",
"URL",
"."
] | 661593b7b43c42d1bc508dec795356297991255e | https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/pyr.py#L41-L64 | train |
toastdriven/restless | restless/pyr.py | PyramidResource.add_views | def add_views(cls, config, rule_prefix, routename_prefix=None):
"""
A convenience method for registering the routes and views in pyramid.
This automatically adds a list and detail endpoint to your routes.
:param config: The pyramid ``Configurator`` object for your app.
:type config: ``pyramid.config.Configurator``
:param rule_prefix: The start of the URL to handle.
:type rule_prefix: string
:param routename_prefix: (Optional) A prefix for the route's name.
The default is ``None``, which will autocreate a prefix based on the
class name. Ex: ``PostResource`` -> ``api_post_list``
:type routename_prefix: string
:returns: ``pyramid.config.Configurator``
"""
methods = ('GET', 'POST', 'PUT', 'DELETE')
config.add_route(
cls.build_routename('list', routename_prefix),
rule_prefix
)
config.add_view(
cls.as_list(),
route_name=cls.build_routename('list', routename_prefix),
request_method=methods
)
config.add_route(
cls.build_routename('detail', routename_prefix),
rule_prefix + '{name}/'
)
config.add_view(
cls.as_detail(),
route_name=cls.build_routename('detail', routename_prefix),
request_method=methods
)
return config | python | def add_views(cls, config, rule_prefix, routename_prefix=None):
"""
A convenience method for registering the routes and views in pyramid.
This automatically adds a list and detail endpoint to your routes.
:param config: The pyramid ``Configurator`` object for your app.
:type config: ``pyramid.config.Configurator``
:param rule_prefix: The start of the URL to handle.
:type rule_prefix: string
:param routename_prefix: (Optional) A prefix for the route's name.
The default is ``None``, which will autocreate a prefix based on the
class name. Ex: ``PostResource`` -> ``api_post_list``
:type routename_prefix: string
:returns: ``pyramid.config.Configurator``
"""
methods = ('GET', 'POST', 'PUT', 'DELETE')
config.add_route(
cls.build_routename('list', routename_prefix),
rule_prefix
)
config.add_view(
cls.as_list(),
route_name=cls.build_routename('list', routename_prefix),
request_method=methods
)
config.add_route(
cls.build_routename('detail', routename_prefix),
rule_prefix + '{name}/'
)
config.add_view(
cls.as_detail(),
route_name=cls.build_routename('detail', routename_prefix),
request_method=methods
)
return config | [
"def",
"add_views",
"(",
"cls",
",",
"config",
",",
"rule_prefix",
",",
"routename_prefix",
"=",
"None",
")",
":",
"methods",
"=",
"(",
"'GET'",
",",
"'POST'",
",",
"'PUT'",
",",
"'DELETE'",
")",
"config",
".",
"add_route",
"(",
"cls",
".",
"build_routename",
"(",
"'list'",
",",
"routename_prefix",
")",
",",
"rule_prefix",
")",
"config",
".",
"add_view",
"(",
"cls",
".",
"as_list",
"(",
")",
",",
"route_name",
"=",
"cls",
".",
"build_routename",
"(",
"'list'",
",",
"routename_prefix",
")",
",",
"request_method",
"=",
"methods",
")",
"config",
".",
"add_route",
"(",
"cls",
".",
"build_routename",
"(",
"'detail'",
",",
"routename_prefix",
")",
",",
"rule_prefix",
"+",
"'{name}/'",
")",
"config",
".",
"add_view",
"(",
"cls",
".",
"as_detail",
"(",
")",
",",
"route_name",
"=",
"cls",
".",
"build_routename",
"(",
"'detail'",
",",
"routename_prefix",
")",
",",
"request_method",
"=",
"methods",
")",
"return",
"config"
] | A convenience method for registering the routes and views in pyramid.
This automatically adds a list and detail endpoint to your routes.
:param config: The pyramid ``Configurator`` object for your app.
:type config: ``pyramid.config.Configurator``
:param rule_prefix: The start of the URL to handle.
:type rule_prefix: string
:param routename_prefix: (Optional) A prefix for the route's name.
The default is ``None``, which will autocreate a prefix based on the
class name. Ex: ``PostResource`` -> ``api_post_list``
:type routename_prefix: string
:returns: ``pyramid.config.Configurator`` | [
"A",
"convenience",
"method",
"for",
"registering",
"the",
"routes",
"and",
"views",
"in",
"pyramid",
"."
] | 661593b7b43c42d1bc508dec795356297991255e | https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/pyr.py#L67-L107 | train |
toastdriven/restless | restless/serializers.py | JSONSerializer.deserialize | def deserialize(self, body):
"""
The low-level deserialization.
Underpins ``deserialize``, ``deserialize_list`` &
``deserialize_detail``.
Has no built-in smarts, simply loads the JSON.
:param body: The body of the current request
:type body: string
:returns: The deserialized data
:rtype: ``list`` or ``dict``
"""
try:
if isinstance(body, bytes):
return json.loads(body.decode('utf-8'))
return json.loads(body)
except ValueError:
raise BadRequest('Request body is not valid JSON') | python | def deserialize(self, body):
"""
The low-level deserialization.
Underpins ``deserialize``, ``deserialize_list`` &
``deserialize_detail``.
Has no built-in smarts, simply loads the JSON.
:param body: The body of the current request
:type body: string
:returns: The deserialized data
:rtype: ``list`` or ``dict``
"""
try:
if isinstance(body, bytes):
return json.loads(body.decode('utf-8'))
return json.loads(body)
except ValueError:
raise BadRequest('Request body is not valid JSON') | [
"def",
"deserialize",
"(",
"self",
",",
"body",
")",
":",
"try",
":",
"if",
"isinstance",
"(",
"body",
",",
"bytes",
")",
":",
"return",
"json",
".",
"loads",
"(",
"body",
".",
"decode",
"(",
"'utf-8'",
")",
")",
"return",
"json",
".",
"loads",
"(",
"body",
")",
"except",
"ValueError",
":",
"raise",
"BadRequest",
"(",
"'Request body is not valid JSON'",
")"
] | The low-level deserialization.
Underpins ``deserialize``, ``deserialize_list`` &
``deserialize_detail``.
Has no built-in smarts, simply loads the JSON.
:param body: The body of the current request
:type body: string
:returns: The deserialized data
:rtype: ``list`` or ``dict`` | [
"The",
"low",
"-",
"level",
"deserialization",
"."
] | 661593b7b43c42d1bc508dec795356297991255e | https://github.com/toastdriven/restless/blob/661593b7b43c42d1bc508dec795356297991255e/restless/serializers.py#L47-L67 | train |
mila-iqia/fuel | fuel/converters/mnist.py | convert_mnist | def convert_mnist(directory, output_directory, output_filename=None,
dtype=None):
"""Converts the MNIST dataset to HDF5.
Converts the MNIST dataset to an HDF5 dataset compatible with
:class:`fuel.datasets.MNIST`. The converted dataset is
saved as 'mnist.hdf5'.
This method assumes the existence of the following files:
`train-images-idx3-ubyte.gz`, `train-labels-idx1-ubyte.gz`
`t10k-images-idx3-ubyte.gz`, `t10k-labels-idx1-ubyte.gz`
It assumes the existence of the following files:
* `train-images-idx3-ubyte.gz`
* `train-labels-idx1-ubyte.gz`
* `t10k-images-idx3-ubyte.gz`
* `t10k-labels-idx1-ubyte.gz`
Parameters
----------
directory : str
Directory in which input files reside.
output_directory : str
Directory in which to save the converted dataset.
output_filename : str, optional
Name of the saved dataset. Defaults to `None`, in which case a name
based on `dtype` will be used.
dtype : str, optional
Either 'float32', 'float64', or 'bool'. Defaults to `None`,
in which case images will be returned in their original
unsigned byte format.
Returns
-------
output_paths : tuple of str
Single-element tuple containing the path to the converted dataset.
"""
if not output_filename:
if dtype:
output_filename = 'mnist_{}.hdf5'.format(dtype)
else:
output_filename = 'mnist.hdf5'
output_path = os.path.join(output_directory, output_filename)
h5file = h5py.File(output_path, mode='w')
train_feat_path = os.path.join(directory, TRAIN_IMAGES)
train_features = read_mnist_images(train_feat_path, dtype)
train_lab_path = os.path.join(directory, TRAIN_LABELS)
train_labels = read_mnist_labels(train_lab_path)
test_feat_path = os.path.join(directory, TEST_IMAGES)
test_features = read_mnist_images(test_feat_path, dtype)
test_lab_path = os.path.join(directory, TEST_LABELS)
test_labels = read_mnist_labels(test_lab_path)
data = (('train', 'features', train_features),
('train', 'targets', train_labels),
('test', 'features', test_features),
('test', 'targets', test_labels))
fill_hdf5_file(h5file, data)
h5file['features'].dims[0].label = 'batch'
h5file['features'].dims[1].label = 'channel'
h5file['features'].dims[2].label = 'height'
h5file['features'].dims[3].label = 'width'
h5file['targets'].dims[0].label = 'batch'
h5file['targets'].dims[1].label = 'index'
h5file.flush()
h5file.close()
return (output_path,) | python | def convert_mnist(directory, output_directory, output_filename=None,
dtype=None):
"""Converts the MNIST dataset to HDF5.
Converts the MNIST dataset to an HDF5 dataset compatible with
:class:`fuel.datasets.MNIST`. The converted dataset is
saved as 'mnist.hdf5'.
This method assumes the existence of the following files:
`train-images-idx3-ubyte.gz`, `train-labels-idx1-ubyte.gz`
`t10k-images-idx3-ubyte.gz`, `t10k-labels-idx1-ubyte.gz`
It assumes the existence of the following files:
* `train-images-idx3-ubyte.gz`
* `train-labels-idx1-ubyte.gz`
* `t10k-images-idx3-ubyte.gz`
* `t10k-labels-idx1-ubyte.gz`
Parameters
----------
directory : str
Directory in which input files reside.
output_directory : str
Directory in which to save the converted dataset.
output_filename : str, optional
Name of the saved dataset. Defaults to `None`, in which case a name
based on `dtype` will be used.
dtype : str, optional
Either 'float32', 'float64', or 'bool'. Defaults to `None`,
in which case images will be returned in their original
unsigned byte format.
Returns
-------
output_paths : tuple of str
Single-element tuple containing the path to the converted dataset.
"""
if not output_filename:
if dtype:
output_filename = 'mnist_{}.hdf5'.format(dtype)
else:
output_filename = 'mnist.hdf5'
output_path = os.path.join(output_directory, output_filename)
h5file = h5py.File(output_path, mode='w')
train_feat_path = os.path.join(directory, TRAIN_IMAGES)
train_features = read_mnist_images(train_feat_path, dtype)
train_lab_path = os.path.join(directory, TRAIN_LABELS)
train_labels = read_mnist_labels(train_lab_path)
test_feat_path = os.path.join(directory, TEST_IMAGES)
test_features = read_mnist_images(test_feat_path, dtype)
test_lab_path = os.path.join(directory, TEST_LABELS)
test_labels = read_mnist_labels(test_lab_path)
data = (('train', 'features', train_features),
('train', 'targets', train_labels),
('test', 'features', test_features),
('test', 'targets', test_labels))
fill_hdf5_file(h5file, data)
h5file['features'].dims[0].label = 'batch'
h5file['features'].dims[1].label = 'channel'
h5file['features'].dims[2].label = 'height'
h5file['features'].dims[3].label = 'width'
h5file['targets'].dims[0].label = 'batch'
h5file['targets'].dims[1].label = 'index'
h5file.flush()
h5file.close()
return (output_path,) | [
"def",
"convert_mnist",
"(",
"directory",
",",
"output_directory",
",",
"output_filename",
"=",
"None",
",",
"dtype",
"=",
"None",
")",
":",
"if",
"not",
"output_filename",
":",
"if",
"dtype",
":",
"output_filename",
"=",
"'mnist_{}.hdf5'",
".",
"format",
"(",
"dtype",
")",
"else",
":",
"output_filename",
"=",
"'mnist.hdf5'",
"output_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"output_directory",
",",
"output_filename",
")",
"h5file",
"=",
"h5py",
".",
"File",
"(",
"output_path",
",",
"mode",
"=",
"'w'",
")",
"train_feat_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"TRAIN_IMAGES",
")",
"train_features",
"=",
"read_mnist_images",
"(",
"train_feat_path",
",",
"dtype",
")",
"train_lab_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"TRAIN_LABELS",
")",
"train_labels",
"=",
"read_mnist_labels",
"(",
"train_lab_path",
")",
"test_feat_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"TEST_IMAGES",
")",
"test_features",
"=",
"read_mnist_images",
"(",
"test_feat_path",
",",
"dtype",
")",
"test_lab_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"TEST_LABELS",
")",
"test_labels",
"=",
"read_mnist_labels",
"(",
"test_lab_path",
")",
"data",
"=",
"(",
"(",
"'train'",
",",
"'features'",
",",
"train_features",
")",
",",
"(",
"'train'",
",",
"'targets'",
",",
"train_labels",
")",
",",
"(",
"'test'",
",",
"'features'",
",",
"test_features",
")",
",",
"(",
"'test'",
",",
"'targets'",
",",
"test_labels",
")",
")",
"fill_hdf5_file",
"(",
"h5file",
",",
"data",
")",
"h5file",
"[",
"'features'",
"]",
".",
"dims",
"[",
"0",
"]",
".",
"label",
"=",
"'batch'",
"h5file",
"[",
"'features'",
"]",
".",
"dims",
"[",
"1",
"]",
".",
"label",
"=",
"'channel'",
"h5file",
"[",
"'features'",
"]",
".",
"dims",
"[",
"2",
"]",
".",
"label",
"=",
"'height'",
"h5file",
"[",
"'features'",
"]",
".",
"dims",
"[",
"3",
"]",
".",
"label",
"=",
"'width'",
"h5file",
"[",
"'targets'",
"]",
".",
"dims",
"[",
"0",
"]",
".",
"label",
"=",
"'batch'",
"h5file",
"[",
"'targets'",
"]",
".",
"dims",
"[",
"1",
"]",
".",
"label",
"=",
"'index'",
"h5file",
".",
"flush",
"(",
")",
"h5file",
".",
"close",
"(",
")",
"return",
"(",
"output_path",
",",
")"
] | Converts the MNIST dataset to HDF5.
Converts the MNIST dataset to an HDF5 dataset compatible with
:class:`fuel.datasets.MNIST`. The converted dataset is
saved as 'mnist.hdf5'.
This method assumes the existence of the following files:
`train-images-idx3-ubyte.gz`, `train-labels-idx1-ubyte.gz`
`t10k-images-idx3-ubyte.gz`, `t10k-labels-idx1-ubyte.gz`
It assumes the existence of the following files:
* `train-images-idx3-ubyte.gz`
* `train-labels-idx1-ubyte.gz`
* `t10k-images-idx3-ubyte.gz`
* `t10k-labels-idx1-ubyte.gz`
Parameters
----------
directory : str
Directory in which input files reside.
output_directory : str
Directory in which to save the converted dataset.
output_filename : str, optional
Name of the saved dataset. Defaults to `None`, in which case a name
based on `dtype` will be used.
dtype : str, optional
Either 'float32', 'float64', or 'bool'. Defaults to `None`,
in which case images will be returned in their original
unsigned byte format.
Returns
-------
output_paths : tuple of str
Single-element tuple containing the path to the converted dataset. | [
"Converts",
"the",
"MNIST",
"dataset",
"to",
"HDF5",
"."
] | 1d6292dc25e3a115544237e392e61bff6631d23c | https://github.com/mila-iqia/fuel/blob/1d6292dc25e3a115544237e392e61bff6631d23c/fuel/converters/mnist.py#L22-L92 | train |
mila-iqia/fuel | fuel/converters/mnist.py | fill_subparser | def fill_subparser(subparser):
"""Sets up a subparser to convert the MNIST dataset files.
Parameters
----------
subparser : :class:`argparse.ArgumentParser`
Subparser handling the `mnist` command.
"""
subparser.add_argument(
"--dtype", help="dtype to save to; by default, images will be " +
"returned in their original unsigned byte format",
choices=('float32', 'float64', 'bool'), type=str, default=None)
return convert_mnist | python | def fill_subparser(subparser):
"""Sets up a subparser to convert the MNIST dataset files.
Parameters
----------
subparser : :class:`argparse.ArgumentParser`
Subparser handling the `mnist` command.
"""
subparser.add_argument(
"--dtype", help="dtype to save to; by default, images will be " +
"returned in their original unsigned byte format",
choices=('float32', 'float64', 'bool'), type=str, default=None)
return convert_mnist | [
"def",
"fill_subparser",
"(",
"subparser",
")",
":",
"subparser",
".",
"add_argument",
"(",
"\"--dtype\"",
",",
"help",
"=",
"\"dtype to save to; by default, images will be \"",
"+",
"\"returned in their original unsigned byte format\"",
",",
"choices",
"=",
"(",
"'float32'",
",",
"'float64'",
",",
"'bool'",
")",
",",
"type",
"=",
"str",
",",
"default",
"=",
"None",
")",
"return",
"convert_mnist"
] | Sets up a subparser to convert the MNIST dataset files.
Parameters
----------
subparser : :class:`argparse.ArgumentParser`
Subparser handling the `mnist` command. | [
"Sets",
"up",
"a",
"subparser",
"to",
"convert",
"the",
"MNIST",
"dataset",
"files",
"."
] | 1d6292dc25e3a115544237e392e61bff6631d23c | https://github.com/mila-iqia/fuel/blob/1d6292dc25e3a115544237e392e61bff6631d23c/fuel/converters/mnist.py#L95-L108 | train |
mila-iqia/fuel | fuel/converters/mnist.py | read_mnist_images | def read_mnist_images(filename, dtype=None):
"""Read MNIST images from the original ubyte file format.
Parameters
----------
filename : str
Filename/path from which to read images.
dtype : 'float32', 'float64', or 'bool'
If unspecified, images will be returned in their original
unsigned byte format.
Returns
-------
images : :class:`~numpy.ndarray`, shape (n_images, 1, n_rows, n_cols)
An image array, with individual examples indexed along the
first axis and the image dimensions along the second and
third axis.
Notes
-----
If the dtype provided was Boolean, the resulting array will
be Boolean with `True` if the corresponding pixel had a value
greater than or equal to 128, `False` otherwise.
If the dtype provided was a float dtype, the values will be mapped to
the unit interval [0, 1], with pixel values that were 255 in the
original unsigned byte representation equal to 1.0.
"""
with gzip.open(filename, 'rb') as f:
magic, number, rows, cols = struct.unpack('>iiii', f.read(16))
if magic != MNIST_IMAGE_MAGIC:
raise ValueError("Wrong magic number reading MNIST image file")
array = numpy.frombuffer(f.read(), dtype='uint8')
array = array.reshape((number, 1, rows, cols))
if dtype:
dtype = numpy.dtype(dtype)
if dtype.kind == 'b':
# If the user wants Booleans, threshold at half the range.
array = array >= 128
elif dtype.kind == 'f':
# Otherwise, just convert.
array = array.astype(dtype)
array /= 255.
else:
raise ValueError("Unknown dtype to convert MNIST to")
return array | python | def read_mnist_images(filename, dtype=None):
"""Read MNIST images from the original ubyte file format.
Parameters
----------
filename : str
Filename/path from which to read images.
dtype : 'float32', 'float64', or 'bool'
If unspecified, images will be returned in their original
unsigned byte format.
Returns
-------
images : :class:`~numpy.ndarray`, shape (n_images, 1, n_rows, n_cols)
An image array, with individual examples indexed along the
first axis and the image dimensions along the second and
third axis.
Notes
-----
If the dtype provided was Boolean, the resulting array will
be Boolean with `True` if the corresponding pixel had a value
greater than or equal to 128, `False` otherwise.
If the dtype provided was a float dtype, the values will be mapped to
the unit interval [0, 1], with pixel values that were 255 in the
original unsigned byte representation equal to 1.0.
"""
with gzip.open(filename, 'rb') as f:
magic, number, rows, cols = struct.unpack('>iiii', f.read(16))
if magic != MNIST_IMAGE_MAGIC:
raise ValueError("Wrong magic number reading MNIST image file")
array = numpy.frombuffer(f.read(), dtype='uint8')
array = array.reshape((number, 1, rows, cols))
if dtype:
dtype = numpy.dtype(dtype)
if dtype.kind == 'b':
# If the user wants Booleans, threshold at half the range.
array = array >= 128
elif dtype.kind == 'f':
# Otherwise, just convert.
array = array.astype(dtype)
array /= 255.
else:
raise ValueError("Unknown dtype to convert MNIST to")
return array | [
"def",
"read_mnist_images",
"(",
"filename",
",",
"dtype",
"=",
"None",
")",
":",
"with",
"gzip",
".",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"f",
":",
"magic",
",",
"number",
",",
"rows",
",",
"cols",
"=",
"struct",
".",
"unpack",
"(",
"'>iiii'",
",",
"f",
".",
"read",
"(",
"16",
")",
")",
"if",
"magic",
"!=",
"MNIST_IMAGE_MAGIC",
":",
"raise",
"ValueError",
"(",
"\"Wrong magic number reading MNIST image file\"",
")",
"array",
"=",
"numpy",
".",
"frombuffer",
"(",
"f",
".",
"read",
"(",
")",
",",
"dtype",
"=",
"'uint8'",
")",
"array",
"=",
"array",
".",
"reshape",
"(",
"(",
"number",
",",
"1",
",",
"rows",
",",
"cols",
")",
")",
"if",
"dtype",
":",
"dtype",
"=",
"numpy",
".",
"dtype",
"(",
"dtype",
")",
"if",
"dtype",
".",
"kind",
"==",
"'b'",
":",
"# If the user wants Booleans, threshold at half the range.",
"array",
"=",
"array",
">=",
"128",
"elif",
"dtype",
".",
"kind",
"==",
"'f'",
":",
"# Otherwise, just convert.",
"array",
"=",
"array",
".",
"astype",
"(",
"dtype",
")",
"array",
"/=",
"255.",
"else",
":",
"raise",
"ValueError",
"(",
"\"Unknown dtype to convert MNIST to\"",
")",
"return",
"array"
] | Read MNIST images from the original ubyte file format.
Parameters
----------
filename : str
Filename/path from which to read images.
dtype : 'float32', 'float64', or 'bool'
If unspecified, images will be returned in their original
unsigned byte format.
Returns
-------
images : :class:`~numpy.ndarray`, shape (n_images, 1, n_rows, n_cols)
An image array, with individual examples indexed along the
first axis and the image dimensions along the second and
third axis.
Notes
-----
If the dtype provided was Boolean, the resulting array will
be Boolean with `True` if the corresponding pixel had a value
greater than or equal to 128, `False` otherwise.
If the dtype provided was a float dtype, the values will be mapped to
the unit interval [0, 1], with pixel values that were 255 in the
original unsigned byte representation equal to 1.0. | [
"Read",
"MNIST",
"images",
"from",
"the",
"original",
"ubyte",
"file",
"format",
"."
] | 1d6292dc25e3a115544237e392e61bff6631d23c | https://github.com/mila-iqia/fuel/blob/1d6292dc25e3a115544237e392e61bff6631d23c/fuel/converters/mnist.py#L111-L159 | train |
mila-iqia/fuel | fuel/converters/mnist.py | read_mnist_labels | def read_mnist_labels(filename):
"""Read MNIST labels from the original ubyte file format.
Parameters
----------
filename : str
Filename/path from which to read labels.
Returns
-------
labels : :class:`~numpy.ndarray`, shape (nlabels, 1)
A one-dimensional unsigned byte array containing the
labels as integers.
"""
with gzip.open(filename, 'rb') as f:
magic, _ = struct.unpack('>ii', f.read(8))
if magic != MNIST_LABEL_MAGIC:
raise ValueError("Wrong magic number reading MNIST label file")
array = numpy.frombuffer(f.read(), dtype='uint8')
array = array.reshape(array.size, 1)
return array | python | def read_mnist_labels(filename):
"""Read MNIST labels from the original ubyte file format.
Parameters
----------
filename : str
Filename/path from which to read labels.
Returns
-------
labels : :class:`~numpy.ndarray`, shape (nlabels, 1)
A one-dimensional unsigned byte array containing the
labels as integers.
"""
with gzip.open(filename, 'rb') as f:
magic, _ = struct.unpack('>ii', f.read(8))
if magic != MNIST_LABEL_MAGIC:
raise ValueError("Wrong magic number reading MNIST label file")
array = numpy.frombuffer(f.read(), dtype='uint8')
array = array.reshape(array.size, 1)
return array | [
"def",
"read_mnist_labels",
"(",
"filename",
")",
":",
"with",
"gzip",
".",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"f",
":",
"magic",
",",
"_",
"=",
"struct",
".",
"unpack",
"(",
"'>ii'",
",",
"f",
".",
"read",
"(",
"8",
")",
")",
"if",
"magic",
"!=",
"MNIST_LABEL_MAGIC",
":",
"raise",
"ValueError",
"(",
"\"Wrong magic number reading MNIST label file\"",
")",
"array",
"=",
"numpy",
".",
"frombuffer",
"(",
"f",
".",
"read",
"(",
")",
",",
"dtype",
"=",
"'uint8'",
")",
"array",
"=",
"array",
".",
"reshape",
"(",
"array",
".",
"size",
",",
"1",
")",
"return",
"array"
] | Read MNIST labels from the original ubyte file format.
Parameters
----------
filename : str
Filename/path from which to read labels.
Returns
-------
labels : :class:`~numpy.ndarray`, shape (nlabels, 1)
A one-dimensional unsigned byte array containing the
labels as integers. | [
"Read",
"MNIST",
"labels",
"from",
"the",
"original",
"ubyte",
"file",
"format",
"."
] | 1d6292dc25e3a115544237e392e61bff6631d23c | https://github.com/mila-iqia/fuel/blob/1d6292dc25e3a115544237e392e61bff6631d23c/fuel/converters/mnist.py#L162-L183 | train |
mila-iqia/fuel | fuel/converters/ilsvrc2010.py | prepare_hdf5_file | def prepare_hdf5_file(hdf5_file, n_train, n_valid, n_test):
"""Create datasets within a given HDF5 file.
Parameters
----------
hdf5_file : :class:`h5py.File` instance
HDF5 file handle to which to write.
n_train : int
The number of training set examples.
n_valid : int
The number of validation set examples.
n_test : int
The number of test set examples.
"""
n_total = n_train + n_valid + n_test
splits = create_splits(n_train, n_valid, n_test)
hdf5_file.attrs['split'] = H5PYDataset.create_split_array(splits)
vlen_dtype = h5py.special_dtype(vlen=numpy.dtype('uint8'))
hdf5_file.create_dataset('encoded_images', shape=(n_total,),
dtype=vlen_dtype)
hdf5_file.create_dataset('targets', shape=(n_total, 1), dtype=numpy.int16)
hdf5_file.create_dataset('filenames', shape=(n_total, 1), dtype='S32') | python | def prepare_hdf5_file(hdf5_file, n_train, n_valid, n_test):
"""Create datasets within a given HDF5 file.
Parameters
----------
hdf5_file : :class:`h5py.File` instance
HDF5 file handle to which to write.
n_train : int
The number of training set examples.
n_valid : int
The number of validation set examples.
n_test : int
The number of test set examples.
"""
n_total = n_train + n_valid + n_test
splits = create_splits(n_train, n_valid, n_test)
hdf5_file.attrs['split'] = H5PYDataset.create_split_array(splits)
vlen_dtype = h5py.special_dtype(vlen=numpy.dtype('uint8'))
hdf5_file.create_dataset('encoded_images', shape=(n_total,),
dtype=vlen_dtype)
hdf5_file.create_dataset('targets', shape=(n_total, 1), dtype=numpy.int16)
hdf5_file.create_dataset('filenames', shape=(n_total, 1), dtype='S32') | [
"def",
"prepare_hdf5_file",
"(",
"hdf5_file",
",",
"n_train",
",",
"n_valid",
",",
"n_test",
")",
":",
"n_total",
"=",
"n_train",
"+",
"n_valid",
"+",
"n_test",
"splits",
"=",
"create_splits",
"(",
"n_train",
",",
"n_valid",
",",
"n_test",
")",
"hdf5_file",
".",
"attrs",
"[",
"'split'",
"]",
"=",
"H5PYDataset",
".",
"create_split_array",
"(",
"splits",
")",
"vlen_dtype",
"=",
"h5py",
".",
"special_dtype",
"(",
"vlen",
"=",
"numpy",
".",
"dtype",
"(",
"'uint8'",
")",
")",
"hdf5_file",
".",
"create_dataset",
"(",
"'encoded_images'",
",",
"shape",
"=",
"(",
"n_total",
",",
")",
",",
"dtype",
"=",
"vlen_dtype",
")",
"hdf5_file",
".",
"create_dataset",
"(",
"'targets'",
",",
"shape",
"=",
"(",
"n_total",
",",
"1",
")",
",",
"dtype",
"=",
"numpy",
".",
"int16",
")",
"hdf5_file",
".",
"create_dataset",
"(",
"'filenames'",
",",
"shape",
"=",
"(",
"n_total",
",",
"1",
")",
",",
"dtype",
"=",
"'S32'",
")"
] | Create datasets within a given HDF5 file.
Parameters
----------
hdf5_file : :class:`h5py.File` instance
HDF5 file handle to which to write.
n_train : int
The number of training set examples.
n_valid : int
The number of validation set examples.
n_test : int
The number of test set examples. | [
"Create",
"datasets",
"within",
"a",
"given",
"HDF5",
"file",
"."
] | 1d6292dc25e3a115544237e392e61bff6631d23c | https://github.com/mila-iqia/fuel/blob/1d6292dc25e3a115544237e392e61bff6631d23c/fuel/converters/ilsvrc2010.py#L179-L201 | train |
mila-iqia/fuel | fuel/converters/ilsvrc2010.py | process_train_set | def process_train_set(hdf5_file, train_archive, patch_archive, n_train,
wnid_map, shuffle_seed=None):
"""Process the ILSVRC2010 training set.
Parameters
----------
hdf5_file : :class:`h5py.File` instance
HDF5 file handle to which to write. Assumes `features`, `targets`
and `filenames` already exist and have first dimension larger than
`n_train`.
train_archive : str or file-like object
Filename or file handle for the TAR archive of training images.
patch_archive : str or file-like object
Filename or file handle for the TAR archive of patch images.
n_train : int
The number of items in the training set.
wnid_map : dict
A dictionary mapping WordNet IDs to class indices.
shuffle_seed : int or sequence, optional
Seed for a NumPy random number generator that permutes the
training set on disk. If `None`, no permutation is performed
(this is the default).
"""
producer = partial(train_set_producer, train_archive=train_archive,
patch_archive=patch_archive, wnid_map=wnid_map)
consumer = partial(image_consumer, hdf5_file=hdf5_file,
num_expected=n_train, shuffle_seed=shuffle_seed)
producer_consumer(producer, consumer) | python | def process_train_set(hdf5_file, train_archive, patch_archive, n_train,
wnid_map, shuffle_seed=None):
"""Process the ILSVRC2010 training set.
Parameters
----------
hdf5_file : :class:`h5py.File` instance
HDF5 file handle to which to write. Assumes `features`, `targets`
and `filenames` already exist and have first dimension larger than
`n_train`.
train_archive : str or file-like object
Filename or file handle for the TAR archive of training images.
patch_archive : str or file-like object
Filename or file handle for the TAR archive of patch images.
n_train : int
The number of items in the training set.
wnid_map : dict
A dictionary mapping WordNet IDs to class indices.
shuffle_seed : int or sequence, optional
Seed for a NumPy random number generator that permutes the
training set on disk. If `None`, no permutation is performed
(this is the default).
"""
producer = partial(train_set_producer, train_archive=train_archive,
patch_archive=patch_archive, wnid_map=wnid_map)
consumer = partial(image_consumer, hdf5_file=hdf5_file,
num_expected=n_train, shuffle_seed=shuffle_seed)
producer_consumer(producer, consumer) | [
"def",
"process_train_set",
"(",
"hdf5_file",
",",
"train_archive",
",",
"patch_archive",
",",
"n_train",
",",
"wnid_map",
",",
"shuffle_seed",
"=",
"None",
")",
":",
"producer",
"=",
"partial",
"(",
"train_set_producer",
",",
"train_archive",
"=",
"train_archive",
",",
"patch_archive",
"=",
"patch_archive",
",",
"wnid_map",
"=",
"wnid_map",
")",
"consumer",
"=",
"partial",
"(",
"image_consumer",
",",
"hdf5_file",
"=",
"hdf5_file",
",",
"num_expected",
"=",
"n_train",
",",
"shuffle_seed",
"=",
"shuffle_seed",
")",
"producer_consumer",
"(",
"producer",
",",
"consumer",
")"
] | Process the ILSVRC2010 training set.
Parameters
----------
hdf5_file : :class:`h5py.File` instance
HDF5 file handle to which to write. Assumes `features`, `targets`
and `filenames` already exist and have first dimension larger than
`n_train`.
train_archive : str or file-like object
Filename or file handle for the TAR archive of training images.
patch_archive : str or file-like object
Filename or file handle for the TAR archive of patch images.
n_train : int
The number of items in the training set.
wnid_map : dict
A dictionary mapping WordNet IDs to class indices.
shuffle_seed : int or sequence, optional
Seed for a NumPy random number generator that permutes the
training set on disk. If `None`, no permutation is performed
(this is the default). | [
"Process",
"the",
"ILSVRC2010",
"training",
"set",
"."
] | 1d6292dc25e3a115544237e392e61bff6631d23c | https://github.com/mila-iqia/fuel/blob/1d6292dc25e3a115544237e392e61bff6631d23c/fuel/converters/ilsvrc2010.py#L204-L232 | train |
mila-iqia/fuel | fuel/converters/ilsvrc2010.py | image_consumer | def image_consumer(socket, hdf5_file, num_expected, shuffle_seed=None,
offset=0):
"""Fill an HDF5 file with incoming images from a socket.
Parameters
----------
socket : :class:`zmq.Socket`
PULL socket on which to receive images.
hdf5_file : :class:`h5py.File` instance
HDF5 file handle to which to write. Assumes `features`, `targets`
and `filenames` already exist and have first dimension larger than
`sum(images_per_class)`.
num_expected : int
The number of items we expect to be sent over the socket.
shuffle_seed : int or sequence, optional
Seed for a NumPy random number generator that permutes the
images on disk.
offset : int, optional
The offset in the HDF5 datasets at which to start writing
received examples. Defaults to 0.
"""
with progress_bar('images', maxval=num_expected) as pb:
if shuffle_seed is None:
index_gen = iter(xrange(num_expected))
else:
rng = numpy.random.RandomState(shuffle_seed)
index_gen = iter(rng.permutation(num_expected))
for i, num in enumerate(index_gen):
image_filename, class_index = socket.recv_pyobj(zmq.SNDMORE)
image_data = numpy.fromstring(socket.recv(), dtype='uint8')
_write_to_hdf5(hdf5_file, num + offset, image_filename,
image_data, class_index)
pb.update(i + 1) | python | def image_consumer(socket, hdf5_file, num_expected, shuffle_seed=None,
offset=0):
"""Fill an HDF5 file with incoming images from a socket.
Parameters
----------
socket : :class:`zmq.Socket`
PULL socket on which to receive images.
hdf5_file : :class:`h5py.File` instance
HDF5 file handle to which to write. Assumes `features`, `targets`
and `filenames` already exist and have first dimension larger than
`sum(images_per_class)`.
num_expected : int
The number of items we expect to be sent over the socket.
shuffle_seed : int or sequence, optional
Seed for a NumPy random number generator that permutes the
images on disk.
offset : int, optional
The offset in the HDF5 datasets at which to start writing
received examples. Defaults to 0.
"""
with progress_bar('images', maxval=num_expected) as pb:
if shuffle_seed is None:
index_gen = iter(xrange(num_expected))
else:
rng = numpy.random.RandomState(shuffle_seed)
index_gen = iter(rng.permutation(num_expected))
for i, num in enumerate(index_gen):
image_filename, class_index = socket.recv_pyobj(zmq.SNDMORE)
image_data = numpy.fromstring(socket.recv(), dtype='uint8')
_write_to_hdf5(hdf5_file, num + offset, image_filename,
image_data, class_index)
pb.update(i + 1) | [
"def",
"image_consumer",
"(",
"socket",
",",
"hdf5_file",
",",
"num_expected",
",",
"shuffle_seed",
"=",
"None",
",",
"offset",
"=",
"0",
")",
":",
"with",
"progress_bar",
"(",
"'images'",
",",
"maxval",
"=",
"num_expected",
")",
"as",
"pb",
":",
"if",
"shuffle_seed",
"is",
"None",
":",
"index_gen",
"=",
"iter",
"(",
"xrange",
"(",
"num_expected",
")",
")",
"else",
":",
"rng",
"=",
"numpy",
".",
"random",
".",
"RandomState",
"(",
"shuffle_seed",
")",
"index_gen",
"=",
"iter",
"(",
"rng",
".",
"permutation",
"(",
"num_expected",
")",
")",
"for",
"i",
",",
"num",
"in",
"enumerate",
"(",
"index_gen",
")",
":",
"image_filename",
",",
"class_index",
"=",
"socket",
".",
"recv_pyobj",
"(",
"zmq",
".",
"SNDMORE",
")",
"image_data",
"=",
"numpy",
".",
"fromstring",
"(",
"socket",
".",
"recv",
"(",
")",
",",
"dtype",
"=",
"'uint8'",
")",
"_write_to_hdf5",
"(",
"hdf5_file",
",",
"num",
"+",
"offset",
",",
"image_filename",
",",
"image_data",
",",
"class_index",
")",
"pb",
".",
"update",
"(",
"i",
"+",
"1",
")"
] | Fill an HDF5 file with incoming images from a socket.
Parameters
----------
socket : :class:`zmq.Socket`
PULL socket on which to receive images.
hdf5_file : :class:`h5py.File` instance
HDF5 file handle to which to write. Assumes `features`, `targets`
and `filenames` already exist and have first dimension larger than
`sum(images_per_class)`.
num_expected : int
The number of items we expect to be sent over the socket.
shuffle_seed : int or sequence, optional
Seed for a NumPy random number generator that permutes the
images on disk.
offset : int, optional
The offset in the HDF5 datasets at which to start writing
received examples. Defaults to 0. | [
"Fill",
"an",
"HDF5",
"file",
"with",
"incoming",
"images",
"from",
"a",
"socket",
"."
] | 1d6292dc25e3a115544237e392e61bff6631d23c | https://github.com/mila-iqia/fuel/blob/1d6292dc25e3a115544237e392e61bff6631d23c/fuel/converters/ilsvrc2010.py#L283-L316 | train |
mila-iqia/fuel | fuel/converters/ilsvrc2010.py | process_other_set | def process_other_set(hdf5_file, which_set, image_archive, patch_archive,
groundtruth, offset):
"""Process the validation or test set.
Parameters
----------
hdf5_file : :class:`h5py.File` instance
HDF5 file handle to which to write. Assumes `features`, `targets`
and `filenames` already exist and have first dimension larger than
`sum(images_per_class)`.
which_set : str
Which set of images is being processed. One of 'train', 'valid',
'test'. Used for extracting the appropriate images from the patch
archive.
image_archive : str or file-like object
The filename or file-handle for the TAR archive containing images.
patch_archive : str or file-like object
Filename or file handle for the TAR archive of patch images.
groundtruth : iterable
Iterable container containing scalar 0-based class index for each
image, sorted by filename.
offset : int
The offset in the HDF5 datasets at which to start writing.
"""
producer = partial(other_set_producer, image_archive=image_archive,
patch_archive=patch_archive,
groundtruth=groundtruth, which_set=which_set)
consumer = partial(image_consumer, hdf5_file=hdf5_file,
num_expected=len(groundtruth), offset=offset)
producer_consumer(producer, consumer) | python | def process_other_set(hdf5_file, which_set, image_archive, patch_archive,
groundtruth, offset):
"""Process the validation or test set.
Parameters
----------
hdf5_file : :class:`h5py.File` instance
HDF5 file handle to which to write. Assumes `features`, `targets`
and `filenames` already exist and have first dimension larger than
`sum(images_per_class)`.
which_set : str
Which set of images is being processed. One of 'train', 'valid',
'test'. Used for extracting the appropriate images from the patch
archive.
image_archive : str or file-like object
The filename or file-handle for the TAR archive containing images.
patch_archive : str or file-like object
Filename or file handle for the TAR archive of patch images.
groundtruth : iterable
Iterable container containing scalar 0-based class index for each
image, sorted by filename.
offset : int
The offset in the HDF5 datasets at which to start writing.
"""
producer = partial(other_set_producer, image_archive=image_archive,
patch_archive=patch_archive,
groundtruth=groundtruth, which_set=which_set)
consumer = partial(image_consumer, hdf5_file=hdf5_file,
num_expected=len(groundtruth), offset=offset)
producer_consumer(producer, consumer) | [
"def",
"process_other_set",
"(",
"hdf5_file",
",",
"which_set",
",",
"image_archive",
",",
"patch_archive",
",",
"groundtruth",
",",
"offset",
")",
":",
"producer",
"=",
"partial",
"(",
"other_set_producer",
",",
"image_archive",
"=",
"image_archive",
",",
"patch_archive",
"=",
"patch_archive",
",",
"groundtruth",
"=",
"groundtruth",
",",
"which_set",
"=",
"which_set",
")",
"consumer",
"=",
"partial",
"(",
"image_consumer",
",",
"hdf5_file",
"=",
"hdf5_file",
",",
"num_expected",
"=",
"len",
"(",
"groundtruth",
")",
",",
"offset",
"=",
"offset",
")",
"producer_consumer",
"(",
"producer",
",",
"consumer",
")"
] | Process the validation or test set.
Parameters
----------
hdf5_file : :class:`h5py.File` instance
HDF5 file handle to which to write. Assumes `features`, `targets`
and `filenames` already exist and have first dimension larger than
`sum(images_per_class)`.
which_set : str
Which set of images is being processed. One of 'train', 'valid',
'test'. Used for extracting the appropriate images from the patch
archive.
image_archive : str or file-like object
The filename or file-handle for the TAR archive containing images.
patch_archive : str or file-like object
Filename or file handle for the TAR archive of patch images.
groundtruth : iterable
Iterable container containing scalar 0-based class index for each
image, sorted by filename.
offset : int
The offset in the HDF5 datasets at which to start writing. | [
"Process",
"the",
"validation",
"or",
"test",
"set",
"."
] | 1d6292dc25e3a115544237e392e61bff6631d23c | https://github.com/mila-iqia/fuel/blob/1d6292dc25e3a115544237e392e61bff6631d23c/fuel/converters/ilsvrc2010.py#L319-L349 | train |
mila-iqia/fuel | fuel/converters/ilsvrc2010.py | load_from_tar_or_patch | def load_from_tar_or_patch(tar, image_filename, patch_images):
"""Do everything necessary to process an image inside a TAR.
Parameters
----------
tar : `TarFile` instance
The tar from which to read `image_filename`.
image_filename : str
Fully-qualified path inside of `tar` from which to read an
image file.
patch_images : dict
A dictionary containing filenames (without path) of replacements
to be substituted in place of the version of the same file found
in `tar`.
Returns
-------
image_data : bytes
The JPEG bytes representing either the image from the TAR archive
or its replacement from the patch dictionary.
patched : bool
True if the image was retrieved from the patch dictionary. False
if it was retrieved from the TAR file.
"""
patched = True
image_bytes = patch_images.get(os.path.basename(image_filename), None)
if image_bytes is None:
patched = False
try:
image_bytes = tar.extractfile(image_filename).read()
numpy.array(Image.open(io.BytesIO(image_bytes)))
except (IOError, OSError):
with gzip.GzipFile(fileobj=tar.extractfile(image_filename)) as gz:
image_bytes = gz.read()
numpy.array(Image.open(io.BytesIO(image_bytes)))
return image_bytes, patched | python | def load_from_tar_or_patch(tar, image_filename, patch_images):
"""Do everything necessary to process an image inside a TAR.
Parameters
----------
tar : `TarFile` instance
The tar from which to read `image_filename`.
image_filename : str
Fully-qualified path inside of `tar` from which to read an
image file.
patch_images : dict
A dictionary containing filenames (without path) of replacements
to be substituted in place of the version of the same file found
in `tar`.
Returns
-------
image_data : bytes
The JPEG bytes representing either the image from the TAR archive
or its replacement from the patch dictionary.
patched : bool
True if the image was retrieved from the patch dictionary. False
if it was retrieved from the TAR file.
"""
patched = True
image_bytes = patch_images.get(os.path.basename(image_filename), None)
if image_bytes is None:
patched = False
try:
image_bytes = tar.extractfile(image_filename).read()
numpy.array(Image.open(io.BytesIO(image_bytes)))
except (IOError, OSError):
with gzip.GzipFile(fileobj=tar.extractfile(image_filename)) as gz:
image_bytes = gz.read()
numpy.array(Image.open(io.BytesIO(image_bytes)))
return image_bytes, patched | [
"def",
"load_from_tar_or_patch",
"(",
"tar",
",",
"image_filename",
",",
"patch_images",
")",
":",
"patched",
"=",
"True",
"image_bytes",
"=",
"patch_images",
".",
"get",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"image_filename",
")",
",",
"None",
")",
"if",
"image_bytes",
"is",
"None",
":",
"patched",
"=",
"False",
"try",
":",
"image_bytes",
"=",
"tar",
".",
"extractfile",
"(",
"image_filename",
")",
".",
"read",
"(",
")",
"numpy",
".",
"array",
"(",
"Image",
".",
"open",
"(",
"io",
".",
"BytesIO",
"(",
"image_bytes",
")",
")",
")",
"except",
"(",
"IOError",
",",
"OSError",
")",
":",
"with",
"gzip",
".",
"GzipFile",
"(",
"fileobj",
"=",
"tar",
".",
"extractfile",
"(",
"image_filename",
")",
")",
"as",
"gz",
":",
"image_bytes",
"=",
"gz",
".",
"read",
"(",
")",
"numpy",
".",
"array",
"(",
"Image",
".",
"open",
"(",
"io",
".",
"BytesIO",
"(",
"image_bytes",
")",
")",
")",
"return",
"image_bytes",
",",
"patched"
] | Do everything necessary to process an image inside a TAR.
Parameters
----------
tar : `TarFile` instance
The tar from which to read `image_filename`.
image_filename : str
Fully-qualified path inside of `tar` from which to read an
image file.
patch_images : dict
A dictionary containing filenames (without path) of replacements
to be substituted in place of the version of the same file found
in `tar`.
Returns
-------
image_data : bytes
The JPEG bytes representing either the image from the TAR archive
or its replacement from the patch dictionary.
patched : bool
True if the image was retrieved from the patch dictionary. False
if it was retrieved from the TAR file. | [
"Do",
"everything",
"necessary",
"to",
"process",
"an",
"image",
"inside",
"a",
"TAR",
"."
] | 1d6292dc25e3a115544237e392e61bff6631d23c | https://github.com/mila-iqia/fuel/blob/1d6292dc25e3a115544237e392e61bff6631d23c/fuel/converters/ilsvrc2010.py#L390-L426 | train |
mila-iqia/fuel | fuel/converters/ilsvrc2010.py | read_devkit | def read_devkit(f):
"""Read relevant information from the development kit archive.
Parameters
----------
f : str or file-like object
The filename or file-handle for the gzipped TAR archive
containing the ILSVRC2010 development kit.
Returns
-------
synsets : ndarray, 1-dimensional, compound dtype
See :func:`read_metadata_mat_file` for details.
cost_matrix : ndarray, 2-dimensional, uint8
See :func:`read_metadata_mat_file` for details.
raw_valid_groundtruth : ndarray, 1-dimensional, int16
The labels for the ILSVRC2010 validation set,
distributed with the development kit code.
"""
with tar_open(f) as tar:
# Metadata table containing class hierarchy, textual descriptions, etc.
meta_mat = tar.extractfile(DEVKIT_META_PATH)
synsets, cost_matrix = read_metadata_mat_file(meta_mat)
# Raw validation data groundtruth, ILSVRC2010 IDs. Confusingly
# distributed inside the development kit archive.
raw_valid_groundtruth = numpy.loadtxt(tar.extractfile(
DEVKIT_VALID_GROUNDTRUTH_PATH), dtype=numpy.int16)
return synsets, cost_matrix, raw_valid_groundtruth | python | def read_devkit(f):
"""Read relevant information from the development kit archive.
Parameters
----------
f : str or file-like object
The filename or file-handle for the gzipped TAR archive
containing the ILSVRC2010 development kit.
Returns
-------
synsets : ndarray, 1-dimensional, compound dtype
See :func:`read_metadata_mat_file` for details.
cost_matrix : ndarray, 2-dimensional, uint8
See :func:`read_metadata_mat_file` for details.
raw_valid_groundtruth : ndarray, 1-dimensional, int16
The labels for the ILSVRC2010 validation set,
distributed with the development kit code.
"""
with tar_open(f) as tar:
# Metadata table containing class hierarchy, textual descriptions, etc.
meta_mat = tar.extractfile(DEVKIT_META_PATH)
synsets, cost_matrix = read_metadata_mat_file(meta_mat)
# Raw validation data groundtruth, ILSVRC2010 IDs. Confusingly
# distributed inside the development kit archive.
raw_valid_groundtruth = numpy.loadtxt(tar.extractfile(
DEVKIT_VALID_GROUNDTRUTH_PATH), dtype=numpy.int16)
return synsets, cost_matrix, raw_valid_groundtruth | [
"def",
"read_devkit",
"(",
"f",
")",
":",
"with",
"tar_open",
"(",
"f",
")",
"as",
"tar",
":",
"# Metadata table containing class hierarchy, textual descriptions, etc.",
"meta_mat",
"=",
"tar",
".",
"extractfile",
"(",
"DEVKIT_META_PATH",
")",
"synsets",
",",
"cost_matrix",
"=",
"read_metadata_mat_file",
"(",
"meta_mat",
")",
"# Raw validation data groundtruth, ILSVRC2010 IDs. Confusingly",
"# distributed inside the development kit archive.",
"raw_valid_groundtruth",
"=",
"numpy",
".",
"loadtxt",
"(",
"tar",
".",
"extractfile",
"(",
"DEVKIT_VALID_GROUNDTRUTH_PATH",
")",
",",
"dtype",
"=",
"numpy",
".",
"int16",
")",
"return",
"synsets",
",",
"cost_matrix",
",",
"raw_valid_groundtruth"
] | Read relevant information from the development kit archive.
Parameters
----------
f : str or file-like object
The filename or file-handle for the gzipped TAR archive
containing the ILSVRC2010 development kit.
Returns
-------
synsets : ndarray, 1-dimensional, compound dtype
See :func:`read_metadata_mat_file` for details.
cost_matrix : ndarray, 2-dimensional, uint8
See :func:`read_metadata_mat_file` for details.
raw_valid_groundtruth : ndarray, 1-dimensional, int16
The labels for the ILSVRC2010 validation set,
distributed with the development kit code. | [
"Read",
"relevant",
"information",
"from",
"the",
"development",
"kit",
"archive",
"."
] | 1d6292dc25e3a115544237e392e61bff6631d23c | https://github.com/mila-iqia/fuel/blob/1d6292dc25e3a115544237e392e61bff6631d23c/fuel/converters/ilsvrc2010.py#L429-L458 | train |
mila-iqia/fuel | fuel/converters/ilsvrc2010.py | extract_patch_images | def extract_patch_images(f, which_set):
"""Extracts a dict of the "patch images" for ILSVRC2010.
Parameters
----------
f : str or file-like object
The filename or file-handle to the patch images TAR file.
which_set : str
Which set of images to extract. One of 'train', 'valid', 'test'.
Returns
-------
dict
A dictionary contains a mapping of filenames (without path) to a
bytes object containing the replacement image.
Notes
-----
Certain images in the distributed archives are blank, or display
an "image not available" banner. A separate TAR file of
"patch images" is distributed with the corrected versions of
these. It is this archive that this function is intended to read.
"""
if which_set not in ('train', 'valid', 'test'):
raise ValueError('which_set must be one of train, valid, or test')
which_set = 'val' if which_set == 'valid' else which_set
patch_images = {}
with tar_open(f) as tar:
for info_obj in tar:
if not info_obj.name.endswith('.JPEG'):
continue
# Pretty sure that '/' is used for tarfile regardless of
# os.path.sep, but I officially don't care about Windows.
tokens = info_obj.name.split('/')
file_which_set = tokens[-2]
if file_which_set != which_set:
continue
filename = tokens[-1]
patch_images[filename] = tar.extractfile(info_obj.name).read()
return patch_images | python | def extract_patch_images(f, which_set):
"""Extracts a dict of the "patch images" for ILSVRC2010.
Parameters
----------
f : str or file-like object
The filename or file-handle to the patch images TAR file.
which_set : str
Which set of images to extract. One of 'train', 'valid', 'test'.
Returns
-------
dict
A dictionary contains a mapping of filenames (without path) to a
bytes object containing the replacement image.
Notes
-----
Certain images in the distributed archives are blank, or display
an "image not available" banner. A separate TAR file of
"patch images" is distributed with the corrected versions of
these. It is this archive that this function is intended to read.
"""
if which_set not in ('train', 'valid', 'test'):
raise ValueError('which_set must be one of train, valid, or test')
which_set = 'val' if which_set == 'valid' else which_set
patch_images = {}
with tar_open(f) as tar:
for info_obj in tar:
if not info_obj.name.endswith('.JPEG'):
continue
# Pretty sure that '/' is used for tarfile regardless of
# os.path.sep, but I officially don't care about Windows.
tokens = info_obj.name.split('/')
file_which_set = tokens[-2]
if file_which_set != which_set:
continue
filename = tokens[-1]
patch_images[filename] = tar.extractfile(info_obj.name).read()
return patch_images | [
"def",
"extract_patch_images",
"(",
"f",
",",
"which_set",
")",
":",
"if",
"which_set",
"not",
"in",
"(",
"'train'",
",",
"'valid'",
",",
"'test'",
")",
":",
"raise",
"ValueError",
"(",
"'which_set must be one of train, valid, or test'",
")",
"which_set",
"=",
"'val'",
"if",
"which_set",
"==",
"'valid'",
"else",
"which_set",
"patch_images",
"=",
"{",
"}",
"with",
"tar_open",
"(",
"f",
")",
"as",
"tar",
":",
"for",
"info_obj",
"in",
"tar",
":",
"if",
"not",
"info_obj",
".",
"name",
".",
"endswith",
"(",
"'.JPEG'",
")",
":",
"continue",
"# Pretty sure that '/' is used for tarfile regardless of",
"# os.path.sep, but I officially don't care about Windows.",
"tokens",
"=",
"info_obj",
".",
"name",
".",
"split",
"(",
"'/'",
")",
"file_which_set",
"=",
"tokens",
"[",
"-",
"2",
"]",
"if",
"file_which_set",
"!=",
"which_set",
":",
"continue",
"filename",
"=",
"tokens",
"[",
"-",
"1",
"]",
"patch_images",
"[",
"filename",
"]",
"=",
"tar",
".",
"extractfile",
"(",
"info_obj",
".",
"name",
")",
".",
"read",
"(",
")",
"return",
"patch_images"
] | Extracts a dict of the "patch images" for ILSVRC2010.
Parameters
----------
f : str or file-like object
The filename or file-handle to the patch images TAR file.
which_set : str
Which set of images to extract. One of 'train', 'valid', 'test'.
Returns
-------
dict
A dictionary contains a mapping of filenames (without path) to a
bytes object containing the replacement image.
Notes
-----
Certain images in the distributed archives are blank, or display
an "image not available" banner. A separate TAR file of
"patch images" is distributed with the corrected versions of
these. It is this archive that this function is intended to read. | [
"Extracts",
"a",
"dict",
"of",
"the",
"patch",
"images",
"for",
"ILSVRC2010",
"."
] | 1d6292dc25e3a115544237e392e61bff6631d23c | https://github.com/mila-iqia/fuel/blob/1d6292dc25e3a115544237e392e61bff6631d23c/fuel/converters/ilsvrc2010.py#L533-L573 | train |
mila-iqia/fuel | fuel/converters/cifar10.py | convert_cifar10 | def convert_cifar10(directory, output_directory,
output_filename='cifar10.hdf5'):
"""Converts the CIFAR-10 dataset to HDF5.
Converts the CIFAR-10 dataset to an HDF5 dataset compatible with
:class:`fuel.datasets.CIFAR10`. The converted dataset is saved as
'cifar10.hdf5'.
It assumes the existence of the following file:
* `cifar-10-python.tar.gz`
Parameters
----------
directory : str
Directory in which input files reside.
output_directory : str
Directory in which to save the converted dataset.
output_filename : str, optional
Name of the saved dataset. Defaults to 'cifar10.hdf5'.
Returns
-------
output_paths : tuple of str
Single-element tuple containing the path to the converted dataset.
"""
output_path = os.path.join(output_directory, output_filename)
h5file = h5py.File(output_path, mode='w')
input_file = os.path.join(directory, DISTRIBUTION_FILE)
tar_file = tarfile.open(input_file, 'r:gz')
train_batches = []
for batch in range(1, 6):
file = tar_file.extractfile(
'cifar-10-batches-py/data_batch_%d' % batch)
try:
if six.PY3:
array = cPickle.load(file, encoding='latin1')
else:
array = cPickle.load(file)
train_batches.append(array)
finally:
file.close()
train_features = numpy.concatenate(
[batch['data'].reshape(batch['data'].shape[0], 3, 32, 32)
for batch in train_batches])
train_labels = numpy.concatenate(
[numpy.array(batch['labels'], dtype=numpy.uint8)
for batch in train_batches])
train_labels = numpy.expand_dims(train_labels, 1)
file = tar_file.extractfile('cifar-10-batches-py/test_batch')
try:
if six.PY3:
test = cPickle.load(file, encoding='latin1')
else:
test = cPickle.load(file)
finally:
file.close()
test_features = test['data'].reshape(test['data'].shape[0],
3, 32, 32)
test_labels = numpy.array(test['labels'], dtype=numpy.uint8)
test_labels = numpy.expand_dims(test_labels, 1)
data = (('train', 'features', train_features),
('train', 'targets', train_labels),
('test', 'features', test_features),
('test', 'targets', test_labels))
fill_hdf5_file(h5file, data)
h5file['features'].dims[0].label = 'batch'
h5file['features'].dims[1].label = 'channel'
h5file['features'].dims[2].label = 'height'
h5file['features'].dims[3].label = 'width'
h5file['targets'].dims[0].label = 'batch'
h5file['targets'].dims[1].label = 'index'
h5file.flush()
h5file.close()
return (output_path,) | python | def convert_cifar10(directory, output_directory,
output_filename='cifar10.hdf5'):
"""Converts the CIFAR-10 dataset to HDF5.
Converts the CIFAR-10 dataset to an HDF5 dataset compatible with
:class:`fuel.datasets.CIFAR10`. The converted dataset is saved as
'cifar10.hdf5'.
It assumes the existence of the following file:
* `cifar-10-python.tar.gz`
Parameters
----------
directory : str
Directory in which input files reside.
output_directory : str
Directory in which to save the converted dataset.
output_filename : str, optional
Name of the saved dataset. Defaults to 'cifar10.hdf5'.
Returns
-------
output_paths : tuple of str
Single-element tuple containing the path to the converted dataset.
"""
output_path = os.path.join(output_directory, output_filename)
h5file = h5py.File(output_path, mode='w')
input_file = os.path.join(directory, DISTRIBUTION_FILE)
tar_file = tarfile.open(input_file, 'r:gz')
train_batches = []
for batch in range(1, 6):
file = tar_file.extractfile(
'cifar-10-batches-py/data_batch_%d' % batch)
try:
if six.PY3:
array = cPickle.load(file, encoding='latin1')
else:
array = cPickle.load(file)
train_batches.append(array)
finally:
file.close()
train_features = numpy.concatenate(
[batch['data'].reshape(batch['data'].shape[0], 3, 32, 32)
for batch in train_batches])
train_labels = numpy.concatenate(
[numpy.array(batch['labels'], dtype=numpy.uint8)
for batch in train_batches])
train_labels = numpy.expand_dims(train_labels, 1)
file = tar_file.extractfile('cifar-10-batches-py/test_batch')
try:
if six.PY3:
test = cPickle.load(file, encoding='latin1')
else:
test = cPickle.load(file)
finally:
file.close()
test_features = test['data'].reshape(test['data'].shape[0],
3, 32, 32)
test_labels = numpy.array(test['labels'], dtype=numpy.uint8)
test_labels = numpy.expand_dims(test_labels, 1)
data = (('train', 'features', train_features),
('train', 'targets', train_labels),
('test', 'features', test_features),
('test', 'targets', test_labels))
fill_hdf5_file(h5file, data)
h5file['features'].dims[0].label = 'batch'
h5file['features'].dims[1].label = 'channel'
h5file['features'].dims[2].label = 'height'
h5file['features'].dims[3].label = 'width'
h5file['targets'].dims[0].label = 'batch'
h5file['targets'].dims[1].label = 'index'
h5file.flush()
h5file.close()
return (output_path,) | [
"def",
"convert_cifar10",
"(",
"directory",
",",
"output_directory",
",",
"output_filename",
"=",
"'cifar10.hdf5'",
")",
":",
"output_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"output_directory",
",",
"output_filename",
")",
"h5file",
"=",
"h5py",
".",
"File",
"(",
"output_path",
",",
"mode",
"=",
"'w'",
")",
"input_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"DISTRIBUTION_FILE",
")",
"tar_file",
"=",
"tarfile",
".",
"open",
"(",
"input_file",
",",
"'r:gz'",
")",
"train_batches",
"=",
"[",
"]",
"for",
"batch",
"in",
"range",
"(",
"1",
",",
"6",
")",
":",
"file",
"=",
"tar_file",
".",
"extractfile",
"(",
"'cifar-10-batches-py/data_batch_%d'",
"%",
"batch",
")",
"try",
":",
"if",
"six",
".",
"PY3",
":",
"array",
"=",
"cPickle",
".",
"load",
"(",
"file",
",",
"encoding",
"=",
"'latin1'",
")",
"else",
":",
"array",
"=",
"cPickle",
".",
"load",
"(",
"file",
")",
"train_batches",
".",
"append",
"(",
"array",
")",
"finally",
":",
"file",
".",
"close",
"(",
")",
"train_features",
"=",
"numpy",
".",
"concatenate",
"(",
"[",
"batch",
"[",
"'data'",
"]",
".",
"reshape",
"(",
"batch",
"[",
"'data'",
"]",
".",
"shape",
"[",
"0",
"]",
",",
"3",
",",
"32",
",",
"32",
")",
"for",
"batch",
"in",
"train_batches",
"]",
")",
"train_labels",
"=",
"numpy",
".",
"concatenate",
"(",
"[",
"numpy",
".",
"array",
"(",
"batch",
"[",
"'labels'",
"]",
",",
"dtype",
"=",
"numpy",
".",
"uint8",
")",
"for",
"batch",
"in",
"train_batches",
"]",
")",
"train_labels",
"=",
"numpy",
".",
"expand_dims",
"(",
"train_labels",
",",
"1",
")",
"file",
"=",
"tar_file",
".",
"extractfile",
"(",
"'cifar-10-batches-py/test_batch'",
")",
"try",
":",
"if",
"six",
".",
"PY3",
":",
"test",
"=",
"cPickle",
".",
"load",
"(",
"file",
",",
"encoding",
"=",
"'latin1'",
")",
"else",
":",
"test",
"=",
"cPickle",
".",
"load",
"(",
"file",
")",
"finally",
":",
"file",
".",
"close",
"(",
")",
"test_features",
"=",
"test",
"[",
"'data'",
"]",
".",
"reshape",
"(",
"test",
"[",
"'data'",
"]",
".",
"shape",
"[",
"0",
"]",
",",
"3",
",",
"32",
",",
"32",
")",
"test_labels",
"=",
"numpy",
".",
"array",
"(",
"test",
"[",
"'labels'",
"]",
",",
"dtype",
"=",
"numpy",
".",
"uint8",
")",
"test_labels",
"=",
"numpy",
".",
"expand_dims",
"(",
"test_labels",
",",
"1",
")",
"data",
"=",
"(",
"(",
"'train'",
",",
"'features'",
",",
"train_features",
")",
",",
"(",
"'train'",
",",
"'targets'",
",",
"train_labels",
")",
",",
"(",
"'test'",
",",
"'features'",
",",
"test_features",
")",
",",
"(",
"'test'",
",",
"'targets'",
",",
"test_labels",
")",
")",
"fill_hdf5_file",
"(",
"h5file",
",",
"data",
")",
"h5file",
"[",
"'features'",
"]",
".",
"dims",
"[",
"0",
"]",
".",
"label",
"=",
"'batch'",
"h5file",
"[",
"'features'",
"]",
".",
"dims",
"[",
"1",
"]",
".",
"label",
"=",
"'channel'",
"h5file",
"[",
"'features'",
"]",
".",
"dims",
"[",
"2",
"]",
".",
"label",
"=",
"'height'",
"h5file",
"[",
"'features'",
"]",
".",
"dims",
"[",
"3",
"]",
".",
"label",
"=",
"'width'",
"h5file",
"[",
"'targets'",
"]",
".",
"dims",
"[",
"0",
"]",
".",
"label",
"=",
"'batch'",
"h5file",
"[",
"'targets'",
"]",
".",
"dims",
"[",
"1",
"]",
".",
"label",
"=",
"'index'",
"h5file",
".",
"flush",
"(",
")",
"h5file",
".",
"close",
"(",
")",
"return",
"(",
"output_path",
",",
")"
] | Converts the CIFAR-10 dataset to HDF5.
Converts the CIFAR-10 dataset to an HDF5 dataset compatible with
:class:`fuel.datasets.CIFAR10`. The converted dataset is saved as
'cifar10.hdf5'.
It assumes the existence of the following file:
* `cifar-10-python.tar.gz`
Parameters
----------
directory : str
Directory in which input files reside.
output_directory : str
Directory in which to save the converted dataset.
output_filename : str, optional
Name of the saved dataset. Defaults to 'cifar10.hdf5'.
Returns
-------
output_paths : tuple of str
Single-element tuple containing the path to the converted dataset. | [
"Converts",
"the",
"CIFAR",
"-",
"10",
"dataset",
"to",
"HDF5",
"."
] | 1d6292dc25e3a115544237e392e61bff6631d23c | https://github.com/mila-iqia/fuel/blob/1d6292dc25e3a115544237e392e61bff6631d23c/fuel/converters/cifar10.py#L15-L97 | train |
mila-iqia/fuel | fuel/converters/base.py | check_exists | def check_exists(required_files):
"""Decorator that checks if required files exist before running.
Parameters
----------
required_files : list of str
A list of strings indicating the filenames of regular files
(not directories) that should be found in the input directory
(which is the first argument to the wrapped function).
Returns
-------
wrapper : function
A function that takes a function and returns a wrapped function.
The function returned by `wrapper` will include input file
existence verification.
Notes
-----
Assumes that the directory in which to find the input files is
provided as the first argument, with the argument name `directory`.
"""
def function_wrapper(f):
@wraps(f)
def wrapped(directory, *args, **kwargs):
missing = []
for filename in required_files:
if not os.path.isfile(os.path.join(directory, filename)):
missing.append(filename)
if len(missing) > 0:
raise MissingInputFiles('Required files missing', missing)
return f(directory, *args, **kwargs)
return wrapped
return function_wrapper | python | def check_exists(required_files):
"""Decorator that checks if required files exist before running.
Parameters
----------
required_files : list of str
A list of strings indicating the filenames of regular files
(not directories) that should be found in the input directory
(which is the first argument to the wrapped function).
Returns
-------
wrapper : function
A function that takes a function and returns a wrapped function.
The function returned by `wrapper` will include input file
existence verification.
Notes
-----
Assumes that the directory in which to find the input files is
provided as the first argument, with the argument name `directory`.
"""
def function_wrapper(f):
@wraps(f)
def wrapped(directory, *args, **kwargs):
missing = []
for filename in required_files:
if not os.path.isfile(os.path.join(directory, filename)):
missing.append(filename)
if len(missing) > 0:
raise MissingInputFiles('Required files missing', missing)
return f(directory, *args, **kwargs)
return wrapped
return function_wrapper | [
"def",
"check_exists",
"(",
"required_files",
")",
":",
"def",
"function_wrapper",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"wrapped",
"(",
"directory",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"missing",
"=",
"[",
"]",
"for",
"filename",
"in",
"required_files",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"filename",
")",
")",
":",
"missing",
".",
"append",
"(",
"filename",
")",
"if",
"len",
"(",
"missing",
")",
">",
"0",
":",
"raise",
"MissingInputFiles",
"(",
"'Required files missing'",
",",
"missing",
")",
"return",
"f",
"(",
"directory",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"wrapped",
"return",
"function_wrapper"
] | Decorator that checks if required files exist before running.
Parameters
----------
required_files : list of str
A list of strings indicating the filenames of regular files
(not directories) that should be found in the input directory
(which is the first argument to the wrapped function).
Returns
-------
wrapper : function
A function that takes a function and returns a wrapped function.
The function returned by `wrapper` will include input file
existence verification.
Notes
-----
Assumes that the directory in which to find the input files is
provided as the first argument, with the argument name `directory`. | [
"Decorator",
"that",
"checks",
"if",
"required",
"files",
"exist",
"before",
"running",
"."
] | 1d6292dc25e3a115544237e392e61bff6631d23c | https://github.com/mila-iqia/fuel/blob/1d6292dc25e3a115544237e392e61bff6631d23c/fuel/converters/base.py#L13-L47 | train |
mila-iqia/fuel | fuel/converters/base.py | fill_hdf5_file | def fill_hdf5_file(h5file, data):
"""Fills an HDF5 file in a H5PYDataset-compatible manner.
Parameters
----------
h5file : :class:`h5py.File`
File handle for an HDF5 file.
data : tuple of tuple
One element per split/source pair. Each element consists of a
tuple of (split_name, source_name, data_array, comment), where
* 'split_name' is a string identifier for the split name
* 'source_name' is a string identifier for the source name
* 'data_array' is a :class:`numpy.ndarray` containing the data
for this split/source pair
* 'comment' is a comment string for the split/source pair
The 'comment' element can optionally be omitted.
"""
# Check that all sources for a split have the same length
split_names = set(split_tuple[0] for split_tuple in data)
for name in split_names:
lengths = [len(split_tuple[2]) for split_tuple in data
if split_tuple[0] == name]
if not all(le == lengths[0] for le in lengths):
raise ValueError("split '{}' has sources that ".format(name) +
"vary in length")
# Initialize split dictionary
split_dict = dict([(split_name, {}) for split_name in split_names])
# Compute total source lengths and check that splits have the same dtype
# across a source
source_names = set(split_tuple[1] for split_tuple in data)
for name in source_names:
splits = [s for s in data if s[1] == name]
indices = numpy.cumsum([0] + [len(s[2]) for s in splits])
if not all(s[2].dtype == splits[0][2].dtype for s in splits):
raise ValueError("source '{}' has splits that ".format(name) +
"vary in dtype")
if not all(s[2].shape[1:] == splits[0][2].shape[1:] for s in splits):
raise ValueError("source '{}' has splits that ".format(name) +
"vary in shapes")
dataset = h5file.create_dataset(
name, (sum(len(s[2]) for s in splits),) + splits[0][2].shape[1:],
dtype=splits[0][2].dtype)
dataset[...] = numpy.concatenate([s[2] for s in splits], axis=0)
for i, j, s in zip(indices[:-1], indices[1:], splits):
if len(s) == 4:
split_dict[s[0]][name] = (i, j, None, s[3])
else:
split_dict[s[0]][name] = (i, j)
h5file.attrs['split'] = H5PYDataset.create_split_array(split_dict) | python | def fill_hdf5_file(h5file, data):
"""Fills an HDF5 file in a H5PYDataset-compatible manner.
Parameters
----------
h5file : :class:`h5py.File`
File handle for an HDF5 file.
data : tuple of tuple
One element per split/source pair. Each element consists of a
tuple of (split_name, source_name, data_array, comment), where
* 'split_name' is a string identifier for the split name
* 'source_name' is a string identifier for the source name
* 'data_array' is a :class:`numpy.ndarray` containing the data
for this split/source pair
* 'comment' is a comment string for the split/source pair
The 'comment' element can optionally be omitted.
"""
# Check that all sources for a split have the same length
split_names = set(split_tuple[0] for split_tuple in data)
for name in split_names:
lengths = [len(split_tuple[2]) for split_tuple in data
if split_tuple[0] == name]
if not all(le == lengths[0] for le in lengths):
raise ValueError("split '{}' has sources that ".format(name) +
"vary in length")
# Initialize split dictionary
split_dict = dict([(split_name, {}) for split_name in split_names])
# Compute total source lengths and check that splits have the same dtype
# across a source
source_names = set(split_tuple[1] for split_tuple in data)
for name in source_names:
splits = [s for s in data if s[1] == name]
indices = numpy.cumsum([0] + [len(s[2]) for s in splits])
if not all(s[2].dtype == splits[0][2].dtype for s in splits):
raise ValueError("source '{}' has splits that ".format(name) +
"vary in dtype")
if not all(s[2].shape[1:] == splits[0][2].shape[1:] for s in splits):
raise ValueError("source '{}' has splits that ".format(name) +
"vary in shapes")
dataset = h5file.create_dataset(
name, (sum(len(s[2]) for s in splits),) + splits[0][2].shape[1:],
dtype=splits[0][2].dtype)
dataset[...] = numpy.concatenate([s[2] for s in splits], axis=0)
for i, j, s in zip(indices[:-1], indices[1:], splits):
if len(s) == 4:
split_dict[s[0]][name] = (i, j, None, s[3])
else:
split_dict[s[0]][name] = (i, j)
h5file.attrs['split'] = H5PYDataset.create_split_array(split_dict) | [
"def",
"fill_hdf5_file",
"(",
"h5file",
",",
"data",
")",
":",
"# Check that all sources for a split have the same length",
"split_names",
"=",
"set",
"(",
"split_tuple",
"[",
"0",
"]",
"for",
"split_tuple",
"in",
"data",
")",
"for",
"name",
"in",
"split_names",
":",
"lengths",
"=",
"[",
"len",
"(",
"split_tuple",
"[",
"2",
"]",
")",
"for",
"split_tuple",
"in",
"data",
"if",
"split_tuple",
"[",
"0",
"]",
"==",
"name",
"]",
"if",
"not",
"all",
"(",
"le",
"==",
"lengths",
"[",
"0",
"]",
"for",
"le",
"in",
"lengths",
")",
":",
"raise",
"ValueError",
"(",
"\"split '{}' has sources that \"",
".",
"format",
"(",
"name",
")",
"+",
"\"vary in length\"",
")",
"# Initialize split dictionary",
"split_dict",
"=",
"dict",
"(",
"[",
"(",
"split_name",
",",
"{",
"}",
")",
"for",
"split_name",
"in",
"split_names",
"]",
")",
"# Compute total source lengths and check that splits have the same dtype",
"# across a source",
"source_names",
"=",
"set",
"(",
"split_tuple",
"[",
"1",
"]",
"for",
"split_tuple",
"in",
"data",
")",
"for",
"name",
"in",
"source_names",
":",
"splits",
"=",
"[",
"s",
"for",
"s",
"in",
"data",
"if",
"s",
"[",
"1",
"]",
"==",
"name",
"]",
"indices",
"=",
"numpy",
".",
"cumsum",
"(",
"[",
"0",
"]",
"+",
"[",
"len",
"(",
"s",
"[",
"2",
"]",
")",
"for",
"s",
"in",
"splits",
"]",
")",
"if",
"not",
"all",
"(",
"s",
"[",
"2",
"]",
".",
"dtype",
"==",
"splits",
"[",
"0",
"]",
"[",
"2",
"]",
".",
"dtype",
"for",
"s",
"in",
"splits",
")",
":",
"raise",
"ValueError",
"(",
"\"source '{}' has splits that \"",
".",
"format",
"(",
"name",
")",
"+",
"\"vary in dtype\"",
")",
"if",
"not",
"all",
"(",
"s",
"[",
"2",
"]",
".",
"shape",
"[",
"1",
":",
"]",
"==",
"splits",
"[",
"0",
"]",
"[",
"2",
"]",
".",
"shape",
"[",
"1",
":",
"]",
"for",
"s",
"in",
"splits",
")",
":",
"raise",
"ValueError",
"(",
"\"source '{}' has splits that \"",
".",
"format",
"(",
"name",
")",
"+",
"\"vary in shapes\"",
")",
"dataset",
"=",
"h5file",
".",
"create_dataset",
"(",
"name",
",",
"(",
"sum",
"(",
"len",
"(",
"s",
"[",
"2",
"]",
")",
"for",
"s",
"in",
"splits",
")",
",",
")",
"+",
"splits",
"[",
"0",
"]",
"[",
"2",
"]",
".",
"shape",
"[",
"1",
":",
"]",
",",
"dtype",
"=",
"splits",
"[",
"0",
"]",
"[",
"2",
"]",
".",
"dtype",
")",
"dataset",
"[",
"...",
"]",
"=",
"numpy",
".",
"concatenate",
"(",
"[",
"s",
"[",
"2",
"]",
"for",
"s",
"in",
"splits",
"]",
",",
"axis",
"=",
"0",
")",
"for",
"i",
",",
"j",
",",
"s",
"in",
"zip",
"(",
"indices",
"[",
":",
"-",
"1",
"]",
",",
"indices",
"[",
"1",
":",
"]",
",",
"splits",
")",
":",
"if",
"len",
"(",
"s",
")",
"==",
"4",
":",
"split_dict",
"[",
"s",
"[",
"0",
"]",
"]",
"[",
"name",
"]",
"=",
"(",
"i",
",",
"j",
",",
"None",
",",
"s",
"[",
"3",
"]",
")",
"else",
":",
"split_dict",
"[",
"s",
"[",
"0",
"]",
"]",
"[",
"name",
"]",
"=",
"(",
"i",
",",
"j",
")",
"h5file",
".",
"attrs",
"[",
"'split'",
"]",
"=",
"H5PYDataset",
".",
"create_split_array",
"(",
"split_dict",
")"
] | Fills an HDF5 file in a H5PYDataset-compatible manner.
Parameters
----------
h5file : :class:`h5py.File`
File handle for an HDF5 file.
data : tuple of tuple
One element per split/source pair. Each element consists of a
tuple of (split_name, source_name, data_array, comment), where
* 'split_name' is a string identifier for the split name
* 'source_name' is a string identifier for the source name
* 'data_array' is a :class:`numpy.ndarray` containing the data
for this split/source pair
* 'comment' is a comment string for the split/source pair
The 'comment' element can optionally be omitted. | [
"Fills",
"an",
"HDF5",
"file",
"in",
"a",
"H5PYDataset",
"-",
"compatible",
"manner",
"."
] | 1d6292dc25e3a115544237e392e61bff6631d23c | https://github.com/mila-iqia/fuel/blob/1d6292dc25e3a115544237e392e61bff6631d23c/fuel/converters/base.py#L50-L103 | train |
mila-iqia/fuel | fuel/converters/base.py | progress_bar | def progress_bar(name, maxval, prefix='Converting'):
"""Manages a progress bar for a conversion.
Parameters
----------
name : str
Name of the file being converted.
maxval : int
Total number of steps for the conversion.
"""
widgets = ['{} {}: '.format(prefix, name), Percentage(), ' ',
Bar(marker='=', left='[', right=']'), ' ', ETA()]
bar = ProgressBar(widgets=widgets, max_value=maxval, fd=sys.stdout).start()
try:
yield bar
finally:
bar.update(maxval)
bar.finish() | python | def progress_bar(name, maxval, prefix='Converting'):
"""Manages a progress bar for a conversion.
Parameters
----------
name : str
Name of the file being converted.
maxval : int
Total number of steps for the conversion.
"""
widgets = ['{} {}: '.format(prefix, name), Percentage(), ' ',
Bar(marker='=', left='[', right=']'), ' ', ETA()]
bar = ProgressBar(widgets=widgets, max_value=maxval, fd=sys.stdout).start()
try:
yield bar
finally:
bar.update(maxval)
bar.finish() | [
"def",
"progress_bar",
"(",
"name",
",",
"maxval",
",",
"prefix",
"=",
"'Converting'",
")",
":",
"widgets",
"=",
"[",
"'{} {}: '",
".",
"format",
"(",
"prefix",
",",
"name",
")",
",",
"Percentage",
"(",
")",
",",
"' '",
",",
"Bar",
"(",
"marker",
"=",
"'='",
",",
"left",
"=",
"'['",
",",
"right",
"=",
"']'",
")",
",",
"' '",
",",
"ETA",
"(",
")",
"]",
"bar",
"=",
"ProgressBar",
"(",
"widgets",
"=",
"widgets",
",",
"max_value",
"=",
"maxval",
",",
"fd",
"=",
"sys",
".",
"stdout",
")",
".",
"start",
"(",
")",
"try",
":",
"yield",
"bar",
"finally",
":",
"bar",
".",
"update",
"(",
"maxval",
")",
"bar",
".",
"finish",
"(",
")"
] | Manages a progress bar for a conversion.
Parameters
----------
name : str
Name of the file being converted.
maxval : int
Total number of steps for the conversion. | [
"Manages",
"a",
"progress",
"bar",
"for",
"a",
"conversion",
"."
] | 1d6292dc25e3a115544237e392e61bff6631d23c | https://github.com/mila-iqia/fuel/blob/1d6292dc25e3a115544237e392e61bff6631d23c/fuel/converters/base.py#L107-L125 | train |
mila-iqia/fuel | fuel/converters/iris.py | convert_iris | def convert_iris(directory, output_directory, output_filename='iris.hdf5'):
"""Convert the Iris dataset to HDF5.
Converts the Iris dataset to an HDF5 dataset compatible with
:class:`fuel.datasets.Iris`. The converted dataset is
saved as 'iris.hdf5'.
This method assumes the existence of the file `iris.data`.
Parameters
----------
directory : str
Directory in which input files reside.
output_directory : str
Directory in which to save the converted dataset.
output_filename : str, optional
Name of the saved dataset. Defaults to `None`, in which case a name
based on `dtype` will be used.
Returns
-------
output_paths : tuple of str
Single-element tuple containing the path to the converted dataset.
"""
classes = {b'Iris-setosa': 0, b'Iris-versicolor': 1, b'Iris-virginica': 2}
data = numpy.loadtxt(
os.path.join(directory, 'iris.data'),
converters={4: lambda x: classes[x]},
delimiter=',')
features = data[:, :-1].astype('float32')
targets = data[:, -1].astype('uint8').reshape((-1, 1))
data = (('all', 'features', features),
('all', 'targets', targets))
output_path = os.path.join(output_directory, output_filename)
h5file = h5py.File(output_path, mode='w')
fill_hdf5_file(h5file, data)
h5file['features'].dims[0].label = 'batch'
h5file['features'].dims[1].label = 'feature'
h5file['targets'].dims[0].label = 'batch'
h5file['targets'].dims[1].label = 'index'
h5file.flush()
h5file.close()
return (output_path,) | python | def convert_iris(directory, output_directory, output_filename='iris.hdf5'):
"""Convert the Iris dataset to HDF5.
Converts the Iris dataset to an HDF5 dataset compatible with
:class:`fuel.datasets.Iris`. The converted dataset is
saved as 'iris.hdf5'.
This method assumes the existence of the file `iris.data`.
Parameters
----------
directory : str
Directory in which input files reside.
output_directory : str
Directory in which to save the converted dataset.
output_filename : str, optional
Name of the saved dataset. Defaults to `None`, in which case a name
based on `dtype` will be used.
Returns
-------
output_paths : tuple of str
Single-element tuple containing the path to the converted dataset.
"""
classes = {b'Iris-setosa': 0, b'Iris-versicolor': 1, b'Iris-virginica': 2}
data = numpy.loadtxt(
os.path.join(directory, 'iris.data'),
converters={4: lambda x: classes[x]},
delimiter=',')
features = data[:, :-1].astype('float32')
targets = data[:, -1].astype('uint8').reshape((-1, 1))
data = (('all', 'features', features),
('all', 'targets', targets))
output_path = os.path.join(output_directory, output_filename)
h5file = h5py.File(output_path, mode='w')
fill_hdf5_file(h5file, data)
h5file['features'].dims[0].label = 'batch'
h5file['features'].dims[1].label = 'feature'
h5file['targets'].dims[0].label = 'batch'
h5file['targets'].dims[1].label = 'index'
h5file.flush()
h5file.close()
return (output_path,) | [
"def",
"convert_iris",
"(",
"directory",
",",
"output_directory",
",",
"output_filename",
"=",
"'iris.hdf5'",
")",
":",
"classes",
"=",
"{",
"b'Iris-setosa'",
":",
"0",
",",
"b'Iris-versicolor'",
":",
"1",
",",
"b'Iris-virginica'",
":",
"2",
"}",
"data",
"=",
"numpy",
".",
"loadtxt",
"(",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"'iris.data'",
")",
",",
"converters",
"=",
"{",
"4",
":",
"lambda",
"x",
":",
"classes",
"[",
"x",
"]",
"}",
",",
"delimiter",
"=",
"','",
")",
"features",
"=",
"data",
"[",
":",
",",
":",
"-",
"1",
"]",
".",
"astype",
"(",
"'float32'",
")",
"targets",
"=",
"data",
"[",
":",
",",
"-",
"1",
"]",
".",
"astype",
"(",
"'uint8'",
")",
".",
"reshape",
"(",
"(",
"-",
"1",
",",
"1",
")",
")",
"data",
"=",
"(",
"(",
"'all'",
",",
"'features'",
",",
"features",
")",
",",
"(",
"'all'",
",",
"'targets'",
",",
"targets",
")",
")",
"output_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"output_directory",
",",
"output_filename",
")",
"h5file",
"=",
"h5py",
".",
"File",
"(",
"output_path",
",",
"mode",
"=",
"'w'",
")",
"fill_hdf5_file",
"(",
"h5file",
",",
"data",
")",
"h5file",
"[",
"'features'",
"]",
".",
"dims",
"[",
"0",
"]",
".",
"label",
"=",
"'batch'",
"h5file",
"[",
"'features'",
"]",
".",
"dims",
"[",
"1",
"]",
".",
"label",
"=",
"'feature'",
"h5file",
"[",
"'targets'",
"]",
".",
"dims",
"[",
"0",
"]",
".",
"label",
"=",
"'batch'",
"h5file",
"[",
"'targets'",
"]",
".",
"dims",
"[",
"1",
"]",
".",
"label",
"=",
"'index'",
"h5file",
".",
"flush",
"(",
")",
"h5file",
".",
"close",
"(",
")",
"return",
"(",
"output_path",
",",
")"
] | Convert the Iris dataset to HDF5.
Converts the Iris dataset to an HDF5 dataset compatible with
:class:`fuel.datasets.Iris`. The converted dataset is
saved as 'iris.hdf5'.
This method assumes the existence of the file `iris.data`.
Parameters
----------
directory : str
Directory in which input files reside.
output_directory : str
Directory in which to save the converted dataset.
output_filename : str, optional
Name of the saved dataset. Defaults to `None`, in which case a name
based on `dtype` will be used.
Returns
-------
output_paths : tuple of str
Single-element tuple containing the path to the converted dataset. | [
"Convert",
"the",
"Iris",
"dataset",
"to",
"HDF5",
"."
] | 1d6292dc25e3a115544237e392e61bff6631d23c | https://github.com/mila-iqia/fuel/blob/1d6292dc25e3a115544237e392e61bff6631d23c/fuel/converters/iris.py#L9-L54 | train |
mila-iqia/fuel | fuel/downloaders/ilsvrc2012.py | fill_subparser | def fill_subparser(subparser):
"""Sets up a subparser to download the ILSVRC2012 dataset files.
Note that you will need to use `--url-prefix` to download the
non-public files (namely, the TARs of images). This is a single
prefix that is common to all distributed files, which you can
obtain by registering at the ImageNet website [DOWNLOAD].
Note that these files are quite large and you may be better off
simply downloading them separately and running ``fuel-convert``.
.. [DOWNLOAD] http://www.image-net.org/download-images
Parameters
----------
subparser : :class:`argparse.ArgumentParser`
Subparser handling the `ilsvrc2012` command.
"""
urls = ([None] * len(ALL_FILES))
filenames = list(ALL_FILES)
subparser.set_defaults(urls=urls, filenames=filenames)
subparser.add_argument('-P', '--url-prefix', type=str, default=None,
help="URL prefix to prepend to the filenames of "
"non-public files, in order to download them. "
"Be sure to include the trailing slash.")
return default_downloader | python | def fill_subparser(subparser):
"""Sets up a subparser to download the ILSVRC2012 dataset files.
Note that you will need to use `--url-prefix` to download the
non-public files (namely, the TARs of images). This is a single
prefix that is common to all distributed files, which you can
obtain by registering at the ImageNet website [DOWNLOAD].
Note that these files are quite large and you may be better off
simply downloading them separately and running ``fuel-convert``.
.. [DOWNLOAD] http://www.image-net.org/download-images
Parameters
----------
subparser : :class:`argparse.ArgumentParser`
Subparser handling the `ilsvrc2012` command.
"""
urls = ([None] * len(ALL_FILES))
filenames = list(ALL_FILES)
subparser.set_defaults(urls=urls, filenames=filenames)
subparser.add_argument('-P', '--url-prefix', type=str, default=None,
help="URL prefix to prepend to the filenames of "
"non-public files, in order to download them. "
"Be sure to include the trailing slash.")
return default_downloader | [
"def",
"fill_subparser",
"(",
"subparser",
")",
":",
"urls",
"=",
"(",
"[",
"None",
"]",
"*",
"len",
"(",
"ALL_FILES",
")",
")",
"filenames",
"=",
"list",
"(",
"ALL_FILES",
")",
"subparser",
".",
"set_defaults",
"(",
"urls",
"=",
"urls",
",",
"filenames",
"=",
"filenames",
")",
"subparser",
".",
"add_argument",
"(",
"'-P'",
",",
"'--url-prefix'",
",",
"type",
"=",
"str",
",",
"default",
"=",
"None",
",",
"help",
"=",
"\"URL prefix to prepend to the filenames of \"",
"\"non-public files, in order to download them. \"",
"\"Be sure to include the trailing slash.\"",
")",
"return",
"default_downloader"
] | Sets up a subparser to download the ILSVRC2012 dataset files.
Note that you will need to use `--url-prefix` to download the
non-public files (namely, the TARs of images). This is a single
prefix that is common to all distributed files, which you can
obtain by registering at the ImageNet website [DOWNLOAD].
Note that these files are quite large and you may be better off
simply downloading them separately and running ``fuel-convert``.
.. [DOWNLOAD] http://www.image-net.org/download-images
Parameters
----------
subparser : :class:`argparse.ArgumentParser`
Subparser handling the `ilsvrc2012` command. | [
"Sets",
"up",
"a",
"subparser",
"to",
"download",
"the",
"ILSVRC2012",
"dataset",
"files",
"."
] | 1d6292dc25e3a115544237e392e61bff6631d23c | https://github.com/mila-iqia/fuel/blob/1d6292dc25e3a115544237e392e61bff6631d23c/fuel/downloaders/ilsvrc2012.py#L5-L32 | train |
mila-iqia/fuel | fuel/transformers/sequences.py | Window._get_target_index | def _get_target_index(self):
"""Return the index where the target window starts."""
return (self.index + self.source_window * (not self.overlapping) +
self.offset) | python | def _get_target_index(self):
"""Return the index where the target window starts."""
return (self.index + self.source_window * (not self.overlapping) +
self.offset) | [
"def",
"_get_target_index",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"index",
"+",
"self",
".",
"source_window",
"*",
"(",
"not",
"self",
".",
"overlapping",
")",
"+",
"self",
".",
"offset",
")"
] | Return the index where the target window starts. | [
"Return",
"the",
"index",
"where",
"the",
"target",
"window",
"starts",
"."
] | 1d6292dc25e3a115544237e392e61bff6631d23c | https://github.com/mila-iqia/fuel/blob/1d6292dc25e3a115544237e392e61bff6631d23c/fuel/transformers/sequences.py#L66-L69 | train |
mila-iqia/fuel | fuel/transformers/sequences.py | Window._get_end_index | def _get_end_index(self):
"""Return the end of both windows."""
return max(self.index + self.source_window,
self._get_target_index() + self.target_window) | python | def _get_end_index(self):
"""Return the end of both windows."""
return max(self.index + self.source_window,
self._get_target_index() + self.target_window) | [
"def",
"_get_end_index",
"(",
"self",
")",
":",
"return",
"max",
"(",
"self",
".",
"index",
"+",
"self",
".",
"source_window",
",",
"self",
".",
"_get_target_index",
"(",
")",
"+",
"self",
".",
"target_window",
")"
] | Return the end of both windows. | [
"Return",
"the",
"end",
"of",
"both",
"windows",
"."
] | 1d6292dc25e3a115544237e392e61bff6631d23c | https://github.com/mila-iqia/fuel/blob/1d6292dc25e3a115544237e392e61bff6631d23c/fuel/transformers/sequences.py#L71-L74 | train |
mila-iqia/fuel | fuel/converters/svhn.py | convert_svhn | def convert_svhn(which_format, directory, output_directory,
output_filename=None):
"""Converts the SVHN dataset to HDF5.
Converts the SVHN dataset [SVHN] to an HDF5 dataset compatible
with :class:`fuel.datasets.SVHN`. The converted dataset is
saved as 'svhn_format_1.hdf5' or 'svhn_format_2.hdf5', depending
on the `which_format` argument.
.. [SVHN] Yuval Netzer, Tao Wang, Adam Coates, Alessandro Bissacco,
Bo Wu, Andrew Y. Ng. *Reading Digits in Natural Images with
Unsupervised Feature Learning*, NIPS Workshop on Deep Learning
and Unsupervised Feature Learning, 2011.
Parameters
----------
which_format : int
Either 1 or 2. Determines which format (format 1: full numbers
or format 2: cropped digits) to convert.
directory : str
Directory in which input files reside.
output_directory : str
Directory in which to save the converted dataset.
output_filename : str, optional
Name of the saved dataset. Defaults to 'svhn_format_1.hdf5' or
'svhn_format_2.hdf5', depending on `which_format`.
Returns
-------
output_paths : tuple of str
Single-element tuple containing the path to the converted dataset.
"""
if which_format not in (1, 2):
raise ValueError("SVHN format needs to be either 1 or 2.")
if not output_filename:
output_filename = 'svhn_format_{}.hdf5'.format(which_format)
if which_format == 1:
return convert_svhn_format_1(
directory, output_directory, output_filename)
else:
return convert_svhn_format_2(
directory, output_directory, output_filename) | python | def convert_svhn(which_format, directory, output_directory,
output_filename=None):
"""Converts the SVHN dataset to HDF5.
Converts the SVHN dataset [SVHN] to an HDF5 dataset compatible
with :class:`fuel.datasets.SVHN`. The converted dataset is
saved as 'svhn_format_1.hdf5' or 'svhn_format_2.hdf5', depending
on the `which_format` argument.
.. [SVHN] Yuval Netzer, Tao Wang, Adam Coates, Alessandro Bissacco,
Bo Wu, Andrew Y. Ng. *Reading Digits in Natural Images with
Unsupervised Feature Learning*, NIPS Workshop on Deep Learning
and Unsupervised Feature Learning, 2011.
Parameters
----------
which_format : int
Either 1 or 2. Determines which format (format 1: full numbers
or format 2: cropped digits) to convert.
directory : str
Directory in which input files reside.
output_directory : str
Directory in which to save the converted dataset.
output_filename : str, optional
Name of the saved dataset. Defaults to 'svhn_format_1.hdf5' or
'svhn_format_2.hdf5', depending on `which_format`.
Returns
-------
output_paths : tuple of str
Single-element tuple containing the path to the converted dataset.
"""
if which_format not in (1, 2):
raise ValueError("SVHN format needs to be either 1 or 2.")
if not output_filename:
output_filename = 'svhn_format_{}.hdf5'.format(which_format)
if which_format == 1:
return convert_svhn_format_1(
directory, output_directory, output_filename)
else:
return convert_svhn_format_2(
directory, output_directory, output_filename) | [
"def",
"convert_svhn",
"(",
"which_format",
",",
"directory",
",",
"output_directory",
",",
"output_filename",
"=",
"None",
")",
":",
"if",
"which_format",
"not",
"in",
"(",
"1",
",",
"2",
")",
":",
"raise",
"ValueError",
"(",
"\"SVHN format needs to be either 1 or 2.\"",
")",
"if",
"not",
"output_filename",
":",
"output_filename",
"=",
"'svhn_format_{}.hdf5'",
".",
"format",
"(",
"which_format",
")",
"if",
"which_format",
"==",
"1",
":",
"return",
"convert_svhn_format_1",
"(",
"directory",
",",
"output_directory",
",",
"output_filename",
")",
"else",
":",
"return",
"convert_svhn_format_2",
"(",
"directory",
",",
"output_directory",
",",
"output_filename",
")"
] | Converts the SVHN dataset to HDF5.
Converts the SVHN dataset [SVHN] to an HDF5 dataset compatible
with :class:`fuel.datasets.SVHN`. The converted dataset is
saved as 'svhn_format_1.hdf5' or 'svhn_format_2.hdf5', depending
on the `which_format` argument.
.. [SVHN] Yuval Netzer, Tao Wang, Adam Coates, Alessandro Bissacco,
Bo Wu, Andrew Y. Ng. *Reading Digits in Natural Images with
Unsupervised Feature Learning*, NIPS Workshop on Deep Learning
and Unsupervised Feature Learning, 2011.
Parameters
----------
which_format : int
Either 1 or 2. Determines which format (format 1: full numbers
or format 2: cropped digits) to convert.
directory : str
Directory in which input files reside.
output_directory : str
Directory in which to save the converted dataset.
output_filename : str, optional
Name of the saved dataset. Defaults to 'svhn_format_1.hdf5' or
'svhn_format_2.hdf5', depending on `which_format`.
Returns
-------
output_paths : tuple of str
Single-element tuple containing the path to the converted dataset. | [
"Converts",
"the",
"SVHN",
"dataset",
"to",
"HDF5",
"."
] | 1d6292dc25e3a115544237e392e61bff6631d23c | https://github.com/mila-iqia/fuel/blob/1d6292dc25e3a115544237e392e61bff6631d23c/fuel/converters/svhn.py#L327-L369 | train |
mila-iqia/fuel | fuel/utils/formats.py | open_ | def open_(filename, mode='r', encoding=None):
"""Open a text file with encoding and optional gzip compression.
Note that on legacy Python any encoding other than ``None`` or opening
GZipped files will return an unpicklable file-like object.
Parameters
----------
filename : str
The filename to read.
mode : str, optional
The mode with which to open the file. Defaults to `r`.
encoding : str, optional
The encoding to use (see the codecs documentation_ for supported
values). Defaults to ``None``.
.. _documentation:
https://docs.python.org/3/library/codecs.html#standard-encodings
"""
if filename.endswith('.gz'):
if six.PY2:
zf = io.BufferedReader(gzip.open(filename, mode))
if encoding:
return codecs.getreader(encoding)(zf)
else:
return zf
else:
return io.BufferedReader(gzip.open(filename, mode,
encoding=encoding))
if six.PY2:
if encoding:
return codecs.open(filename, mode, encoding=encoding)
else:
return open(filename, mode)
else:
return open(filename, mode, encoding=encoding) | python | def open_(filename, mode='r', encoding=None):
"""Open a text file with encoding and optional gzip compression.
Note that on legacy Python any encoding other than ``None`` or opening
GZipped files will return an unpicklable file-like object.
Parameters
----------
filename : str
The filename to read.
mode : str, optional
The mode with which to open the file. Defaults to `r`.
encoding : str, optional
The encoding to use (see the codecs documentation_ for supported
values). Defaults to ``None``.
.. _documentation:
https://docs.python.org/3/library/codecs.html#standard-encodings
"""
if filename.endswith('.gz'):
if six.PY2:
zf = io.BufferedReader(gzip.open(filename, mode))
if encoding:
return codecs.getreader(encoding)(zf)
else:
return zf
else:
return io.BufferedReader(gzip.open(filename, mode,
encoding=encoding))
if six.PY2:
if encoding:
return codecs.open(filename, mode, encoding=encoding)
else:
return open(filename, mode)
else:
return open(filename, mode, encoding=encoding) | [
"def",
"open_",
"(",
"filename",
",",
"mode",
"=",
"'r'",
",",
"encoding",
"=",
"None",
")",
":",
"if",
"filename",
".",
"endswith",
"(",
"'.gz'",
")",
":",
"if",
"six",
".",
"PY2",
":",
"zf",
"=",
"io",
".",
"BufferedReader",
"(",
"gzip",
".",
"open",
"(",
"filename",
",",
"mode",
")",
")",
"if",
"encoding",
":",
"return",
"codecs",
".",
"getreader",
"(",
"encoding",
")",
"(",
"zf",
")",
"else",
":",
"return",
"zf",
"else",
":",
"return",
"io",
".",
"BufferedReader",
"(",
"gzip",
".",
"open",
"(",
"filename",
",",
"mode",
",",
"encoding",
"=",
"encoding",
")",
")",
"if",
"six",
".",
"PY2",
":",
"if",
"encoding",
":",
"return",
"codecs",
".",
"open",
"(",
"filename",
",",
"mode",
",",
"encoding",
"=",
"encoding",
")",
"else",
":",
"return",
"open",
"(",
"filename",
",",
"mode",
")",
"else",
":",
"return",
"open",
"(",
"filename",
",",
"mode",
",",
"encoding",
"=",
"encoding",
")"
] | Open a text file with encoding and optional gzip compression.
Note that on legacy Python any encoding other than ``None`` or opening
GZipped files will return an unpicklable file-like object.
Parameters
----------
filename : str
The filename to read.
mode : str, optional
The mode with which to open the file. Defaults to `r`.
encoding : str, optional
The encoding to use (see the codecs documentation_ for supported
values). Defaults to ``None``.
.. _documentation:
https://docs.python.org/3/library/codecs.html#standard-encodings | [
"Open",
"a",
"text",
"file",
"with",
"encoding",
"and",
"optional",
"gzip",
"compression",
"."
] | 1d6292dc25e3a115544237e392e61bff6631d23c | https://github.com/mila-iqia/fuel/blob/1d6292dc25e3a115544237e392e61bff6631d23c/fuel/utils/formats.py#L9-L45 | train |
mila-iqia/fuel | fuel/utils/formats.py | tar_open | def tar_open(f):
"""Open either a filename or a file-like object as a TarFile.
Parameters
----------
f : str or file-like object
The filename or file-like object from which to read.
Returns
-------
TarFile
A `TarFile` instance.
"""
if isinstance(f, six.string_types):
return tarfile.open(name=f)
else:
return tarfile.open(fileobj=f) | python | def tar_open(f):
"""Open either a filename or a file-like object as a TarFile.
Parameters
----------
f : str or file-like object
The filename or file-like object from which to read.
Returns
-------
TarFile
A `TarFile` instance.
"""
if isinstance(f, six.string_types):
return tarfile.open(name=f)
else:
return tarfile.open(fileobj=f) | [
"def",
"tar_open",
"(",
"f",
")",
":",
"if",
"isinstance",
"(",
"f",
",",
"six",
".",
"string_types",
")",
":",
"return",
"tarfile",
".",
"open",
"(",
"name",
"=",
"f",
")",
"else",
":",
"return",
"tarfile",
".",
"open",
"(",
"fileobj",
"=",
"f",
")"
] | Open either a filename or a file-like object as a TarFile.
Parameters
----------
f : str or file-like object
The filename or file-like object from which to read.
Returns
-------
TarFile
A `TarFile` instance. | [
"Open",
"either",
"a",
"filename",
"or",
"a",
"file",
"-",
"like",
"object",
"as",
"a",
"TarFile",
"."
] | 1d6292dc25e3a115544237e392e61bff6631d23c | https://github.com/mila-iqia/fuel/blob/1d6292dc25e3a115544237e392e61bff6631d23c/fuel/utils/formats.py#L48-L65 | train |
mila-iqia/fuel | fuel/utils/cache.py | copy_from_server_to_local | def copy_from_server_to_local(dataset_remote_dir, dataset_local_dir,
remote_fname, local_fname):
"""Copies a remote file locally.
Parameters
----------
remote_fname : str
Remote file to copy
local_fname : str
Path and name of the local copy to be made of the remote file.
"""
log.debug("Copying file `{}` to a local directory `{}`."
.format(remote_fname, dataset_local_dir))
head, tail = os.path.split(local_fname)
head += os.path.sep
if not os.path.exists(head):
os.makedirs(os.path.dirname(head))
shutil.copyfile(remote_fname, local_fname)
# Copy the original group id and file permission
st = os.stat(remote_fname)
os.chmod(local_fname, st.st_mode)
# If the user have read access to the data, but not a member
# of the group, he can't set the group. So we must catch the
# exception. But we still want to do this, for directory where
# only member of the group can read that data.
try:
os.chown(local_fname, -1, st.st_gid)
except OSError:
pass
# Need to give group write permission to the folders
# For the locking mechanism
# Try to set the original group as above
dirs = os.path.dirname(local_fname).replace(dataset_local_dir, '')
sep = dirs.split(os.path.sep)
if sep[0] == "":
sep = sep[1:]
for i in range(len(sep)):
orig_p = os.path.join(dataset_remote_dir, *sep[:i + 1])
new_p = os.path.join(dataset_local_dir, *sep[:i + 1])
orig_st = os.stat(orig_p)
new_st = os.stat(new_p)
if not new_st.st_mode & stat.S_IWGRP:
os.chmod(new_p, new_st.st_mode | stat.S_IWGRP)
if orig_st.st_gid != new_st.st_gid:
try:
os.chown(new_p, -1, orig_st.st_gid)
except OSError:
pass | python | def copy_from_server_to_local(dataset_remote_dir, dataset_local_dir,
remote_fname, local_fname):
"""Copies a remote file locally.
Parameters
----------
remote_fname : str
Remote file to copy
local_fname : str
Path and name of the local copy to be made of the remote file.
"""
log.debug("Copying file `{}` to a local directory `{}`."
.format(remote_fname, dataset_local_dir))
head, tail = os.path.split(local_fname)
head += os.path.sep
if not os.path.exists(head):
os.makedirs(os.path.dirname(head))
shutil.copyfile(remote_fname, local_fname)
# Copy the original group id and file permission
st = os.stat(remote_fname)
os.chmod(local_fname, st.st_mode)
# If the user have read access to the data, but not a member
# of the group, he can't set the group. So we must catch the
# exception. But we still want to do this, for directory where
# only member of the group can read that data.
try:
os.chown(local_fname, -1, st.st_gid)
except OSError:
pass
# Need to give group write permission to the folders
# For the locking mechanism
# Try to set the original group as above
dirs = os.path.dirname(local_fname).replace(dataset_local_dir, '')
sep = dirs.split(os.path.sep)
if sep[0] == "":
sep = sep[1:]
for i in range(len(sep)):
orig_p = os.path.join(dataset_remote_dir, *sep[:i + 1])
new_p = os.path.join(dataset_local_dir, *sep[:i + 1])
orig_st = os.stat(orig_p)
new_st = os.stat(new_p)
if not new_st.st_mode & stat.S_IWGRP:
os.chmod(new_p, new_st.st_mode | stat.S_IWGRP)
if orig_st.st_gid != new_st.st_gid:
try:
os.chown(new_p, -1, orig_st.st_gid)
except OSError:
pass | [
"def",
"copy_from_server_to_local",
"(",
"dataset_remote_dir",
",",
"dataset_local_dir",
",",
"remote_fname",
",",
"local_fname",
")",
":",
"log",
".",
"debug",
"(",
"\"Copying file `{}` to a local directory `{}`.\"",
".",
"format",
"(",
"remote_fname",
",",
"dataset_local_dir",
")",
")",
"head",
",",
"tail",
"=",
"os",
".",
"path",
".",
"split",
"(",
"local_fname",
")",
"head",
"+=",
"os",
".",
"path",
".",
"sep",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"head",
")",
":",
"os",
".",
"makedirs",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"head",
")",
")",
"shutil",
".",
"copyfile",
"(",
"remote_fname",
",",
"local_fname",
")",
"# Copy the original group id and file permission",
"st",
"=",
"os",
".",
"stat",
"(",
"remote_fname",
")",
"os",
".",
"chmod",
"(",
"local_fname",
",",
"st",
".",
"st_mode",
")",
"# If the user have read access to the data, but not a member",
"# of the group, he can't set the group. So we must catch the",
"# exception. But we still want to do this, for directory where",
"# only member of the group can read that data.",
"try",
":",
"os",
".",
"chown",
"(",
"local_fname",
",",
"-",
"1",
",",
"st",
".",
"st_gid",
")",
"except",
"OSError",
":",
"pass",
"# Need to give group write permission to the folders",
"# For the locking mechanism",
"# Try to set the original group as above",
"dirs",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"local_fname",
")",
".",
"replace",
"(",
"dataset_local_dir",
",",
"''",
")",
"sep",
"=",
"dirs",
".",
"split",
"(",
"os",
".",
"path",
".",
"sep",
")",
"if",
"sep",
"[",
"0",
"]",
"==",
"\"\"",
":",
"sep",
"=",
"sep",
"[",
"1",
":",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"sep",
")",
")",
":",
"orig_p",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dataset_remote_dir",
",",
"*",
"sep",
"[",
":",
"i",
"+",
"1",
"]",
")",
"new_p",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dataset_local_dir",
",",
"*",
"sep",
"[",
":",
"i",
"+",
"1",
"]",
")",
"orig_st",
"=",
"os",
".",
"stat",
"(",
"orig_p",
")",
"new_st",
"=",
"os",
".",
"stat",
"(",
"new_p",
")",
"if",
"not",
"new_st",
".",
"st_mode",
"&",
"stat",
".",
"S_IWGRP",
":",
"os",
".",
"chmod",
"(",
"new_p",
",",
"new_st",
".",
"st_mode",
"|",
"stat",
".",
"S_IWGRP",
")",
"if",
"orig_st",
".",
"st_gid",
"!=",
"new_st",
".",
"st_gid",
":",
"try",
":",
"os",
".",
"chown",
"(",
"new_p",
",",
"-",
"1",
",",
"orig_st",
".",
"st_gid",
")",
"except",
"OSError",
":",
"pass"
] | Copies a remote file locally.
Parameters
----------
remote_fname : str
Remote file to copy
local_fname : str
Path and name of the local copy to be made of the remote file. | [
"Copies",
"a",
"remote",
"file",
"locally",
"."
] | 1d6292dc25e3a115544237e392e61bff6631d23c | https://github.com/mila-iqia/fuel/blob/1d6292dc25e3a115544237e392e61bff6631d23c/fuel/utils/cache.py#L217-L269 | train |
mila-iqia/fuel | fuel/converters/adult.py | convert_to_one_hot | def convert_to_one_hot(y):
"""
converts y into one hot reprsentation.
Parameters
----------
y : list
A list containing continous integer values.
Returns
-------
one_hot : numpy.ndarray
A numpy.ndarray object, which is one-hot representation of y.
"""
max_value = max(y)
min_value = min(y)
length = len(y)
one_hot = numpy.zeros((length, (max_value - min_value + 1)))
one_hot[numpy.arange(length), y] = 1
return one_hot | python | def convert_to_one_hot(y):
"""
converts y into one hot reprsentation.
Parameters
----------
y : list
A list containing continous integer values.
Returns
-------
one_hot : numpy.ndarray
A numpy.ndarray object, which is one-hot representation of y.
"""
max_value = max(y)
min_value = min(y)
length = len(y)
one_hot = numpy.zeros((length, (max_value - min_value + 1)))
one_hot[numpy.arange(length), y] = 1
return one_hot | [
"def",
"convert_to_one_hot",
"(",
"y",
")",
":",
"max_value",
"=",
"max",
"(",
"y",
")",
"min_value",
"=",
"min",
"(",
"y",
")",
"length",
"=",
"len",
"(",
"y",
")",
"one_hot",
"=",
"numpy",
".",
"zeros",
"(",
"(",
"length",
",",
"(",
"max_value",
"-",
"min_value",
"+",
"1",
")",
")",
")",
"one_hot",
"[",
"numpy",
".",
"arange",
"(",
"length",
")",
",",
"y",
"]",
"=",
"1",
"return",
"one_hot"
] | converts y into one hot reprsentation.
Parameters
----------
y : list
A list containing continous integer values.
Returns
-------
one_hot : numpy.ndarray
A numpy.ndarray object, which is one-hot representation of y. | [
"converts",
"y",
"into",
"one",
"hot",
"reprsentation",
"."
] | 1d6292dc25e3a115544237e392e61bff6631d23c | https://github.com/mila-iqia/fuel/blob/1d6292dc25e3a115544237e392e61bff6631d23c/fuel/converters/adult.py#L9-L29 | train |
mila-iqia/fuel | fuel/converters/binarized_mnist.py | convert_binarized_mnist | def convert_binarized_mnist(directory, output_directory,
output_filename='binarized_mnist.hdf5'):
"""Converts the binarized MNIST dataset to HDF5.
Converts the binarized MNIST dataset used in R. Salakhutdinov's DBN
paper [DBN] to an HDF5 dataset compatible with
:class:`fuel.datasets.BinarizedMNIST`. The converted dataset is
saved as 'binarized_mnist.hdf5'.
This method assumes the existence of the files
`binarized_mnist_{train,valid,test}.amat`, which are accessible
through Hugo Larochelle's website [HUGO].
.. [DBN] Ruslan Salakhutdinov and Iain Murray, *On the Quantitative
Analysis of Deep Belief Networks*, Proceedings of the 25th
international conference on Machine learning, 2008, pp. 872-879.
Parameters
----------
directory : str
Directory in which input files reside.
output_directory : str
Directory in which to save the converted dataset.
output_filename : str, optional
Name of the saved dataset. Defaults to 'binarized_mnist.hdf5'.
Returns
-------
output_paths : tuple of str
Single-element tuple containing the path to the converted dataset.
"""
output_path = os.path.join(output_directory, output_filename)
h5file = h5py.File(output_path, mode='w')
train_set = numpy.loadtxt(
os.path.join(directory, TRAIN_FILE)).reshape(
(-1, 1, 28, 28)).astype('uint8')
valid_set = numpy.loadtxt(
os.path.join(directory, VALID_FILE)).reshape(
(-1, 1, 28, 28)).astype('uint8')
test_set = numpy.loadtxt(
os.path.join(directory, TEST_FILE)).reshape(
(-1, 1, 28, 28)).astype('uint8')
data = (('train', 'features', train_set),
('valid', 'features', valid_set),
('test', 'features', test_set))
fill_hdf5_file(h5file, data)
for i, label in enumerate(('batch', 'channel', 'height', 'width')):
h5file['features'].dims[i].label = label
h5file.flush()
h5file.close()
return (output_path,) | python | def convert_binarized_mnist(directory, output_directory,
output_filename='binarized_mnist.hdf5'):
"""Converts the binarized MNIST dataset to HDF5.
Converts the binarized MNIST dataset used in R. Salakhutdinov's DBN
paper [DBN] to an HDF5 dataset compatible with
:class:`fuel.datasets.BinarizedMNIST`. The converted dataset is
saved as 'binarized_mnist.hdf5'.
This method assumes the existence of the files
`binarized_mnist_{train,valid,test}.amat`, which are accessible
through Hugo Larochelle's website [HUGO].
.. [DBN] Ruslan Salakhutdinov and Iain Murray, *On the Quantitative
Analysis of Deep Belief Networks*, Proceedings of the 25th
international conference on Machine learning, 2008, pp. 872-879.
Parameters
----------
directory : str
Directory in which input files reside.
output_directory : str
Directory in which to save the converted dataset.
output_filename : str, optional
Name of the saved dataset. Defaults to 'binarized_mnist.hdf5'.
Returns
-------
output_paths : tuple of str
Single-element tuple containing the path to the converted dataset.
"""
output_path = os.path.join(output_directory, output_filename)
h5file = h5py.File(output_path, mode='w')
train_set = numpy.loadtxt(
os.path.join(directory, TRAIN_FILE)).reshape(
(-1, 1, 28, 28)).astype('uint8')
valid_set = numpy.loadtxt(
os.path.join(directory, VALID_FILE)).reshape(
(-1, 1, 28, 28)).astype('uint8')
test_set = numpy.loadtxt(
os.path.join(directory, TEST_FILE)).reshape(
(-1, 1, 28, 28)).astype('uint8')
data = (('train', 'features', train_set),
('valid', 'features', valid_set),
('test', 'features', test_set))
fill_hdf5_file(h5file, data)
for i, label in enumerate(('batch', 'channel', 'height', 'width')):
h5file['features'].dims[i].label = label
h5file.flush()
h5file.close()
return (output_path,) | [
"def",
"convert_binarized_mnist",
"(",
"directory",
",",
"output_directory",
",",
"output_filename",
"=",
"'binarized_mnist.hdf5'",
")",
":",
"output_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"output_directory",
",",
"output_filename",
")",
"h5file",
"=",
"h5py",
".",
"File",
"(",
"output_path",
",",
"mode",
"=",
"'w'",
")",
"train_set",
"=",
"numpy",
".",
"loadtxt",
"(",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"TRAIN_FILE",
")",
")",
".",
"reshape",
"(",
"(",
"-",
"1",
",",
"1",
",",
"28",
",",
"28",
")",
")",
".",
"astype",
"(",
"'uint8'",
")",
"valid_set",
"=",
"numpy",
".",
"loadtxt",
"(",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"VALID_FILE",
")",
")",
".",
"reshape",
"(",
"(",
"-",
"1",
",",
"1",
",",
"28",
",",
"28",
")",
")",
".",
"astype",
"(",
"'uint8'",
")",
"test_set",
"=",
"numpy",
".",
"loadtxt",
"(",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"TEST_FILE",
")",
")",
".",
"reshape",
"(",
"(",
"-",
"1",
",",
"1",
",",
"28",
",",
"28",
")",
")",
".",
"astype",
"(",
"'uint8'",
")",
"data",
"=",
"(",
"(",
"'train'",
",",
"'features'",
",",
"train_set",
")",
",",
"(",
"'valid'",
",",
"'features'",
",",
"valid_set",
")",
",",
"(",
"'test'",
",",
"'features'",
",",
"test_set",
")",
")",
"fill_hdf5_file",
"(",
"h5file",
",",
"data",
")",
"for",
"i",
",",
"label",
"in",
"enumerate",
"(",
"(",
"'batch'",
",",
"'channel'",
",",
"'height'",
",",
"'width'",
")",
")",
":",
"h5file",
"[",
"'features'",
"]",
".",
"dims",
"[",
"i",
"]",
".",
"label",
"=",
"label",
"h5file",
".",
"flush",
"(",
")",
"h5file",
".",
"close",
"(",
")",
"return",
"(",
"output_path",
",",
")"
] | Converts the binarized MNIST dataset to HDF5.
Converts the binarized MNIST dataset used in R. Salakhutdinov's DBN
paper [DBN] to an HDF5 dataset compatible with
:class:`fuel.datasets.BinarizedMNIST`. The converted dataset is
saved as 'binarized_mnist.hdf5'.
This method assumes the existence of the files
`binarized_mnist_{train,valid,test}.amat`, which are accessible
through Hugo Larochelle's website [HUGO].
.. [DBN] Ruslan Salakhutdinov and Iain Murray, *On the Quantitative
Analysis of Deep Belief Networks*, Proceedings of the 25th
international conference on Machine learning, 2008, pp. 872-879.
Parameters
----------
directory : str
Directory in which input files reside.
output_directory : str
Directory in which to save the converted dataset.
output_filename : str, optional
Name of the saved dataset. Defaults to 'binarized_mnist.hdf5'.
Returns
-------
output_paths : tuple of str
Single-element tuple containing the path to the converted dataset. | [
"Converts",
"the",
"binarized",
"MNIST",
"dataset",
"to",
"HDF5",
"."
] | 1d6292dc25e3a115544237e392e61bff6631d23c | https://github.com/mila-iqia/fuel/blob/1d6292dc25e3a115544237e392e61bff6631d23c/fuel/converters/binarized_mnist.py#L17-L71 | train |
mila-iqia/fuel | fuel/downloaders/cifar10.py | fill_subparser | def fill_subparser(subparser):
"""Sets up a subparser to download the CIFAR-10 dataset file.
The CIFAR-10 dataset file is downloaded from Alex Krizhevsky's
website [ALEX].
Parameters
----------
subparser : :class:`argparse.ArgumentParser`
Subparser handling the `cifar10` command.
"""
url = 'http://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz'
filename = 'cifar-10-python.tar.gz'
subparser.set_defaults(urls=[url], filenames=[filename])
return default_downloader | python | def fill_subparser(subparser):
"""Sets up a subparser to download the CIFAR-10 dataset file.
The CIFAR-10 dataset file is downloaded from Alex Krizhevsky's
website [ALEX].
Parameters
----------
subparser : :class:`argparse.ArgumentParser`
Subparser handling the `cifar10` command.
"""
url = 'http://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz'
filename = 'cifar-10-python.tar.gz'
subparser.set_defaults(urls=[url], filenames=[filename])
return default_downloader | [
"def",
"fill_subparser",
"(",
"subparser",
")",
":",
"url",
"=",
"'http://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz'",
"filename",
"=",
"'cifar-10-python.tar.gz'",
"subparser",
".",
"set_defaults",
"(",
"urls",
"=",
"[",
"url",
"]",
",",
"filenames",
"=",
"[",
"filename",
"]",
")",
"return",
"default_downloader"
] | Sets up a subparser to download the CIFAR-10 dataset file.
The CIFAR-10 dataset file is downloaded from Alex Krizhevsky's
website [ALEX].
Parameters
----------
subparser : :class:`argparse.ArgumentParser`
Subparser handling the `cifar10` command. | [
"Sets",
"up",
"a",
"subparser",
"to",
"download",
"the",
"CIFAR",
"-",
"10",
"dataset",
"file",
"."
] | 1d6292dc25e3a115544237e392e61bff6631d23c | https://github.com/mila-iqia/fuel/blob/1d6292dc25e3a115544237e392e61bff6631d23c/fuel/downloaders/cifar10.py#L4-L19 | train |
mila-iqia/fuel | fuel/converters/celeba.py | convert_celeba_aligned_cropped | def convert_celeba_aligned_cropped(directory, output_directory,
output_filename=OUTPUT_FILENAME):
"""Converts the aligned and cropped CelebA dataset to HDF5.
Converts the CelebA dataset to an HDF5 dataset compatible with
:class:`fuel.datasets.CelebA`. The converted dataset is saved as
'celeba_aligned_cropped.hdf5'.
It assumes the existence of the following files:
* `img_align_celeba.zip`
* `list_attr_celeba.txt`
Parameters
----------
directory : str
Directory in which input files reside.
output_directory : str
Directory in which to save the converted dataset.
output_filename : str, optional
Name of the saved dataset. Defaults to
'celeba_aligned_cropped.hdf5'.
Returns
-------
output_paths : tuple of str
Single-element tuple containing the path to the converted
dataset.
"""
output_path = os.path.join(output_directory, output_filename)
h5file = _initialize_conversion(directory, output_path, (218, 178))
features_dataset = h5file['features']
image_file_path = os.path.join(directory, IMAGE_FILE)
with zipfile.ZipFile(image_file_path, 'r') as image_file:
with progress_bar('images', NUM_EXAMPLES) as bar:
for i in range(NUM_EXAMPLES):
image_name = 'img_align_celeba/{:06d}.jpg'.format(i + 1)
features_dataset[i] = numpy.asarray(
Image.open(
image_file.open(image_name, 'r'))).transpose(2, 0, 1)
bar.update(i + 1)
h5file.flush()
h5file.close()
return (output_path,) | python | def convert_celeba_aligned_cropped(directory, output_directory,
output_filename=OUTPUT_FILENAME):
"""Converts the aligned and cropped CelebA dataset to HDF5.
Converts the CelebA dataset to an HDF5 dataset compatible with
:class:`fuel.datasets.CelebA`. The converted dataset is saved as
'celeba_aligned_cropped.hdf5'.
It assumes the existence of the following files:
* `img_align_celeba.zip`
* `list_attr_celeba.txt`
Parameters
----------
directory : str
Directory in which input files reside.
output_directory : str
Directory in which to save the converted dataset.
output_filename : str, optional
Name of the saved dataset. Defaults to
'celeba_aligned_cropped.hdf5'.
Returns
-------
output_paths : tuple of str
Single-element tuple containing the path to the converted
dataset.
"""
output_path = os.path.join(output_directory, output_filename)
h5file = _initialize_conversion(directory, output_path, (218, 178))
features_dataset = h5file['features']
image_file_path = os.path.join(directory, IMAGE_FILE)
with zipfile.ZipFile(image_file_path, 'r') as image_file:
with progress_bar('images', NUM_EXAMPLES) as bar:
for i in range(NUM_EXAMPLES):
image_name = 'img_align_celeba/{:06d}.jpg'.format(i + 1)
features_dataset[i] = numpy.asarray(
Image.open(
image_file.open(image_name, 'r'))).transpose(2, 0, 1)
bar.update(i + 1)
h5file.flush()
h5file.close()
return (output_path,) | [
"def",
"convert_celeba_aligned_cropped",
"(",
"directory",
",",
"output_directory",
",",
"output_filename",
"=",
"OUTPUT_FILENAME",
")",
":",
"output_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"output_directory",
",",
"output_filename",
")",
"h5file",
"=",
"_initialize_conversion",
"(",
"directory",
",",
"output_path",
",",
"(",
"218",
",",
"178",
")",
")",
"features_dataset",
"=",
"h5file",
"[",
"'features'",
"]",
"image_file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"IMAGE_FILE",
")",
"with",
"zipfile",
".",
"ZipFile",
"(",
"image_file_path",
",",
"'r'",
")",
"as",
"image_file",
":",
"with",
"progress_bar",
"(",
"'images'",
",",
"NUM_EXAMPLES",
")",
"as",
"bar",
":",
"for",
"i",
"in",
"range",
"(",
"NUM_EXAMPLES",
")",
":",
"image_name",
"=",
"'img_align_celeba/{:06d}.jpg'",
".",
"format",
"(",
"i",
"+",
"1",
")",
"features_dataset",
"[",
"i",
"]",
"=",
"numpy",
".",
"asarray",
"(",
"Image",
".",
"open",
"(",
"image_file",
".",
"open",
"(",
"image_name",
",",
"'r'",
")",
")",
")",
".",
"transpose",
"(",
"2",
",",
"0",
",",
"1",
")",
"bar",
".",
"update",
"(",
"i",
"+",
"1",
")",
"h5file",
".",
"flush",
"(",
")",
"h5file",
".",
"close",
"(",
")",
"return",
"(",
"output_path",
",",
")"
] | Converts the aligned and cropped CelebA dataset to HDF5.
Converts the CelebA dataset to an HDF5 dataset compatible with
:class:`fuel.datasets.CelebA`. The converted dataset is saved as
'celeba_aligned_cropped.hdf5'.
It assumes the existence of the following files:
* `img_align_celeba.zip`
* `list_attr_celeba.txt`
Parameters
----------
directory : str
Directory in which input files reside.
output_directory : str
Directory in which to save the converted dataset.
output_filename : str, optional
Name of the saved dataset. Defaults to
'celeba_aligned_cropped.hdf5'.
Returns
-------
output_paths : tuple of str
Single-element tuple containing the path to the converted
dataset. | [
"Converts",
"the",
"aligned",
"and",
"cropped",
"CelebA",
"dataset",
"to",
"HDF5",
"."
] | 1d6292dc25e3a115544237e392e61bff6631d23c | https://github.com/mila-iqia/fuel/blob/1d6292dc25e3a115544237e392e61bff6631d23c/fuel/converters/celeba.py#L55-L102 | train |
mila-iqia/fuel | fuel/converters/celeba.py | convert_celeba | def convert_celeba(which_format, directory, output_directory,
output_filename=None):
"""Converts the CelebA dataset to HDF5.
Converts the CelebA dataset to an HDF5 dataset compatible with
:class:`fuel.datasets.CelebA`. The converted dataset is
saved as 'celeba_aligned_cropped.hdf5' or 'celeba_64.hdf5',
depending on the `which_format` argument.
Parameters
----------
which_format : str
Either 'aligned_cropped' or '64'. Determines which format
to convert to.
directory : str
Directory in which input files reside.
output_directory : str
Directory in which to save the converted dataset.
output_filename : str, optional
Name of the saved dataset. Defaults to
'celeba_aligned_cropped.hdf5' or 'celeba_64.hdf5',
depending on `which_format`.
Returns
-------
output_paths : tuple of str
Single-element tuple containing the path to the converted dataset.
"""
if which_format not in ('aligned_cropped', '64'):
raise ValueError("CelebA format needs to be either "
"'aligned_cropped' or '64'.")
if not output_filename:
output_filename = 'celeba_{}.hdf5'.format(which_format)
if which_format == 'aligned_cropped':
return convert_celeba_aligned_cropped(
directory, output_directory, output_filename)
else:
return convert_celeba_64(
directory, output_directory, output_filename) | python | def convert_celeba(which_format, directory, output_directory,
output_filename=None):
"""Converts the CelebA dataset to HDF5.
Converts the CelebA dataset to an HDF5 dataset compatible with
:class:`fuel.datasets.CelebA`. The converted dataset is
saved as 'celeba_aligned_cropped.hdf5' or 'celeba_64.hdf5',
depending on the `which_format` argument.
Parameters
----------
which_format : str
Either 'aligned_cropped' or '64'. Determines which format
to convert to.
directory : str
Directory in which input files reside.
output_directory : str
Directory in which to save the converted dataset.
output_filename : str, optional
Name of the saved dataset. Defaults to
'celeba_aligned_cropped.hdf5' or 'celeba_64.hdf5',
depending on `which_format`.
Returns
-------
output_paths : tuple of str
Single-element tuple containing the path to the converted dataset.
"""
if which_format not in ('aligned_cropped', '64'):
raise ValueError("CelebA format needs to be either "
"'aligned_cropped' or '64'.")
if not output_filename:
output_filename = 'celeba_{}.hdf5'.format(which_format)
if which_format == 'aligned_cropped':
return convert_celeba_aligned_cropped(
directory, output_directory, output_filename)
else:
return convert_celeba_64(
directory, output_directory, output_filename) | [
"def",
"convert_celeba",
"(",
"which_format",
",",
"directory",
",",
"output_directory",
",",
"output_filename",
"=",
"None",
")",
":",
"if",
"which_format",
"not",
"in",
"(",
"'aligned_cropped'",
",",
"'64'",
")",
":",
"raise",
"ValueError",
"(",
"\"CelebA format needs to be either \"",
"\"'aligned_cropped' or '64'.\"",
")",
"if",
"not",
"output_filename",
":",
"output_filename",
"=",
"'celeba_{}.hdf5'",
".",
"format",
"(",
"which_format",
")",
"if",
"which_format",
"==",
"'aligned_cropped'",
":",
"return",
"convert_celeba_aligned_cropped",
"(",
"directory",
",",
"output_directory",
",",
"output_filename",
")",
"else",
":",
"return",
"convert_celeba_64",
"(",
"directory",
",",
"output_directory",
",",
"output_filename",
")"
] | Converts the CelebA dataset to HDF5.
Converts the CelebA dataset to an HDF5 dataset compatible with
:class:`fuel.datasets.CelebA`. The converted dataset is
saved as 'celeba_aligned_cropped.hdf5' or 'celeba_64.hdf5',
depending on the `which_format` argument.
Parameters
----------
which_format : str
Either 'aligned_cropped' or '64'. Determines which format
to convert to.
directory : str
Directory in which input files reside.
output_directory : str
Directory in which to save the converted dataset.
output_filename : str, optional
Name of the saved dataset. Defaults to
'celeba_aligned_cropped.hdf5' or 'celeba_64.hdf5',
depending on `which_format`.
Returns
-------
output_paths : tuple of str
Single-element tuple containing the path to the converted dataset. | [
"Converts",
"the",
"CelebA",
"dataset",
"to",
"HDF5",
"."
] | 1d6292dc25e3a115544237e392e61bff6631d23c | https://github.com/mila-iqia/fuel/blob/1d6292dc25e3a115544237e392e61bff6631d23c/fuel/converters/celeba.py#L159-L198 | train |
mila-iqia/fuel | fuel/utils/disk.py | disk_usage | def disk_usage(path):
"""Return free usage about the given path, in bytes.
Parameters
----------
path : str
Folder for which to return disk usage
Returns
-------
output : tuple
Tuple containing total space in the folder and currently
used space in the folder
"""
st = os.statvfs(path)
total = st.f_blocks * st.f_frsize
used = (st.f_blocks - st.f_bfree) * st.f_frsize
return total, used | python | def disk_usage(path):
"""Return free usage about the given path, in bytes.
Parameters
----------
path : str
Folder for which to return disk usage
Returns
-------
output : tuple
Tuple containing total space in the folder and currently
used space in the folder
"""
st = os.statvfs(path)
total = st.f_blocks * st.f_frsize
used = (st.f_blocks - st.f_bfree) * st.f_frsize
return total, used | [
"def",
"disk_usage",
"(",
"path",
")",
":",
"st",
"=",
"os",
".",
"statvfs",
"(",
"path",
")",
"total",
"=",
"st",
".",
"f_blocks",
"*",
"st",
".",
"f_frsize",
"used",
"=",
"(",
"st",
".",
"f_blocks",
"-",
"st",
".",
"f_bfree",
")",
"*",
"st",
".",
"f_frsize",
"return",
"total",
",",
"used"
] | Return free usage about the given path, in bytes.
Parameters
----------
path : str
Folder for which to return disk usage
Returns
-------
output : tuple
Tuple containing total space in the folder and currently
used space in the folder | [
"Return",
"free",
"usage",
"about",
"the",
"given",
"path",
"in",
"bytes",
"."
] | 1d6292dc25e3a115544237e392e61bff6631d23c | https://github.com/mila-iqia/fuel/blob/1d6292dc25e3a115544237e392e61bff6631d23c/fuel/utils/disk.py#L39-L57 | train |
mila-iqia/fuel | fuel/utils/disk.py | safe_mkdir | def safe_mkdir(folder_name, force_perm=None):
"""Create the specified folder.
If the parent folders do not exist, they are also created.
If the folder already exists, nothing is done.
Parameters
----------
folder_name : str
Name of the folder to create.
force_perm : str
Mode to use for folder creation.
"""
if os.path.exists(folder_name):
return
intermediary_folders = folder_name.split(os.path.sep)
# Remove invalid elements from intermediary_folders
if intermediary_folders[-1] == "":
intermediary_folders = intermediary_folders[:-1]
if force_perm:
force_perm_path = folder_name.split(os.path.sep)
if force_perm_path[-1] == "":
force_perm_path = force_perm_path[:-1]
for i in range(1, len(intermediary_folders)):
folder_to_create = os.path.sep.join(intermediary_folders[:i + 1])
if os.path.exists(folder_to_create):
continue
os.mkdir(folder_to_create)
if force_perm:
os.chmod(folder_to_create, force_perm) | python | def safe_mkdir(folder_name, force_perm=None):
"""Create the specified folder.
If the parent folders do not exist, they are also created.
If the folder already exists, nothing is done.
Parameters
----------
folder_name : str
Name of the folder to create.
force_perm : str
Mode to use for folder creation.
"""
if os.path.exists(folder_name):
return
intermediary_folders = folder_name.split(os.path.sep)
# Remove invalid elements from intermediary_folders
if intermediary_folders[-1] == "":
intermediary_folders = intermediary_folders[:-1]
if force_perm:
force_perm_path = folder_name.split(os.path.sep)
if force_perm_path[-1] == "":
force_perm_path = force_perm_path[:-1]
for i in range(1, len(intermediary_folders)):
folder_to_create = os.path.sep.join(intermediary_folders[:i + 1])
if os.path.exists(folder_to_create):
continue
os.mkdir(folder_to_create)
if force_perm:
os.chmod(folder_to_create, force_perm) | [
"def",
"safe_mkdir",
"(",
"folder_name",
",",
"force_perm",
"=",
"None",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"folder_name",
")",
":",
"return",
"intermediary_folders",
"=",
"folder_name",
".",
"split",
"(",
"os",
".",
"path",
".",
"sep",
")",
"# Remove invalid elements from intermediary_folders",
"if",
"intermediary_folders",
"[",
"-",
"1",
"]",
"==",
"\"\"",
":",
"intermediary_folders",
"=",
"intermediary_folders",
"[",
":",
"-",
"1",
"]",
"if",
"force_perm",
":",
"force_perm_path",
"=",
"folder_name",
".",
"split",
"(",
"os",
".",
"path",
".",
"sep",
")",
"if",
"force_perm_path",
"[",
"-",
"1",
"]",
"==",
"\"\"",
":",
"force_perm_path",
"=",
"force_perm_path",
"[",
":",
"-",
"1",
"]",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"intermediary_folders",
")",
")",
":",
"folder_to_create",
"=",
"os",
".",
"path",
".",
"sep",
".",
"join",
"(",
"intermediary_folders",
"[",
":",
"i",
"+",
"1",
"]",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"folder_to_create",
")",
":",
"continue",
"os",
".",
"mkdir",
"(",
"folder_to_create",
")",
"if",
"force_perm",
":",
"os",
".",
"chmod",
"(",
"folder_to_create",
",",
"force_perm",
")"
] | Create the specified folder.
If the parent folders do not exist, they are also created.
If the folder already exists, nothing is done.
Parameters
----------
folder_name : str
Name of the folder to create.
force_perm : str
Mode to use for folder creation. | [
"Create",
"the",
"specified",
"folder",
"."
] | 1d6292dc25e3a115544237e392e61bff6631d23c | https://github.com/mila-iqia/fuel/blob/1d6292dc25e3a115544237e392e61bff6631d23c/fuel/utils/disk.py#L60-L93 | train |
mila-iqia/fuel | fuel/utils/disk.py | check_enough_space | def check_enough_space(dataset_local_dir, remote_fname, local_fname,
max_disk_usage=0.9):
"""Check if the given local folder has enough space.
Check if the given local folder has enough space to store
the specified remote file.
Parameters
----------
remote_fname : str
Path to the remote file
remote_fname : str
Path to the local folder
max_disk_usage : float
Fraction indicating how much of the total space in the
local folder can be used before the local cache must stop
adding to it.
Returns
-------
output : boolean
True if there is enough space to store the remote file.
"""
storage_need = os.path.getsize(remote_fname)
storage_total, storage_used = disk_usage(dataset_local_dir)
# Instead of only looking if there's enough space, we ensure we do not
# go over max disk usage level to avoid filling the disk/partition
return ((storage_used + storage_need) <
(storage_total * max_disk_usage)) | python | def check_enough_space(dataset_local_dir, remote_fname, local_fname,
max_disk_usage=0.9):
"""Check if the given local folder has enough space.
Check if the given local folder has enough space to store
the specified remote file.
Parameters
----------
remote_fname : str
Path to the remote file
remote_fname : str
Path to the local folder
max_disk_usage : float
Fraction indicating how much of the total space in the
local folder can be used before the local cache must stop
adding to it.
Returns
-------
output : boolean
True if there is enough space to store the remote file.
"""
storage_need = os.path.getsize(remote_fname)
storage_total, storage_used = disk_usage(dataset_local_dir)
# Instead of only looking if there's enough space, we ensure we do not
# go over max disk usage level to avoid filling the disk/partition
return ((storage_used + storage_need) <
(storage_total * max_disk_usage)) | [
"def",
"check_enough_space",
"(",
"dataset_local_dir",
",",
"remote_fname",
",",
"local_fname",
",",
"max_disk_usage",
"=",
"0.9",
")",
":",
"storage_need",
"=",
"os",
".",
"path",
".",
"getsize",
"(",
"remote_fname",
")",
"storage_total",
",",
"storage_used",
"=",
"disk_usage",
"(",
"dataset_local_dir",
")",
"# Instead of only looking if there's enough space, we ensure we do not",
"# go over max disk usage level to avoid filling the disk/partition",
"return",
"(",
"(",
"storage_used",
"+",
"storage_need",
")",
"<",
"(",
"storage_total",
"*",
"max_disk_usage",
")",
")"
] | Check if the given local folder has enough space.
Check if the given local folder has enough space to store
the specified remote file.
Parameters
----------
remote_fname : str
Path to the remote file
remote_fname : str
Path to the local folder
max_disk_usage : float
Fraction indicating how much of the total space in the
local folder can be used before the local cache must stop
adding to it.
Returns
-------
output : boolean
True if there is enough space to store the remote file. | [
"Check",
"if",
"the",
"given",
"local",
"folder",
"has",
"enough",
"space",
"."
] | 1d6292dc25e3a115544237e392e61bff6631d23c | https://github.com/mila-iqia/fuel/blob/1d6292dc25e3a115544237e392e61bff6631d23c/fuel/utils/disk.py#L96-L126 | train |
mila-iqia/fuel | fuel/converters/cifar100.py | convert_cifar100 | def convert_cifar100(directory, output_directory,
output_filename='cifar100.hdf5'):
"""Converts the CIFAR-100 dataset to HDF5.
Converts the CIFAR-100 dataset to an HDF5 dataset compatible with
:class:`fuel.datasets.CIFAR100`. The converted dataset is saved as
'cifar100.hdf5'.
This method assumes the existence of the following file:
`cifar-100-python.tar.gz`
Parameters
----------
directory : str
Directory in which the required input files reside.
output_directory : str
Directory in which to save the converted dataset.
output_filename : str, optional
Name of the saved dataset. Defaults to 'cifar100.hdf5'.
Returns
-------
output_paths : tuple of str
Single-element tuple containing the path to the converted dataset.
"""
output_path = os.path.join(output_directory, output_filename)
h5file = h5py.File(output_path, mode="w")
input_file = os.path.join(directory, 'cifar-100-python.tar.gz')
tar_file = tarfile.open(input_file, 'r:gz')
file = tar_file.extractfile('cifar-100-python/train')
try:
if six.PY3:
train = cPickle.load(file, encoding='latin1')
else:
train = cPickle.load(file)
finally:
file.close()
train_features = train['data'].reshape(train['data'].shape[0],
3, 32, 32)
train_coarse_labels = numpy.array(train['coarse_labels'],
dtype=numpy.uint8)
train_fine_labels = numpy.array(train['fine_labels'],
dtype=numpy.uint8)
file = tar_file.extractfile('cifar-100-python/test')
try:
if six.PY3:
test = cPickle.load(file, encoding='latin1')
else:
test = cPickle.load(file)
finally:
file.close()
test_features = test['data'].reshape(test['data'].shape[0],
3, 32, 32)
test_coarse_labels = numpy.array(test['coarse_labels'], dtype=numpy.uint8)
test_fine_labels = numpy.array(test['fine_labels'], dtype=numpy.uint8)
data = (('train', 'features', train_features),
('train', 'coarse_labels', train_coarse_labels.reshape((-1, 1))),
('train', 'fine_labels', train_fine_labels.reshape((-1, 1))),
('test', 'features', test_features),
('test', 'coarse_labels', test_coarse_labels.reshape((-1, 1))),
('test', 'fine_labels', test_fine_labels.reshape((-1, 1))))
fill_hdf5_file(h5file, data)
h5file['features'].dims[0].label = 'batch'
h5file['features'].dims[1].label = 'channel'
h5file['features'].dims[2].label = 'height'
h5file['features'].dims[3].label = 'width'
h5file['coarse_labels'].dims[0].label = 'batch'
h5file['coarse_labels'].dims[1].label = 'index'
h5file['fine_labels'].dims[0].label = 'batch'
h5file['fine_labels'].dims[1].label = 'index'
h5file.flush()
h5file.close()
return (output_path,) | python | def convert_cifar100(directory, output_directory,
output_filename='cifar100.hdf5'):
"""Converts the CIFAR-100 dataset to HDF5.
Converts the CIFAR-100 dataset to an HDF5 dataset compatible with
:class:`fuel.datasets.CIFAR100`. The converted dataset is saved as
'cifar100.hdf5'.
This method assumes the existence of the following file:
`cifar-100-python.tar.gz`
Parameters
----------
directory : str
Directory in which the required input files reside.
output_directory : str
Directory in which to save the converted dataset.
output_filename : str, optional
Name of the saved dataset. Defaults to 'cifar100.hdf5'.
Returns
-------
output_paths : tuple of str
Single-element tuple containing the path to the converted dataset.
"""
output_path = os.path.join(output_directory, output_filename)
h5file = h5py.File(output_path, mode="w")
input_file = os.path.join(directory, 'cifar-100-python.tar.gz')
tar_file = tarfile.open(input_file, 'r:gz')
file = tar_file.extractfile('cifar-100-python/train')
try:
if six.PY3:
train = cPickle.load(file, encoding='latin1')
else:
train = cPickle.load(file)
finally:
file.close()
train_features = train['data'].reshape(train['data'].shape[0],
3, 32, 32)
train_coarse_labels = numpy.array(train['coarse_labels'],
dtype=numpy.uint8)
train_fine_labels = numpy.array(train['fine_labels'],
dtype=numpy.uint8)
file = tar_file.extractfile('cifar-100-python/test')
try:
if six.PY3:
test = cPickle.load(file, encoding='latin1')
else:
test = cPickle.load(file)
finally:
file.close()
test_features = test['data'].reshape(test['data'].shape[0],
3, 32, 32)
test_coarse_labels = numpy.array(test['coarse_labels'], dtype=numpy.uint8)
test_fine_labels = numpy.array(test['fine_labels'], dtype=numpy.uint8)
data = (('train', 'features', train_features),
('train', 'coarse_labels', train_coarse_labels.reshape((-1, 1))),
('train', 'fine_labels', train_fine_labels.reshape((-1, 1))),
('test', 'features', test_features),
('test', 'coarse_labels', test_coarse_labels.reshape((-1, 1))),
('test', 'fine_labels', test_fine_labels.reshape((-1, 1))))
fill_hdf5_file(h5file, data)
h5file['features'].dims[0].label = 'batch'
h5file['features'].dims[1].label = 'channel'
h5file['features'].dims[2].label = 'height'
h5file['features'].dims[3].label = 'width'
h5file['coarse_labels'].dims[0].label = 'batch'
h5file['coarse_labels'].dims[1].label = 'index'
h5file['fine_labels'].dims[0].label = 'batch'
h5file['fine_labels'].dims[1].label = 'index'
h5file.flush()
h5file.close()
return (output_path,) | [
"def",
"convert_cifar100",
"(",
"directory",
",",
"output_directory",
",",
"output_filename",
"=",
"'cifar100.hdf5'",
")",
":",
"output_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"output_directory",
",",
"output_filename",
")",
"h5file",
"=",
"h5py",
".",
"File",
"(",
"output_path",
",",
"mode",
"=",
"\"w\"",
")",
"input_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"'cifar-100-python.tar.gz'",
")",
"tar_file",
"=",
"tarfile",
".",
"open",
"(",
"input_file",
",",
"'r:gz'",
")",
"file",
"=",
"tar_file",
".",
"extractfile",
"(",
"'cifar-100-python/train'",
")",
"try",
":",
"if",
"six",
".",
"PY3",
":",
"train",
"=",
"cPickle",
".",
"load",
"(",
"file",
",",
"encoding",
"=",
"'latin1'",
")",
"else",
":",
"train",
"=",
"cPickle",
".",
"load",
"(",
"file",
")",
"finally",
":",
"file",
".",
"close",
"(",
")",
"train_features",
"=",
"train",
"[",
"'data'",
"]",
".",
"reshape",
"(",
"train",
"[",
"'data'",
"]",
".",
"shape",
"[",
"0",
"]",
",",
"3",
",",
"32",
",",
"32",
")",
"train_coarse_labels",
"=",
"numpy",
".",
"array",
"(",
"train",
"[",
"'coarse_labels'",
"]",
",",
"dtype",
"=",
"numpy",
".",
"uint8",
")",
"train_fine_labels",
"=",
"numpy",
".",
"array",
"(",
"train",
"[",
"'fine_labels'",
"]",
",",
"dtype",
"=",
"numpy",
".",
"uint8",
")",
"file",
"=",
"tar_file",
".",
"extractfile",
"(",
"'cifar-100-python/test'",
")",
"try",
":",
"if",
"six",
".",
"PY3",
":",
"test",
"=",
"cPickle",
".",
"load",
"(",
"file",
",",
"encoding",
"=",
"'latin1'",
")",
"else",
":",
"test",
"=",
"cPickle",
".",
"load",
"(",
"file",
")",
"finally",
":",
"file",
".",
"close",
"(",
")",
"test_features",
"=",
"test",
"[",
"'data'",
"]",
".",
"reshape",
"(",
"test",
"[",
"'data'",
"]",
".",
"shape",
"[",
"0",
"]",
",",
"3",
",",
"32",
",",
"32",
")",
"test_coarse_labels",
"=",
"numpy",
".",
"array",
"(",
"test",
"[",
"'coarse_labels'",
"]",
",",
"dtype",
"=",
"numpy",
".",
"uint8",
")",
"test_fine_labels",
"=",
"numpy",
".",
"array",
"(",
"test",
"[",
"'fine_labels'",
"]",
",",
"dtype",
"=",
"numpy",
".",
"uint8",
")",
"data",
"=",
"(",
"(",
"'train'",
",",
"'features'",
",",
"train_features",
")",
",",
"(",
"'train'",
",",
"'coarse_labels'",
",",
"train_coarse_labels",
".",
"reshape",
"(",
"(",
"-",
"1",
",",
"1",
")",
")",
")",
",",
"(",
"'train'",
",",
"'fine_labels'",
",",
"train_fine_labels",
".",
"reshape",
"(",
"(",
"-",
"1",
",",
"1",
")",
")",
")",
",",
"(",
"'test'",
",",
"'features'",
",",
"test_features",
")",
",",
"(",
"'test'",
",",
"'coarse_labels'",
",",
"test_coarse_labels",
".",
"reshape",
"(",
"(",
"-",
"1",
",",
"1",
")",
")",
")",
",",
"(",
"'test'",
",",
"'fine_labels'",
",",
"test_fine_labels",
".",
"reshape",
"(",
"(",
"-",
"1",
",",
"1",
")",
")",
")",
")",
"fill_hdf5_file",
"(",
"h5file",
",",
"data",
")",
"h5file",
"[",
"'features'",
"]",
".",
"dims",
"[",
"0",
"]",
".",
"label",
"=",
"'batch'",
"h5file",
"[",
"'features'",
"]",
".",
"dims",
"[",
"1",
"]",
".",
"label",
"=",
"'channel'",
"h5file",
"[",
"'features'",
"]",
".",
"dims",
"[",
"2",
"]",
".",
"label",
"=",
"'height'",
"h5file",
"[",
"'features'",
"]",
".",
"dims",
"[",
"3",
"]",
".",
"label",
"=",
"'width'",
"h5file",
"[",
"'coarse_labels'",
"]",
".",
"dims",
"[",
"0",
"]",
".",
"label",
"=",
"'batch'",
"h5file",
"[",
"'coarse_labels'",
"]",
".",
"dims",
"[",
"1",
"]",
".",
"label",
"=",
"'index'",
"h5file",
"[",
"'fine_labels'",
"]",
".",
"dims",
"[",
"0",
"]",
".",
"label",
"=",
"'batch'",
"h5file",
"[",
"'fine_labels'",
"]",
".",
"dims",
"[",
"1",
"]",
".",
"label",
"=",
"'index'",
"h5file",
".",
"flush",
"(",
")",
"h5file",
".",
"close",
"(",
")",
"return",
"(",
"output_path",
",",
")"
] | Converts the CIFAR-100 dataset to HDF5.
Converts the CIFAR-100 dataset to an HDF5 dataset compatible with
:class:`fuel.datasets.CIFAR100`. The converted dataset is saved as
'cifar100.hdf5'.
This method assumes the existence of the following file:
`cifar-100-python.tar.gz`
Parameters
----------
directory : str
Directory in which the required input files reside.
output_directory : str
Directory in which to save the converted dataset.
output_filename : str, optional
Name of the saved dataset. Defaults to 'cifar100.hdf5'.
Returns
-------
output_paths : tuple of str
Single-element tuple containing the path to the converted dataset. | [
"Converts",
"the",
"CIFAR",
"-",
"100",
"dataset",
"to",
"HDF5",
"."
] | 1d6292dc25e3a115544237e392e61bff6631d23c | https://github.com/mila-iqia/fuel/blob/1d6292dc25e3a115544237e392e61bff6631d23c/fuel/converters/cifar100.py#L15-L95 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.