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/project.py
ProjectPlotter._plot_methods
def _plot_methods(self): """A dictionary with mappings from plot method to their summary""" ret = {} for attr in filter(lambda s: not s.startswith("_"), dir(self)): obj = getattr(self, attr) if isinstance(obj, PlotterInterface): ret[attr] = obj._summary return ret
python
def _plot_methods(self): """A dictionary with mappings from plot method to their summary""" ret = {} for attr in filter(lambda s: not s.startswith("_"), dir(self)): obj = getattr(self, attr) if isinstance(obj, PlotterInterface): ret[attr] = obj._summary return ret
[ "def", "_plot_methods", "(", "self", ")", ":", "ret", "=", "{", "}", "for", "attr", "in", "filter", "(", "lambda", "s", ":", "not", "s", ".", "startswith", "(", "\"_\"", ")", ",", "dir", "(", "self", ")", ")", ":", "obj", "=", "getattr", "(", "...
A dictionary with mappings from plot method to their summary
[ "A", "dictionary", "with", "mappings", "from", "plot", "method", "to", "their", "summary" ]
75a0a15a9a1dd018e79d2df270d56c4bf5f311d5
https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/project.py#L1514-L1521
train
43,500
Chilipp/psyplot
psyplot/project.py
ProjectPlotter.show_plot_methods
def show_plot_methods(self): """Print the plotmethods of this instance""" print_func = PlotterInterface._print_func if print_func is None: print_func = six.print_ s = "\n".join( "%s\n %s" % t for t in six.iteritems(self._plot_methods)) return print_func(s)
python
def show_plot_methods(self): """Print the plotmethods of this instance""" print_func = PlotterInterface._print_func if print_func is None: print_func = six.print_ s = "\n".join( "%s\n %s" % t for t in six.iteritems(self._plot_methods)) return print_func(s)
[ "def", "show_plot_methods", "(", "self", ")", ":", "print_func", "=", "PlotterInterface", ".", "_print_func", "if", "print_func", "is", "None", ":", "print_func", "=", "six", ".", "print_", "s", "=", "\"\\n\"", ".", "join", "(", "\"%s\\n %s\"", "%", "t", ...
Print the plotmethods of this instance
[ "Print", "the", "plotmethods", "of", "this", "instance" ]
75a0a15a9a1dd018e79d2df270d56c4bf5f311d5
https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/project.py#L1523-L1530
train
43,501
Chilipp/psyplot
psyplot/project.py
ProjectPlotter._register_plotter
def _register_plotter(cls, identifier, module, plotter_name, plotter_cls=None, summary='', prefer_list=False, default_slice=None, default_dims={}, show_examples=True, example_call="filename, name=['my_variable'], ...", plugin=None): """ Register a plotter for making plots This class method registeres a plot function for the :class:`Project` class under the name of the given `identifier` Parameters ---------- %(Project._register_plotter.parameters)s Other Parameters ---------------- prefer_list: bool Determines the `prefer_list` parameter in the `from_dataset` method. If True, the plotter is expected to work with instances of :class:`psyplot.InteractiveList` instead of :class:`psyplot.InteractiveArray`. %(ArrayList.from_dataset.parameters.default_slice)s default_dims: dict Default dimensions that shall be used for plotting (e.g. {'x': slice(None), 'y': slice(None)} for longitude-latitude plots) show_examples: bool, optional If True, examples how to access the plotter documentation are included in class documentation example_call: str, optional The arguments and keyword arguments that shall be included in the example of the generated plot method. This call will then appear as ``>>> psy.plot.%%(identifier)s(%%(example_call)s)`` in the documentation plugin: str The name of the plugin """ full_name = '%s.%s' % (module, plotter_name) if plotter_cls is not None: # plotter has already been imported docstrings.params['%s.formatoptions' % (full_name)] = \ plotter_cls.show_keys( indent=4, func=str, # include links in sphinx doc include_links=None) doc_str = ('Possible formatoptions are\n\n' '%%(%s.formatoptions)s') % full_name else: doc_str = '' summary = summary or ( 'Open and plot data via :class:`%s.%s` plotters' % ( module, plotter_name)) if plotter_cls is not None: _versions.update(get_versions(key=lambda s: s == plugin)) class PlotMethod(cls._plot_method_base_cls): __doc__ = cls._gen_doc(summary, full_name, identifier, example_call, doc_str, show_examples) _default_slice = default_slice _default_dims = default_dims _plotter_cls = plotter_cls _prefer_list = prefer_list _plugin = plugin _summary = summary setattr(cls, identifier, PlotMethod(identifier, module, plotter_name))
python
def _register_plotter(cls, identifier, module, plotter_name, plotter_cls=None, summary='', prefer_list=False, default_slice=None, default_dims={}, show_examples=True, example_call="filename, name=['my_variable'], ...", plugin=None): """ Register a plotter for making plots This class method registeres a plot function for the :class:`Project` class under the name of the given `identifier` Parameters ---------- %(Project._register_plotter.parameters)s Other Parameters ---------------- prefer_list: bool Determines the `prefer_list` parameter in the `from_dataset` method. If True, the plotter is expected to work with instances of :class:`psyplot.InteractiveList` instead of :class:`psyplot.InteractiveArray`. %(ArrayList.from_dataset.parameters.default_slice)s default_dims: dict Default dimensions that shall be used for plotting (e.g. {'x': slice(None), 'y': slice(None)} for longitude-latitude plots) show_examples: bool, optional If True, examples how to access the plotter documentation are included in class documentation example_call: str, optional The arguments and keyword arguments that shall be included in the example of the generated plot method. This call will then appear as ``>>> psy.plot.%%(identifier)s(%%(example_call)s)`` in the documentation plugin: str The name of the plugin """ full_name = '%s.%s' % (module, plotter_name) if plotter_cls is not None: # plotter has already been imported docstrings.params['%s.formatoptions' % (full_name)] = \ plotter_cls.show_keys( indent=4, func=str, # include links in sphinx doc include_links=None) doc_str = ('Possible formatoptions are\n\n' '%%(%s.formatoptions)s') % full_name else: doc_str = '' summary = summary or ( 'Open and plot data via :class:`%s.%s` plotters' % ( module, plotter_name)) if plotter_cls is not None: _versions.update(get_versions(key=lambda s: s == plugin)) class PlotMethod(cls._plot_method_base_cls): __doc__ = cls._gen_doc(summary, full_name, identifier, example_call, doc_str, show_examples) _default_slice = default_slice _default_dims = default_dims _plotter_cls = plotter_cls _prefer_list = prefer_list _plugin = plugin _summary = summary setattr(cls, identifier, PlotMethod(identifier, module, plotter_name))
[ "def", "_register_plotter", "(", "cls", ",", "identifier", ",", "module", ",", "plotter_name", ",", "plotter_cls", "=", "None", ",", "summary", "=", "''", ",", "prefer_list", "=", "False", ",", "default_slice", "=", "None", ",", "default_dims", "=", "{", "...
Register a plotter for making plots This class method registeres a plot function for the :class:`Project` class under the name of the given `identifier` Parameters ---------- %(Project._register_plotter.parameters)s Other Parameters ---------------- prefer_list: bool Determines the `prefer_list` parameter in the `from_dataset` method. If True, the plotter is expected to work with instances of :class:`psyplot.InteractiveList` instead of :class:`psyplot.InteractiveArray`. %(ArrayList.from_dataset.parameters.default_slice)s default_dims: dict Default dimensions that shall be used for plotting (e.g. {'x': slice(None), 'y': slice(None)} for longitude-latitude plots) show_examples: bool, optional If True, examples how to access the plotter documentation are included in class documentation example_call: str, optional The arguments and keyword arguments that shall be included in the example of the generated plot method. This call will then appear as ``>>> psy.plot.%%(identifier)s(%%(example_call)s)`` in the documentation plugin: str The name of the plugin
[ "Register", "a", "plotter", "for", "making", "plots" ]
75a0a15a9a1dd018e79d2df270d56c4bf5f311d5
https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/project.py#L1560-L1629
train
43,502
Chilipp/psyplot
psyplot/project.py
PlotterInterface.plotter_cls
def plotter_cls(self): """The plotter class""" ret = self._plotter_cls if ret is None: self._logger.debug('importing %s', self.module) mod = import_module(self.module) plotter = self.plotter_name if plotter not in vars(mod): raise ImportError("Module %r does not have a %r plotter!" % ( mod, plotter)) ret = self._plotter_cls = getattr(mod, plotter) _versions.update(get_versions(key=lambda s: s == self._plugin)) return ret
python
def plotter_cls(self): """The plotter class""" ret = self._plotter_cls if ret is None: self._logger.debug('importing %s', self.module) mod = import_module(self.module) plotter = self.plotter_name if plotter not in vars(mod): raise ImportError("Module %r does not have a %r plotter!" % ( mod, plotter)) ret = self._plotter_cls = getattr(mod, plotter) _versions.update(get_versions(key=lambda s: s == self._plugin)) return ret
[ "def", "plotter_cls", "(", "self", ")", ":", "ret", "=", "self", ".", "_plotter_cls", "if", "ret", "is", "None", ":", "self", ".", "_logger", ".", "debug", "(", "'importing %s'", ",", "self", ".", "module", ")", "mod", "=", "import_module", "(", "self"...
The plotter class
[ "The", "plotter", "class" ]
75a0a15a9a1dd018e79d2df270d56c4bf5f311d5
https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/project.py#L1689-L1701
train
43,503
Chilipp/psyplot
psyplot/project.py
DatasetPlotter._add_data
def _add_data(self, plotter_cls, *args, **kwargs): """ Add new plots to the project Parameters ---------- %(ProjectPlotter._add_data.parameters.no_filename_or_obj)s Other Parameters ---------------- %(ProjectPlotter._add_data.other_parameters)s Returns ------- %(ProjectPlotter._add_data.returns)s """ # this method is just a shortcut to the :meth:`Project._add_data` # method but is reimplemented by subclasses as the # :class:`DatasetPlotter` or the :class:`DataArrayPlotter` return super(DatasetPlotter, self)._add_data(plotter_cls, self._ds, *args, **kwargs)
python
def _add_data(self, plotter_cls, *args, **kwargs): """ Add new plots to the project Parameters ---------- %(ProjectPlotter._add_data.parameters.no_filename_or_obj)s Other Parameters ---------------- %(ProjectPlotter._add_data.other_parameters)s Returns ------- %(ProjectPlotter._add_data.returns)s """ # this method is just a shortcut to the :meth:`Project._add_data` # method but is reimplemented by subclasses as the # :class:`DatasetPlotter` or the :class:`DataArrayPlotter` return super(DatasetPlotter, self)._add_data(plotter_cls, self._ds, *args, **kwargs)
[ "def", "_add_data", "(", "self", ",", "plotter_cls", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# this method is just a shortcut to the :meth:`Project._add_data`", "# method but is reimplemented by subclasses as the", "# :class:`DatasetPlotter` or the :class:`DataArrayPl...
Add new plots to the project Parameters ---------- %(ProjectPlotter._add_data.parameters.no_filename_or_obj)s Other Parameters ---------------- %(ProjectPlotter._add_data.other_parameters)s Returns ------- %(ProjectPlotter._add_data.returns)s
[ "Add", "new", "plots", "to", "the", "project" ]
75a0a15a9a1dd018e79d2df270d56c4bf5f311d5
https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/project.py#L1953-L1973
train
43,504
Chilipp/psyplot
psyplot/project.py
DataArrayPlotterInterface.check_data
def check_data(self, *args, **kwargs): """Check whether the plotter of this plot method can visualize the data """ plotter_cls = self.plotter_cls da_list = self._project_plotter._da.psy.to_interactive_list() return plotter_cls.check_data( da_list.all_names, da_list.all_dims, da_list.is_unstructured)
python
def check_data(self, *args, **kwargs): """Check whether the plotter of this plot method can visualize the data """ plotter_cls = self.plotter_cls da_list = self._project_plotter._da.psy.to_interactive_list() return plotter_cls.check_data( da_list.all_names, da_list.all_dims, da_list.is_unstructured)
[ "def", "check_data", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "plotter_cls", "=", "self", ".", "plotter_cls", "da_list", "=", "self", ".", "_project_plotter", ".", "_da", ".", "psy", ".", "to_interactive_list", "(", ")", "return"...
Check whether the plotter of this plot method can visualize the data
[ "Check", "whether", "the", "plotter", "of", "this", "plot", "method", "can", "visualize", "the", "data" ]
75a0a15a9a1dd018e79d2df270d56c4bf5f311d5
https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/project.py#L2051-L2057
train
43,505
Chilipp/psyplot
psyplot/project.py
DataArrayPlotter._add_data
def _add_data(self, plotter_cls, *args, **kwargs): """ Visualize this data array Parameters ---------- %(Plotter.parameters.no_data)s Returns ------- psyplot.plotter.Plotter The plotter that visualizes the data """ # this method is just a shortcut to the :meth:`Project._add_data` # method but is reimplemented by subclasses as the # :class:`DatasetPlotter` or the :class:`DataArrayPlotter` return plotter_cls(self._da, *args, **kwargs)
python
def _add_data(self, plotter_cls, *args, **kwargs): """ Visualize this data array Parameters ---------- %(Plotter.parameters.no_data)s Returns ------- psyplot.plotter.Plotter The plotter that visualizes the data """ # this method is just a shortcut to the :meth:`Project._add_data` # method but is reimplemented by subclasses as the # :class:`DatasetPlotter` or the :class:`DataArrayPlotter` return plotter_cls(self._da, *args, **kwargs)
[ "def", "_add_data", "(", "self", ",", "plotter_cls", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# this method is just a shortcut to the :meth:`Project._add_data`", "# method but is reimplemented by subclasses as the", "# :class:`DatasetPlotter` or the :class:`DataArrayPl...
Visualize this data array Parameters ---------- %(Plotter.parameters.no_data)s Returns ------- psyplot.plotter.Plotter The plotter that visualizes the data
[ "Visualize", "this", "data", "array" ]
75a0a15a9a1dd018e79d2df270d56c4bf5f311d5
https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/project.py#L2074-L2090
train
43,506
mfcloud/python-zvm-sdk
doc/ext/restapi_parameters.py
RestAPIParametersDirective.yaml_from_file
def yaml_from_file(self, fpath): """Collect Parameter stanzas from inline + file. This allows use to reference an external file for the actual parameter definitions. """ lookup = self._load_param_file(fpath) if not lookup: return content = "\n".join(self.content) parsed = yaml.safe_load(content) # self.app.info("Params loaded is %s" % parsed) # self.app.info("Lookup table looks like %s" % lookup) new_content = list() for paramlist in parsed: if not isinstance(paramlist, dict): self.app.warn( ("Invalid parameter definition ``%s``. Expected " "format: ``name: reference``. " " Skipping." % paramlist), (self.state_machine.node.source, self.state_machine.node.line)) continue for name, ref in paramlist.items(): if ref in lookup: new_content.append((name, lookup[ref])) else: self.app.warn( ("No field definition for ``%s`` found in ``%s``. " " Skipping." % (ref, fpath)), (self.state_machine.node.source, self.state_machine.node.line)) # self.app.info("New content %s" % new_content) self.yaml = new_content
python
def yaml_from_file(self, fpath): """Collect Parameter stanzas from inline + file. This allows use to reference an external file for the actual parameter definitions. """ lookup = self._load_param_file(fpath) if not lookup: return content = "\n".join(self.content) parsed = yaml.safe_load(content) # self.app.info("Params loaded is %s" % parsed) # self.app.info("Lookup table looks like %s" % lookup) new_content = list() for paramlist in parsed: if not isinstance(paramlist, dict): self.app.warn( ("Invalid parameter definition ``%s``. Expected " "format: ``name: reference``. " " Skipping." % paramlist), (self.state_machine.node.source, self.state_machine.node.line)) continue for name, ref in paramlist.items(): if ref in lookup: new_content.append((name, lookup[ref])) else: self.app.warn( ("No field definition for ``%s`` found in ``%s``. " " Skipping." % (ref, fpath)), (self.state_machine.node.source, self.state_machine.node.line)) # self.app.info("New content %s" % new_content) self.yaml = new_content
[ "def", "yaml_from_file", "(", "self", ",", "fpath", ")", ":", "lookup", "=", "self", ".", "_load_param_file", "(", "fpath", ")", "if", "not", "lookup", ":", "return", "content", "=", "\"\\n\"", ".", "join", "(", "self", ".", "content", ")", "parsed", "...
Collect Parameter stanzas from inline + file. This allows use to reference an external file for the actual parameter definitions.
[ "Collect", "Parameter", "stanzas", "from", "inline", "+", "file", "." ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/doc/ext/restapi_parameters.py#L78-L114
train
43,507
jvarho/pylibscrypt
pylibscrypt/libsodium_load.py
get_libsodium
def get_libsodium(): '''Locate the libsodium C library''' __SONAMES = (13, 10, 5, 4) # Import libsodium from system sys_sodium = ctypes.util.find_library('sodium') if sys_sodium is None: sys_sodium = ctypes.util.find_library('libsodium') if sys_sodium: try: return ctypes.CDLL(sys_sodium) except OSError: pass # Import from local path if sys.platform.startswith('win'): try: return ctypes.cdll.LoadLibrary('libsodium') except OSError: pass for soname_ver in __SONAMES: try: return ctypes.cdll.LoadLibrary( 'libsodium-{0}'.format(soname_ver) ) except OSError: pass elif sys.platform.startswith('darwin'): try: return ctypes.cdll.LoadLibrary('libsodium.dylib') except OSError: try: libidx = __file__.find('lib') if libidx > 0: libpath = __file__[0:libidx+3] + '/libsodium.dylib' return ctypes.cdll.LoadLibrary(libpath) except OSError: pass else: try: return ctypes.cdll.LoadLibrary('libsodium.so') except OSError: pass for soname_ver in __SONAMES: try: return ctypes.cdll.LoadLibrary( 'libsodium.so.{0}'.format(soname_ver) ) except OSError: pass
python
def get_libsodium(): '''Locate the libsodium C library''' __SONAMES = (13, 10, 5, 4) # Import libsodium from system sys_sodium = ctypes.util.find_library('sodium') if sys_sodium is None: sys_sodium = ctypes.util.find_library('libsodium') if sys_sodium: try: return ctypes.CDLL(sys_sodium) except OSError: pass # Import from local path if sys.platform.startswith('win'): try: return ctypes.cdll.LoadLibrary('libsodium') except OSError: pass for soname_ver in __SONAMES: try: return ctypes.cdll.LoadLibrary( 'libsodium-{0}'.format(soname_ver) ) except OSError: pass elif sys.platform.startswith('darwin'): try: return ctypes.cdll.LoadLibrary('libsodium.dylib') except OSError: try: libidx = __file__.find('lib') if libidx > 0: libpath = __file__[0:libidx+3] + '/libsodium.dylib' return ctypes.cdll.LoadLibrary(libpath) except OSError: pass else: try: return ctypes.cdll.LoadLibrary('libsodium.so') except OSError: pass for soname_ver in __SONAMES: try: return ctypes.cdll.LoadLibrary( 'libsodium.so.{0}'.format(soname_ver) ) except OSError: pass
[ "def", "get_libsodium", "(", ")", ":", "__SONAMES", "=", "(", "13", ",", "10", ",", "5", ",", "4", ")", "# Import libsodium from system", "sys_sodium", "=", "ctypes", ".", "util", ".", "find_library", "(", "'sodium'", ")", "if", "sys_sodium", "is", "None",...
Locate the libsodium C library
[ "Locate", "the", "libsodium", "C", "library" ]
f2ff02e49f44aa620e308a4a64dd8376b9510f99
https://github.com/jvarho/pylibscrypt/blob/f2ff02e49f44aa620e308a4a64dd8376b9510f99/pylibscrypt/libsodium_load.py#L19-L71
train
43,508
Chilipp/psyplot
psyplot/__main__.py
main
def main(args=None): """Main function for usage of psyplot from the command line This function creates a parser that parses command lines to the :func:`make_plot` functions or (if the ``psyplot_gui`` module is present, to the :func:`psyplot_gui.start_app` function) Returns ------- psyplot.parser.FuncArgParser The parser that has been used from the command line""" try: from psyplot_gui import get_parser as _get_parser except ImportError: logger.debug('Failed to import gui', exc_info=True) parser = get_parser(create=False) parser.update_arg('output', required=True) parser.create_arguments() parser.parse2func(args) else: parser = _get_parser(create=False) parser.create_arguments() parser.parse_known2func(args)
python
def main(args=None): """Main function for usage of psyplot from the command line This function creates a parser that parses command lines to the :func:`make_plot` functions or (if the ``psyplot_gui`` module is present, to the :func:`psyplot_gui.start_app` function) Returns ------- psyplot.parser.FuncArgParser The parser that has been used from the command line""" try: from psyplot_gui import get_parser as _get_parser except ImportError: logger.debug('Failed to import gui', exc_info=True) parser = get_parser(create=False) parser.update_arg('output', required=True) parser.create_arguments() parser.parse2func(args) else: parser = _get_parser(create=False) parser.create_arguments() parser.parse_known2func(args)
[ "def", "main", "(", "args", "=", "None", ")", ":", "try", ":", "from", "psyplot_gui", "import", "get_parser", "as", "_get_parser", "except", "ImportError", ":", "logger", ".", "debug", "(", "'Failed to import gui'", ",", "exc_info", "=", "True", ")", "parser...
Main function for usage of psyplot from the command line This function creates a parser that parses command lines to the :func:`make_plot` functions or (if the ``psyplot_gui`` module is present, to the :func:`psyplot_gui.start_app` function) Returns ------- psyplot.parser.FuncArgParser The parser that has been used from the command line
[ "Main", "function", "for", "usage", "of", "psyplot", "from", "the", "command", "line" ]
75a0a15a9a1dd018e79d2df270d56c4bf5f311d5
https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/__main__.py#L24-L46
train
43,509
Chilipp/psyplot
psyplot/__main__.py
make_plot
def make_plot(fnames=[], name=[], dims=None, plot_method=None, output=None, project=None, engine=None, formatoptions=None, tight=False, rc_file=None, encoding=None, enable_post=False, seaborn_style=None, output_project=None, concat_dim=get_default_value(xr.open_mfdataset, 'concat_dim'), chname={}): """ Eventually start the QApplication or only make a plot Parameters ---------- fnames: list of str Either the filenames to show, or, if the `project` parameter is set, the a list of `,`-separated filenames to make a mapping from the original filename to a new one name: list of str The variable names to plot if the `output` parameter is set dims: dict A mapping from coordinate names to integers if the `project` is not given plot_method: str The name of the plot_method to use output: str or list of str If set, the data is loaded and the figures are saved to the specified filename and now graphical user interface is shown project: str If set, the project located at the given file name is loaded engine: str The engine to use for opening the dataset (see :func:`psyplot.data.open_dataset`) formatoptions: dict A dictionary of formatoption that is applied to the data visualized by the chosen `plot_method` tight: bool If True/set, it is tried to figure out the tight bbox of the figure and adjust the paper size of the `output` to it rc_file: str The path to a yaml configuration file that can be used to update the :attr:`~psyplot.config.rcsetup.rcParams` encoding: str The encoding to use for loading the project. If None, it is automatically determined by pickle. Note: Set this to ``'latin1'`` if using a project created with python2 on python3. enable_post: bool Enable the :attr:`~psyplot.plotter.Plotter.post` processing formatoption. If True/set, post processing scripts are enabled in the given `project`. Only set this if you are sure that you can trust the given project file because it may be a security vulnerability. seaborn_style: str The name of the style of the seaborn package that can be used for the :func:`seaborn.set_style` function output_project: str The name of a project file to save the project to concat_dim: str The concatenation dimension if multiple files in `fnames` are provided chname: dict A mapping from variable names in the project to variable names in the datasets that should be used instead """ if project is not None and (name != [] or dims is not None): warn('The `name` and `dims` parameter are ignored if the `project`' ' parameter is set!') if rc_file is not None: rcParams.load_from_file(rc_file) if dims is not None and not isinstance(dims, dict): dims = dict(chain(*map(six.iteritems, dims))) if len(output) == 1: output = output[0] if not fnames and not project: raise ValueError( "Either a filename or a project file must be provided if " "the output parameter is set!") elif project is None and plot_method is None: raise ValueError( "A plotting method must be provided if the output parameter " "is set and not the project!") if seaborn_style is not None: import seaborn as sns sns.set_style(seaborn_style) import psyplot.project as psy if project is not None: fnames = [s.split(',') for s in fnames] chname = dict(chname) single_files = (l[0] for l in fnames if len(l) == 1) alternative_paths = defaultdict(lambda: next(single_files, None)) alternative_paths.update([l for l in fnames if len(l) == 2]) p = psy.Project.load_project( project, alternative_paths=alternative_paths, engine=engine, encoding=encoding, enable_post=enable_post, chname=chname) if formatoptions is not None: p.update(fmt=formatoptions) p.export(output, tight=tight) else: pm = getattr(psy.plot, plot_method, None) if pm is None: raise ValueError("Unknown plot method %s!" % plot_method) kwargs = {'name': name} if name else {} p = pm( fnames, dims=dims or {}, engine=engine, fmt=formatoptions or {}, mf_mode=True, concat_dim=concat_dim, **kwargs) p.export(output, tight=tight) if output_project is not None: p.save_project(output_project) return
python
def make_plot(fnames=[], name=[], dims=None, plot_method=None, output=None, project=None, engine=None, formatoptions=None, tight=False, rc_file=None, encoding=None, enable_post=False, seaborn_style=None, output_project=None, concat_dim=get_default_value(xr.open_mfdataset, 'concat_dim'), chname={}): """ Eventually start the QApplication or only make a plot Parameters ---------- fnames: list of str Either the filenames to show, or, if the `project` parameter is set, the a list of `,`-separated filenames to make a mapping from the original filename to a new one name: list of str The variable names to plot if the `output` parameter is set dims: dict A mapping from coordinate names to integers if the `project` is not given plot_method: str The name of the plot_method to use output: str or list of str If set, the data is loaded and the figures are saved to the specified filename and now graphical user interface is shown project: str If set, the project located at the given file name is loaded engine: str The engine to use for opening the dataset (see :func:`psyplot.data.open_dataset`) formatoptions: dict A dictionary of formatoption that is applied to the data visualized by the chosen `plot_method` tight: bool If True/set, it is tried to figure out the tight bbox of the figure and adjust the paper size of the `output` to it rc_file: str The path to a yaml configuration file that can be used to update the :attr:`~psyplot.config.rcsetup.rcParams` encoding: str The encoding to use for loading the project. If None, it is automatically determined by pickle. Note: Set this to ``'latin1'`` if using a project created with python2 on python3. enable_post: bool Enable the :attr:`~psyplot.plotter.Plotter.post` processing formatoption. If True/set, post processing scripts are enabled in the given `project`. Only set this if you are sure that you can trust the given project file because it may be a security vulnerability. seaborn_style: str The name of the style of the seaborn package that can be used for the :func:`seaborn.set_style` function output_project: str The name of a project file to save the project to concat_dim: str The concatenation dimension if multiple files in `fnames` are provided chname: dict A mapping from variable names in the project to variable names in the datasets that should be used instead """ if project is not None and (name != [] or dims is not None): warn('The `name` and `dims` parameter are ignored if the `project`' ' parameter is set!') if rc_file is not None: rcParams.load_from_file(rc_file) if dims is not None and not isinstance(dims, dict): dims = dict(chain(*map(six.iteritems, dims))) if len(output) == 1: output = output[0] if not fnames and not project: raise ValueError( "Either a filename or a project file must be provided if " "the output parameter is set!") elif project is None and plot_method is None: raise ValueError( "A plotting method must be provided if the output parameter " "is set and not the project!") if seaborn_style is not None: import seaborn as sns sns.set_style(seaborn_style) import psyplot.project as psy if project is not None: fnames = [s.split(',') for s in fnames] chname = dict(chname) single_files = (l[0] for l in fnames if len(l) == 1) alternative_paths = defaultdict(lambda: next(single_files, None)) alternative_paths.update([l for l in fnames if len(l) == 2]) p = psy.Project.load_project( project, alternative_paths=alternative_paths, engine=engine, encoding=encoding, enable_post=enable_post, chname=chname) if formatoptions is not None: p.update(fmt=formatoptions) p.export(output, tight=tight) else: pm = getattr(psy.plot, plot_method, None) if pm is None: raise ValueError("Unknown plot method %s!" % plot_method) kwargs = {'name': name} if name else {} p = pm( fnames, dims=dims or {}, engine=engine, fmt=formatoptions or {}, mf_mode=True, concat_dim=concat_dim, **kwargs) p.export(output, tight=tight) if output_project is not None: p.save_project(output_project) return
[ "def", "make_plot", "(", "fnames", "=", "[", "]", ",", "name", "=", "[", "]", ",", "dims", "=", "None", ",", "plot_method", "=", "None", ",", "output", "=", "None", ",", "project", "=", "None", ",", "engine", "=", "None", ",", "formatoptions", "=",...
Eventually start the QApplication or only make a plot Parameters ---------- fnames: list of str Either the filenames to show, or, if the `project` parameter is set, the a list of `,`-separated filenames to make a mapping from the original filename to a new one name: list of str The variable names to plot if the `output` parameter is set dims: dict A mapping from coordinate names to integers if the `project` is not given plot_method: str The name of the plot_method to use output: str or list of str If set, the data is loaded and the figures are saved to the specified filename and now graphical user interface is shown project: str If set, the project located at the given file name is loaded engine: str The engine to use for opening the dataset (see :func:`psyplot.data.open_dataset`) formatoptions: dict A dictionary of formatoption that is applied to the data visualized by the chosen `plot_method` tight: bool If True/set, it is tried to figure out the tight bbox of the figure and adjust the paper size of the `output` to it rc_file: str The path to a yaml configuration file that can be used to update the :attr:`~psyplot.config.rcsetup.rcParams` encoding: str The encoding to use for loading the project. If None, it is automatically determined by pickle. Note: Set this to ``'latin1'`` if using a project created with python2 on python3. enable_post: bool Enable the :attr:`~psyplot.plotter.Plotter.post` processing formatoption. If True/set, post processing scripts are enabled in the given `project`. Only set this if you are sure that you can trust the given project file because it may be a security vulnerability. seaborn_style: str The name of the style of the seaborn package that can be used for the :func:`seaborn.set_style` function output_project: str The name of a project file to save the project to concat_dim: str The concatenation dimension if multiple files in `fnames` are provided chname: dict A mapping from variable names in the project to variable names in the datasets that should be used instead
[ "Eventually", "start", "the", "QApplication", "or", "only", "make", "a", "plot" ]
75a0a15a9a1dd018e79d2df270d56c4bf5f311d5
https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/__main__.py#L51-L159
train
43,510
Chilipp/psyplot
psyplot/utils.py
check_key
def check_key(key, possible_keys, raise_error=True, name='formatoption keyword', msg=("See show_fmtkeys function for possible formatopion " "keywords"), *args, **kwargs): """ Checks whether the key is in a list of possible keys This function checks whether the given `key` is in `possible_keys` and if not looks for similar sounding keys Parameters ---------- key: str Key to check possible_keys: list of strings a list of possible keys to use raise_error: bool If not True, a list of similar keys is returned name: str The name of the key that shall be used in the error message msg: str The additional message that shall be used if no close match to key is found ``*args,**kwargs`` They are passed to the :func:`difflib.get_close_matches` function (i.e. `n` to increase the number of returned similar keys and `cutoff` to change the sensibility) Returns ------- str The `key` if it is a valid string, else an empty string list A list of similar formatoption strings (if found) str An error message which includes Raises ------ KeyError If the key is not a valid formatoption and `raise_error` is True""" if key not in possible_keys: similarkeys = get_close_matches(key, possible_keys, *args, **kwargs) if similarkeys: msg = ('Unknown %s %s! Possible similiar ' 'frasings are %s.') % (name, key, ', '.join(similarkeys)) else: msg = ("Unknown %s %s! ") % (name, key) + msg if not raise_error: return '', similarkeys, msg raise KeyError(msg) else: return key, [key], ''
python
def check_key(key, possible_keys, raise_error=True, name='formatoption keyword', msg=("See show_fmtkeys function for possible formatopion " "keywords"), *args, **kwargs): """ Checks whether the key is in a list of possible keys This function checks whether the given `key` is in `possible_keys` and if not looks for similar sounding keys Parameters ---------- key: str Key to check possible_keys: list of strings a list of possible keys to use raise_error: bool If not True, a list of similar keys is returned name: str The name of the key that shall be used in the error message msg: str The additional message that shall be used if no close match to key is found ``*args,**kwargs`` They are passed to the :func:`difflib.get_close_matches` function (i.e. `n` to increase the number of returned similar keys and `cutoff` to change the sensibility) Returns ------- str The `key` if it is a valid string, else an empty string list A list of similar formatoption strings (if found) str An error message which includes Raises ------ KeyError If the key is not a valid formatoption and `raise_error` is True""" if key not in possible_keys: similarkeys = get_close_matches(key, possible_keys, *args, **kwargs) if similarkeys: msg = ('Unknown %s %s! Possible similiar ' 'frasings are %s.') % (name, key, ', '.join(similarkeys)) else: msg = ("Unknown %s %s! ") % (name, key) + msg if not raise_error: return '', similarkeys, msg raise KeyError(msg) else: return key, [key], ''
[ "def", "check_key", "(", "key", ",", "possible_keys", ",", "raise_error", "=", "True", ",", "name", "=", "'formatoption keyword'", ",", "msg", "=", "(", "\"See show_fmtkeys function for possible formatopion \"", "\"keywords\"", ")", ",", "*", "args", ",", "*", "*"...
Checks whether the key is in a list of possible keys This function checks whether the given `key` is in `possible_keys` and if not looks for similar sounding keys Parameters ---------- key: str Key to check possible_keys: list of strings a list of possible keys to use raise_error: bool If not True, a list of similar keys is returned name: str The name of the key that shall be used in the error message msg: str The additional message that shall be used if no close match to key is found ``*args,**kwargs`` They are passed to the :func:`difflib.get_close_matches` function (i.e. `n` to increase the number of returned similar keys and `cutoff` to change the sensibility) Returns ------- str The `key` if it is a valid string, else an empty string list A list of similar formatoption strings (if found) str An error message which includes Raises ------ KeyError If the key is not a valid formatoption and `raise_error` is True
[ "Checks", "whether", "the", "key", "is", "in", "a", "list", "of", "possible", "keys" ]
75a0a15a9a1dd018e79d2df270d56c4bf5f311d5
https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/utils.py#L182-L235
train
43,511
Chilipp/psyplot
psyplot/utils.py
sort_kwargs
def sort_kwargs(kwargs, *param_lists): """Function to sort keyword arguments and sort them into dictionaries This function returns dictionaries that contain the keyword arguments from `kwargs` corresponding given iterables in ``*params`` Parameters ---------- kwargs: dict Original dictionary ``*param_lists`` iterables of strings, each standing for a possible key in kwargs Returns ------- list len(params) + 1 dictionaries. Each dictionary contains the items of `kwargs` corresponding to the specified list in ``*param_lists``. The last dictionary contains the remaining items""" return chain( ({key: kwargs.pop(key) for key in params.intersection(kwargs)} for params in map(set, param_lists)), [kwargs])
python
def sort_kwargs(kwargs, *param_lists): """Function to sort keyword arguments and sort them into dictionaries This function returns dictionaries that contain the keyword arguments from `kwargs` corresponding given iterables in ``*params`` Parameters ---------- kwargs: dict Original dictionary ``*param_lists`` iterables of strings, each standing for a possible key in kwargs Returns ------- list len(params) + 1 dictionaries. Each dictionary contains the items of `kwargs` corresponding to the specified list in ``*param_lists``. The last dictionary contains the remaining items""" return chain( ({key: kwargs.pop(key) for key in params.intersection(kwargs)} for params in map(set, param_lists)), [kwargs])
[ "def", "sort_kwargs", "(", "kwargs", ",", "*", "param_lists", ")", ":", "return", "chain", "(", "(", "{", "key", ":", "kwargs", ".", "pop", "(", "key", ")", "for", "key", "in", "params", ".", "intersection", "(", "kwargs", ")", "}", "for", "params", ...
Function to sort keyword arguments and sort them into dictionaries This function returns dictionaries that contain the keyword arguments from `kwargs` corresponding given iterables in ``*params`` Parameters ---------- kwargs: dict Original dictionary ``*param_lists`` iterables of strings, each standing for a possible key in kwargs Returns ------- list len(params) + 1 dictionaries. Each dictionary contains the items of `kwargs` corresponding to the specified list in ``*param_lists``. The last dictionary contains the remaining items
[ "Function", "to", "sort", "keyword", "arguments", "and", "sort", "them", "into", "dictionaries" ]
75a0a15a9a1dd018e79d2df270d56c4bf5f311d5
https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/utils.py#L238-L259
train
43,512
Chilipp/psyplot
psyplot/utils.py
hashable
def hashable(val): """Test if `val` is hashable and if not, get it's string representation Parameters ---------- val: object Any (possibly not hashable) python object Returns ------- val or string The given `val` if it is hashable or it's string representation""" if val is None: return val try: hash(val) except TypeError: return repr(val) else: return val
python
def hashable(val): """Test if `val` is hashable and if not, get it's string representation Parameters ---------- val: object Any (possibly not hashable) python object Returns ------- val or string The given `val` if it is hashable or it's string representation""" if val is None: return val try: hash(val) except TypeError: return repr(val) else: return val
[ "def", "hashable", "(", "val", ")", ":", "if", "val", "is", "None", ":", "return", "val", "try", ":", "hash", "(", "val", ")", "except", "TypeError", ":", "return", "repr", "(", "val", ")", "else", ":", "return", "val" ]
Test if `val` is hashable and if not, get it's string representation Parameters ---------- val: object Any (possibly not hashable) python object Returns ------- val or string The given `val` if it is hashable or it's string representation
[ "Test", "if", "val", "is", "hashable", "and", "if", "not", "get", "it", "s", "string", "representation" ]
75a0a15a9a1dd018e79d2df270d56c4bf5f311d5
https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/utils.py#L262-L281
train
43,513
Chilipp/psyplot
psyplot/utils.py
join_dicts
def join_dicts(dicts, delimiter=None, keep_all=False): """Join multiple dictionaries into one Parameters ---------- dicts: list of dict A list of dictionaries delimiter: str The string that shall be used as the delimiter in case that there are multiple values for one attribute in the arrays. If None, they will be returned as sets keep_all: bool If True, all formatoptions are kept. Otherwise only the intersection Returns ------- dict The combined dictionary""" if not dicts: return {} if keep_all: all_keys = set(chain(*(d.keys() for d in dicts))) else: all_keys = set(dicts[0]) for d in dicts[1:]: all_keys.intersection_update(d) ret = {} for key in all_keys: vals = {hashable(d.get(key, None)) for d in dicts} - {None} if len(vals) == 1: ret[key] = next(iter(vals)) elif delimiter is None: ret[key] = vals else: ret[key] = delimiter.join(map(str, vals)) return ret
python
def join_dicts(dicts, delimiter=None, keep_all=False): """Join multiple dictionaries into one Parameters ---------- dicts: list of dict A list of dictionaries delimiter: str The string that shall be used as the delimiter in case that there are multiple values for one attribute in the arrays. If None, they will be returned as sets keep_all: bool If True, all formatoptions are kept. Otherwise only the intersection Returns ------- dict The combined dictionary""" if not dicts: return {} if keep_all: all_keys = set(chain(*(d.keys() for d in dicts))) else: all_keys = set(dicts[0]) for d in dicts[1:]: all_keys.intersection_update(d) ret = {} for key in all_keys: vals = {hashable(d.get(key, None)) for d in dicts} - {None} if len(vals) == 1: ret[key] = next(iter(vals)) elif delimiter is None: ret[key] = vals else: ret[key] = delimiter.join(map(str, vals)) return ret
[ "def", "join_dicts", "(", "dicts", ",", "delimiter", "=", "None", ",", "keep_all", "=", "False", ")", ":", "if", "not", "dicts", ":", "return", "{", "}", "if", "keep_all", ":", "all_keys", "=", "set", "(", "chain", "(", "*", "(", "d", ".", "keys", ...
Join multiple dictionaries into one Parameters ---------- dicts: list of dict A list of dictionaries delimiter: str The string that shall be used as the delimiter in case that there are multiple values for one attribute in the arrays. If None, they will be returned as sets keep_all: bool If True, all formatoptions are kept. Otherwise only the intersection Returns ------- dict The combined dictionary
[ "Join", "multiple", "dictionaries", "into", "one" ]
75a0a15a9a1dd018e79d2df270d56c4bf5f311d5
https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/utils.py#L285-L320
train
43,514
mfcloud/python-zvm-sdk
zvmsdk/api.py
check_guest_exist
def check_guest_exist(check_index=0): """Check guest exist in database. :param check_index: The parameter index of userid(s), default as 0 """ def outer(f): @six.wraps(f) def inner(self, *args, **kw): userids = args[check_index] if isinstance(userids, list): # convert all userids to upper case userids = [uid.upper() for uid in userids] new_args = (args[:check_index] + (userids,) + args[check_index + 1:]) else: # convert the userid to upper case userids = userids.upper() new_args = (args[:check_index] + (userids,) + args[check_index + 1:]) userids = [userids] self._vmops.check_guests_exist_in_db(userids) return f(self, *new_args, **kw) return inner return outer
python
def check_guest_exist(check_index=0): """Check guest exist in database. :param check_index: The parameter index of userid(s), default as 0 """ def outer(f): @six.wraps(f) def inner(self, *args, **kw): userids = args[check_index] if isinstance(userids, list): # convert all userids to upper case userids = [uid.upper() for uid in userids] new_args = (args[:check_index] + (userids,) + args[check_index + 1:]) else: # convert the userid to upper case userids = userids.upper() new_args = (args[:check_index] + (userids,) + args[check_index + 1:]) userids = [userids] self._vmops.check_guests_exist_in_db(userids) return f(self, *new_args, **kw) return inner return outer
[ "def", "check_guest_exist", "(", "check_index", "=", "0", ")", ":", "def", "outer", "(", "f", ")", ":", "@", "six", ".", "wraps", "(", "f", ")", "def", "inner", "(", "self", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "userids", "=", "args...
Check guest exist in database. :param check_index: The parameter index of userid(s), default as 0
[ "Check", "guest", "exist", "in", "database", "." ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/api.py#L38-L66
train
43,515
mfcloud/python-zvm-sdk
zvmsdk/api.py
SDKAPI.guest_start
def guest_start(self, userid): """Power on a virtual machine. :param str userid: the id of the virtual machine to be power on :returns: None """ action = "start guest '%s'" % userid with zvmutils.log_and_reraise_sdkbase_error(action): self._vmops.guest_start(userid)
python
def guest_start(self, userid): """Power on a virtual machine. :param str userid: the id of the virtual machine to be power on :returns: None """ action = "start guest '%s'" % userid with zvmutils.log_and_reraise_sdkbase_error(action): self._vmops.guest_start(userid)
[ "def", "guest_start", "(", "self", ",", "userid", ")", ":", "action", "=", "\"start guest '%s'\"", "%", "userid", "with", "zvmutils", ".", "log_and_reraise_sdkbase_error", "(", "action", ")", ":", "self", ".", "_vmops", ".", "guest_start", "(", "userid", ")" ]
Power on a virtual machine. :param str userid: the id of the virtual machine to be power on :returns: None
[ "Power", "on", "a", "virtual", "machine", "." ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/api.py#L84-L93
train
43,516
mfcloud/python-zvm-sdk
zvmsdk/api.py
SDKAPI.guest_stop
def guest_stop(self, userid, **kwargs): """Power off a virtual machine. :param str userid: the id of the virtual machine to be power off :param dict kwargs: - timeout=<value>: Integer, time to wait for vm to be deactivate, the recommended value is 300 - poll_interval=<value> Integer, how often to signal guest while waiting for it to be deactivate, the recommended value is 20 :returns: None """ action = "stop guest '%s'" % userid with zvmutils.log_and_reraise_sdkbase_error(action): self._vmops.guest_stop(userid, **kwargs)
python
def guest_stop(self, userid, **kwargs): """Power off a virtual machine. :param str userid: the id of the virtual machine to be power off :param dict kwargs: - timeout=<value>: Integer, time to wait for vm to be deactivate, the recommended value is 300 - poll_interval=<value> Integer, how often to signal guest while waiting for it to be deactivate, the recommended value is 20 :returns: None """ action = "stop guest '%s'" % userid with zvmutils.log_and_reraise_sdkbase_error(action): self._vmops.guest_stop(userid, **kwargs)
[ "def", "guest_stop", "(", "self", ",", "userid", ",", "*", "*", "kwargs", ")", ":", "action", "=", "\"stop guest '%s'\"", "%", "userid", "with", "zvmutils", ".", "log_and_reraise_sdkbase_error", "(", "action", ")", ":", "self", ".", "_vmops", ".", "guest_sto...
Power off a virtual machine. :param str userid: the id of the virtual machine to be power off :param dict kwargs: - timeout=<value>: Integer, time to wait for vm to be deactivate, the recommended value is 300 - poll_interval=<value> Integer, how often to signal guest while waiting for it to be deactivate, the recommended value is 20 :returns: None
[ "Power", "off", "a", "virtual", "machine", "." ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/api.py#L96-L113
train
43,517
mfcloud/python-zvm-sdk
zvmsdk/api.py
SDKAPI.guest_unpause
def guest_unpause(self, userid): """Unpause a virtual machine. :param str userid: the id of the virtual machine to be unpaused :returns: None """ action = "unpause guest '%s'" % userid with zvmutils.log_and_reraise_sdkbase_error(action): self._vmops.guest_unpause(userid)
python
def guest_unpause(self, userid): """Unpause a virtual machine. :param str userid: the id of the virtual machine to be unpaused :returns: None """ action = "unpause guest '%s'" % userid with zvmutils.log_and_reraise_sdkbase_error(action): self._vmops.guest_unpause(userid)
[ "def", "guest_unpause", "(", "self", ",", "userid", ")", ":", "action", "=", "\"unpause guest '%s'\"", "%", "userid", "with", "zvmutils", ".", "log_and_reraise_sdkbase_error", "(", "action", ")", ":", "self", ".", "_vmops", ".", "guest_unpause", "(", "userid", ...
Unpause a virtual machine. :param str userid: the id of the virtual machine to be unpaused :returns: None
[ "Unpause", "a", "virtual", "machine", "." ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/api.py#L168-L176
train
43,518
mfcloud/python-zvm-sdk
zvmsdk/api.py
SDKAPI.guest_get_power_state
def guest_get_power_state(self, userid): """Returns power state.""" action = "get power state of guest '%s'" % userid with zvmutils.log_and_reraise_sdkbase_error(action): return self._vmops.get_power_state(userid)
python
def guest_get_power_state(self, userid): """Returns power state.""" action = "get power state of guest '%s'" % userid with zvmutils.log_and_reraise_sdkbase_error(action): return self._vmops.get_power_state(userid)
[ "def", "guest_get_power_state", "(", "self", ",", "userid", ")", ":", "action", "=", "\"get power state of guest '%s'\"", "%", "userid", "with", "zvmutils", ".", "log_and_reraise_sdkbase_error", "(", "action", ")", ":", "return", "self", ".", "_vmops", ".", "get_p...
Returns power state.
[ "Returns", "power", "state", "." ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/api.py#L179-L183
train
43,519
mfcloud/python-zvm-sdk
zvmsdk/api.py
SDKAPI.guest_get_info
def guest_get_info(self, userid): """Get the status of a virtual machine. :param str userid: the id of the virtual machine :returns: Dictionary contains: power_state: (str) the running state, one of on | off max_mem_kb: (int) the maximum memory in KBytes allowed mem_kb: (int) the memory in KBytes used by the instance num_cpu: (int) the number of virtual CPUs for the instance cpu_time_us: (int) the CPU time used in microseconds """ action = "get info of guest '%s'" % userid with zvmutils.log_and_reraise_sdkbase_error(action): return self._vmops.get_info(userid)
python
def guest_get_info(self, userid): """Get the status of a virtual machine. :param str userid: the id of the virtual machine :returns: Dictionary contains: power_state: (str) the running state, one of on | off max_mem_kb: (int) the maximum memory in KBytes allowed mem_kb: (int) the memory in KBytes used by the instance num_cpu: (int) the number of virtual CPUs for the instance cpu_time_us: (int) the CPU time used in microseconds """ action = "get info of guest '%s'" % userid with zvmutils.log_and_reraise_sdkbase_error(action): return self._vmops.get_info(userid)
[ "def", "guest_get_info", "(", "self", ",", "userid", ")", ":", "action", "=", "\"get info of guest '%s'\"", "%", "userid", "with", "zvmutils", ".", "log_and_reraise_sdkbase_error", "(", "action", ")", ":", "return", "self", ".", "_vmops", ".", "get_info", "(", ...
Get the status of a virtual machine. :param str userid: the id of the virtual machine :returns: Dictionary contains: power_state: (str) the running state, one of on | off max_mem_kb: (int) the maximum memory in KBytes allowed mem_kb: (int) the memory in KBytes used by the instance num_cpu: (int) the number of virtual CPUs for the instance cpu_time_us: (int) the CPU time used in microseconds
[ "Get", "the", "status", "of", "a", "virtual", "machine", "." ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/api.py#L186-L200
train
43,520
mfcloud/python-zvm-sdk
zvmsdk/api.py
SDKAPI.image_delete
def image_delete(self, image_name): """Delete image from image repository :param image_name: the name of the image to be deleted """ try: self._imageops.image_delete(image_name) except exception.SDKBaseException: LOG.error("Failed to delete image '%s'" % image_name) raise
python
def image_delete(self, image_name): """Delete image from image repository :param image_name: the name of the image to be deleted """ try: self._imageops.image_delete(image_name) except exception.SDKBaseException: LOG.error("Failed to delete image '%s'" % image_name) raise
[ "def", "image_delete", "(", "self", ",", "image_name", ")", ":", "try", ":", "self", ".", "_imageops", ".", "image_delete", "(", "image_name", ")", "except", "exception", ".", "SDKBaseException", ":", "LOG", ".", "error", "(", "\"Failed to delete image '%s'\"", ...
Delete image from image repository :param image_name: the name of the image to be deleted
[ "Delete", "image", "from", "image", "repository" ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/api.py#L249-L258
train
43,521
mfcloud/python-zvm-sdk
zvmsdk/api.py
SDKAPI.image_get_root_disk_size
def image_get_root_disk_size(self, image_name): """Get the root disk size of the image :param image_name: the image name in image Repository :returns: the disk size in units CYL or BLK """ try: return self._imageops.image_get_root_disk_size(image_name) except exception.SDKBaseException: LOG.error("Failed to get root disk size units of image '%s'" % image_name) raise
python
def image_get_root_disk_size(self, image_name): """Get the root disk size of the image :param image_name: the image name in image Repository :returns: the disk size in units CYL or BLK """ try: return self._imageops.image_get_root_disk_size(image_name) except exception.SDKBaseException: LOG.error("Failed to get root disk size units of image '%s'" % image_name) raise
[ "def", "image_get_root_disk_size", "(", "self", ",", "image_name", ")", ":", "try", ":", "return", "self", ".", "_imageops", ".", "image_get_root_disk_size", "(", "image_name", ")", "except", "exception", ".", "SDKBaseException", ":", "LOG", ".", "error", "(", ...
Get the root disk size of the image :param image_name: the image name in image Repository :returns: the disk size in units CYL or BLK
[ "Get", "the", "root", "disk", "size", "of", "the", "image" ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/api.py#L260-L271
train
43,522
mfcloud/python-zvm-sdk
zvmsdk/api.py
SDKAPI.image_import
def image_import(self, image_name, url, image_meta, remote_host=None): """Import image to zvmsdk image repository :param image_name: image name that can be uniquely identify an image :param str url: image url to specify the location of image such as http://netloc/path/to/file.tar.gz.0 https://netloc/path/to/file.tar.gz.0 file:///path/to/file.tar.gz.0 :param dict image_meta: a dictionary to describe the image info, such as md5sum, os_version. For example: {'os_version': 'rhel6.2', 'md5sum': ' 46f199c336eab1e35a72fa6b5f6f11f5'} :param string remote_host: if the image url schema is file, the remote_host is used to indicate where the image comes from, the format is username@IP eg. nova@192.168.99.1, the default value is None, it indicate the image is from a local file system. If the image url schema is http/https, this value will be useless """ try: self._imageops.image_import(image_name, url, image_meta, remote_host=remote_host) except exception.SDKBaseException: LOG.error("Failed to import image '%s'" % image_name) raise
python
def image_import(self, image_name, url, image_meta, remote_host=None): """Import image to zvmsdk image repository :param image_name: image name that can be uniquely identify an image :param str url: image url to specify the location of image such as http://netloc/path/to/file.tar.gz.0 https://netloc/path/to/file.tar.gz.0 file:///path/to/file.tar.gz.0 :param dict image_meta: a dictionary to describe the image info, such as md5sum, os_version. For example: {'os_version': 'rhel6.2', 'md5sum': ' 46f199c336eab1e35a72fa6b5f6f11f5'} :param string remote_host: if the image url schema is file, the remote_host is used to indicate where the image comes from, the format is username@IP eg. nova@192.168.99.1, the default value is None, it indicate the image is from a local file system. If the image url schema is http/https, this value will be useless """ try: self._imageops.image_import(image_name, url, image_meta, remote_host=remote_host) except exception.SDKBaseException: LOG.error("Failed to import image '%s'" % image_name) raise
[ "def", "image_import", "(", "self", ",", "image_name", ",", "url", ",", "image_meta", ",", "remote_host", "=", "None", ")", ":", "try", ":", "self", ".", "_imageops", ".", "image_import", "(", "image_name", ",", "url", ",", "image_meta", ",", "remote_host"...
Import image to zvmsdk image repository :param image_name: image name that can be uniquely identify an image :param str url: image url to specify the location of image such as http://netloc/path/to/file.tar.gz.0 https://netloc/path/to/file.tar.gz.0 file:///path/to/file.tar.gz.0 :param dict image_meta: a dictionary to describe the image info, such as md5sum, os_version. For example: {'os_version': 'rhel6.2', 'md5sum': ' 46f199c336eab1e35a72fa6b5f6f11f5'} :param string remote_host: if the image url schema is file, the remote_host is used to indicate where the image comes from, the format is username@IP eg. nova@192.168.99.1, the default value is None, it indicate the image is from a local file system. If the image url schema is http/https, this value will be useless
[ "Import", "image", "to", "zvmsdk", "image", "repository" ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/api.py#L273-L298
train
43,523
mfcloud/python-zvm-sdk
zvmsdk/api.py
SDKAPI.image_query
def image_query(self, imagename=None): """Get the list of image info in image repository :param imagename: Used to retrieve the specified image info, if not specified, all images info will be returned :returns: A list that contains the specified or all images info """ try: return self._imageops.image_query(imagename) except exception.SDKBaseException: LOG.error("Failed to query image") raise
python
def image_query(self, imagename=None): """Get the list of image info in image repository :param imagename: Used to retrieve the specified image info, if not specified, all images info will be returned :returns: A list that contains the specified or all images info """ try: return self._imageops.image_query(imagename) except exception.SDKBaseException: LOG.error("Failed to query image") raise
[ "def", "image_query", "(", "self", ",", "imagename", "=", "None", ")", ":", "try", ":", "return", "self", ".", "_imageops", ".", "image_query", "(", "imagename", ")", "except", "exception", ".", "SDKBaseException", ":", "LOG", ".", "error", "(", "\"Failed ...
Get the list of image info in image repository :param imagename: Used to retrieve the specified image info, if not specified, all images info will be returned :returns: A list that contains the specified or all images info
[ "Get", "the", "list", "of", "image", "info", "in", "image", "repository" ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/api.py#L300-L312
train
43,524
mfcloud/python-zvm-sdk
zvmsdk/api.py
SDKAPI.guest_deploy
def guest_deploy(self, userid, image_name, transportfiles=None, remotehost=None, vdev=None, hostname=None): """ Deploy the image to vm. :param userid: (str) the user id of the vm :param image_name: (str) the name of image that used to deploy the vm :param transportfiles: (str) the files that used to customize the vm :param remotehost: the server where the transportfiles located, the format is username@IP, eg nova@192.168.99.1 :param vdev: (str) the device that image will be deploy to :param hostname: (str) the hostname of the vm. This parameter will be ignored if transportfiles present. """ action = ("deploy image '%(img)s' to guest '%(vm)s'" % {'img': image_name, 'vm': userid}) with zvmutils.log_and_reraise_sdkbase_error(action): self._vmops.guest_deploy(userid, image_name, transportfiles, remotehost, vdev, hostname)
python
def guest_deploy(self, userid, image_name, transportfiles=None, remotehost=None, vdev=None, hostname=None): """ Deploy the image to vm. :param userid: (str) the user id of the vm :param image_name: (str) the name of image that used to deploy the vm :param transportfiles: (str) the files that used to customize the vm :param remotehost: the server where the transportfiles located, the format is username@IP, eg nova@192.168.99.1 :param vdev: (str) the device that image will be deploy to :param hostname: (str) the hostname of the vm. This parameter will be ignored if transportfiles present. """ action = ("deploy image '%(img)s' to guest '%(vm)s'" % {'img': image_name, 'vm': userid}) with zvmutils.log_and_reraise_sdkbase_error(action): self._vmops.guest_deploy(userid, image_name, transportfiles, remotehost, vdev, hostname)
[ "def", "guest_deploy", "(", "self", ",", "userid", ",", "image_name", ",", "transportfiles", "=", "None", ",", "remotehost", "=", "None", ",", "vdev", "=", "None", ",", "hostname", "=", "None", ")", ":", "action", "=", "(", "\"deploy image '%(img)s' to guest...
Deploy the image to vm. :param userid: (str) the user id of the vm :param image_name: (str) the name of image that used to deploy the vm :param transportfiles: (str) the files that used to customize the vm :param remotehost: the server where the transportfiles located, the format is username@IP, eg nova@192.168.99.1 :param vdev: (str) the device that image will be deploy to :param hostname: (str) the hostname of the vm. This parameter will be ignored if transportfiles present.
[ "Deploy", "the", "image", "to", "vm", "." ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/api.py#L339-L356
train
43,525
mfcloud/python-zvm-sdk
zvmsdk/api.py
SDKAPI.guest_capture
def guest_capture(self, userid, image_name, capture_type='rootonly', compress_level=6): """ Capture the guest to generate a image :param userid: (str) the user id of the vm :param image_name: (str) the unique image name after capture :param capture_type: (str) the type of capture, the value can be: rootonly: indicate just root device will be captured alldisks: indicate all the devices of the userid will be captured :param compress_level: the compression level of the image, default is 6 """ action = ("capture guest '%(vm)s' to generate image '%(img)s'" % {'vm': userid, 'img': image_name}) with zvmutils.log_and_reraise_sdkbase_error(action): self._vmops.guest_capture(userid, image_name, capture_type=capture_type, compress_level=compress_level)
python
def guest_capture(self, userid, image_name, capture_type='rootonly', compress_level=6): """ Capture the guest to generate a image :param userid: (str) the user id of the vm :param image_name: (str) the unique image name after capture :param capture_type: (str) the type of capture, the value can be: rootonly: indicate just root device will be captured alldisks: indicate all the devices of the userid will be captured :param compress_level: the compression level of the image, default is 6 """ action = ("capture guest '%(vm)s' to generate image '%(img)s'" % {'vm': userid, 'img': image_name}) with zvmutils.log_and_reraise_sdkbase_error(action): self._vmops.guest_capture(userid, image_name, capture_type=capture_type, compress_level=compress_level)
[ "def", "guest_capture", "(", "self", ",", "userid", ",", "image_name", ",", "capture_type", "=", "'rootonly'", ",", "compress_level", "=", "6", ")", ":", "action", "=", "(", "\"capture guest '%(vm)s' to generate image '%(img)s'\"", "%", "{", "'vm'", ":", "userid",...
Capture the guest to generate a image :param userid: (str) the user id of the vm :param image_name: (str) the unique image name after capture :param capture_type: (str) the type of capture, the value can be: rootonly: indicate just root device will be captured alldisks: indicate all the devices of the userid will be captured :param compress_level: the compression level of the image, default is 6
[ "Capture", "the", "guest", "to", "generate", "a", "image" ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/api.py#L359-L377
train
43,526
mfcloud/python-zvm-sdk
zvmsdk/api.py
SDKAPI.guest_create_nic
def guest_create_nic(self, userid, vdev=None, nic_id=None, mac_addr=None, active=False): """ Create the nic for the vm, add NICDEF record into the user direct. :param str userid: the user id of the vm :param str vdev: nic device number, 1- to 4- hexadecimal digits :param str nic_id: nic identifier :param str mac_addr: mac address, it is only be used when changing the guest's user direct. Format should be xx:xx:xx:xx:xx:xx, and x is a hexadecimal digit :param bool active: whether add a nic on active guest system :returns: nic device number, 1- to 4- hexadecimal digits :rtype: str """ if mac_addr is not None: if not zvmutils.valid_mac_addr(mac_addr): raise exception.SDKInvalidInputFormat( msg=("Invalid mac address, format should be " "xx:xx:xx:xx:xx:xx, and x is a hexadecimal digit")) return self._networkops.create_nic(userid, vdev=vdev, nic_id=nic_id, mac_addr=mac_addr, active=active)
python
def guest_create_nic(self, userid, vdev=None, nic_id=None, mac_addr=None, active=False): """ Create the nic for the vm, add NICDEF record into the user direct. :param str userid: the user id of the vm :param str vdev: nic device number, 1- to 4- hexadecimal digits :param str nic_id: nic identifier :param str mac_addr: mac address, it is only be used when changing the guest's user direct. Format should be xx:xx:xx:xx:xx:xx, and x is a hexadecimal digit :param bool active: whether add a nic on active guest system :returns: nic device number, 1- to 4- hexadecimal digits :rtype: str """ if mac_addr is not None: if not zvmutils.valid_mac_addr(mac_addr): raise exception.SDKInvalidInputFormat( msg=("Invalid mac address, format should be " "xx:xx:xx:xx:xx:xx, and x is a hexadecimal digit")) return self._networkops.create_nic(userid, vdev=vdev, nic_id=nic_id, mac_addr=mac_addr, active=active)
[ "def", "guest_create_nic", "(", "self", ",", "userid", ",", "vdev", "=", "None", ",", "nic_id", "=", "None", ",", "mac_addr", "=", "None", ",", "active", "=", "False", ")", ":", "if", "mac_addr", "is", "not", "None", ":", "if", "not", "zvmutils", "."...
Create the nic for the vm, add NICDEF record into the user direct. :param str userid: the user id of the vm :param str vdev: nic device number, 1- to 4- hexadecimal digits :param str nic_id: nic identifier :param str mac_addr: mac address, it is only be used when changing the guest's user direct. Format should be xx:xx:xx:xx:xx:xx, and x is a hexadecimal digit :param bool active: whether add a nic on active guest system :returns: nic device number, 1- to 4- hexadecimal digits :rtype: str
[ "Create", "the", "nic", "for", "the", "vm", "add", "NICDEF", "record", "into", "the", "user", "direct", "." ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/api.py#L380-L401
train
43,527
mfcloud/python-zvm-sdk
zvmsdk/api.py
SDKAPI.guest_delete_nic
def guest_delete_nic(self, userid, vdev, active=False): """ delete the nic for the vm :param str userid: the user id of the vm :param str vdev: nic device number, 1- to 4- hexadecimal digits :param bool active: whether delete a nic on active guest system """ self._networkops.delete_nic(userid, vdev, active=active)
python
def guest_delete_nic(self, userid, vdev, active=False): """ delete the nic for the vm :param str userid: the user id of the vm :param str vdev: nic device number, 1- to 4- hexadecimal digits :param bool active: whether delete a nic on active guest system """ self._networkops.delete_nic(userid, vdev, active=active)
[ "def", "guest_delete_nic", "(", "self", ",", "userid", ",", "vdev", ",", "active", "=", "False", ")", ":", "self", ".", "_networkops", ".", "delete_nic", "(", "userid", ",", "vdev", ",", "active", "=", "active", ")" ]
delete the nic for the vm :param str userid: the user id of the vm :param str vdev: nic device number, 1- to 4- hexadecimal digits :param bool active: whether delete a nic on active guest system
[ "delete", "the", "nic", "for", "the", "vm" ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/api.py#L404-L411
train
43,528
mfcloud/python-zvm-sdk
zvmsdk/api.py
SDKAPI.guest_get_definition_info
def guest_get_definition_info(self, userid, **kwargs): """Get definition info for the specified guest vm, also could be used to check specific info. :param str userid: the user id of the guest vm :param dict kwargs: Dictionary used to check specific info in user direct. Valid keywords for kwargs: nic_coupled=<vdev>, where <vdev> is the virtual device number of the nic to be checked the couple status. :returns: Dictionary describing user direct and check info result :rtype: dict """ action = "get the definition info of guest '%s'" % userid with zvmutils.log_and_reraise_sdkbase_error(action): return self._vmops.get_definition_info(userid, **kwargs)
python
def guest_get_definition_info(self, userid, **kwargs): """Get definition info for the specified guest vm, also could be used to check specific info. :param str userid: the user id of the guest vm :param dict kwargs: Dictionary used to check specific info in user direct. Valid keywords for kwargs: nic_coupled=<vdev>, where <vdev> is the virtual device number of the nic to be checked the couple status. :returns: Dictionary describing user direct and check info result :rtype: dict """ action = "get the definition info of guest '%s'" % userid with zvmutils.log_and_reraise_sdkbase_error(action): return self._vmops.get_definition_info(userid, **kwargs)
[ "def", "guest_get_definition_info", "(", "self", ",", "userid", ",", "*", "*", "kwargs", ")", ":", "action", "=", "\"get the definition info of guest '%s'\"", "%", "userid", "with", "zvmutils", ".", "log_and_reraise_sdkbase_error", "(", "action", ")", ":", "return",...
Get definition info for the specified guest vm, also could be used to check specific info. :param str userid: the user id of the guest vm :param dict kwargs: Dictionary used to check specific info in user direct. Valid keywords for kwargs: nic_coupled=<vdev>, where <vdev> is the virtual device number of the nic to be checked the couple status. :returns: Dictionary describing user direct and check info result :rtype: dict
[ "Get", "definition", "info", "for", "the", "specified", "guest", "vm", "also", "could", "be", "used", "to", "check", "specific", "info", "." ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/api.py#L414-L429
train
43,529
mfcloud/python-zvm-sdk
zvmsdk/api.py
SDKAPI.guest_live_resize_cpus
def guest_live_resize_cpus(self, userid, cpu_cnt): """Live resize virtual cpus of guests. :param userid: (str) the userid of the guest to be live resized :param cpu_cnt: (int) The number of virtual cpus that the guest should have in active state after live resize. The value should be an integer between 1 and 64. """ action = "live resize guest '%s' to have '%i' virtual cpus" % (userid, cpu_cnt) LOG.info("Begin to %s" % action) with zvmutils.log_and_reraise_sdkbase_error(action): self._vmops.live_resize_cpus(userid, cpu_cnt) LOG.info("%s successfully." % action)
python
def guest_live_resize_cpus(self, userid, cpu_cnt): """Live resize virtual cpus of guests. :param userid: (str) the userid of the guest to be live resized :param cpu_cnt: (int) The number of virtual cpus that the guest should have in active state after live resize. The value should be an integer between 1 and 64. """ action = "live resize guest '%s' to have '%i' virtual cpus" % (userid, cpu_cnt) LOG.info("Begin to %s" % action) with zvmutils.log_and_reraise_sdkbase_error(action): self._vmops.live_resize_cpus(userid, cpu_cnt) LOG.info("%s successfully." % action)
[ "def", "guest_live_resize_cpus", "(", "self", ",", "userid", ",", "cpu_cnt", ")", ":", "action", "=", "\"live resize guest '%s' to have '%i' virtual cpus\"", "%", "(", "userid", ",", "cpu_cnt", ")", "LOG", ".", "info", "(", "\"Begin to %s\"", "%", "action", ")", ...
Live resize virtual cpus of guests. :param userid: (str) the userid of the guest to be live resized :param cpu_cnt: (int) The number of virtual cpus that the guest should have in active state after live resize. The value should be an integer between 1 and 64.
[ "Live", "resize", "virtual", "cpus", "of", "guests", "." ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/api.py#L632-L646
train
43,530
mfcloud/python-zvm-sdk
zvmsdk/api.py
SDKAPI.guest_resize_cpus
def guest_resize_cpus(self, userid, cpu_cnt): """Resize virtual cpus of guests. :param userid: (str) the userid of the guest to be resized :param cpu_cnt: (int) The number of virtual cpus that the guest should have defined in user directory after resize. The value should be an integer between 1 and 64. """ action = "resize guest '%s' to have '%i' virtual cpus" % (userid, cpu_cnt) LOG.info("Begin to %s" % action) with zvmutils.log_and_reraise_sdkbase_error(action): self._vmops.resize_cpus(userid, cpu_cnt) LOG.info("%s successfully." % action)
python
def guest_resize_cpus(self, userid, cpu_cnt): """Resize virtual cpus of guests. :param userid: (str) the userid of the guest to be resized :param cpu_cnt: (int) The number of virtual cpus that the guest should have defined in user directory after resize. The value should be an integer between 1 and 64. """ action = "resize guest '%s' to have '%i' virtual cpus" % (userid, cpu_cnt) LOG.info("Begin to %s" % action) with zvmutils.log_and_reraise_sdkbase_error(action): self._vmops.resize_cpus(userid, cpu_cnt) LOG.info("%s successfully." % action)
[ "def", "guest_resize_cpus", "(", "self", ",", "userid", ",", "cpu_cnt", ")", ":", "action", "=", "\"resize guest '%s' to have '%i' virtual cpus\"", "%", "(", "userid", ",", "cpu_cnt", ")", "LOG", ".", "info", "(", "\"Begin to %s\"", "%", "action", ")", "with", ...
Resize virtual cpus of guests. :param userid: (str) the userid of the guest to be resized :param cpu_cnt: (int) The number of virtual cpus that the guest should have defined in user directory after resize. The value should be an integer between 1 and 64.
[ "Resize", "virtual", "cpus", "of", "guests", "." ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/api.py#L649-L663
train
43,531
mfcloud/python-zvm-sdk
zvmsdk/api.py
SDKAPI.guest_live_resize_mem
def guest_live_resize_mem(self, userid, size): """Live resize memory of guests. :param userid: (str) the userid of the guest to be live resized :param size: (str) The memory size that the guest should have in available status after live resize. The value should be specified by 1-4 bits of number suffixed by either M (Megabytes) or G (Gigabytes). And the number should be an integer. """ action = "live resize guest '%s' to have '%s' memory" % (userid, size) LOG.info("Begin to %s" % action) with zvmutils.log_and_reraise_sdkbase_error(action): self._vmops.live_resize_memory(userid, size) LOG.info("%s successfully." % action)
python
def guest_live_resize_mem(self, userid, size): """Live resize memory of guests. :param userid: (str) the userid of the guest to be live resized :param size: (str) The memory size that the guest should have in available status after live resize. The value should be specified by 1-4 bits of number suffixed by either M (Megabytes) or G (Gigabytes). And the number should be an integer. """ action = "live resize guest '%s' to have '%s' memory" % (userid, size) LOG.info("Begin to %s" % action) with zvmutils.log_and_reraise_sdkbase_error(action): self._vmops.live_resize_memory(userid, size) LOG.info("%s successfully." % action)
[ "def", "guest_live_resize_mem", "(", "self", ",", "userid", ",", "size", ")", ":", "action", "=", "\"live resize guest '%s' to have '%s' memory\"", "%", "(", "userid", ",", "size", ")", "LOG", ".", "info", "(", "\"Begin to %s\"", "%", "action", ")", "with", "z...
Live resize memory of guests. :param userid: (str) the userid of the guest to be live resized :param size: (str) The memory size that the guest should have in available status after live resize. The value should be specified by 1-4 bits of number suffixed by either M (Megabytes) or G (Gigabytes). And the number should be an integer.
[ "Live", "resize", "memory", "of", "guests", "." ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/api.py#L666-L682
train
43,532
mfcloud/python-zvm-sdk
zvmsdk/api.py
SDKAPI.guest_resize_mem
def guest_resize_mem(self, userid, size): """Resize memory of guests. :param userid: (str) the userid of the guest to be resized :param size: (str) The memory size that the guest should have defined in user directory after resize. The value should be specified by 1-4 bits of number suffixed by either M (Megabytes) or G (Gigabytes). And the number should be an integer. """ action = "resize guest '%s' to have '%s' memory" % (userid, size) LOG.info("Begin to %s" % action) with zvmutils.log_and_reraise_sdkbase_error(action): self._vmops.resize_memory(userid, size) LOG.info("%s successfully." % action)
python
def guest_resize_mem(self, userid, size): """Resize memory of guests. :param userid: (str) the userid of the guest to be resized :param size: (str) The memory size that the guest should have defined in user directory after resize. The value should be specified by 1-4 bits of number suffixed by either M (Megabytes) or G (Gigabytes). And the number should be an integer. """ action = "resize guest '%s' to have '%s' memory" % (userid, size) LOG.info("Begin to %s" % action) with zvmutils.log_and_reraise_sdkbase_error(action): self._vmops.resize_memory(userid, size) LOG.info("%s successfully." % action)
[ "def", "guest_resize_mem", "(", "self", ",", "userid", ",", "size", ")", ":", "action", "=", "\"resize guest '%s' to have '%s' memory\"", "%", "(", "userid", ",", "size", ")", "LOG", ".", "info", "(", "\"Begin to %s\"", "%", "action", ")", "with", "zvmutils", ...
Resize memory of guests. :param userid: (str) the userid of the guest to be resized :param size: (str) The memory size that the guest should have defined in user directory after resize. The value should be specified by 1-4 bits of number suffixed by either M (Megabytes) or G (Gigabytes). And the number should be an integer.
[ "Resize", "memory", "of", "guests", "." ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/api.py#L685-L700
train
43,533
mfcloud/python-zvm-sdk
zvmsdk/api.py
SDKAPI.guest_create_disks
def guest_create_disks(self, userid, disk_list): """Add disks to an existing guest vm. :param userid: (str) the userid of the vm to be created :param disk_list: (list) a list of disks info for the guest. It has one dictionary that contain some of the below keys for each disk, the root disk should be the first element in the list, the format is: {'size': str, 'format': str, 'is_boot_disk': bool, 'disk_pool': str} In which, 'size': case insensitive, the unit can be in Megabytes (M), Gigabytes (G), or number of cylinders/blocks, eg 512M, 1g or just 2000. 'format': optional, can be ext2, ext3, ext4, xfs, if not specified, the disk will not be formatted. 'is_boot_disk': For root disk, this key must be set to indicate the image that will be deployed on this disk. 'disk_pool': optional, if not specified, the disk will be created by using the value from configure file,the format is ECKD:eckdpoolname or FBA:fbapoolname. For example: [{'size': '1g', 'is_boot_disk': True, 'disk_pool': 'ECKD:eckdpool1'}, {'size': '200000', 'disk_pool': 'FBA:fbapool1', 'format': 'ext3'}] In this case it will create one disk 0100(in case the vdev for root disk is 0100) with size 1g from ECKD disk pool eckdpool1 for guest , then set IPL 0100 in guest's user directory, and it will create 0101 with 200000 blocks from FBA disk pool fbapool1, and formated with ext3. """ if disk_list == [] or disk_list is None: # nothing to do LOG.debug("No disk specified when calling guest_create_disks, " "nothing happened") return action = "create disks '%s' for guest '%s'" % (str(disk_list), userid) with zvmutils.log_and_reraise_sdkbase_error(action): return self._vmops.create_disks(userid, disk_list)
python
def guest_create_disks(self, userid, disk_list): """Add disks to an existing guest vm. :param userid: (str) the userid of the vm to be created :param disk_list: (list) a list of disks info for the guest. It has one dictionary that contain some of the below keys for each disk, the root disk should be the first element in the list, the format is: {'size': str, 'format': str, 'is_boot_disk': bool, 'disk_pool': str} In which, 'size': case insensitive, the unit can be in Megabytes (M), Gigabytes (G), or number of cylinders/blocks, eg 512M, 1g or just 2000. 'format': optional, can be ext2, ext3, ext4, xfs, if not specified, the disk will not be formatted. 'is_boot_disk': For root disk, this key must be set to indicate the image that will be deployed on this disk. 'disk_pool': optional, if not specified, the disk will be created by using the value from configure file,the format is ECKD:eckdpoolname or FBA:fbapoolname. For example: [{'size': '1g', 'is_boot_disk': True, 'disk_pool': 'ECKD:eckdpool1'}, {'size': '200000', 'disk_pool': 'FBA:fbapool1', 'format': 'ext3'}] In this case it will create one disk 0100(in case the vdev for root disk is 0100) with size 1g from ECKD disk pool eckdpool1 for guest , then set IPL 0100 in guest's user directory, and it will create 0101 with 200000 blocks from FBA disk pool fbapool1, and formated with ext3. """ if disk_list == [] or disk_list is None: # nothing to do LOG.debug("No disk specified when calling guest_create_disks, " "nothing happened") return action = "create disks '%s' for guest '%s'" % (str(disk_list), userid) with zvmutils.log_and_reraise_sdkbase_error(action): return self._vmops.create_disks(userid, disk_list)
[ "def", "guest_create_disks", "(", "self", ",", "userid", ",", "disk_list", ")", ":", "if", "disk_list", "==", "[", "]", "or", "disk_list", "is", "None", ":", "# nothing to do", "LOG", ".", "debug", "(", "\"No disk specified when calling guest_create_disks, \"", "\...
Add disks to an existing guest vm. :param userid: (str) the userid of the vm to be created :param disk_list: (list) a list of disks info for the guest. It has one dictionary that contain some of the below keys for each disk, the root disk should be the first element in the list, the format is: {'size': str, 'format': str, 'is_boot_disk': bool, 'disk_pool': str} In which, 'size': case insensitive, the unit can be in Megabytes (M), Gigabytes (G), or number of cylinders/blocks, eg 512M, 1g or just 2000. 'format': optional, can be ext2, ext3, ext4, xfs, if not specified, the disk will not be formatted. 'is_boot_disk': For root disk, this key must be set to indicate the image that will be deployed on this disk. 'disk_pool': optional, if not specified, the disk will be created by using the value from configure file,the format is ECKD:eckdpoolname or FBA:fbapoolname. For example: [{'size': '1g', 'is_boot_disk': True, 'disk_pool': 'ECKD:eckdpool1'}, {'size': '200000', 'disk_pool': 'FBA:fbapool1', 'format': 'ext3'}] In this case it will create one disk 0100(in case the vdev for root disk is 0100) with size 1g from ECKD disk pool eckdpool1 for guest , then set IPL 0100 in guest's user directory, and it will create 0101 with 200000 blocks from FBA disk pool fbapool1, and formated with ext3.
[ "Add", "disks", "to", "an", "existing", "guest", "vm", "." ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/api.py#L703-L748
train
43,534
mfcloud/python-zvm-sdk
zvmsdk/api.py
SDKAPI.guest_delete_disks
def guest_delete_disks(self, userid, disk_vdev_list): """Delete disks from an existing guest vm. :param userid: (str) the userid of the vm to be deleted :param disk_vdev_list: (list) the vdev list of disks to be deleted, for example: ['0101', '0102'] """ action = "delete disks '%s' from guest '%s'" % (str(disk_vdev_list), userid) with zvmutils.log_and_reraise_sdkbase_error(action): self._vmops.delete_disks(userid, disk_vdev_list)
python
def guest_delete_disks(self, userid, disk_vdev_list): """Delete disks from an existing guest vm. :param userid: (str) the userid of the vm to be deleted :param disk_vdev_list: (list) the vdev list of disks to be deleted, for example: ['0101', '0102'] """ action = "delete disks '%s' from guest '%s'" % (str(disk_vdev_list), userid) with zvmutils.log_and_reraise_sdkbase_error(action): self._vmops.delete_disks(userid, disk_vdev_list)
[ "def", "guest_delete_disks", "(", "self", ",", "userid", ",", "disk_vdev_list", ")", ":", "action", "=", "\"delete disks '%s' from guest '%s'\"", "%", "(", "str", "(", "disk_vdev_list", ")", ",", "userid", ")", "with", "zvmutils", ".", "log_and_reraise_sdkbase_error...
Delete disks from an existing guest vm. :param userid: (str) the userid of the vm to be deleted :param disk_vdev_list: (list) the vdev list of disks to be deleted, for example: ['0101', '0102']
[ "Delete", "disks", "from", "an", "existing", "guest", "vm", "." ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/api.py#L751-L761
train
43,535
mfcloud/python-zvm-sdk
zvmsdk/api.py
SDKAPI.guest_nic_couple_to_vswitch
def guest_nic_couple_to_vswitch(self, userid, nic_vdev, vswitch_name, active=False): """ Couple nic device to specified vswitch. :param str userid: the user's name who owns the nic :param str nic_vdev: nic device number, 1- to 4- hexadecimal digits :param str vswitch_name: the name of the vswitch :param bool active: whether make the change on active guest system """ self._networkops.couple_nic_to_vswitch(userid, nic_vdev, vswitch_name, active=active)
python
def guest_nic_couple_to_vswitch(self, userid, nic_vdev, vswitch_name, active=False): """ Couple nic device to specified vswitch. :param str userid: the user's name who owns the nic :param str nic_vdev: nic device number, 1- to 4- hexadecimal digits :param str vswitch_name: the name of the vswitch :param bool active: whether make the change on active guest system """ self._networkops.couple_nic_to_vswitch(userid, nic_vdev, vswitch_name, active=active)
[ "def", "guest_nic_couple_to_vswitch", "(", "self", ",", "userid", ",", "nic_vdev", ",", "vswitch_name", ",", "active", "=", "False", ")", ":", "self", ".", "_networkops", ".", "couple_nic_to_vswitch", "(", "userid", ",", "nic_vdev", ",", "vswitch_name", ",", "...
Couple nic device to specified vswitch. :param str userid: the user's name who owns the nic :param str nic_vdev: nic device number, 1- to 4- hexadecimal digits :param str vswitch_name: the name of the vswitch :param bool active: whether make the change on active guest system
[ "Couple", "nic", "device", "to", "specified", "vswitch", "." ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/api.py#L764-L774
train
43,536
mfcloud/python-zvm-sdk
zvmsdk/api.py
SDKAPI.guest_nic_uncouple_from_vswitch
def guest_nic_uncouple_from_vswitch(self, userid, nic_vdev, active=False): """ Disonnect nic device with network. :param str userid: the user's name who owns the nic :param str nic_vdev: nic device number, 1- to 4- hexadecimal digits :param bool active: whether make the change on active guest system """ self._networkops.uncouple_nic_from_vswitch(userid, nic_vdev, active=active)
python
def guest_nic_uncouple_from_vswitch(self, userid, nic_vdev, active=False): """ Disonnect nic device with network. :param str userid: the user's name who owns the nic :param str nic_vdev: nic device number, 1- to 4- hexadecimal digits :param bool active: whether make the change on active guest system """ self._networkops.uncouple_nic_from_vswitch(userid, nic_vdev, active=active)
[ "def", "guest_nic_uncouple_from_vswitch", "(", "self", ",", "userid", ",", "nic_vdev", ",", "active", "=", "False", ")", ":", "self", ".", "_networkops", ".", "uncouple_nic_from_vswitch", "(", "userid", ",", "nic_vdev", ",", "active", "=", "active", ")" ]
Disonnect nic device with network. :param str userid: the user's name who owns the nic :param str nic_vdev: nic device number, 1- to 4- hexadecimal digits :param bool active: whether make the change on active guest system
[ "Disonnect", "nic", "device", "with", "network", "." ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/api.py#L777-L786
train
43,537
mfcloud/python-zvm-sdk
zvmsdk/api.py
SDKAPI.vswitch_create
def vswitch_create(self, name, rdev=None, controller='*', connection='CONNECT', network_type='ETHERNET', router="NONROUTER", vid='UNAWARE', port_type='ACCESS', gvrp='GVRP', queue_mem=8, native_vid=1, persist=True): """ Create vswitch. :param str name: the vswitch name :param str rdev: the real device number, a maximum of three devices, all 1-4 characters in length, delimited by blanks. 'NONE' may also be specified :param str controller: the vswitch's controller, it could be the userid controlling the real device, or '*' to specifies that any available controller may be used :param str connection: - CONnect: Activate the real device connection. - DISCONnect: Do not activate the real device connection. - NOUPLINK: The vswitch will never have connectivity through the UPLINK port :param str network_type: Specifies the transport mechanism to be used for the vswitch, as follows: IP, ETHERNET :param str router: - NONrouter: The OSA-Express device identified in real_device_address= will not act as a router to the vswitch - PRIrouter: The OSA-Express device identified in real_device_address= will act as a primary router to the vswitch - Note: If the network_type is ETHERNET, this value must be unspecified, otherwise, if this value is unspecified, default is NONROUTER :param str/int vid: the VLAN ID. This can be any of the following values: UNAWARE, AWARE or 1-4094 :param str port_type: - ACCESS: The default porttype attribute for guests authorized for the virtual switch. The guest is unaware of VLAN IDs and sends and receives only untagged traffic - TRUNK: The default porttype attribute for guests authorized for the virtual switch. The guest is VLAN aware and sends and receives tagged traffic for those VLANs to which the guest is authorized. If the guest is also authorized to the natvid, untagged traffic sent or received by the guest is associated with the native VLAN ID (natvid) of the virtual switch. :param str gvrp: - GVRP: Indicates that the VLAN IDs in use on the virtual switch should be registered with GVRP-aware switches on the LAN. This provides dynamic VLAN registration and VLAN registration removal for networking switches. This eliminates the need to manually configure the individual port VLAN assignments. - NOGVRP: Do not register VLAN IDs with GVRP-aware switches on the LAN. When NOGVRP is specified VLAN port assignments must be configured manually :param int queue_mem: A number between 1 and 8, specifying the QDIO buffer size in megabytes. :param int native_vid: the native vlan id, 1-4094 or None :param bool persist: whether create the vswitch in the permanent configuration for the system """ if ((queue_mem < 1) or (queue_mem > 8)): errmsg = ('API vswitch_create: Invalid "queue_mem" input, ' 'it should be 1-8') raise exception.SDKInvalidInputFormat(msg=errmsg) if isinstance(vid, int) or vid.upper() != 'UNAWARE': if ((native_vid is not None) and ((native_vid < 1) or (native_vid > 4094))): errmsg = ('API vswitch_create: Invalid "native_vid" input, ' 'it should be 1-4094 or None') raise exception.SDKInvalidInputFormat(msg=errmsg) if network_type.upper() == 'ETHERNET': router = None self._networkops.add_vswitch(name, rdev=rdev, controller=controller, connection=connection, network_type=network_type, router=router, vid=vid, port_type=port_type, gvrp=gvrp, queue_mem=queue_mem, native_vid=native_vid, persist=persist)
python
def vswitch_create(self, name, rdev=None, controller='*', connection='CONNECT', network_type='ETHERNET', router="NONROUTER", vid='UNAWARE', port_type='ACCESS', gvrp='GVRP', queue_mem=8, native_vid=1, persist=True): """ Create vswitch. :param str name: the vswitch name :param str rdev: the real device number, a maximum of three devices, all 1-4 characters in length, delimited by blanks. 'NONE' may also be specified :param str controller: the vswitch's controller, it could be the userid controlling the real device, or '*' to specifies that any available controller may be used :param str connection: - CONnect: Activate the real device connection. - DISCONnect: Do not activate the real device connection. - NOUPLINK: The vswitch will never have connectivity through the UPLINK port :param str network_type: Specifies the transport mechanism to be used for the vswitch, as follows: IP, ETHERNET :param str router: - NONrouter: The OSA-Express device identified in real_device_address= will not act as a router to the vswitch - PRIrouter: The OSA-Express device identified in real_device_address= will act as a primary router to the vswitch - Note: If the network_type is ETHERNET, this value must be unspecified, otherwise, if this value is unspecified, default is NONROUTER :param str/int vid: the VLAN ID. This can be any of the following values: UNAWARE, AWARE or 1-4094 :param str port_type: - ACCESS: The default porttype attribute for guests authorized for the virtual switch. The guest is unaware of VLAN IDs and sends and receives only untagged traffic - TRUNK: The default porttype attribute for guests authorized for the virtual switch. The guest is VLAN aware and sends and receives tagged traffic for those VLANs to which the guest is authorized. If the guest is also authorized to the natvid, untagged traffic sent or received by the guest is associated with the native VLAN ID (natvid) of the virtual switch. :param str gvrp: - GVRP: Indicates that the VLAN IDs in use on the virtual switch should be registered with GVRP-aware switches on the LAN. This provides dynamic VLAN registration and VLAN registration removal for networking switches. This eliminates the need to manually configure the individual port VLAN assignments. - NOGVRP: Do not register VLAN IDs with GVRP-aware switches on the LAN. When NOGVRP is specified VLAN port assignments must be configured manually :param int queue_mem: A number between 1 and 8, specifying the QDIO buffer size in megabytes. :param int native_vid: the native vlan id, 1-4094 or None :param bool persist: whether create the vswitch in the permanent configuration for the system """ if ((queue_mem < 1) or (queue_mem > 8)): errmsg = ('API vswitch_create: Invalid "queue_mem" input, ' 'it should be 1-8') raise exception.SDKInvalidInputFormat(msg=errmsg) if isinstance(vid, int) or vid.upper() != 'UNAWARE': if ((native_vid is not None) and ((native_vid < 1) or (native_vid > 4094))): errmsg = ('API vswitch_create: Invalid "native_vid" input, ' 'it should be 1-4094 or None') raise exception.SDKInvalidInputFormat(msg=errmsg) if network_type.upper() == 'ETHERNET': router = None self._networkops.add_vswitch(name, rdev=rdev, controller=controller, connection=connection, network_type=network_type, router=router, vid=vid, port_type=port_type, gvrp=gvrp, queue_mem=queue_mem, native_vid=native_vid, persist=persist)
[ "def", "vswitch_create", "(", "self", ",", "name", ",", "rdev", "=", "None", ",", "controller", "=", "'*'", ",", "connection", "=", "'CONNECT'", ",", "network_type", "=", "'ETHERNET'", ",", "router", "=", "\"NONROUTER\"", ",", "vid", "=", "'UNAWARE'", ",",...
Create vswitch. :param str name: the vswitch name :param str rdev: the real device number, a maximum of three devices, all 1-4 characters in length, delimited by blanks. 'NONE' may also be specified :param str controller: the vswitch's controller, it could be the userid controlling the real device, or '*' to specifies that any available controller may be used :param str connection: - CONnect: Activate the real device connection. - DISCONnect: Do not activate the real device connection. - NOUPLINK: The vswitch will never have connectivity through the UPLINK port :param str network_type: Specifies the transport mechanism to be used for the vswitch, as follows: IP, ETHERNET :param str router: - NONrouter: The OSA-Express device identified in real_device_address= will not act as a router to the vswitch - PRIrouter: The OSA-Express device identified in real_device_address= will act as a primary router to the vswitch - Note: If the network_type is ETHERNET, this value must be unspecified, otherwise, if this value is unspecified, default is NONROUTER :param str/int vid: the VLAN ID. This can be any of the following values: UNAWARE, AWARE or 1-4094 :param str port_type: - ACCESS: The default porttype attribute for guests authorized for the virtual switch. The guest is unaware of VLAN IDs and sends and receives only untagged traffic - TRUNK: The default porttype attribute for guests authorized for the virtual switch. The guest is VLAN aware and sends and receives tagged traffic for those VLANs to which the guest is authorized. If the guest is also authorized to the natvid, untagged traffic sent or received by the guest is associated with the native VLAN ID (natvid) of the virtual switch. :param str gvrp: - GVRP: Indicates that the VLAN IDs in use on the virtual switch should be registered with GVRP-aware switches on the LAN. This provides dynamic VLAN registration and VLAN registration removal for networking switches. This eliminates the need to manually configure the individual port VLAN assignments. - NOGVRP: Do not register VLAN IDs with GVRP-aware switches on the LAN. When NOGVRP is specified VLAN port assignments must be configured manually :param int queue_mem: A number between 1 and 8, specifying the QDIO buffer size in megabytes. :param int native_vid: the native vlan id, 1-4094 or None :param bool persist: whether create the vswitch in the permanent configuration for the system
[ "Create", "vswitch", "." ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/api.py#L796-L888
train
43,538
mfcloud/python-zvm-sdk
zvmsdk/api.py
SDKAPI.guest_get_console_output
def guest_get_console_output(self, userid): """Get the console output of the guest virtual machine. :param str userid: the user id of the vm :returns: console log string :rtype: str """ action = "get the console output of guest '%s'" % userid with zvmutils.log_and_reraise_sdkbase_error(action): output = self._vmops.get_console_output(userid) return output
python
def guest_get_console_output(self, userid): """Get the console output of the guest virtual machine. :param str userid: the user id of the vm :returns: console log string :rtype: str """ action = "get the console output of guest '%s'" % userid with zvmutils.log_and_reraise_sdkbase_error(action): output = self._vmops.get_console_output(userid) return output
[ "def", "guest_get_console_output", "(", "self", ",", "userid", ")", ":", "action", "=", "\"get the console output of guest '%s'\"", "%", "userid", "with", "zvmutils", ".", "log_and_reraise_sdkbase_error", "(", "action", ")", ":", "output", "=", "self", ".", "_vmops"...
Get the console output of the guest virtual machine. :param str userid: the user id of the vm :returns: console log string :rtype: str
[ "Get", "the", "console", "output", "of", "the", "guest", "virtual", "machine", "." ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/api.py#L891-L902
train
43,539
mfcloud/python-zvm-sdk
zvmsdk/api.py
SDKAPI.guest_delete
def guest_delete(self, userid): """Delete guest. :param userid: the user id of the vm """ # check guest exist in database or not userid = userid.upper() if not self._vmops.check_guests_exist_in_db(userid, raise_exc=False): if zvmutils.check_userid_exist(userid): LOG.error("Guest '%s' does not exist in guests database" % userid) raise exception.SDKObjectNotExistError( obj_desc=("Guest '%s'" % userid), modID='guest') else: LOG.debug("The guest %s does not exist." % userid) return action = "delete guest '%s'" % userid with zvmutils.log_and_reraise_sdkbase_error(action): return self._vmops.delete_vm(userid)
python
def guest_delete(self, userid): """Delete guest. :param userid: the user id of the vm """ # check guest exist in database or not userid = userid.upper() if not self._vmops.check_guests_exist_in_db(userid, raise_exc=False): if zvmutils.check_userid_exist(userid): LOG.error("Guest '%s' does not exist in guests database" % userid) raise exception.SDKObjectNotExistError( obj_desc=("Guest '%s'" % userid), modID='guest') else: LOG.debug("The guest %s does not exist." % userid) return action = "delete guest '%s'" % userid with zvmutils.log_and_reraise_sdkbase_error(action): return self._vmops.delete_vm(userid)
[ "def", "guest_delete", "(", "self", ",", "userid", ")", ":", "# check guest exist in database or not", "userid", "=", "userid", ".", "upper", "(", ")", "if", "not", "self", ".", "_vmops", ".", "check_guests_exist_in_db", "(", "userid", ",", "raise_exc", "=", "...
Delete guest. :param userid: the user id of the vm
[ "Delete", "guest", "." ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/api.py#L904-L924
train
43,540
mfcloud/python-zvm-sdk
zvmsdk/api.py
SDKAPI.guest_inspect_stats
def guest_inspect_stats(self, userid_list): """Get the statistics including cpu and mem of the guests :param userid_list: a single userid string or a list of guest userids :returns: dictionary describing the cpu statistics of the vm in the form {'UID1': { 'guest_cpus': xx, 'used_cpu_time_us': xx, 'elapsed_cpu_time_us': xx, 'min_cpu_count': xx, 'max_cpu_limit': xx, 'samples_cpu_in_use': xx, 'samples_cpu_delay': xx, 'used_mem_kb': xx, 'max_mem_kb': xx, 'min_mem_kb': xx, 'shared_mem_kb': xx }, 'UID2': { 'guest_cpus': xx, 'used_cpu_time_us': xx, 'elapsed_cpu_time_us': xx, 'min_cpu_count': xx, 'max_cpu_limit': xx, 'samples_cpu_in_use': xx, 'samples_cpu_delay': xx, 'used_mem_kb': xx, 'max_mem_kb': xx, 'min_mem_kb': xx, 'shared_mem_kb': xx } } for the guests that are shutdown or not exist, no data returned in the dictionary """ if not isinstance(userid_list, list): userid_list = [userid_list] action = "get the statistics of guest '%s'" % str(userid_list) with zvmutils.log_and_reraise_sdkbase_error(action): return self._monitor.inspect_stats(userid_list)
python
def guest_inspect_stats(self, userid_list): """Get the statistics including cpu and mem of the guests :param userid_list: a single userid string or a list of guest userids :returns: dictionary describing the cpu statistics of the vm in the form {'UID1': { 'guest_cpus': xx, 'used_cpu_time_us': xx, 'elapsed_cpu_time_us': xx, 'min_cpu_count': xx, 'max_cpu_limit': xx, 'samples_cpu_in_use': xx, 'samples_cpu_delay': xx, 'used_mem_kb': xx, 'max_mem_kb': xx, 'min_mem_kb': xx, 'shared_mem_kb': xx }, 'UID2': { 'guest_cpus': xx, 'used_cpu_time_us': xx, 'elapsed_cpu_time_us': xx, 'min_cpu_count': xx, 'max_cpu_limit': xx, 'samples_cpu_in_use': xx, 'samples_cpu_delay': xx, 'used_mem_kb': xx, 'max_mem_kb': xx, 'min_mem_kb': xx, 'shared_mem_kb': xx } } for the guests that are shutdown or not exist, no data returned in the dictionary """ if not isinstance(userid_list, list): userid_list = [userid_list] action = "get the statistics of guest '%s'" % str(userid_list) with zvmutils.log_and_reraise_sdkbase_error(action): return self._monitor.inspect_stats(userid_list)
[ "def", "guest_inspect_stats", "(", "self", ",", "userid_list", ")", ":", "if", "not", "isinstance", "(", "userid_list", ",", "list", ")", ":", "userid_list", "=", "[", "userid_list", "]", "action", "=", "\"get the statistics of guest '%s'\"", "%", "str", "(", ...
Get the statistics including cpu and mem of the guests :param userid_list: a single userid string or a list of guest userids :returns: dictionary describing the cpu statistics of the vm in the form {'UID1': { 'guest_cpus': xx, 'used_cpu_time_us': xx, 'elapsed_cpu_time_us': xx, 'min_cpu_count': xx, 'max_cpu_limit': xx, 'samples_cpu_in_use': xx, 'samples_cpu_delay': xx, 'used_mem_kb': xx, 'max_mem_kb': xx, 'min_mem_kb': xx, 'shared_mem_kb': xx }, 'UID2': { 'guest_cpus': xx, 'used_cpu_time_us': xx, 'elapsed_cpu_time_us': xx, 'min_cpu_count': xx, 'max_cpu_limit': xx, 'samples_cpu_in_use': xx, 'samples_cpu_delay': xx, 'used_mem_kb': xx, 'max_mem_kb': xx, 'min_mem_kb': xx, 'shared_mem_kb': xx } } for the guests that are shutdown or not exist, no data returned in the dictionary
[ "Get", "the", "statistics", "including", "cpu", "and", "mem", "of", "the", "guests" ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/api.py#L927-L968
train
43,541
mfcloud/python-zvm-sdk
zvmsdk/api.py
SDKAPI.guest_inspect_vnics
def guest_inspect_vnics(self, userid_list): """Get the vnics statistics of the guest virtual machines :param userid_list: a single userid string or a list of guest userids :returns: dictionary describing the vnics statistics of the vm in the form {'UID1': [{ 'vswitch_name': xx, 'nic_vdev': xx, 'nic_fr_rx': xx, 'nic_fr_tx': xx, 'nic_fr_rx_dsc': xx, 'nic_fr_tx_dsc': xx, 'nic_fr_rx_err': xx, 'nic_fr_tx_err': xx, 'nic_rx': xx, 'nic_tx': xx }, ], 'UID2': [{ 'vswitch_name': xx, 'nic_vdev': xx, 'nic_fr_rx': xx, 'nic_fr_tx': xx, 'nic_fr_rx_dsc': xx, 'nic_fr_tx_dsc': xx, 'nic_fr_rx_err': xx, 'nic_fr_tx_err': xx, 'nic_rx': xx, 'nic_tx': xx }, ] } for the guests that are shutdown or not exist, no data returned in the dictionary """ if not isinstance(userid_list, list): userid_list = [userid_list] action = "get the vnics statistics of guest '%s'" % str(userid_list) with zvmutils.log_and_reraise_sdkbase_error(action): return self._monitor.inspect_vnics(userid_list)
python
def guest_inspect_vnics(self, userid_list): """Get the vnics statistics of the guest virtual machines :param userid_list: a single userid string or a list of guest userids :returns: dictionary describing the vnics statistics of the vm in the form {'UID1': [{ 'vswitch_name': xx, 'nic_vdev': xx, 'nic_fr_rx': xx, 'nic_fr_tx': xx, 'nic_fr_rx_dsc': xx, 'nic_fr_tx_dsc': xx, 'nic_fr_rx_err': xx, 'nic_fr_tx_err': xx, 'nic_rx': xx, 'nic_tx': xx }, ], 'UID2': [{ 'vswitch_name': xx, 'nic_vdev': xx, 'nic_fr_rx': xx, 'nic_fr_tx': xx, 'nic_fr_rx_dsc': xx, 'nic_fr_tx_dsc': xx, 'nic_fr_rx_err': xx, 'nic_fr_tx_err': xx, 'nic_rx': xx, 'nic_tx': xx }, ] } for the guests that are shutdown or not exist, no data returned in the dictionary """ if not isinstance(userid_list, list): userid_list = [userid_list] action = "get the vnics statistics of guest '%s'" % str(userid_list) with zvmutils.log_and_reraise_sdkbase_error(action): return self._monitor.inspect_vnics(userid_list)
[ "def", "guest_inspect_vnics", "(", "self", ",", "userid_list", ")", ":", "if", "not", "isinstance", "(", "userid_list", ",", "list", ")", ":", "userid_list", "=", "[", "userid_list", "]", "action", "=", "\"get the vnics statistics of guest '%s'\"", "%", "str", "...
Get the vnics statistics of the guest virtual machines :param userid_list: a single userid string or a list of guest userids :returns: dictionary describing the vnics statistics of the vm in the form {'UID1': [{ 'vswitch_name': xx, 'nic_vdev': xx, 'nic_fr_rx': xx, 'nic_fr_tx': xx, 'nic_fr_rx_dsc': xx, 'nic_fr_tx_dsc': xx, 'nic_fr_rx_err': xx, 'nic_fr_tx_err': xx, 'nic_rx': xx, 'nic_tx': xx }, ], 'UID2': [{ 'vswitch_name': xx, 'nic_vdev': xx, 'nic_fr_rx': xx, 'nic_fr_tx': xx, 'nic_fr_rx_dsc': xx, 'nic_fr_tx_dsc': xx, 'nic_fr_rx_err': xx, 'nic_fr_tx_err': xx, 'nic_rx': xx, 'nic_tx': xx }, ] } for the guests that are shutdown or not exist, no data returned in the dictionary
[ "Get", "the", "vnics", "statistics", "of", "the", "guest", "virtual", "machines" ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/api.py#L971-L1013
train
43,542
mfcloud/python-zvm-sdk
zvmsdk/api.py
SDKAPI.vswitch_set_vlan_id_for_user
def vswitch_set_vlan_id_for_user(self, vswitch_name, userid, vlan_id): """Set vlan id for user when connecting to the vswitch :param str vswitch_name: the name of the vswitch :param str userid: the user id of the vm :param int vlan_id: the VLAN id """ self._networkops.set_vswitch_port_vlan_id(vswitch_name, userid, vlan_id)
python
def vswitch_set_vlan_id_for_user(self, vswitch_name, userid, vlan_id): """Set vlan id for user when connecting to the vswitch :param str vswitch_name: the name of the vswitch :param str userid: the user id of the vm :param int vlan_id: the VLAN id """ self._networkops.set_vswitch_port_vlan_id(vswitch_name, userid, vlan_id)
[ "def", "vswitch_set_vlan_id_for_user", "(", "self", ",", "vswitch_name", ",", "userid", ",", "vlan_id", ")", ":", "self", ".", "_networkops", ".", "set_vswitch_port_vlan_id", "(", "vswitch_name", ",", "userid", ",", "vlan_id", ")" ]
Set vlan id for user when connecting to the vswitch :param str vswitch_name: the name of the vswitch :param str userid: the user id of the vm :param int vlan_id: the VLAN id
[ "Set", "vlan", "id", "for", "user", "when", "connecting", "to", "the", "vswitch" ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/api.py#L1035-L1043
train
43,543
mfcloud/python-zvm-sdk
zvmsdk/api.py
SDKAPI.guest_config_minidisks
def guest_config_minidisks(self, userid, disk_info): """Punch the script that used to process additional disks to vm :param str userid: the user id of the vm :param disk_info: a list contains disks info for the guest. It contains dictionaries that describes disk info for each disk. Each dictionary has 3 keys, format is required, vdev and mntdir are optional. For example, if vdev is not specified, it will start from the next vdev of CONF.zvm.user_root_vdev, eg. if CONF.zvm.user_root_vdev is 0100, zvmsdk will use 0101 as the vdev for first additional disk in disk_info, and if mntdir is not specified, zvmsdk will use /mnt/ephemeral0 as the mount point of first additional disk Here are some examples: [{'vdev': '0101', 'format': 'ext3', 'mntdir': '/mnt/ephemeral0'}] In this case, the zvmsdk will treat 0101 as additional disk's vdev, and it's formatted with ext3, and will be mounted to /mnt/ephemeral0 [{'format': 'ext3'}, {'format': 'ext4'}] In this case, if CONF.zvm.user_root_vdev is 0100, zvmsdk will configure the first additional disk as 0101, mount it to /mnt/ephemeral0 with ext3, and configure the second additional disk 0102, mount it to /mnt/ephemeral1 with ext4. """ action = "config disks for userid '%s'" % userid with zvmutils.log_and_reraise_sdkbase_error(action): self._vmops.guest_config_minidisks(userid, disk_info)
python
def guest_config_minidisks(self, userid, disk_info): """Punch the script that used to process additional disks to vm :param str userid: the user id of the vm :param disk_info: a list contains disks info for the guest. It contains dictionaries that describes disk info for each disk. Each dictionary has 3 keys, format is required, vdev and mntdir are optional. For example, if vdev is not specified, it will start from the next vdev of CONF.zvm.user_root_vdev, eg. if CONF.zvm.user_root_vdev is 0100, zvmsdk will use 0101 as the vdev for first additional disk in disk_info, and if mntdir is not specified, zvmsdk will use /mnt/ephemeral0 as the mount point of first additional disk Here are some examples: [{'vdev': '0101', 'format': 'ext3', 'mntdir': '/mnt/ephemeral0'}] In this case, the zvmsdk will treat 0101 as additional disk's vdev, and it's formatted with ext3, and will be mounted to /mnt/ephemeral0 [{'format': 'ext3'}, {'format': 'ext4'}] In this case, if CONF.zvm.user_root_vdev is 0100, zvmsdk will configure the first additional disk as 0101, mount it to /mnt/ephemeral0 with ext3, and configure the second additional disk 0102, mount it to /mnt/ephemeral1 with ext4. """ action = "config disks for userid '%s'" % userid with zvmutils.log_and_reraise_sdkbase_error(action): self._vmops.guest_config_minidisks(userid, disk_info)
[ "def", "guest_config_minidisks", "(", "self", ",", "userid", ",", "disk_info", ")", ":", "action", "=", "\"config disks for userid '%s'\"", "%", "userid", "with", "zvmutils", ".", "log_and_reraise_sdkbase_error", "(", "action", ")", ":", "self", ".", "_vmops", "."...
Punch the script that used to process additional disks to vm :param str userid: the user id of the vm :param disk_info: a list contains disks info for the guest. It contains dictionaries that describes disk info for each disk. Each dictionary has 3 keys, format is required, vdev and mntdir are optional. For example, if vdev is not specified, it will start from the next vdev of CONF.zvm.user_root_vdev, eg. if CONF.zvm.user_root_vdev is 0100, zvmsdk will use 0101 as the vdev for first additional disk in disk_info, and if mntdir is not specified, zvmsdk will use /mnt/ephemeral0 as the mount point of first additional disk Here are some examples: [{'vdev': '0101', 'format': 'ext3', 'mntdir': '/mnt/ephemeral0'}] In this case, the zvmsdk will treat 0101 as additional disk's vdev, and it's formatted with ext3, and will be mounted to /mnt/ephemeral0 [{'format': 'ext3'}, {'format': 'ext4'}] In this case, if CONF.zvm.user_root_vdev is 0100, zvmsdk will configure the first additional disk as 0101, mount it to /mnt/ephemeral0 with ext3, and configure the second additional disk 0102, mount it to /mnt/ephemeral1 with ext4.
[ "Punch", "the", "script", "that", "used", "to", "process", "additional", "disks", "to", "vm" ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/api.py#L1046-L1079
train
43,544
mfcloud/python-zvm-sdk
zvmsdk/api.py
SDKAPI.vswitch_set
def vswitch_set(self, vswitch_name, **kwargs): """Change the configuration of an existing virtual switch :param str vswitch_name: the name of the virtual switch :param dict kwargs: - grant_userid=<value>: A userid to be added to the access list - user_vlan_id=<value>: user VLAN ID. Support following ways: 1. As single values between 1 and 4094. A maximum of four values may be specified, separated by blanks. Example: 1010 2020 3030 4040 2. As a range of two numbers, separated by a dash (-). A maximum of two ranges may be specified. Example: 10-12 20-22 - revoke_userid=<value>: A userid to be removed from the access list - real_device_address=<value>: The real device address or the real device address and OSA Express port number of a QDIO OSA Express device to be used to create the switch to the virtual adapter. If using a real device and an OSA Express port number, specify the real device number followed by a period(.), the letter 'P' (or 'p'), followed by the port number as a hexadecimal number. A maximum of three device addresses, all 1-7 characters in length, may be specified, delimited by blanks. 'None' may also be specified - port_name=<value>: The name used to identify the OSA Expanded adapter. A maximum of three port names, all 1-8 characters in length, may be specified, delimited by blanks. - controller_name=<value>: One of the following: 1. The userid controlling the real device. A maximum of eight userids, all 1-8 characters in length, may be specified, delimited by blanks. 2. '*': Specifies that any available controller may be used - connection_value=<value>: One of the following values: CONnect: Activate the real device connection. DISCONnect: Do not activate the real device connection. - queue_memory_limit=<value>: A number between 1 and 8 specifying the QDIO buffer size in megabytes. - routing_value=<value>: Specifies whether the OSA-Express QDIO device will act as a router to the virtual switch, as follows: NONrouter: The OSA-Express device identified in real_device_address= will not act as a router to the vswitch PRIrouter: The OSA-Express device identified in real_device_address= will act as a primary router to the vswitch - port_type=<value>: Specifies the port type, ACCESS or TRUNK - persist=<value>: one of the following values: NO: The vswitch is updated on the active system, but is not updated in the permanent configuration for the system. YES: The vswitch is updated on the active system and also in the permanent configuration for the system. If not specified, the default is NO. - gvrp_value=<value>: GVRP or NOGVRP - mac_id=<value>: A unique identifier (up to six hexadecimal digits) used as part of the vswitch MAC address - uplink=<value>: One of the following: NO: The port being enabled is not the vswitch's UPLINK port. YES: The port being enabled is the vswitch's UPLINK port. - nic_userid=<value>: One of the following: 1. The userid of the port to/from which the UPLINK port will be connected or disconnected. If a userid is specified, then nic_vdev= must also be specified 2. '*': Disconnect the currently connected guest port to/from the special virtual switch UPLINK port. (This is equivalent to specifying NIC NONE on CP SET VSWITCH). - nic_vdev=<value>: The virtual device to/from which the the UPLINK port will be connected/disconnected. If this value is specified, nic_userid= must also be specified, with a userid. - lacp=<value>: One of the following values: ACTIVE: Indicates that the virtual switch will initiate negotiations with the physical switch via the link aggregation control protocol (LACP) and will respond to LACP packets sent by the physical switch. INACTIVE: Indicates that aggregation is to be performed, but without LACP. - Interval=<value>: The interval to be used by the control program (CP) when doing load balancing of conversations across multiple links in the group. This can be any of the following values: 1 - 9990: Indicates the number of seconds between load balancing operations across the link aggregation group. OFF: Indicates that no load balancing is done. - group_rdev=<value>: The real device address or the real device address and OSA Express port number of a QDIO OSA Express devcie to be affected within the link aggregation group associated with this vswitch. If using a real device and an OSA Express port number, specify the real device number followed by a period (.), the letter 'P' (or 'p'), followed by the port number as a hexadecimal number. A maximum of eight device addresses all 1-7 characters in length, may be specified, delimited by blanks. Note: If a real device address is specified, this device will be added to the link aggregation group associated with this vswitch. (The link aggregation group will be created if it does not already exist.) - iptimeout=<value>: A number between 1 and 240 specifying the length of time in minutes that a remote IP address table entry remains in the IP address table for the virtual switch. - port_isolation=<value>: ON or OFF - promiscuous=<value>: One of the following: NO: The userid or port on the grant is not authorized to use the vswitch in promiscuous mode YES: The userid or port on the grant is authorized to use the vswitch in promiscuous mode. - MAC_protect=<value>: ON, OFF or UNSPECified - VLAN_counters=<value>: ON or OFF """ for k in kwargs.keys(): if k not in constants.SET_VSWITCH_KEYWORDS: errmsg = ('API vswitch_set: Invalid keyword %s' % k) raise exception.SDKInvalidInputFormat(msg=errmsg) self._networkops.set_vswitch(vswitch_name, **kwargs)
python
def vswitch_set(self, vswitch_name, **kwargs): """Change the configuration of an existing virtual switch :param str vswitch_name: the name of the virtual switch :param dict kwargs: - grant_userid=<value>: A userid to be added to the access list - user_vlan_id=<value>: user VLAN ID. Support following ways: 1. As single values between 1 and 4094. A maximum of four values may be specified, separated by blanks. Example: 1010 2020 3030 4040 2. As a range of two numbers, separated by a dash (-). A maximum of two ranges may be specified. Example: 10-12 20-22 - revoke_userid=<value>: A userid to be removed from the access list - real_device_address=<value>: The real device address or the real device address and OSA Express port number of a QDIO OSA Express device to be used to create the switch to the virtual adapter. If using a real device and an OSA Express port number, specify the real device number followed by a period(.), the letter 'P' (or 'p'), followed by the port number as a hexadecimal number. A maximum of three device addresses, all 1-7 characters in length, may be specified, delimited by blanks. 'None' may also be specified - port_name=<value>: The name used to identify the OSA Expanded adapter. A maximum of three port names, all 1-8 characters in length, may be specified, delimited by blanks. - controller_name=<value>: One of the following: 1. The userid controlling the real device. A maximum of eight userids, all 1-8 characters in length, may be specified, delimited by blanks. 2. '*': Specifies that any available controller may be used - connection_value=<value>: One of the following values: CONnect: Activate the real device connection. DISCONnect: Do not activate the real device connection. - queue_memory_limit=<value>: A number between 1 and 8 specifying the QDIO buffer size in megabytes. - routing_value=<value>: Specifies whether the OSA-Express QDIO device will act as a router to the virtual switch, as follows: NONrouter: The OSA-Express device identified in real_device_address= will not act as a router to the vswitch PRIrouter: The OSA-Express device identified in real_device_address= will act as a primary router to the vswitch - port_type=<value>: Specifies the port type, ACCESS or TRUNK - persist=<value>: one of the following values: NO: The vswitch is updated on the active system, but is not updated in the permanent configuration for the system. YES: The vswitch is updated on the active system and also in the permanent configuration for the system. If not specified, the default is NO. - gvrp_value=<value>: GVRP or NOGVRP - mac_id=<value>: A unique identifier (up to six hexadecimal digits) used as part of the vswitch MAC address - uplink=<value>: One of the following: NO: The port being enabled is not the vswitch's UPLINK port. YES: The port being enabled is the vswitch's UPLINK port. - nic_userid=<value>: One of the following: 1. The userid of the port to/from which the UPLINK port will be connected or disconnected. If a userid is specified, then nic_vdev= must also be specified 2. '*': Disconnect the currently connected guest port to/from the special virtual switch UPLINK port. (This is equivalent to specifying NIC NONE on CP SET VSWITCH). - nic_vdev=<value>: The virtual device to/from which the the UPLINK port will be connected/disconnected. If this value is specified, nic_userid= must also be specified, with a userid. - lacp=<value>: One of the following values: ACTIVE: Indicates that the virtual switch will initiate negotiations with the physical switch via the link aggregation control protocol (LACP) and will respond to LACP packets sent by the physical switch. INACTIVE: Indicates that aggregation is to be performed, but without LACP. - Interval=<value>: The interval to be used by the control program (CP) when doing load balancing of conversations across multiple links in the group. This can be any of the following values: 1 - 9990: Indicates the number of seconds between load balancing operations across the link aggregation group. OFF: Indicates that no load balancing is done. - group_rdev=<value>: The real device address or the real device address and OSA Express port number of a QDIO OSA Express devcie to be affected within the link aggregation group associated with this vswitch. If using a real device and an OSA Express port number, specify the real device number followed by a period (.), the letter 'P' (or 'p'), followed by the port number as a hexadecimal number. A maximum of eight device addresses all 1-7 characters in length, may be specified, delimited by blanks. Note: If a real device address is specified, this device will be added to the link aggregation group associated with this vswitch. (The link aggregation group will be created if it does not already exist.) - iptimeout=<value>: A number between 1 and 240 specifying the length of time in minutes that a remote IP address table entry remains in the IP address table for the virtual switch. - port_isolation=<value>: ON or OFF - promiscuous=<value>: One of the following: NO: The userid or port on the grant is not authorized to use the vswitch in promiscuous mode YES: The userid or port on the grant is authorized to use the vswitch in promiscuous mode. - MAC_protect=<value>: ON, OFF or UNSPECified - VLAN_counters=<value>: ON or OFF """ for k in kwargs.keys(): if k not in constants.SET_VSWITCH_KEYWORDS: errmsg = ('API vswitch_set: Invalid keyword %s' % k) raise exception.SDKInvalidInputFormat(msg=errmsg) self._networkops.set_vswitch(vswitch_name, **kwargs)
[ "def", "vswitch_set", "(", "self", ",", "vswitch_name", ",", "*", "*", "kwargs", ")", ":", "for", "k", "in", "kwargs", ".", "keys", "(", ")", ":", "if", "k", "not", "in", "constants", ".", "SET_VSWITCH_KEYWORDS", ":", "errmsg", "=", "(", "'API vswitch_...
Change the configuration of an existing virtual switch :param str vswitch_name: the name of the virtual switch :param dict kwargs: - grant_userid=<value>: A userid to be added to the access list - user_vlan_id=<value>: user VLAN ID. Support following ways: 1. As single values between 1 and 4094. A maximum of four values may be specified, separated by blanks. Example: 1010 2020 3030 4040 2. As a range of two numbers, separated by a dash (-). A maximum of two ranges may be specified. Example: 10-12 20-22 - revoke_userid=<value>: A userid to be removed from the access list - real_device_address=<value>: The real device address or the real device address and OSA Express port number of a QDIO OSA Express device to be used to create the switch to the virtual adapter. If using a real device and an OSA Express port number, specify the real device number followed by a period(.), the letter 'P' (or 'p'), followed by the port number as a hexadecimal number. A maximum of three device addresses, all 1-7 characters in length, may be specified, delimited by blanks. 'None' may also be specified - port_name=<value>: The name used to identify the OSA Expanded adapter. A maximum of three port names, all 1-8 characters in length, may be specified, delimited by blanks. - controller_name=<value>: One of the following: 1. The userid controlling the real device. A maximum of eight userids, all 1-8 characters in length, may be specified, delimited by blanks. 2. '*': Specifies that any available controller may be used - connection_value=<value>: One of the following values: CONnect: Activate the real device connection. DISCONnect: Do not activate the real device connection. - queue_memory_limit=<value>: A number between 1 and 8 specifying the QDIO buffer size in megabytes. - routing_value=<value>: Specifies whether the OSA-Express QDIO device will act as a router to the virtual switch, as follows: NONrouter: The OSA-Express device identified in real_device_address= will not act as a router to the vswitch PRIrouter: The OSA-Express device identified in real_device_address= will act as a primary router to the vswitch - port_type=<value>: Specifies the port type, ACCESS or TRUNK - persist=<value>: one of the following values: NO: The vswitch is updated on the active system, but is not updated in the permanent configuration for the system. YES: The vswitch is updated on the active system and also in the permanent configuration for the system. If not specified, the default is NO. - gvrp_value=<value>: GVRP or NOGVRP - mac_id=<value>: A unique identifier (up to six hexadecimal digits) used as part of the vswitch MAC address - uplink=<value>: One of the following: NO: The port being enabled is not the vswitch's UPLINK port. YES: The port being enabled is the vswitch's UPLINK port. - nic_userid=<value>: One of the following: 1. The userid of the port to/from which the UPLINK port will be connected or disconnected. If a userid is specified, then nic_vdev= must also be specified 2. '*': Disconnect the currently connected guest port to/from the special virtual switch UPLINK port. (This is equivalent to specifying NIC NONE on CP SET VSWITCH). - nic_vdev=<value>: The virtual device to/from which the the UPLINK port will be connected/disconnected. If this value is specified, nic_userid= must also be specified, with a userid. - lacp=<value>: One of the following values: ACTIVE: Indicates that the virtual switch will initiate negotiations with the physical switch via the link aggregation control protocol (LACP) and will respond to LACP packets sent by the physical switch. INACTIVE: Indicates that aggregation is to be performed, but without LACP. - Interval=<value>: The interval to be used by the control program (CP) when doing load balancing of conversations across multiple links in the group. This can be any of the following values: 1 - 9990: Indicates the number of seconds between load balancing operations across the link aggregation group. OFF: Indicates that no load balancing is done. - group_rdev=<value>: The real device address or the real device address and OSA Express port number of a QDIO OSA Express devcie to be affected within the link aggregation group associated with this vswitch. If using a real device and an OSA Express port number, specify the real device number followed by a period (.), the letter 'P' (or 'p'), followed by the port number as a hexadecimal number. A maximum of eight device addresses all 1-7 characters in length, may be specified, delimited by blanks. Note: If a real device address is specified, this device will be added to the link aggregation group associated with this vswitch. (The link aggregation group will be created if it does not already exist.) - iptimeout=<value>: A number between 1 and 240 specifying the length of time in minutes that a remote IP address table entry remains in the IP address table for the virtual switch. - port_isolation=<value>: ON or OFF - promiscuous=<value>: One of the following: NO: The userid or port on the grant is not authorized to use the vswitch in promiscuous mode YES: The userid or port on the grant is authorized to use the vswitch in promiscuous mode. - MAC_protect=<value>: ON, OFF or UNSPECified - VLAN_counters=<value>: ON or OFF
[ "Change", "the", "configuration", "of", "an", "existing", "virtual", "switch" ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/api.py#L1081-L1215
train
43,545
mfcloud/python-zvm-sdk
zvmsdk/api.py
SDKAPI.vswitch_delete
def vswitch_delete(self, vswitch_name, persist=True): """ Delete vswitch. :param str name: the vswitch name :param bool persist: whether delete the vswitch from the permanent configuration for the system """ self._networkops.delete_vswitch(vswitch_name, persist)
python
def vswitch_delete(self, vswitch_name, persist=True): """ Delete vswitch. :param str name: the vswitch name :param bool persist: whether delete the vswitch from the permanent configuration for the system """ self._networkops.delete_vswitch(vswitch_name, persist)
[ "def", "vswitch_delete", "(", "self", ",", "vswitch_name", ",", "persist", "=", "True", ")", ":", "self", ".", "_networkops", ".", "delete_vswitch", "(", "vswitch_name", ",", "persist", ")" ]
Delete vswitch. :param str name: the vswitch name :param bool persist: whether delete the vswitch from the permanent configuration for the system
[ "Delete", "vswitch", "." ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/api.py#L1217-L1224
train
43,546
mfcloud/python-zvm-sdk
zvmsdk/api.py
SDKAPI.guests_get_nic_info
def guests_get_nic_info(self, userid=None, nic_id=None, vswitch=None): """ Retrieve nic information in the network database according to the requirements, the nic information will include the guest name, nic device number, vswitch name that the nic is coupled to, nic identifier and the comments. :param str userid: the user id of the vm :param str nic_id: nic identifier :param str vswitch: the name of the vswitch :returns: list describing nic information, format is [ (userid, interface, vswitch, nic_id, comments), (userid, interface, vswitch, nic_id, comments) ], such as [ ('VM01', '1000', 'xcatvsw2', '1111-2222', None), ('VM02', '2000', 'xcatvsw3', None, None) ] :rtype: list """ action = "get nic information" with zvmutils.log_and_reraise_sdkbase_error(action): return self._networkops.get_nic_info(userid=userid, nic_id=nic_id, vswitch=vswitch)
python
def guests_get_nic_info(self, userid=None, nic_id=None, vswitch=None): """ Retrieve nic information in the network database according to the requirements, the nic information will include the guest name, nic device number, vswitch name that the nic is coupled to, nic identifier and the comments. :param str userid: the user id of the vm :param str nic_id: nic identifier :param str vswitch: the name of the vswitch :returns: list describing nic information, format is [ (userid, interface, vswitch, nic_id, comments), (userid, interface, vswitch, nic_id, comments) ], such as [ ('VM01', '1000', 'xcatvsw2', '1111-2222', None), ('VM02', '2000', 'xcatvsw3', None, None) ] :rtype: list """ action = "get nic information" with zvmutils.log_and_reraise_sdkbase_error(action): return self._networkops.get_nic_info(userid=userid, nic_id=nic_id, vswitch=vswitch)
[ "def", "guests_get_nic_info", "(", "self", ",", "userid", "=", "None", ",", "nic_id", "=", "None", ",", "vswitch", "=", "None", ")", ":", "action", "=", "\"get nic information\"", "with", "zvmutils", ".", "log_and_reraise_sdkbase_error", "(", "action", ")", ":...
Retrieve nic information in the network database according to the requirements, the nic information will include the guest name, nic device number, vswitch name that the nic is coupled to, nic identifier and the comments. :param str userid: the user id of the vm :param str nic_id: nic identifier :param str vswitch: the name of the vswitch :returns: list describing nic information, format is [ (userid, interface, vswitch, nic_id, comments), (userid, interface, vswitch, nic_id, comments) ], such as [ ('VM01', '1000', 'xcatvsw2', '1111-2222', None), ('VM02', '2000', 'xcatvsw3', None, None) ] :rtype: list
[ "Retrieve", "nic", "information", "in", "the", "network", "database", "according", "to", "the", "requirements", "the", "nic", "information", "will", "include", "the", "guest", "name", "nic", "device", "number", "vswitch", "name", "that", "the", "nic", "is", "c...
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/api.py#L1422-L1446
train
43,547
mfcloud/python-zvm-sdk
zvmsdk/api.py
SDKAPI.vswitch_query
def vswitch_query(self, vswitch_name): """Check the virtual switch status :param str vswitch_name: the name of the virtual switch :returns: Dictionary describing virtual switch info :rtype: dict """ action = "get virtual switch information" with zvmutils.log_and_reraise_sdkbase_error(action): return self._networkops.vswitch_query(vswitch_name)
python
def vswitch_query(self, vswitch_name): """Check the virtual switch status :param str vswitch_name: the name of the virtual switch :returns: Dictionary describing virtual switch info :rtype: dict """ action = "get virtual switch information" with zvmutils.log_and_reraise_sdkbase_error(action): return self._networkops.vswitch_query(vswitch_name)
[ "def", "vswitch_query", "(", "self", ",", "vswitch_name", ")", ":", "action", "=", "\"get virtual switch information\"", "with", "zvmutils", ".", "log_and_reraise_sdkbase_error", "(", "action", ")", ":", "return", "self", ".", "_networkops", ".", "vswitch_query", "(...
Check the virtual switch status :param str vswitch_name: the name of the virtual switch :returns: Dictionary describing virtual switch info :rtype: dict
[ "Check", "the", "virtual", "switch", "status" ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/api.py#L1448-L1457
train
43,548
mfcloud/python-zvm-sdk
zvmsdk/api.py
SDKAPI.guest_delete_network_interface
def guest_delete_network_interface(self, userid, os_version, vdev, active=False): """ delete the nic and network configuration for the vm :param str userid: the user id of the guest :param str os_version: operating system version of the guest :param str vdev: nic device number, 1- to 4- hexadecimal digits :param bool active: whether delete a nic on active guest system """ self._networkops.delete_nic(userid, vdev, active=active) self._networkops.delete_network_configuration(userid, os_version, vdev, active=active)
python
def guest_delete_network_interface(self, userid, os_version, vdev, active=False): """ delete the nic and network configuration for the vm :param str userid: the user id of the guest :param str os_version: operating system version of the guest :param str vdev: nic device number, 1- to 4- hexadecimal digits :param bool active: whether delete a nic on active guest system """ self._networkops.delete_nic(userid, vdev, active=active) self._networkops.delete_network_configuration(userid, os_version, vdev, active=active)
[ "def", "guest_delete_network_interface", "(", "self", ",", "userid", ",", "os_version", ",", "vdev", ",", "active", "=", "False", ")", ":", "self", ".", "_networkops", ".", "delete_nic", "(", "userid", ",", "vdev", ",", "active", "=", "active", ")", "self"...
delete the nic and network configuration for the vm :param str userid: the user id of the guest :param str os_version: operating system version of the guest :param str vdev: nic device number, 1- to 4- hexadecimal digits :param bool active: whether delete a nic on active guest system
[ "delete", "the", "nic", "and", "network", "configuration", "for", "the", "vm" ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/api.py#L1460-L1471
train
43,549
mfcloud/python-zvm-sdk
zvmsdk/config.py
ConfigOpts._fixpath
def _fixpath(self, p): """Apply tilde expansion and absolutization to a path.""" return os.path.abspath(os.path.expanduser(p))
python
def _fixpath(self, p): """Apply tilde expansion and absolutization to a path.""" return os.path.abspath(os.path.expanduser(p))
[ "def", "_fixpath", "(", "self", ",", "p", ")", ":", "return", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "expanduser", "(", "p", ")", ")" ]
Apply tilde expansion and absolutization to a path.
[ "Apply", "tilde", "expansion", "and", "absolutization", "to", "a", "path", "." ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/config.py#L588-L590
train
43,550
jvarho/pylibscrypt
pylibscrypt/mcf.py
scrypt_mcf
def scrypt_mcf(scrypt, password, salt=None, N=SCRYPT_N, r=SCRYPT_r, p=SCRYPT_p, prefix=SCRYPT_MCF_PREFIX_DEFAULT): """Derives a Modular Crypt Format hash using the scrypt KDF given Expects the signature: scrypt(password, salt, N=SCRYPT_N, r=SCRYPT_r, p=SCRYPT_p, olen=64) If no salt is given, a random salt of 128+ bits is used. (Recommended.) """ if isinstance(password, unicode): password = password.encode('utf8') elif not isinstance(password, bytes): raise TypeError('password must be a unicode or byte string') if salt is not None and not isinstance(salt, bytes): raise TypeError('salt must be a byte string') if salt is not None and not (1 <= len(salt) <= 16): raise ValueError('salt must be 1-16 bytes') if r > 255: raise ValueError('scrypt_mcf r out of range [1,255]') if p > 255: raise ValueError('scrypt_mcf p out of range [1,255]') if N > 2**31: raise ValueError('scrypt_mcf N out of range [2,2**31]') if b'\0' in password: raise ValueError('scrypt_mcf password must not contain zero bytes') if prefix == SCRYPT_MCF_PREFIX_s1: if salt is None: salt = os.urandom(16) hash = scrypt(password, salt, N, r, p) return _scrypt_mcf_encode_s1(N, r, p, salt, hash) elif prefix == SCRYPT_MCF_PREFIX_7 or prefix == SCRYPT_MCF_PREFIX_ANY: if salt is None: salt = os.urandom(32) salt = _cb64enc(salt) hash = scrypt(password, salt, N, r, p, 32) return _scrypt_mcf_encode_7(N, r, p, salt, hash) else: raise ValueError("Unrecognized MCF format")
python
def scrypt_mcf(scrypt, password, salt=None, N=SCRYPT_N, r=SCRYPT_r, p=SCRYPT_p, prefix=SCRYPT_MCF_PREFIX_DEFAULT): """Derives a Modular Crypt Format hash using the scrypt KDF given Expects the signature: scrypt(password, salt, N=SCRYPT_N, r=SCRYPT_r, p=SCRYPT_p, olen=64) If no salt is given, a random salt of 128+ bits is used. (Recommended.) """ if isinstance(password, unicode): password = password.encode('utf8') elif not isinstance(password, bytes): raise TypeError('password must be a unicode or byte string') if salt is not None and not isinstance(salt, bytes): raise TypeError('salt must be a byte string') if salt is not None and not (1 <= len(salt) <= 16): raise ValueError('salt must be 1-16 bytes') if r > 255: raise ValueError('scrypt_mcf r out of range [1,255]') if p > 255: raise ValueError('scrypt_mcf p out of range [1,255]') if N > 2**31: raise ValueError('scrypt_mcf N out of range [2,2**31]') if b'\0' in password: raise ValueError('scrypt_mcf password must not contain zero bytes') if prefix == SCRYPT_MCF_PREFIX_s1: if salt is None: salt = os.urandom(16) hash = scrypt(password, salt, N, r, p) return _scrypt_mcf_encode_s1(N, r, p, salt, hash) elif prefix == SCRYPT_MCF_PREFIX_7 or prefix == SCRYPT_MCF_PREFIX_ANY: if salt is None: salt = os.urandom(32) salt = _cb64enc(salt) hash = scrypt(password, salt, N, r, p, 32) return _scrypt_mcf_encode_7(N, r, p, salt, hash) else: raise ValueError("Unrecognized MCF format")
[ "def", "scrypt_mcf", "(", "scrypt", ",", "password", ",", "salt", "=", "None", ",", "N", "=", "SCRYPT_N", ",", "r", "=", "SCRYPT_r", ",", "p", "=", "SCRYPT_p", ",", "prefix", "=", "SCRYPT_MCF_PREFIX_DEFAULT", ")", ":", "if", "isinstance", "(", "password"...
Derives a Modular Crypt Format hash using the scrypt KDF given Expects the signature: scrypt(password, salt, N=SCRYPT_N, r=SCRYPT_r, p=SCRYPT_p, olen=64) If no salt is given, a random salt of 128+ bits is used. (Recommended.)
[ "Derives", "a", "Modular", "Crypt", "Format", "hash", "using", "the", "scrypt", "KDF", "given" ]
f2ff02e49f44aa620e308a4a64dd8376b9510f99
https://github.com/jvarho/pylibscrypt/blob/f2ff02e49f44aa620e308a4a64dd8376b9510f99/pylibscrypt/mcf.py#L199-L237
train
43,551
Chilipp/psyplot
psyplot/plugin_template.py
new_plugin
def new_plugin(odir, py_name=None, version='0.0.1.dev0', description='New plugin'): """ Create a new plugin for the psyplot package Parameters ---------- odir: str The name of the directory where the data will be copied to. The directory must not exist! The name of the directory also defines the name of the package. py_name: str The name of the python package. If None, the basename of `odir` is used (and ``'-'`` is replaced by ``'_'``) version: str The version of the package description: str The description of the plugin""" name = osp.basename(odir) if py_name is None: py_name = name.replace('-', '_') src = osp.join(osp.dirname(__file__), 'plugin-template-files') # copy the source files shutil.copytree(src, odir) os.rename(osp.join(odir, 'plugin_template'), osp.join(odir, py_name)) replacements = {'PLUGIN_NAME': name, 'PLUGIN_PYNAME': py_name, 'PLUGIN_VERSION': version, 'PLUGIN_DESC': description, } files = [ 'README.md', 'setup.py', osp.join(py_name, 'plugin.py'), osp.join(py_name, 'plotters.py'), osp.join(py_name, '__init__.py'), ] for fname in files: with open(osp.join(odir, fname)) as f: s = f.read() for key, val in replacements.items(): s = s.replace(key, val) with open(osp.join(odir, fname), 'w') as f: f.write(s)
python
def new_plugin(odir, py_name=None, version='0.0.1.dev0', description='New plugin'): """ Create a new plugin for the psyplot package Parameters ---------- odir: str The name of the directory where the data will be copied to. The directory must not exist! The name of the directory also defines the name of the package. py_name: str The name of the python package. If None, the basename of `odir` is used (and ``'-'`` is replaced by ``'_'``) version: str The version of the package description: str The description of the plugin""" name = osp.basename(odir) if py_name is None: py_name = name.replace('-', '_') src = osp.join(osp.dirname(__file__), 'plugin-template-files') # copy the source files shutil.copytree(src, odir) os.rename(osp.join(odir, 'plugin_template'), osp.join(odir, py_name)) replacements = {'PLUGIN_NAME': name, 'PLUGIN_PYNAME': py_name, 'PLUGIN_VERSION': version, 'PLUGIN_DESC': description, } files = [ 'README.md', 'setup.py', osp.join(py_name, 'plugin.py'), osp.join(py_name, 'plotters.py'), osp.join(py_name, '__init__.py'), ] for fname in files: with open(osp.join(odir, fname)) as f: s = f.read() for key, val in replacements.items(): s = s.replace(key, val) with open(osp.join(odir, fname), 'w') as f: f.write(s)
[ "def", "new_plugin", "(", "odir", ",", "py_name", "=", "None", ",", "version", "=", "'0.0.1.dev0'", ",", "description", "=", "'New plugin'", ")", ":", "name", "=", "osp", ".", "basename", "(", "odir", ")", "if", "py_name", "is", "None", ":", "py_name", ...
Create a new plugin for the psyplot package Parameters ---------- odir: str The name of the directory where the data will be copied to. The directory must not exist! The name of the directory also defines the name of the package. py_name: str The name of the python package. If None, the basename of `odir` is used (and ``'-'`` is replaced by ``'_'``) version: str The version of the package description: str The description of the plugin
[ "Create", "a", "new", "plugin", "for", "the", "psyplot", "package" ]
75a0a15a9a1dd018e79d2df270d56c4bf5f311d5
https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/plugin_template.py#L9-L55
train
43,552
Chilipp/psyplot
psyplot/__init__.py
get_versions
def get_versions(requirements=True, key=None): """ Get the version information for psyplot, the plugins and its requirements Parameters ---------- requirements: bool If True, the requirements of the plugins and psyplot are investigated key: func A function that determines whether a plugin shall be considererd or not. The function must take a single argument, that is the name of the plugin as string, and must return True (import the plugin) or False (skip the plugin). If None, all plugins are imported Returns ------- dict A mapping from ``'psyplot'``/the plugin names to a dictionary with the ``'version'`` key and the corresponding version is returned. If `requirements` is True, it also contains a mapping from ``'requirements'`` a dictionary with the versions Examples -------- Using the built-in JSON module, we get something like .. code-block:: python import json print(json.dumps(psyplot.get_versions(), indent=4)) { "psy_simple.plugin": { "version": "1.0.0.dev0" }, "psyplot": { "version": "1.0.0.dev0", "requirements": { "matplotlib": "1.5.3", "numpy": "1.11.3", "pandas": "0.19.2", "xarray": "0.9.1" } }, "psy_maps.plugin": { "version": "1.0.0.dev0", "requirements": { "cartopy": "0.15.0" } } } """ from pkg_resources import iter_entry_points ret = {'psyplot': _get_versions(requirements)} for ep in iter_entry_points(group='psyplot', name='plugin'): if str(ep) in rcParams._plugins: logger.debug('Loading entrypoint %s', ep) if key is not None and not key(ep.module_name): continue mod = ep.load() try: ret[str(ep.module_name)] = mod.get_versions(requirements) except AttributeError: ret[str(ep.module_name)] = { 'version': getattr(mod, 'plugin_version', getattr(mod, '__version__', ''))} if key is None: try: import psyplot_gui except ImportError: pass else: ret['psyplot_gui'] = psyplot_gui.get_versions(requirements) return ret
python
def get_versions(requirements=True, key=None): """ Get the version information for psyplot, the plugins and its requirements Parameters ---------- requirements: bool If True, the requirements of the plugins and psyplot are investigated key: func A function that determines whether a plugin shall be considererd or not. The function must take a single argument, that is the name of the plugin as string, and must return True (import the plugin) or False (skip the plugin). If None, all plugins are imported Returns ------- dict A mapping from ``'psyplot'``/the plugin names to a dictionary with the ``'version'`` key and the corresponding version is returned. If `requirements` is True, it also contains a mapping from ``'requirements'`` a dictionary with the versions Examples -------- Using the built-in JSON module, we get something like .. code-block:: python import json print(json.dumps(psyplot.get_versions(), indent=4)) { "psy_simple.plugin": { "version": "1.0.0.dev0" }, "psyplot": { "version": "1.0.0.dev0", "requirements": { "matplotlib": "1.5.3", "numpy": "1.11.3", "pandas": "0.19.2", "xarray": "0.9.1" } }, "psy_maps.plugin": { "version": "1.0.0.dev0", "requirements": { "cartopy": "0.15.0" } } } """ from pkg_resources import iter_entry_points ret = {'psyplot': _get_versions(requirements)} for ep in iter_entry_points(group='psyplot', name='plugin'): if str(ep) in rcParams._plugins: logger.debug('Loading entrypoint %s', ep) if key is not None and not key(ep.module_name): continue mod = ep.load() try: ret[str(ep.module_name)] = mod.get_versions(requirements) except AttributeError: ret[str(ep.module_name)] = { 'version': getattr(mod, 'plugin_version', getattr(mod, '__version__', ''))} if key is None: try: import psyplot_gui except ImportError: pass else: ret['psyplot_gui'] = psyplot_gui.get_versions(requirements) return ret
[ "def", "get_versions", "(", "requirements", "=", "True", ",", "key", "=", "None", ")", ":", "from", "pkg_resources", "import", "iter_entry_points", "ret", "=", "{", "'psyplot'", ":", "_get_versions", "(", "requirements", ")", "}", "for", "ep", "in", "iter_en...
Get the version information for psyplot, the plugins and its requirements Parameters ---------- requirements: bool If True, the requirements of the plugins and psyplot are investigated key: func A function that determines whether a plugin shall be considererd or not. The function must take a single argument, that is the name of the plugin as string, and must return True (import the plugin) or False (skip the plugin). If None, all plugins are imported Returns ------- dict A mapping from ``'psyplot'``/the plugin names to a dictionary with the ``'version'`` key and the corresponding version is returned. If `requirements` is True, it also contains a mapping from ``'requirements'`` a dictionary with the versions Examples -------- Using the built-in JSON module, we get something like .. code-block:: python import json print(json.dumps(psyplot.get_versions(), indent=4)) { "psy_simple.plugin": { "version": "1.0.0.dev0" }, "psyplot": { "version": "1.0.0.dev0", "requirements": { "matplotlib": "1.5.3", "numpy": "1.11.3", "pandas": "0.19.2", "xarray": "0.9.1" } }, "psy_maps.plugin": { "version": "1.0.0.dev0", "requirements": { "cartopy": "0.15.0" } } }
[ "Get", "the", "version", "information", "for", "psyplot", "the", "plugins", "and", "its", "requirements" ]
75a0a15a9a1dd018e79d2df270d56c4bf5f311d5
https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/__init__.py#L35-L107
train
43,553
mfcloud/python-zvm-sdk
zvmsdk/database.py
NetworkDbOperator.switch_add_record
def switch_add_record(self, userid, interface, port=None, switch=None, comments=None): """Add userid and nic name address into switch table.""" with get_network_conn() as conn: conn.execute("INSERT INTO switch VALUES (?, ?, ?, ?, ?)", (userid, interface, switch, port, comments)) LOG.debug("New record in the switch table: user %s, " "nic %s, port %s" % (userid, interface, port))
python
def switch_add_record(self, userid, interface, port=None, switch=None, comments=None): """Add userid and nic name address into switch table.""" with get_network_conn() as conn: conn.execute("INSERT INTO switch VALUES (?, ?, ?, ?, ?)", (userid, interface, switch, port, comments)) LOG.debug("New record in the switch table: user %s, " "nic %s, port %s" % (userid, interface, port))
[ "def", "switch_add_record", "(", "self", ",", "userid", ",", "interface", ",", "port", "=", "None", ",", "switch", "=", "None", ",", "comments", "=", "None", ")", ":", "with", "get_network_conn", "(", ")", "as", "conn", ":", "conn", ".", "execute", "("...
Add userid and nic name address into switch table.
[ "Add", "userid", "and", "nic", "name", "address", "into", "switch", "table", "." ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/database.py#L170-L178
train
43,554
mfcloud/python-zvm-sdk
zvmsdk/database.py
NetworkDbOperator.switch_update_record_with_switch
def switch_update_record_with_switch(self, userid, interface, switch=None): """Update information in switch table.""" if not self._get_switch_by_user_interface(userid, interface): msg = "User %s with nic %s does not exist in DB" % (userid, interface) LOG.error(msg) obj_desc = ('User %s with nic %s' % (userid, interface)) raise exception.SDKObjectNotExistError(obj_desc, modID=self._module_id) if switch is not None: with get_network_conn() as conn: conn.execute("UPDATE switch SET switch=? " "WHERE userid=? and interface=?", (switch, userid, interface)) LOG.debug("Set switch to %s for user %s with nic %s " "in switch table" % (switch, userid, interface)) else: with get_network_conn() as conn: conn.execute("UPDATE switch SET switch=NULL " "WHERE userid=? and interface=?", (userid, interface)) LOG.debug("Set switch to None for user %s with nic %s " "in switch table" % (userid, interface))
python
def switch_update_record_with_switch(self, userid, interface, switch=None): """Update information in switch table.""" if not self._get_switch_by_user_interface(userid, interface): msg = "User %s with nic %s does not exist in DB" % (userid, interface) LOG.error(msg) obj_desc = ('User %s with nic %s' % (userid, interface)) raise exception.SDKObjectNotExistError(obj_desc, modID=self._module_id) if switch is not None: with get_network_conn() as conn: conn.execute("UPDATE switch SET switch=? " "WHERE userid=? and interface=?", (switch, userid, interface)) LOG.debug("Set switch to %s for user %s with nic %s " "in switch table" % (switch, userid, interface)) else: with get_network_conn() as conn: conn.execute("UPDATE switch SET switch=NULL " "WHERE userid=? and interface=?", (userid, interface)) LOG.debug("Set switch to None for user %s with nic %s " "in switch table" % (userid, interface))
[ "def", "switch_update_record_with_switch", "(", "self", ",", "userid", ",", "interface", ",", "switch", "=", "None", ")", ":", "if", "not", "self", ".", "_get_switch_by_user_interface", "(", "userid", ",", "interface", ")", ":", "msg", "=", "\"User %s with nic %...
Update information in switch table.
[ "Update", "information", "in", "switch", "table", "." ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/database.py#L190-L216
train
43,555
mfcloud/python-zvm-sdk
zvmsdk/database.py
ImageDbOperator.image_query_record
def image_query_record(self, imagename=None): """Query the image record from database, if imagename is None, all of the image records will be returned, otherwise only the specified image record will be returned.""" if imagename: with get_image_conn() as conn: result = conn.execute("SELECT * FROM image WHERE " "imagename=?", (imagename,)) image_list = result.fetchall() if not image_list: obj_desc = "Image with name: %s" % imagename raise exception.SDKObjectNotExistError(obj_desc=obj_desc, modID=self._module_id) else: with get_image_conn() as conn: result = conn.execute("SELECT * FROM image") image_list = result.fetchall() # Map each image record to be a dict, with the key is the field name in # image DB image_keys_list = ['imagename', 'imageosdistro', 'md5sum', 'disk_size_units', 'image_size_in_bytes', 'type', 'comments'] image_result = [] for item in image_list: image_item = dict(zip(image_keys_list, item)) image_result.append(image_item) return image_result
python
def image_query_record(self, imagename=None): """Query the image record from database, if imagename is None, all of the image records will be returned, otherwise only the specified image record will be returned.""" if imagename: with get_image_conn() as conn: result = conn.execute("SELECT * FROM image WHERE " "imagename=?", (imagename,)) image_list = result.fetchall() if not image_list: obj_desc = "Image with name: %s" % imagename raise exception.SDKObjectNotExistError(obj_desc=obj_desc, modID=self._module_id) else: with get_image_conn() as conn: result = conn.execute("SELECT * FROM image") image_list = result.fetchall() # Map each image record to be a dict, with the key is the field name in # image DB image_keys_list = ['imagename', 'imageosdistro', 'md5sum', 'disk_size_units', 'image_size_in_bytes', 'type', 'comments'] image_result = [] for item in image_list: image_item = dict(zip(image_keys_list, item)) image_result.append(image_item) return image_result
[ "def", "image_query_record", "(", "self", ",", "imagename", "=", "None", ")", ":", "if", "imagename", ":", "with", "get_image_conn", "(", ")", "as", "conn", ":", "result", "=", "conn", ".", "execute", "(", "\"SELECT * FROM image WHERE \"", "\"imagename=?\"", "...
Query the image record from database, if imagename is None, all of the image records will be returned, otherwise only the specified image record will be returned.
[ "Query", "the", "image", "record", "from", "database", "if", "imagename", "is", "None", "all", "of", "the", "image", "records", "will", "be", "returned", "otherwise", "only", "the", "specified", "image", "record", "will", "be", "returned", "." ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/database.py#L463-L492
train
43,556
ratcave/wavefront_reader
wavefront_reader/writing.py
face_index
def face_index(vertices): """Takes an MxNx3 array and returns a 2D vertices and MxN face_indices arrays""" new_verts = [] face_indices = [] for wall in vertices: face_wall = [] for vert in wall: if new_verts: if not np.isclose(vert, new_verts).all(axis=1).any(): new_verts.append(vert) else: new_verts.append(vert) face_index = np.where(np.isclose(vert, new_verts).all(axis=1))[0][0] face_wall.append(face_index) face_indices.append(face_wall) return np.array(new_verts), np.array(face_indices)
python
def face_index(vertices): """Takes an MxNx3 array and returns a 2D vertices and MxN face_indices arrays""" new_verts = [] face_indices = [] for wall in vertices: face_wall = [] for vert in wall: if new_verts: if not np.isclose(vert, new_verts).all(axis=1).any(): new_verts.append(vert) else: new_verts.append(vert) face_index = np.where(np.isclose(vert, new_verts).all(axis=1))[0][0] face_wall.append(face_index) face_indices.append(face_wall) return np.array(new_verts), np.array(face_indices)
[ "def", "face_index", "(", "vertices", ")", ":", "new_verts", "=", "[", "]", "face_indices", "=", "[", "]", "for", "wall", "in", "vertices", ":", "face_wall", "=", "[", "]", "for", "vert", "in", "wall", ":", "if", "new_verts", ":", "if", "not", "np", ...
Takes an MxNx3 array and returns a 2D vertices and MxN face_indices arrays
[ "Takes", "an", "MxNx3", "array", "and", "returns", "a", "2D", "vertices", "and", "MxN", "face_indices", "arrays" ]
c515164a3952d6b85f8044f429406fddd862bfd0
https://github.com/ratcave/wavefront_reader/blob/c515164a3952d6b85f8044f429406fddd862bfd0/wavefront_reader/writing.py#L8-L23
train
43,557
ratcave/wavefront_reader
wavefront_reader/writing.py
fan_triangulate
def fan_triangulate(indices): """Return an array of vertices in triangular order using a fan triangulation algorithm.""" if len(indices[0]) != 4: raise ValueError("Assumes working with a sequence of quad indices") new_indices = [] for face in indices: new_indices.extend([face[:-1], face[1:]]) return np.array(new_indices)
python
def fan_triangulate(indices): """Return an array of vertices in triangular order using a fan triangulation algorithm.""" if len(indices[0]) != 4: raise ValueError("Assumes working with a sequence of quad indices") new_indices = [] for face in indices: new_indices.extend([face[:-1], face[1:]]) return np.array(new_indices)
[ "def", "fan_triangulate", "(", "indices", ")", ":", "if", "len", "(", "indices", "[", "0", "]", ")", "!=", "4", ":", "raise", "ValueError", "(", "\"Assumes working with a sequence of quad indices\"", ")", "new_indices", "=", "[", "]", "for", "face", "in", "i...
Return an array of vertices in triangular order using a fan triangulation algorithm.
[ "Return", "an", "array", "of", "vertices", "in", "triangular", "order", "using", "a", "fan", "triangulation", "algorithm", "." ]
c515164a3952d6b85f8044f429406fddd862bfd0
https://github.com/ratcave/wavefront_reader/blob/c515164a3952d6b85f8044f429406fddd862bfd0/wavefront_reader/writing.py#L26-L33
train
43,558
ratcave/wavefront_reader
wavefront_reader/writing.py
WavefrontWriter.from_indexed_arrays
def from_indexed_arrays(cls, name, verts, normals): """Takes MxNx3 verts, Mx3 normals to build obj file""" # Put header in string wavefront_str = "o {name}\n".format(name=name) new_verts, face_indices = face_index(verts) assert new_verts.shape[1] == 3, "verts should be Nx3 array" assert face_indices.ndim == 2 face_indices = fan_triangulate(face_indices) # Write Vertex data from vert_dict for vert in new_verts: wavefront_str += "v {0} {1} {2}\n".format(*vert) # Write (false) UV Texture data wavefront_str += "vt 1.0 1.0\n" for norm in normals: wavefront_str += "vn {0} {1} {2}\n".format(*norm) assert len(face_indices) == len(normals) * 2 for norm_idx, vert_idx, in enumerate(face_indices): wavefront_str += "f" for vv in vert_idx: wavefront_str += " {}/{}/{}".format(vv + 1, 1, (norm_idx // 2) + 1 ) wavefront_str += "\n" return cls(string=wavefront_str)
python
def from_indexed_arrays(cls, name, verts, normals): """Takes MxNx3 verts, Mx3 normals to build obj file""" # Put header in string wavefront_str = "o {name}\n".format(name=name) new_verts, face_indices = face_index(verts) assert new_verts.shape[1] == 3, "verts should be Nx3 array" assert face_indices.ndim == 2 face_indices = fan_triangulate(face_indices) # Write Vertex data from vert_dict for vert in new_verts: wavefront_str += "v {0} {1} {2}\n".format(*vert) # Write (false) UV Texture data wavefront_str += "vt 1.0 1.0\n" for norm in normals: wavefront_str += "vn {0} {1} {2}\n".format(*norm) assert len(face_indices) == len(normals) * 2 for norm_idx, vert_idx, in enumerate(face_indices): wavefront_str += "f" for vv in vert_idx: wavefront_str += " {}/{}/{}".format(vv + 1, 1, (norm_idx // 2) + 1 ) wavefront_str += "\n" return cls(string=wavefront_str)
[ "def", "from_indexed_arrays", "(", "cls", ",", "name", ",", "verts", ",", "normals", ")", ":", "# Put header in string", "wavefront_str", "=", "\"o {name}\\n\"", ".", "format", "(", "name", "=", "name", ")", "new_verts", ",", "face_indices", "=", "face_index", ...
Takes MxNx3 verts, Mx3 normals to build obj file
[ "Takes", "MxNx3", "verts", "Mx3", "normals", "to", "build", "obj", "file" ]
c515164a3952d6b85f8044f429406fddd862bfd0
https://github.com/ratcave/wavefront_reader/blob/c515164a3952d6b85f8044f429406fddd862bfd0/wavefront_reader/writing.py#L107-L137
train
43,559
ratcave/wavefront_reader
wavefront_reader/writing.py
WavefrontWriter.dump
def dump(self, f): """Write Wavefront data to file. Takes File object or filename.""" try: f.write(self._data) except AttributeError: with open(f, 'w') as wf: wf.write(self._data)
python
def dump(self, f): """Write Wavefront data to file. Takes File object or filename.""" try: f.write(self._data) except AttributeError: with open(f, 'w') as wf: wf.write(self._data)
[ "def", "dump", "(", "self", ",", "f", ")", ":", "try", ":", "f", ".", "write", "(", "self", ".", "_data", ")", "except", "AttributeError", ":", "with", "open", "(", "f", ",", "'w'", ")", "as", "wf", ":", "wf", ".", "write", "(", "self", ".", ...
Write Wavefront data to file. Takes File object or filename.
[ "Write", "Wavefront", "data", "to", "file", ".", "Takes", "File", "object", "or", "filename", "." ]
c515164a3952d6b85f8044f429406fddd862bfd0
https://github.com/ratcave/wavefront_reader/blob/c515164a3952d6b85f8044f429406fddd862bfd0/wavefront_reader/writing.py#L139-L145
train
43,560
mfcloud/python-zvm-sdk
smtLayer/cmdVM.py
doIt
def doIt(rh): """ Perform the requested function by invoking the subfunction handler. Input: Request Handle Output: Request Handle updated with parsed input. Return code - 0: ok, non-zero: error """ rh.printSysLog("Enter cmdVM.doIt") # Show the invocation parameters, if requested. if 'showParms' in rh.parms and rh.parms['showParms'] is True: rh.printLn("N", "Invocation parameters: ") rh.printLn("N", " Routine: cmdVM." + str(subfuncHandler[rh.subfunction][0]) + "(reqHandle)") rh.printLn("N", " function: " + rh.function) rh.printLn("N", " userid: " + rh.userid) rh.printLn("N", " subfunction: " + rh.subfunction) rh.printLn("N", " parms{}: ") for key in rh.parms: if key != 'showParms': rh.printLn("N", " " + key + ": " + str(rh.parms[key])) rh.printLn("N", " ") # Call the subfunction handler subfuncHandler[rh.subfunction][1](rh) rh.printSysLog("Exit cmdVM.doIt, rc: " + str(rh.results['overallRC'])) return rh.results['overallRC']
python
def doIt(rh): """ Perform the requested function by invoking the subfunction handler. Input: Request Handle Output: Request Handle updated with parsed input. Return code - 0: ok, non-zero: error """ rh.printSysLog("Enter cmdVM.doIt") # Show the invocation parameters, if requested. if 'showParms' in rh.parms and rh.parms['showParms'] is True: rh.printLn("N", "Invocation parameters: ") rh.printLn("N", " Routine: cmdVM." + str(subfuncHandler[rh.subfunction][0]) + "(reqHandle)") rh.printLn("N", " function: " + rh.function) rh.printLn("N", " userid: " + rh.userid) rh.printLn("N", " subfunction: " + rh.subfunction) rh.printLn("N", " parms{}: ") for key in rh.parms: if key != 'showParms': rh.printLn("N", " " + key + ": " + str(rh.parms[key])) rh.printLn("N", " ") # Call the subfunction handler subfuncHandler[rh.subfunction][1](rh) rh.printSysLog("Exit cmdVM.doIt, rc: " + str(rh.results['overallRC'])) return rh.results['overallRC']
[ "def", "doIt", "(", "rh", ")", ":", "rh", ".", "printSysLog", "(", "\"Enter cmdVM.doIt\"", ")", "# Show the invocation parameters, if requested.", "if", "'showParms'", "in", "rh", ".", "parms", "and", "rh", ".", "parms", "[", "'showParms'", "]", "is", "True", ...
Perform the requested function by invoking the subfunction handler. Input: Request Handle Output: Request Handle updated with parsed input. Return code - 0: ok, non-zero: error
[ "Perform", "the", "requested", "function", "by", "invoking", "the", "subfunction", "handler", "." ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/smtLayer/cmdVM.py#L66-L98
train
43,561
mfcloud/python-zvm-sdk
smtLayer/cmdVM.py
invokeCmd
def invokeCmd(rh): """ Invoke the command in the virtual machine's operating system. Input: Request Handle with the following properties: function - 'CMDVM' subfunction - 'CMD' userid - userid of the virtual machine parms['cmd'] - Command to send Output: Request Handle updated with the results. Return code - 0: ok, non-zero: error """ rh.printSysLog("Enter cmdVM.invokeCmd, userid: " + rh.userid) results = execCmdThruIUCV(rh, rh.userid, rh.parms['cmd']) if results['overallRC'] == 0: rh.printLn("N", results['response']) else: rh.printLn("ES", results['response']) rh.updateResults(results) rh.printSysLog("Exit cmdVM.invokeCmd, rc: " + str(results['overallRC'])) return results['overallRC']
python
def invokeCmd(rh): """ Invoke the command in the virtual machine's operating system. Input: Request Handle with the following properties: function - 'CMDVM' subfunction - 'CMD' userid - userid of the virtual machine parms['cmd'] - Command to send Output: Request Handle updated with the results. Return code - 0: ok, non-zero: error """ rh.printSysLog("Enter cmdVM.invokeCmd, userid: " + rh.userid) results = execCmdThruIUCV(rh, rh.userid, rh.parms['cmd']) if results['overallRC'] == 0: rh.printLn("N", results['response']) else: rh.printLn("ES", results['response']) rh.updateResults(results) rh.printSysLog("Exit cmdVM.invokeCmd, rc: " + str(results['overallRC'])) return results['overallRC']
[ "def", "invokeCmd", "(", "rh", ")", ":", "rh", ".", "printSysLog", "(", "\"Enter cmdVM.invokeCmd, userid: \"", "+", "rh", ".", "userid", ")", "results", "=", "execCmdThruIUCV", "(", "rh", ",", "rh", ".", "userid", ",", "rh", ".", "parms", "[", "'cmd'", "...
Invoke the command in the virtual machine's operating system. Input: Request Handle with the following properties: function - 'CMDVM' subfunction - 'CMD' userid - userid of the virtual machine parms['cmd'] - Command to send Output: Request Handle updated with the results. Return code - 0: ok, non-zero: error
[ "Invoke", "the", "command", "in", "the", "virtual", "machine", "s", "operating", "system", "." ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/smtLayer/cmdVM.py#L134-L161
train
43,562
mfcloud/python-zvm-sdk
zvmsdk/smtclient.py
SMTClient.add_mdisks
def add_mdisks(self, userid, disk_list, start_vdev=None): """Add disks for the userid :disks: A list dictionary to describe disk info, for example: disk: [{'size': '1g', 'format': 'ext3', 'disk_pool': 'ECKD:eckdpool1'}] """ for idx, disk in enumerate(disk_list): if 'vdev' in disk: # this means user want to create their own device number vdev = disk['vdev'] else: vdev = self.generate_disk_vdev(start_vdev=start_vdev, offset=idx) self._add_mdisk(userid, disk, vdev) disk['vdev'] = vdev if disk.get('disk_pool') is None: disk['disk_pool'] = CONF.zvm.disk_pool sizeUpper = disk.get('size').strip().upper() sizeUnit = sizeUpper[-1] if sizeUnit != 'G' and sizeUnit != 'M': sizeValue = sizeUpper disk_pool = disk.get('disk_pool') [diskpool_type, diskpool_name] = disk_pool.split(':') if (diskpool_type.upper() == 'ECKD'): # Convert the cylinders to bytes convert = 737280 else: # Convert the blocks to bytes convert = 512 byteSize = float(float(int(sizeValue) * convert / 1024) / 1024) unit = "M" if (byteSize > 1024): byteSize = float(byteSize / 1024) unit = "G" byteSize = "%.1f" % byteSize disk['size'] = byteSize + unit return disk_list
python
def add_mdisks(self, userid, disk_list, start_vdev=None): """Add disks for the userid :disks: A list dictionary to describe disk info, for example: disk: [{'size': '1g', 'format': 'ext3', 'disk_pool': 'ECKD:eckdpool1'}] """ for idx, disk in enumerate(disk_list): if 'vdev' in disk: # this means user want to create their own device number vdev = disk['vdev'] else: vdev = self.generate_disk_vdev(start_vdev=start_vdev, offset=idx) self._add_mdisk(userid, disk, vdev) disk['vdev'] = vdev if disk.get('disk_pool') is None: disk['disk_pool'] = CONF.zvm.disk_pool sizeUpper = disk.get('size').strip().upper() sizeUnit = sizeUpper[-1] if sizeUnit != 'G' and sizeUnit != 'M': sizeValue = sizeUpper disk_pool = disk.get('disk_pool') [diskpool_type, diskpool_name] = disk_pool.split(':') if (diskpool_type.upper() == 'ECKD'): # Convert the cylinders to bytes convert = 737280 else: # Convert the blocks to bytes convert = 512 byteSize = float(float(int(sizeValue) * convert / 1024) / 1024) unit = "M" if (byteSize > 1024): byteSize = float(byteSize / 1024) unit = "G" byteSize = "%.1f" % byteSize disk['size'] = byteSize + unit return disk_list
[ "def", "add_mdisks", "(", "self", ",", "userid", ",", "disk_list", ",", "start_vdev", "=", "None", ")", ":", "for", "idx", ",", "disk", "in", "enumerate", "(", "disk_list", ")", ":", "if", "'vdev'", "in", "disk", ":", "# this means user want to create their ...
Add disks for the userid :disks: A list dictionary to describe disk info, for example: disk: [{'size': '1g', 'format': 'ext3', 'disk_pool': 'ECKD:eckdpool1'}]
[ "Add", "disks", "for", "the", "userid" ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/smtclient.py#L142-L186
train
43,563
mfcloud/python-zvm-sdk
zvmsdk/smtclient.py
SMTClient._dedicate_device
def _dedicate_device(self, userid, vaddr, raddr, mode): """dedicate device.""" action = 'dedicate' rd = ('changevm %(uid)s %(act)s %(va)s %(ra)s %(mod)i' % {'uid': userid, 'act': action, 'va': vaddr, 'ra': raddr, 'mod': mode}) action = "dedicate device to userid '%s'" % userid with zvmutils.log_and_reraise_smt_request_failed(action): self._request(rd)
python
def _dedicate_device(self, userid, vaddr, raddr, mode): """dedicate device.""" action = 'dedicate' rd = ('changevm %(uid)s %(act)s %(va)s %(ra)s %(mod)i' % {'uid': userid, 'act': action, 'va': vaddr, 'ra': raddr, 'mod': mode}) action = "dedicate device to userid '%s'" % userid with zvmutils.log_and_reraise_smt_request_failed(action): self._request(rd)
[ "def", "_dedicate_device", "(", "self", ",", "userid", ",", "vaddr", ",", "raddr", ",", "mode", ")", ":", "action", "=", "'dedicate'", "rd", "=", "(", "'changevm %(uid)s %(act)s %(va)s %(ra)s %(mod)i'", "%", "{", "'uid'", ":", "userid", ",", "'act'", ":", "a...
dedicate device.
[ "dedicate", "device", "." ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/smtclient.py#L205-L213
train
43,564
mfcloud/python-zvm-sdk
zvmsdk/smtclient.py
SMTClient.get_fcp_info_by_status
def get_fcp_info_by_status(self, userid, status): """get fcp information by the status. :userid: The name of the image to query fcp info :status: The status of target fcps. eg:'active', 'free' or 'offline'. """ results = self._get_fcp_info_by_status(userid, status) return results
python
def get_fcp_info_by_status(self, userid, status): """get fcp information by the status. :userid: The name of the image to query fcp info :status: The status of target fcps. eg:'active', 'free' or 'offline'. """ results = self._get_fcp_info_by_status(userid, status) return results
[ "def", "get_fcp_info_by_status", "(", "self", ",", "userid", ",", "status", ")", ":", "results", "=", "self", ".", "_get_fcp_info_by_status", "(", "userid", ",", "status", ")", "return", "results" ]
get fcp information by the status. :userid: The name of the image to query fcp info :status: The status of target fcps. eg:'active', 'free' or 'offline'.
[ "get", "fcp", "information", "by", "the", "status", "." ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/smtclient.py#L215-L223
train
43,565
mfcloud/python-zvm-sdk
zvmsdk/smtclient.py
SMTClient._undedicate_device
def _undedicate_device(self, userid, vaddr): """undedicate device.""" action = 'undedicate' rd = ('changevm %(uid)s %(act)s %(va)s' % {'uid': userid, 'act': action, 'va': vaddr}) action = "undedicate device from userid '%s'" % userid with zvmutils.log_and_reraise_smt_request_failed(action): self._request(rd)
python
def _undedicate_device(self, userid, vaddr): """undedicate device.""" action = 'undedicate' rd = ('changevm %(uid)s %(act)s %(va)s' % {'uid': userid, 'act': action, 'va': vaddr}) action = "undedicate device from userid '%s'" % userid with zvmutils.log_and_reraise_smt_request_failed(action): self._request(rd)
[ "def", "_undedicate_device", "(", "self", ",", "userid", ",", "vaddr", ")", ":", "action", "=", "'undedicate'", "rd", "=", "(", "'changevm %(uid)s %(act)s %(va)s'", "%", "{", "'uid'", ":", "userid", ",", "'act'", ":", "action", ",", "'va'", ":", "vaddr", "...
undedicate device.
[ "undedicate", "device", "." ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/smtclient.py#L243-L251
train
43,566
mfcloud/python-zvm-sdk
zvmsdk/smtclient.py
SMTClient.get_image_performance_info
def get_image_performance_info(self, userid): """Get CPU and memory usage information. :userid: the zvm userid to be queried """ pi_dict = self.image_performance_query([userid]) return pi_dict.get(userid, None)
python
def get_image_performance_info(self, userid): """Get CPU and memory usage information. :userid: the zvm userid to be queried """ pi_dict = self.image_performance_query([userid]) return pi_dict.get(userid, None)
[ "def", "get_image_performance_info", "(", "self", ",", "userid", ")", ":", "pi_dict", "=", "self", ".", "image_performance_query", "(", "[", "userid", "]", ")", "return", "pi_dict", ".", "get", "(", "userid", ",", "None", ")" ]
Get CPU and memory usage information. :userid: the zvm userid to be queried
[ "Get", "CPU", "and", "memory", "usage", "information", "." ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/smtclient.py#L253-L259
train
43,567
mfcloud/python-zvm-sdk
zvmsdk/smtclient.py
SMTClient._parse_vswitch_inspect_data
def _parse_vswitch_inspect_data(self, rd_list): """ Parse the Virtual_Network_Vswitch_Query_Byte_Stats data to get inspect data. """ def _parse_value(data_list, idx, keyword, offset): return idx + offset, data_list[idx].rpartition(keyword)[2].strip() vsw_dict = {} with zvmutils.expect_invalid_resp_data(): # vswitch count idx = 0 idx, vsw_count = _parse_value(rd_list, idx, 'vswitch count:', 2) vsw_dict['vswitch_count'] = int(vsw_count) # deal with each vswitch data vsw_dict['vswitches'] = [] for i in range(vsw_dict['vswitch_count']): vsw_data = {} # skip vswitch number idx += 1 # vswitch name idx, vsw_name = _parse_value(rd_list, idx, 'vswitch name:', 1) vsw_data['vswitch_name'] = vsw_name # uplink count idx, up_count = _parse_value(rd_list, idx, 'uplink count:', 1) # skip uplink data idx += int(up_count) * 9 # skip bridge data idx += 8 # nic count vsw_data['nics'] = [] idx, nic_count = _parse_value(rd_list, idx, 'nic count:', 1) nic_count = int(nic_count) for j in range(nic_count): nic_data = {} idx, nic_id = _parse_value(rd_list, idx, 'nic_id:', 1) userid, toss, vdev = nic_id.partition(' ') nic_data['userid'] = userid nic_data['vdev'] = vdev idx, nic_data['nic_fr_rx'] = _parse_value(rd_list, idx, 'nic_fr_rx:', 1 ) idx, nic_data['nic_fr_rx_dsc'] = _parse_value(rd_list, idx, 'nic_fr_rx_dsc:', 1 ) idx, nic_data['nic_fr_rx_err'] = _parse_value(rd_list, idx, 'nic_fr_rx_err:', 1 ) idx, nic_data['nic_fr_tx'] = _parse_value(rd_list, idx, 'nic_fr_tx:', 1 ) idx, nic_data['nic_fr_tx_dsc'] = _parse_value(rd_list, idx, 'nic_fr_tx_dsc:', 1 ) idx, nic_data['nic_fr_tx_err'] = _parse_value(rd_list, idx, 'nic_fr_tx_err:', 1 ) idx, nic_data['nic_rx'] = _parse_value(rd_list, idx, 'nic_rx:', 1 ) idx, nic_data['nic_tx'] = _parse_value(rd_list, idx, 'nic_tx:', 1 ) vsw_data['nics'].append(nic_data) # vlan count idx, vlan_count = _parse_value(rd_list, idx, 'vlan count:', 1) # skip vlan data idx += int(vlan_count) * 3 # skip the blank line idx += 1 vsw_dict['vswitches'].append(vsw_data) return vsw_dict
python
def _parse_vswitch_inspect_data(self, rd_list): """ Parse the Virtual_Network_Vswitch_Query_Byte_Stats data to get inspect data. """ def _parse_value(data_list, idx, keyword, offset): return idx + offset, data_list[idx].rpartition(keyword)[2].strip() vsw_dict = {} with zvmutils.expect_invalid_resp_data(): # vswitch count idx = 0 idx, vsw_count = _parse_value(rd_list, idx, 'vswitch count:', 2) vsw_dict['vswitch_count'] = int(vsw_count) # deal with each vswitch data vsw_dict['vswitches'] = [] for i in range(vsw_dict['vswitch_count']): vsw_data = {} # skip vswitch number idx += 1 # vswitch name idx, vsw_name = _parse_value(rd_list, idx, 'vswitch name:', 1) vsw_data['vswitch_name'] = vsw_name # uplink count idx, up_count = _parse_value(rd_list, idx, 'uplink count:', 1) # skip uplink data idx += int(up_count) * 9 # skip bridge data idx += 8 # nic count vsw_data['nics'] = [] idx, nic_count = _parse_value(rd_list, idx, 'nic count:', 1) nic_count = int(nic_count) for j in range(nic_count): nic_data = {} idx, nic_id = _parse_value(rd_list, idx, 'nic_id:', 1) userid, toss, vdev = nic_id.partition(' ') nic_data['userid'] = userid nic_data['vdev'] = vdev idx, nic_data['nic_fr_rx'] = _parse_value(rd_list, idx, 'nic_fr_rx:', 1 ) idx, nic_data['nic_fr_rx_dsc'] = _parse_value(rd_list, idx, 'nic_fr_rx_dsc:', 1 ) idx, nic_data['nic_fr_rx_err'] = _parse_value(rd_list, idx, 'nic_fr_rx_err:', 1 ) idx, nic_data['nic_fr_tx'] = _parse_value(rd_list, idx, 'nic_fr_tx:', 1 ) idx, nic_data['nic_fr_tx_dsc'] = _parse_value(rd_list, idx, 'nic_fr_tx_dsc:', 1 ) idx, nic_data['nic_fr_tx_err'] = _parse_value(rd_list, idx, 'nic_fr_tx_err:', 1 ) idx, nic_data['nic_rx'] = _parse_value(rd_list, idx, 'nic_rx:', 1 ) idx, nic_data['nic_tx'] = _parse_value(rd_list, idx, 'nic_tx:', 1 ) vsw_data['nics'].append(nic_data) # vlan count idx, vlan_count = _parse_value(rd_list, idx, 'vlan count:', 1) # skip vlan data idx += int(vlan_count) * 3 # skip the blank line idx += 1 vsw_dict['vswitches'].append(vsw_data) return vsw_dict
[ "def", "_parse_vswitch_inspect_data", "(", "self", ",", "rd_list", ")", ":", "def", "_parse_value", "(", "data_list", ",", "idx", ",", "keyword", ",", "offset", ")", ":", "return", "idx", "+", "offset", ",", "data_list", "[", "idx", "]", ".", "rpartition",...
Parse the Virtual_Network_Vswitch_Query_Byte_Stats data to get inspect data.
[ "Parse", "the", "Virtual_Network_Vswitch_Query_Byte_Stats", "data", "to", "get", "inspect", "data", "." ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/smtclient.py#L261-L334
train
43,568
mfcloud/python-zvm-sdk
zvmsdk/smtclient.py
SMTClient.guest_start
def guest_start(self, userid): """Power on VM.""" requestData = "PowerVM " + userid + " on" with zvmutils.log_and_reraise_smt_request_failed(): self._request(requestData)
python
def guest_start(self, userid): """Power on VM.""" requestData = "PowerVM " + userid + " on" with zvmutils.log_and_reraise_smt_request_failed(): self._request(requestData)
[ "def", "guest_start", "(", "self", ",", "userid", ")", ":", "requestData", "=", "\"PowerVM \"", "+", "userid", "+", "\" on\"", "with", "zvmutils", ".", "log_and_reraise_smt_request_failed", "(", ")", ":", "self", ".", "_request", "(", "requestData", ")" ]
Power on VM.
[ "Power", "on", "VM", "." ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/smtclient.py#L368-L372
train
43,569
mfcloud/python-zvm-sdk
zvmsdk/smtclient.py
SMTClient.guest_stop
def guest_stop(self, userid, **kwargs): """Power off VM.""" requestData = "PowerVM " + userid + " off" if 'timeout' in kwargs.keys() and kwargs['timeout']: requestData += ' --maxwait ' + str(kwargs['timeout']) if 'poll_interval' in kwargs.keys() and kwargs['poll_interval']: requestData += ' --poll ' + str(kwargs['poll_interval']) with zvmutils.log_and_reraise_smt_request_failed(): self._request(requestData)
python
def guest_stop(self, userid, **kwargs): """Power off VM.""" requestData = "PowerVM " + userid + " off" if 'timeout' in kwargs.keys() and kwargs['timeout']: requestData += ' --maxwait ' + str(kwargs['timeout']) if 'poll_interval' in kwargs.keys() and kwargs['poll_interval']: requestData += ' --poll ' + str(kwargs['poll_interval']) with zvmutils.log_and_reraise_smt_request_failed(): self._request(requestData)
[ "def", "guest_stop", "(", "self", ",", "userid", ",", "*", "*", "kwargs", ")", ":", "requestData", "=", "\"PowerVM \"", "+", "userid", "+", "\" off\"", "if", "'timeout'", "in", "kwargs", ".", "keys", "(", ")", "and", "kwargs", "[", "'timeout'", "]", ":...
Power off VM.
[ "Power", "off", "VM", "." ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/smtclient.py#L374-L384
train
43,570
mfcloud/python-zvm-sdk
zvmsdk/smtclient.py
SMTClient.live_migrate_move
def live_migrate_move(self, userid, destination, parms): """ moves the specified virtual machine, while it continues to run, to the specified system within the SSI cluster. """ rd = ('migratevm %(uid)s move --destination %(dest)s ' % {'uid': userid, 'dest': destination}) if 'maxtotal' in parms: rd += ('--maxtotal ' + str(parms['maxTotal'])) if 'maxquiesce' in parms: rd += ('--maxquiesce ' + str(parms['maxquiesce'])) if 'immediate' in parms: rd += " --immediate" if 'forcearch' in parms: rd += " --forcearch" if 'forcedomain' in parms: rd += " --forcedomain" if 'forcestorage' in parms: rd += " --forcestorage" action = "move userid '%s' to SSI '%s'" % (userid, destination) try: self._request(rd) 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 live_migrate_move(self, userid, destination, parms): """ moves the specified virtual machine, while it continues to run, to the specified system within the SSI cluster. """ rd = ('migratevm %(uid)s move --destination %(dest)s ' % {'uid': userid, 'dest': destination}) if 'maxtotal' in parms: rd += ('--maxtotal ' + str(parms['maxTotal'])) if 'maxquiesce' in parms: rd += ('--maxquiesce ' + str(parms['maxquiesce'])) if 'immediate' in parms: rd += " --immediate" if 'forcearch' in parms: rd += " --forcearch" if 'forcedomain' in parms: rd += " --forcedomain" if 'forcestorage' in parms: rd += " --forcestorage" action = "move userid '%s' to SSI '%s'" % (userid, destination) try: self._request(rd) 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", "live_migrate_move", "(", "self", ",", "userid", ",", "destination", ",", "parms", ")", ":", "rd", "=", "(", "'migratevm %(uid)s move --destination %(dest)s '", "%", "{", "'uid'", ":", "userid", ",", "'dest'", ":", "destination", "}", ")", "if", "'maxto...
moves the specified virtual machine, while it continues to run, to the specified system within the SSI cluster.
[ "moves", "the", "specified", "virtual", "machine", "while", "it", "continues", "to", "run", "to", "the", "specified", "system", "within", "the", "SSI", "cluster", "." ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/smtclient.py#L422-L451
train
43,571
mfcloud/python-zvm-sdk
zvmsdk/smtclient.py
SMTClient.create_vm
def create_vm(self, userid, cpu, memory, disk_list, profile, max_cpu, max_mem, ipl_from, ipl_param, ipl_loadparam): """ Create VM and add disks if specified. """ rd = ('makevm %(uid)s directory LBYONLY %(mem)im %(pri)s ' '--cpus %(cpu)i --profile %(prof)s --maxCPU %(max_cpu)i ' '--maxMemSize %(max_mem)s --setReservedMem' % {'uid': userid, 'mem': memory, 'pri': const.ZVM_USER_DEFAULT_PRIVILEGE, 'cpu': cpu, 'prof': profile, 'max_cpu': max_cpu, 'max_mem': max_mem}) if CONF.zvm.default_admin_userid: rd += (' --logonby "%s"' % CONF.zvm.default_admin_userid) if (disk_list and 'is_boot_disk' in disk_list[0] and disk_list[0]['is_boot_disk']): # we assume at least one disk exist, which means, is_boot_disk # is true for exactly one disk. rd += (' --ipl %s' % self._get_ipl_param(ipl_from)) # load param for ipl if ipl_param: rd += ' --iplParam %s' % ipl_param if ipl_loadparam: rd += ' --iplLoadparam %s' % ipl_loadparam action = "create userid '%s'" % userid try: self._request(rd) except exception.SDKSMTRequestFailed as err: if ((err.results['rc'] == 436) and (err.results['rs'] == 4)): result = "Profile '%s'" % profile raise exception.SDKObjectNotExistError(obj_desc=result, modID='guest') else: 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) # Add the guest to db immediately after user created action = "add guest '%s' to database" % userid with zvmutils.log_and_reraise_sdkbase_error(action): self._GuestDbOperator.add_guest(userid) # Continue to add disk if disk_list: # Add disks for vm return self.add_mdisks(userid, disk_list)
python
def create_vm(self, userid, cpu, memory, disk_list, profile, max_cpu, max_mem, ipl_from, ipl_param, ipl_loadparam): """ Create VM and add disks if specified. """ rd = ('makevm %(uid)s directory LBYONLY %(mem)im %(pri)s ' '--cpus %(cpu)i --profile %(prof)s --maxCPU %(max_cpu)i ' '--maxMemSize %(max_mem)s --setReservedMem' % {'uid': userid, 'mem': memory, 'pri': const.ZVM_USER_DEFAULT_PRIVILEGE, 'cpu': cpu, 'prof': profile, 'max_cpu': max_cpu, 'max_mem': max_mem}) if CONF.zvm.default_admin_userid: rd += (' --logonby "%s"' % CONF.zvm.default_admin_userid) if (disk_list and 'is_boot_disk' in disk_list[0] and disk_list[0]['is_boot_disk']): # we assume at least one disk exist, which means, is_boot_disk # is true for exactly one disk. rd += (' --ipl %s' % self._get_ipl_param(ipl_from)) # load param for ipl if ipl_param: rd += ' --iplParam %s' % ipl_param if ipl_loadparam: rd += ' --iplLoadparam %s' % ipl_loadparam action = "create userid '%s'" % userid try: self._request(rd) except exception.SDKSMTRequestFailed as err: if ((err.results['rc'] == 436) and (err.results['rs'] == 4)): result = "Profile '%s'" % profile raise exception.SDKObjectNotExistError(obj_desc=result, modID='guest') else: 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) # Add the guest to db immediately after user created action = "add guest '%s' to database" % userid with zvmutils.log_and_reraise_sdkbase_error(action): self._GuestDbOperator.add_guest(userid) # Continue to add disk if disk_list: # Add disks for vm return self.add_mdisks(userid, disk_list)
[ "def", "create_vm", "(", "self", ",", "userid", ",", "cpu", ",", "memory", ",", "disk_list", ",", "profile", ",", "max_cpu", ",", "max_mem", ",", "ipl_from", ",", "ipl_param", ",", "ipl_loadparam", ")", ":", "rd", "=", "(", "'makevm %(uid)s directory LBYONLY...
Create VM and add disks if specified.
[ "Create", "VM", "and", "add", "disks", "if", "specified", "." ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/smtclient.py#L479-L531
train
43,572
mfcloud/python-zvm-sdk
zvmsdk/smtclient.py
SMTClient._add_mdisk
def _add_mdisk(self, userid, disk, vdev): """Create one disk for userid NOTE: No read, write and multi password specified, and access mode default as 'MR'. """ size = disk['size'] fmt = disk.get('format', 'ext4') disk_pool = disk.get('disk_pool') or CONF.zvm.disk_pool [diskpool_type, diskpool_name] = disk_pool.split(':') if (diskpool_type.upper() == 'ECKD'): action = 'add3390' else: action = 'add9336' rd = ' '.join(['changevm', userid, action, diskpool_name, vdev, size, '--mode MR']) if fmt and fmt != 'none': rd += (' --filesystem %s' % fmt.lower()) action = "add mdisk to userid '%s'" % userid with zvmutils.log_and_reraise_smt_request_failed(action): self._request(rd)
python
def _add_mdisk(self, userid, disk, vdev): """Create one disk for userid NOTE: No read, write and multi password specified, and access mode default as 'MR'. """ size = disk['size'] fmt = disk.get('format', 'ext4') disk_pool = disk.get('disk_pool') or CONF.zvm.disk_pool [diskpool_type, diskpool_name] = disk_pool.split(':') if (diskpool_type.upper() == 'ECKD'): action = 'add3390' else: action = 'add9336' rd = ' '.join(['changevm', userid, action, diskpool_name, vdev, size, '--mode MR']) if fmt and fmt != 'none': rd += (' --filesystem %s' % fmt.lower()) action = "add mdisk to userid '%s'" % userid with zvmutils.log_and_reraise_smt_request_failed(action): self._request(rd)
[ "def", "_add_mdisk", "(", "self", ",", "userid", ",", "disk", ",", "vdev", ")", ":", "size", "=", "disk", "[", "'size'", "]", "fmt", "=", "disk", ".", "get", "(", "'format'", ",", "'ext4'", ")", "disk_pool", "=", "disk", ".", "get", "(", "'disk_poo...
Create one disk for userid NOTE: No read, write and multi password specified, and access mode default as 'MR'.
[ "Create", "one", "disk", "for", "userid" ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/smtclient.py#L533-L557
train
43,573
mfcloud/python-zvm-sdk
zvmsdk/smtclient.py
SMTClient.get_vm_list
def get_vm_list(self): """Get the list of guests that are created by SDK return userid list""" action = "list all guests in database" with zvmutils.log_and_reraise_sdkbase_error(action): guests_in_db = self._GuestDbOperator.get_guest_list() guests_migrated = self._GuestDbOperator.get_migrated_guest_list() # db query return value in tuple (uuid, userid, metadata, comments) userids_in_db = [g[1].upper() for g in guests_in_db] userids_migrated = [g[1].upper() for g in guests_migrated] userid_list = list(set(userids_in_db) - set(userids_migrated)) return userid_list
python
def get_vm_list(self): """Get the list of guests that are created by SDK return userid list""" action = "list all guests in database" with zvmutils.log_and_reraise_sdkbase_error(action): guests_in_db = self._GuestDbOperator.get_guest_list() guests_migrated = self._GuestDbOperator.get_migrated_guest_list() # db query return value in tuple (uuid, userid, metadata, comments) userids_in_db = [g[1].upper() for g in guests_in_db] userids_migrated = [g[1].upper() for g in guests_migrated] userid_list = list(set(userids_in_db) - set(userids_migrated)) return userid_list
[ "def", "get_vm_list", "(", "self", ")", ":", "action", "=", "\"list all guests in database\"", "with", "zvmutils", ".", "log_and_reraise_sdkbase_error", "(", "action", ")", ":", "guests_in_db", "=", "self", ".", "_GuestDbOperator", ".", "get_guest_list", "(", ")", ...
Get the list of guests that are created by SDK return userid list
[ "Get", "the", "list", "of", "guests", "that", "are", "created", "by", "SDK", "return", "userid", "list" ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/smtclient.py#L559-L572
train
43,574
mfcloud/python-zvm-sdk
zvmsdk/smtclient.py
SMTClient.guest_authorize_iucv_client
def guest_authorize_iucv_client(self, userid, client=None): """Punch a script that used to set the authorized client userid in vm If the guest is in log off status, the change will take effect when the guest start up at first time. If the guest is in active status, power off and power on are needed for the change to take effect. :param str guest: the user id of the vm :param str client: the user id of the client that can communicate to guest using IUCV""" client = client or zvmutils.get_smt_userid() iucv_path = "/tmp/" + userid if not os.path.exists(iucv_path): os.makedirs(iucv_path) iucv_auth_file = iucv_path + "/iucvauth.sh" zvmutils.generate_iucv_authfile(iucv_auth_file, client) try: requestData = "ChangeVM " + userid + " punchfile " + \ iucv_auth_file + " --class x" self._request(requestData) except exception.SDKSMTRequestFailed as err: msg = ("Failed to punch IUCV auth file to userid '%s'. SMT error:" " %s" % (userid, err.format_message())) LOG.error(msg) raise exception.SDKSMTRequestFailed(err.results, msg) finally: self._pathutils.clean_temp_folder(iucv_path)
python
def guest_authorize_iucv_client(self, userid, client=None): """Punch a script that used to set the authorized client userid in vm If the guest is in log off status, the change will take effect when the guest start up at first time. If the guest is in active status, power off and power on are needed for the change to take effect. :param str guest: the user id of the vm :param str client: the user id of the client that can communicate to guest using IUCV""" client = client or zvmutils.get_smt_userid() iucv_path = "/tmp/" + userid if not os.path.exists(iucv_path): os.makedirs(iucv_path) iucv_auth_file = iucv_path + "/iucvauth.sh" zvmutils.generate_iucv_authfile(iucv_auth_file, client) try: requestData = "ChangeVM " + userid + " punchfile " + \ iucv_auth_file + " --class x" self._request(requestData) except exception.SDKSMTRequestFailed as err: msg = ("Failed to punch IUCV auth file to userid '%s'. SMT error:" " %s" % (userid, err.format_message())) LOG.error(msg) raise exception.SDKSMTRequestFailed(err.results, msg) finally: self._pathutils.clean_temp_folder(iucv_path)
[ "def", "guest_authorize_iucv_client", "(", "self", ",", "userid", ",", "client", "=", "None", ")", ":", "client", "=", "client", "or", "zvmutils", ".", "get_smt_userid", "(", ")", "iucv_path", "=", "\"/tmp/\"", "+", "userid", "if", "not", "os", ".", "path"...
Punch a script that used to set the authorized client userid in vm If the guest is in log off status, the change will take effect when the guest start up at first time. If the guest is in active status, power off and power on are needed for the change to take effect. :param str guest: the user id of the vm :param str client: the user id of the client that can communicate to guest using IUCV
[ "Punch", "a", "script", "that", "used", "to", "set", "the", "authorized", "client", "userid", "in", "vm", "If", "the", "guest", "is", "in", "log", "off", "status", "the", "change", "will", "take", "effect", "when", "the", "guest", "start", "up", "at", ...
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/smtclient.py#L580-L609
train
43,575
mfcloud/python-zvm-sdk
zvmsdk/smtclient.py
SMTClient.grant_user_to_vswitch
def grant_user_to_vswitch(self, vswitch_name, userid): """Set vswitch to grant user.""" smt_userid = zvmutils.get_smt_userid() requestData = ' '.join(( 'SMAPI %s API Virtual_Network_Vswitch_Set_Extended' % smt_userid, "--operands", "-k switch_name=%s" % vswitch_name, "-k grant_userid=%s" % userid, "-k persist=YES")) try: self._request(requestData) except exception.SDKSMTRequestFailed as err: LOG.error("Failed to grant user %s to vswitch %s, error: %s" % (userid, vswitch_name, err.format_message())) self._set_vswitch_exception(err, vswitch_name)
python
def grant_user_to_vswitch(self, vswitch_name, userid): """Set vswitch to grant user.""" smt_userid = zvmutils.get_smt_userid() requestData = ' '.join(( 'SMAPI %s API Virtual_Network_Vswitch_Set_Extended' % smt_userid, "--operands", "-k switch_name=%s" % vswitch_name, "-k grant_userid=%s" % userid, "-k persist=YES")) try: self._request(requestData) except exception.SDKSMTRequestFailed as err: LOG.error("Failed to grant user %s to vswitch %s, error: %s" % (userid, vswitch_name, err.format_message())) self._set_vswitch_exception(err, vswitch_name)
[ "def", "grant_user_to_vswitch", "(", "self", ",", "vswitch_name", ",", "userid", ")", ":", "smt_userid", "=", "zvmutils", ".", "get_smt_userid", "(", ")", "requestData", "=", "' '", ".", "join", "(", "(", "'SMAPI %s API Virtual_Network_Vswitch_Set_Extended'", "%", ...
Set vswitch to grant user.
[ "Set", "vswitch", "to", "grant", "user", "." ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/smtclient.py#L926-L941
train
43,576
mfcloud/python-zvm-sdk
zvmsdk/smtclient.py
SMTClient.image_performance_query
def image_performance_query(self, uid_list): """Call Image_Performance_Query to get guest current status. :uid_list: A list of zvm userids to be queried """ if uid_list == []: return {} if not isinstance(uid_list, list): uid_list = [uid_list] smt_userid = zvmutils.get_smt_userid() rd = ' '.join(( "SMAPI %s API Image_Performance_Query" % smt_userid, "--operands", '-T "%s"' % (' '.join(uid_list)), "-c %d" % len(uid_list))) action = "get performance info of userid '%s'" % str(uid_list) with zvmutils.log_and_reraise_smt_request_failed(action): results = self._request(rd) ipq_kws = { 'userid': "Guest name:", 'guest_cpus': "Guest CPUs:", 'used_cpu_time': "Used CPU time:", 'elapsed_cpu_time': "Elapsed time:", 'min_cpu_count': "Minimum CPU count:", 'max_cpu_limit': "Max CPU limit:", 'samples_cpu_in_use': "Samples CPU in use:", 'samples_cpu_delay': "Samples CPU delay:", 'used_memory': "Used memory:", 'max_memory': "Max memory:", 'min_memory': "Minimum memory:", 'shared_memory': "Shared memory:", } pi_dict = {} pi = {} rpi_list = ('\n'.join(results['response'])).split("\n\n") for rpi in rpi_list: try: pi = zvmutils.translate_response_to_dict(rpi, ipq_kws) except exception.SDKInternalError as err: emsg = err.format_message() # when there is only one userid queried and this userid is # in 'off'state, the smcli will only returns the queried # userid number, no valid performance info returned. if(emsg.__contains__("No value matched with keywords.")): continue else: raise err for k, v in pi.items(): pi[k] = v.strip('" ') if pi.get('userid') is not None: pi_dict[pi['userid']] = pi return pi_dict
python
def image_performance_query(self, uid_list): """Call Image_Performance_Query to get guest current status. :uid_list: A list of zvm userids to be queried """ if uid_list == []: return {} if not isinstance(uid_list, list): uid_list = [uid_list] smt_userid = zvmutils.get_smt_userid() rd = ' '.join(( "SMAPI %s API Image_Performance_Query" % smt_userid, "--operands", '-T "%s"' % (' '.join(uid_list)), "-c %d" % len(uid_list))) action = "get performance info of userid '%s'" % str(uid_list) with zvmutils.log_and_reraise_smt_request_failed(action): results = self._request(rd) ipq_kws = { 'userid': "Guest name:", 'guest_cpus': "Guest CPUs:", 'used_cpu_time': "Used CPU time:", 'elapsed_cpu_time': "Elapsed time:", 'min_cpu_count': "Minimum CPU count:", 'max_cpu_limit': "Max CPU limit:", 'samples_cpu_in_use': "Samples CPU in use:", 'samples_cpu_delay': "Samples CPU delay:", 'used_memory': "Used memory:", 'max_memory': "Max memory:", 'min_memory': "Minimum memory:", 'shared_memory': "Shared memory:", } pi_dict = {} pi = {} rpi_list = ('\n'.join(results['response'])).split("\n\n") for rpi in rpi_list: try: pi = zvmutils.translate_response_to_dict(rpi, ipq_kws) except exception.SDKInternalError as err: emsg = err.format_message() # when there is only one userid queried and this userid is # in 'off'state, the smcli will only returns the queried # userid number, no valid performance info returned. if(emsg.__contains__("No value matched with keywords.")): continue else: raise err for k, v in pi.items(): pi[k] = v.strip('" ') if pi.get('userid') is not None: pi_dict[pi['userid']] = pi return pi_dict
[ "def", "image_performance_query", "(", "self", ",", "uid_list", ")", ":", "if", "uid_list", "==", "[", "]", ":", "return", "{", "}", "if", "not", "isinstance", "(", "uid_list", ",", "list", ")", ":", "uid_list", "=", "[", "uid_list", "]", "smt_userid", ...
Call Image_Performance_Query to get guest current status. :uid_list: A list of zvm userids to be queried
[ "Call", "Image_Performance_Query", "to", "get", "guest", "current", "status", "." ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/smtclient.py#L985-L1041
train
43,577
mfcloud/python-zvm-sdk
zvmsdk/smtclient.py
SMTClient.system_image_performance_query
def system_image_performance_query(self, namelist): """Call System_Image_Performance_Query to get guest current status. :namelist: A namelist that defined in smapi namelist file. """ smt_userid = zvmutils.get_smt_userid() rd = ' '.join(( "SMAPI %s API System_Image_Performance_Query" % smt_userid, "--operands -T %s" % namelist)) action = "get performance info of namelist '%s'" % namelist with zvmutils.log_and_reraise_smt_request_failed(action): results = self._request(rd) ipq_kws = { 'userid': "Guest name:", 'guest_cpus': "Guest CPUs:", 'used_cpu_time': "Used CPU time:", 'elapsed_cpu_time': "Elapsed time:", 'min_cpu_count': "Minimum CPU count:", 'max_cpu_limit': "Max CPU limit:", 'samples_cpu_in_use': "Samples CPU in use:", 'samples_cpu_delay': "Samples CPU delay:", 'used_memory': "Used memory:", 'max_memory': "Max memory:", 'min_memory': "Minimum memory:", 'shared_memory': "Shared memory:", } pi_dict = {} pi = {} rpi_list = ('\n'.join(results['response'])).split("\n\n") for rpi in rpi_list: try: pi = zvmutils.translate_response_to_dict(rpi, ipq_kws) except exception.SDKInternalError as err: emsg = err.format_message() # when there is only one userid queried and this userid is # in 'off'state, the smcli will only returns the queried # userid number, no valid performance info returned. if(emsg.__contains__("No value matched with keywords.")): continue else: raise err for k, v in pi.items(): pi[k] = v.strip('" ') if pi.get('userid') is not None: pi_dict[pi['userid']] = pi return pi_dict
python
def system_image_performance_query(self, namelist): """Call System_Image_Performance_Query to get guest current status. :namelist: A namelist that defined in smapi namelist file. """ smt_userid = zvmutils.get_smt_userid() rd = ' '.join(( "SMAPI %s API System_Image_Performance_Query" % smt_userid, "--operands -T %s" % namelist)) action = "get performance info of namelist '%s'" % namelist with zvmutils.log_and_reraise_smt_request_failed(action): results = self._request(rd) ipq_kws = { 'userid': "Guest name:", 'guest_cpus': "Guest CPUs:", 'used_cpu_time': "Used CPU time:", 'elapsed_cpu_time': "Elapsed time:", 'min_cpu_count': "Minimum CPU count:", 'max_cpu_limit': "Max CPU limit:", 'samples_cpu_in_use': "Samples CPU in use:", 'samples_cpu_delay': "Samples CPU delay:", 'used_memory': "Used memory:", 'max_memory': "Max memory:", 'min_memory': "Minimum memory:", 'shared_memory': "Shared memory:", } pi_dict = {} pi = {} rpi_list = ('\n'.join(results['response'])).split("\n\n") for rpi in rpi_list: try: pi = zvmutils.translate_response_to_dict(rpi, ipq_kws) except exception.SDKInternalError as err: emsg = err.format_message() # when there is only one userid queried and this userid is # in 'off'state, the smcli will only returns the queried # userid number, no valid performance info returned. if(emsg.__contains__("No value matched with keywords.")): continue else: raise err for k, v in pi.items(): pi[k] = v.strip('" ') if pi.get('userid') is not None: pi_dict[pi['userid']] = pi return pi_dict
[ "def", "system_image_performance_query", "(", "self", ",", "namelist", ")", ":", "smt_userid", "=", "zvmutils", ".", "get_smt_userid", "(", ")", "rd", "=", "' '", ".", "join", "(", "(", "\"SMAPI %s API System_Image_Performance_Query\"", "%", "smt_userid", ",", "\"...
Call System_Image_Performance_Query to get guest current status. :namelist: A namelist that defined in smapi namelist file.
[ "Call", "System_Image_Performance_Query", "to", "get", "guest", "current", "status", "." ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/smtclient.py#L1043-L1091
train
43,578
mfcloud/python-zvm-sdk
zvmsdk/smtclient.py
SMTClient._couple_nic
def _couple_nic(self, userid, vdev, vswitch_name, active=False): """Couple NIC to vswitch by adding vswitch into user direct.""" if active: self._is_active(userid) msg = ('Start to couple nic device %(vdev)s of guest %(vm)s ' 'with vswitch %(vsw)s' % {'vdev': vdev, 'vm': userid, 'vsw': vswitch_name}) LOG.info(msg) requestData = ' '.join(( 'SMAPI %s' % userid, "API Virtual_Network_Adapter_Connect_Vswitch_DM", "--operands", "-v %s" % vdev, "-n %s" % vswitch_name)) try: self._request(requestData) except exception.SDKSMTRequestFailed as err: LOG.error("Failed to couple nic %s to vswitch %s for user %s " "in the guest's user direct, error: %s" % (vdev, vswitch_name, userid, err.format_message())) self._couple_inactive_exception(err, userid, vdev, vswitch_name) # the inst must be active, or this call will failed if active: requestData = ' '.join(( 'SMAPI %s' % userid, 'API Virtual_Network_Adapter_Connect_Vswitch', "--operands", "-v %s" % vdev, "-n %s" % vswitch_name)) try: self._request(requestData) except (exception.SDKSMTRequestFailed, exception.SDKInternalError) as err1: results1 = err1.results msg1 = err1.format_message() if ((results1 is not None) and (results1['rc'] == 204) and (results1['rs'] == 20)): LOG.warning("Virtual device %s already connected " "on the active guest system", vdev) else: persist_OK = True requestData = ' '.join(( 'SMAPI %s' % userid, 'API Virtual_Network_Adapter_Disconnect_DM', "--operands", '-v %s' % vdev)) try: self._request(requestData) except (exception.SDKSMTRequestFailed, exception.SDKInternalError) as err2: results2 = err2.results msg2 = err2.format_message() if ((results2 is not None) and (results2['rc'] == 212) and (results2['rs'] == 32)): persist_OK = True else: persist_OK = False if persist_OK: self._couple_active_exception(err1, userid, vdev, vswitch_name) else: raise exception.SDKNetworkOperationError(rs=3, nic=vdev, vswitch=vswitch_name, couple_err=msg1, revoke_err=msg2) """Update information in switch table.""" self._NetDbOperator.switch_update_record_with_switch(userid, vdev, vswitch_name) msg = ('Couple nic device %(vdev)s of guest %(vm)s ' 'with vswitch %(vsw)s successfully' % {'vdev': vdev, 'vm': userid, 'vsw': vswitch_name}) LOG.info(msg)
python
def _couple_nic(self, userid, vdev, vswitch_name, active=False): """Couple NIC to vswitch by adding vswitch into user direct.""" if active: self._is_active(userid) msg = ('Start to couple nic device %(vdev)s of guest %(vm)s ' 'with vswitch %(vsw)s' % {'vdev': vdev, 'vm': userid, 'vsw': vswitch_name}) LOG.info(msg) requestData = ' '.join(( 'SMAPI %s' % userid, "API Virtual_Network_Adapter_Connect_Vswitch_DM", "--operands", "-v %s" % vdev, "-n %s" % vswitch_name)) try: self._request(requestData) except exception.SDKSMTRequestFailed as err: LOG.error("Failed to couple nic %s to vswitch %s for user %s " "in the guest's user direct, error: %s" % (vdev, vswitch_name, userid, err.format_message())) self._couple_inactive_exception(err, userid, vdev, vswitch_name) # the inst must be active, or this call will failed if active: requestData = ' '.join(( 'SMAPI %s' % userid, 'API Virtual_Network_Adapter_Connect_Vswitch', "--operands", "-v %s" % vdev, "-n %s" % vswitch_name)) try: self._request(requestData) except (exception.SDKSMTRequestFailed, exception.SDKInternalError) as err1: results1 = err1.results msg1 = err1.format_message() if ((results1 is not None) and (results1['rc'] == 204) and (results1['rs'] == 20)): LOG.warning("Virtual device %s already connected " "on the active guest system", vdev) else: persist_OK = True requestData = ' '.join(( 'SMAPI %s' % userid, 'API Virtual_Network_Adapter_Disconnect_DM', "--operands", '-v %s' % vdev)) try: self._request(requestData) except (exception.SDKSMTRequestFailed, exception.SDKInternalError) as err2: results2 = err2.results msg2 = err2.format_message() if ((results2 is not None) and (results2['rc'] == 212) and (results2['rs'] == 32)): persist_OK = True else: persist_OK = False if persist_OK: self._couple_active_exception(err1, userid, vdev, vswitch_name) else: raise exception.SDKNetworkOperationError(rs=3, nic=vdev, vswitch=vswitch_name, couple_err=msg1, revoke_err=msg2) """Update information in switch table.""" self._NetDbOperator.switch_update_record_with_switch(userid, vdev, vswitch_name) msg = ('Couple nic device %(vdev)s of guest %(vm)s ' 'with vswitch %(vsw)s successfully' % {'vdev': vdev, 'vm': userid, 'vsw': vswitch_name}) LOG.info(msg)
[ "def", "_couple_nic", "(", "self", ",", "userid", ",", "vdev", ",", "vswitch_name", ",", "active", "=", "False", ")", ":", "if", "active", ":", "self", ".", "_is_active", "(", "userid", ")", "msg", "=", "(", "'Start to couple nic device %(vdev)s of guest %(vm)...
Couple NIC to vswitch by adding vswitch into user direct.
[ "Couple", "NIC", "to", "vswitch", "by", "adding", "vswitch", "into", "user", "direct", "." ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/smtclient.py#L1580-L1658
train
43,579
mfcloud/python-zvm-sdk
zvmsdk/smtclient.py
SMTClient.couple_nic_to_vswitch
def couple_nic_to_vswitch(self, userid, nic_vdev, vswitch_name, active=False): """Couple nic to vswitch.""" if active: msg = ("both in the user direct of guest %s and on " "the active guest system" % userid) else: msg = "in the user direct of guest %s" % userid LOG.debug("Connect nic %s to switch %s %s", nic_vdev, vswitch_name, msg) self._couple_nic(userid, nic_vdev, vswitch_name, active=active)
python
def couple_nic_to_vswitch(self, userid, nic_vdev, vswitch_name, active=False): """Couple nic to vswitch.""" if active: msg = ("both in the user direct of guest %s and on " "the active guest system" % userid) else: msg = "in the user direct of guest %s" % userid LOG.debug("Connect nic %s to switch %s %s", nic_vdev, vswitch_name, msg) self._couple_nic(userid, nic_vdev, vswitch_name, active=active)
[ "def", "couple_nic_to_vswitch", "(", "self", ",", "userid", ",", "nic_vdev", ",", "vswitch_name", ",", "active", "=", "False", ")", ":", "if", "active", ":", "msg", "=", "(", "\"both in the user direct of guest %s and on \"", "\"the active guest system\"", "%", "use...
Couple nic to vswitch.
[ "Couple", "nic", "to", "vswitch", "." ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/smtclient.py#L1660-L1670
train
43,580
mfcloud/python-zvm-sdk
zvmsdk/smtclient.py
SMTClient._uncouple_nic
def _uncouple_nic(self, userid, vdev, active=False): """Uncouple NIC from vswitch""" if active: self._is_active(userid) msg = ('Start to uncouple nic device %(vdev)s of guest %(vm)s' % {'vdev': vdev, 'vm': userid}) LOG.info(msg) requestData = ' '.join(( 'SMAPI %s' % userid, "API Virtual_Network_Adapter_Disconnect_DM", "--operands", "-v %s" % vdev)) try: self._request(requestData) except (exception.SDKSMTRequestFailed, exception.SDKInternalError) as err: results = err.results emsg = err.format_message() if ((results is not None) and (results['rc'] == 212) and (results['rs'] == 32)): LOG.warning("Virtual device %s is already disconnected " "in the guest's user direct", vdev) else: LOG.error("Failed to uncouple nic %s in the guest's user " "direct, error: %s" % (vdev, emsg)) self._uncouple_inactive_exception(err, userid, vdev) """Update information in switch table.""" self._NetDbOperator.switch_update_record_with_switch(userid, vdev, None) # the inst must be active, or this call will failed if active: requestData = ' '.join(( 'SMAPI %s' % userid, 'API Virtual_Network_Adapter_Disconnect', "--operands", "-v %s" % vdev)) try: self._request(requestData) except (exception.SDKSMTRequestFailed, exception.SDKInternalError) as err: results = err.results emsg = err.format_message() if ((results is not None) and (results['rc'] == 204) and (results['rs'] == 48)): LOG.warning("Virtual device %s is already " "disconnected on the active " "guest system", vdev) else: LOG.error("Failed to uncouple nic %s on the active " "guest system, error: %s" % (vdev, emsg)) self._uncouple_active_exception(err, userid, vdev) msg = ('Uncouple nic device %(vdev)s of guest %(vm)s successfully' % {'vdev': vdev, 'vm': userid}) LOG.info(msg)
python
def _uncouple_nic(self, userid, vdev, active=False): """Uncouple NIC from vswitch""" if active: self._is_active(userid) msg = ('Start to uncouple nic device %(vdev)s of guest %(vm)s' % {'vdev': vdev, 'vm': userid}) LOG.info(msg) requestData = ' '.join(( 'SMAPI %s' % userid, "API Virtual_Network_Adapter_Disconnect_DM", "--operands", "-v %s" % vdev)) try: self._request(requestData) except (exception.SDKSMTRequestFailed, exception.SDKInternalError) as err: results = err.results emsg = err.format_message() if ((results is not None) and (results['rc'] == 212) and (results['rs'] == 32)): LOG.warning("Virtual device %s is already disconnected " "in the guest's user direct", vdev) else: LOG.error("Failed to uncouple nic %s in the guest's user " "direct, error: %s" % (vdev, emsg)) self._uncouple_inactive_exception(err, userid, vdev) """Update information in switch table.""" self._NetDbOperator.switch_update_record_with_switch(userid, vdev, None) # the inst must be active, or this call will failed if active: requestData = ' '.join(( 'SMAPI %s' % userid, 'API Virtual_Network_Adapter_Disconnect', "--operands", "-v %s" % vdev)) try: self._request(requestData) except (exception.SDKSMTRequestFailed, exception.SDKInternalError) as err: results = err.results emsg = err.format_message() if ((results is not None) and (results['rc'] == 204) and (results['rs'] == 48)): LOG.warning("Virtual device %s is already " "disconnected on the active " "guest system", vdev) else: LOG.error("Failed to uncouple nic %s on the active " "guest system, error: %s" % (vdev, emsg)) self._uncouple_active_exception(err, userid, vdev) msg = ('Uncouple nic device %(vdev)s of guest %(vm)s successfully' % {'vdev': vdev, 'vm': userid}) LOG.info(msg)
[ "def", "_uncouple_nic", "(", "self", ",", "userid", ",", "vdev", ",", "active", "=", "False", ")", ":", "if", "active", ":", "self", ".", "_is_active", "(", "userid", ")", "msg", "=", "(", "'Start to uncouple nic device %(vdev)s of guest %(vm)s'", "%", "{", ...
Uncouple NIC from vswitch
[ "Uncouple", "NIC", "from", "vswitch" ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/smtclient.py#L1702-L1761
train
43,581
mfcloud/python-zvm-sdk
zvmsdk/smtclient.py
SMTClient._get_image_size
def _get_image_size(self, image_path): """Return disk size in bytes""" command = 'du -b %s' % image_path (rc, output) = zvmutils.execute(command) if rc: msg = ("Error happened when executing command du -b with" "reason: %s" % output) LOG.error(msg) raise exception.SDKImageOperationError(rs=8) size = output.split()[0] return size
python
def _get_image_size(self, image_path): """Return disk size in bytes""" command = 'du -b %s' % image_path (rc, output) = zvmutils.execute(command) if rc: msg = ("Error happened when executing command du -b with" "reason: %s" % output) LOG.error(msg) raise exception.SDKImageOperationError(rs=8) size = output.split()[0] return size
[ "def", "_get_image_size", "(", "self", ",", "image_path", ")", ":", "command", "=", "'du -b %s'", "%", "image_path", "(", "rc", ",", "output", ")", "=", "zvmutils", ".", "execute", "(", "command", ")", "if", "rc", ":", "msg", "=", "(", "\"Error happened ...
Return disk size in bytes
[ "Return", "disk", "size", "in", "bytes" ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/smtclient.py#L2007-L2017
train
43,582
mfcloud/python-zvm-sdk
zvmsdk/smtclient.py
SMTClient._get_md5sum
def _get_md5sum(self, fpath): """Calculate the md5sum of the specific image file""" try: current_md5 = hashlib.md5() if isinstance(fpath, six.string_types) and os.path.exists(fpath): with open(fpath, "rb") as fh: for chunk in self._read_chunks(fh): current_md5.update(chunk) elif (fpath.__class__.__name__ in ["StringIO", "StringO"] or isinstance(fpath, IOBase)): for chunk in self._read_chunks(fpath): current_md5.update(chunk) else: return "" return current_md5.hexdigest() except Exception: msg = ("Failed to calculate the image's md5sum") LOG.error(msg) raise exception.SDKImageOperationError(rs=3)
python
def _get_md5sum(self, fpath): """Calculate the md5sum of the specific image file""" try: current_md5 = hashlib.md5() if isinstance(fpath, six.string_types) and os.path.exists(fpath): with open(fpath, "rb") as fh: for chunk in self._read_chunks(fh): current_md5.update(chunk) elif (fpath.__class__.__name__ in ["StringIO", "StringO"] or isinstance(fpath, IOBase)): for chunk in self._read_chunks(fpath): current_md5.update(chunk) else: return "" return current_md5.hexdigest() except Exception: msg = ("Failed to calculate the image's md5sum") LOG.error(msg) raise exception.SDKImageOperationError(rs=3)
[ "def", "_get_md5sum", "(", "self", ",", "fpath", ")", ":", "try", ":", "current_md5", "=", "hashlib", ".", "md5", "(", ")", "if", "isinstance", "(", "fpath", ",", "six", ".", "string_types", ")", "and", "os", ".", "path", ".", "exists", "(", "fpath",...
Calculate the md5sum of the specific image file
[ "Calculate", "the", "md5sum", "of", "the", "specific", "image", "file" ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/smtclient.py#L2047-L2066
train
43,583
mfcloud/python-zvm-sdk
zvmsdk/smtclient.py
SMTClient.get_guest_connection_status
def get_guest_connection_status(self, userid): '''Get guest vm connection status.''' rd = ' '.join(('getvm', userid, 'isreachable')) results = self._request(rd) if results['rs'] == 1: return True else: return False
python
def get_guest_connection_status(self, userid): '''Get guest vm connection status.''' rd = ' '.join(('getvm', userid, 'isreachable')) results = self._request(rd) if results['rs'] == 1: return True else: return False
[ "def", "get_guest_connection_status", "(", "self", ",", "userid", ")", ":", "rd", "=", "' '", ".", "join", "(", "(", "'getvm'", ",", "userid", ",", "'isreachable'", ")", ")", "results", "=", "self", ".", "_request", "(", "rd", ")", "if", "results", "["...
Get guest vm connection status.
[ "Get", "guest", "vm", "connection", "status", "." ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/smtclient.py#L2125-L2132
train
43,584
mfcloud/python-zvm-sdk
zvmsdk/smtclient.py
SMTClient.process_additional_minidisks
def process_additional_minidisks(self, userid, disk_info): '''Generate and punch the scripts used to process additional disk into target vm's reader. ''' for idx, disk in enumerate(disk_info): vdev = disk.get('vdev') or self.generate_disk_vdev( offset = (idx + 1)) fmt = disk.get('format') mount_dir = disk.get('mntdir') or ''.join(['/mnt/ephemeral', str(vdev)]) disk_parms = self._generate_disk_parmline(vdev, fmt, mount_dir) func_name = '/var/lib/zvmsdk/setupDisk' self.aemod_handler(userid, func_name, disk_parms) # trigger do-script if self.get_power_state(userid) == 'on': self.execute_cmd(userid, "/usr/bin/zvmguestconfigure start")
python
def process_additional_minidisks(self, userid, disk_info): '''Generate and punch the scripts used to process additional disk into target vm's reader. ''' for idx, disk in enumerate(disk_info): vdev = disk.get('vdev') or self.generate_disk_vdev( offset = (idx + 1)) fmt = disk.get('format') mount_dir = disk.get('mntdir') or ''.join(['/mnt/ephemeral', str(vdev)]) disk_parms = self._generate_disk_parmline(vdev, fmt, mount_dir) func_name = '/var/lib/zvmsdk/setupDisk' self.aemod_handler(userid, func_name, disk_parms) # trigger do-script if self.get_power_state(userid) == 'on': self.execute_cmd(userid, "/usr/bin/zvmguestconfigure start")
[ "def", "process_additional_minidisks", "(", "self", ",", "userid", ",", "disk_info", ")", ":", "for", "idx", ",", "disk", "in", "enumerate", "(", "disk_info", ")", ":", "vdev", "=", "disk", ".", "get", "(", "'vdev'", ")", "or", "self", ".", "generate_dis...
Generate and punch the scripts used to process additional disk into target vm's reader.
[ "Generate", "and", "punch", "the", "scripts", "used", "to", "process", "additional", "disk", "into", "target", "vm", "s", "reader", "." ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/smtclient.py#L2145-L2161
train
43,585
mfcloud/python-zvm-sdk
zvmsdk/smtclient.py
SMTClient._request_with_error_ignored
def _request_with_error_ignored(self, rd): """Send smt request, log and ignore any errors.""" try: return self._request(rd) except Exception as err: # log as warning and ignore namelist operation failures LOG.warning(six.text_type(err))
python
def _request_with_error_ignored(self, rd): """Send smt request, log and ignore any errors.""" try: return self._request(rd) except Exception as err: # log as warning and ignore namelist operation failures LOG.warning(six.text_type(err))
[ "def", "_request_with_error_ignored", "(", "self", ",", "rd", ")", ":", "try", ":", "return", "self", ".", "_request", "(", "rd", ")", "except", "Exception", "as", "err", ":", "# log as warning and ignore namelist operation failures", "LOG", ".", "warning", "(", ...
Send smt request, log and ignore any errors.
[ "Send", "smt", "request", "log", "and", "ignore", "any", "errors", "." ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/smtclient.py#L2743-L2749
train
43,586
mfcloud/python-zvm-sdk
zvmsdk/smtclient.py
FilesystemBackend.image_import
def image_import(cls, image_name, url, target, **kwargs): """Import image from remote host to local image repository using scp. If remote_host not specified, it means the source file exist in local file system, just copy the image to image repository """ source = urlparse.urlparse(url).path if kwargs['remote_host']: if '@' in kwargs['remote_host']: source_path = ':'.join([kwargs['remote_host'], source]) command = ' '.join(['/usr/bin/scp', "-P", CONF.zvm.remotehost_sshd_port, "-o StrictHostKeyChecking=no", '-r ', source_path, target]) (rc, output) = zvmutils.execute(command) if rc: msg = ("Copying image file from remote filesystem failed" " with reason: %s" % output) LOG.error(msg) raise exception.SDKImageOperationError(rs=10, err=output) else: msg = ("The specified remote_host %s format invalid" % kwargs['remote_host']) LOG.error(msg) raise exception.SDKImageOperationError(rs=11, rh=kwargs['remote_host']) else: LOG.debug("Remote_host not specified, will copy from local") try: shutil.copyfile(source, target) except Exception as err: msg = ("Import image from local file system failed" " with reason %s" % six.text_type(err)) LOG.error(msg) raise exception.SDKImageOperationError(rs=12, err=six.text_type(err))
python
def image_import(cls, image_name, url, target, **kwargs): """Import image from remote host to local image repository using scp. If remote_host not specified, it means the source file exist in local file system, just copy the image to image repository """ source = urlparse.urlparse(url).path if kwargs['remote_host']: if '@' in kwargs['remote_host']: source_path = ':'.join([kwargs['remote_host'], source]) command = ' '.join(['/usr/bin/scp', "-P", CONF.zvm.remotehost_sshd_port, "-o StrictHostKeyChecking=no", '-r ', source_path, target]) (rc, output) = zvmutils.execute(command) if rc: msg = ("Copying image file from remote filesystem failed" " with reason: %s" % output) LOG.error(msg) raise exception.SDKImageOperationError(rs=10, err=output) else: msg = ("The specified remote_host %s format invalid" % kwargs['remote_host']) LOG.error(msg) raise exception.SDKImageOperationError(rs=11, rh=kwargs['remote_host']) else: LOG.debug("Remote_host not specified, will copy from local") try: shutil.copyfile(source, target) except Exception as err: msg = ("Import image from local file system failed" " with reason %s" % six.text_type(err)) LOG.error(msg) raise exception.SDKImageOperationError(rs=12, err=six.text_type(err))
[ "def", "image_import", "(", "cls", ",", "image_name", ",", "url", ",", "target", ",", "*", "*", "kwargs", ")", ":", "source", "=", "urlparse", ".", "urlparse", "(", "url", ")", ".", "path", "if", "kwargs", "[", "'remote_host'", "]", ":", "if", "'@'",...
Import image from remote host to local image repository using scp. If remote_host not specified, it means the source file exist in local file system, just copy the image to image repository
[ "Import", "image", "from", "remote", "host", "to", "local", "image", "repository", "using", "scp", ".", "If", "remote_host", "not", "specified", "it", "means", "the", "source", "file", "exist", "in", "local", "file", "system", "just", "copy", "the", "image",...
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/smtclient.py#L3273-L3307
train
43,587
mfcloud/python-zvm-sdk
zvmsdk/smtclient.py
FilesystemBackend.image_export
def image_export(cls, source_path, dest_url, **kwargs): """Export the specific image to remote host or local file system """ dest_path = urlparse.urlparse(dest_url).path if kwargs['remote_host']: target_path = ':'.join([kwargs['remote_host'], dest_path]) command = ' '.join(['/usr/bin/scp', "-P", CONF.zvm.remotehost_sshd_port, "-o StrictHostKeyChecking=no", '-r ', source_path, target_path]) (rc, output) = zvmutils.execute(command) if rc: msg = ("Error happened when copying image file to remote " "host with reason: %s" % output) LOG.error(msg) raise exception.SDKImageOperationError(rs=21, msg=output) else: # Copy to local file system LOG.debug("Remote_host not specified, will copy to local server") try: shutil.copyfile(source_path, dest_path) except Exception as err: msg = ("Export image from %(src)s to local file system" " %(dest)s failed: %(err)s" % {'src': source_path, 'dest': dest_path, 'err': six.text_type(err)}) LOG.error(msg) raise exception.SDKImageOperationError(rs=22, err=six.text_type(err))
python
def image_export(cls, source_path, dest_url, **kwargs): """Export the specific image to remote host or local file system """ dest_path = urlparse.urlparse(dest_url).path if kwargs['remote_host']: target_path = ':'.join([kwargs['remote_host'], dest_path]) command = ' '.join(['/usr/bin/scp', "-P", CONF.zvm.remotehost_sshd_port, "-o StrictHostKeyChecking=no", '-r ', source_path, target_path]) (rc, output) = zvmutils.execute(command) if rc: msg = ("Error happened when copying image file to remote " "host with reason: %s" % output) LOG.error(msg) raise exception.SDKImageOperationError(rs=21, msg=output) else: # Copy to local file system LOG.debug("Remote_host not specified, will copy to local server") try: shutil.copyfile(source_path, dest_path) except Exception as err: msg = ("Export image from %(src)s to local file system" " %(dest)s failed: %(err)s" % {'src': source_path, 'dest': dest_path, 'err': six.text_type(err)}) LOG.error(msg) raise exception.SDKImageOperationError(rs=22, err=six.text_type(err))
[ "def", "image_export", "(", "cls", ",", "source_path", ",", "dest_url", ",", "*", "*", "kwargs", ")", ":", "dest_path", "=", "urlparse", ".", "urlparse", "(", "dest_url", ")", ".", "path", "if", "kwargs", "[", "'remote_host'", "]", ":", "target_path", "=...
Export the specific image to remote host or local file system
[ "Export", "the", "specific", "image", "to", "remote", "host", "or", "local", "file", "system" ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/smtclient.py#L3310-L3338
train
43,588
Chilipp/psyplot
psyplot/docstring.py
indent
def indent(text, num=4): """Indet the given string""" str_indent = ' ' * num return str_indent + ('\n' + str_indent).join(text.splitlines())
python
def indent(text, num=4): """Indet the given string""" str_indent = ' ' * num return str_indent + ('\n' + str_indent).join(text.splitlines())
[ "def", "indent", "(", "text", ",", "num", "=", "4", ")", ":", "str_indent", "=", "' '", "*", "num", "return", "str_indent", "+", "(", "'\\n'", "+", "str_indent", ")", ".", "join", "(", "text", ".", "splitlines", "(", ")", ")" ]
Indet the given string
[ "Indet", "the", "given", "string" ]
75a0a15a9a1dd018e79d2df270d56c4bf5f311d5
https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/docstring.py#L26-L29
train
43,589
Chilipp/psyplot
psyplot/docstring.py
append_original_doc
def append_original_doc(parent, num=0): """Return an iterator that append the docstring of the given `parent` function to the applied function""" def func(func): func.__doc__ = func.__doc__ and func.__doc__ + indent( parent.__doc__, num) return func return func
python
def append_original_doc(parent, num=0): """Return an iterator that append the docstring of the given `parent` function to the applied function""" def func(func): func.__doc__ = func.__doc__ and func.__doc__ + indent( parent.__doc__, num) return func return func
[ "def", "append_original_doc", "(", "parent", ",", "num", "=", "0", ")", ":", "def", "func", "(", "func", ")", ":", "func", ".", "__doc__", "=", "func", ".", "__doc__", "and", "func", ".", "__doc__", "+", "indent", "(", "parent", ".", "__doc__", ",", ...
Return an iterator that append the docstring of the given `parent` function to the applied function
[ "Return", "an", "iterator", "that", "append", "the", "docstring", "of", "the", "given", "parent", "function", "to", "the", "applied", "function" ]
75a0a15a9a1dd018e79d2df270d56c4bf5f311d5
https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/docstring.py#L32-L39
train
43,590
Chilipp/psyplot
psyplot/docstring.py
PsyplotDocstringProcessor.get_sections
def get_sections(self, s, base, sections=[ 'Parameters', 'Other Parameters', 'Possible types']): """ Extract the specified sections out of the given string The same as the :meth:`docrep.DocstringProcessor.get_sections` method but uses the ``'Possible types'`` section by default, too Parameters ---------- %(DocstringProcessor.get_sections.parameters)s Returns ------- str The replaced string """ return super(PsyplotDocstringProcessor, self).get_sections(s, base, sections)
python
def get_sections(self, s, base, sections=[ 'Parameters', 'Other Parameters', 'Possible types']): """ Extract the specified sections out of the given string The same as the :meth:`docrep.DocstringProcessor.get_sections` method but uses the ``'Possible types'`` section by default, too Parameters ---------- %(DocstringProcessor.get_sections.parameters)s Returns ------- str The replaced string """ return super(PsyplotDocstringProcessor, self).get_sections(s, base, sections)
[ "def", "get_sections", "(", "self", ",", "s", ",", "base", ",", "sections", "=", "[", "'Parameters'", ",", "'Other Parameters'", ",", "'Possible types'", "]", ")", ":", "return", "super", "(", "PsyplotDocstringProcessor", ",", "self", ")", ".", "get_sections",...
Extract the specified sections out of the given string The same as the :meth:`docrep.DocstringProcessor.get_sections` method but uses the ``'Possible types'`` section by default, too Parameters ---------- %(DocstringProcessor.get_sections.parameters)s Returns ------- str The replaced string
[ "Extract", "the", "specified", "sections", "out", "of", "the", "given", "string" ]
75a0a15a9a1dd018e79d2df270d56c4bf5f311d5
https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/docstring.py#L57-L75
train
43,591
mfcloud/python-zvm-sdk
zvmsdk/configdrive.py
create_config_drive
def create_config_drive(network_interface_info, os_version): """Generate config driver for zVM guest vm. :param dict network_interface_info: Required keys: ip_addr - (str) IP address nic_vdev - (str) VDEV of the nic gateway_v4 - IPV4 gateway broadcast_v4 - IPV4 broadcast address netmask_v4 - IPV4 netmask :param str os_version: operating system version of the guest """ temp_path = CONF.guest.temp_path if not os.path.exists(temp_path): os.mkdir(temp_path) cfg_dir = os.path.join(temp_path, 'openstack') if os.path.exists(cfg_dir): shutil.rmtree(cfg_dir) content_dir = os.path.join(cfg_dir, 'content') latest_dir = os.path.join(cfg_dir, 'latest') os.mkdir(cfg_dir) os.mkdir(content_dir) os.mkdir(latest_dir) net_file = os.path.join(content_dir, '0000') generate_net_file(network_interface_info, net_file, os_version) znetconfig_file = os.path.join(content_dir, '0001') generate_znetconfig_file(znetconfig_file, os_version) meta_data_path = os.path.join(latest_dir, 'meta_data.json') generate_meta_data(meta_data_path) network_data_path = os.path.join(latest_dir, 'network_data.json') generate_file('{}', network_data_path) vendor_data_path = os.path.join(latest_dir, 'vendor_data.json') generate_file('{}', vendor_data_path) tar_path = os.path.join(temp_path, 'cfgdrive.tgz') tar = tarfile.open(tar_path, "w:gz") os.chdir(temp_path) tar.add('openstack') tar.close() return tar_path
python
def create_config_drive(network_interface_info, os_version): """Generate config driver for zVM guest vm. :param dict network_interface_info: Required keys: ip_addr - (str) IP address nic_vdev - (str) VDEV of the nic gateway_v4 - IPV4 gateway broadcast_v4 - IPV4 broadcast address netmask_v4 - IPV4 netmask :param str os_version: operating system version of the guest """ temp_path = CONF.guest.temp_path if not os.path.exists(temp_path): os.mkdir(temp_path) cfg_dir = os.path.join(temp_path, 'openstack') if os.path.exists(cfg_dir): shutil.rmtree(cfg_dir) content_dir = os.path.join(cfg_dir, 'content') latest_dir = os.path.join(cfg_dir, 'latest') os.mkdir(cfg_dir) os.mkdir(content_dir) os.mkdir(latest_dir) net_file = os.path.join(content_dir, '0000') generate_net_file(network_interface_info, net_file, os_version) znetconfig_file = os.path.join(content_dir, '0001') generate_znetconfig_file(znetconfig_file, os_version) meta_data_path = os.path.join(latest_dir, 'meta_data.json') generate_meta_data(meta_data_path) network_data_path = os.path.join(latest_dir, 'network_data.json') generate_file('{}', network_data_path) vendor_data_path = os.path.join(latest_dir, 'vendor_data.json') generate_file('{}', vendor_data_path) tar_path = os.path.join(temp_path, 'cfgdrive.tgz') tar = tarfile.open(tar_path, "w:gz") os.chdir(temp_path) tar.add('openstack') tar.close() return tar_path
[ "def", "create_config_drive", "(", "network_interface_info", ",", "os_version", ")", ":", "temp_path", "=", "CONF", ".", "guest", ".", "temp_path", "if", "not", "os", ".", "path", ".", "exists", "(", "temp_path", ")", ":", "os", ".", "mkdir", "(", "temp_pa...
Generate config driver for zVM guest vm. :param dict network_interface_info: Required keys: ip_addr - (str) IP address nic_vdev - (str) VDEV of the nic gateway_v4 - IPV4 gateway broadcast_v4 - IPV4 broadcast address netmask_v4 - IPV4 netmask :param str os_version: operating system version of the guest
[ "Generate", "config", "driver", "for", "zVM", "guest", "vm", "." ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/configdrive.py#L113-L153
train
43,592
mfcloud/python-zvm-sdk
zvmsdk/monitor.py
MeteringCache.set
def set(self, ctype, key, data): """Set or update cache content. :param ctype: cache type :param key: the key to be set value :param data: cache data """ with zvmutils.acquire_lock(self._lock): target_cache = self._get_ctype_cache(ctype) target_cache['data'][key] = data
python
def set(self, ctype, key, data): """Set or update cache content. :param ctype: cache type :param key: the key to be set value :param data: cache data """ with zvmutils.acquire_lock(self._lock): target_cache = self._get_ctype_cache(ctype) target_cache['data'][key] = data
[ "def", "set", "(", "self", ",", "ctype", ",", "key", ",", "data", ")", ":", "with", "zvmutils", ".", "acquire_lock", "(", "self", ".", "_lock", ")", ":", "target_cache", "=", "self", ".", "_get_ctype_cache", "(", "ctype", ")", "target_cache", "[", "'da...
Set or update cache content. :param ctype: cache type :param key: the key to be set value :param data: cache data
[ "Set", "or", "update", "cache", "content", "." ]
de9994ceca764f5460ce51bd74237986341d8e3c
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/monitor.py#L190-L199
train
43,593
Chilipp/psyplot
psyplot/warning.py
warn
def warn(message, category=PsyPlotWarning, logger=None): """wrapper around the warnings.warn function for non-critical warnings. logger may be a logging.Logger instance""" if logger is not None: message = "[Warning by %s]\n%s" % (logger.name, message) warnings.warn(message, category, stacklevel=3)
python
def warn(message, category=PsyPlotWarning, logger=None): """wrapper around the warnings.warn function for non-critical warnings. logger may be a logging.Logger instance""" if logger is not None: message = "[Warning by %s]\n%s" % (logger.name, message) warnings.warn(message, category, stacklevel=3)
[ "def", "warn", "(", "message", ",", "category", "=", "PsyPlotWarning", ",", "logger", "=", "None", ")", ":", "if", "logger", "is", "not", "None", ":", "message", "=", "\"[Warning by %s]\\n%s\"", "%", "(", "logger", ".", "name", ",", "message", ")", "warn...
wrapper around the warnings.warn function for non-critical warnings. logger may be a logging.Logger instance
[ "wrapper", "around", "the", "warnings", ".", "warn", "function", "for", "non", "-", "critical", "warnings", ".", "logger", "may", "be", "a", "logging", ".", "Logger", "instance" ]
75a0a15a9a1dd018e79d2df270d56c4bf5f311d5
https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/warning.py#L66-L71
train
43,594
Chilipp/psyplot
psyplot/warning.py
critical
def critical(message, category=PsyPlotCritical, logger=None): """wrapper around the warnings.warn function for critical warnings. logger may be a logging.Logger instance""" if logger is not None: message = "[Critical warning by %s]\n%s" % (logger.name, message) warnings.warn(message, category, stacklevel=2)
python
def critical(message, category=PsyPlotCritical, logger=None): """wrapper around the warnings.warn function for critical warnings. logger may be a logging.Logger instance""" if logger is not None: message = "[Critical warning by %s]\n%s" % (logger.name, message) warnings.warn(message, category, stacklevel=2)
[ "def", "critical", "(", "message", ",", "category", "=", "PsyPlotCritical", ",", "logger", "=", "None", ")", ":", "if", "logger", "is", "not", "None", ":", "message", "=", "\"[Critical warning by %s]\\n%s\"", "%", "(", "logger", ".", "name", ",", "message", ...
wrapper around the warnings.warn function for critical warnings. logger may be a logging.Logger instance
[ "wrapper", "around", "the", "warnings", ".", "warn", "function", "for", "critical", "warnings", ".", "logger", "may", "be", "a", "logging", ".", "Logger", "instance" ]
75a0a15a9a1dd018e79d2df270d56c4bf5f311d5
https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/warning.py#L74-L79
train
43,595
Chilipp/psyplot
psyplot/warning.py
customwarn
def customwarn(message, category, filename, lineno, *args, **kwargs): """Use the psyplot.warning logger for categories being out of PsyPlotWarning and PsyPlotCritical and the default warnings.showwarning function for all the others.""" if category is PsyPlotWarning: logger.warning(warnings.formatwarning( "\n%s" % message, category, filename, lineno)) elif category is PsyPlotCritical: logger.critical(warnings.formatwarning( "\n%s" % message, category, filename, lineno), exc_info=True) else: old_showwarning(message, category, filename, lineno, *args, **kwargs)
python
def customwarn(message, category, filename, lineno, *args, **kwargs): """Use the psyplot.warning logger for categories being out of PsyPlotWarning and PsyPlotCritical and the default warnings.showwarning function for all the others.""" if category is PsyPlotWarning: logger.warning(warnings.formatwarning( "\n%s" % message, category, filename, lineno)) elif category is PsyPlotCritical: logger.critical(warnings.formatwarning( "\n%s" % message, category, filename, lineno), exc_info=True) else: old_showwarning(message, category, filename, lineno, *args, **kwargs)
[ "def", "customwarn", "(", "message", ",", "category", ",", "filename", ",", "lineno", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "category", "is", "PsyPlotWarning", ":", "logger", ".", "warning", "(", "warnings", ".", "formatwarning", "("...
Use the psyplot.warning logger for categories being out of PsyPlotWarning and PsyPlotCritical and the default warnings.showwarning function for all the others.
[ "Use", "the", "psyplot", ".", "warning", "logger", "for", "categories", "being", "out", "of", "PsyPlotWarning", "and", "PsyPlotCritical", "and", "the", "default", "warnings", ".", "showwarning", "function", "for", "all", "the", "others", "." ]
75a0a15a9a1dd018e79d2df270d56c4bf5f311d5
https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/warning.py#L85-L97
train
43,596
Chilipp/psyplot
psyplot/config/logsetup.py
_get_home
def _get_home(): """Find user's home directory if possible. Otherwise, returns None. :see: http://mail.python.org/pipermail/python-list/2005-February/325395.html This function is copied from matplotlib version 1.4.3, Jan 2016 """ try: if six.PY2 and sys.platform == 'win32': path = os.path.expanduser(b"~").decode(sys.getfilesystemencoding()) else: path = os.path.expanduser("~") except ImportError: # This happens on Google App Engine (pwd module is not present). pass else: if os.path.isdir(path): return path for evar in ('HOME', 'USERPROFILE', 'TMP'): path = os.environ.get(evar) if path is not None and os.path.isdir(path): return path return None
python
def _get_home(): """Find user's home directory if possible. Otherwise, returns None. :see: http://mail.python.org/pipermail/python-list/2005-February/325395.html This function is copied from matplotlib version 1.4.3, Jan 2016 """ try: if six.PY2 and sys.platform == 'win32': path = os.path.expanduser(b"~").decode(sys.getfilesystemencoding()) else: path = os.path.expanduser("~") except ImportError: # This happens on Google App Engine (pwd module is not present). pass else: if os.path.isdir(path): return path for evar in ('HOME', 'USERPROFILE', 'TMP'): path = os.environ.get(evar) if path is not None and os.path.isdir(path): return path return None
[ "def", "_get_home", "(", ")", ":", "try", ":", "if", "six", ".", "PY2", "and", "sys", ".", "platform", "==", "'win32'", ":", "path", "=", "os", ".", "path", ".", "expanduser", "(", "b\"~\"", ")", ".", "decode", "(", "sys", ".", "getfilesystemencoding...
Find user's home directory if possible. Otherwise, returns None. :see: http://mail.python.org/pipermail/python-list/2005-February/325395.html This function is copied from matplotlib version 1.4.3, Jan 2016
[ "Find", "user", "s", "home", "directory", "if", "possible", ".", "Otherwise", "returns", "None", "." ]
75a0a15a9a1dd018e79d2df270d56c4bf5f311d5
https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/config/logsetup.py#L14-L37
train
43,597
tonybaloney/requests-staticmock
requests_staticmock/adapter.py
Adapter.match_url
def match_url(self, request): """ Match the request against a file in the adapter directory :param request: The request :type request: :class:`requests.Request` :return: Path to the file :rtype: ``str`` """ parsed_url = urlparse(request.path_url) path_url = parsed_url.path query_params = parsed_url.query match = None for path in self.paths: for item in self.index: target_path = os.path.join(BASE_PATH, path, path_url[1:]) query_path = target_path.lower() + quote( '?' + query_params).lower() if target_path.lower() == item[0]: match = item[1] break elif query_path == item[0]: match = item[1] break return match
python
def match_url(self, request): """ Match the request against a file in the adapter directory :param request: The request :type request: :class:`requests.Request` :return: Path to the file :rtype: ``str`` """ parsed_url = urlparse(request.path_url) path_url = parsed_url.path query_params = parsed_url.query match = None for path in self.paths: for item in self.index: target_path = os.path.join(BASE_PATH, path, path_url[1:]) query_path = target_path.lower() + quote( '?' + query_params).lower() if target_path.lower() == item[0]: match = item[1] break elif query_path == item[0]: match = item[1] break return match
[ "def", "match_url", "(", "self", ",", "request", ")", ":", "parsed_url", "=", "urlparse", "(", "request", ".", "path_url", ")", "path_url", "=", "parsed_url", ".", "path", "query_params", "=", "parsed_url", ".", "query", "match", "=", "None", "for", "path"...
Match the request against a file in the adapter directory :param request: The request :type request: :class:`requests.Request` :return: Path to the file :rtype: ``str``
[ "Match", "the", "request", "against", "a", "file", "in", "the", "adapter", "directory" ]
431a68acc8e04eec42143bd1de43635cbc94fc3f
https://github.com/tonybaloney/requests-staticmock/blob/431a68acc8e04eec42143bd1de43635cbc94fc3f/requests_staticmock/adapter.py#L50-L77
train
43,598
tonybaloney/requests-staticmock
requests_staticmock/adapter.py
Adapter._reindex
def _reindex(self): """ Create a case-insensitive index of the paths """ self.index = [] for path in self.paths: target_path = os.path.normpath(os.path.join(BASE_PATH, path)) for root, subdirs, files in os.walk(target_path): for f in files: self.index.append( (os.path.join(root, f).lower(), os.path.join(root, f)))
python
def _reindex(self): """ Create a case-insensitive index of the paths """ self.index = [] for path in self.paths: target_path = os.path.normpath(os.path.join(BASE_PATH, path)) for root, subdirs, files in os.walk(target_path): for f in files: self.index.append( (os.path.join(root, f).lower(), os.path.join(root, f)))
[ "def", "_reindex", "(", "self", ")", ":", "self", ".", "index", "=", "[", "]", "for", "path", "in", "self", ".", "paths", ":", "target_path", "=", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "BASE_PATH", ",", "pa...
Create a case-insensitive index of the paths
[ "Create", "a", "case", "-", "insensitive", "index", "of", "the", "paths" ]
431a68acc8e04eec42143bd1de43635cbc94fc3f
https://github.com/tonybaloney/requests-staticmock/blob/431a68acc8e04eec42143bd1de43635cbc94fc3f/requests_staticmock/adapter.py#L109-L121
train
43,599