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 listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
Chilipp/psyplot | psyplot/data.py | ArrayList.coords_intersect | def coords_intersect(self):
"""Coordinates of the arrays in this list that are used in all arrays
"""
return set.intersection(*map(
set, (getattr(arr, 'coords_intersect', arr.coords) for arr in self)
)) | python | def coords_intersect(self):
"""Coordinates of the arrays in this list that are used in all arrays
"""
return set.intersection(*map(
set, (getattr(arr, 'coords_intersect', arr.coords) for arr in self)
)) | [
"def",
"coords_intersect",
"(",
"self",
")",
":",
"return",
"set",
".",
"intersection",
"(",
"*",
"map",
"(",
"set",
",",
"(",
"getattr",
"(",
"arr",
",",
"'coords_intersect'",
",",
"arr",
".",
"coords",
")",
"for",
"arr",
"in",
"self",
")",
")",
")"... | Coordinates of the arrays in this list that are used in all arrays | [
"Coordinates",
"of",
"the",
"arrays",
"in",
"this",
"list",
"that",
"are",
"used",
"in",
"all",
"arrays"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L3263-L3268 | train | 43,400 |
Chilipp/psyplot | psyplot/data.py | ArrayList.with_plotter | def with_plotter(self):
"""The arrays in this instance that are visualized with a plotter"""
return self.__class__(
(arr for arr in self if arr.psy.plotter is not None),
auto_update=bool(self.auto_update)) | python | def with_plotter(self):
"""The arrays in this instance that are visualized with a plotter"""
return self.__class__(
(arr for arr in self if arr.psy.plotter is not None),
auto_update=bool(self.auto_update)) | [
"def",
"with_plotter",
"(",
"self",
")",
":",
"return",
"self",
".",
"__class__",
"(",
"(",
"arr",
"for",
"arr",
"in",
"self",
"if",
"arr",
".",
"psy",
".",
"plotter",
"is",
"not",
"None",
")",
",",
"auto_update",
"=",
"bool",
"(",
"self",
".",
"au... | The arrays in this instance that are visualized with a plotter | [
"The",
"arrays",
"in",
"this",
"instance",
"that",
"are",
"visualized",
"with",
"a",
"plotter"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L3271-L3275 | train | 43,401 |
Chilipp/psyplot | psyplot/data.py | ArrayList.rename | def rename(self, arr, new_name=True):
"""
Rename an array to find a name that isn't already in the list
Parameters
----------
arr: InteractiveBase
A :class:`InteractiveArray` or :class:`InteractiveList` instance
whose name shall be checked
new_name: bool or str
If False, and the ``arr_name`` attribute of the new array is
already in the list, a ValueError is raised.
If True and the ``arr_name`` attribute of the new array is not
already in the list, the name is not changed. Otherwise, if the
array name is already in use, `new_name` is set to 'arr{0}'.
If not True, this will be used for renaming (if the array name of
`arr` is in use or not). ``'{0}'`` is replaced by a counter
Returns
-------
InteractiveBase
`arr` with changed ``arr_name`` attribute
bool or None
True, if the array has been renamed, False if not and None if the
array is already in the list
Raises
------
ValueError
If it was impossible to find a name that isn't already in the list
ValueError
If `new_name` is False and the array is already in the list"""
name_in_me = arr.psy.arr_name in self.arr_names
if not name_in_me:
return arr, False
elif name_in_me and not self._contains_array(arr):
if new_name is False:
raise ValueError(
"Array name %s is already in use! Set the `new_name` "
"parameter to None for renaming!" % arr.psy.arr_name)
elif new_name is True:
new_name = new_name if isstring(new_name) else 'arr{0}'
arr.psy.arr_name = self.next_available_name(new_name)
return arr, True
return arr, None | python | def rename(self, arr, new_name=True):
"""
Rename an array to find a name that isn't already in the list
Parameters
----------
arr: InteractiveBase
A :class:`InteractiveArray` or :class:`InteractiveList` instance
whose name shall be checked
new_name: bool or str
If False, and the ``arr_name`` attribute of the new array is
already in the list, a ValueError is raised.
If True and the ``arr_name`` attribute of the new array is not
already in the list, the name is not changed. Otherwise, if the
array name is already in use, `new_name` is set to 'arr{0}'.
If not True, this will be used for renaming (if the array name of
`arr` is in use or not). ``'{0}'`` is replaced by a counter
Returns
-------
InteractiveBase
`arr` with changed ``arr_name`` attribute
bool or None
True, if the array has been renamed, False if not and None if the
array is already in the list
Raises
------
ValueError
If it was impossible to find a name that isn't already in the list
ValueError
If `new_name` is False and the array is already in the list"""
name_in_me = arr.psy.arr_name in self.arr_names
if not name_in_me:
return arr, False
elif name_in_me and not self._contains_array(arr):
if new_name is False:
raise ValueError(
"Array name %s is already in use! Set the `new_name` "
"parameter to None for renaming!" % arr.psy.arr_name)
elif new_name is True:
new_name = new_name if isstring(new_name) else 'arr{0}'
arr.psy.arr_name = self.next_available_name(new_name)
return arr, True
return arr, None | [
"def",
"rename",
"(",
"self",
",",
"arr",
",",
"new_name",
"=",
"True",
")",
":",
"name_in_me",
"=",
"arr",
".",
"psy",
".",
"arr_name",
"in",
"self",
".",
"arr_names",
"if",
"not",
"name_in_me",
":",
"return",
"arr",
",",
"False",
"elif",
"name_in_me"... | Rename an array to find a name that isn't already in the list
Parameters
----------
arr: InteractiveBase
A :class:`InteractiveArray` or :class:`InteractiveList` instance
whose name shall be checked
new_name: bool or str
If False, and the ``arr_name`` attribute of the new array is
already in the list, a ValueError is raised.
If True and the ``arr_name`` attribute of the new array is not
already in the list, the name is not changed. Otherwise, if the
array name is already in use, `new_name` is set to 'arr{0}'.
If not True, this will be used for renaming (if the array name of
`arr` is in use or not). ``'{0}'`` is replaced by a counter
Returns
-------
InteractiveBase
`arr` with changed ``arr_name`` attribute
bool or None
True, if the array has been renamed, False if not and None if the
array is already in the list
Raises
------
ValueError
If it was impossible to find a name that isn't already in the list
ValueError
If `new_name` is False and the array is already in the list | [
"Rename",
"an",
"array",
"to",
"find",
"a",
"name",
"that",
"isn",
"t",
"already",
"in",
"the",
"list"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L3312-L3356 | train | 43,402 |
Chilipp/psyplot | psyplot/data.py | ArrayList.copy | def copy(self, deep=False):
"""Returns a copy of the list
Parameters
----------
deep: bool
If False (default), only the list is copied and not the contained
arrays, otherwise the contained arrays are deep copied"""
if not deep:
return self.__class__(self[:], attrs=self.attrs.copy(),
auto_update=not bool(self.no_auto_update))
else:
return self.__class__(
[arr.psy.copy(deep) for arr in self], attrs=self.attrs.copy(),
auto_update=not bool(self.auto_update)) | python | def copy(self, deep=False):
"""Returns a copy of the list
Parameters
----------
deep: bool
If False (default), only the list is copied and not the contained
arrays, otherwise the contained arrays are deep copied"""
if not deep:
return self.__class__(self[:], attrs=self.attrs.copy(),
auto_update=not bool(self.no_auto_update))
else:
return self.__class__(
[arr.psy.copy(deep) for arr in self], attrs=self.attrs.copy(),
auto_update=not bool(self.auto_update)) | [
"def",
"copy",
"(",
"self",
",",
"deep",
"=",
"False",
")",
":",
"if",
"not",
"deep",
":",
"return",
"self",
".",
"__class__",
"(",
"self",
"[",
":",
"]",
",",
"attrs",
"=",
"self",
".",
"attrs",
".",
"copy",
"(",
")",
",",
"auto_update",
"=",
... | Returns a copy of the list
Parameters
----------
deep: bool
If False (default), only the list is copied and not the contained
arrays, otherwise the contained arrays are deep copied | [
"Returns",
"a",
"copy",
"of",
"the",
"list"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L3384-L3398 | train | 43,403 |
Chilipp/psyplot | psyplot/data.py | ArrayList._get_tnames | def _get_tnames(self):
"""Get the name of the time coordinate of the objects in this list"""
tnames = set()
for arr in self:
if isinstance(arr, InteractiveList):
tnames.update(arr.get_tnames())
else:
tnames.add(arr.psy.decoder.get_tname(
next(arr.psy.iter_base_variables), arr.coords))
return tnames - {None} | python | def _get_tnames(self):
"""Get the name of the time coordinate of the objects in this list"""
tnames = set()
for arr in self:
if isinstance(arr, InteractiveList):
tnames.update(arr.get_tnames())
else:
tnames.add(arr.psy.decoder.get_tname(
next(arr.psy.iter_base_variables), arr.coords))
return tnames - {None} | [
"def",
"_get_tnames",
"(",
"self",
")",
":",
"tnames",
"=",
"set",
"(",
")",
"for",
"arr",
"in",
"self",
":",
"if",
"isinstance",
"(",
"arr",
",",
"InteractiveList",
")",
":",
"tnames",
".",
"update",
"(",
"arr",
".",
"get_tnames",
"(",
")",
")",
"... | Get the name of the time coordinate of the objects in this list | [
"Get",
"the",
"name",
"of",
"the",
"time",
"coordinate",
"of",
"the",
"objects",
"in",
"this",
"list"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L4015-L4024 | train | 43,404 |
Chilipp/psyplot | psyplot/data.py | ArrayList._register_update | def _register_update(self, method='isel', replot=False, dims={}, fmt={},
force=False, todefault=False):
"""
Register new dimensions and formatoptions for updating. The keywords
are the same as for each single array
Parameters
----------
%(InteractiveArray._register_update.parameters)s"""
for arr in self:
arr.psy._register_update(method=method, replot=replot, dims=dims,
fmt=fmt, force=force, todefault=todefault) | python | def _register_update(self, method='isel', replot=False, dims={}, fmt={},
force=False, todefault=False):
"""
Register new dimensions and formatoptions for updating. The keywords
are the same as for each single array
Parameters
----------
%(InteractiveArray._register_update.parameters)s"""
for arr in self:
arr.psy._register_update(method=method, replot=replot, dims=dims,
fmt=fmt, force=force, todefault=todefault) | [
"def",
"_register_update",
"(",
"self",
",",
"method",
"=",
"'isel'",
",",
"replot",
"=",
"False",
",",
"dims",
"=",
"{",
"}",
",",
"fmt",
"=",
"{",
"}",
",",
"force",
"=",
"False",
",",
"todefault",
"=",
"False",
")",
":",
"for",
"arr",
"in",
"s... | Register new dimensions and formatoptions for updating. The keywords
are the same as for each single array
Parameters
----------
%(InteractiveArray._register_update.parameters)s | [
"Register",
"new",
"dimensions",
"and",
"formatoptions",
"for",
"updating",
".",
"The",
"keywords",
"are",
"the",
"same",
"as",
"for",
"each",
"single",
"array"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L4027-L4039 | train | 43,405 |
Chilipp/psyplot | psyplot/data.py | ArrayList.draw | def draw(self):
"""Draws all the figures in this instance"""
for fig in set(chain(*map(
lambda arr: arr.psy.plotter.figs2draw, self.with_plotter))):
self.logger.debug("Drawing figure %s", fig.number)
fig.canvas.draw()
for arr in self:
if arr.psy.plotter is not None:
arr.psy.plotter._figs2draw.clear()
self.logger.debug("Done drawing.") | python | def draw(self):
"""Draws all the figures in this instance"""
for fig in set(chain(*map(
lambda arr: arr.psy.plotter.figs2draw, self.with_plotter))):
self.logger.debug("Drawing figure %s", fig.number)
fig.canvas.draw()
for arr in self:
if arr.psy.plotter is not None:
arr.psy.plotter._figs2draw.clear()
self.logger.debug("Done drawing.") | [
"def",
"draw",
"(",
"self",
")",
":",
"for",
"fig",
"in",
"set",
"(",
"chain",
"(",
"*",
"map",
"(",
"lambda",
"arr",
":",
"arr",
".",
"psy",
".",
"plotter",
".",
"figs2draw",
",",
"self",
".",
"with_plotter",
")",
")",
")",
":",
"self",
".",
"... | Draws all the figures in this instance | [
"Draws",
"all",
"the",
"figures",
"in",
"this",
"instance"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L4142-L4151 | train | 43,406 |
Chilipp/psyplot | psyplot/data.py | ArrayList._contains_array | def _contains_array(self, val):
"""Checks whether exactly this array is in the list"""
arr = self(arr_name=val.psy.arr_name)[0]
is_not_list = any(
map(lambda a: not isinstance(a, InteractiveList),
[arr, val]))
is_list = any(map(lambda a: isinstance(a, InteractiveList),
[arr, val]))
# if one is an InteractiveList and the other not, they differ
if is_list and is_not_list:
return False
# if both are interactive lists, check the lists
if is_list:
return all(a in arr for a in val) and all(a in val for a in arr)
# else we check the shapes and values
return arr is val | python | def _contains_array(self, val):
"""Checks whether exactly this array is in the list"""
arr = self(arr_name=val.psy.arr_name)[0]
is_not_list = any(
map(lambda a: not isinstance(a, InteractiveList),
[arr, val]))
is_list = any(map(lambda a: isinstance(a, InteractiveList),
[arr, val]))
# if one is an InteractiveList and the other not, they differ
if is_list and is_not_list:
return False
# if both are interactive lists, check the lists
if is_list:
return all(a in arr for a in val) and all(a in val for a in arr)
# else we check the shapes and values
return arr is val | [
"def",
"_contains_array",
"(",
"self",
",",
"val",
")",
":",
"arr",
"=",
"self",
"(",
"arr_name",
"=",
"val",
".",
"psy",
".",
"arr_name",
")",
"[",
"0",
"]",
"is_not_list",
"=",
"any",
"(",
"map",
"(",
"lambda",
"a",
":",
"not",
"isinstance",
"(",... | Checks whether exactly this array is in the list | [
"Checks",
"whether",
"exactly",
"this",
"array",
"is",
"in",
"the",
"list"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L4275-L4290 | train | 43,407 |
Chilipp/psyplot | psyplot/data.py | ArrayList.next_available_name | def next_available_name(self, fmt_str='arr{0}', counter=None):
"""Create a new array out of the given format string
Parameters
----------
format_str: str
The base string to use. ``'{0}'`` will be replaced by a counter
counter: iterable
An iterable where the numbers should be drawn from. If None,
``range(100)`` is used
Returns
-------
str
A possible name that is not in the current project"""
names = self.arr_names
counter = counter or iter(range(1000))
try:
new_name = next(
filter(lambda n: n not in names,
map(fmt_str.format, counter)))
except StopIteration:
raise ValueError(
"{0} already in the list".format(fmt_str))
return new_name | python | def next_available_name(self, fmt_str='arr{0}', counter=None):
"""Create a new array out of the given format string
Parameters
----------
format_str: str
The base string to use. ``'{0}'`` will be replaced by a counter
counter: iterable
An iterable where the numbers should be drawn from. If None,
``range(100)`` is used
Returns
-------
str
A possible name that is not in the current project"""
names = self.arr_names
counter = counter or iter(range(1000))
try:
new_name = next(
filter(lambda n: n not in names,
map(fmt_str.format, counter)))
except StopIteration:
raise ValueError(
"{0} already in the list".format(fmt_str))
return new_name | [
"def",
"next_available_name",
"(",
"self",
",",
"fmt_str",
"=",
"'arr{0}'",
",",
"counter",
"=",
"None",
")",
":",
"names",
"=",
"self",
".",
"arr_names",
"counter",
"=",
"counter",
"or",
"iter",
"(",
"range",
"(",
"1000",
")",
")",
"try",
":",
"new_na... | Create a new array out of the given format string
Parameters
----------
format_str: str
The base string to use. ``'{0}'`` will be replaced by a counter
counter: iterable
An iterable where the numbers should be drawn from. If None,
``range(100)`` is used
Returns
-------
str
A possible name that is not in the current project | [
"Create",
"a",
"new",
"array",
"out",
"of",
"the",
"given",
"format",
"string"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L4328-L4352 | train | 43,408 |
Chilipp/psyplot | psyplot/data.py | ArrayList.append | def append(self, value, new_name=False):
"""
Append a new array to the list
Parameters
----------
value: InteractiveBase
The data object to append to this list
%(ArrayList.rename.parameters.new_name)s
Raises
------
%(ArrayList.rename.raises)s
See Also
--------
list.append, extend, rename"""
arr, renamed = self.rename(value, new_name)
if renamed is not None:
super(ArrayList, self).append(value) | python | def append(self, value, new_name=False):
"""
Append a new array to the list
Parameters
----------
value: InteractiveBase
The data object to append to this list
%(ArrayList.rename.parameters.new_name)s
Raises
------
%(ArrayList.rename.raises)s
See Also
--------
list.append, extend, rename"""
arr, renamed = self.rename(value, new_name)
if renamed is not None:
super(ArrayList, self).append(value) | [
"def",
"append",
"(",
"self",
",",
"value",
",",
"new_name",
"=",
"False",
")",
":",
"arr",
",",
"renamed",
"=",
"self",
".",
"rename",
"(",
"value",
",",
"new_name",
")",
"if",
"renamed",
"is",
"not",
"None",
":",
"super",
"(",
"ArrayList",
",",
"... | Append a new array to the list
Parameters
----------
value: InteractiveBase
The data object to append to this list
%(ArrayList.rename.parameters.new_name)s
Raises
------
%(ArrayList.rename.raises)s
See Also
--------
list.append, extend, rename | [
"Append",
"a",
"new",
"array",
"to",
"the",
"list"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L4355-L4374 | train | 43,409 |
Chilipp/psyplot | psyplot/data.py | ArrayList.extend | def extend(self, iterable, new_name=False):
"""
Add further arrays from an iterable to this list
Parameters
----------
iterable
Any iterable that contains :class:`InteractiveBase` instances
%(ArrayList.rename.parameters.new_name)s
Raises
------
%(ArrayList.rename.raises)s
See Also
--------
list.extend, append, rename"""
# extend those arrays that aren't alredy in the list
super(ArrayList, self).extend(t[0] for t in filter(
lambda t: t[1] is not None, (
self.rename(arr, new_name) for arr in iterable))) | python | def extend(self, iterable, new_name=False):
"""
Add further arrays from an iterable to this list
Parameters
----------
iterable
Any iterable that contains :class:`InteractiveBase` instances
%(ArrayList.rename.parameters.new_name)s
Raises
------
%(ArrayList.rename.raises)s
See Also
--------
list.extend, append, rename"""
# extend those arrays that aren't alredy in the list
super(ArrayList, self).extend(t[0] for t in filter(
lambda t: t[1] is not None, (
self.rename(arr, new_name) for arr in iterable))) | [
"def",
"extend",
"(",
"self",
",",
"iterable",
",",
"new_name",
"=",
"False",
")",
":",
"# extend those arrays that aren't alredy in the list",
"super",
"(",
"ArrayList",
",",
"self",
")",
".",
"extend",
"(",
"t",
"[",
"0",
"]",
"for",
"t",
"in",
"filter",
... | Add further arrays from an iterable to this list
Parameters
----------
iterable
Any iterable that contains :class:`InteractiveBase` instances
%(ArrayList.rename.parameters.new_name)s
Raises
------
%(ArrayList.rename.raises)s
See Also
--------
list.extend, append, rename | [
"Add",
"further",
"arrays",
"from",
"an",
"iterable",
"to",
"this",
"list"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L4377-L4397 | train | 43,410 |
Chilipp/psyplot | psyplot/data.py | ArrayList.remove | def remove(self, arr):
"""Removes an array from the list
Parameters
----------
arr: str or :class:`InteractiveBase`
The array name or the data object in this list to remove
Raises
------
ValueError
If no array with the specified array name is in the list"""
name = arr if isinstance(arr, six.string_types) else arr.psy.arr_name
if arr not in self:
raise ValueError(
"Array {0} not in the list".format(name))
for i, arr in enumerate(self):
if arr.psy.arr_name == name:
del self[i]
return
raise ValueError(
"No array found with name {0}".format(name)) | python | def remove(self, arr):
"""Removes an array from the list
Parameters
----------
arr: str or :class:`InteractiveBase`
The array name or the data object in this list to remove
Raises
------
ValueError
If no array with the specified array name is in the list"""
name = arr if isinstance(arr, six.string_types) else arr.psy.arr_name
if arr not in self:
raise ValueError(
"Array {0} not in the list".format(name))
for i, arr in enumerate(self):
if arr.psy.arr_name == name:
del self[i]
return
raise ValueError(
"No array found with name {0}".format(name)) | [
"def",
"remove",
"(",
"self",
",",
"arr",
")",
":",
"name",
"=",
"arr",
"if",
"isinstance",
"(",
"arr",
",",
"six",
".",
"string_types",
")",
"else",
"arr",
".",
"psy",
".",
"arr_name",
"if",
"arr",
"not",
"in",
"self",
":",
"raise",
"ValueError",
... | Removes an array from the list
Parameters
----------
arr: str or :class:`InteractiveBase`
The array name or the data object in this list to remove
Raises
------
ValueError
If no array with the specified array name is in the list | [
"Removes",
"an",
"array",
"from",
"the",
"list"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L4399-L4420 | train | 43,411 |
Chilipp/psyplot | psyplot/data.py | InteractiveList._register_update | def _register_update(self, method='isel', replot=False, dims={}, fmt={},
force=False, todefault=False):
"""
Register new dimensions and formatoptions for updating
Parameters
----------
%(InteractiveArray._register_update.parameters)s"""
ArrayList._register_update(self, method=method, dims=dims)
InteractiveBase._register_update(self, fmt=fmt, todefault=todefault,
replot=bool(dims) or replot,
force=force) | python | def _register_update(self, method='isel', replot=False, dims={}, fmt={},
force=False, todefault=False):
"""
Register new dimensions and formatoptions for updating
Parameters
----------
%(InteractiveArray._register_update.parameters)s"""
ArrayList._register_update(self, method=method, dims=dims)
InteractiveBase._register_update(self, fmt=fmt, todefault=todefault,
replot=bool(dims) or replot,
force=force) | [
"def",
"_register_update",
"(",
"self",
",",
"method",
"=",
"'isel'",
",",
"replot",
"=",
"False",
",",
"dims",
"=",
"{",
"}",
",",
"fmt",
"=",
"{",
"}",
",",
"force",
"=",
"False",
",",
"todefault",
"=",
"False",
")",
":",
"ArrayList",
".",
"_regi... | Register new dimensions and formatoptions for updating
Parameters
----------
%(InteractiveArray._register_update.parameters)s | [
"Register",
"new",
"dimensions",
"and",
"formatoptions",
"for",
"updating"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L4602-L4613 | train | 43,412 |
Chilipp/psyplot | psyplot/data.py | InteractiveList.from_dataset | def from_dataset(cls, *args, **kwargs):
"""
Create an InteractiveList instance from the given base dataset
Parameters
----------
%(ArrayList.from_dataset.parameters.no_plotter)s
plotter: psyplot.plotter.Plotter
The plotter instance that is used to visualize the data in this
list
make_plot: bool
If True, the plot is made
Other Parameters
----------------
%(ArrayList.from_dataset.other_parameters.no_args_kwargs)s
``**kwargs``
Further keyword arguments may point to any of the dimensions of the
data (see `dims`)
Returns
-------
%(ArrayList.from_dataset.returns)s"""
plotter = kwargs.pop('plotter', None)
make_plot = kwargs.pop('make_plot', True)
instance = super(InteractiveList, cls).from_dataset(*args, **kwargs)
if plotter is not None:
plotter.initialize_plot(instance, make_plot=make_plot)
return instance | python | def from_dataset(cls, *args, **kwargs):
"""
Create an InteractiveList instance from the given base dataset
Parameters
----------
%(ArrayList.from_dataset.parameters.no_plotter)s
plotter: psyplot.plotter.Plotter
The plotter instance that is used to visualize the data in this
list
make_plot: bool
If True, the plot is made
Other Parameters
----------------
%(ArrayList.from_dataset.other_parameters.no_args_kwargs)s
``**kwargs``
Further keyword arguments may point to any of the dimensions of the
data (see `dims`)
Returns
-------
%(ArrayList.from_dataset.returns)s"""
plotter = kwargs.pop('plotter', None)
make_plot = kwargs.pop('make_plot', True)
instance = super(InteractiveList, cls).from_dataset(*args, **kwargs)
if plotter is not None:
plotter.initialize_plot(instance, make_plot=make_plot)
return instance | [
"def",
"from_dataset",
"(",
"cls",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"plotter",
"=",
"kwargs",
".",
"pop",
"(",
"'plotter'",
",",
"None",
")",
"make_plot",
"=",
"kwargs",
".",
"pop",
"(",
"'make_plot'",
",",
"True",
")",
"instance"... | Create an InteractiveList instance from the given base dataset
Parameters
----------
%(ArrayList.from_dataset.parameters.no_plotter)s
plotter: psyplot.plotter.Plotter
The plotter instance that is used to visualize the data in this
list
make_plot: bool
If True, the plot is made
Other Parameters
----------------
%(ArrayList.from_dataset.other_parameters.no_args_kwargs)s
``**kwargs``
Further keyword arguments may point to any of the dimensions of the
data (see `dims`)
Returns
-------
%(ArrayList.from_dataset.returns)s | [
"Create",
"an",
"InteractiveList",
"instance",
"from",
"the",
"given",
"base",
"dataset"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L4675-L4703 | train | 43,413 |
mfcloud/python-zvm-sdk | tools/sample.py | capture_guest | def capture_guest(userid):
"""Caputre a virtual machine image.
Input parameters:
:userid: USERID of the guest, last 8 if length > 8
Output parameters:
:image_name: Image name that captured
"""
# check power state, if down, start it
ret = sdk_client.send_request('guest_get_power_state', userid)
power_status = ret['output']
if power_status == 'off':
sdk_client.send_request('guest_start', userid)
# TODO: how much time?
time.sleep(1)
# do capture
image_name = 'image_captured_%03d' % (time.time() % 1000)
sdk_client.send_request('guest_capture', userid, image_name,
capture_type='rootonly', compress_level=6)
return image_name | python | def capture_guest(userid):
"""Caputre a virtual machine image.
Input parameters:
:userid: USERID of the guest, last 8 if length > 8
Output parameters:
:image_name: Image name that captured
"""
# check power state, if down, start it
ret = sdk_client.send_request('guest_get_power_state', userid)
power_status = ret['output']
if power_status == 'off':
sdk_client.send_request('guest_start', userid)
# TODO: how much time?
time.sleep(1)
# do capture
image_name = 'image_captured_%03d' % (time.time() % 1000)
sdk_client.send_request('guest_capture', userid, image_name,
capture_type='rootonly', compress_level=6)
return image_name | [
"def",
"capture_guest",
"(",
"userid",
")",
":",
"# check power state, if down, start it",
"ret",
"=",
"sdk_client",
".",
"send_request",
"(",
"'guest_get_power_state'",
",",
"userid",
")",
"power_status",
"=",
"ret",
"[",
"'output'",
"]",
"if",
"power_status",
"=="... | Caputre a virtual machine image.
Input parameters:
:userid: USERID of the guest, last 8 if length > 8
Output parameters:
:image_name: Image name that captured | [
"Caputre",
"a",
"virtual",
"machine",
"image",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/tools/sample.py#L71-L92 | train | 43,414 |
mfcloud/python-zvm-sdk | tools/sample.py | import_image | def import_image(image_path, os_version):
"""Import image.
Input parameters:
:image_path: Image file path
:os_version: Operating system version. e.g. rhel7.2
"""
image_name = os.path.basename(image_path)
print("Checking if image %s exists or not, import it if not exists" %
image_name)
image_info = sdk_client.send_request('image_query', imagename=image_name)
if 'overallRC' in image_info and image_info['overallRC']:
print("Importing image %s ..." % image_name)
url = 'file://' + image_path
ret = sdk_client.send_request('image_import', image_name, url,
{'os_version': os_version})
else:
print("Image %s already exists" % image_name) | python | def import_image(image_path, os_version):
"""Import image.
Input parameters:
:image_path: Image file path
:os_version: Operating system version. e.g. rhel7.2
"""
image_name = os.path.basename(image_path)
print("Checking if image %s exists or not, import it if not exists" %
image_name)
image_info = sdk_client.send_request('image_query', imagename=image_name)
if 'overallRC' in image_info and image_info['overallRC']:
print("Importing image %s ..." % image_name)
url = 'file://' + image_path
ret = sdk_client.send_request('image_import', image_name, url,
{'os_version': os_version})
else:
print("Image %s already exists" % image_name) | [
"def",
"import_image",
"(",
"image_path",
",",
"os_version",
")",
":",
"image_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"image_path",
")",
"print",
"(",
"\"Checking if image %s exists or not, import it if not exists\"",
"%",
"image_name",
")",
"image_info",... | Import image.
Input parameters:
:image_path: Image file path
:os_version: Operating system version. e.g. rhel7.2 | [
"Import",
"image",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/tools/sample.py#L95-L112 | train | 43,415 |
mfcloud/python-zvm-sdk | tools/sample.py | _run_guest | def _run_guest(userid, image_path, os_version, profile,
cpu, memory, network_info, disks_list):
"""Deploy and provision a virtual machine.
Input parameters:
:userid: USERID of the guest, no more than 8.
:image_name: path of the image file
:os_version: os version of the image file
:profile: profile of the userid
:cpu: the number of vcpus
:memory: memory
:network_info: dict of network info.members:
:ip_addr: ip address of vm
:gateway: gateway of net
:vswitch_name: switch name
:cidr: CIDR
:disks_list: list of disks to add.eg:
disks_list = [{'size': '3g',
'is_boot_disk': True,
'disk_pool': 'ECKD:xcateckd'}]
"""
# Import image if not exists
import_image(image_path, os_version)
# Start time
spawn_start = time.time()
# Create userid
print("Creating userid %s ..." % userid)
ret = sdk_client.send_request('guest_create', userid, cpu, memory,
disk_list=disks_list,
user_profile=profile)
if ret['overallRC']:
print 'guest_create error:%s' % ret
return -1
# Deploy image to root disk
image_name = os.path.basename(image_path)
print("Deploying %s to %s ..." % (image_name, userid))
ret = sdk_client.send_request('guest_deploy', userid, image_name)
if ret['overallRC']:
print 'guest_deploy error:%s' % ret
return -2
# Create network device and configure network interface
print("Configuring network interface for %s ..." % userid)
ret = sdk_client.send_request('guest_create_network_interface', userid,
os_version, [network_info])
if ret['overallRC']:
print 'guest_create_network error:%s' % ret
return -3
# Couple to vswitch
ret = sdk_client.send_request('guest_nic_couple_to_vswitch', userid,
'1000', network_info['vswitch_name'])
if ret['overallRC']:
print 'guest_nic_couple error:%s' % ret
return -4
# Grant user
ret = sdk_client.send_request('vswitch_grant_user',
network_info['vswitch_name'],
userid)
if ret['overallRC']:
print 'vswitch_grant_user error:%s' % ret
return -5
# Power on the vm
print("Starting guest %s" % userid)
ret = sdk_client.send_request('guest_start', userid)
if ret['overallRC']:
print 'guest_start error:%s' % ret
return -6
# End time
spawn_time = time.time() - spawn_start
print "Instance-%s pawned succeeded in %s seconds" % (userid, spawn_time) | python | def _run_guest(userid, image_path, os_version, profile,
cpu, memory, network_info, disks_list):
"""Deploy and provision a virtual machine.
Input parameters:
:userid: USERID of the guest, no more than 8.
:image_name: path of the image file
:os_version: os version of the image file
:profile: profile of the userid
:cpu: the number of vcpus
:memory: memory
:network_info: dict of network info.members:
:ip_addr: ip address of vm
:gateway: gateway of net
:vswitch_name: switch name
:cidr: CIDR
:disks_list: list of disks to add.eg:
disks_list = [{'size': '3g',
'is_boot_disk': True,
'disk_pool': 'ECKD:xcateckd'}]
"""
# Import image if not exists
import_image(image_path, os_version)
# Start time
spawn_start = time.time()
# Create userid
print("Creating userid %s ..." % userid)
ret = sdk_client.send_request('guest_create', userid, cpu, memory,
disk_list=disks_list,
user_profile=profile)
if ret['overallRC']:
print 'guest_create error:%s' % ret
return -1
# Deploy image to root disk
image_name = os.path.basename(image_path)
print("Deploying %s to %s ..." % (image_name, userid))
ret = sdk_client.send_request('guest_deploy', userid, image_name)
if ret['overallRC']:
print 'guest_deploy error:%s' % ret
return -2
# Create network device and configure network interface
print("Configuring network interface for %s ..." % userid)
ret = sdk_client.send_request('guest_create_network_interface', userid,
os_version, [network_info])
if ret['overallRC']:
print 'guest_create_network error:%s' % ret
return -3
# Couple to vswitch
ret = sdk_client.send_request('guest_nic_couple_to_vswitch', userid,
'1000', network_info['vswitch_name'])
if ret['overallRC']:
print 'guest_nic_couple error:%s' % ret
return -4
# Grant user
ret = sdk_client.send_request('vswitch_grant_user',
network_info['vswitch_name'],
userid)
if ret['overallRC']:
print 'vswitch_grant_user error:%s' % ret
return -5
# Power on the vm
print("Starting guest %s" % userid)
ret = sdk_client.send_request('guest_start', userid)
if ret['overallRC']:
print 'guest_start error:%s' % ret
return -6
# End time
spawn_time = time.time() - spawn_start
print "Instance-%s pawned succeeded in %s seconds" % (userid, spawn_time) | [
"def",
"_run_guest",
"(",
"userid",
",",
"image_path",
",",
"os_version",
",",
"profile",
",",
"cpu",
",",
"memory",
",",
"network_info",
",",
"disks_list",
")",
":",
"# Import image if not exists",
"import_image",
"(",
"image_path",
",",
"os_version",
")",
"# S... | Deploy and provision a virtual machine.
Input parameters:
:userid: USERID of the guest, no more than 8.
:image_name: path of the image file
:os_version: os version of the image file
:profile: profile of the userid
:cpu: the number of vcpus
:memory: memory
:network_info: dict of network info.members:
:ip_addr: ip address of vm
:gateway: gateway of net
:vswitch_name: switch name
:cidr: CIDR
:disks_list: list of disks to add.eg:
disks_list = [{'size': '3g',
'is_boot_disk': True,
'disk_pool': 'ECKD:xcateckd'}] | [
"Deploy",
"and",
"provision",
"a",
"virtual",
"machine",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/tools/sample.py#L124-L197 | train | 43,416 |
mfcloud/python-zvm-sdk | tools/sample.py | run_guest | def run_guest():
""" A sample for quick deploy and start a virtual guest."""
global GUEST_USERID
global GUEST_PROFILE
global GUEST_VCPUS
global GUEST_MEMORY
global GUEST_ROOT_DISK_SIZE
global DISK_POOL
global IMAGE_PATH
global IMAGE_OS_VERSION
global GUEST_IP_ADDR
global GATEWAY
global CIDR
global VSWITCH_NAME
network_info = {'ip_addr': GUEST_IP_ADDR,
'gateway_addr': GATEWAY,
'cidr': CIDR,
'vswitch_name': VSWITCH_NAME}
disks_list = [{'size': '%ig' % GUEST_ROOT_DISK_SIZE,
'is_boot_disk': True,
'disk_pool': DISK_POOL}]
_run_guest(GUEST_USERID, IMAGE_PATH, IMAGE_OS_VERSION, GUEST_PROFILE,
GUEST_VCPUS, GUEST_MEMORY, network_info, disks_list) | python | def run_guest():
""" A sample for quick deploy and start a virtual guest."""
global GUEST_USERID
global GUEST_PROFILE
global GUEST_VCPUS
global GUEST_MEMORY
global GUEST_ROOT_DISK_SIZE
global DISK_POOL
global IMAGE_PATH
global IMAGE_OS_VERSION
global GUEST_IP_ADDR
global GATEWAY
global CIDR
global VSWITCH_NAME
network_info = {'ip_addr': GUEST_IP_ADDR,
'gateway_addr': GATEWAY,
'cidr': CIDR,
'vswitch_name': VSWITCH_NAME}
disks_list = [{'size': '%ig' % GUEST_ROOT_DISK_SIZE,
'is_boot_disk': True,
'disk_pool': DISK_POOL}]
_run_guest(GUEST_USERID, IMAGE_PATH, IMAGE_OS_VERSION, GUEST_PROFILE,
GUEST_VCPUS, GUEST_MEMORY, network_info, disks_list) | [
"def",
"run_guest",
"(",
")",
":",
"global",
"GUEST_USERID",
"global",
"GUEST_PROFILE",
"global",
"GUEST_VCPUS",
"global",
"GUEST_MEMORY",
"global",
"GUEST_ROOT_DISK_SIZE",
"global",
"DISK_POOL",
"global",
"IMAGE_PATH",
"global",
"IMAGE_OS_VERSION",
"global",
"GUEST_IP_AD... | A sample for quick deploy and start a virtual guest. | [
"A",
"sample",
"for",
"quick",
"deploy",
"and",
"start",
"a",
"virtual",
"guest",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/tools/sample.py#L200-L224 | train | 43,417 |
mfcloud/python-zvm-sdk | zvmsdk/sdkwsgi/validation/__init__.py | _remove_unexpected_query_parameters | def _remove_unexpected_query_parameters(schema, req):
"""Remove unexpected properties from the req.GET."""
additional_properties = schema.get('addtionalProperties', True)
if additional_properties:
pattern_regexes = []
patterns = schema.get('patternProperties', None)
if patterns:
for regex in patterns:
pattern_regexes.append(re.compile(regex))
for param in set(req.GET.keys()):
if param not in schema['properties'].keys():
if not (list(regex for regex in pattern_regexes if
regex.match(param))):
del req.GET[param] | python | def _remove_unexpected_query_parameters(schema, req):
"""Remove unexpected properties from the req.GET."""
additional_properties = schema.get('addtionalProperties', True)
if additional_properties:
pattern_regexes = []
patterns = schema.get('patternProperties', None)
if patterns:
for regex in patterns:
pattern_regexes.append(re.compile(regex))
for param in set(req.GET.keys()):
if param not in schema['properties'].keys():
if not (list(regex for regex in pattern_regexes if
regex.match(param))):
del req.GET[param] | [
"def",
"_remove_unexpected_query_parameters",
"(",
"schema",
",",
"req",
")",
":",
"additional_properties",
"=",
"schema",
".",
"get",
"(",
"'addtionalProperties'",
",",
"True",
")",
"if",
"additional_properties",
":",
"pattern_regexes",
"=",
"[",
"]",
"patterns",
... | Remove unexpected properties from the req.GET. | [
"Remove",
"unexpected",
"properties",
"from",
"the",
"req",
".",
"GET",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/sdkwsgi/validation/__init__.py#L111-L127 | train | 43,418 |
mfcloud/python-zvm-sdk | zvmsdk/sdkwsgi/validation/__init__.py | query_schema | def query_schema(query_params_schema, min_version=None,
max_version=None):
"""Register a schema to validate request query parameters."""
def add_validator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
if 'req' in kwargs:
req = kwargs['req']
else:
req = args[1]
if req.environ['wsgiorg.routing_args'][1]:
if _schema_validation_helper(query_params_schema,
req.environ['wsgiorg.routing_args'][1],
args, kwargs, is_body=False):
_remove_unexpected_query_parameters(query_params_schema,
req)
else:
if _schema_validation_helper(query_params_schema,
req.GET.dict_of_lists(),
args, kwargs, is_body=False):
_remove_unexpected_query_parameters(query_params_schema,
req)
return func(*args, **kwargs)
return wrapper
return add_validator | python | def query_schema(query_params_schema, min_version=None,
max_version=None):
"""Register a schema to validate request query parameters."""
def add_validator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
if 'req' in kwargs:
req = kwargs['req']
else:
req = args[1]
if req.environ['wsgiorg.routing_args'][1]:
if _schema_validation_helper(query_params_schema,
req.environ['wsgiorg.routing_args'][1],
args, kwargs, is_body=False):
_remove_unexpected_query_parameters(query_params_schema,
req)
else:
if _schema_validation_helper(query_params_schema,
req.GET.dict_of_lists(),
args, kwargs, is_body=False):
_remove_unexpected_query_parameters(query_params_schema,
req)
return func(*args, **kwargs)
return wrapper
return add_validator | [
"def",
"query_schema",
"(",
"query_params_schema",
",",
"min_version",
"=",
"None",
",",
"max_version",
"=",
"None",
")",
":",
"def",
"add_validator",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"a... | Register a schema to validate request query parameters. | [
"Register",
"a",
"schema",
"to",
"validate",
"request",
"query",
"parameters",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/sdkwsgi/validation/__init__.py#L130-L157 | train | 43,419 |
mfcloud/python-zvm-sdk | zvmconnector/restclient.py | RESTClient._close_after_stream | def _close_after_stream(self, response, chunk_size):
"""Iterate over the content and ensure the response is closed after."""
# Yield each chunk in the response body
for chunk in response.iter_content(chunk_size=chunk_size):
yield chunk
# Once we're done streaming the body, ensure everything is closed.
response.close() | python | def _close_after_stream(self, response, chunk_size):
"""Iterate over the content and ensure the response is closed after."""
# Yield each chunk in the response body
for chunk in response.iter_content(chunk_size=chunk_size):
yield chunk
# Once we're done streaming the body, ensure everything is closed.
response.close() | [
"def",
"_close_after_stream",
"(",
"self",
",",
"response",
",",
"chunk_size",
")",
":",
"# Yield each chunk in the response body",
"for",
"chunk",
"in",
"response",
".",
"iter_content",
"(",
"chunk_size",
"=",
"chunk_size",
")",
":",
"yield",
"chunk",
"# Once we're... | Iterate over the content and ensure the response is closed after. | [
"Iterate",
"over",
"the",
"content",
"and",
"ensure",
"the",
"response",
"is",
"closed",
"after",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmconnector/restclient.py#L993-L999 | train | 43,420 |
Chilipp/psyplot | psyplot/sphinxext/extended_napoleon.py | process_docstring | def process_docstring(app, what, name, obj, options, lines):
"""Process the docstring for a given python object.
Called when autodoc has read and processed a docstring. `lines` is a list
of docstring lines that `_process_docstring` modifies in place to change
what Sphinx outputs.
The following settings in conf.py control what styles of docstrings will
be parsed:
* ``napoleon_google_docstring`` -- parse Google style docstrings
* ``napoleon_numpy_docstring`` -- parse NumPy style docstrings
Parameters
----------
app : sphinx.application.Sphinx
Application object representing the Sphinx process.
what : str
A string specifying the type of the object to which the docstring
belongs. Valid values: "module", "class", "exception", "function",
"method", "attribute".
name : str
The fully qualified name of the object.
obj : module, class, exception, function, method, or attribute
The object to which the docstring belongs.
options : sphinx.ext.autodoc.Options
The options given to the directive: an object with attributes
inherited_members, undoc_members, show_inheritance and noindex that
are True if the flag option of same name was given to the auto
directive.
lines : list of str
The lines of the docstring, see above.
.. note:: `lines` is modified *in place*
Notes
-----
This function is (to most parts) taken from the :mod:`sphinx.ext.napoleon`
module, sphinx version 1.3.1, and adapted to the classes defined here"""
result_lines = lines
if app.config.napoleon_numpy_docstring:
docstring = ExtendedNumpyDocstring(
result_lines, app.config, app, what, name, obj, options)
result_lines = docstring.lines()
if app.config.napoleon_google_docstring:
docstring = ExtendedGoogleDocstring(
result_lines, app.config, app, what, name, obj, options)
result_lines = docstring.lines()
lines[:] = result_lines[:] | python | def process_docstring(app, what, name, obj, options, lines):
"""Process the docstring for a given python object.
Called when autodoc has read and processed a docstring. `lines` is a list
of docstring lines that `_process_docstring` modifies in place to change
what Sphinx outputs.
The following settings in conf.py control what styles of docstrings will
be parsed:
* ``napoleon_google_docstring`` -- parse Google style docstrings
* ``napoleon_numpy_docstring`` -- parse NumPy style docstrings
Parameters
----------
app : sphinx.application.Sphinx
Application object representing the Sphinx process.
what : str
A string specifying the type of the object to which the docstring
belongs. Valid values: "module", "class", "exception", "function",
"method", "attribute".
name : str
The fully qualified name of the object.
obj : module, class, exception, function, method, or attribute
The object to which the docstring belongs.
options : sphinx.ext.autodoc.Options
The options given to the directive: an object with attributes
inherited_members, undoc_members, show_inheritance and noindex that
are True if the flag option of same name was given to the auto
directive.
lines : list of str
The lines of the docstring, see above.
.. note:: `lines` is modified *in place*
Notes
-----
This function is (to most parts) taken from the :mod:`sphinx.ext.napoleon`
module, sphinx version 1.3.1, and adapted to the classes defined here"""
result_lines = lines
if app.config.napoleon_numpy_docstring:
docstring = ExtendedNumpyDocstring(
result_lines, app.config, app, what, name, obj, options)
result_lines = docstring.lines()
if app.config.napoleon_google_docstring:
docstring = ExtendedGoogleDocstring(
result_lines, app.config, app, what, name, obj, options)
result_lines = docstring.lines()
lines[:] = result_lines[:] | [
"def",
"process_docstring",
"(",
"app",
",",
"what",
",",
"name",
",",
"obj",
",",
"options",
",",
"lines",
")",
":",
"result_lines",
"=",
"lines",
"if",
"app",
".",
"config",
".",
"napoleon_numpy_docstring",
":",
"docstring",
"=",
"ExtendedNumpyDocstring",
... | Process the docstring for a given python object.
Called when autodoc has read and processed a docstring. `lines` is a list
of docstring lines that `_process_docstring` modifies in place to change
what Sphinx outputs.
The following settings in conf.py control what styles of docstrings will
be parsed:
* ``napoleon_google_docstring`` -- parse Google style docstrings
* ``napoleon_numpy_docstring`` -- parse NumPy style docstrings
Parameters
----------
app : sphinx.application.Sphinx
Application object representing the Sphinx process.
what : str
A string specifying the type of the object to which the docstring
belongs. Valid values: "module", "class", "exception", "function",
"method", "attribute".
name : str
The fully qualified name of the object.
obj : module, class, exception, function, method, or attribute
The object to which the docstring belongs.
options : sphinx.ext.autodoc.Options
The options given to the directive: an object with attributes
inherited_members, undoc_members, show_inheritance and noindex that
are True if the flag option of same name was given to the auto
directive.
lines : list of str
The lines of the docstring, see above.
.. note:: `lines` is modified *in place*
Notes
-----
This function is (to most parts) taken from the :mod:`sphinx.ext.napoleon`
module, sphinx version 1.3.1, and adapted to the classes defined here | [
"Process",
"the",
"docstring",
"for",
"a",
"given",
"python",
"object",
"."
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/sphinxext/extended_napoleon.py#L84-L133 | train | 43,421 |
Chilipp/psyplot | psyplot/sphinxext/extended_napoleon.py | setup | def setup(app):
"""Sphinx extension setup function
When the extension is loaded, Sphinx imports this module and executes
the ``setup()`` function, which in turn notifies Sphinx of everything
the extension offers.
Parameters
----------
app : sphinx.application.Sphinx
Application object representing the Sphinx process
Notes
-----
This function uses the setup function of the :mod:`sphinx.ext.napoleon`
module"""
from sphinx.application import Sphinx
if not isinstance(app, Sphinx):
return # probably called by tests
app.connect('autodoc-process-docstring', process_docstring)
return napoleon_setup(app) | python | def setup(app):
"""Sphinx extension setup function
When the extension is loaded, Sphinx imports this module and executes
the ``setup()`` function, which in turn notifies Sphinx of everything
the extension offers.
Parameters
----------
app : sphinx.application.Sphinx
Application object representing the Sphinx process
Notes
-----
This function uses the setup function of the :mod:`sphinx.ext.napoleon`
module"""
from sphinx.application import Sphinx
if not isinstance(app, Sphinx):
return # probably called by tests
app.connect('autodoc-process-docstring', process_docstring)
return napoleon_setup(app) | [
"def",
"setup",
"(",
"app",
")",
":",
"from",
"sphinx",
".",
"application",
"import",
"Sphinx",
"if",
"not",
"isinstance",
"(",
"app",
",",
"Sphinx",
")",
":",
"return",
"# probably called by tests",
"app",
".",
"connect",
"(",
"'autodoc-process-docstring'",
"... | Sphinx extension setup function
When the extension is loaded, Sphinx imports this module and executes
the ``setup()`` function, which in turn notifies Sphinx of everything
the extension offers.
Parameters
----------
app : sphinx.application.Sphinx
Application object representing the Sphinx process
Notes
-----
This function uses the setup function of the :mod:`sphinx.ext.napoleon`
module | [
"Sphinx",
"extension",
"setup",
"function"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/sphinxext/extended_napoleon.py#L136-L157 | train | 43,422 |
Chilipp/psyplot | psyplot/plotter.py | format_time | def format_time(x):
"""Formats date values
This function formats :class:`datetime.datetime` and
:class:`datetime.timedelta` objects (and the corresponding numpy objects)
using the :func:`xarray.core.formatting.format_timestamp` and the
:func:`xarray.core.formatting.format_timedelta` functions.
Parameters
----------
x: object
The value to format. If not a time object, the value is returned
Returns
-------
str or `x`
Either the formatted time object or the initial `x`"""
if isinstance(x, (datetime64, datetime)):
return format_timestamp(x)
elif isinstance(x, (timedelta64, timedelta)):
return format_timedelta(x)
elif isinstance(x, ndarray):
return list(x) if x.ndim else x[()]
return x | python | def format_time(x):
"""Formats date values
This function formats :class:`datetime.datetime` and
:class:`datetime.timedelta` objects (and the corresponding numpy objects)
using the :func:`xarray.core.formatting.format_timestamp` and the
:func:`xarray.core.formatting.format_timedelta` functions.
Parameters
----------
x: object
The value to format. If not a time object, the value is returned
Returns
-------
str or `x`
Either the formatted time object or the initial `x`"""
if isinstance(x, (datetime64, datetime)):
return format_timestamp(x)
elif isinstance(x, (timedelta64, timedelta)):
return format_timedelta(x)
elif isinstance(x, ndarray):
return list(x) if x.ndim else x[()]
return x | [
"def",
"format_time",
"(",
"x",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"(",
"datetime64",
",",
"datetime",
")",
")",
":",
"return",
"format_timestamp",
"(",
"x",
")",
"elif",
"isinstance",
"(",
"x",
",",
"(",
"timedelta64",
",",
"timedelta",
")",... | Formats date values
This function formats :class:`datetime.datetime` and
:class:`datetime.timedelta` objects (and the corresponding numpy objects)
using the :func:`xarray.core.formatting.format_timestamp` and the
:func:`xarray.core.formatting.format_timedelta` functions.
Parameters
----------
x: object
The value to format. If not a time object, the value is returned
Returns
-------
str or `x`
Either the formatted time object or the initial `x` | [
"Formats",
"date",
"values"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/plotter.py#L60-L83 | train | 43,423 |
Chilipp/psyplot | psyplot/plotter.py | is_data_dependent | def is_data_dependent(fmto, data):
"""Check whether a formatoption is data dependent
Parameters
----------
fmto: Formatoption
The :class:`Formatoption` instance to check
data: xarray.DataArray
The data array to use if the :attr:`~Formatoption.data_dependent`
attribute is a callable
Returns
-------
bool
True, if the formatoption depends on the data"""
if callable(fmto.data_dependent):
return fmto.data_dependent(data)
return fmto.data_dependent | python | def is_data_dependent(fmto, data):
"""Check whether a formatoption is data dependent
Parameters
----------
fmto: Formatoption
The :class:`Formatoption` instance to check
data: xarray.DataArray
The data array to use if the :attr:`~Formatoption.data_dependent`
attribute is a callable
Returns
-------
bool
True, if the formatoption depends on the data"""
if callable(fmto.data_dependent):
return fmto.data_dependent(data)
return fmto.data_dependent | [
"def",
"is_data_dependent",
"(",
"fmto",
",",
"data",
")",
":",
"if",
"callable",
"(",
"fmto",
".",
"data_dependent",
")",
":",
"return",
"fmto",
".",
"data_dependent",
"(",
"data",
")",
"return",
"fmto",
".",
"data_dependent"
] | Check whether a formatoption is data dependent
Parameters
----------
fmto: Formatoption
The :class:`Formatoption` instance to check
data: xarray.DataArray
The data array to use if the :attr:`~Formatoption.data_dependent`
attribute is a callable
Returns
-------
bool
True, if the formatoption depends on the data | [
"Check",
"whether",
"a",
"formatoption",
"is",
"data",
"dependent"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/plotter.py#L86-L103 | train | 43,424 |
Chilipp/psyplot | psyplot/plotter.py | Plotter.ax | def ax(self):
"""Axes instance of the plot"""
if self._ax is None:
import matplotlib.pyplot as plt
plt.figure()
self._ax = plt.axes(projection=self._get_sample_projection())
return self._ax | python | def ax(self):
"""Axes instance of the plot"""
if self._ax is None:
import matplotlib.pyplot as plt
plt.figure()
self._ax = plt.axes(projection=self._get_sample_projection())
return self._ax | [
"def",
"ax",
"(",
"self",
")",
":",
"if",
"self",
".",
"_ax",
"is",
"None",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"plt",
".",
"figure",
"(",
")",
"self",
".",
"_ax",
"=",
"plt",
".",
"axes",
"(",
"projection",
"=",
"self",
".",... | Axes instance of the plot | [
"Axes",
"instance",
"of",
"the",
"plot"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/plotter.py#L958-L964 | train | 43,425 |
Chilipp/psyplot | psyplot/plotter.py | Plotter._fmto_groups | def _fmto_groups(self):
"""Mapping from group to a set of formatoptions"""
ret = defaultdict(set)
for key in self:
ret[getattr(self, key).group].add(getattr(self, key))
return dict(ret) | python | def _fmto_groups(self):
"""Mapping from group to a set of formatoptions"""
ret = defaultdict(set)
for key in self:
ret[getattr(self, key).group].add(getattr(self, key))
return dict(ret) | [
"def",
"_fmto_groups",
"(",
"self",
")",
":",
"ret",
"=",
"defaultdict",
"(",
"set",
")",
"for",
"key",
"in",
"self",
":",
"ret",
"[",
"getattr",
"(",
"self",
",",
"key",
")",
".",
"group",
"]",
".",
"add",
"(",
"getattr",
"(",
"self",
",",
"key"... | Mapping from group to a set of formatoptions | [
"Mapping",
"from",
"group",
"to",
"a",
"set",
"of",
"formatoptions"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/plotter.py#L1059-L1064 | train | 43,426 |
Chilipp/psyplot | psyplot/plotter.py | Plotter._try2set | def _try2set(self, fmto, *args, **kwargs):
"""Sets the value in `fmto` and gives additional informations when fail
Parameters
----------
fmto: Formatoption
``*args`` and ``**kwargs``
Anything that is passed to `fmto`s :meth:`~Formatoption.set_value`
method"""
try:
fmto.set_value(*args, **kwargs)
except Exception as e:
critical("Error while setting %s!" % fmto.key,
logger=getattr(self, 'logger', None))
raise e | python | def _try2set(self, fmto, *args, **kwargs):
"""Sets the value in `fmto` and gives additional informations when fail
Parameters
----------
fmto: Formatoption
``*args`` and ``**kwargs``
Anything that is passed to `fmto`s :meth:`~Formatoption.set_value`
method"""
try:
fmto.set_value(*args, **kwargs)
except Exception as e:
critical("Error while setting %s!" % fmto.key,
logger=getattr(self, 'logger', None))
raise e | [
"def",
"_try2set",
"(",
"self",
",",
"fmto",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"fmto",
".",
"set_value",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"Exception",
"as",
"e",
":",
"critical",
"(",
"\"Err... | Sets the value in `fmto` and gives additional informations when fail
Parameters
----------
fmto: Formatoption
``*args`` and ``**kwargs``
Anything that is passed to `fmto`s :meth:`~Formatoption.set_value`
method | [
"Sets",
"the",
"value",
"in",
"fmto",
"and",
"gives",
"additional",
"informations",
"when",
"fail"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/plotter.py#L1196-L1210 | train | 43,427 |
Chilipp/psyplot | psyplot/plotter.py | Plotter.check_key | def check_key(self, key, raise_error=True, *args, **kwargs):
"""
Checks whether the key is a valid formatoption
Parameters
----------
%(check_key.parameters.no_possible_keys|name)s
Returns
-------
%(check_key.returns)s
Raises
------
%(check_key.raises)s"""
return check_key(
key, possible_keys=list(self), raise_error=raise_error,
name='formatoption keyword', *args, **kwargs) | python | def check_key(self, key, raise_error=True, *args, **kwargs):
"""
Checks whether the key is a valid formatoption
Parameters
----------
%(check_key.parameters.no_possible_keys|name)s
Returns
-------
%(check_key.returns)s
Raises
------
%(check_key.raises)s"""
return check_key(
key, possible_keys=list(self), raise_error=raise_error,
name='formatoption keyword', *args, **kwargs) | [
"def",
"check_key",
"(",
"self",
",",
"key",
",",
"raise_error",
"=",
"True",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"check_key",
"(",
"key",
",",
"possible_keys",
"=",
"list",
"(",
"self",
")",
",",
"raise_error",
"=",
"raise... | Checks whether the key is a valid formatoption
Parameters
----------
%(check_key.parameters.no_possible_keys|name)s
Returns
-------
%(check_key.returns)s
Raises
------
%(check_key.raises)s | [
"Checks",
"whether",
"the",
"key",
"is",
"a",
"valid",
"formatoption"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/plotter.py#L1234-L1251 | train | 43,428 |
Chilipp/psyplot | psyplot/plotter.py | Plotter.initialize_plot | def initialize_plot(self, data=None, ax=None, make_plot=True, clear=False,
draw=False, remove=False, priority=None):
"""
Initialize the plot for a data array
Parameters
----------
data: InteractiveArray or ArrayList, optional
Data object that shall be visualized.
- If not None and `plot` is True, the given data is visualized.
- If None and the :attr:`data` attribute is not None, the data in
the :attr:`data` attribute is visualized
- If both are None, nothing is done.
%(Plotter.parameters.ax|make_plot|clear)s
%(InteractiveBase.start_update.parameters.draw)s
remove: bool
If True, old effects by the formatoptions in this plotter are
undone first
priority: int
If given, initialize only the formatoption with the given priority.
This value must be out of :data:`START`, :data:`BEFOREPLOTTING` or
:data:`END`
"""
if data is None and self.data is not None:
data = self.data
else:
self.data = data
self.ax = ax
if data is None: # nothing to do if no data is given
return
self.no_auto_update = not (
not self.no_auto_update or not data.psy.no_auto_update)
data.psy.plotter = self
if not make_plot: # stop here if we shall not plot
return
self.logger.debug("Initializing plot...")
if remove:
self.logger.debug(" Removing old formatoptions...")
for fmto in self._fmtos:
try:
fmto.remove()
except Exception:
self.logger.debug(
"Could not remove %s while initializing", fmto.key,
exc_info=True)
if clear:
self.logger.debug(" Clearing axes...")
self.ax.clear()
self.cleared = True
# get the formatoptions. We sort them here by key to make sure that the
# order always stays the same (easier for debugging)
fmto_groups = self._grouped_fmtos(self._sorted_by_priority(
sorted(self._fmtos, key=lambda fmto: fmto.key)))
self.plot_data = self.data
self._updating = True
for fmto_priority, grouper in fmto_groups:
if priority is None or fmto_priority == priority:
self._plot_by_priority(fmto_priority, grouper,
initializing=True)
self._release_all(True) # finish the update
self.cleared = False
self.replot = False
self._initialized = True
self._updating = False
if draw is None:
draw = rcParams['auto_draw']
if draw:
self.draw()
if rcParams['auto_show']:
self.show() | python | def initialize_plot(self, data=None, ax=None, make_plot=True, clear=False,
draw=False, remove=False, priority=None):
"""
Initialize the plot for a data array
Parameters
----------
data: InteractiveArray or ArrayList, optional
Data object that shall be visualized.
- If not None and `plot` is True, the given data is visualized.
- If None and the :attr:`data` attribute is not None, the data in
the :attr:`data` attribute is visualized
- If both are None, nothing is done.
%(Plotter.parameters.ax|make_plot|clear)s
%(InteractiveBase.start_update.parameters.draw)s
remove: bool
If True, old effects by the formatoptions in this plotter are
undone first
priority: int
If given, initialize only the formatoption with the given priority.
This value must be out of :data:`START`, :data:`BEFOREPLOTTING` or
:data:`END`
"""
if data is None and self.data is not None:
data = self.data
else:
self.data = data
self.ax = ax
if data is None: # nothing to do if no data is given
return
self.no_auto_update = not (
not self.no_auto_update or not data.psy.no_auto_update)
data.psy.plotter = self
if not make_plot: # stop here if we shall not plot
return
self.logger.debug("Initializing plot...")
if remove:
self.logger.debug(" Removing old formatoptions...")
for fmto in self._fmtos:
try:
fmto.remove()
except Exception:
self.logger.debug(
"Could not remove %s while initializing", fmto.key,
exc_info=True)
if clear:
self.logger.debug(" Clearing axes...")
self.ax.clear()
self.cleared = True
# get the formatoptions. We sort them here by key to make sure that the
# order always stays the same (easier for debugging)
fmto_groups = self._grouped_fmtos(self._sorted_by_priority(
sorted(self._fmtos, key=lambda fmto: fmto.key)))
self.plot_data = self.data
self._updating = True
for fmto_priority, grouper in fmto_groups:
if priority is None or fmto_priority == priority:
self._plot_by_priority(fmto_priority, grouper,
initializing=True)
self._release_all(True) # finish the update
self.cleared = False
self.replot = False
self._initialized = True
self._updating = False
if draw is None:
draw = rcParams['auto_draw']
if draw:
self.draw()
if rcParams['auto_show']:
self.show() | [
"def",
"initialize_plot",
"(",
"self",
",",
"data",
"=",
"None",
",",
"ax",
"=",
"None",
",",
"make_plot",
"=",
"True",
",",
"clear",
"=",
"False",
",",
"draw",
"=",
"False",
",",
"remove",
"=",
"False",
",",
"priority",
"=",
"None",
")",
":",
"if"... | Initialize the plot for a data array
Parameters
----------
data: InteractiveArray or ArrayList, optional
Data object that shall be visualized.
- If not None and `plot` is True, the given data is visualized.
- If None and the :attr:`data` attribute is not None, the data in
the :attr:`data` attribute is visualized
- If both are None, nothing is done.
%(Plotter.parameters.ax|make_plot|clear)s
%(InteractiveBase.start_update.parameters.draw)s
remove: bool
If True, old effects by the formatoptions in this plotter are
undone first
priority: int
If given, initialize only the formatoption with the given priority.
This value must be out of :data:`START`, :data:`BEFOREPLOTTING` or
:data:`END` | [
"Initialize",
"the",
"plot",
"for",
"a",
"data",
"array"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/plotter.py#L1298-L1369 | train | 43,429 |
Chilipp/psyplot | psyplot/plotter.py | Plotter._register_update | def _register_update(self, fmt={}, replot=False, force=False,
todefault=False):
"""
Register formatoptions for the update
Parameters
----------
fmt: dict
Keys can be any valid formatoptions with the corresponding values
(see the :attr:`formatoptions` attribute)
replot: bool
Boolean that determines whether the data specific formatoptions
shall be updated in any case or not.
%(InteractiveBase._register_update.parameters.force|todefault)s"""
if self.disabled:
return
self.replot = self.replot or replot
self._todefault = self._todefault or todefault
if force is True:
force = list(fmt)
self._force.update(
[ret[0] for ret in map(self.check_key, force or [])])
# check the keys
list(map(self.check_key, fmt))
self._registered_updates.update(fmt) | python | def _register_update(self, fmt={}, replot=False, force=False,
todefault=False):
"""
Register formatoptions for the update
Parameters
----------
fmt: dict
Keys can be any valid formatoptions with the corresponding values
(see the :attr:`formatoptions` attribute)
replot: bool
Boolean that determines whether the data specific formatoptions
shall be updated in any case or not.
%(InteractiveBase._register_update.parameters.force|todefault)s"""
if self.disabled:
return
self.replot = self.replot or replot
self._todefault = self._todefault or todefault
if force is True:
force = list(fmt)
self._force.update(
[ret[0] for ret in map(self.check_key, force or [])])
# check the keys
list(map(self.check_key, fmt))
self._registered_updates.update(fmt) | [
"def",
"_register_update",
"(",
"self",
",",
"fmt",
"=",
"{",
"}",
",",
"replot",
"=",
"False",
",",
"force",
"=",
"False",
",",
"todefault",
"=",
"False",
")",
":",
"if",
"self",
".",
"disabled",
":",
"return",
"self",
".",
"replot",
"=",
"self",
... | Register formatoptions for the update
Parameters
----------
fmt: dict
Keys can be any valid formatoptions with the corresponding values
(see the :attr:`formatoptions` attribute)
replot: bool
Boolean that determines whether the data specific formatoptions
shall be updated in any case or not.
%(InteractiveBase._register_update.parameters.force|todefault)s | [
"Register",
"formatoptions",
"for",
"the",
"update"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/plotter.py#L1376-L1400 | train | 43,430 |
Chilipp/psyplot | psyplot/plotter.py | Plotter.reinit | def reinit(self, draw=None, clear=False):
"""
Reinitializes the plot with the same data and on the same axes.
Parameters
----------
%(InteractiveBase.start_update.parameters.draw)s
clear: bool
Whether to clear the axes or not
Warnings
--------
The axes may be cleared when calling this method (even if `clear` is
set to False)!"""
# call the initialize_plot method. Note that clear can be set to
# False if any fmto has requires_clearing attribute set to True,
# because this then has been cleared before
self.initialize_plot(
self.data, self._ax, draw=draw, clear=clear or any(
fmto.requires_clearing for fmto in self._fmtos),
remove=True) | python | def reinit(self, draw=None, clear=False):
"""
Reinitializes the plot with the same data and on the same axes.
Parameters
----------
%(InteractiveBase.start_update.parameters.draw)s
clear: bool
Whether to clear the axes or not
Warnings
--------
The axes may be cleared when calling this method (even if `clear` is
set to False)!"""
# call the initialize_plot method. Note that clear can be set to
# False if any fmto has requires_clearing attribute set to True,
# because this then has been cleared before
self.initialize_plot(
self.data, self._ax, draw=draw, clear=clear or any(
fmto.requires_clearing for fmto in self._fmtos),
remove=True) | [
"def",
"reinit",
"(",
"self",
",",
"draw",
"=",
"None",
",",
"clear",
"=",
"False",
")",
":",
"# call the initialize_plot method. Note that clear can be set to",
"# False if any fmto has requires_clearing attribute set to True,",
"# because this then has been cleared before",
"self... | Reinitializes the plot with the same data and on the same axes.
Parameters
----------
%(InteractiveBase.start_update.parameters.draw)s
clear: bool
Whether to clear the axes or not
Warnings
--------
The axes may be cleared when calling this method (even if `clear` is
set to False)! | [
"Reinitializes",
"the",
"plot",
"with",
"the",
"same",
"data",
"and",
"on",
"the",
"same",
"axes",
"."
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/plotter.py#L1566-L1586 | train | 43,431 |
Chilipp/psyplot | psyplot/plotter.py | Plotter.draw | def draw(self):
"""Draw the figures and those that are shared and have been changed"""
for fig in self.figs2draw:
fig.canvas.draw()
self._figs2draw.clear() | python | def draw(self):
"""Draw the figures and those that are shared and have been changed"""
for fig in self.figs2draw:
fig.canvas.draw()
self._figs2draw.clear() | [
"def",
"draw",
"(",
"self",
")",
":",
"for",
"fig",
"in",
"self",
".",
"figs2draw",
":",
"fig",
".",
"canvas",
".",
"draw",
"(",
")",
"self",
".",
"_figs2draw",
".",
"clear",
"(",
")"
] | Draw the figures and those that are shared and have been changed | [
"Draw",
"the",
"figures",
"and",
"those",
"that",
"are",
"shared",
"and",
"have",
"been",
"changed"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/plotter.py#L1588-L1592 | train | 43,432 |
Chilipp/psyplot | psyplot/plotter.py | Plotter._set_and_filter | def _set_and_filter(self):
"""Filters the registered updates and sort out what is not needed
This method filters out the formatoptions that have not changed, sets
the new value and returns an iterable that is sorted by the priority
(highest priority comes first) and dependencies
Returns
-------
list
list of :class:`Formatoption` objects that have to be updated"""
fmtos = []
seen = set()
for key in self._force:
self._registered_updates.setdefault(key, getattr(self, key).value)
for key, value in chain(
six.iteritems(self._registered_updates),
six.iteritems(
{key: getattr(self, key).default for key in self})
if self._todefault else ()):
if key in seen:
continue
seen.add(key)
fmto = getattr(self, key)
# if the key is shared, a warning will be printed as long as
# this plotter is not also updating (for example due to a whole
# project update)
if key in self._shared and key not in self._force:
if not self._shared[key].plotter._updating:
warn(("%s formatoption is shared with another plotter."
" Use the unshare method to enable the updating") % (
fmto.key),
logger=self.logger)
changed = False
else:
try:
changed = fmto.check_and_set(
value, todefault=self._todefault,
validate=not self.no_validation)
except Exception as e:
self._registered_updates.pop(key, None)
self.logger.debug('Failed to set %s', key)
raise e
changed = changed or key in self._force
if changed:
fmtos.append(fmto)
fmtos = self._insert_additionals(fmtos, seen)
for fmto in fmtos:
fmto.lock.acquire()
self._todefault = False
self._registered_updates.clear()
self._force.clear()
return fmtos | python | def _set_and_filter(self):
"""Filters the registered updates and sort out what is not needed
This method filters out the formatoptions that have not changed, sets
the new value and returns an iterable that is sorted by the priority
(highest priority comes first) and dependencies
Returns
-------
list
list of :class:`Formatoption` objects that have to be updated"""
fmtos = []
seen = set()
for key in self._force:
self._registered_updates.setdefault(key, getattr(self, key).value)
for key, value in chain(
six.iteritems(self._registered_updates),
six.iteritems(
{key: getattr(self, key).default for key in self})
if self._todefault else ()):
if key in seen:
continue
seen.add(key)
fmto = getattr(self, key)
# if the key is shared, a warning will be printed as long as
# this plotter is not also updating (for example due to a whole
# project update)
if key in self._shared and key not in self._force:
if not self._shared[key].plotter._updating:
warn(("%s formatoption is shared with another plotter."
" Use the unshare method to enable the updating") % (
fmto.key),
logger=self.logger)
changed = False
else:
try:
changed = fmto.check_and_set(
value, todefault=self._todefault,
validate=not self.no_validation)
except Exception as e:
self._registered_updates.pop(key, None)
self.logger.debug('Failed to set %s', key)
raise e
changed = changed or key in self._force
if changed:
fmtos.append(fmto)
fmtos = self._insert_additionals(fmtos, seen)
for fmto in fmtos:
fmto.lock.acquire()
self._todefault = False
self._registered_updates.clear()
self._force.clear()
return fmtos | [
"def",
"_set_and_filter",
"(",
"self",
")",
":",
"fmtos",
"=",
"[",
"]",
"seen",
"=",
"set",
"(",
")",
"for",
"key",
"in",
"self",
".",
"_force",
":",
"self",
".",
"_registered_updates",
".",
"setdefault",
"(",
"key",
",",
"getattr",
"(",
"self",
","... | Filters the registered updates and sort out what is not needed
This method filters out the formatoptions that have not changed, sets
the new value and returns an iterable that is sorted by the priority
(highest priority comes first) and dependencies
Returns
-------
list
list of :class:`Formatoption` objects that have to be updated | [
"Filters",
"the",
"registered",
"updates",
"and",
"sort",
"out",
"what",
"is",
"not",
"needed"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/plotter.py#L1604-L1656 | train | 43,433 |
Chilipp/psyplot | psyplot/plotter.py | Plotter._insert_additionals | def _insert_additionals(self, fmtos, seen=None):
"""
Insert additional formatoptions into `fmtos`.
This method inserts those formatoptions into `fmtos` that are required
because one of the following criteria is fullfilled:
1. The :attr:`replot` attribute is True
2. Any formatoption with START priority is in `fmtos`
3. A dependency of one formatoption is in `fmtos`
Parameters
----------
fmtos: list
The list of formatoptions that shall be updated
seen: set
The formatoption keys that shall not be included. If None, all
formatoptions in `fmtos` are used
Returns
-------
fmtos
The initial `fmtos` plus further formatoptions
Notes
-----
`fmtos` and `seen` are modified in place (except that any formatoption
in the initial `fmtos` has :attr:`~Formatoption.requires_clearing`
attribute set to True)"""
def get_dependencies(fmto):
if fmto is None:
return []
return fmto.dependencies + list(chain(*map(
lambda key: get_dependencies(getattr(self, key, None)),
fmto.dependencies)))
seen = seen or {fmto.key for fmto in fmtos}
keys = {fmto.key for fmto in fmtos}
self.replot = self.replot or any(
fmto.requires_replot for fmto in fmtos)
if self.replot or any(fmto.priority >= START for fmto in fmtos):
self.replot = True
self.plot_data = self.data
new_fmtos = dict((f.key, f) for f in self._fmtos
if ((f not in fmtos and is_data_dependent(
f, self.data))))
seen.update(new_fmtos)
keys.update(new_fmtos)
fmtos += list(new_fmtos.values())
# insert the formatoptions that have to be updated if the plot is
# changed
if any(fmto.priority >= BEFOREPLOTTING for fmto in fmtos):
new_fmtos = dict((f.key, f) for f in self._fmtos
if ((f not in fmtos and f.update_after_plot)))
fmtos += list(new_fmtos.values())
for fmto in set(self._fmtos).difference(fmtos):
all_dependencies = get_dependencies(fmto)
if keys.intersection(all_dependencies):
fmtos.append(fmto)
if any(fmto.requires_clearing for fmto in fmtos):
self.cleared = True
return list(self._fmtos)
return fmtos | python | def _insert_additionals(self, fmtos, seen=None):
"""
Insert additional formatoptions into `fmtos`.
This method inserts those formatoptions into `fmtos` that are required
because one of the following criteria is fullfilled:
1. The :attr:`replot` attribute is True
2. Any formatoption with START priority is in `fmtos`
3. A dependency of one formatoption is in `fmtos`
Parameters
----------
fmtos: list
The list of formatoptions that shall be updated
seen: set
The formatoption keys that shall not be included. If None, all
formatoptions in `fmtos` are used
Returns
-------
fmtos
The initial `fmtos` plus further formatoptions
Notes
-----
`fmtos` and `seen` are modified in place (except that any formatoption
in the initial `fmtos` has :attr:`~Formatoption.requires_clearing`
attribute set to True)"""
def get_dependencies(fmto):
if fmto is None:
return []
return fmto.dependencies + list(chain(*map(
lambda key: get_dependencies(getattr(self, key, None)),
fmto.dependencies)))
seen = seen or {fmto.key for fmto in fmtos}
keys = {fmto.key for fmto in fmtos}
self.replot = self.replot or any(
fmto.requires_replot for fmto in fmtos)
if self.replot or any(fmto.priority >= START for fmto in fmtos):
self.replot = True
self.plot_data = self.data
new_fmtos = dict((f.key, f) for f in self._fmtos
if ((f not in fmtos and is_data_dependent(
f, self.data))))
seen.update(new_fmtos)
keys.update(new_fmtos)
fmtos += list(new_fmtos.values())
# insert the formatoptions that have to be updated if the plot is
# changed
if any(fmto.priority >= BEFOREPLOTTING for fmto in fmtos):
new_fmtos = dict((f.key, f) for f in self._fmtos
if ((f not in fmtos and f.update_after_plot)))
fmtos += list(new_fmtos.values())
for fmto in set(self._fmtos).difference(fmtos):
all_dependencies = get_dependencies(fmto)
if keys.intersection(all_dependencies):
fmtos.append(fmto)
if any(fmto.requires_clearing for fmto in fmtos):
self.cleared = True
return list(self._fmtos)
return fmtos | [
"def",
"_insert_additionals",
"(",
"self",
",",
"fmtos",
",",
"seen",
"=",
"None",
")",
":",
"def",
"get_dependencies",
"(",
"fmto",
")",
":",
"if",
"fmto",
"is",
"None",
":",
"return",
"[",
"]",
"return",
"fmto",
".",
"dependencies",
"+",
"list",
"(",... | Insert additional formatoptions into `fmtos`.
This method inserts those formatoptions into `fmtos` that are required
because one of the following criteria is fullfilled:
1. The :attr:`replot` attribute is True
2. Any formatoption with START priority is in `fmtos`
3. A dependency of one formatoption is in `fmtos`
Parameters
----------
fmtos: list
The list of formatoptions that shall be updated
seen: set
The formatoption keys that shall not be included. If None, all
formatoptions in `fmtos` are used
Returns
-------
fmtos
The initial `fmtos` plus further formatoptions
Notes
-----
`fmtos` and `seen` are modified in place (except that any formatoption
in the initial `fmtos` has :attr:`~Formatoption.requires_clearing`
attribute set to True) | [
"Insert",
"additional",
"formatoptions",
"into",
"fmtos",
"."
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/plotter.py#L1658-L1720 | train | 43,434 |
Chilipp/psyplot | psyplot/plotter.py | Plotter._sorted_by_priority | def _sorted_by_priority(self, fmtos, changed=None):
"""Sort the formatoption objects by their priority and dependency
Parameters
----------
fmtos: list
list of :class:`Formatoption` instances
changed: list
the list of formatoption keys that have changed
Yields
------
Formatoption
The next formatoption as it comes by the sorting
Warnings
--------
The list `fmtos` is cleared by this method!"""
def pop_fmto(key):
idx = fmtos_keys.index(key)
del fmtos_keys[idx]
return fmtos.pop(idx)
def get_children(fmto, parents_keys):
all_fmtos = fmtos_keys + parents_keys
for key in fmto.children + fmto.dependencies:
if key not in fmtos_keys:
continue
child_fmto = pop_fmto(key)
for childs_child in get_children(
child_fmto, parents_keys + [child_fmto.key]):
yield childs_child
# filter out if parent is in update list
if (any(key in all_fmtos for key in child_fmto.parents) or
fmto.key in child_fmto.parents):
continue
yield child_fmto
fmtos.sort(key=lambda fmto: fmto.priority, reverse=True)
fmtos_keys = [fmto.key for fmto in fmtos]
self._last_update = changed or fmtos_keys[:]
self.logger.debug("Update the formatoptions %s", fmtos_keys)
while fmtos:
del fmtos_keys[0]
fmto = fmtos.pop(0)
# first update children
for child_fmto in get_children(fmto, [fmto.key]):
yield child_fmto
# filter out if parent is in update list
if any(key in fmtos_keys for key in fmto.parents):
continue
yield fmto | python | def _sorted_by_priority(self, fmtos, changed=None):
"""Sort the formatoption objects by their priority and dependency
Parameters
----------
fmtos: list
list of :class:`Formatoption` instances
changed: list
the list of formatoption keys that have changed
Yields
------
Formatoption
The next formatoption as it comes by the sorting
Warnings
--------
The list `fmtos` is cleared by this method!"""
def pop_fmto(key):
idx = fmtos_keys.index(key)
del fmtos_keys[idx]
return fmtos.pop(idx)
def get_children(fmto, parents_keys):
all_fmtos = fmtos_keys + parents_keys
for key in fmto.children + fmto.dependencies:
if key not in fmtos_keys:
continue
child_fmto = pop_fmto(key)
for childs_child in get_children(
child_fmto, parents_keys + [child_fmto.key]):
yield childs_child
# filter out if parent is in update list
if (any(key in all_fmtos for key in child_fmto.parents) or
fmto.key in child_fmto.parents):
continue
yield child_fmto
fmtos.sort(key=lambda fmto: fmto.priority, reverse=True)
fmtos_keys = [fmto.key for fmto in fmtos]
self._last_update = changed or fmtos_keys[:]
self.logger.debug("Update the formatoptions %s", fmtos_keys)
while fmtos:
del fmtos_keys[0]
fmto = fmtos.pop(0)
# first update children
for child_fmto in get_children(fmto, [fmto.key]):
yield child_fmto
# filter out if parent is in update list
if any(key in fmtos_keys for key in fmto.parents):
continue
yield fmto | [
"def",
"_sorted_by_priority",
"(",
"self",
",",
"fmtos",
",",
"changed",
"=",
"None",
")",
":",
"def",
"pop_fmto",
"(",
"key",
")",
":",
"idx",
"=",
"fmtos_keys",
".",
"index",
"(",
"key",
")",
"del",
"fmtos_keys",
"[",
"idx",
"]",
"return",
"fmtos",
... | Sort the formatoption objects by their priority and dependency
Parameters
----------
fmtos: list
list of :class:`Formatoption` instances
changed: list
the list of formatoption keys that have changed
Yields
------
Formatoption
The next formatoption as it comes by the sorting
Warnings
--------
The list `fmtos` is cleared by this method! | [
"Sort",
"the",
"formatoption",
"objects",
"by",
"their",
"priority",
"and",
"dependency"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/plotter.py#L1722-L1773 | train | 43,435 |
Chilipp/psyplot | psyplot/plotter.py | Plotter._get_formatoptions | def _get_formatoptions(cls, include_bases=True):
"""
Iterator over formatoptions
This class method returns an iterator that contains all the
formatoptions descriptors that are in this class and that are defined
in the base classes
Notes
-----
There is absolutely no need to call this method besides the plotter
initialization, since all formatoptions are in the plotter itself.
Just type::
>>> list(plotter)
to get the formatoptions.
See Also
--------
_format_keys"""
def base_fmtos(base):
return filter(
lambda key: isinstance(getattr(cls, key), Formatoption),
getattr(base, '_get_formatoptions', empty)(False))
def empty(*args, **kwargs):
return list()
fmtos = (attr for attr, obj in six.iteritems(cls.__dict__)
if isinstance(obj, Formatoption))
if not include_bases:
return fmtos
return unique_everseen(chain(fmtos, *map(base_fmtos, cls.__mro__))) | python | def _get_formatoptions(cls, include_bases=True):
"""
Iterator over formatoptions
This class method returns an iterator that contains all the
formatoptions descriptors that are in this class and that are defined
in the base classes
Notes
-----
There is absolutely no need to call this method besides the plotter
initialization, since all formatoptions are in the plotter itself.
Just type::
>>> list(plotter)
to get the formatoptions.
See Also
--------
_format_keys"""
def base_fmtos(base):
return filter(
lambda key: isinstance(getattr(cls, key), Formatoption),
getattr(base, '_get_formatoptions', empty)(False))
def empty(*args, **kwargs):
return list()
fmtos = (attr for attr, obj in six.iteritems(cls.__dict__)
if isinstance(obj, Formatoption))
if not include_bases:
return fmtos
return unique_everseen(chain(fmtos, *map(base_fmtos, cls.__mro__))) | [
"def",
"_get_formatoptions",
"(",
"cls",
",",
"include_bases",
"=",
"True",
")",
":",
"def",
"base_fmtos",
"(",
"base",
")",
":",
"return",
"filter",
"(",
"lambda",
"key",
":",
"isinstance",
"(",
"getattr",
"(",
"cls",
",",
"key",
")",
",",
"Formatoption... | Iterator over formatoptions
This class method returns an iterator that contains all the
formatoptions descriptors that are in this class and that are defined
in the base classes
Notes
-----
There is absolutely no need to call this method besides the plotter
initialization, since all formatoptions are in the plotter itself.
Just type::
>>> list(plotter)
to get the formatoptions.
See Also
--------
_format_keys | [
"Iterator",
"over",
"formatoptions"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/plotter.py#L1776-L1808 | train | 43,436 |
Chilipp/psyplot | psyplot/plotter.py | Plotter._enhance_keys | def _enhance_keys(cls, keys=None, *args, **kwargs):
"""
Enhance the given keys by groups
Parameters
----------
keys: list of str or None
If None, the all formatoptions of the given class are used. Group
names from the :attr:`psyplot.plotter.groups` mapping are replaced
by the formatoptions
Other Parameters
----------------
%(check_key.parameters.kwargs)s
Returns
-------
list of str
The enhanced list of the formatoptions"""
all_keys = list(cls._get_formatoptions())
if isinstance(keys, six.string_types):
keys = [keys]
else:
keys = list(keys or sorted(all_keys))
fmto_groups = defaultdict(list)
for key in all_keys:
fmto_groups[getattr(cls, key).group].append(key)
new_i = 0
for i, key in enumerate(keys[:]):
if key in fmto_groups:
del keys[new_i]
for key2 in fmto_groups[key]:
if key2 not in keys:
keys.insert(new_i, key2)
new_i += 1
else:
valid, similar, message = check_key(
key, all_keys, False, 'formatoption keyword', *args,
**kwargs)
if not valid:
keys.remove(key)
new_i -= 1
warn(message)
new_i += 1
return keys | python | def _enhance_keys(cls, keys=None, *args, **kwargs):
"""
Enhance the given keys by groups
Parameters
----------
keys: list of str or None
If None, the all formatoptions of the given class are used. Group
names from the :attr:`psyplot.plotter.groups` mapping are replaced
by the formatoptions
Other Parameters
----------------
%(check_key.parameters.kwargs)s
Returns
-------
list of str
The enhanced list of the formatoptions"""
all_keys = list(cls._get_formatoptions())
if isinstance(keys, six.string_types):
keys = [keys]
else:
keys = list(keys or sorted(all_keys))
fmto_groups = defaultdict(list)
for key in all_keys:
fmto_groups[getattr(cls, key).group].append(key)
new_i = 0
for i, key in enumerate(keys[:]):
if key in fmto_groups:
del keys[new_i]
for key2 in fmto_groups[key]:
if key2 not in keys:
keys.insert(new_i, key2)
new_i += 1
else:
valid, similar, message = check_key(
key, all_keys, False, 'formatoption keyword', *args,
**kwargs)
if not valid:
keys.remove(key)
new_i -= 1
warn(message)
new_i += 1
return keys | [
"def",
"_enhance_keys",
"(",
"cls",
",",
"keys",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"all_keys",
"=",
"list",
"(",
"cls",
".",
"_get_formatoptions",
"(",
")",
")",
"if",
"isinstance",
"(",
"keys",
",",
"six",
".",
"str... | Enhance the given keys by groups
Parameters
----------
keys: list of str or None
If None, the all formatoptions of the given class are used. Group
names from the :attr:`psyplot.plotter.groups` mapping are replaced
by the formatoptions
Other Parameters
----------------
%(check_key.parameters.kwargs)s
Returns
-------
list of str
The enhanced list of the formatoptions | [
"Enhance",
"the",
"given",
"keys",
"by",
"groups"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/plotter.py#L1816-L1861 | train | 43,437 |
Chilipp/psyplot | psyplot/plotter.py | Plotter.show_keys | def show_keys(cls, keys=None, indent=0, grouped=False, func=None,
include_links=False, *args, **kwargs):
"""
Classmethod to return a nice looking table with the given formatoptions
Parameters
----------
%(Plotter._enhance_keys.parameters)s
indent: int
The indentation of the table
grouped: bool, optional
If True, the formatoptions are grouped corresponding to the
:attr:`Formatoption.groupname` attribute
Other Parameters
----------------
func: function or None
The function the is used for returning (by default it is printed
via the :func:`print` function or (when using the gui) in the
help explorer). The given function must take a string as argument
include_links: bool or None, optional
Default False. If True, links (in restructured formats) are
included in the description. If None, the behaviour is determined
by the :attr:`psyplot.plotter.Plotter.include_links` attribute.
%(Plotter._enhance_keys.other_parameters)s
Returns
-------
results of `func`
None if `func` is the print function, otherwise anything else
See Also
--------
show_summaries, show_docs"""
def titled_group(groupname):
bars = str_indent + '*' * len(groupname) + '\n'
return bars + str_indent + groupname + '\n' + bars
keys = cls._enhance_keys(keys, *args, **kwargs)
str_indent = " " * indent
func = func or default_print_func
# call this function recursively when grouped is True
if grouped:
grouped_keys = DefaultOrderedDict(list)
for fmto in map(lambda key: getattr(cls, key), keys):
grouped_keys[fmto.groupname].append(fmto.key)
text = ""
for group, keys in six.iteritems(grouped_keys):
text += titled_group(group) + cls.show_keys(
keys, indent=indent, grouped=False, func=six.text_type,
include_links=include_links) + '\n\n'
return func(text.rstrip())
if not keys:
return
n = len(keys)
ncols = min([4, n]) # number of columns
# The number of cells in the table is one of the following cases:
# 1. The number of columns and equal to the number of keys
# 2. The number of keys
# 3. The number of keys plus the empty cells in the last column
ncells = n + ((ncols - (n % ncols)) if n != ncols else 0)
if include_links or (include_links is None and cls.include_links):
long_keys = list(map(lambda key: ':attr:`~%s.%s.%s`' % (
cls.__module__, cls.__name__, key), keys))
else:
long_keys = keys
maxn = max(map(len, long_keys)) # maximal lenght of the keys
# extend with empty cells
long_keys.extend([' ' * maxn] * (ncells - n))
bars = (str_indent + '+-' + ("-"*(maxn) + "-+-")*ncols)[:-1]
lines = ('| %s |\n%s' % (' | '.join(
key.ljust(maxn) for key in long_keys[i:i+ncols]), bars)
for i in range(0, n, ncols))
text = bars + "\n" + str_indent + ("\n" + str_indent).join(
lines)
if six.PY2:
text = text.encode('utf-8')
return func(text) | python | def show_keys(cls, keys=None, indent=0, grouped=False, func=None,
include_links=False, *args, **kwargs):
"""
Classmethod to return a nice looking table with the given formatoptions
Parameters
----------
%(Plotter._enhance_keys.parameters)s
indent: int
The indentation of the table
grouped: bool, optional
If True, the formatoptions are grouped corresponding to the
:attr:`Formatoption.groupname` attribute
Other Parameters
----------------
func: function or None
The function the is used for returning (by default it is printed
via the :func:`print` function or (when using the gui) in the
help explorer). The given function must take a string as argument
include_links: bool or None, optional
Default False. If True, links (in restructured formats) are
included in the description. If None, the behaviour is determined
by the :attr:`psyplot.plotter.Plotter.include_links` attribute.
%(Plotter._enhance_keys.other_parameters)s
Returns
-------
results of `func`
None if `func` is the print function, otherwise anything else
See Also
--------
show_summaries, show_docs"""
def titled_group(groupname):
bars = str_indent + '*' * len(groupname) + '\n'
return bars + str_indent + groupname + '\n' + bars
keys = cls._enhance_keys(keys, *args, **kwargs)
str_indent = " " * indent
func = func or default_print_func
# call this function recursively when grouped is True
if grouped:
grouped_keys = DefaultOrderedDict(list)
for fmto in map(lambda key: getattr(cls, key), keys):
grouped_keys[fmto.groupname].append(fmto.key)
text = ""
for group, keys in six.iteritems(grouped_keys):
text += titled_group(group) + cls.show_keys(
keys, indent=indent, grouped=False, func=six.text_type,
include_links=include_links) + '\n\n'
return func(text.rstrip())
if not keys:
return
n = len(keys)
ncols = min([4, n]) # number of columns
# The number of cells in the table is one of the following cases:
# 1. The number of columns and equal to the number of keys
# 2. The number of keys
# 3. The number of keys plus the empty cells in the last column
ncells = n + ((ncols - (n % ncols)) if n != ncols else 0)
if include_links or (include_links is None and cls.include_links):
long_keys = list(map(lambda key: ':attr:`~%s.%s.%s`' % (
cls.__module__, cls.__name__, key), keys))
else:
long_keys = keys
maxn = max(map(len, long_keys)) # maximal lenght of the keys
# extend with empty cells
long_keys.extend([' ' * maxn] * (ncells - n))
bars = (str_indent + '+-' + ("-"*(maxn) + "-+-")*ncols)[:-1]
lines = ('| %s |\n%s' % (' | '.join(
key.ljust(maxn) for key in long_keys[i:i+ncols]), bars)
for i in range(0, n, ncols))
text = bars + "\n" + str_indent + ("\n" + str_indent).join(
lines)
if six.PY2:
text = text.encode('utf-8')
return func(text) | [
"def",
"show_keys",
"(",
"cls",
",",
"keys",
"=",
"None",
",",
"indent",
"=",
"0",
",",
"grouped",
"=",
"False",
",",
"func",
"=",
"None",
",",
"include_links",
"=",
"False",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"titled_group... | Classmethod to return a nice looking table with the given formatoptions
Parameters
----------
%(Plotter._enhance_keys.parameters)s
indent: int
The indentation of the table
grouped: bool, optional
If True, the formatoptions are grouped corresponding to the
:attr:`Formatoption.groupname` attribute
Other Parameters
----------------
func: function or None
The function the is used for returning (by default it is printed
via the :func:`print` function or (when using the gui) in the
help explorer). The given function must take a string as argument
include_links: bool or None, optional
Default False. If True, links (in restructured formats) are
included in the description. If None, the behaviour is determined
by the :attr:`psyplot.plotter.Plotter.include_links` attribute.
%(Plotter._enhance_keys.other_parameters)s
Returns
-------
results of `func`
None if `func` is the print function, otherwise anything else
See Also
--------
show_summaries, show_docs | [
"Classmethod",
"to",
"return",
"a",
"nice",
"looking",
"table",
"with",
"the",
"given",
"formatoptions"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/plotter.py#L1868-L1947 | train | 43,438 |
Chilipp/psyplot | psyplot/plotter.py | Plotter._show_doc | def _show_doc(cls, fmt_func, keys=None, indent=0, grouped=False,
func=None, include_links=False, *args, **kwargs):
"""
Classmethod to print the formatoptions and their documentation
This function is the basis for the :meth:`show_summaries` and
:meth:`show_docs` methods
Parameters
----------
fmt_func: function
A function that takes the key, the key as it is printed, and the
documentation of a formatoption as argument and returns what shall
be printed
%(Plotter.show_keys.parameters)s
Other Parameters
----------------
%(Plotter.show_keys.other_parameters)s
Returns
-------
%(Plotter.show_keys.returns)s
See Also
--------
show_summaries, show_docs"""
def titled_group(groupname):
bars = str_indent + '*' * len(groupname) + '\n'
return bars + str_indent + groupname + '\n' + bars
func = func or default_print_func
keys = cls._enhance_keys(keys, *args, **kwargs)
str_indent = " " * indent
if grouped:
grouped_keys = DefaultOrderedDict(list)
for fmto in map(lambda key: getattr(cls, key), keys):
grouped_keys[fmto.groupname].append(fmto.key)
text = "\n\n".join(
titled_group(group) + cls._show_doc(
fmt_func, keys, indent=indent, grouped=False,
func=str, include_links=include_links)
for group, keys in six.iteritems(grouped_keys))
return func(text.rstrip())
if include_links or (include_links is None and cls.include_links):
long_keys = list(map(lambda key: ':attr:`~%s.%s.%s`' % (
cls.__module__, cls.__name__, key), keys))
else:
long_keys = keys
text = '\n'.join(str_indent + long_key + '\n' + fmt_func(
key, long_key, getattr(cls, key).__doc__) for long_key, key in zip(
long_keys, keys))
return func(text) | python | def _show_doc(cls, fmt_func, keys=None, indent=0, grouped=False,
func=None, include_links=False, *args, **kwargs):
"""
Classmethod to print the formatoptions and their documentation
This function is the basis for the :meth:`show_summaries` and
:meth:`show_docs` methods
Parameters
----------
fmt_func: function
A function that takes the key, the key as it is printed, and the
documentation of a formatoption as argument and returns what shall
be printed
%(Plotter.show_keys.parameters)s
Other Parameters
----------------
%(Plotter.show_keys.other_parameters)s
Returns
-------
%(Plotter.show_keys.returns)s
See Also
--------
show_summaries, show_docs"""
def titled_group(groupname):
bars = str_indent + '*' * len(groupname) + '\n'
return bars + str_indent + groupname + '\n' + bars
func = func or default_print_func
keys = cls._enhance_keys(keys, *args, **kwargs)
str_indent = " " * indent
if grouped:
grouped_keys = DefaultOrderedDict(list)
for fmto in map(lambda key: getattr(cls, key), keys):
grouped_keys[fmto.groupname].append(fmto.key)
text = "\n\n".join(
titled_group(group) + cls._show_doc(
fmt_func, keys, indent=indent, grouped=False,
func=str, include_links=include_links)
for group, keys in six.iteritems(grouped_keys))
return func(text.rstrip())
if include_links or (include_links is None and cls.include_links):
long_keys = list(map(lambda key: ':attr:`~%s.%s.%s`' % (
cls.__module__, cls.__name__, key), keys))
else:
long_keys = keys
text = '\n'.join(str_indent + long_key + '\n' + fmt_func(
key, long_key, getattr(cls, key).__doc__) for long_key, key in zip(
long_keys, keys))
return func(text) | [
"def",
"_show_doc",
"(",
"cls",
",",
"fmt_func",
",",
"keys",
"=",
"None",
",",
"indent",
"=",
"0",
",",
"grouped",
"=",
"False",
",",
"func",
"=",
"None",
",",
"include_links",
"=",
"False",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"... | Classmethod to print the formatoptions and their documentation
This function is the basis for the :meth:`show_summaries` and
:meth:`show_docs` methods
Parameters
----------
fmt_func: function
A function that takes the key, the key as it is printed, and the
documentation of a formatoption as argument and returns what shall
be printed
%(Plotter.show_keys.parameters)s
Other Parameters
----------------
%(Plotter.show_keys.other_parameters)s
Returns
-------
%(Plotter.show_keys.returns)s
See Also
--------
show_summaries, show_docs | [
"Classmethod",
"to",
"print",
"the",
"formatoptions",
"and",
"their",
"documentation"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/plotter.py#L1951-L2006 | train | 43,439 |
Chilipp/psyplot | psyplot/plotter.py | Plotter.show_summaries | def show_summaries(cls, keys=None, indent=0, *args, **kwargs):
"""
Classmethod to print the summaries of the formatoptions
Parameters
----------
%(Plotter.show_keys.parameters)s
Other Parameters
----------------
%(Plotter.show_keys.other_parameters)s
Returns
-------
%(Plotter.show_keys.returns)s
See Also
--------
show_keys, show_docs"""
def find_summary(key, key_txt, doc):
return '\n'.join(wrapper.wrap(doc[:doc.find('\n\n')]))
str_indent = " " * indent
wrapper = TextWrapper(width=80, initial_indent=str_indent + ' ' * 4,
subsequent_indent=str_indent + ' ' * 4)
return cls._show_doc(find_summary, keys=keys, indent=indent,
*args, **kwargs) | python | def show_summaries(cls, keys=None, indent=0, *args, **kwargs):
"""
Classmethod to print the summaries of the formatoptions
Parameters
----------
%(Plotter.show_keys.parameters)s
Other Parameters
----------------
%(Plotter.show_keys.other_parameters)s
Returns
-------
%(Plotter.show_keys.returns)s
See Also
--------
show_keys, show_docs"""
def find_summary(key, key_txt, doc):
return '\n'.join(wrapper.wrap(doc[:doc.find('\n\n')]))
str_indent = " " * indent
wrapper = TextWrapper(width=80, initial_indent=str_indent + ' ' * 4,
subsequent_indent=str_indent + ' ' * 4)
return cls._show_doc(find_summary, keys=keys, indent=indent,
*args, **kwargs) | [
"def",
"show_summaries",
"(",
"cls",
",",
"keys",
"=",
"None",
",",
"indent",
"=",
"0",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"find_summary",
"(",
"key",
",",
"key_txt",
",",
"doc",
")",
":",
"return",
"'\\n'",
".",
"join",
... | Classmethod to print the summaries of the formatoptions
Parameters
----------
%(Plotter.show_keys.parameters)s
Other Parameters
----------------
%(Plotter.show_keys.other_parameters)s
Returns
-------
%(Plotter.show_keys.returns)s
See Also
--------
show_keys, show_docs | [
"Classmethod",
"to",
"print",
"the",
"summaries",
"of",
"the",
"formatoptions"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/plotter.py#L2010-L2035 | train | 43,440 |
Chilipp/psyplot | psyplot/plotter.py | Plotter.show_docs | def show_docs(cls, keys=None, indent=0, *args, **kwargs):
"""
Classmethod to print the full documentations of the formatoptions
Parameters
----------
%(Plotter.show_keys.parameters)s
Other Parameters
----------------
%(Plotter.show_keys.other_parameters)s
Returns
-------
%(Plotter.show_keys.returns)s
See Also
--------
show_keys, show_docs"""
def full_doc(key, key_txt, doc):
return ('=' * len(key_txt)) + '\n' + doc + '\n'
return cls._show_doc(full_doc, keys=keys, indent=indent,
*args, **kwargs) | python | def show_docs(cls, keys=None, indent=0, *args, **kwargs):
"""
Classmethod to print the full documentations of the formatoptions
Parameters
----------
%(Plotter.show_keys.parameters)s
Other Parameters
----------------
%(Plotter.show_keys.other_parameters)s
Returns
-------
%(Plotter.show_keys.returns)s
See Also
--------
show_keys, show_docs"""
def full_doc(key, key_txt, doc):
return ('=' * len(key_txt)) + '\n' + doc + '\n'
return cls._show_doc(full_doc, keys=keys, indent=indent,
*args, **kwargs) | [
"def",
"show_docs",
"(",
"cls",
",",
"keys",
"=",
"None",
",",
"indent",
"=",
"0",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"full_doc",
"(",
"key",
",",
"key_txt",
",",
"doc",
")",
":",
"return",
"(",
"'='",
"*",
"len",
"(",
... | Classmethod to print the full documentations of the formatoptions
Parameters
----------
%(Plotter.show_keys.parameters)s
Other Parameters
----------------
%(Plotter.show_keys.other_parameters)s
Returns
-------
%(Plotter.show_keys.returns)s
See Also
--------
show_keys, show_docs | [
"Classmethod",
"to",
"print",
"the",
"full",
"documentations",
"of",
"the",
"formatoptions"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/plotter.py#L2039-L2061 | train | 43,441 |
Chilipp/psyplot | psyplot/plotter.py | Plotter._get_rc_strings | def _get_rc_strings(cls):
"""
Recursive method to get the base strings in the rcParams dictionary.
This method takes the :attr:`_rcparams_string` attribute from the given
`class` and combines it with the :attr:`_rcparams_string` attributes
from the base classes.
The returned frozenset can be used as base strings for the
:meth:`psyplot.config.rcsetup.RcParams.find_and_replace` method.
Returns
-------
list
The first entry is the :attr:`_rcparams_string` of this class,
the following the :attr:`_rcparams_string` attributes of the
base classes according to the method resolution order of this
class"""
return list(unique_everseen(chain(
*map(lambda base: getattr(base, '_rcparams_string', []),
cls.__mro__)))) | python | def _get_rc_strings(cls):
"""
Recursive method to get the base strings in the rcParams dictionary.
This method takes the :attr:`_rcparams_string` attribute from the given
`class` and combines it with the :attr:`_rcparams_string` attributes
from the base classes.
The returned frozenset can be used as base strings for the
:meth:`psyplot.config.rcsetup.RcParams.find_and_replace` method.
Returns
-------
list
The first entry is the :attr:`_rcparams_string` of this class,
the following the :attr:`_rcparams_string` attributes of the
base classes according to the method resolution order of this
class"""
return list(unique_everseen(chain(
*map(lambda base: getattr(base, '_rcparams_string', []),
cls.__mro__)))) | [
"def",
"_get_rc_strings",
"(",
"cls",
")",
":",
"return",
"list",
"(",
"unique_everseen",
"(",
"chain",
"(",
"*",
"map",
"(",
"lambda",
"base",
":",
"getattr",
"(",
"base",
",",
"'_rcparams_string'",
",",
"[",
"]",
")",
",",
"cls",
".",
"__mro__",
")",... | Recursive method to get the base strings in the rcParams dictionary.
This method takes the :attr:`_rcparams_string` attribute from the given
`class` and combines it with the :attr:`_rcparams_string` attributes
from the base classes.
The returned frozenset can be used as base strings for the
:meth:`psyplot.config.rcsetup.RcParams.find_and_replace` method.
Returns
-------
list
The first entry is the :attr:`_rcparams_string` of this class,
the following the :attr:`_rcparams_string` attributes of the
base classes according to the method resolution order of this
class | [
"Recursive",
"method",
"to",
"get",
"the",
"base",
"strings",
"in",
"the",
"rcParams",
"dictionary",
"."
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/plotter.py#L2064-L2083 | train | 43,442 |
Chilipp/psyplot | psyplot/plotter.py | Plotter._set_rc | def _set_rc(self):
"""Method to set the rcparams and defaultParams for this plotter"""
base_str = self._get_rc_strings()
# to make sure that the '.' is not interpreted as a regex pattern,
# we specify the pattern_base by ourselves
pattern_base = map(lambda s: s.replace('.', '\.'), base_str)
# pattern for valid keys being all formatoptions in this plotter
pattern = '(%s)(?=$)' % '|'.join(self._get_formatoptions())
self._rc = rcParams.find_and_replace(base_str, pattern=pattern,
pattern_base=pattern_base)
user_rc = SubDict(rcParams['plotter.user'], base_str, pattern=pattern,
pattern_base=pattern_base)
self._rc.update(user_rc.data)
self._defaultParams = SubDict(rcParams.defaultParams, base_str,
pattern=pattern,
pattern_base=pattern_base) | python | def _set_rc(self):
"""Method to set the rcparams and defaultParams for this plotter"""
base_str = self._get_rc_strings()
# to make sure that the '.' is not interpreted as a regex pattern,
# we specify the pattern_base by ourselves
pattern_base = map(lambda s: s.replace('.', '\.'), base_str)
# pattern for valid keys being all formatoptions in this plotter
pattern = '(%s)(?=$)' % '|'.join(self._get_formatoptions())
self._rc = rcParams.find_and_replace(base_str, pattern=pattern,
pattern_base=pattern_base)
user_rc = SubDict(rcParams['plotter.user'], base_str, pattern=pattern,
pattern_base=pattern_base)
self._rc.update(user_rc.data)
self._defaultParams = SubDict(rcParams.defaultParams, base_str,
pattern=pattern,
pattern_base=pattern_base) | [
"def",
"_set_rc",
"(",
"self",
")",
":",
"base_str",
"=",
"self",
".",
"_get_rc_strings",
"(",
")",
"# to make sure that the '.' is not interpreted as a regex pattern,",
"# we specify the pattern_base by ourselves",
"pattern_base",
"=",
"map",
"(",
"lambda",
"s",
":",
"s"... | Method to set the rcparams and defaultParams for this plotter | [
"Method",
"to",
"set",
"the",
"rcparams",
"and",
"defaultParams",
"for",
"this",
"plotter"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/plotter.py#L2085-L2101 | train | 43,443 |
Chilipp/psyplot | psyplot/plotter.py | Plotter.update | def update(self, fmt={}, replot=False, auto_update=False, draw=None,
force=False, todefault=False, **kwargs):
"""
Update the formatoptions and the plot
If the :attr:`data` attribute of this plotter is None, the plotter is
updated like a usual dictionary (see :meth:`dict.update`). Otherwise
the update is registered and the plot is updated if `auto_update` is
True or if the :meth:`start_update` method is called (see below).
Parameters
----------
%(Plotter._register_update.parameters)s
%(InteractiveBase.start_update.parameters)s
%(InteractiveBase.update.parameters.auto_update)s
``**kwargs``
Any other formatoption that shall be updated (additionally to those
in `fmt`)
Notes
-----
%(InteractiveBase.update.notes)s"""
if self.disabled:
return
fmt = dict(fmt)
if kwargs:
fmt.update(kwargs)
# if the data is None, update like a usual dictionary (but with
# validation)
if not self._initialized:
for key, val in six.iteritems(fmt):
self[key] = val
return
self._register_update(fmt=fmt, replot=replot, force=force,
todefault=todefault)
if not self.no_auto_update or auto_update:
self.start_update(draw=draw) | python | def update(self, fmt={}, replot=False, auto_update=False, draw=None,
force=False, todefault=False, **kwargs):
"""
Update the formatoptions and the plot
If the :attr:`data` attribute of this plotter is None, the plotter is
updated like a usual dictionary (see :meth:`dict.update`). Otherwise
the update is registered and the plot is updated if `auto_update` is
True or if the :meth:`start_update` method is called (see below).
Parameters
----------
%(Plotter._register_update.parameters)s
%(InteractiveBase.start_update.parameters)s
%(InteractiveBase.update.parameters.auto_update)s
``**kwargs``
Any other formatoption that shall be updated (additionally to those
in `fmt`)
Notes
-----
%(InteractiveBase.update.notes)s"""
if self.disabled:
return
fmt = dict(fmt)
if kwargs:
fmt.update(kwargs)
# if the data is None, update like a usual dictionary (but with
# validation)
if not self._initialized:
for key, val in six.iteritems(fmt):
self[key] = val
return
self._register_update(fmt=fmt, replot=replot, force=force,
todefault=todefault)
if not self.no_auto_update or auto_update:
self.start_update(draw=draw) | [
"def",
"update",
"(",
"self",
",",
"fmt",
"=",
"{",
"}",
",",
"replot",
"=",
"False",
",",
"auto_update",
"=",
"False",
",",
"draw",
"=",
"None",
",",
"force",
"=",
"False",
",",
"todefault",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",... | Update the formatoptions and the plot
If the :attr:`data` attribute of this plotter is None, the plotter is
updated like a usual dictionary (see :meth:`dict.update`). Otherwise
the update is registered and the plot is updated if `auto_update` is
True or if the :meth:`start_update` method is called (see below).
Parameters
----------
%(Plotter._register_update.parameters)s
%(InteractiveBase.start_update.parameters)s
%(InteractiveBase.update.parameters.auto_update)s
``**kwargs``
Any other formatoption that shall be updated (additionally to those
in `fmt`)
Notes
-----
%(InteractiveBase.update.notes)s | [
"Update",
"the",
"formatoptions",
"and",
"the",
"plot"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/plotter.py#L2106-L2143 | train | 43,444 |
Chilipp/psyplot | psyplot/plotter.py | Plotter._set_sharing_keys | def _set_sharing_keys(self, keys):
"""
Set the keys to share or unshare
Parameters
----------
keys: string or iterable of strings
The iterable may contain formatoptions that shall be shared (or
unshared), or group names of formatoptions to share all
formatoptions of that group (see the :attr:`fmt_groups` property).
If None, all formatoptions of this plotter are inserted.
Returns
-------
set
The set of formatoptions to share (or unshare)"""
if isinstance(keys, str):
keys = {keys}
keys = set(self) if keys is None else set(keys)
fmto_groups = self._fmto_groups
keys.update(chain(*(map(lambda fmto: fmto.key, fmto_groups[key])
for key in keys.intersection(fmto_groups))))
keys.difference_update(fmto_groups)
return keys | python | def _set_sharing_keys(self, keys):
"""
Set the keys to share or unshare
Parameters
----------
keys: string or iterable of strings
The iterable may contain formatoptions that shall be shared (or
unshared), or group names of formatoptions to share all
formatoptions of that group (see the :attr:`fmt_groups` property).
If None, all formatoptions of this plotter are inserted.
Returns
-------
set
The set of formatoptions to share (or unshare)"""
if isinstance(keys, str):
keys = {keys}
keys = set(self) if keys is None else set(keys)
fmto_groups = self._fmto_groups
keys.update(chain(*(map(lambda fmto: fmto.key, fmto_groups[key])
for key in keys.intersection(fmto_groups))))
keys.difference_update(fmto_groups)
return keys | [
"def",
"_set_sharing_keys",
"(",
"self",
",",
"keys",
")",
":",
"if",
"isinstance",
"(",
"keys",
",",
"str",
")",
":",
"keys",
"=",
"{",
"keys",
"}",
"keys",
"=",
"set",
"(",
"self",
")",
"if",
"keys",
"is",
"None",
"else",
"set",
"(",
"keys",
")... | Set the keys to share or unshare
Parameters
----------
keys: string or iterable of strings
The iterable may contain formatoptions that shall be shared (or
unshared), or group names of formatoptions to share all
formatoptions of that group (see the :attr:`fmt_groups` property).
If None, all formatoptions of this plotter are inserted.
Returns
-------
set
The set of formatoptions to share (or unshare) | [
"Set",
"the",
"keys",
"to",
"share",
"or",
"unshare"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/plotter.py#L2145-L2168 | train | 43,445 |
Chilipp/psyplot | psyplot/plotter.py | Plotter.share | def share(self, plotters, keys=None, draw=None, auto_update=False):
"""
Share the formatoptions of this plotter with others
This method shares the formatoptions of this :class:`Plotter` instance
with others to make sure that, if the formatoption of this changes,
those of the others change as well
Parameters
----------
plotters: list of :class:`Plotter` instances or a :class:`Plotter`
The plotters to share the formatoptions with
keys: string or iterable of strings
The formatoptions to share, or group names of formatoptions to
share all formatoptions of that group (see the
:attr:`fmt_groups` property). If None, all formatoptions of this
plotter are unshared.
%(InteractiveBase.start_update.parameters.draw)s
%(InteractiveBase.update.parameters.auto_update)s
See Also
--------
unshare, unshare_me"""
auto_update = auto_update or not self.no_auto_update
if isinstance(plotters, Plotter):
plotters = [plotters]
keys = self._set_sharing_keys(keys)
for plotter in plotters:
for key in keys:
fmto = self._shared.get(key, getattr(self, key))
if not getattr(plotter, key) == fmto:
plotter._shared[key] = getattr(self, key)
fmto.shared.add(getattr(plotter, key))
# now exit if we are not initialized
if self._initialized:
self.update(force=keys, auto_update=auto_update, draw=draw)
for plotter in plotters:
if not plotter._initialized:
continue
old_registered = plotter._registered_updates.copy()
plotter._registered_updates.clear()
try:
plotter.update(force=keys, auto_update=auto_update, draw=draw)
except:
raise
finally:
plotter._registered_updates.clear()
plotter._registered_updates.update(old_registered)
if draw is None:
draw = rcParams['auto_draw']
if draw:
self.draw()
if rcParams['auto_show']:
self.show() | python | def share(self, plotters, keys=None, draw=None, auto_update=False):
"""
Share the formatoptions of this plotter with others
This method shares the formatoptions of this :class:`Plotter` instance
with others to make sure that, if the formatoption of this changes,
those of the others change as well
Parameters
----------
plotters: list of :class:`Plotter` instances or a :class:`Plotter`
The plotters to share the formatoptions with
keys: string or iterable of strings
The formatoptions to share, or group names of formatoptions to
share all formatoptions of that group (see the
:attr:`fmt_groups` property). If None, all formatoptions of this
plotter are unshared.
%(InteractiveBase.start_update.parameters.draw)s
%(InteractiveBase.update.parameters.auto_update)s
See Also
--------
unshare, unshare_me"""
auto_update = auto_update or not self.no_auto_update
if isinstance(plotters, Plotter):
plotters = [plotters]
keys = self._set_sharing_keys(keys)
for plotter in plotters:
for key in keys:
fmto = self._shared.get(key, getattr(self, key))
if not getattr(plotter, key) == fmto:
plotter._shared[key] = getattr(self, key)
fmto.shared.add(getattr(plotter, key))
# now exit if we are not initialized
if self._initialized:
self.update(force=keys, auto_update=auto_update, draw=draw)
for plotter in plotters:
if not plotter._initialized:
continue
old_registered = plotter._registered_updates.copy()
plotter._registered_updates.clear()
try:
plotter.update(force=keys, auto_update=auto_update, draw=draw)
except:
raise
finally:
plotter._registered_updates.clear()
plotter._registered_updates.update(old_registered)
if draw is None:
draw = rcParams['auto_draw']
if draw:
self.draw()
if rcParams['auto_show']:
self.show() | [
"def",
"share",
"(",
"self",
",",
"plotters",
",",
"keys",
"=",
"None",
",",
"draw",
"=",
"None",
",",
"auto_update",
"=",
"False",
")",
":",
"auto_update",
"=",
"auto_update",
"or",
"not",
"self",
".",
"no_auto_update",
"if",
"isinstance",
"(",
"plotter... | Share the formatoptions of this plotter with others
This method shares the formatoptions of this :class:`Plotter` instance
with others to make sure that, if the formatoption of this changes,
those of the others change as well
Parameters
----------
plotters: list of :class:`Plotter` instances or a :class:`Plotter`
The plotters to share the formatoptions with
keys: string or iterable of strings
The formatoptions to share, or group names of formatoptions to
share all formatoptions of that group (see the
:attr:`fmt_groups` property). If None, all formatoptions of this
plotter are unshared.
%(InteractiveBase.start_update.parameters.draw)s
%(InteractiveBase.update.parameters.auto_update)s
See Also
--------
unshare, unshare_me | [
"Share",
"the",
"formatoptions",
"of",
"this",
"plotter",
"with",
"others"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/plotter.py#L2172-L2225 | train | 43,446 |
Chilipp/psyplot | psyplot/plotter.py | Plotter.has_changed | def has_changed(self, key, include_last=True):
"""
Determine whether a formatoption changed in the last update
Parameters
----------
key: str
A formatoption key contained in this plotter
include_last: bool
if True and the formatoption has been included in the last update,
the return value will not be None. Otherwise the return value will
only be not None if it changed during the last update
Returns
-------
None or list
- None, if the value has not been changed during the last update or
`key` is not a valid formatoption key
- a list of length two with the old value in the first place and
the given `value` at the second"""
if self._initializing or key not in self:
return
fmto = getattr(self, key)
if self._old_fmt and key in self._old_fmt[-1]:
old_val = self._old_fmt[-1][key]
else:
old_val = fmto.default
if (fmto.diff(old_val) or (include_last and
fmto.key in self._last_update)):
return [old_val, fmto.value] | python | def has_changed(self, key, include_last=True):
"""
Determine whether a formatoption changed in the last update
Parameters
----------
key: str
A formatoption key contained in this plotter
include_last: bool
if True and the formatoption has been included in the last update,
the return value will not be None. Otherwise the return value will
only be not None if it changed during the last update
Returns
-------
None or list
- None, if the value has not been changed during the last update or
`key` is not a valid formatoption key
- a list of length two with the old value in the first place and
the given `value` at the second"""
if self._initializing or key not in self:
return
fmto = getattr(self, key)
if self._old_fmt and key in self._old_fmt[-1]:
old_val = self._old_fmt[-1][key]
else:
old_val = fmto.default
if (fmto.diff(old_val) or (include_last and
fmto.key in self._last_update)):
return [old_val, fmto.value] | [
"def",
"has_changed",
"(",
"self",
",",
"key",
",",
"include_last",
"=",
"True",
")",
":",
"if",
"self",
".",
"_initializing",
"or",
"key",
"not",
"in",
"self",
":",
"return",
"fmto",
"=",
"getattr",
"(",
"self",
",",
"key",
")",
"if",
"self",
".",
... | Determine whether a formatoption changed in the last update
Parameters
----------
key: str
A formatoption key contained in this plotter
include_last: bool
if True and the formatoption has been included in the last update,
the return value will not be None. Otherwise the return value will
only be not None if it changed during the last update
Returns
-------
None or list
- None, if the value has not been changed during the last update or
`key` is not a valid formatoption key
- a list of length two with the old value in the first place and
the given `value` at the second | [
"Determine",
"whether",
"a",
"formatoption",
"changed",
"in",
"the",
"last",
"update"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/plotter.py#L2328-L2357 | train | 43,447 |
mfcloud/python-zvm-sdk | zvmsdk/utils.py | convert_to_mb | def convert_to_mb(s):
"""Convert memory size from GB to MB."""
s = s.upper()
try:
if s.endswith('G'):
return float(s[:-1].strip()) * 1024
elif s.endswith('T'):
return float(s[:-1].strip()) * 1024 * 1024
else:
return float(s[:-1].strip())
except (IndexError, ValueError, KeyError, TypeError):
errmsg = ("Invalid memory format: %s") % s
raise exception.SDKInternalError(msg=errmsg) | python | def convert_to_mb(s):
"""Convert memory size from GB to MB."""
s = s.upper()
try:
if s.endswith('G'):
return float(s[:-1].strip()) * 1024
elif s.endswith('T'):
return float(s[:-1].strip()) * 1024 * 1024
else:
return float(s[:-1].strip())
except (IndexError, ValueError, KeyError, TypeError):
errmsg = ("Invalid memory format: %s") % s
raise exception.SDKInternalError(msg=errmsg) | [
"def",
"convert_to_mb",
"(",
"s",
")",
":",
"s",
"=",
"s",
".",
"upper",
"(",
")",
"try",
":",
"if",
"s",
".",
"endswith",
"(",
"'G'",
")",
":",
"return",
"float",
"(",
"s",
"[",
":",
"-",
"1",
"]",
".",
"strip",
"(",
")",
")",
"*",
"1024",... | Convert memory size from GB to MB. | [
"Convert",
"memory",
"size",
"from",
"GB",
"to",
"MB",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/utils.py#L113-L125 | train | 43,448 |
mfcloud/python-zvm-sdk | zvmsdk/utils.py | check_input_types | def check_input_types(*types, **validkeys):
"""This is a function decorator to check all input parameters given to
decorated function are in expected types.
The checks can be skipped by specify skip_input_checks=True in decorated
function.
:param tuple types: expected types of input parameters to the decorated
function
:param validkeys: valid keywords(str) in a list.
e.g. validkeys=['key1', 'key2']
"""
def decorator(function):
@functools.wraps(function)
def wrap_func(*args, **kwargs):
if args[0]._skip_input_check:
# skip input check
return function(*args, **kwargs)
# drop class object self
inputs = args[1:]
if (len(inputs) > len(types)):
msg = ("Too many parameters provided: %(specified)d specified,"
"%(expected)d expected." %
{'specified': len(inputs), 'expected': len(types)})
LOG.info(msg)
raise exception.SDKInvalidInputNumber(function.__name__,
len(types), len(inputs))
argtypes = tuple(map(type, inputs))
match_types = types[0:len(argtypes)]
invalid_type = False
invalid_userid_idx = -1
for idx in range(len(argtypes)):
_mtypes = match_types[idx]
if not isinstance(_mtypes, tuple):
_mtypes = (_mtypes,)
argtype = argtypes[idx]
if constants._TUSERID in _mtypes:
userid_type = True
for _tmtype in _mtypes:
if ((argtype == _tmtype) and
(_tmtype != constants._TUSERID)):
userid_type = False
if (userid_type and
(not valid_userid(inputs[idx]))):
invalid_userid_idx = idx
break
elif argtype not in _mtypes:
invalid_type = True
break
if invalid_userid_idx != -1:
msg = ("Invalid string value found at the #%d parameter, "
"length should be less or equal to 8 and should not be "
"null or contain spaces." % (invalid_userid_idx + 1))
LOG.info(msg)
raise exception.SDKInvalidInputFormat(msg=msg)
if invalid_type:
msg = ("Invalid input types: %(argtypes)s; "
"Expected types: %(types)s" %
{'argtypes': str(argtypes), 'types': str(types)})
LOG.info(msg)
raise exception.SDKInvalidInputTypes(function.__name__,
str(types), str(argtypes))
valid_keys = validkeys.get('valid_keys')
if valid_keys:
for k in kwargs.keys():
if k not in valid_keys:
msg = ("Invalid keyword: %(key)s; "
"Expected keywords are: %(keys)s" %
{'key': k, 'keys': str(valid_keys)})
LOG.info(msg)
raise exception.SDKInvalidInputFormat(msg=msg)
return function(*args, **kwargs)
return wrap_func
return decorator | python | def check_input_types(*types, **validkeys):
"""This is a function decorator to check all input parameters given to
decorated function are in expected types.
The checks can be skipped by specify skip_input_checks=True in decorated
function.
:param tuple types: expected types of input parameters to the decorated
function
:param validkeys: valid keywords(str) in a list.
e.g. validkeys=['key1', 'key2']
"""
def decorator(function):
@functools.wraps(function)
def wrap_func(*args, **kwargs):
if args[0]._skip_input_check:
# skip input check
return function(*args, **kwargs)
# drop class object self
inputs = args[1:]
if (len(inputs) > len(types)):
msg = ("Too many parameters provided: %(specified)d specified,"
"%(expected)d expected." %
{'specified': len(inputs), 'expected': len(types)})
LOG.info(msg)
raise exception.SDKInvalidInputNumber(function.__name__,
len(types), len(inputs))
argtypes = tuple(map(type, inputs))
match_types = types[0:len(argtypes)]
invalid_type = False
invalid_userid_idx = -1
for idx in range(len(argtypes)):
_mtypes = match_types[idx]
if not isinstance(_mtypes, tuple):
_mtypes = (_mtypes,)
argtype = argtypes[idx]
if constants._TUSERID in _mtypes:
userid_type = True
for _tmtype in _mtypes:
if ((argtype == _tmtype) and
(_tmtype != constants._TUSERID)):
userid_type = False
if (userid_type and
(not valid_userid(inputs[idx]))):
invalid_userid_idx = idx
break
elif argtype not in _mtypes:
invalid_type = True
break
if invalid_userid_idx != -1:
msg = ("Invalid string value found at the #%d parameter, "
"length should be less or equal to 8 and should not be "
"null or contain spaces." % (invalid_userid_idx + 1))
LOG.info(msg)
raise exception.SDKInvalidInputFormat(msg=msg)
if invalid_type:
msg = ("Invalid input types: %(argtypes)s; "
"Expected types: %(types)s" %
{'argtypes': str(argtypes), 'types': str(types)})
LOG.info(msg)
raise exception.SDKInvalidInputTypes(function.__name__,
str(types), str(argtypes))
valid_keys = validkeys.get('valid_keys')
if valid_keys:
for k in kwargs.keys():
if k not in valid_keys:
msg = ("Invalid keyword: %(key)s; "
"Expected keywords are: %(keys)s" %
{'key': k, 'keys': str(valid_keys)})
LOG.info(msg)
raise exception.SDKInvalidInputFormat(msg=msg)
return function(*args, **kwargs)
return wrap_func
return decorator | [
"def",
"check_input_types",
"(",
"*",
"types",
",",
"*",
"*",
"validkeys",
")",
":",
"def",
"decorator",
"(",
"function",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"function",
")",
"def",
"wrap_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
"... | This is a function decorator to check all input parameters given to
decorated function are in expected types.
The checks can be skipped by specify skip_input_checks=True in decorated
function.
:param tuple types: expected types of input parameters to the decorated
function
:param validkeys: valid keywords(str) in a list.
e.g. validkeys=['key1', 'key2'] | [
"This",
"is",
"a",
"function",
"decorator",
"to",
"check",
"all",
"input",
"parameters",
"given",
"to",
"decorated",
"function",
"are",
"in",
"expected",
"types",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/utils.py#L253-L332 | train | 43,449 |
mfcloud/python-zvm-sdk | zvmsdk/utils.py | expect_and_reraise_internal_error | def expect_and_reraise_internal_error(modID='SDK'):
"""Catch all kinds of zvm client request failure and reraise.
modID: the moduleID that the internal error happens in.
"""
try:
yield
except exception.SDKInternalError as err:
msg = err.format_message()
raise exception.SDKInternalError(msg, modID=modID) | python | def expect_and_reraise_internal_error(modID='SDK'):
"""Catch all kinds of zvm client request failure and reraise.
modID: the moduleID that the internal error happens in.
"""
try:
yield
except exception.SDKInternalError as err:
msg = err.format_message()
raise exception.SDKInternalError(msg, modID=modID) | [
"def",
"expect_and_reraise_internal_error",
"(",
"modID",
"=",
"'SDK'",
")",
":",
"try",
":",
"yield",
"except",
"exception",
".",
"SDKInternalError",
"as",
"err",
":",
"msg",
"=",
"err",
".",
"format_message",
"(",
")",
"raise",
"exception",
".",
"SDKInternal... | Catch all kinds of zvm client request failure and reraise.
modID: the moduleID that the internal error happens in. | [
"Catch",
"all",
"kinds",
"of",
"zvm",
"client",
"request",
"failure",
"and",
"reraise",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/utils.py#L383-L392 | train | 43,450 |
mfcloud/python-zvm-sdk | zvmsdk/utils.py | log_and_reraise_smt_request_failed | def log_and_reraise_smt_request_failed(action=None):
"""Catch SDK base exception and print error log before reraise exception.
msg: the error message to be logged.
"""
try:
yield
except exception.SDKSMTRequestFailed as err:
msg = ''
if action is not None:
msg = "Failed to %s. " % action
msg += "SMT error: %s" % err.format_message()
LOG.error(msg)
raise exception.SDKSMTRequestFailed(err.results, msg) | python | def log_and_reraise_smt_request_failed(action=None):
"""Catch SDK base exception and print error log before reraise exception.
msg: the error message to be logged.
"""
try:
yield
except exception.SDKSMTRequestFailed as err:
msg = ''
if action is not None:
msg = "Failed to %s. " % action
msg += "SMT error: %s" % err.format_message()
LOG.error(msg)
raise exception.SDKSMTRequestFailed(err.results, msg) | [
"def",
"log_and_reraise_smt_request_failed",
"(",
"action",
"=",
"None",
")",
":",
"try",
":",
"yield",
"except",
"exception",
".",
"SDKSMTRequestFailed",
"as",
"err",
":",
"msg",
"=",
"''",
"if",
"action",
"is",
"not",
"None",
":",
"msg",
"=",
"\"Failed to ... | Catch SDK base exception and print error log before reraise exception.
msg: the error message to be logged. | [
"Catch",
"SDK",
"base",
"exception",
"and",
"print",
"error",
"log",
"before",
"reraise",
"exception",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/utils.py#L410-L423 | train | 43,451 |
mfcloud/python-zvm-sdk | zvmsdk/utils.py | get_smt_userid | def get_smt_userid():
"""Get the userid of smt server"""
cmd = ["sudo", "/sbin/vmcp", "query userid"]
try:
userid = subprocess.check_output(cmd,
close_fds=True,
stderr=subprocess.STDOUT)
userid = bytes.decode(userid)
userid = userid.split()[0]
return userid
except Exception as err:
msg = ("Could not find the userid of the smt server: %s") % err
raise exception.SDKInternalError(msg=msg) | python | def get_smt_userid():
"""Get the userid of smt server"""
cmd = ["sudo", "/sbin/vmcp", "query userid"]
try:
userid = subprocess.check_output(cmd,
close_fds=True,
stderr=subprocess.STDOUT)
userid = bytes.decode(userid)
userid = userid.split()[0]
return userid
except Exception as err:
msg = ("Could not find the userid of the smt server: %s") % err
raise exception.SDKInternalError(msg=msg) | [
"def",
"get_smt_userid",
"(",
")",
":",
"cmd",
"=",
"[",
"\"sudo\"",
",",
"\"/sbin/vmcp\"",
",",
"\"query userid\"",
"]",
"try",
":",
"userid",
"=",
"subprocess",
".",
"check_output",
"(",
"cmd",
",",
"close_fds",
"=",
"True",
",",
"stderr",
"=",
"subproce... | Get the userid of smt server | [
"Get",
"the",
"userid",
"of",
"smt",
"server"
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/utils.py#L437-L449 | train | 43,452 |
mfcloud/python-zvm-sdk | zvmsdk/utils.py | get_namelist | def get_namelist():
"""Generate namelist.
Either through set CONF.zvm.namelist, or by generate based on smt userid.
"""
if CONF.zvm.namelist is not None:
# namelist length limit should be 64, but there's bug limit to 8
# will change the limit to 8 once the bug fixed
if len(CONF.zvm.namelist) <= 8:
return CONF.zvm.namelist
# return ''.join(('NL', get_smt_userid().rjust(6, '0')[-6:]))
# py3 compatible changes
userid = get_smt_userid()
return 'NL' + userid.rjust(6, '0')[-6:] | python | def get_namelist():
"""Generate namelist.
Either through set CONF.zvm.namelist, or by generate based on smt userid.
"""
if CONF.zvm.namelist is not None:
# namelist length limit should be 64, but there's bug limit to 8
# will change the limit to 8 once the bug fixed
if len(CONF.zvm.namelist) <= 8:
return CONF.zvm.namelist
# return ''.join(('NL', get_smt_userid().rjust(6, '0')[-6:]))
# py3 compatible changes
userid = get_smt_userid()
return 'NL' + userid.rjust(6, '0')[-6:] | [
"def",
"get_namelist",
"(",
")",
":",
"if",
"CONF",
".",
"zvm",
".",
"namelist",
"is",
"not",
"None",
":",
"# namelist length limit should be 64, but there's bug limit to 8",
"# will change the limit to 8 once the bug fixed",
"if",
"len",
"(",
"CONF",
".",
"zvm",
".",
... | Generate namelist.
Either through set CONF.zvm.namelist, or by generate based on smt userid. | [
"Generate",
"namelist",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/utils.py#L452-L466 | train | 43,453 |
mfcloud/python-zvm-sdk | zvmsdk/utils.py | generate_iucv_authfile | def generate_iucv_authfile(fn, client):
"""Generate the iucv_authorized_userid file"""
lines = ['#!/bin/bash\n',
'echo -n %s > /etc/iucv_authorized_userid\n' % client]
with open(fn, 'w') as f:
f.writelines(lines) | python | def generate_iucv_authfile(fn, client):
"""Generate the iucv_authorized_userid file"""
lines = ['#!/bin/bash\n',
'echo -n %s > /etc/iucv_authorized_userid\n' % client]
with open(fn, 'w') as f:
f.writelines(lines) | [
"def",
"generate_iucv_authfile",
"(",
"fn",
",",
"client",
")",
":",
"lines",
"=",
"[",
"'#!/bin/bash\\n'",
",",
"'echo -n %s > /etc/iucv_authorized_userid\\n'",
"%",
"client",
"]",
"with",
"open",
"(",
"fn",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write... | Generate the iucv_authorized_userid file | [
"Generate",
"the",
"iucv_authorized_userid",
"file"
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/utils.py#L469-L474 | train | 43,454 |
mfcloud/python-zvm-sdk | zvmsdk/utils.py | translate_response_to_dict | def translate_response_to_dict(rawdata, dirt):
"""Translate SMT response to a python dictionary.
SMT response example:
keyword1: value1\n
keyword2: value2\n
...
keywordn: valuen\n
Will return a python dictionary:
{keyword1: value1,
keyword2: value2,
...
keywordn: valuen,}
"""
data_list = rawdata.split("\n")
data = {}
for ls in data_list:
for k in list(dirt.keys()):
if ls.__contains__(dirt[k]):
data[k] = ls[(ls.find(dirt[k]) + len(dirt[k])):].strip()
break
if data == {}:
msg = ("Invalid smt response data. Error: No value matched with "
"keywords. Raw Data: %(raw)s; Keywords: %(kws)s" %
{'raw': rawdata, 'kws': str(dirt)})
raise exception.SDKInternalError(msg=msg)
return data | python | def translate_response_to_dict(rawdata, dirt):
"""Translate SMT response to a python dictionary.
SMT response example:
keyword1: value1\n
keyword2: value2\n
...
keywordn: valuen\n
Will return a python dictionary:
{keyword1: value1,
keyword2: value2,
...
keywordn: valuen,}
"""
data_list = rawdata.split("\n")
data = {}
for ls in data_list:
for k in list(dirt.keys()):
if ls.__contains__(dirt[k]):
data[k] = ls[(ls.find(dirt[k]) + len(dirt[k])):].strip()
break
if data == {}:
msg = ("Invalid smt response data. Error: No value matched with "
"keywords. Raw Data: %(raw)s; Keywords: %(kws)s" %
{'raw': rawdata, 'kws': str(dirt)})
raise exception.SDKInternalError(msg=msg)
return data | [
"def",
"translate_response_to_dict",
"(",
"rawdata",
",",
"dirt",
")",
":",
"data_list",
"=",
"rawdata",
".",
"split",
"(",
"\"\\n\"",
")",
"data",
"=",
"{",
"}",
"for",
"ls",
"in",
"data_list",
":",
"for",
"k",
"in",
"list",
"(",
"dirt",
".",
"keys",
... | Translate SMT response to a python dictionary.
SMT response example:
keyword1: value1\n
keyword2: value2\n
...
keywordn: valuen\n
Will return a python dictionary:
{keyword1: value1,
keyword2: value2,
...
keywordn: valuen,} | [
"Translate",
"SMT",
"response",
"to",
"a",
"python",
"dictionary",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/utils.py#L478-L509 | train | 43,455 |
mfcloud/python-zvm-sdk | sample/simple/sample.py | delete_guest | def delete_guest(userid):
""" Destroy a virtual machine.
Input parameters:
:userid: USERID of the guest, last 8 if length > 8
"""
# Check if the guest exists.
guest_list_info = client.send_request('guest_list')
# the string 'userid' need to be coded as 'u'userid' in case of py2 interpreter.
userid_1 = (unicode(userid, "utf-8") if sys.version[0] == '2' else userid)
if userid_1 not in guest_list_info['output']:
RuntimeError("Userid %s does not exist!" % userid)
# Delete the guest.
guest_delete_info = client.send_request('guest_delete', userid)
if guest_delete_info['overallRC']:
print("\nFailed to delete guest %s!" % userid)
else:
print("\nSucceeded to delete guest %s!" % userid) | python | def delete_guest(userid):
""" Destroy a virtual machine.
Input parameters:
:userid: USERID of the guest, last 8 if length > 8
"""
# Check if the guest exists.
guest_list_info = client.send_request('guest_list')
# the string 'userid' need to be coded as 'u'userid' in case of py2 interpreter.
userid_1 = (unicode(userid, "utf-8") if sys.version[0] == '2' else userid)
if userid_1 not in guest_list_info['output']:
RuntimeError("Userid %s does not exist!" % userid)
# Delete the guest.
guest_delete_info = client.send_request('guest_delete', userid)
if guest_delete_info['overallRC']:
print("\nFailed to delete guest %s!" % userid)
else:
print("\nSucceeded to delete guest %s!" % userid) | [
"def",
"delete_guest",
"(",
"userid",
")",
":",
"# Check if the guest exists.",
"guest_list_info",
"=",
"client",
".",
"send_request",
"(",
"'guest_list'",
")",
"# the string 'userid' need to be coded as 'u'userid' in case of py2 interpreter.",
"userid_1",
"=",
"(",
"unicode",
... | Destroy a virtual machine.
Input parameters:
:userid: USERID of the guest, last 8 if length > 8 | [
"Destroy",
"a",
"virtual",
"machine",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/sample/simple/sample.py#L15-L36 | train | 43,456 |
mfcloud/python-zvm-sdk | sample/simple/sample.py | describe_guest | def describe_guest(userid):
""" Get the basic information of virtual machine.
Input parameters:
:userid: USERID of the guest, last 8 if length > 8
"""
# Check if the guest exists.
guest_list_info = client.send_request('guest_list')
userid_1 = (unicode(userid, "utf-8") if sys.version[0] == '2' else userid)
if userid_1 not in guest_list_info['output']:
raise RuntimeError("Guest %s does not exist!" % userid)
guest_describe_info = client.send_request('guest_get_definition_info', userid)
print("\nThe created guest %s's info are: \n%s\n" % (userid, guest_describe_info)) | python | def describe_guest(userid):
""" Get the basic information of virtual machine.
Input parameters:
:userid: USERID of the guest, last 8 if length > 8
"""
# Check if the guest exists.
guest_list_info = client.send_request('guest_list')
userid_1 = (unicode(userid, "utf-8") if sys.version[0] == '2' else userid)
if userid_1 not in guest_list_info['output']:
raise RuntimeError("Guest %s does not exist!" % userid)
guest_describe_info = client.send_request('guest_get_definition_info', userid)
print("\nThe created guest %s's info are: \n%s\n" % (userid, guest_describe_info)) | [
"def",
"describe_guest",
"(",
"userid",
")",
":",
"# Check if the guest exists.",
"guest_list_info",
"=",
"client",
".",
"send_request",
"(",
"'guest_list'",
")",
"userid_1",
"=",
"(",
"unicode",
"(",
"userid",
",",
"\"utf-8\"",
")",
"if",
"sys",
".",
"version",... | Get the basic information of virtual machine.
Input parameters:
:userid: USERID of the guest, last 8 if length > 8 | [
"Get",
"the",
"basic",
"information",
"of",
"virtual",
"machine",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/sample/simple/sample.py#L39-L54 | train | 43,457 |
mfcloud/python-zvm-sdk | sample/simple/sample.py | import_image | def import_image(image_path, os_version):
""" Import the specific image.
Input parameters:
:image_path: Image file name
:os_version: Operation System version. e.g. rhel7.4
"""
image_name = os.path.basename(image_path)
print("\nChecking if image %s exists ..." % image_name)
image_query_info = client.send_request('image_query', imagename = image_name)
if image_query_info['overallRC']:
print("Importing image %s ..." % image_name)
url = "file://" + image_path
image_import_info = client.send_request('image_import', image_name, url,
{'os_version': os_version})
if image_import_info['overallRC']:
raise RuntimeError("Failed to import image %s!\n%s" %
(image_name, image_import_info))
else:
print("Succeeded to import image %s!" % image_name)
else:
print("Image %s already exists!" % image_name) | python | def import_image(image_path, os_version):
""" Import the specific image.
Input parameters:
:image_path: Image file name
:os_version: Operation System version. e.g. rhel7.4
"""
image_name = os.path.basename(image_path)
print("\nChecking if image %s exists ..." % image_name)
image_query_info = client.send_request('image_query', imagename = image_name)
if image_query_info['overallRC']:
print("Importing image %s ..." % image_name)
url = "file://" + image_path
image_import_info = client.send_request('image_import', image_name, url,
{'os_version': os_version})
if image_import_info['overallRC']:
raise RuntimeError("Failed to import image %s!\n%s" %
(image_name, image_import_info))
else:
print("Succeeded to import image %s!" % image_name)
else:
print("Image %s already exists!" % image_name) | [
"def",
"import_image",
"(",
"image_path",
",",
"os_version",
")",
":",
"image_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"image_path",
")",
"print",
"(",
"\"\\nChecking if image %s exists ...\"",
"%",
"image_name",
")",
"image_query_info",
"=",
"client",... | Import the specific image.
Input parameters:
:image_path: Image file name
:os_version: Operation System version. e.g. rhel7.4 | [
"Import",
"the",
"specific",
"image",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/sample/simple/sample.py#L57-L79 | train | 43,458 |
mfcloud/python-zvm-sdk | sample/simple/sample.py | create_guest | def create_guest(userid, cpu, memory, disks_list, profile):
""" Create the userid.
Input parameters:
:userid: USERID of the guest, last 8 if length > 8
:cpu: the number of vcpus
:memory: memory
:disks_list: list of disks to add
:profile: profile of the userid
"""
# Check if the userid already exists.
guest_list_info = client.send_request('guest_list')
userid_1 = (unicode(userid, "utf-8") if sys.version[0] == '2' else userid)
if userid_1 in guest_list_info['output']:
raise RuntimeError("Guest %s already exists!" % userid)
# Create the guest.
print("\nCreating guest: %s ..." % userid)
guest_create_info = client.send_request('guest_create', userid, cpu, memory,
disk_list = disks_list,
user_profile = profile)
if guest_create_info['overallRC']:
raise RuntimeError("Failed to create guest %s!\n%s" %
(userid, guest_create_info))
else:
print("Succeeded to create guest %s!" % userid) | python | def create_guest(userid, cpu, memory, disks_list, profile):
""" Create the userid.
Input parameters:
:userid: USERID of the guest, last 8 if length > 8
:cpu: the number of vcpus
:memory: memory
:disks_list: list of disks to add
:profile: profile of the userid
"""
# Check if the userid already exists.
guest_list_info = client.send_request('guest_list')
userid_1 = (unicode(userid, "utf-8") if sys.version[0] == '2' else userid)
if userid_1 in guest_list_info['output']:
raise RuntimeError("Guest %s already exists!" % userid)
# Create the guest.
print("\nCreating guest: %s ..." % userid)
guest_create_info = client.send_request('guest_create', userid, cpu, memory,
disk_list = disks_list,
user_profile = profile)
if guest_create_info['overallRC']:
raise RuntimeError("Failed to create guest %s!\n%s" %
(userid, guest_create_info))
else:
print("Succeeded to create guest %s!" % userid) | [
"def",
"create_guest",
"(",
"userid",
",",
"cpu",
",",
"memory",
",",
"disks_list",
",",
"profile",
")",
":",
"# Check if the userid already exists.",
"guest_list_info",
"=",
"client",
".",
"send_request",
"(",
"'guest_list'",
")",
"userid_1",
"=",
"(",
"unicode",... | Create the userid.
Input parameters:
:userid: USERID of the guest, last 8 if length > 8
:cpu: the number of vcpus
:memory: memory
:disks_list: list of disks to add
:profile: profile of the userid | [
"Create",
"the",
"userid",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/sample/simple/sample.py#L82-L109 | train | 43,459 |
mfcloud/python-zvm-sdk | sample/simple/sample.py | deploy_guest | def deploy_guest(userid, image_name):
""" Deploy image to root disk.
Input parameters:
:userid: USERID of the guest, last 8 if length > 8
:image_path: Image file name
"""
print("\nDeploying %s to %s ..." % (image_name, userid))
guest_deploy_info = client.send_request('guest_deploy', userid, image_name)
# if failed to deploy, then delete the guest.
if guest_deploy_info['overallRC']:
print("\nFailed to deploy guest %s!\n%s" % (userid, guest_deploy_info))
print("\nDeleting the guest %s that failed to deploy..." % userid)
# call terminage_guest() to delete the guest that failed to deploy.
delete_guest(userid)
os._exit(0)
else:
print("Succeeded to deploy %s!" % userid) | python | def deploy_guest(userid, image_name):
""" Deploy image to root disk.
Input parameters:
:userid: USERID of the guest, last 8 if length > 8
:image_path: Image file name
"""
print("\nDeploying %s to %s ..." % (image_name, userid))
guest_deploy_info = client.send_request('guest_deploy', userid, image_name)
# if failed to deploy, then delete the guest.
if guest_deploy_info['overallRC']:
print("\nFailed to deploy guest %s!\n%s" % (userid, guest_deploy_info))
print("\nDeleting the guest %s that failed to deploy..." % userid)
# call terminage_guest() to delete the guest that failed to deploy.
delete_guest(userid)
os._exit(0)
else:
print("Succeeded to deploy %s!" % userid) | [
"def",
"deploy_guest",
"(",
"userid",
",",
"image_name",
")",
":",
"print",
"(",
"\"\\nDeploying %s to %s ...\"",
"%",
"(",
"image_name",
",",
"userid",
")",
")",
"guest_deploy_info",
"=",
"client",
".",
"send_request",
"(",
"'guest_deploy'",
",",
"userid",
",",... | Deploy image to root disk.
Input parameters:
:userid: USERID of the guest, last 8 if length > 8
:image_path: Image file name | [
"Deploy",
"image",
"to",
"root",
"disk",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/sample/simple/sample.py#L111-L130 | train | 43,460 |
mfcloud/python-zvm-sdk | sample/simple/sample.py | create_network | def create_network(userid, os_version, network_info):
""" Create network device and configure network interface.
Input parameters:
:userid: USERID of the guest, last 8 if length > 8
:os_version: os version of the image file
:network_info: dict of network info
"""
print("\nConfiguring network interface for %s ..." % userid)
network_create_info = client.send_request('guest_create_network_interface',
userid, os_version, network_info)
if network_create_info['overallRC']:
raise RuntimeError("Failed to create network for guest %s!\n%s" %
(userid, network_create_info))
else:
print("Succeeded to create network for guest %s!" % userid) | python | def create_network(userid, os_version, network_info):
""" Create network device and configure network interface.
Input parameters:
:userid: USERID of the guest, last 8 if length > 8
:os_version: os version of the image file
:network_info: dict of network info
"""
print("\nConfiguring network interface for %s ..." % userid)
network_create_info = client.send_request('guest_create_network_interface',
userid, os_version, network_info)
if network_create_info['overallRC']:
raise RuntimeError("Failed to create network for guest %s!\n%s" %
(userid, network_create_info))
else:
print("Succeeded to create network for guest %s!" % userid) | [
"def",
"create_network",
"(",
"userid",
",",
"os_version",
",",
"network_info",
")",
":",
"print",
"(",
"\"\\nConfiguring network interface for %s ...\"",
"%",
"userid",
")",
"network_create_info",
"=",
"client",
".",
"send_request",
"(",
"'guest_create_network_interface'... | Create network device and configure network interface.
Input parameters:
:userid: USERID of the guest, last 8 if length > 8
:os_version: os version of the image file
:network_info: dict of network info | [
"Create",
"network",
"device",
"and",
"configure",
"network",
"interface",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/sample/simple/sample.py#L132-L148 | train | 43,461 |
mfcloud/python-zvm-sdk | sample/simple/sample.py | coupleTo_vswitch | def coupleTo_vswitch(userid, vswitch_name):
""" Couple to vswitch.
Input parameters:
:userid: USERID of the guest, last 8 if length > 8
:network_info: dict of network info
"""
print("\nCoupleing to vswitch for %s ..." % userid)
vswitch_info = client.send_request('guest_nic_couple_to_vswitch',
userid, '1000', vswitch_name)
if vswitch_info['overallRC']:
raise RuntimeError("Failed to couple to vswitch for guest %s!\n%s" %
(userid, vswitch_info))
else:
print("Succeeded to couple to vswitch for guest %s!" % userid) | python | def coupleTo_vswitch(userid, vswitch_name):
""" Couple to vswitch.
Input parameters:
:userid: USERID of the guest, last 8 if length > 8
:network_info: dict of network info
"""
print("\nCoupleing to vswitch for %s ..." % userid)
vswitch_info = client.send_request('guest_nic_couple_to_vswitch',
userid, '1000', vswitch_name)
if vswitch_info['overallRC']:
raise RuntimeError("Failed to couple to vswitch for guest %s!\n%s" %
(userid, vswitch_info))
else:
print("Succeeded to couple to vswitch for guest %s!" % userid) | [
"def",
"coupleTo_vswitch",
"(",
"userid",
",",
"vswitch_name",
")",
":",
"print",
"(",
"\"\\nCoupleing to vswitch for %s ...\"",
"%",
"userid",
")",
"vswitch_info",
"=",
"client",
".",
"send_request",
"(",
"'guest_nic_couple_to_vswitch'",
",",
"userid",
",",
"'1000'",... | Couple to vswitch.
Input parameters:
:userid: USERID of the guest, last 8 if length > 8
:network_info: dict of network info | [
"Couple",
"to",
"vswitch",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/sample/simple/sample.py#L151-L166 | train | 43,462 |
mfcloud/python-zvm-sdk | sample/simple/sample.py | grant_user | def grant_user(userid, vswitch_name):
""" Grant user.
Input parameters:
:userid: USERID of the guest, last 8 if length > 8
:network_info: dict of network info
"""
print("\nGranting user %s ..." % userid)
user_grant_info = client.send_request('vswitch_grant_user', vswitch_name, userid)
if user_grant_info['overallRC']:
raise RuntimeError("Failed to grant user %s!" %userid)
else:
print("Succeeded to grant user %s!" % userid) | python | def grant_user(userid, vswitch_name):
""" Grant user.
Input parameters:
:userid: USERID of the guest, last 8 if length > 8
:network_info: dict of network info
"""
print("\nGranting user %s ..." % userid)
user_grant_info = client.send_request('vswitch_grant_user', vswitch_name, userid)
if user_grant_info['overallRC']:
raise RuntimeError("Failed to grant user %s!" %userid)
else:
print("Succeeded to grant user %s!" % userid) | [
"def",
"grant_user",
"(",
"userid",
",",
"vswitch_name",
")",
":",
"print",
"(",
"\"\\nGranting user %s ...\"",
"%",
"userid",
")",
"user_grant_info",
"=",
"client",
".",
"send_request",
"(",
"'vswitch_grant_user'",
",",
"vswitch_name",
",",
"userid",
")",
"if",
... | Grant user.
Input parameters:
:userid: USERID of the guest, last 8 if length > 8
:network_info: dict of network info | [
"Grant",
"user",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/sample/simple/sample.py#L169-L182 | train | 43,463 |
mfcloud/python-zvm-sdk | sample/simple/sample.py | start_guest | def start_guest(userid):
""" Power on the vm.
Input parameters:
:userid: USERID of the guest, last 8 if length > 8
"""
# Check the power state before starting guest.
power_state_info = client.send_request('guest_get_power_state', userid)
print("\nPower state is: %s." % power_state_info['output'])
# start guest.
guest_start_info = client.send_request('guest_start', userid)
if guest_start_info['overallRC']:
raise RuntimeError('Failed to start guest %s!\n%s' %
(userid, guest_start_info))
else:
print("Succeeded to start guest %s!" % userid)
# Check the power state after starting guest.
power_state_info = client.send_request('guest_get_power_state', userid)
print("Power state is: %s." % power_state_info['output'])
if guest_start_info['overallRC']:
print("Guest_start error: %s" % guest_start_info) | python | def start_guest(userid):
""" Power on the vm.
Input parameters:
:userid: USERID of the guest, last 8 if length > 8
"""
# Check the power state before starting guest.
power_state_info = client.send_request('guest_get_power_state', userid)
print("\nPower state is: %s." % power_state_info['output'])
# start guest.
guest_start_info = client.send_request('guest_start', userid)
if guest_start_info['overallRC']:
raise RuntimeError('Failed to start guest %s!\n%s' %
(userid, guest_start_info))
else:
print("Succeeded to start guest %s!" % userid)
# Check the power state after starting guest.
power_state_info = client.send_request('guest_get_power_state', userid)
print("Power state is: %s." % power_state_info['output'])
if guest_start_info['overallRC']:
print("Guest_start error: %s" % guest_start_info) | [
"def",
"start_guest",
"(",
"userid",
")",
":",
"# Check the power state before starting guest.",
"power_state_info",
"=",
"client",
".",
"send_request",
"(",
"'guest_get_power_state'",
",",
"userid",
")",
"print",
"(",
"\"\\nPower state is: %s.\"",
"%",
"power_state_info",
... | Power on the vm.
Input parameters:
:userid: USERID of the guest, last 8 if length > 8 | [
"Power",
"on",
"the",
"vm",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/sample/simple/sample.py#L185-L209 | train | 43,464 |
mfcloud/python-zvm-sdk | sample/simple/sample.py | _run_guest | def _run_guest(userid, image_path, os_version, profile,
cpu, memory, network_info, vswitch_name, disks_list):
""" Deploy and provide a virtual machine.
Input parameters:
:userid: USERID of the guest, no more than 8
:image_path: image file path
:os_version: os version of the image file
:profile: profile of the userid
:cpu: the number of vcpus
:memory: memory
:network_info: dict of network info. Members are:
:ip_addr: ip address of vm
:gateway: gateway of network
:cidr: CIDR
:vswitch_name: vswitch name
:disks_list: list of disks to add. For example:
disks_list = [{'size': '3g',
'is_boot_disk': True,
'disk_pool': 'ECDK: xcateckd'}]
"""
print("Start deploying a virtual machine:")
# Import image if not exists.
import_image(image_path, os_version)
# Start time.
spawn_start = time.time()
# Create guest.
create_guest(userid, cpu, memory, disks_list, profile)
# Deploy image to root disk.
image_name = os.path.basename(image_path)
deploy_guest(userid, image_name)
# Create network device and configure network interface.
create_network(userid, os_version, network_info)
# Couple to vswitch.
coupleTo_vswitch(userid, vswitch_name)
# Grant user.
grant_user(userid, vswitch_name)
# Power on the vm.
start_guest(userid)
# End the time.
spawn_time = time.time() - spawn_start
print("Instance-%s spawned succeeded in %s seconds!" %
(userid, spawn_time))
# Describe guest.
describe_guest(userid) | python | def _run_guest(userid, image_path, os_version, profile,
cpu, memory, network_info, vswitch_name, disks_list):
""" Deploy and provide a virtual machine.
Input parameters:
:userid: USERID of the guest, no more than 8
:image_path: image file path
:os_version: os version of the image file
:profile: profile of the userid
:cpu: the number of vcpus
:memory: memory
:network_info: dict of network info. Members are:
:ip_addr: ip address of vm
:gateway: gateway of network
:cidr: CIDR
:vswitch_name: vswitch name
:disks_list: list of disks to add. For example:
disks_list = [{'size': '3g',
'is_boot_disk': True,
'disk_pool': 'ECDK: xcateckd'}]
"""
print("Start deploying a virtual machine:")
# Import image if not exists.
import_image(image_path, os_version)
# Start time.
spawn_start = time.time()
# Create guest.
create_guest(userid, cpu, memory, disks_list, profile)
# Deploy image to root disk.
image_name = os.path.basename(image_path)
deploy_guest(userid, image_name)
# Create network device and configure network interface.
create_network(userid, os_version, network_info)
# Couple to vswitch.
coupleTo_vswitch(userid, vswitch_name)
# Grant user.
grant_user(userid, vswitch_name)
# Power on the vm.
start_guest(userid)
# End the time.
spawn_time = time.time() - spawn_start
print("Instance-%s spawned succeeded in %s seconds!" %
(userid, spawn_time))
# Describe guest.
describe_guest(userid) | [
"def",
"_run_guest",
"(",
"userid",
",",
"image_path",
",",
"os_version",
",",
"profile",
",",
"cpu",
",",
"memory",
",",
"network_info",
",",
"vswitch_name",
",",
"disks_list",
")",
":",
"print",
"(",
"\"Start deploying a virtual machine:\"",
")",
"# Import image... | Deploy and provide a virtual machine.
Input parameters:
:userid: USERID of the guest, no more than 8
:image_path: image file path
:os_version: os version of the image file
:profile: profile of the userid
:cpu: the number of vcpus
:memory: memory
:network_info: dict of network info. Members are:
:ip_addr: ip address of vm
:gateway: gateway of network
:cidr: CIDR
:vswitch_name: vswitch name
:disks_list: list of disks to add. For example:
disks_list = [{'size': '3g',
'is_boot_disk': True,
'disk_pool': 'ECDK: xcateckd'}] | [
"Deploy",
"and",
"provide",
"a",
"virtual",
"machine",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/sample/simple/sample.py#L212-L266 | train | 43,465 |
mfcloud/python-zvm-sdk | sample/simple/sample.py | _user_input_properties | def _user_input_properties():
""" User input the properties of guest, image, and network. """
global GUEST_USERID
global GUEST_PROFILE
global GUEST_VCPUS
global GUEST_MEMORY
global GUEST_ROOT_DISK_SIZE
global DISK_POOL
global IMAGE_PATH
global IMAGE_OS_VERSION
global GUEST_IP_ADDR
global GATEWAY
global CIDR
global VSWITCH_NAME
global NETWORK_INFO
global DISKS_LIST
pythonVersion = sys.version[0]
print("Your python interpreter's version is %s." % pythonVersion)
if pythonVersion == '2':
print("Input properties with string type in ''.")
else:
print("Input properties without ''.")
print("Please input guest properties:")
GUEST_USERID = input("guest_userid = ")
GUEST_PROFILE = input("guest_profile = ")
GUEST_VCPUS = int(input("guest_vcpus = "))
GUEST_MEMORY = int(input("guest_memory (in Megabytes) = "))
GUEST_ROOT_DISK_SIZE = int(input("guest_root_disk_size (in Gigabytes) = "))
GUEST_POOL = input("disk_pool = ")
print("\n")
IMAGE_PATH = input("image_path = ")
IMAGE_OS_VERSION = input("image_os_version = ")
print("\n")
GUEST_IP_ADDR = input("guest_ip_addr = ")
GATEWAY = input("gateway = ")
CIDR = input("cidr = ")
VSWITCH_NAME = input("vswitch_name = ")
NETWORK_INFO = [{'ip_addr': GUEST_IP_ADDR, 'gateway_addr': GATEWAY, 'cidr': CIDR}]
DISKS_LIST = [{'size': '%dg' % GUEST_ROOT_DISK_SIZE,
'is_boot_disk': True, 'disk_pool': GUEST_POOL}] | python | def _user_input_properties():
""" User input the properties of guest, image, and network. """
global GUEST_USERID
global GUEST_PROFILE
global GUEST_VCPUS
global GUEST_MEMORY
global GUEST_ROOT_DISK_SIZE
global DISK_POOL
global IMAGE_PATH
global IMAGE_OS_VERSION
global GUEST_IP_ADDR
global GATEWAY
global CIDR
global VSWITCH_NAME
global NETWORK_INFO
global DISKS_LIST
pythonVersion = sys.version[0]
print("Your python interpreter's version is %s." % pythonVersion)
if pythonVersion == '2':
print("Input properties with string type in ''.")
else:
print("Input properties without ''.")
print("Please input guest properties:")
GUEST_USERID = input("guest_userid = ")
GUEST_PROFILE = input("guest_profile = ")
GUEST_VCPUS = int(input("guest_vcpus = "))
GUEST_MEMORY = int(input("guest_memory (in Megabytes) = "))
GUEST_ROOT_DISK_SIZE = int(input("guest_root_disk_size (in Gigabytes) = "))
GUEST_POOL = input("disk_pool = ")
print("\n")
IMAGE_PATH = input("image_path = ")
IMAGE_OS_VERSION = input("image_os_version = ")
print("\n")
GUEST_IP_ADDR = input("guest_ip_addr = ")
GATEWAY = input("gateway = ")
CIDR = input("cidr = ")
VSWITCH_NAME = input("vswitch_name = ")
NETWORK_INFO = [{'ip_addr': GUEST_IP_ADDR, 'gateway_addr': GATEWAY, 'cidr': CIDR}]
DISKS_LIST = [{'size': '%dg' % GUEST_ROOT_DISK_SIZE,
'is_boot_disk': True, 'disk_pool': GUEST_POOL}] | [
"def",
"_user_input_properties",
"(",
")",
":",
"global",
"GUEST_USERID",
"global",
"GUEST_PROFILE",
"global",
"GUEST_VCPUS",
"global",
"GUEST_MEMORY",
"global",
"GUEST_ROOT_DISK_SIZE",
"global",
"DISK_POOL",
"global",
"IMAGE_PATH",
"global",
"IMAGE_OS_VERSION",
"global",
... | User input the properties of guest, image, and network. | [
"User",
"input",
"the",
"properties",
"of",
"guest",
"image",
"and",
"network",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/sample/simple/sample.py#L269-L315 | train | 43,466 |
mfcloud/python-zvm-sdk | sample/simple/sample.py | run_guest | def run_guest():
"""
A sample for quickly deploy and start a virtual guest.
"""
# user input the properties of guest, image and network.
_user_input_properties()
# run a guest.
_run_guest(GUEST_USERID, IMAGE_PATH, IMAGE_OS_VERSION, GUEST_PROFILE,
GUEST_VCPUS, GUEST_MEMORY, NETWORK_INFO, VSWITCH_NAME, DISKS_LIST) | python | def run_guest():
"""
A sample for quickly deploy and start a virtual guest.
"""
# user input the properties of guest, image and network.
_user_input_properties()
# run a guest.
_run_guest(GUEST_USERID, IMAGE_PATH, IMAGE_OS_VERSION, GUEST_PROFILE,
GUEST_VCPUS, GUEST_MEMORY, NETWORK_INFO, VSWITCH_NAME, DISKS_LIST) | [
"def",
"run_guest",
"(",
")",
":",
"# user input the properties of guest, image and network.",
"_user_input_properties",
"(",
")",
"# run a guest.",
"_run_guest",
"(",
"GUEST_USERID",
",",
"IMAGE_PATH",
",",
"IMAGE_OS_VERSION",
",",
"GUEST_PROFILE",
",",
"GUEST_VCPUS",
",",... | A sample for quickly deploy and start a virtual guest. | [
"A",
"sample",
"for",
"quickly",
"deploy",
"and",
"start",
"a",
"virtual",
"guest",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/sample/simple/sample.py#L318-L328 | train | 43,467 |
mfcloud/python-zvm-sdk | doc/source/conf.py | package_version | def package_version(filename, varname):
"""Return package version string by reading `filename` and retrieving its
module-global variable `varnam`."""
_locals = {}
with open(filename) as fp:
exec(fp.read(), None, _locals)
return _locals[varname] | python | def package_version(filename, varname):
"""Return package version string by reading `filename` and retrieving its
module-global variable `varnam`."""
_locals = {}
with open(filename) as fp:
exec(fp.read(), None, _locals)
return _locals[varname] | [
"def",
"package_version",
"(",
"filename",
",",
"varname",
")",
":",
"_locals",
"=",
"{",
"}",
"with",
"open",
"(",
"filename",
")",
"as",
"fp",
":",
"exec",
"(",
"fp",
".",
"read",
"(",
")",
",",
"None",
",",
"_locals",
")",
"return",
"_locals",
"... | Return package version string by reading `filename` and retrieving its
module-global variable `varnam`. | [
"Return",
"package",
"version",
"string",
"by",
"reading",
"filename",
"and",
"retrieving",
"its",
"module",
"-",
"global",
"variable",
"varnam",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/doc/source/conf.py#L69-L75 | train | 43,468 |
mfcloud/python-zvm-sdk | smtLayer/smapi.py | invokeSmapiApi | def invokeSmapiApi(rh):
"""
Invoke a SMAPI API.
Input:
Request Handle with the following properties:
function - 'SMAPI'
subfunction - 'API'
userid - 'HYPERVISOR'
parms['apiName'] - Name of API as defined by SMCLI
parms['operands'] - List (array) of operands to send or
an empty list.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter smapi.invokeSmapiApi")
if rh.userid != 'HYPERVISOR':
userid = rh.userid
else:
userid = 'dummy'
parms = ["-T", userid]
if 'operands' in rh.parms:
parms.extend(rh.parms['operands'])
results = invokeSMCLI(rh, rh.parms['apiName'], parms)
if results['overallRC'] == 0:
rh.printLn("N", results['response'])
else:
# SMAPI API failed.
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results from invokeSMCLI
rh.printSysLog("Exit smapi.invokeCmd, rc: " + str(rh.results['overallRC']))
return rh.results['overallRC'] | python | def invokeSmapiApi(rh):
"""
Invoke a SMAPI API.
Input:
Request Handle with the following properties:
function - 'SMAPI'
subfunction - 'API'
userid - 'HYPERVISOR'
parms['apiName'] - Name of API as defined by SMCLI
parms['operands'] - List (array) of operands to send or
an empty list.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter smapi.invokeSmapiApi")
if rh.userid != 'HYPERVISOR':
userid = rh.userid
else:
userid = 'dummy'
parms = ["-T", userid]
if 'operands' in rh.parms:
parms.extend(rh.parms['operands'])
results = invokeSMCLI(rh, rh.parms['apiName'], parms)
if results['overallRC'] == 0:
rh.printLn("N", results['response'])
else:
# SMAPI API failed.
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results from invokeSMCLI
rh.printSysLog("Exit smapi.invokeCmd, rc: " + str(rh.results['overallRC']))
return rh.results['overallRC'] | [
"def",
"invokeSmapiApi",
"(",
"rh",
")",
":",
"rh",
".",
"printSysLog",
"(",
"\"Enter smapi.invokeSmapiApi\"",
")",
"if",
"rh",
".",
"userid",
"!=",
"'HYPERVISOR'",
":",
"userid",
"=",
"rh",
".",
"userid",
"else",
":",
"userid",
"=",
"'dummy'",
"parms",
"=... | Invoke a SMAPI API.
Input:
Request Handle with the following properties:
function - 'SMAPI'
subfunction - 'API'
userid - 'HYPERVISOR'
parms['apiName'] - Name of API as defined by SMCLI
parms['operands'] - List (array) of operands to send or
an empty list.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error | [
"Invoke",
"a",
"SMAPI",
"API",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/smtLayer/smapi.py#L133-L170 | train | 43,469 |
mfcloud/python-zvm-sdk | zvmsdk/volumeop.py | FCPManager.init_fcp | def init_fcp(self, assigner_id):
"""init_fcp to init the FCP managed by this host"""
# TODO master_fcp_list (zvm_zhcp_fcp_list) really need?
fcp_list = CONF.volume.fcp_list
if fcp_list == '':
errmsg = ("because CONF.volume.fcp_list is empty, "
"no volume functions available")
LOG.info(errmsg)
return
self._fcp_info = self._init_fcp_pool(fcp_list, assigner_id)
self._sync_db_fcp_list() | python | def init_fcp(self, assigner_id):
"""init_fcp to init the FCP managed by this host"""
# TODO master_fcp_list (zvm_zhcp_fcp_list) really need?
fcp_list = CONF.volume.fcp_list
if fcp_list == '':
errmsg = ("because CONF.volume.fcp_list is empty, "
"no volume functions available")
LOG.info(errmsg)
return
self._fcp_info = self._init_fcp_pool(fcp_list, assigner_id)
self._sync_db_fcp_list() | [
"def",
"init_fcp",
"(",
"self",
",",
"assigner_id",
")",
":",
"# TODO master_fcp_list (zvm_zhcp_fcp_list) really need?",
"fcp_list",
"=",
"CONF",
".",
"volume",
".",
"fcp_list",
"if",
"fcp_list",
"==",
"''",
":",
"errmsg",
"=",
"(",
"\"because CONF.volume.fcp_list is ... | init_fcp to init the FCP managed by this host | [
"init_fcp",
"to",
"init",
"the",
"FCP",
"managed",
"by",
"this",
"host"
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/volumeop.py#L258-L269 | train | 43,470 |
mfcloud/python-zvm-sdk | zvmsdk/volumeop.py | FCPManager._expand_fcp_list | def _expand_fcp_list(fcp_list):
"""Expand fcp list string into a python list object which contains
each fcp devices in the list string. A fcp list is composed of fcp
device addresses, range indicator '-', and split indicator ';'.
For example, if fcp_list is
"0011-0013;0015;0017-0018", expand_fcp_list(fcp_list) will return
[0011, 0012, 0013, 0015, 0017, 0018].
"""
LOG.debug("Expand FCP list %s" % fcp_list)
if not fcp_list:
return set()
range_pattern = '[0-9a-fA-F]{1,4}(-[0-9a-fA-F]{1,4})?'
match_pattern = "^(%(range)s)(;%(range)s)*$" % {'range': range_pattern}
if not re.match(match_pattern, fcp_list):
errmsg = ("Invalid FCP address %s") % fcp_list
raise exception.SDKInternalError(msg=errmsg)
fcp_devices = set()
for _range in fcp_list.split(';'):
if '-' not in _range:
# single device
fcp_addr = int(_range, 16)
fcp_devices.add("%04x" % fcp_addr)
else:
# a range of address
(_min, _max) = _range.split('-')
_min = int(_min, 16)
_max = int(_max, 16)
for fcp_addr in range(_min, _max + 1):
fcp_devices.add("%04x" % fcp_addr)
# remove duplicate entries
return fcp_devices | python | def _expand_fcp_list(fcp_list):
"""Expand fcp list string into a python list object which contains
each fcp devices in the list string. A fcp list is composed of fcp
device addresses, range indicator '-', and split indicator ';'.
For example, if fcp_list is
"0011-0013;0015;0017-0018", expand_fcp_list(fcp_list) will return
[0011, 0012, 0013, 0015, 0017, 0018].
"""
LOG.debug("Expand FCP list %s" % fcp_list)
if not fcp_list:
return set()
range_pattern = '[0-9a-fA-F]{1,4}(-[0-9a-fA-F]{1,4})?'
match_pattern = "^(%(range)s)(;%(range)s)*$" % {'range': range_pattern}
if not re.match(match_pattern, fcp_list):
errmsg = ("Invalid FCP address %s") % fcp_list
raise exception.SDKInternalError(msg=errmsg)
fcp_devices = set()
for _range in fcp_list.split(';'):
if '-' not in _range:
# single device
fcp_addr = int(_range, 16)
fcp_devices.add("%04x" % fcp_addr)
else:
# a range of address
(_min, _max) = _range.split('-')
_min = int(_min, 16)
_max = int(_max, 16)
for fcp_addr in range(_min, _max + 1):
fcp_devices.add("%04x" % fcp_addr)
# remove duplicate entries
return fcp_devices | [
"def",
"_expand_fcp_list",
"(",
"fcp_list",
")",
":",
"LOG",
".",
"debug",
"(",
"\"Expand FCP list %s\"",
"%",
"fcp_list",
")",
"if",
"not",
"fcp_list",
":",
"return",
"set",
"(",
")",
"range_pattern",
"=",
"'[0-9a-fA-F]{1,4}(-[0-9a-fA-F]{1,4})?'",
"match_pattern",
... | Expand fcp list string into a python list object which contains
each fcp devices in the list string. A fcp list is composed of fcp
device addresses, range indicator '-', and split indicator ';'.
For example, if fcp_list is
"0011-0013;0015;0017-0018", expand_fcp_list(fcp_list) will return
[0011, 0012, 0013, 0015, 0017, 0018]. | [
"Expand",
"fcp",
"list",
"string",
"into",
"a",
"python",
"list",
"object",
"which",
"contains",
"each",
"fcp",
"devices",
"in",
"the",
"list",
"string",
".",
"A",
"fcp",
"list",
"is",
"composed",
"of",
"fcp",
"device",
"addresses",
"range",
"indicator",
"... | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/volumeop.py#L315-L352 | train | 43,471 |
mfcloud/python-zvm-sdk | zvmsdk/volumeop.py | FCPManager._add_fcp | def _add_fcp(self, fcp):
"""add fcp to db if it's not in db but in fcp list and init it"""
try:
LOG.info("fcp %s found in CONF.volume.fcp_list, add it to db" %
fcp)
self.db.new(fcp)
except Exception:
LOG.info("failed to add fcp %s into db", fcp) | python | def _add_fcp(self, fcp):
"""add fcp to db if it's not in db but in fcp list and init it"""
try:
LOG.info("fcp %s found in CONF.volume.fcp_list, add it to db" %
fcp)
self.db.new(fcp)
except Exception:
LOG.info("failed to add fcp %s into db", fcp) | [
"def",
"_add_fcp",
"(",
"self",
",",
"fcp",
")",
":",
"try",
":",
"LOG",
".",
"info",
"(",
"\"fcp %s found in CONF.volume.fcp_list, add it to db\"",
"%",
"fcp",
")",
"self",
".",
"db",
".",
"new",
"(",
"fcp",
")",
"except",
"Exception",
":",
"LOG",
".",
... | add fcp to db if it's not in db but in fcp list and init it | [
"add",
"fcp",
"to",
"db",
"if",
"it",
"s",
"not",
"in",
"db",
"but",
"in",
"fcp",
"list",
"and",
"init",
"it"
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/volumeop.py#L360-L367 | train | 43,472 |
mfcloud/python-zvm-sdk | zvmsdk/volumeop.py | FCPManager._sync_db_fcp_list | def _sync_db_fcp_list(self):
"""sync db records from given fcp list, for example, you need
warn if some FCP already removed while it's still in use,
or info about the new FCP added"""
fcp_db_list = self.db.get_all()
for fcp_rec in fcp_db_list:
if not fcp_rec[0].lower() in self._fcp_pool:
self._report_orphan_fcp(fcp_rec[0])
for fcp_conf_rec, v in self._fcp_pool.items():
res = self.db.get_from_fcp(fcp_conf_rec)
# if not found this record, a [] will be returned
if len(res) == 0:
self._add_fcp(fcp_conf_rec) | python | def _sync_db_fcp_list(self):
"""sync db records from given fcp list, for example, you need
warn if some FCP already removed while it's still in use,
or info about the new FCP added"""
fcp_db_list = self.db.get_all()
for fcp_rec in fcp_db_list:
if not fcp_rec[0].lower() in self._fcp_pool:
self._report_orphan_fcp(fcp_rec[0])
for fcp_conf_rec, v in self._fcp_pool.items():
res = self.db.get_from_fcp(fcp_conf_rec)
# if not found this record, a [] will be returned
if len(res) == 0:
self._add_fcp(fcp_conf_rec) | [
"def",
"_sync_db_fcp_list",
"(",
"self",
")",
":",
"fcp_db_list",
"=",
"self",
".",
"db",
".",
"get_all",
"(",
")",
"for",
"fcp_rec",
"in",
"fcp_db_list",
":",
"if",
"not",
"fcp_rec",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"in",
"self",
".",
"_fcp_po... | sync db records from given fcp list, for example, you need
warn if some FCP already removed while it's still in use,
or info about the new FCP added | [
"sync",
"db",
"records",
"from",
"given",
"fcp",
"list",
"for",
"example",
"you",
"need",
"warn",
"if",
"some",
"FCP",
"already",
"removed",
"while",
"it",
"s",
"still",
"in",
"use",
"or",
"info",
"about",
"the",
"new",
"FCP",
"added"
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/volumeop.py#L369-L384 | train | 43,473 |
mfcloud/python-zvm-sdk | zvmsdk/volumeop.py | FCPManager.find_and_reserve_fcp | def find_and_reserve_fcp(self, assigner_id):
"""reserve the fcp to assigner_id
The function to reserve a fcp for user
1. Check whether assigner_id has a fcp already
if yes, make the reserve of that record to 1
2. No fcp, then find a fcp and reserve it
fcp will be returned, or None indicate no fcp
"""
fcp_list = self.db.get_from_assigner(assigner_id)
if not fcp_list:
new_fcp = self.db.find_and_reserve()
if new_fcp is None:
LOG.info("no more fcp to be allocated")
return None
LOG.debug("allocated %s fcp for %s assigner" %
(new_fcp, assigner_id))
return new_fcp
else:
# we got it from db, let's reuse it
old_fcp = fcp_list[0][0]
self.db.reserve(fcp_list[0][0])
return old_fcp | python | def find_and_reserve_fcp(self, assigner_id):
"""reserve the fcp to assigner_id
The function to reserve a fcp for user
1. Check whether assigner_id has a fcp already
if yes, make the reserve of that record to 1
2. No fcp, then find a fcp and reserve it
fcp will be returned, or None indicate no fcp
"""
fcp_list = self.db.get_from_assigner(assigner_id)
if not fcp_list:
new_fcp = self.db.find_and_reserve()
if new_fcp is None:
LOG.info("no more fcp to be allocated")
return None
LOG.debug("allocated %s fcp for %s assigner" %
(new_fcp, assigner_id))
return new_fcp
else:
# we got it from db, let's reuse it
old_fcp = fcp_list[0][0]
self.db.reserve(fcp_list[0][0])
return old_fcp | [
"def",
"find_and_reserve_fcp",
"(",
"self",
",",
"assigner_id",
")",
":",
"fcp_list",
"=",
"self",
".",
"db",
".",
"get_from_assigner",
"(",
"assigner_id",
")",
"if",
"not",
"fcp_list",
":",
"new_fcp",
"=",
"self",
".",
"db",
".",
"find_and_reserve",
"(",
... | reserve the fcp to assigner_id
The function to reserve a fcp for user
1. Check whether assigner_id has a fcp already
if yes, make the reserve of that record to 1
2. No fcp, then find a fcp and reserve it
fcp will be returned, or None indicate no fcp | [
"reserve",
"the",
"fcp",
"to",
"assigner_id"
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/volumeop.py#L402-L426 | train | 43,474 |
mfcloud/python-zvm-sdk | zvmsdk/volumeop.py | FCPManager.increase_fcp_usage | def increase_fcp_usage(self, fcp, assigner_id=None):
"""Incrase fcp usage of given fcp
Returns True if it's a new fcp, otherwise return False
"""
# TODO: check assigner_id to make sure on the correct fcp record
connections = self.db.get_connections_from_assigner(assigner_id)
new = False
if connections == 0:
self.db.assign(fcp, assigner_id)
new = True
else:
self.db.increase_usage(fcp)
return new | python | def increase_fcp_usage(self, fcp, assigner_id=None):
"""Incrase fcp usage of given fcp
Returns True if it's a new fcp, otherwise return False
"""
# TODO: check assigner_id to make sure on the correct fcp record
connections = self.db.get_connections_from_assigner(assigner_id)
new = False
if connections == 0:
self.db.assign(fcp, assigner_id)
new = True
else:
self.db.increase_usage(fcp)
return new | [
"def",
"increase_fcp_usage",
"(",
"self",
",",
"fcp",
",",
"assigner_id",
"=",
"None",
")",
":",
"# TODO: check assigner_id to make sure on the correct fcp record",
"connections",
"=",
"self",
".",
"db",
".",
"get_connections_from_assigner",
"(",
"assigner_id",
")",
"ne... | Incrase fcp usage of given fcp
Returns True if it's a new fcp, otherwise return False | [
"Incrase",
"fcp",
"usage",
"of",
"given",
"fcp"
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/volumeop.py#L428-L443 | train | 43,475 |
mfcloud/python-zvm-sdk | zvmsdk/volumeop.py | FCPManager.get_available_fcp | def get_available_fcp(self):
"""get all the fcps not reserved"""
# get the unreserved FCP devices belongs to assigner_id
available_list = []
free_unreserved = self.db.get_all_free_unreserved()
for item in free_unreserved:
available_list.append(item[0])
return available_list | python | def get_available_fcp(self):
"""get all the fcps not reserved"""
# get the unreserved FCP devices belongs to assigner_id
available_list = []
free_unreserved = self.db.get_all_free_unreserved()
for item in free_unreserved:
available_list.append(item[0])
return available_list | [
"def",
"get_available_fcp",
"(",
"self",
")",
":",
"# get the unreserved FCP devices belongs to assigner_id",
"available_list",
"=",
"[",
"]",
"free_unreserved",
"=",
"self",
".",
"db",
".",
"get_all_free_unreserved",
"(",
")",
"for",
"item",
"in",
"free_unreserved",
... | get all the fcps not reserved | [
"get",
"all",
"the",
"fcps",
"not",
"reserved"
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/volumeop.py#L458-L465 | train | 43,476 |
mfcloud/python-zvm-sdk | zvmsdk/volumeop.py | FCPVolumeManager._attach | def _attach(self, fcp, assigner_id, target_wwpn, target_lun,
multipath, os_version, mount_point):
"""Attach a volume
First, we need translate fcp into local wwpn, then
dedicate fcp to the user if it's needed, after that
call smt layer to call linux command
"""
LOG.info('Start to attach device to %s' % assigner_id)
self.fcp_mgr.init_fcp(assigner_id)
new = self.fcp_mgr.increase_fcp_usage(fcp, assigner_id)
try:
if new:
self._dedicate_fcp(fcp, assigner_id)
self._add_disk(fcp, assigner_id, target_wwpn, target_lun,
multipath, os_version, mount_point)
except exception.SDKBaseException as err:
errmsg = 'rollback attach because error:' + err.format_message()
LOG.error(errmsg)
connections = self.fcp_mgr.decrease_fcp_usage(fcp, assigner_id)
# if connections less than 1, undedicate the device
if not connections:
with zvmutils.ignore_errors():
self._undedicate_fcp(fcp, assigner_id)
raise exception.SDKBaseException(msg=errmsg)
# TODO: other exceptions?
LOG.info('Attaching device to %s is done.' % assigner_id) | python | def _attach(self, fcp, assigner_id, target_wwpn, target_lun,
multipath, os_version, mount_point):
"""Attach a volume
First, we need translate fcp into local wwpn, then
dedicate fcp to the user if it's needed, after that
call smt layer to call linux command
"""
LOG.info('Start to attach device to %s' % assigner_id)
self.fcp_mgr.init_fcp(assigner_id)
new = self.fcp_mgr.increase_fcp_usage(fcp, assigner_id)
try:
if new:
self._dedicate_fcp(fcp, assigner_id)
self._add_disk(fcp, assigner_id, target_wwpn, target_lun,
multipath, os_version, mount_point)
except exception.SDKBaseException as err:
errmsg = 'rollback attach because error:' + err.format_message()
LOG.error(errmsg)
connections = self.fcp_mgr.decrease_fcp_usage(fcp, assigner_id)
# if connections less than 1, undedicate the device
if not connections:
with zvmutils.ignore_errors():
self._undedicate_fcp(fcp, assigner_id)
raise exception.SDKBaseException(msg=errmsg)
# TODO: other exceptions?
LOG.info('Attaching device to %s is done.' % assigner_id) | [
"def",
"_attach",
"(",
"self",
",",
"fcp",
",",
"assigner_id",
",",
"target_wwpn",
",",
"target_lun",
",",
"multipath",
",",
"os_version",
",",
"mount_point",
")",
":",
"LOG",
".",
"info",
"(",
"'Start to attach device to %s'",
"%",
"assigner_id",
")",
"self",... | Attach a volume
First, we need translate fcp into local wwpn, then
dedicate fcp to the user if it's needed, after that
call smt layer to call linux command | [
"Attach",
"a",
"volume"
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/volumeop.py#L496-L524 | train | 43,477 |
mfcloud/python-zvm-sdk | zvmsdk/volumeop.py | FCPVolumeManager.get_volume_connector | def get_volume_connector(self, assigner_id):
"""Get connector information of the instance for attaching to volumes.
Connector information is a dictionary representing the ip of the
machine that will be making the connection, the name of the iscsi
initiator and the hostname of the machine as follows::
{
'zvm_fcp': fcp
'wwpns': [wwpn]
'host': host
}
"""
empty_connector = {'zvm_fcp': [], 'wwpns': [], 'host': ''}
# init fcp pool
self.fcp_mgr.init_fcp(assigner_id)
fcp_list = self.fcp_mgr.get_available_fcp()
if not fcp_list:
errmsg = "No available FCP device found."
LOG.warning(errmsg)
return empty_connector
wwpns = []
for fcp_no in fcp_list:
wwpn = self.fcp_mgr.get_wwpn(fcp_no)
if not wwpn:
errmsg = "FCP device %s has no available WWPN." % fcp_no
LOG.warning(errmsg)
else:
wwpns.append(wwpn)
if not wwpns:
errmsg = "No available WWPN found."
LOG.warning(errmsg)
return empty_connector
inv_info = self._smtclient.get_host_info()
zvm_host = inv_info['zvm_host']
if zvm_host == '':
errmsg = "zvm host not specified."
LOG.warning(errmsg)
return empty_connector
connector = {'zvm_fcp': fcp_list,
'wwpns': wwpns,
'host': zvm_host}
LOG.debug('get_volume_connector returns %s for %s' %
(connector, assigner_id))
return connector | python | def get_volume_connector(self, assigner_id):
"""Get connector information of the instance for attaching to volumes.
Connector information is a dictionary representing the ip of the
machine that will be making the connection, the name of the iscsi
initiator and the hostname of the machine as follows::
{
'zvm_fcp': fcp
'wwpns': [wwpn]
'host': host
}
"""
empty_connector = {'zvm_fcp': [], 'wwpns': [], 'host': ''}
# init fcp pool
self.fcp_mgr.init_fcp(assigner_id)
fcp_list = self.fcp_mgr.get_available_fcp()
if not fcp_list:
errmsg = "No available FCP device found."
LOG.warning(errmsg)
return empty_connector
wwpns = []
for fcp_no in fcp_list:
wwpn = self.fcp_mgr.get_wwpn(fcp_no)
if not wwpn:
errmsg = "FCP device %s has no available WWPN." % fcp_no
LOG.warning(errmsg)
else:
wwpns.append(wwpn)
if not wwpns:
errmsg = "No available WWPN found."
LOG.warning(errmsg)
return empty_connector
inv_info = self._smtclient.get_host_info()
zvm_host = inv_info['zvm_host']
if zvm_host == '':
errmsg = "zvm host not specified."
LOG.warning(errmsg)
return empty_connector
connector = {'zvm_fcp': fcp_list,
'wwpns': wwpns,
'host': zvm_host}
LOG.debug('get_volume_connector returns %s for %s' %
(connector, assigner_id))
return connector | [
"def",
"get_volume_connector",
"(",
"self",
",",
"assigner_id",
")",
":",
"empty_connector",
"=",
"{",
"'zvm_fcp'",
":",
"[",
"]",
",",
"'wwpns'",
":",
"[",
"]",
",",
"'host'",
":",
"''",
"}",
"# init fcp pool",
"self",
".",
"fcp_mgr",
".",
"init_fcp",
"... | Get connector information of the instance for attaching to volumes.
Connector information is a dictionary representing the ip of the
machine that will be making the connection, the name of the iscsi
initiator and the hostname of the machine as follows::
{
'zvm_fcp': fcp
'wwpns': [wwpn]
'host': host
} | [
"Get",
"connector",
"information",
"of",
"the",
"instance",
"for",
"attaching",
"to",
"volumes",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/volumeop.py#L609-L658 | train | 43,478 |
jvarho/pylibscrypt | pylibscrypt/pypyscrypt_inline.py | blockmix_salsa8 | def blockmix_salsa8(BY, Yi, r):
"""Blockmix; Used by SMix"""
start = (2 * r - 1) * 16
X = BY[start:start+16] # BlockMix - 1
tmp = [0]*16
for i in xrange(2 * r): # BlockMix - 2
#blockxor(BY, i * 16, X, 0, 16) # BlockMix - 3(inner)
salsa20_8(X, tmp, BY, i * 16, BY, Yi + i*16) # BlockMix - 3(outer)
#array_overwrite(X, 0, BY, Yi + (i * 16), 16) # BlockMix - 4
for i in xrange(r): # BlockMix - 6
BY[i * 16:(i * 16)+(16)] = BY[Yi + (i * 2) * 16:(Yi + (i * 2) * 16)+(16)]
BY[(i + r) * 16:((i + r) * 16)+(16)] = BY[Yi + (i*2 + 1) * 16:(Yi + (i*2 + 1) * 16)+(16)] | python | def blockmix_salsa8(BY, Yi, r):
"""Blockmix; Used by SMix"""
start = (2 * r - 1) * 16
X = BY[start:start+16] # BlockMix - 1
tmp = [0]*16
for i in xrange(2 * r): # BlockMix - 2
#blockxor(BY, i * 16, X, 0, 16) # BlockMix - 3(inner)
salsa20_8(X, tmp, BY, i * 16, BY, Yi + i*16) # BlockMix - 3(outer)
#array_overwrite(X, 0, BY, Yi + (i * 16), 16) # BlockMix - 4
for i in xrange(r): # BlockMix - 6
BY[i * 16:(i * 16)+(16)] = BY[Yi + (i * 2) * 16:(Yi + (i * 2) * 16)+(16)]
BY[(i + r) * 16:((i + r) * 16)+(16)] = BY[Yi + (i*2 + 1) * 16:(Yi + (i*2 + 1) * 16)+(16)] | [
"def",
"blockmix_salsa8",
"(",
"BY",
",",
"Yi",
",",
"r",
")",
":",
"start",
"=",
"(",
"2",
"*",
"r",
"-",
"1",
")",
"*",
"16",
"X",
"=",
"BY",
"[",
"start",
":",
"start",
"+",
"16",
"]",
"# BlockMix - 1",
"tmp",
"=",
"[",
"0",
"]",
"*",
"1... | Blockmix; Used by SMix | [
"Blockmix",
";",
"Used",
"by",
"SMix"
] | f2ff02e49f44aa620e308a4a64dd8376b9510f99 | https://github.com/jvarho/pylibscrypt/blob/f2ff02e49f44aa620e308a4a64dd8376b9510f99/pylibscrypt/pypyscrypt_inline.py#L138-L152 | train | 43,479 |
Chilipp/psyplot | psyplot/project.py | multiple_subplots | def multiple_subplots(rows=1, cols=1, maxplots=None, n=1, delete=True,
for_maps=False, *args, **kwargs):
"""
Function to create subplots.
This function creates so many subplots on so many figures until the
specified number `n` is reached.
Parameters
----------
rows: int
The number of subplots per rows
cols: int
The number of subplots per column
maxplots: int
The number of subplots per figure (if None, it will be row*cols)
n: int
number of subplots to create
delete: bool
If True, the additional subplots per figure are deleted
for_maps: bool
If True this is a simple shortcut for setting
``subplot_kw=dict(projection=cartopy.crs.PlateCarree())`` and is
useful if you want to use the :attr:`~ProjectPlotter.mapplot`,
:attr:`~ProjectPlotter.mapvector` or
:attr:`~ProjectPlotter.mapcombined` plotting methods
``*args`` and ``**kwargs``
anything that is passed to the :func:`matplotlib.pyplot.subplots`
function
Returns
-------
list
list of maplotlib.axes.SubplotBase instances"""
import matplotlib.pyplot as plt
axes = np.array([])
maxplots = maxplots or rows * cols
kwargs.setdefault('figsize', [
min(8.*cols, 16), min(6.5*rows, 12)])
if for_maps:
import cartopy.crs as ccrs
subplot_kw = kwargs.setdefault('subplot_kw', {})
subplot_kw['projection'] = ccrs.PlateCarree()
for i in range(0, n, maxplots):
fig, ax = plt.subplots(rows, cols, *args, **kwargs)
try:
axes = np.append(axes, ax.ravel()[:maxplots])
if delete:
for iax in range(maxplots, rows * cols):
fig.delaxes(ax.ravel()[iax])
except AttributeError: # got a single subplot
axes = np.append(axes, [ax])
if i + maxplots > n and delete:
for ax2 in axes[n:]:
fig.delaxes(ax2)
axes = axes[:n]
return axes | python | def multiple_subplots(rows=1, cols=1, maxplots=None, n=1, delete=True,
for_maps=False, *args, **kwargs):
"""
Function to create subplots.
This function creates so many subplots on so many figures until the
specified number `n` is reached.
Parameters
----------
rows: int
The number of subplots per rows
cols: int
The number of subplots per column
maxplots: int
The number of subplots per figure (if None, it will be row*cols)
n: int
number of subplots to create
delete: bool
If True, the additional subplots per figure are deleted
for_maps: bool
If True this is a simple shortcut for setting
``subplot_kw=dict(projection=cartopy.crs.PlateCarree())`` and is
useful if you want to use the :attr:`~ProjectPlotter.mapplot`,
:attr:`~ProjectPlotter.mapvector` or
:attr:`~ProjectPlotter.mapcombined` plotting methods
``*args`` and ``**kwargs``
anything that is passed to the :func:`matplotlib.pyplot.subplots`
function
Returns
-------
list
list of maplotlib.axes.SubplotBase instances"""
import matplotlib.pyplot as plt
axes = np.array([])
maxplots = maxplots or rows * cols
kwargs.setdefault('figsize', [
min(8.*cols, 16), min(6.5*rows, 12)])
if for_maps:
import cartopy.crs as ccrs
subplot_kw = kwargs.setdefault('subplot_kw', {})
subplot_kw['projection'] = ccrs.PlateCarree()
for i in range(0, n, maxplots):
fig, ax = plt.subplots(rows, cols, *args, **kwargs)
try:
axes = np.append(axes, ax.ravel()[:maxplots])
if delete:
for iax in range(maxplots, rows * cols):
fig.delaxes(ax.ravel()[iax])
except AttributeError: # got a single subplot
axes = np.append(axes, [ax])
if i + maxplots > n and delete:
for ax2 in axes[n:]:
fig.delaxes(ax2)
axes = axes[:n]
return axes | [
"def",
"multiple_subplots",
"(",
"rows",
"=",
"1",
",",
"cols",
"=",
"1",
",",
"maxplots",
"=",
"None",
",",
"n",
"=",
"1",
",",
"delete",
"=",
"True",
",",
"for_maps",
"=",
"False",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
... | Function to create subplots.
This function creates so many subplots on so many figures until the
specified number `n` is reached.
Parameters
----------
rows: int
The number of subplots per rows
cols: int
The number of subplots per column
maxplots: int
The number of subplots per figure (if None, it will be row*cols)
n: int
number of subplots to create
delete: bool
If True, the additional subplots per figure are deleted
for_maps: bool
If True this is a simple shortcut for setting
``subplot_kw=dict(projection=cartopy.crs.PlateCarree())`` and is
useful if you want to use the :attr:`~ProjectPlotter.mapplot`,
:attr:`~ProjectPlotter.mapvector` or
:attr:`~ProjectPlotter.mapcombined` plotting methods
``*args`` and ``**kwargs``
anything that is passed to the :func:`matplotlib.pyplot.subplots`
function
Returns
-------
list
list of maplotlib.axes.SubplotBase instances | [
"Function",
"to",
"create",
"subplots",
"."
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/project.py#L82-L138 | train | 43,480 |
Chilipp/psyplot | psyplot/project.py | _only_main | def _only_main(func):
"""Call the given `func` only from the main project"""
@wraps(func)
def wrapper(self, *args, **kwargs):
if not self.is_main:
return getattr(self.main, func.__name__)(*args, **kwargs)
return func(self, *args, **kwargs)
return wrapper | python | def _only_main(func):
"""Call the given `func` only from the main project"""
@wraps(func)
def wrapper(self, *args, **kwargs):
if not self.is_main:
return getattr(self.main, func.__name__)(*args, **kwargs)
return func(self, *args, **kwargs)
return wrapper | [
"def",
"_only_main",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"is_main",
":",
"return",
"getattr",
"(",
"self",
".",
"main... | Call the given `func` only from the main project | [
"Call",
"the",
"given",
"func",
"only",
"from",
"the",
"main",
"project"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/project.py#L145-L152 | train | 43,481 |
Chilipp/psyplot | psyplot/project.py | gcp | def gcp(main=False):
"""
Get the current project
Parameters
----------
main: bool
If True, the current main project is returned, otherwise the current
subproject is returned.
See Also
--------
scp: Sets the current project
project: Creates a new project"""
if main:
return project() if _current_project is None else _current_project
else:
return gcp(True) if _current_subproject is None else \
_current_subproject | python | def gcp(main=False):
"""
Get the current project
Parameters
----------
main: bool
If True, the current main project is returned, otherwise the current
subproject is returned.
See Also
--------
scp: Sets the current project
project: Creates a new project"""
if main:
return project() if _current_project is None else _current_project
else:
return gcp(True) if _current_subproject is None else \
_current_subproject | [
"def",
"gcp",
"(",
"main",
"=",
"False",
")",
":",
"if",
"main",
":",
"return",
"project",
"(",
")",
"if",
"_current_project",
"is",
"None",
"else",
"_current_project",
"else",
":",
"return",
"gcp",
"(",
"True",
")",
"if",
"_current_subproject",
"is",
"N... | Get the current project
Parameters
----------
main: bool
If True, the current main project is returned, otherwise the current
subproject is returned.
See Also
--------
scp: Sets the current project
project: Creates a new project | [
"Get",
"the",
"current",
"project"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/project.py#L2262-L2279 | train | 43,482 |
Chilipp/psyplot | psyplot/project.py | _scp | def _scp(p, main=False):
"""scp version that allows a bit more control over whether the project is a
main project or not"""
global _current_subproject
global _current_project
if p is None:
mp = project() if main or _current_project is None else \
_current_project
_current_subproject = Project(main=mp)
elif not main:
_current_subproject = p
else:
_current_project = p | python | def _scp(p, main=False):
"""scp version that allows a bit more control over whether the project is a
main project or not"""
global _current_subproject
global _current_project
if p is None:
mp = project() if main or _current_project is None else \
_current_project
_current_subproject = Project(main=mp)
elif not main:
_current_subproject = p
else:
_current_project = p | [
"def",
"_scp",
"(",
"p",
",",
"main",
"=",
"False",
")",
":",
"global",
"_current_subproject",
"global",
"_current_project",
"if",
"p",
"is",
"None",
":",
"mp",
"=",
"project",
"(",
")",
"if",
"main",
"or",
"_current_project",
"is",
"None",
"else",
"_cur... | scp version that allows a bit more control over whether the project is a
main project or not | [
"scp",
"version",
"that",
"allows",
"a",
"bit",
"more",
"control",
"over",
"whether",
"the",
"project",
"is",
"a",
"main",
"project",
"or",
"not"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/project.py#L2298-L2310 | train | 43,483 |
Chilipp/psyplot | psyplot/project.py | close | def close(num=None, figs=True, data=True, ds=True, remove_only=False):
"""
Close the project
This method closes the current project (figures, data and datasets) or the
project specified by `num`
Parameters
----------
num: int, None or 'all'
if :class:`int`, it specifies the number of the project, if None, the
current subproject is closed, if ``'all'``, all open projects are
closed
%(Project.close.parameters)s
See Also
--------
Project.close"""
kws = dict(figs=figs, data=data, ds=ds, remove_only=remove_only)
cp_num = gcp(True).num
got_cp = False
if num is None:
project = gcp()
scp(None)
project.close(**kws)
elif num == 'all':
for project in _open_projects[:]:
project.close(**kws)
got_cp = got_cp or project.main.num == cp_num
del _open_projects[0]
else:
if isinstance(num, Project):
project = num
else:
project = [project for project in _open_projects
if project.num == num][0]
project.close(**kws)
try:
_open_projects.remove(project)
except ValueError:
pass
got_cp = got_cp or project.main.num == cp_num
if got_cp:
if _open_projects:
# set last opened project to the current
scp(_open_projects[-1])
else:
_scp(None, True) | python | def close(num=None, figs=True, data=True, ds=True, remove_only=False):
"""
Close the project
This method closes the current project (figures, data and datasets) or the
project specified by `num`
Parameters
----------
num: int, None or 'all'
if :class:`int`, it specifies the number of the project, if None, the
current subproject is closed, if ``'all'``, all open projects are
closed
%(Project.close.parameters)s
See Also
--------
Project.close"""
kws = dict(figs=figs, data=data, ds=ds, remove_only=remove_only)
cp_num = gcp(True).num
got_cp = False
if num is None:
project = gcp()
scp(None)
project.close(**kws)
elif num == 'all':
for project in _open_projects[:]:
project.close(**kws)
got_cp = got_cp or project.main.num == cp_num
del _open_projects[0]
else:
if isinstance(num, Project):
project = num
else:
project = [project for project in _open_projects
if project.num == num][0]
project.close(**kws)
try:
_open_projects.remove(project)
except ValueError:
pass
got_cp = got_cp or project.main.num == cp_num
if got_cp:
if _open_projects:
# set last opened project to the current
scp(_open_projects[-1])
else:
_scp(None, True) | [
"def",
"close",
"(",
"num",
"=",
"None",
",",
"figs",
"=",
"True",
",",
"data",
"=",
"True",
",",
"ds",
"=",
"True",
",",
"remove_only",
"=",
"False",
")",
":",
"kws",
"=",
"dict",
"(",
"figs",
"=",
"figs",
",",
"data",
"=",
"data",
",",
"ds",
... | Close the project
This method closes the current project (figures, data and datasets) or the
project specified by `num`
Parameters
----------
num: int, None or 'all'
if :class:`int`, it specifies the number of the project, if None, the
current subproject is closed, if ``'all'``, all open projects are
closed
%(Project.close.parameters)s
See Also
--------
Project.close | [
"Close",
"the",
"project"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/project.py#L2345-L2392 | train | 43,484 |
Chilipp/psyplot | psyplot/project.py | Project._fmtos | def _fmtos(self):
"""An iterator over formatoption objects
Contains only the formatoption whose keys are in all plotters in this
list"""
plotters = self.plotters
if len(plotters) == 0:
return {}
p0 = plotters[0]
if len(plotters) == 1:
return p0._fmtos
return (getattr(p0, key) for key in set(p0).intersection(
*map(set, plotters[1:]))) | python | def _fmtos(self):
"""An iterator over formatoption objects
Contains only the formatoption whose keys are in all plotters in this
list"""
plotters = self.plotters
if len(plotters) == 0:
return {}
p0 = plotters[0]
if len(plotters) == 1:
return p0._fmtos
return (getattr(p0, key) for key in set(p0).intersection(
*map(set, plotters[1:]))) | [
"def",
"_fmtos",
"(",
"self",
")",
":",
"plotters",
"=",
"self",
".",
"plotters",
"if",
"len",
"(",
"plotters",
")",
"==",
"0",
":",
"return",
"{",
"}",
"p0",
"=",
"plotters",
"[",
"0",
"]",
"if",
"len",
"(",
"plotters",
")",
"==",
"1",
":",
"r... | An iterator over formatoption objects
Contains only the formatoption whose keys are in all plotters in this
list | [
"An",
"iterator",
"over",
"formatoption",
"objects"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/project.py#L197-L209 | train | 43,485 |
Chilipp/psyplot | psyplot/project.py | Project.figs | def figs(self):
"""A mapping from figures to data objects with the plotter in this
figure"""
ret = utils.DefaultOrderedDict(lambda: self[1:0])
for arr in self:
if arr.psy.plotter is not None:
ret[arr.psy.plotter.ax.get_figure()].append(arr)
return OrderedDict(ret) | python | def figs(self):
"""A mapping from figures to data objects with the plotter in this
figure"""
ret = utils.DefaultOrderedDict(lambda: self[1:0])
for arr in self:
if arr.psy.plotter is not None:
ret[arr.psy.plotter.ax.get_figure()].append(arr)
return OrderedDict(ret) | [
"def",
"figs",
"(",
"self",
")",
":",
"ret",
"=",
"utils",
".",
"DefaultOrderedDict",
"(",
"lambda",
":",
"self",
"[",
"1",
":",
"0",
"]",
")",
"for",
"arr",
"in",
"self",
":",
"if",
"arr",
".",
"psy",
".",
"plotter",
"is",
"not",
"None",
":",
... | A mapping from figures to data objects with the plotter in this
figure | [
"A",
"mapping",
"from",
"figures",
"to",
"data",
"objects",
"with",
"the",
"plotter",
"in",
"this",
"figure"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/project.py#L222-L229 | train | 43,486 |
Chilipp/psyplot | psyplot/project.py | Project.axes | def axes(self):
"""A mapping from axes to data objects with the plotter in this axes
"""
ret = utils.DefaultOrderedDict(lambda: self[1:0])
for arr in self:
if arr.psy.plotter is not None:
ret[arr.psy.plotter.ax].append(arr)
return OrderedDict(ret) | python | def axes(self):
"""A mapping from axes to data objects with the plotter in this axes
"""
ret = utils.DefaultOrderedDict(lambda: self[1:0])
for arr in self:
if arr.psy.plotter is not None:
ret[arr.psy.plotter.ax].append(arr)
return OrderedDict(ret) | [
"def",
"axes",
"(",
"self",
")",
":",
"ret",
"=",
"utils",
".",
"DefaultOrderedDict",
"(",
"lambda",
":",
"self",
"[",
"1",
":",
"0",
"]",
")",
"for",
"arr",
"in",
"self",
":",
"if",
"arr",
".",
"psy",
".",
"plotter",
"is",
"not",
"None",
":",
... | A mapping from axes to data objects with the plotter in this axes | [
"A",
"mapping",
"from",
"axes",
"to",
"data",
"objects",
"with",
"the",
"plotter",
"in",
"this",
"axes"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/project.py#L232-L239 | train | 43,487 |
Chilipp/psyplot | psyplot/project.py | Project.datasets | def datasets(self):
"""A mapping from dataset numbers to datasets in this list"""
return {key: val['ds'] for key, val in six.iteritems(
self._get_ds_descriptions(self.array_info(ds_description=['ds'])))} | python | def datasets(self):
"""A mapping from dataset numbers to datasets in this list"""
return {key: val['ds'] for key, val in six.iteritems(
self._get_ds_descriptions(self.array_info(ds_description=['ds'])))} | [
"def",
"datasets",
"(",
"self",
")",
":",
"return",
"{",
"key",
":",
"val",
"[",
"'ds'",
"]",
"for",
"key",
",",
"val",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"_get_ds_descriptions",
"(",
"self",
".",
"array_info",
"(",
"ds_description",
"=",... | A mapping from dataset numbers to datasets in this list | [
"A",
"mapping",
"from",
"dataset",
"numbers",
"to",
"datasets",
"in",
"this",
"list"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/project.py#L305-L308 | train | 43,488 |
Chilipp/psyplot | psyplot/project.py | Project.disable | def disable(self):
"""Disables the plotters in this list"""
for arr in self:
if arr.psy.plotter:
arr.psy.plotter.disabled = True | python | def disable(self):
"""Disables the plotters in this list"""
for arr in self:
if arr.psy.plotter:
arr.psy.plotter.disabled = True | [
"def",
"disable",
"(",
"self",
")",
":",
"for",
"arr",
"in",
"self",
":",
"if",
"arr",
".",
"psy",
".",
"plotter",
":",
"arr",
".",
"psy",
".",
"plotter",
".",
"disabled",
"=",
"True"
] | Disables the plotters in this list | [
"Disables",
"the",
"plotters",
"in",
"this",
"list"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/project.py#L375-L379 | train | 43,489 |
Chilipp/psyplot | psyplot/project.py | Project.close | def close(self, figs=True, data=False, ds=False, remove_only=False):
"""
Close this project instance
Parameters
----------
figs: bool
Close the figures
data: bool
delete the arrays from the (main) project
ds: bool
If True, close the dataset as well
remove_only: bool
If True and `figs` is True, the figures are not closed but the
plotters are removed"""
import matplotlib.pyplot as plt
close_ds = ds
for arr in self[:]:
if figs and arr.psy.plotter is not None:
if remove_only:
for fmto in arr.psy.plotter._fmtos:
try:
fmto.remove()
except Exception:
pass
else:
plt.close(arr.psy.plotter.ax.get_figure().number)
arr.psy.plotter = None
if data:
self.remove(arr)
if not self.is_main:
try:
self.main.remove(arr)
except ValueError: # arr not in list
pass
if close_ds:
if isinstance(arr, InteractiveList):
for ds in [val['ds'] for val in six.itervalues(
arr._get_ds_descriptions(
arr.array_info(ds_description=['ds'],
standardize_dims=False)))]:
ds.close()
else:
arr.psy.base.close()
if self.is_main and self is gcp(True) and data:
scp(None)
elif self.is_main and self.is_cmp:
self.oncpchange.emit(self)
elif self.main.is_cmp:
self.oncpchange.emit(self.main) | python | def close(self, figs=True, data=False, ds=False, remove_only=False):
"""
Close this project instance
Parameters
----------
figs: bool
Close the figures
data: bool
delete the arrays from the (main) project
ds: bool
If True, close the dataset as well
remove_only: bool
If True and `figs` is True, the figures are not closed but the
plotters are removed"""
import matplotlib.pyplot as plt
close_ds = ds
for arr in self[:]:
if figs and arr.psy.plotter is not None:
if remove_only:
for fmto in arr.psy.plotter._fmtos:
try:
fmto.remove()
except Exception:
pass
else:
plt.close(arr.psy.plotter.ax.get_figure().number)
arr.psy.plotter = None
if data:
self.remove(arr)
if not self.is_main:
try:
self.main.remove(arr)
except ValueError: # arr not in list
pass
if close_ds:
if isinstance(arr, InteractiveList):
for ds in [val['ds'] for val in six.itervalues(
arr._get_ds_descriptions(
arr.array_info(ds_description=['ds'],
standardize_dims=False)))]:
ds.close()
else:
arr.psy.base.close()
if self.is_main and self is gcp(True) and data:
scp(None)
elif self.is_main and self.is_cmp:
self.oncpchange.emit(self)
elif self.main.is_cmp:
self.oncpchange.emit(self.main) | [
"def",
"close",
"(",
"self",
",",
"figs",
"=",
"True",
",",
"data",
"=",
"False",
",",
"ds",
"=",
"False",
",",
"remove_only",
"=",
"False",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"close_ds",
"=",
"ds",
"for",
"arr",
"in",
"s... | Close this project instance
Parameters
----------
figs: bool
Close the figures
data: bool
delete the arrays from the (main) project
ds: bool
If True, close the dataset as well
remove_only: bool
If True and `figs` is True, the figures are not closed but the
plotters are removed | [
"Close",
"this",
"project",
"instance"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/project.py#L423-L472 | train | 43,490 |
Chilipp/psyplot | psyplot/project.py | Project._add_data | def _add_data(self, plotter_cls, filename_or_obj, fmt={}, make_plot=True,
draw=False, mf_mode=False, ax=None, engine=None, delete=True,
share=False, clear=False, enable_post=None,
concat_dim=_concat_dim_default, load=False,
*args, **kwargs):
"""
Extract data from a dataset and visualize it with the given plotter
Parameters
----------
plotter_cls: type
The subclass of :class:`psyplot.plotter.Plotter` to use for
visualization
filename_or_obj: filename, :class:`xarray.Dataset` or data store
The object (or file name) to open. If not a dataset, the
:func:`psyplot.data.open_dataset` will be used to open a dataset
fmt: dict
Formatoptions that shall be when initializing the plot (you can
however also specify them as extra keyword arguments)
make_plot: bool
If True, the data is plotted at the end. Otherwise you have to
call the :meth:`psyplot.plotter.Plotter.initialize_plot` method or
the :meth:`psyplot.plotter.Plotter.reinit` method by yourself
%(InteractiveBase.start_update.parameters.draw)s
mf_mode: bool
If True, the :func:`psyplot.open_mfdataset` method is used.
Otherwise we use the :func:`psyplot.open_dataset` method which can
open only one single dataset
ax: None, tuple (x, y[, z]) or (list of) matplotlib.axes.Axes
Specifies the subplots on which to plot the new data objects.
- If None, a new figure will be created for each created plotter
- If tuple (x, y[, z]), `x` specifies the number of rows, `y` the
number of columns and the optional third parameter `z` the
maximal number of subplots per figure.
- If :class:`matplotlib.axes.Axes` (or list of those, e.g. created
by the :func:`matplotlib.pyplot.subplots` function), the data
will be plotted on these subplots
%(open_dataset.parameters.engine)s
%(multiple_subplots.parameters.delete)s
share: bool, fmt key or list of fmt keys
Determines whether the first created plotter shares it's
formatoptions with the others. If True, all formatoptions are
shared. Strings or list of strings specify the keys to share.
clear: bool
If True, axes are cleared before making the plot. This is only
necessary if the `ax` keyword consists of subplots with projection
that differs from the one that is needed
enable_post: bool
If True, the :attr:`~psyplot.plotter.Plotter.post` formatoption is
enabled and post processing scripts are allowed. If ``None``, this
parameter is set to True if there is a value given for the `post`
formatoption in `fmt` or `kwargs`
%(xarray.open_mfdataset.parameters.concat_dim)s
This parameter only does have an effect if `mf_mode` is True.
load: bool
If True, load the complete dataset into memory before plotting.
This might be useful if the data of other variables in the dataset
has to be accessed multiple times, e.g. for unstructured grids.
%(ArrayList.from_dataset.parameters.no_base)s
Other Parameters
----------------
%(ArrayList.from_dataset.other_parameters.no_args_kwargs)s
``**kwargs``
Any other dimension or formatoption that shall be passed to `dims`
or `fmt` respectively.
Returns
-------
Project
The subproject that contains the new (visualized) data array"""
if not isinstance(filename_or_obj, xarray.Dataset):
if mf_mode:
filename_or_obj = open_mfdataset(filename_or_obj,
engine=engine,
concat_dim=concat_dim)
else:
filename_or_obj = open_dataset(filename_or_obj,
engine=engine)
if load:
old = filename_or_obj
filename_or_obj = filename_or_obj.load()
old.close()
fmt = dict(fmt)
possible_fmts = list(plotter_cls._get_formatoptions())
additional_fmt, kwargs = utils.sort_kwargs(
kwargs, possible_fmts)
fmt.update(additional_fmt)
if enable_post is None:
enable_post = bool(fmt.get('post'))
# create the subproject
sub_project = self.from_dataset(filename_or_obj, **kwargs)
sub_project.main = self
sub_project.no_auto_update = not (
not sub_project.no_auto_update or not self.no_auto_update)
# create the subplots
proj = plotter_cls._get_sample_projection()
if isinstance(ax, tuple):
axes = iter(multiple_subplots(
*ax, n=len(sub_project), subplot_kw={'projection': proj}))
elif ax is None or isinstance(ax, (mpl.axes.SubplotBase,
mpl.axes.Axes)):
axes = repeat(ax)
else:
axes = iter(ax)
clear = clear or (isinstance(ax, tuple) and proj is not None)
for arr in sub_project:
plotter_cls(arr, make_plot=(not bool(share) and make_plot),
draw=False, ax=next(axes), clear=clear,
project=self, enable_post=enable_post, **fmt)
if share:
if share is True:
share = possible_fmts
elif isinstance(share, six.string_types):
share = [share]
else:
share = list(share)
sub_project[0].psy.plotter.share(
[arr.psy.plotter for arr in sub_project[1:]], keys=share,
draw=False)
if make_plot:
for arr in sub_project:
arr.psy.plotter.reinit(draw=False, clear=clear)
if draw is None:
draw = rcParams['auto_draw']
if draw:
sub_project.draw()
if rcParams['auto_show']:
self.show()
self.extend(sub_project, new_name=True)
if self is gcp(True):
scp(sub_project)
return sub_project | python | def _add_data(self, plotter_cls, filename_or_obj, fmt={}, make_plot=True,
draw=False, mf_mode=False, ax=None, engine=None, delete=True,
share=False, clear=False, enable_post=None,
concat_dim=_concat_dim_default, load=False,
*args, **kwargs):
"""
Extract data from a dataset and visualize it with the given plotter
Parameters
----------
plotter_cls: type
The subclass of :class:`psyplot.plotter.Plotter` to use for
visualization
filename_or_obj: filename, :class:`xarray.Dataset` or data store
The object (or file name) to open. If not a dataset, the
:func:`psyplot.data.open_dataset` will be used to open a dataset
fmt: dict
Formatoptions that shall be when initializing the plot (you can
however also specify them as extra keyword arguments)
make_plot: bool
If True, the data is plotted at the end. Otherwise you have to
call the :meth:`psyplot.plotter.Plotter.initialize_plot` method or
the :meth:`psyplot.plotter.Plotter.reinit` method by yourself
%(InteractiveBase.start_update.parameters.draw)s
mf_mode: bool
If True, the :func:`psyplot.open_mfdataset` method is used.
Otherwise we use the :func:`psyplot.open_dataset` method which can
open only one single dataset
ax: None, tuple (x, y[, z]) or (list of) matplotlib.axes.Axes
Specifies the subplots on which to plot the new data objects.
- If None, a new figure will be created for each created plotter
- If tuple (x, y[, z]), `x` specifies the number of rows, `y` the
number of columns and the optional third parameter `z` the
maximal number of subplots per figure.
- If :class:`matplotlib.axes.Axes` (or list of those, e.g. created
by the :func:`matplotlib.pyplot.subplots` function), the data
will be plotted on these subplots
%(open_dataset.parameters.engine)s
%(multiple_subplots.parameters.delete)s
share: bool, fmt key or list of fmt keys
Determines whether the first created plotter shares it's
formatoptions with the others. If True, all formatoptions are
shared. Strings or list of strings specify the keys to share.
clear: bool
If True, axes are cleared before making the plot. This is only
necessary if the `ax` keyword consists of subplots with projection
that differs from the one that is needed
enable_post: bool
If True, the :attr:`~psyplot.plotter.Plotter.post` formatoption is
enabled and post processing scripts are allowed. If ``None``, this
parameter is set to True if there is a value given for the `post`
formatoption in `fmt` or `kwargs`
%(xarray.open_mfdataset.parameters.concat_dim)s
This parameter only does have an effect if `mf_mode` is True.
load: bool
If True, load the complete dataset into memory before plotting.
This might be useful if the data of other variables in the dataset
has to be accessed multiple times, e.g. for unstructured grids.
%(ArrayList.from_dataset.parameters.no_base)s
Other Parameters
----------------
%(ArrayList.from_dataset.other_parameters.no_args_kwargs)s
``**kwargs``
Any other dimension or formatoption that shall be passed to `dims`
or `fmt` respectively.
Returns
-------
Project
The subproject that contains the new (visualized) data array"""
if not isinstance(filename_or_obj, xarray.Dataset):
if mf_mode:
filename_or_obj = open_mfdataset(filename_or_obj,
engine=engine,
concat_dim=concat_dim)
else:
filename_or_obj = open_dataset(filename_or_obj,
engine=engine)
if load:
old = filename_or_obj
filename_or_obj = filename_or_obj.load()
old.close()
fmt = dict(fmt)
possible_fmts = list(plotter_cls._get_formatoptions())
additional_fmt, kwargs = utils.sort_kwargs(
kwargs, possible_fmts)
fmt.update(additional_fmt)
if enable_post is None:
enable_post = bool(fmt.get('post'))
# create the subproject
sub_project = self.from_dataset(filename_or_obj, **kwargs)
sub_project.main = self
sub_project.no_auto_update = not (
not sub_project.no_auto_update or not self.no_auto_update)
# create the subplots
proj = plotter_cls._get_sample_projection()
if isinstance(ax, tuple):
axes = iter(multiple_subplots(
*ax, n=len(sub_project), subplot_kw={'projection': proj}))
elif ax is None or isinstance(ax, (mpl.axes.SubplotBase,
mpl.axes.Axes)):
axes = repeat(ax)
else:
axes = iter(ax)
clear = clear or (isinstance(ax, tuple) and proj is not None)
for arr in sub_project:
plotter_cls(arr, make_plot=(not bool(share) and make_plot),
draw=False, ax=next(axes), clear=clear,
project=self, enable_post=enable_post, **fmt)
if share:
if share is True:
share = possible_fmts
elif isinstance(share, six.string_types):
share = [share]
else:
share = list(share)
sub_project[0].psy.plotter.share(
[arr.psy.plotter for arr in sub_project[1:]], keys=share,
draw=False)
if make_plot:
for arr in sub_project:
arr.psy.plotter.reinit(draw=False, clear=clear)
if draw is None:
draw = rcParams['auto_draw']
if draw:
sub_project.draw()
if rcParams['auto_show']:
self.show()
self.extend(sub_project, new_name=True)
if self is gcp(True):
scp(sub_project)
return sub_project | [
"def",
"_add_data",
"(",
"self",
",",
"plotter_cls",
",",
"filename_or_obj",
",",
"fmt",
"=",
"{",
"}",
",",
"make_plot",
"=",
"True",
",",
"draw",
"=",
"False",
",",
"mf_mode",
"=",
"False",
",",
"ax",
"=",
"None",
",",
"engine",
"=",
"None",
",",
... | Extract data from a dataset and visualize it with the given plotter
Parameters
----------
plotter_cls: type
The subclass of :class:`psyplot.plotter.Plotter` to use for
visualization
filename_or_obj: filename, :class:`xarray.Dataset` or data store
The object (or file name) to open. If not a dataset, the
:func:`psyplot.data.open_dataset` will be used to open a dataset
fmt: dict
Formatoptions that shall be when initializing the plot (you can
however also specify them as extra keyword arguments)
make_plot: bool
If True, the data is plotted at the end. Otherwise you have to
call the :meth:`psyplot.plotter.Plotter.initialize_plot` method or
the :meth:`psyplot.plotter.Plotter.reinit` method by yourself
%(InteractiveBase.start_update.parameters.draw)s
mf_mode: bool
If True, the :func:`psyplot.open_mfdataset` method is used.
Otherwise we use the :func:`psyplot.open_dataset` method which can
open only one single dataset
ax: None, tuple (x, y[, z]) or (list of) matplotlib.axes.Axes
Specifies the subplots on which to plot the new data objects.
- If None, a new figure will be created for each created plotter
- If tuple (x, y[, z]), `x` specifies the number of rows, `y` the
number of columns and the optional third parameter `z` the
maximal number of subplots per figure.
- If :class:`matplotlib.axes.Axes` (or list of those, e.g. created
by the :func:`matplotlib.pyplot.subplots` function), the data
will be plotted on these subplots
%(open_dataset.parameters.engine)s
%(multiple_subplots.parameters.delete)s
share: bool, fmt key or list of fmt keys
Determines whether the first created plotter shares it's
formatoptions with the others. If True, all formatoptions are
shared. Strings or list of strings specify the keys to share.
clear: bool
If True, axes are cleared before making the plot. This is only
necessary if the `ax` keyword consists of subplots with projection
that differs from the one that is needed
enable_post: bool
If True, the :attr:`~psyplot.plotter.Plotter.post` formatoption is
enabled and post processing scripts are allowed. If ``None``, this
parameter is set to True if there is a value given for the `post`
formatoption in `fmt` or `kwargs`
%(xarray.open_mfdataset.parameters.concat_dim)s
This parameter only does have an effect if `mf_mode` is True.
load: bool
If True, load the complete dataset into memory before plotting.
This might be useful if the data of other variables in the dataset
has to be accessed multiple times, e.g. for unstructured grids.
%(ArrayList.from_dataset.parameters.no_base)s
Other Parameters
----------------
%(ArrayList.from_dataset.other_parameters.no_args_kwargs)s
``**kwargs``
Any other dimension or formatoption that shall be passed to `dims`
or `fmt` respectively.
Returns
-------
Project
The subproject that contains the new (visualized) data array | [
"Extract",
"data",
"from",
"a",
"dataset",
"and",
"visualize",
"it",
"with",
"the",
"given",
"plotter"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/project.py#L485-L619 | train | 43,491 |
Chilipp/psyplot | psyplot/project.py | Project.joined_attrs | def joined_attrs(self, delimiter=', ', enhanced=True, plot_data=False,
keep_all=True):
"""Join the attributes of the arrays in this project
Parameters
----------
%(join_dicts.parameters.delimiter)s
enhanced: bool
If True, the :meth:`psyplot.plotter.Plotter.get_enhanced_attrs`
method is used, otherwise the :attr:`xarray.DataArray.attrs`
attribute is used.
plot_data: bool
It True, use the :attr:`psyplot.plotter.Plotter.plot_data`
attribute of the plotters rather than the raw data in this project
%(join_dicts.parameters.keep_all)s
Returns
-------
dict
A mapping from the attribute to the joined attributes which are
either strings or (if there is only one attribute value), the
data type of the corresponding value"""
if enhanced:
all_attrs = [
plotter.get_enhanced_attrs(
getattr(plotter, 'plot_data' if plot_data else 'data'))
for plotter in self.plotters]
else:
if plot_data:
all_attrs = [plotter.plot_data.attrs
for plotter in self.plotters]
else:
all_attrs = [arr.attrs for arr in self]
return utils.join_dicts(all_attrs, delimiter=delimiter,
keep_all=keep_all) | python | def joined_attrs(self, delimiter=', ', enhanced=True, plot_data=False,
keep_all=True):
"""Join the attributes of the arrays in this project
Parameters
----------
%(join_dicts.parameters.delimiter)s
enhanced: bool
If True, the :meth:`psyplot.plotter.Plotter.get_enhanced_attrs`
method is used, otherwise the :attr:`xarray.DataArray.attrs`
attribute is used.
plot_data: bool
It True, use the :attr:`psyplot.plotter.Plotter.plot_data`
attribute of the plotters rather than the raw data in this project
%(join_dicts.parameters.keep_all)s
Returns
-------
dict
A mapping from the attribute to the joined attributes which are
either strings or (if there is only one attribute value), the
data type of the corresponding value"""
if enhanced:
all_attrs = [
plotter.get_enhanced_attrs(
getattr(plotter, 'plot_data' if plot_data else 'data'))
for plotter in self.plotters]
else:
if plot_data:
all_attrs = [plotter.plot_data.attrs
for plotter in self.plotters]
else:
all_attrs = [arr.attrs for arr in self]
return utils.join_dicts(all_attrs, delimiter=delimiter,
keep_all=keep_all) | [
"def",
"joined_attrs",
"(",
"self",
",",
"delimiter",
"=",
"', '",
",",
"enhanced",
"=",
"True",
",",
"plot_data",
"=",
"False",
",",
"keep_all",
"=",
"True",
")",
":",
"if",
"enhanced",
":",
"all_attrs",
"=",
"[",
"plotter",
".",
"get_enhanced_attrs",
"... | Join the attributes of the arrays in this project
Parameters
----------
%(join_dicts.parameters.delimiter)s
enhanced: bool
If True, the :meth:`psyplot.plotter.Plotter.get_enhanced_attrs`
method is used, otherwise the :attr:`xarray.DataArray.attrs`
attribute is used.
plot_data: bool
It True, use the :attr:`psyplot.plotter.Plotter.plot_data`
attribute of the plotters rather than the raw data in this project
%(join_dicts.parameters.keep_all)s
Returns
-------
dict
A mapping from the attribute to the joined attributes which are
either strings or (if there is only one attribute value), the
data type of the corresponding value | [
"Join",
"the",
"attributes",
"of",
"the",
"arrays",
"in",
"this",
"project"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/project.py#L652-L686 | train | 43,492 |
Chilipp/psyplot | psyplot/project.py | Project.export | def export(self, output, tight=False, concat=True, close_pdf=None,
use_time=False, **kwargs):
"""Exports the figures of the project to one or more image files
Parameters
----------
output: str, iterable or matplotlib.backends.backend_pdf.PdfPages
if string or list of strings, those define the names of the output
files. Otherwise you may provide an instance of
:class:`matplotlib.backends.backend_pdf.PdfPages` to save the
figures in it.
If string (or iterable of strings), attribute names in the
xarray.DataArray.attrs attribute as well as index dimensions
are replaced by the respective value (see examples below).
Furthermore a single format string without key (e.g. %i, %s, %d,
etc.) is replaced by a counter.
tight: bool
If True, it is tried to figure out the tight bbox of the figure
(same as bbox_inches='tight')
concat: bool
if True and the output format is `pdf`, all figures are
concatenated into one single pdf
close_pdf: bool or None
If True and the figures are concatenated into one single pdf,
the resulting pdf instance is closed. If False it remains open.
If None and `output` is a string, it is the same as
``close_pdf=True``, if None and `output` is neither a string nor an
iterable, it is the same as ``close_pdf=False``
use_time: bool
If True, formatting strings for the
:meth:`datetime.datetime.strftime` are expected to be found in
`output` (e.g. ``'%m'``, ``'%Y'``, etc.). If so, other formatting
strings must be escaped by double ``'%'`` (e.g. ``'%%i'`` instead
of (``'%i'``))
``**kwargs``
Any valid keyword for the :func:`matplotlib.pyplot.savefig`
function
Returns
-------
matplotlib.backends.backend_pdf.PdfPages or None
a PdfPages instance if output is a string and close_pdf is False,
otherwise None
Examples
--------
Simply save all figures into one single pdf::
>>> p = psy.gcp()
>>> p.export('my_plots.pdf')
Save all figures into separate pngs with increasing numbers (e.g.
``'my_plots_1.png'``)::
>>> p.export('my_plots_%i.png')
Save all figures into separate pngs with the name of the variables
shown in each figure (e.g. ``'my_plots_t2m.png'``)::
>>> p.export('my_plots_%(name)s.png')
Save all figures into separate pngs with the name of the variables
shown in each figure and with increasing numbers (e.g.
``'my_plots_1_t2m.png'``)::
>>> p.export('my_plots_%i_%(name)s.png')
Specify the names for each figure directly via a list::
>>> p.export(['my_plots1.pdf', 'my_plots2.pdf'])
"""
from matplotlib.backends.backend_pdf import PdfPages
if tight:
kwargs['bbox_inches'] = 'tight'
if use_time:
def insert_time(s, attrs):
time = attrs[tname]
try: # assume a valid datetime.datetime instance
s = pd.to_datetime(time).strftime(s)
except ValueError:
pass
return s
tnames = self._get_tnames()
tname = next(iter(tnames)) if len(tnames) == 1 else None
else:
def insert_time(s, attrs):
return s
tname = None
if isinstance(output, six.string_types): # a single string
out_fmt = kwargs.pop('format', os.path.splitext(output))[1][1:]
if out_fmt.lower() == 'pdf' and concat:
attrs = self.joined_attrs('-')
if tname is not None and tname in attrs:
output = insert_time(output, attrs)
pdf = PdfPages(safe_modulo(output, attrs))
def save(fig):
pdf.savefig(fig, **kwargs)
def close():
if close_pdf is None or close_pdf:
pdf.close()
return
return pdf
else:
def save(fig):
attrs = self.figs[fig].joined_attrs('-')
out = output
if tname is not None and tname in attrs:
out = insert_time(out, attrs)
try:
out = safe_modulo(out, i, print_warning=False)
except TypeError:
pass
fig.savefig(safe_modulo(out, attrs), **kwargs)
def close():
pass
elif isinstance(output, Iterable): # a list of strings
output = cycle(output)
def save(fig):
attrs = self.figs[fig].joined_attrs('-')
out = next(output)
if tname is not None and tname in attrs:
out = insert_time(out, attrs)
try:
out = safe_modulo(next(output), i, print_warning=False)
except TypeError:
pass
fig.savefig(safe_modulo(out, attrs), **kwargs)
def close():
pass
else: # an instances of matplotlib.backends.backend_pdf.PdfPages
def save(fig):
output.savefig(fig, **kwargs)
def close():
if close_pdf:
output.close()
for i, fig in enumerate(self.figs, 1):
save(fig)
return close() | python | def export(self, output, tight=False, concat=True, close_pdf=None,
use_time=False, **kwargs):
"""Exports the figures of the project to one or more image files
Parameters
----------
output: str, iterable or matplotlib.backends.backend_pdf.PdfPages
if string or list of strings, those define the names of the output
files. Otherwise you may provide an instance of
:class:`matplotlib.backends.backend_pdf.PdfPages` to save the
figures in it.
If string (or iterable of strings), attribute names in the
xarray.DataArray.attrs attribute as well as index dimensions
are replaced by the respective value (see examples below).
Furthermore a single format string without key (e.g. %i, %s, %d,
etc.) is replaced by a counter.
tight: bool
If True, it is tried to figure out the tight bbox of the figure
(same as bbox_inches='tight')
concat: bool
if True and the output format is `pdf`, all figures are
concatenated into one single pdf
close_pdf: bool or None
If True and the figures are concatenated into one single pdf,
the resulting pdf instance is closed. If False it remains open.
If None and `output` is a string, it is the same as
``close_pdf=True``, if None and `output` is neither a string nor an
iterable, it is the same as ``close_pdf=False``
use_time: bool
If True, formatting strings for the
:meth:`datetime.datetime.strftime` are expected to be found in
`output` (e.g. ``'%m'``, ``'%Y'``, etc.). If so, other formatting
strings must be escaped by double ``'%'`` (e.g. ``'%%i'`` instead
of (``'%i'``))
``**kwargs``
Any valid keyword for the :func:`matplotlib.pyplot.savefig`
function
Returns
-------
matplotlib.backends.backend_pdf.PdfPages or None
a PdfPages instance if output is a string and close_pdf is False,
otherwise None
Examples
--------
Simply save all figures into one single pdf::
>>> p = psy.gcp()
>>> p.export('my_plots.pdf')
Save all figures into separate pngs with increasing numbers (e.g.
``'my_plots_1.png'``)::
>>> p.export('my_plots_%i.png')
Save all figures into separate pngs with the name of the variables
shown in each figure (e.g. ``'my_plots_t2m.png'``)::
>>> p.export('my_plots_%(name)s.png')
Save all figures into separate pngs with the name of the variables
shown in each figure and with increasing numbers (e.g.
``'my_plots_1_t2m.png'``)::
>>> p.export('my_plots_%i_%(name)s.png')
Specify the names for each figure directly via a list::
>>> p.export(['my_plots1.pdf', 'my_plots2.pdf'])
"""
from matplotlib.backends.backend_pdf import PdfPages
if tight:
kwargs['bbox_inches'] = 'tight'
if use_time:
def insert_time(s, attrs):
time = attrs[tname]
try: # assume a valid datetime.datetime instance
s = pd.to_datetime(time).strftime(s)
except ValueError:
pass
return s
tnames = self._get_tnames()
tname = next(iter(tnames)) if len(tnames) == 1 else None
else:
def insert_time(s, attrs):
return s
tname = None
if isinstance(output, six.string_types): # a single string
out_fmt = kwargs.pop('format', os.path.splitext(output))[1][1:]
if out_fmt.lower() == 'pdf' and concat:
attrs = self.joined_attrs('-')
if tname is not None and tname in attrs:
output = insert_time(output, attrs)
pdf = PdfPages(safe_modulo(output, attrs))
def save(fig):
pdf.savefig(fig, **kwargs)
def close():
if close_pdf is None or close_pdf:
pdf.close()
return
return pdf
else:
def save(fig):
attrs = self.figs[fig].joined_attrs('-')
out = output
if tname is not None and tname in attrs:
out = insert_time(out, attrs)
try:
out = safe_modulo(out, i, print_warning=False)
except TypeError:
pass
fig.savefig(safe_modulo(out, attrs), **kwargs)
def close():
pass
elif isinstance(output, Iterable): # a list of strings
output = cycle(output)
def save(fig):
attrs = self.figs[fig].joined_attrs('-')
out = next(output)
if tname is not None and tname in attrs:
out = insert_time(out, attrs)
try:
out = safe_modulo(next(output), i, print_warning=False)
except TypeError:
pass
fig.savefig(safe_modulo(out, attrs), **kwargs)
def close():
pass
else: # an instances of matplotlib.backends.backend_pdf.PdfPages
def save(fig):
output.savefig(fig, **kwargs)
def close():
if close_pdf:
output.close()
for i, fig in enumerate(self.figs, 1):
save(fig)
return close() | [
"def",
"export",
"(",
"self",
",",
"output",
",",
"tight",
"=",
"False",
",",
"concat",
"=",
"True",
",",
"close_pdf",
"=",
"None",
",",
"use_time",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"matplotlib",
".",
"backends",
".",
"backend... | Exports the figures of the project to one or more image files
Parameters
----------
output: str, iterable or matplotlib.backends.backend_pdf.PdfPages
if string or list of strings, those define the names of the output
files. Otherwise you may provide an instance of
:class:`matplotlib.backends.backend_pdf.PdfPages` to save the
figures in it.
If string (or iterable of strings), attribute names in the
xarray.DataArray.attrs attribute as well as index dimensions
are replaced by the respective value (see examples below).
Furthermore a single format string without key (e.g. %i, %s, %d,
etc.) is replaced by a counter.
tight: bool
If True, it is tried to figure out the tight bbox of the figure
(same as bbox_inches='tight')
concat: bool
if True and the output format is `pdf`, all figures are
concatenated into one single pdf
close_pdf: bool or None
If True and the figures are concatenated into one single pdf,
the resulting pdf instance is closed. If False it remains open.
If None and `output` is a string, it is the same as
``close_pdf=True``, if None and `output` is neither a string nor an
iterable, it is the same as ``close_pdf=False``
use_time: bool
If True, formatting strings for the
:meth:`datetime.datetime.strftime` are expected to be found in
`output` (e.g. ``'%m'``, ``'%Y'``, etc.). If so, other formatting
strings must be escaped by double ``'%'`` (e.g. ``'%%i'`` instead
of (``'%i'``))
``**kwargs``
Any valid keyword for the :func:`matplotlib.pyplot.savefig`
function
Returns
-------
matplotlib.backends.backend_pdf.PdfPages or None
a PdfPages instance if output is a string and close_pdf is False,
otherwise None
Examples
--------
Simply save all figures into one single pdf::
>>> p = psy.gcp()
>>> p.export('my_plots.pdf')
Save all figures into separate pngs with increasing numbers (e.g.
``'my_plots_1.png'``)::
>>> p.export('my_plots_%i.png')
Save all figures into separate pngs with the name of the variables
shown in each figure (e.g. ``'my_plots_t2m.png'``)::
>>> p.export('my_plots_%(name)s.png')
Save all figures into separate pngs with the name of the variables
shown in each figure and with increasing numbers (e.g.
``'my_plots_1_t2m.png'``)::
>>> p.export('my_plots_%i_%(name)s.png')
Specify the names for each figure directly via a list::
>>> p.export(['my_plots1.pdf', 'my_plots2.pdf']) | [
"Exports",
"the",
"figures",
"of",
"the",
"project",
"to",
"one",
"or",
"more",
"image",
"files"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/project.py#L688-L835 | train | 43,493 |
Chilipp/psyplot | psyplot/project.py | Project.share | def share(self, base=None, keys=None, by=None, **kwargs):
"""
Share the formatoptions of one plotter with all the others
This method shares specified formatoptions from `base` with all the
plotters in this instance.
Parameters
----------
base: None, Plotter, xarray.DataArray, InteractiveList, or list of them
The source of the plotter that shares its formatoptions with the
others. It can be None (then the first instance in this project
is used), a :class:`~psyplot.plotter.Plotter` or any data object
with a *psy* attribute. If `by` is not None, then it is expected
that `base` is a list of data objects for each figure/axes
%(Plotter.share.parameters.keys)s
by: {'fig', 'figure', 'ax', 'axes'}
Share the formatoptions only with the others on the same
``'figure'`` or the same ``'axes'``. In this case, base must either
be ``None`` or a list of the types specified for `base`
%(Plotter.share.parameters.no_keys|plotters)s
See Also
--------
psyplot.plotter.share"""
if by is not None:
if base is not None:
if hasattr(base, 'psy') or isinstance(base, Plotter):
base = [base]
if by.lower() in ['ax', 'axes']:
bases = {ax: p[0] for ax, p in six.iteritems(
Project(base).axes)}
elif by.lower() in ['fig', 'figure']:
bases = {fig: p[0] for fig, p in six.iteritems(
Project(base).figs)}
else:
raise ValueError(
"*by* must be out of {'fig', 'figure', 'ax', 'axes'}. "
"Not %s" % (by, ))
else:
bases = {}
projects = self.axes if by == 'axes' else self.figs
for obj, p in projects.items():
p.share(bases.get(obj), keys, **kwargs)
else:
plotters = self.plotters
if not plotters:
return
if base is None:
if len(plotters) == 1:
return
base = plotters[0]
plotters = plotters[1:]
elif not isinstance(base, Plotter):
base = getattr(getattr(base, 'psy', base), 'plotter', base)
base.share(plotters, keys=keys, **kwargs) | python | def share(self, base=None, keys=None, by=None, **kwargs):
"""
Share the formatoptions of one plotter with all the others
This method shares specified formatoptions from `base` with all the
plotters in this instance.
Parameters
----------
base: None, Plotter, xarray.DataArray, InteractiveList, or list of them
The source of the plotter that shares its formatoptions with the
others. It can be None (then the first instance in this project
is used), a :class:`~psyplot.plotter.Plotter` or any data object
with a *psy* attribute. If `by` is not None, then it is expected
that `base` is a list of data objects for each figure/axes
%(Plotter.share.parameters.keys)s
by: {'fig', 'figure', 'ax', 'axes'}
Share the formatoptions only with the others on the same
``'figure'`` or the same ``'axes'``. In this case, base must either
be ``None`` or a list of the types specified for `base`
%(Plotter.share.parameters.no_keys|plotters)s
See Also
--------
psyplot.plotter.share"""
if by is not None:
if base is not None:
if hasattr(base, 'psy') or isinstance(base, Plotter):
base = [base]
if by.lower() in ['ax', 'axes']:
bases = {ax: p[0] for ax, p in six.iteritems(
Project(base).axes)}
elif by.lower() in ['fig', 'figure']:
bases = {fig: p[0] for fig, p in six.iteritems(
Project(base).figs)}
else:
raise ValueError(
"*by* must be out of {'fig', 'figure', 'ax', 'axes'}. "
"Not %s" % (by, ))
else:
bases = {}
projects = self.axes if by == 'axes' else self.figs
for obj, p in projects.items():
p.share(bases.get(obj), keys, **kwargs)
else:
plotters = self.plotters
if not plotters:
return
if base is None:
if len(plotters) == 1:
return
base = plotters[0]
plotters = plotters[1:]
elif not isinstance(base, Plotter):
base = getattr(getattr(base, 'psy', base), 'plotter', base)
base.share(plotters, keys=keys, **kwargs) | [
"def",
"share",
"(",
"self",
",",
"base",
"=",
"None",
",",
"keys",
"=",
"None",
",",
"by",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"by",
"is",
"not",
"None",
":",
"if",
"base",
"is",
"not",
"None",
":",
"if",
"hasattr",
"(",
"b... | Share the formatoptions of one plotter with all the others
This method shares specified formatoptions from `base` with all the
plotters in this instance.
Parameters
----------
base: None, Plotter, xarray.DataArray, InteractiveList, or list of them
The source of the plotter that shares its formatoptions with the
others. It can be None (then the first instance in this project
is used), a :class:`~psyplot.plotter.Plotter` or any data object
with a *psy* attribute. If `by` is not None, then it is expected
that `base` is a list of data objects for each figure/axes
%(Plotter.share.parameters.keys)s
by: {'fig', 'figure', 'ax', 'axes'}
Share the formatoptions only with the others on the same
``'figure'`` or the same ``'axes'``. In this case, base must either
be ``None`` or a list of the types specified for `base`
%(Plotter.share.parameters.no_keys|plotters)s
See Also
--------
psyplot.plotter.share | [
"Share",
"the",
"formatoptions",
"of",
"one",
"plotter",
"with",
"all",
"the",
"others"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/project.py#L841-L896 | train | 43,494 |
Chilipp/psyplot | psyplot/project.py | Project.keys | def keys(self, *args, **kwargs):
"""
Show the available formatoptions in this project
Parameters
----------
%(Plotter.show_keys.parameters)s
Other Parameters
----------------
%(Plotter.show_keys.other_parameters)s
Returns
-------
%(Plotter.show_keys.returns)s"""
class TmpClass(Plotter):
pass
for fmto in self._fmtos:
setattr(TmpClass, fmto.key, type(fmto)(fmto.key))
return TmpClass.show_keys(*args, **kwargs) | python | def keys(self, *args, **kwargs):
"""
Show the available formatoptions in this project
Parameters
----------
%(Plotter.show_keys.parameters)s
Other Parameters
----------------
%(Plotter.show_keys.other_parameters)s
Returns
-------
%(Plotter.show_keys.returns)s"""
class TmpClass(Plotter):
pass
for fmto in self._fmtos:
setattr(TmpClass, fmto.key, type(fmto)(fmto.key))
return TmpClass.show_keys(*args, **kwargs) | [
"def",
"keys",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"class",
"TmpClass",
"(",
"Plotter",
")",
":",
"pass",
"for",
"fmto",
"in",
"self",
".",
"_fmtos",
":",
"setattr",
"(",
"TmpClass",
",",
"fmto",
".",
"key",
",",
"ty... | Show the available formatoptions in this project
Parameters
----------
%(Plotter.show_keys.parameters)s
Other Parameters
----------------
%(Plotter.show_keys.other_parameters)s
Returns
-------
%(Plotter.show_keys.returns)s | [
"Show",
"the",
"available",
"formatoptions",
"in",
"this",
"project"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/project.py#L1033-L1053 | train | 43,495 |
Chilipp/psyplot | psyplot/project.py | Project.summaries | def summaries(self, *args, **kwargs):
"""
Show the available formatoptions and their summaries in this project
Parameters
----------
%(Plotter.show_keys.parameters)s
Other Parameters
----------------
%(Plotter.show_keys.other_parameters)s
Returns
-------
%(Plotter.show_keys.returns)s"""
class TmpClass(Plotter):
pass
for fmto in self._fmtos:
setattr(TmpClass, fmto.key, type(fmto)(fmto.key))
return TmpClass.show_summaries(*args, **kwargs) | python | def summaries(self, *args, **kwargs):
"""
Show the available formatoptions and their summaries in this project
Parameters
----------
%(Plotter.show_keys.parameters)s
Other Parameters
----------------
%(Plotter.show_keys.other_parameters)s
Returns
-------
%(Plotter.show_keys.returns)s"""
class TmpClass(Plotter):
pass
for fmto in self._fmtos:
setattr(TmpClass, fmto.key, type(fmto)(fmto.key))
return TmpClass.show_summaries(*args, **kwargs) | [
"def",
"summaries",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"class",
"TmpClass",
"(",
"Plotter",
")",
":",
"pass",
"for",
"fmto",
"in",
"self",
".",
"_fmtos",
":",
"setattr",
"(",
"TmpClass",
",",
"fmto",
".",
"key",
",",
... | Show the available formatoptions and their summaries in this project
Parameters
----------
%(Plotter.show_keys.parameters)s
Other Parameters
----------------
%(Plotter.show_keys.other_parameters)s
Returns
-------
%(Plotter.show_keys.returns)s | [
"Show",
"the",
"available",
"formatoptions",
"and",
"their",
"summaries",
"in",
"this",
"project"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/project.py#L1056-L1076 | train | 43,496 |
Chilipp/psyplot | psyplot/project.py | Project.docs | def docs(self, *args, **kwargs):
"""
Show the available formatoptions in this project and their full docu
Parameters
----------
%(Plotter.show_keys.parameters)s
Other Parameters
----------------
%(Plotter.show_keys.other_parameters)s
Returns
-------
%(Plotter.show_keys.returns)s"""
class TmpClass(Plotter):
pass
for fmto in self._fmtos:
setattr(TmpClass, fmto.key, type(fmto)(fmto.key))
return TmpClass.show_docs(*args, **kwargs) | python | def docs(self, *args, **kwargs):
"""
Show the available formatoptions in this project and their full docu
Parameters
----------
%(Plotter.show_keys.parameters)s
Other Parameters
----------------
%(Plotter.show_keys.other_parameters)s
Returns
-------
%(Plotter.show_keys.returns)s"""
class TmpClass(Plotter):
pass
for fmto in self._fmtos:
setattr(TmpClass, fmto.key, type(fmto)(fmto.key))
return TmpClass.show_docs(*args, **kwargs) | [
"def",
"docs",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"class",
"TmpClass",
"(",
"Plotter",
")",
":",
"pass",
"for",
"fmto",
"in",
"self",
".",
"_fmtos",
":",
"setattr",
"(",
"TmpClass",
",",
"fmto",
".",
"key",
",",
"ty... | Show the available formatoptions in this project and their full docu
Parameters
----------
%(Plotter.show_keys.parameters)s
Other Parameters
----------------
%(Plotter.show_keys.other_parameters)s
Returns
-------
%(Plotter.show_keys.returns)s | [
"Show",
"the",
"available",
"formatoptions",
"in",
"this",
"project",
"and",
"their",
"full",
"docu"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/project.py#L1079-L1099 | train | 43,497 |
Chilipp/psyplot | psyplot/project.py | Project.scp | def scp(cls, project):
"""
Set the current project
Parameters
----------
project: Project or None
The project to set. If it is None, the current subproject is set
to empty. If it is a sub project (see:attr:`Project.is_main`),
the current subproject is set to this project. Otherwise it
replaces the current main project
See Also
--------
scp: The global version for setting the current project
gcp: Returns the current project
project: Creates a new project"""
if project is None:
_scp(None)
cls.oncpchange.emit(gcp())
elif not project.is_main:
if project.main is not _current_project:
_scp(project.main, True)
cls.oncpchange.emit(project.main)
_scp(project)
cls.oncpchange.emit(project)
else:
_scp(project, True)
cls.oncpchange.emit(project)
sp = project[:]
_scp(sp)
cls.oncpchange.emit(sp) | python | def scp(cls, project):
"""
Set the current project
Parameters
----------
project: Project or None
The project to set. If it is None, the current subproject is set
to empty. If it is a sub project (see:attr:`Project.is_main`),
the current subproject is set to this project. Otherwise it
replaces the current main project
See Also
--------
scp: The global version for setting the current project
gcp: Returns the current project
project: Creates a new project"""
if project is None:
_scp(None)
cls.oncpchange.emit(gcp())
elif not project.is_main:
if project.main is not _current_project:
_scp(project.main, True)
cls.oncpchange.emit(project.main)
_scp(project)
cls.oncpchange.emit(project)
else:
_scp(project, True)
cls.oncpchange.emit(project)
sp = project[:]
_scp(sp)
cls.oncpchange.emit(sp) | [
"def",
"scp",
"(",
"cls",
",",
"project",
")",
":",
"if",
"project",
"is",
"None",
":",
"_scp",
"(",
"None",
")",
"cls",
".",
"oncpchange",
".",
"emit",
"(",
"gcp",
"(",
")",
")",
"elif",
"not",
"project",
".",
"is_main",
":",
"if",
"project",
".... | Set the current project
Parameters
----------
project: Project or None
The project to set. If it is None, the current subproject is set
to empty. If it is a sub project (see:attr:`Project.is_main`),
the current subproject is set to this project. Otherwise it
replaces the current main project
See Also
--------
scp: The global version for setting the current project
gcp: Returns the current project
project: Creates a new project | [
"Set",
"the",
"current",
"project"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/project.py#L1327-L1358 | train | 43,498 |
Chilipp/psyplot | psyplot/project.py | _ProjectLoader.inspect_axes | def inspect_axes(ax):
"""Inspect an axes or subplot to get the initialization parameters"""
ret = {'fig': ax.get_figure().number}
if mpl.__version__ < '2.0':
ret['axisbg'] = ax.get_axis_bgcolor()
else: # axisbg is depreceated
ret['facecolor'] = ax.get_facecolor()
proj = getattr(ax, 'projection', None)
if proj is not None and not isinstance(proj, six.string_types):
proj = (proj.__class__.__module__, proj.__class__.__name__)
ret['projection'] = proj
ret['visible'] = ax.get_visible()
ret['spines'] = {}
ret['zorder'] = ax.get_zorder()
ret['yaxis_inverted'] = ax.yaxis_inverted()
ret['xaxis_inverted'] = ax.xaxis_inverted()
for key, val in ax.spines.items():
ret['spines'][key] = {}
for prop in ['linestyle', 'edgecolor', 'linewidth',
'facecolor', 'visible']:
ret['spines'][key][prop] = getattr(val, 'get_' + prop)()
if isinstance(ax, mfig.SubplotBase):
sp = ax.get_subplotspec().get_topmost_subplotspec()
ret['grid_spec'] = sp.get_geometry()[:2]
ret['subplotspec'] = [sp.num1, sp.num2]
ret['is_subplot'] = True
else:
ret['args'] = [ax.get_position(True).bounds]
ret['is_subplot'] = False
return ret | python | def inspect_axes(ax):
"""Inspect an axes or subplot to get the initialization parameters"""
ret = {'fig': ax.get_figure().number}
if mpl.__version__ < '2.0':
ret['axisbg'] = ax.get_axis_bgcolor()
else: # axisbg is depreceated
ret['facecolor'] = ax.get_facecolor()
proj = getattr(ax, 'projection', None)
if proj is not None and not isinstance(proj, six.string_types):
proj = (proj.__class__.__module__, proj.__class__.__name__)
ret['projection'] = proj
ret['visible'] = ax.get_visible()
ret['spines'] = {}
ret['zorder'] = ax.get_zorder()
ret['yaxis_inverted'] = ax.yaxis_inverted()
ret['xaxis_inverted'] = ax.xaxis_inverted()
for key, val in ax.spines.items():
ret['spines'][key] = {}
for prop in ['linestyle', 'edgecolor', 'linewidth',
'facecolor', 'visible']:
ret['spines'][key][prop] = getattr(val, 'get_' + prop)()
if isinstance(ax, mfig.SubplotBase):
sp = ax.get_subplotspec().get_topmost_subplotspec()
ret['grid_spec'] = sp.get_geometry()[:2]
ret['subplotspec'] = [sp.num1, sp.num2]
ret['is_subplot'] = True
else:
ret['args'] = [ax.get_position(True).bounds]
ret['is_subplot'] = False
return ret | [
"def",
"inspect_axes",
"(",
"ax",
")",
":",
"ret",
"=",
"{",
"'fig'",
":",
"ax",
".",
"get_figure",
"(",
")",
".",
"number",
"}",
"if",
"mpl",
".",
"__version__",
"<",
"'2.0'",
":",
"ret",
"[",
"'axisbg'",
"]",
"=",
"ax",
".",
"get_axis_bgcolor",
"... | Inspect an axes or subplot to get the initialization parameters | [
"Inspect",
"an",
"axes",
"or",
"subplot",
"to",
"get",
"the",
"initialization",
"parameters"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/project.py#L1431-L1460 | train | 43,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.