sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1 value |
|---|---|---|
def _add_scope_deco(self, start, end, parent_start, parent_end, base_color,
factor):
"""
Adds a scope decoration that enclose the current scope
:param start: Start of the current scope
:param end: End of the current scope
:param parent_start: Start of the parent scope
:param parent_end: End of the parent scope
:param base_color: base color for scope decoration
:param factor: color factor to apply on the base color (to make it
darker).
"""
color = drift_color(base_color, factor=factor)
# upper part
if start > 0:
d = TextDecoration(self.editor.document(),
start_line=parent_start, end_line=start)
d.set_full_width(True, clear=False)
d.draw_order = 2
d.set_background(color)
self.editor.decorations.append(d)
self._scope_decos.append(d)
# lower part
if end <= self.editor.document().blockCount():
d = TextDecoration(self.editor.document(),
start_line=end, end_line=parent_end + 1)
d.set_full_width(True, clear=False)
d.draw_order = 2
d.set_background(color)
self.editor.decorations.append(d)
self._scope_decos.append(d) | Adds a scope decoration that enclose the current scope
:param start: Start of the current scope
:param end: End of the current scope
:param parent_start: Start of the parent scope
:param parent_end: End of the parent scope
:param base_color: base color for scope decoration
:param factor: color factor to apply on the base color (to make it
darker). | entailment |
def _add_scope_decorations(self, block, start, end):
"""
Show a scope decoration on the editor widget
:param start: Start line
:param end: End line
"""
try:
parent = FoldScope(block).parent()
except ValueError:
parent = None
if TextBlockHelper.is_fold_trigger(block):
base_color = self._get_scope_highlight_color()
factor_step = 5
if base_color.lightness() < 128:
factor_step = 10
factor = 70
else:
factor = 100
while parent:
# highlight parent scope
parent_start, parent_end = parent.get_range()
self._add_scope_deco(
start, end + 1, parent_start, parent_end,
base_color, factor)
# next parent scope
start = parent_start
end = parent_end
parent = parent.parent()
factor += factor_step
# global scope
parent_start = 0
parent_end = self.editor.document().blockCount()
self._add_scope_deco(
start, end + 1, parent_start, parent_end, base_color,
factor + factor_step)
else:
self._clear_scope_decos() | Show a scope decoration on the editor widget
:param start: Start line
:param end: End line | entailment |
def _highlight_surrounding_scopes(self, block):
"""
Highlights the scopes surrounding the current fold scope.
:param block: Block that starts the current fold scope.
"""
scope = FoldScope(block)
if (self._current_scope is None or
self._current_scope.get_range() != scope.get_range()):
self._current_scope = scope
self._clear_scope_decos()
# highlight surrounding parent scopes with a darker color
start, end = scope.get_range()
if not TextBlockHelper.is_collapsed(block):
self._add_scope_decorations(block, start, end) | Highlights the scopes surrounding the current fold scope.
:param block: Block that starts the current fold scope. | entailment |
def leaveEvent(self, event):
"""
Removes scope decorations and background from the editor and the panel
if highlight_caret_scope, else simply update the scope decorations to
match the caret scope.
"""
super(FoldingPanel, self).leaveEvent(event)
QtWidgets.QApplication.restoreOverrideCursor()
self._highlight_runner.cancel_requests()
if not self.highlight_caret_scope:
self._clear_scope_decos()
self._mouse_over_line = None
self._current_scope = None
else:
self._block_nbr = -1
self._highlight_caret_scope()
self.editor.repaint() | Removes scope decorations and background from the editor and the panel
if highlight_caret_scope, else simply update the scope decorations to
match the caret scope. | entailment |
def _add_fold_decoration(self, block, region):
"""
Add fold decorations (boxes arround a folded block in the editor
widget).
"""
deco = TextDecoration(block)
deco.signals.clicked.connect(self._on_fold_deco_clicked)
deco.tooltip = region.text(max_lines=25)
deco.draw_order = 1
deco.block = block
deco.select_line()
deco.set_outline(drift_color(
self._get_scope_highlight_color(), 110))
deco.set_background(self._get_scope_highlight_color())
deco.set_foreground(QtGui.QColor('#808080'))
self._block_decos.append(deco)
self.editor.decorations.append(deco) | Add fold decorations (boxes arround a folded block in the editor
widget). | entailment |
def toggle_fold_trigger(self, block):
"""
Toggle a fold trigger block (expand or collapse it).
:param block: The QTextBlock to expand/collapse
"""
if not TextBlockHelper.is_fold_trigger(block):
return
region = FoldScope(block)
if region.collapsed:
region.unfold()
if self._mouse_over_line is not None:
self._add_scope_decorations(
region._trigger, *region.get_range())
else:
region.fold()
self._clear_scope_decos()
self._refresh_editor_and_scrollbars()
self.trigger_state_changed.emit(region._trigger, region.collapsed) | Toggle a fold trigger block (expand or collapse it).
:param block: The QTextBlock to expand/collapse | entailment |
def on_state_changed(self, state):
"""
On state changed we (dis)connect to the cursorPositionChanged signal
"""
if state:
self.editor.key_pressed.connect(self._on_key_pressed)
if self._highlight_caret:
self.editor.cursorPositionChanged.connect(
self._highlight_caret_scope)
self._block_nbr = -1
self.editor.new_text_set.connect(self._clear_block_deco)
else:
self.editor.key_pressed.disconnect(self._on_key_pressed)
if self._highlight_caret:
self.editor.cursorPositionChanged.disconnect(
self._highlight_caret_scope)
self._block_nbr = -1
self.editor.new_text_set.disconnect(self._clear_block_deco) | On state changed we (dis)connect to the cursorPositionChanged signal | entailment |
def _on_key_pressed(self, event):
"""
Override key press to select the current scope if the user wants
to deleted a folded scope (without selecting it).
"""
delete_request = event.key() in [QtCore.Qt.Key_Backspace,
QtCore.Qt.Key_Delete]
if event.text() or delete_request:
cursor = self.editor.textCursor()
if cursor.hasSelection():
# change selection to encompass the whole scope.
positions_to_check = cursor.selectionStart(), cursor.selectionEnd()
else:
positions_to_check = (cursor.position(), )
for pos in positions_to_check:
block = self.editor.document().findBlock(pos)
th = TextBlockHelper()
if th.is_fold_trigger(block) and th.is_collapsed(block):
self.toggle_fold_trigger(block)
if delete_request and cursor.hasSelection():
scope = FoldScope(self.find_parent_scope(block))
tc = TextHelper(self.editor).select_lines(*scope.get_range())
if tc.selectionStart() > cursor.selectionStart():
start = cursor.selectionStart()
else:
start = tc.selectionStart()
if tc.selectionEnd() < cursor.selectionEnd():
end = cursor.selectionEnd()
else:
end = tc.selectionEnd()
tc.setPosition(start)
tc.setPosition(end, tc.KeepAnchor)
self.editor.setTextCursor(tc) | Override key press to select the current scope if the user wants
to deleted a folded scope (without selecting it). | entailment |
def _on_key_pressed(self, event):
"""
Auto indent if the released key is the return key.
:param event: the key event
"""
if not event.isAccepted():
if event.key() == Qt.Key_Return or event.key() == Qt.Key_Enter:
cursor = self.editor.textCursor()
pre, post = self._get_indent(cursor)
cursor.beginEditBlock()
cursor.insertText("%s\n%s" % (pre, post))
# eats possible whitespaces
cursor.movePosition(cursor.WordRight, cursor.KeepAnchor)
txt = cursor.selectedText()
if txt.startswith(' '):
new_txt = txt.replace(" ", '')
if len(txt) > len(new_txt):
cursor.insertText(new_txt)
cursor.endEditBlock()
event.accept() | Auto indent if the released key is the return key.
:param event: the key event | entailment |
def verify_signature(self, payload, headers):
"""Verify that the payload was sent from our GitHub instance."""
github_signature = headers.get("x-hub-signature")
if not github_signature:
json_abort(401, "X-Hub-Signature header missing.")
gh_webhook_secret = current_app.config["GITHUB_WEBHOOK_SECRET"]
signature = "sha1={}".format(
hmac.new(
gh_webhook_secret.encode("utf-8"), payload, hashlib.sha1
).hexdigest()
)
if not hmac.compare_digest(signature, github_signature):
json_abort(401, "Request signature does not match calculated signature.") | Verify that the payload was sent from our GitHub instance. | entailment |
def get_options(self):
"""Get the options that have been set.
Called after the user has added all their own options
and is ready to use the variables.
"""
(options, args) = self.parser.parse_args()
# Set values from .visdkrc, but only if they haven't already been set
visdkrc_opts = self.read_visdkrc()
for opt in self.config_vars:
if not getattr(options, opt):
# Try and use value from visdkrc
if visdkrc_opts:
if opt in visdkrc_opts:
setattr(options, opt, visdkrc_opts[opt])
# Ensure all the required options are set
for opt in self.required_opts:
if opt not in dir(options) or getattr(options, opt) == None:
self.parser.error('%s must be set!' % opt)
return options | Get the options that have been set.
Called after the user has added all their own options
and is ready to use the variables. | entailment |
def parse_job_files(self):
"""Check for job definitions in known zuul files."""
repo_jobs = []
for rel_job_file_path, job_info in self.job_files.items():
LOGGER.debug("Checking for job definitions in %s", rel_job_file_path)
jobs = self.parse_job_definitions(rel_job_file_path, job_info)
LOGGER.debug("Found %d job definitions in %s", len(jobs), rel_job_file_path)
repo_jobs.extend(jobs)
if not repo_jobs:
LOGGER.info("No job definitions found in repo '%s'", self.repo)
else:
LOGGER.info(
"Found %d job definitions in repo '%s'", len(repo_jobs), self.repo
)
# LOGGER.debug(json.dumps(repo_jobs, indent=4))
return repo_jobs | Check for job definitions in known zuul files. | entailment |
def change_directory(self, directory):
"""
Changes the current directory.
Change is made by running a "cd" command followed by a "clear" command.
:param directory:
:return:
"""
self._process.write(('cd %s\n' % directory).encode())
if sys.platform == 'win32':
self._process.write((os.path.splitdrive(directory)[0] + '\r\n').encode())
self.clear()
else:
self._process.write(b'\x0C') | Changes the current directory.
Change is made by running a "cd" command followed by a "clear" command.
:param directory:
:return: | entailment |
def icon(self):
"""
Gets the icon file name. Read-only.
"""
if isinstance(self._icon, str):
if QtGui.QIcon.hasThemeIcon(self._icon):
return QtGui.QIcon.fromTheme(self._icon)
else:
return QtGui.QIcon(self._icon)
elif isinstance(self._icon, tuple):
return QtGui.QIcon.fromTheme(self._icon[0],
QtGui.QIcon(self._icon[1]))
elif isinstance(self._icon, QtGui.QIcon):
return self._icon
return QtGui.QIcon() | Gets the icon file name. Read-only. | entailment |
def add_marker(self, marker):
"""
Adds the marker to the panel.
:param marker: Marker to add
:type marker: pyqode.core.modes.Marker
"""
self._markers.append(marker)
doc = self.editor.document()
assert isinstance(doc, QtGui.QTextDocument)
block = doc.findBlockByLineNumber(marker._position)
marker.block = block
d = TextDecoration(block)
d.set_full_width()
if self._background:
d.set_background(QtGui.QBrush(self._background))
marker.decoration = d
self.editor.decorations.append(d)
self.repaint() | Adds the marker to the panel.
:param marker: Marker to add
:type marker: pyqode.core.modes.Marker | entailment |
def remove_marker(self, marker):
"""
Removes a marker from the panel
:param marker: Marker to remove
:type marker: pyqode.core.Marker
"""
self._markers.remove(marker)
self._to_remove.append(marker)
if hasattr(marker, 'decoration'):
self.editor.decorations.remove(marker.decoration)
self.repaint() | Removes a marker from the panel
:param marker: Marker to remove
:type marker: pyqode.core.Marker | entailment |
def marker_for_line(self, line):
"""
Returns the marker that is displayed at the specified line number if
any.
:param line: The marker line.
:return: Marker of None
:rtype: pyqode.core.Marker
"""
markers = []
for marker in self._markers:
if line == marker.position:
markers.append(marker)
return markers | Returns the marker that is displayed at the specified line number if
any.
:param line: The marker line.
:return: Marker of None
:rtype: pyqode.core.Marker | entailment |
def _display_tooltip(self, tooltip, top):
"""
Display tooltip at the specified top position.
"""
QtWidgets.QToolTip.showText(self.mapToGlobal(QtCore.QPoint(
self.sizeHint().width(), top)), tooltip, self) | Display tooltip at the specified top position. | entailment |
def finditer_noregex(string, sub, whole_word):
"""
Search occurrences using str.find instead of regular expressions.
:param string: string to parse
:param sub: search string
:param whole_word: True to select whole words only
"""
start = 0
while True:
start = string.find(sub, start)
if start == -1:
return
if whole_word:
if start:
pchar = string[start - 1]
else:
pchar = ' '
try:
nchar = string[start + len(sub)]
except IndexError:
nchar = ' '
if nchar in DocumentWordsProvider.separators and \
pchar in DocumentWordsProvider.separators:
yield start
start += len(sub)
else:
yield start
start += 1 | Search occurrences using str.find instead of regular expressions.
:param string: string to parse
:param sub: search string
:param whole_word: True to select whole words only | entailment |
def findalliter(string, sub, regex=False, case_sensitive=False,
whole_word=False):
"""
Generator that finds all occurrences of ``sub`` in ``string``
:param string: string to parse
:param sub: string to search
:param regex: True to search using regex
:param case_sensitive: True to match case, False to ignore case
:param whole_word: True to returns only whole words
:return:
"""
if not sub:
return
if regex:
flags = re.MULTILINE
if not case_sensitive:
flags |= re.IGNORECASE
for val in re.finditer(sub, string, flags):
yield val.span()
else:
if not case_sensitive:
string = string.lower()
sub = sub.lower()
for val in finditer_noregex(string, sub, whole_word):
yield val, val + len(sub) | Generator that finds all occurrences of ``sub`` in ``string``
:param string: string to parse
:param sub: string to search
:param regex: True to search using regex
:param case_sensitive: True to match case, False to ignore case
:param whole_word: True to returns only whole words
:return: | entailment |
def findall(data):
"""
Worker that finds all occurrences of a given string (or regex)
in a given text.
:param data: Request data dict::
{
'string': string to search in text
'sub': input text
'regex': True to consider string as a regular expression
'whole_word': True to match whole words only.
'case_sensitive': True to match case, False to ignore case
}
:return: list of occurrence positions in text
"""
return list(findalliter(
data['string'], data['sub'], regex=data['regex'],
whole_word=data['whole_word'], case_sensitive=data['case_sensitive'])) | Worker that finds all occurrences of a given string (or regex)
in a given text.
:param data: Request data dict::
{
'string': string to search in text
'sub': input text
'regex': True to consider string as a regular expression
'whole_word': True to match whole words only.
'case_sensitive': True to match case, False to ignore case
}
:return: list of occurrence positions in text | entailment |
def split(txt, seps):
"""
Splits a text in a meaningful list of words based on a list of word
separators (define in pyqode.core.settings)
:param txt: Text to split
:param seps: List of words separators
:return: A **set** of words found in the document (excluding
punctuations, numbers, ...)
"""
# replace all possible separators with a default sep
default_sep = seps[0]
for sep in seps[1:]:
if sep:
txt = txt.replace(sep, default_sep)
# now we can split using the default_sep
raw_words = txt.split(default_sep)
words = set()
for word in raw_words:
# w = w.strip()
if word.replace('_', '').isalpha():
words.add(word)
return sorted(words) | Splits a text in a meaningful list of words based on a list of word
separators (define in pyqode.core.settings)
:param txt: Text to split
:param seps: List of words separators
:return: A **set** of words found in the document (excluding
punctuations, numbers, ...) | entailment |
def complete(self, code, *args):
"""
Provides completions based on the document words.
:param code: code to complete
:param args: additional (unused) arguments.
"""
completions = []
for word in self.split(code, self.separators):
completions.append({'name': word})
return completions | Provides completions based on the document words.
:param code: code to complete
:param args: additional (unused) arguments. | entailment |
def status_to_string(cls, status):
"""
Converts a message status to a string.
:param status: Status to convert (p yqode.core.modes.CheckerMessages)
:return: The status string.
:rtype: str
"""
strings = {CheckerMessages.INFO: "Info",
CheckerMessages.WARNING: "Warning",
CheckerMessages.ERROR: "Error"}
return strings[status] | Converts a message status to a string.
:param status: Status to convert (p yqode.core.modes.CheckerMessages)
:return: The status string.
:rtype: str | entailment |
def add_messages(self, messages):
"""
Adds a message or a list of message.
:param messages: A list of messages or a single message
"""
# remove old messages
if len(messages) > self.limit:
messages = messages[:self.limit]
_logger(self.__class__).log(5, 'adding %s messages' % len(messages))
self._finished = False
self._new_messages = messages
self._to_check = list(self._messages)
self._pending_msg = messages
# start removing messages, new message won't be added until we
# checked all message that need to be removed
QtCore.QTimer.singleShot(1, self._remove_batch) | Adds a message or a list of message.
:param messages: A list of messages or a single message | entailment |
def remove_message(self, message):
"""
Removes a message.
:param message: Message to remove
"""
import time
_logger(self.__class__).log(5, 'removing message %s' % message)
t = time.time()
usd = message.block.userData()
if usd:
try:
usd.messages.remove(message)
except (AttributeError, ValueError):
pass
if message.decoration:
self.editor.decorations.remove(message.decoration)
self._messages.remove(message) | Removes a message.
:param message: Message to remove | entailment |
def clear_messages(self):
"""
Clears all messages.
"""
while len(self._messages):
msg = self._messages.pop(0)
usd = msg.block.userData()
if usd and hasattr(usd, 'messages'):
usd.messages[:] = []
if msg.decoration:
self.editor.decorations.remove(msg.decoration) | Clears all messages. | entailment |
def _on_work_finished(self, results):
"""
Display results.
:param status: Response status
:param results: Response data, messages.
"""
messages = []
for msg in results:
msg = CheckerMessage(*msg)
if msg.line >= self.editor.blockCount():
msg.line = self.editor.blockCount() - 1
block = self.editor.document().findBlockByNumber(msg.line)
msg.block = block
messages.append(msg)
self.add_messages(messages) | Display results.
:param status: Response status
:param results: Response data, messages. | entailment |
def request_analysis(self):
"""
Requests an analysis.
"""
if self._finished:
_logger(self.__class__).log(5, 'running analysis')
self._job_runner.request_job(self._request)
elif self.editor:
# retry later
_logger(self.__class__).log(
5, 'delaying analysis (previous analysis not finished)')
QtCore.QTimer.singleShot(500, self.request_analysis) | Requests an analysis. | entailment |
def _request(self):
""" Requests a checking of the editor content. """
try:
self.editor.toPlainText()
except (TypeError, RuntimeError):
return
try:
max_line_length = self.editor.modes.get(
'RightMarginMode').position
except KeyError:
max_line_length = 79
request_data = {
'code': self.editor.toPlainText(),
'path': self.editor.file.path,
'encoding': self.editor.file.encoding,
'ignore_rules': self.ignore_rules,
'max_line_length': max_line_length,
}
try:
self.editor.backend.send_request(
self._worker, request_data, on_receive=self._on_work_finished)
self._finished = False
except NotRunning:
# retry later
QtCore.QTimer.singleShot(100, self._request) | Requests a checking of the editor content. | entailment |
def openpty():
"""openpty() -> (master_fd, slave_fd)
Open a pty master/slave pair, using os.openpty() if possible."""
try:
return os.openpty()
except (AttributeError, OSError):
pass
master_fd, slave_name = _open_terminal()
slave_fd = slave_open(slave_name)
return master_fd, slave_fd | openpty() -> (master_fd, slave_fd)
Open a pty master/slave pair, using os.openpty() if possible. | entailment |
def master_open():
"""master_open() -> (master_fd, slave_name)
Open a pty master and return the fd, and the filename of the slave end.
Deprecated, use openpty() instead."""
try:
master_fd, slave_fd = os.openpty()
except (AttributeError, OSError):
pass
else:
slave_name = os.ttyname(slave_fd)
os.close(slave_fd)
return master_fd, slave_name
return _open_terminal() | master_open() -> (master_fd, slave_name)
Open a pty master and return the fd, and the filename of the slave end.
Deprecated, use openpty() instead. | entailment |
def _open_terminal():
"""Open pty master and return (master_fd, tty_name)."""
for x in 'pqrstuvwxyzPQRST':
for y in '0123456789abcdef':
pty_name = '/dev/pty' + x + y
try:
fd = os.open(pty_name, os.O_RDWR)
except OSError:
continue
return (fd, '/dev/tty' + x + y)
raise OSError('out of pty devices') | Open pty master and return (master_fd, tty_name). | entailment |
def slave_open(tty_name):
"""slave_open(tty_name) -> slave_fd
Open the pty slave and acquire the controlling terminal, returning
opened filedescriptor.
Deprecated, use openpty() instead."""
result = os.open(tty_name, os.O_RDWR)
try:
from fcntl import ioctl, I_PUSH
except ImportError:
return result
try:
ioctl(result, I_PUSH, "ptem")
ioctl(result, I_PUSH, "ldterm")
except OSError:
pass
return result | slave_open(tty_name) -> slave_fd
Open the pty slave and acquire the controlling terminal, returning
opened filedescriptor.
Deprecated, use openpty() instead. | entailment |
def fork():
"""fork() -> (pid, master_fd)
Fork and make the child a session leader with a controlling terminal."""
try:
pid, fd = os.forkpty()
except (AttributeError, OSError):
pass
else:
if pid == CHILD:
try:
os.setsid()
except OSError:
# os.forkpty() already set us session leader
pass
return pid, fd
master_fd, slave_fd = openpty()
pid = os.fork()
if pid == CHILD:
# Establish a new session.
os.setsid()
os.close(master_fd)
# Slave becomes stdin/stdout/stderr of child.
os.dup2(slave_fd, STDIN_FILENO)
os.dup2(slave_fd, STDOUT_FILENO)
os.dup2(slave_fd, STDERR_FILENO)
if (slave_fd > STDERR_FILENO):
os.close (slave_fd)
# Explicitly open the tty to make it become a controlling tty.
tmp_fd = os.open(os.ttyname(STDOUT_FILENO), os.O_RDWR)
os.close(tmp_fd)
else:
os.close(slave_fd)
# Parent and child process.
return pid, master_fd | fork() -> (pid, master_fd)
Fork and make the child a session leader with a controlling terminal. | entailment |
def _writen(fd, data):
"""Write all the data to a descriptor."""
while data:
n = os.write(fd, data)
data = data[n:] | Write all the data to a descriptor. | entailment |
def _copy(master_fd, master_read=_read, stdin_read=_read):
"""Parent copy loop.
Copies
pty master -> standard output (master_read)
standard input -> pty master (stdin_read)"""
fds = [master_fd, STDIN_FILENO]
while True:
rfds, wfds, xfds = select(fds, [], [])
if master_fd in rfds:
data = master_read(master_fd)
if not data: # Reached EOF.
return
else:
os.write(STDOUT_FILENO, data)
if STDIN_FILENO in rfds:
data = stdin_read(STDIN_FILENO)
if not data:
fds.remove(STDIN_FILENO)
else:
_writen(master_fd, data) | Parent copy loop.
Copies
pty master -> standard output (master_read)
standard input -> pty master (stdin_read) | entailment |
def spawn(argv, master_read=_read, stdin_read=_read):
"""Create a spawned process."""
if type(argv) == type(''):
argv = (argv,)
pid, master_fd = fork()
if pid == CHILD:
try:
os.execlp(argv[0], *argv)
except:
# If we wanted to be really clever, we would use
# the same method as subprocess() to pass the error
# back to the parent. For now just dump stack trace.
traceback.print_exc()
finally:
os._exit(1)
try:
mode = tty.tcgetattr(STDIN_FILENO)
tty.setraw(STDIN_FILENO)
restore = 1
except tty.error: # This is the same as termios.error
restore = 0
try:
_copy(master_fd, master_read, stdin_read)
except OSError:
# Some OSes never return an EOF on pty, just raise
# an error instead.
pass
finally:
if restore:
tty.tcsetattr(STDIN_FILENO, tty.TCSAFLUSH, mode)
os.close(master_fd)
return os.waitpid(pid, 0)[1] | Create a spawned process. | entailment |
def _get_dataobject(self, name, multivalued):
"""This function only gets called if the decorated property
doesn't have a value in the cache."""
logger.debug("Querying server for uncached data object %s", name)
# This will retrieve the value and inject it into the cache
self.update_view_data(properties=[name])
return self._cache[name][0] | This function only gets called if the decorated property
doesn't have a value in the cache. | entailment |
def _get_mor(self, name, multivalued):
"""This function only gets called if the decorated property
doesn't have a value in the cache."""
logger.debug("Querying server for uncached MOR %s", name)
# This will retrieve the value and inject it into the cache
logger.debug("Getting view for MOR")
self.update(properties=[name])
return self._cache[name][0] | This function only gets called if the decorated property
doesn't have a value in the cache. | entailment |
def flush_cache(self, properties=None):
"""Flushes the cache being held for this instance.
:param properties: The list of properties to flush from the cache.
:type properties: list or None (default). If None, flush entire cache.
"""
if hasattr(self, '_cache'):
if properties is None:
del(self._cache)
else:
for prop in properties:
if prop in self._cache:
del(self._cache[prop]) | Flushes the cache being held for this instance.
:param properties: The list of properties to flush from the cache.
:type properties: list or None (default). If None, flush entire cache. | entailment |
def update(self, properties=None):
"""Updates the properties being held for this instance.
:param properties: The list of properties to update.
:type properties: list or None (default). If None, update all
currently cached properties.
"""
if properties is None:
try:
self.update_view_data(properties=list(self._cache.keys()))
except AttributeError:
# We end up here and ignore it self._cache doesn't exist
pass
else:
self.update_view_data(properties=properties) | Updates the properties being held for this instance.
:param properties: The list of properties to update.
:type properties: list or None (default). If None, update all
currently cached properties. | entailment |
def update_view_data(self, properties=None):
"""Update the local object from the server-side object.
>>> vm = VirtualMachine.find_one(client, filter={"name": "genesis"})
>>> # Update all properties
>>> vm.update_view_data()
>>> # Update the config and summary properties
>>> vm.update_view_data(properties=["config", "summary"]
:param properties: A list of properties to update.
:type properties: list
"""
if properties is None:
properties = []
logger.info("Updating view data for object of type %s",
self._mo_ref._type)
property_spec = self._client.create('PropertySpec')
property_spec.type = str(self._mo_ref._type)
# Determine which properties to retrieve from the server
if properties is None:
properties = []
else:
if properties == "all":
logger.debug("Retrieving all properties")
property_spec.all = True
else:
logger.debug("Retrieving %s properties", len(properties))
property_spec.all = False
property_spec.pathSet = properties
object_spec = self._client.create('ObjectSpec')
object_spec.obj = self._mo_ref
pfs = self._client.create('PropertyFilterSpec')
pfs.propSet = [property_spec]
pfs.objectSet = [object_spec]
# Create a copy of the property collector and call the method
pc = self._client.sc.propertyCollector
object_content = pc.RetrieveProperties(specSet=pfs)[0]
if not object_content:
# TODO: Improve error checking and reporting
logger.error("Nothing returned from RetrieveProperties!")
self._set_view_data(object_content) | Update the local object from the server-side object.
>>> vm = VirtualMachine.find_one(client, filter={"name": "genesis"})
>>> # Update all properties
>>> vm.update_view_data()
>>> # Update the config and summary properties
>>> vm.update_view_data(properties=["config", "summary"]
:param properties: A list of properties to update.
:type properties: list | entailment |
def preload(self, name, properties=None):
"""Pre-loads the requested properties for each object in the "name"
attribute.
:param name: The name of the attribute containing the list to
preload.
:type name: str
:param properties: The properties to preload on the objects or the
string all to preload all properties.
:type properties: list or the string "all"
"""
if properties is None:
raise ValueError("You must specify some properties to preload. To"
" preload all properties use the string \"all\".")
# Don't do anything if the attribute contains an empty list
if not getattr(self, name):
return
mo_refs = []
# Iterate over each item and collect the mo_ref
for item in getattr(self, name):
# Make sure the items are ManagedObjectReference's
if isinstance(item, ManagedObject) is False:
raise ValueError("Only ManagedObject's can be pre-loaded.")
mo_refs.append(item._mo_ref)
# Send a single query to the server which gets views
views = self._client.get_views(mo_refs, properties)
# Populate the inst.attr item with the retrieved object/properties
self._cache[name] = (views, time.time()) | Pre-loads the requested properties for each object in the "name"
attribute.
:param name: The name of the attribute containing the list to
preload.
:type name: str
:param properties: The properties to preload on the objects or the
string all to preload all properties.
:type properties: list or the string "all" | entailment |
def _set_view_data(self, object_content):
"""Update the local object from the passed in object_content."""
# A debugging convenience, allows inspection of the object_content
# that was used to create the object
logger.info("Setting view data for a %s", self.__class__)
self._object_content = object_content
for dynprop in object_content.propSet:
# If the class hasn't defined the property, don't use it
if dynprop.name not in self._valid_attrs:
logger.error("Server returned a property '%s' but the object"
" hasn't defined it so it is being ignored." %
dynprop.name)
continue
try:
if not len(dynprop.val):
logger.info("Server returned empty value for %s",
dynprop.name)
except TypeError:
# This except allows us to pass over:
# TypeError: object of type 'datetime.datetime' has no len()
# It will be processed in the next code block
logger.info("%s of type %s has no len!",
dynprop.name, type(dynprop.val))
pass
try:
# See if we have a cache attribute
cache = self._cache
except AttributeError:
# If we don't create one and use it
cache = self._cache = {}
# Values which contain classes starting with Array need
# to be converted into a nicer Python list
if dynprop.val.__class__.__name__.startswith('Array'):
# suds returns a list containing a single item, which
# is another list. Use the first item which is the real list
logger.info("Setting value of an Array* property")
logger.debug("%s being set to %s",
dynprop.name, dynprop.val[0])
now = time.time()
cache[dynprop.name] = (dynprop.val[0], now)
else:
logger.info("Setting value of a single-valued property")
logger.debug("DynamicProperty value is a %s: ",
dynprop.val.__class__.__name__)
logger.debug("%s being set to %s", dynprop.name, dynprop.val)
now = time.time()
cache[dynprop.name] = (dynprop.val, now) | Update the local object from the passed in object_content. | entailment |
def _initialize_repo_cache():
"""Initialize the repository cache used for scraping.
Retrieves a list of repositories with their provider and last scraping time
from Elasticsearch.
This list can be used to check which repos need to be scraped (e.g. after
a specific amount of time).
"""
LOGGER.info("Initializing repository cache")
# Initialize Repo Cache
repo_cache = {}
# Get all repos from Elasticsearch
for hit in GitRepo.search().query("match_all").scan():
# TODO (fschmidt): Maybe we can use this list as cache for the whole
# scraper-webhook part.
# This way, we could reduce the amount of operations needed for GitHub
# and ElasticSearch
repo_cache[hit.repo_name] = hit.to_dict(skip_empty=False)
return repo_cache | Initialize the repository cache used for scraping.
Retrieves a list of repositories with their provider and last scraping time
from Elasticsearch.
This list can be used to check which repos need to be scraped (e.g. after
a specific amount of time). | entailment |
def main(options):
"""Obtains supported features from the license manager"""
client = Client(server=options.server, username=options.username,
password=options.password)
print('Successfully connected to %s' % client.server)
lm_info = client.sc.licenseManager.QuerySupportedFeatures()
for feature in lm_info:
print('%s: %s' % (feature.featureName, feature.state))
client.logout() | Obtains supported features from the license manager | entailment |
def append(self, mode):
"""
Adds a mode to the editor.
:param mode: The mode instance to append.
"""
_logger().log(5, 'adding mode %r', mode.name)
self._modes[mode.name] = mode
mode.on_install(self.editor)
return mode | Adds a mode to the editor.
:param mode: The mode instance to append. | entailment |
def remove(self, name_or_klass):
"""
Removes a mode from the editor.
:param name_or_klass: The name (or class) of the mode to remove.
:returns: The removed mode.
"""
_logger().log(5, 'removing mode %r', name_or_klass)
mode = self.get(name_or_klass)
mode.on_uninstall()
self._modes.pop(mode.name)
return mode | Removes a mode from the editor.
:param name_or_klass: The name (or class) of the mode to remove.
:returns: The removed mode. | entailment |
def get(self, name_or_klass):
"""
Gets a mode by name (or class)
:param name_or_klass: The name or the class of the mode to get
:type name_or_klass: str or type
:rtype: pyqode.core.api.Mode
"""
if not isinstance(name_or_klass, str):
name_or_klass = name_or_klass.__name__
return self._modes[name_or_klass] | Gets a mode by name (or class)
:param name_or_klass: The name or the class of the mode to get
:type name_or_klass: str or type
:rtype: pyqode.core.api.Mode | entailment |
def on_install(self, editor):
"""
Extends :meth:`pyqode.core.api.Mode.on_install` method to set the
editor instance as the parent widget.
.. warning:: Don't forget to call **super** if you override this
method!
:param editor: editor instance
:type editor: pyqode.core.api.CodeEdit
"""
Mode.on_install(self, editor)
self.setParent(editor)
self.setPalette(QtWidgets.QApplication.instance().palette())
self.setFont(QtWidgets.QApplication.instance().font())
self.editor.panels.refresh()
self._background_brush = QtGui.QBrush(QtGui.QColor(
self.palette().window().color()))
self._foreground_pen = QtGui.QPen(QtGui.QColor(
self.palette().windowText().color())) | Extends :meth:`pyqode.core.api.Mode.on_install` method to set the
editor instance as the parent widget.
.. warning:: Don't forget to call **super** if you override this
method!
:param editor: editor instance
:type editor: pyqode.core.api.CodeEdit | entailment |
def setVisible(self, visible):
"""
Shows/Hides the panel
Automatically call CodeEdit.refresh_panels.
:param visible: Visible state
"""
_logger().log(5, '%s visibility changed', self.name)
super(Panel, self).setVisible(visible)
if self.editor:
self.editor.panels.refresh() | Shows/Hides the panel
Automatically call CodeEdit.refresh_panels.
:param visible: Visible state | entailment |
def append(self, decoration):
"""
Adds a text decoration on a CodeEdit instance
:param decoration: Text decoration to add
:type decoration: pyqode.core.api.TextDecoration
"""
if decoration not in self._decorations:
self._decorations.append(decoration)
self._decorations = sorted(
self._decorations, key=lambda sel: sel.draw_order)
self.editor.setExtraSelections(self._decorations)
return True
return False | Adds a text decoration on a CodeEdit instance
:param decoration: Text decoration to add
:type decoration: pyqode.core.api.TextDecoration | entailment |
def remove(self, decoration):
"""
Removes a text decoration from the editor.
:param decoration: Text decoration to remove
:type decoration: pyqode.core.api.TextDecoration
"""
try:
self._decorations.remove(decoration)
self.editor.setExtraSelections(self._decorations)
return True
except ValueError:
return False | Removes a text decoration from the editor.
:param decoration: Text decoration to remove
:type decoration: pyqode.core.api.TextDecoration | entailment |
def clear(self):
"""
Removes all text decoration from the editor.
"""
self._decorations[:] = []
try:
self.editor.setExtraSelections(self._decorations)
except RuntimeError:
pass | Removes all text decoration from the editor. | entailment |
def _on_key_pressed(self, event):
"""
Resets editor font size to the default font size
:param event: wheelEvent
:type event: QKeyEvent
"""
if (int(event.modifiers()) & QtCore.Qt.ControlModifier > 0 and
not int(event.modifiers()) & QtCore.Qt.ShiftModifier):
if event.key() == QtCore.Qt.Key_0:
self.editor.reset_zoom()
event.accept()
if event.key() == QtCore.Qt.Key_Plus:
self.editor.zoom_in()
event.accept()
if event.key() == QtCore.Qt.Key_Minus:
self.editor.zoom_out()
event.accept() | Resets editor font size to the default font size
:param event: wheelEvent
:type event: QKeyEvent | entailment |
def _on_wheel_event(self, event):
"""
Increments or decrements editor fonts settings on mouse wheel event
if ctrl modifier is on.
:param event: wheel event
:type event: QWheelEvent
"""
try:
delta = event.angleDelta().y()
except AttributeError:
# PyQt4/PySide
delta = event.delta()
if int(event.modifiers()) & QtCore.Qt.ControlModifier > 0:
if delta < self.prev_delta:
self.editor.zoom_out()
event.accept()
else:
self.editor.zoom_in()
event.accept() | Increments or decrements editor fonts settings on mouse wheel event
if ctrl modifier is on.
:param event: wheel event
:type event: QWheelEvent | entailment |
def set_writer(self, writer):
"""
Changes the writer function to handle writing to the text edit.
A writer function must have the following prototype:
.. code-block:: python
def write(text_edit, text, color)
:param writer: write function as described above.
"""
if self._writer != writer and self._writer:
self._writer = None
if writer:
self._writer = writer | Changes the writer function to handle writing to the text edit.
A writer function must have the following prototype:
.. code-block:: python
def write(text_edit, text, color)
:param writer: write function as described above. | entailment |
def start_process(self, process, args=None, cwd=None, env=None):
"""
Starts a process interactively.
:param process: Process to run
:type process: str
:param args: List of arguments (list of str)
:type args: list
:param cwd: Working directory
:type cwd: str
:param env: environment variables (dict).
"""
self.setReadOnly(False)
if env is None:
env = {}
if args is None:
args = []
if not self._running:
self.process = QProcess()
self.process.finished.connect(self._on_process_finished)
self.process.started.connect(self.process_started.emit)
self.process.error.connect(self._write_error)
self.process.readyReadStandardError.connect(self._on_stderr)
self.process.readyReadStandardOutput.connect(self._on_stdout)
if cwd:
self.process.setWorkingDirectory(cwd)
e = self.process.systemEnvironment()
ev = QProcessEnvironment()
for v in e:
values = v.split('=')
ev.insert(values[0], '='.join(values[1:]))
for k, v in env.items():
ev.insert(k, v)
self.process.setProcessEnvironment(ev)
self._running = True
self._process_name = process
self._args = args
if self._clear_on_start:
self.clear()
self._user_stop = False
self._write_started()
self.process.start(process, args)
self.process.waitForStarted()
else:
_logger().warning('a process is already running') | Starts a process interactively.
:param process: Process to run
:type process: str
:param args: List of arguments (list of str)
:type args: list
:param cwd: Working directory
:type cwd: str
:param env: environment variables (dict). | entailment |
def stop_process(self):
"""
Stop the process (by killing it).
"""
if self.process is not None:
self._user_stop = True
self.process.kill()
self.setReadOnly(True)
self._running = False | Stop the process (by killing it). | entailment |
def write(text_edit, text, color):
"""
Default write function. Move the cursor to the end and insert text with
the specified color.
:param text_edit: QInteractiveConsole instance
:type text_edit: pyqode.widgets.QInteractiveConsole
:param text: Text to write
:type text: str
:param color: Desired text color
:type color: QColor
"""
try:
text_edit.moveCursor(QTextCursor.End)
text_edit.setTextColor(color)
text_edit.insertPlainText(text)
text_edit.moveCursor(QTextCursor.End)
except RuntimeError:
pass | Default write function. Move the cursor to the end and insert text with
the specified color.
:param text_edit: QInteractiveConsole instance
:type text_edit: pyqode.widgets.QInteractiveConsole
:param text: Text to write
:type text: str
:param color: Desired text color
:type color: QColor | entailment |
def apply_color_scheme(self, color_scheme):
"""
Apply a pygments color scheme to the console.
As there is not a 1 to 1 mapping between color scheme formats and
console formats, we decided to make the following mapping (it usually
looks good for most of the available pygments styles):
- stdout_color = normal color
- stderr_color = red (lighter if background is dark)
- stdin_color = numbers color
- app_msg_color = string color
- bacgorund_color = background
:param color_scheme: pyqode.core.api.ColorScheme to apply
"""
self.stdout_color = color_scheme.formats['normal'].foreground().color()
self.stdin_color = color_scheme.formats['number'].foreground().color()
self.app_msg_color = color_scheme.formats[
'string'].foreground().color()
self.background_color = color_scheme.background
if self.background_color.lightness() < 128:
self.stderr_color = QColor('#FF8080')
else:
self.stderr_color = QColor('red') | Apply a pygments color scheme to the console.
As there is not a 1 to 1 mapping between color scheme formats and
console formats, we decided to make the following mapping (it usually
looks good for most of the available pygments styles):
- stdout_color = normal color
- stderr_color = red (lighter if background is dark)
- stdin_color = numbers color
- app_msg_color = string color
- bacgorund_color = background
:param color_scheme: pyqode.core.api.ColorScheme to apply | entailment |
def convert_to_codec_key(value):
"""
Normalize code key value (encoding codecs must be lower case and must
not contain any dashes).
:param value: value to convert.
"""
if not value:
# fallback to utf-8
value = 'UTF-8'
# UTF-8 -> utf_8
converted = value.replace('-', '_').lower()
# fix some corner cases, see https://github.com/pyQode/pyQode/issues/11
all_aliases = {
'ascii': [
'us_ascii',
'us',
'ansi_x3.4_1968',
'cp367',
'csascii',
'ibm367',
'iso_ir_6',
'iso646_us',
'iso_646.irv:1991'
],
'utf-7': [
'csunicode11utf7',
'unicode_1_1_utf_7',
'unicode_2_0_utf_7',
'x_unicode_1_1_utf_7',
'x_unicode_2_0_utf_7',
],
'utf_8': [
'unicode_1_1_utf_8',
'unicode_2_0_utf_8',
'x_unicode_1_1_utf_8',
'x_unicode_2_0_utf_8',
],
'utf_16': [
'utf_16le',
'ucs_2',
'unicode',
'iso_10646_ucs2'
],
'latin_1': ['iso_8859_1']
}
for key, aliases in all_aliases.items():
if converted in aliases:
return key
return converted | Normalize code key value (encoding codecs must be lower case and must
not contain any dashes).
:param value: value to convert. | entailment |
def process_block(self, current_block, previous_block, text):
"""
Processes a block and setup its folding info.
This method call ``detect_fold_level`` and handles most of the tricky
corner cases so that all you have to do is focus on getting the proper
fold level foreach meaningful block, skipping the blank ones.
:param current_block: current block to process
:param previous_block: previous block
:param text: current block text
"""
prev_fold_level = TextBlockHelper.get_fold_lvl(previous_block)
if text.strip() == '':
# blank line always have the same level as the previous line
fold_level = prev_fold_level
else:
fold_level = self.detect_fold_level(
previous_block, current_block)
if fold_level > self.limit:
fold_level = self.limit
prev_fold_level = TextBlockHelper.get_fold_lvl(previous_block)
if fold_level > prev_fold_level:
# apply on previous blank lines
block = current_block.previous()
while block.isValid() and block.text().strip() == '':
TextBlockHelper.set_fold_lvl(block, fold_level)
block = block.previous()
TextBlockHelper.set_fold_trigger(
block, True)
# update block fold level
if text.strip():
TextBlockHelper.set_fold_trigger(
previous_block, fold_level > prev_fold_level)
TextBlockHelper.set_fold_lvl(current_block, fold_level)
# user pressed enter at the beginning of a fold trigger line
# the previous blank line will keep the trigger state and the new line
# (which actually contains the trigger) must use the prev state (
# and prev state must then be reset).
prev = current_block.previous() # real prev block (may be blank)
if (prev and prev.isValid() and prev.text().strip() == '' and
TextBlockHelper.is_fold_trigger(prev)):
# prev line has the correct trigger fold state
TextBlockHelper.set_collapsed(
current_block, TextBlockHelper.is_collapsed(
prev))
# make empty line not a trigger
TextBlockHelper.set_fold_trigger(prev, False)
TextBlockHelper.set_collapsed(prev, False) | Processes a block and setup its folding info.
This method call ``detect_fold_level`` and handles most of the tricky
corner cases so that all you have to do is focus on getting the proper
fold level foreach meaningful block, skipping the blank ones.
:param current_block: current block to process
:param previous_block: previous block
:param text: current block text | entailment |
def detect_fold_level(self, prev_block, block):
"""
Detects fold level by looking at the block indentation.
:param prev_block: previous text block
:param block: current block to highlight
"""
text = block.text()
# round down to previous indentation guide to ensure contiguous block
# fold level evolution.
return (len(text) - len(text.lstrip())) // self.editor.tab_length | Detects fold level by looking at the block indentation.
:param prev_block: previous text block
:param block: current block to highlight | entailment |
def read_config(contents):
"""Reads pylintrc config into native ConfigParser object.
Args:
contents (str): The contents of the file containing the INI config.
Returns:
ConfigParser.ConfigParser: The parsed configuration.
"""
file_obj = io.StringIO(contents)
config = six.moves.configparser.ConfigParser()
config.readfp(file_obj)
return config | Reads pylintrc config into native ConfigParser object.
Args:
contents (str): The contents of the file containing the INI config.
Returns:
ConfigParser.ConfigParser: The parsed configuration. | entailment |
def load_local_config(filename):
"""Loads the pylint.config.py file.
Args:
filename (str): The python file containing the local configuration.
Returns:
module: The loaded Python module.
"""
if not filename:
return imp.new_module('local_pylint_config')
module = imp.load_source('local_pylint_config', filename)
return module | Loads the pylint.config.py file.
Args:
filename (str): The python file containing the local configuration.
Returns:
module: The loaded Python module. | entailment |
def determine_final_config(config_module):
"""Determines the final additions and replacements.
Combines the config module with the defaults.
Args:
config_module: The loaded local configuration module.
Returns:
Config: the final configuration.
"""
config = Config(
DEFAULT_LIBRARY_RC_ADDITIONS, DEFAULT_LIBRARY_RC_REPLACEMENTS,
DEFAULT_TEST_RC_ADDITIONS, DEFAULT_TEST_RC_REPLACEMENTS)
for field in config._fields:
if hasattr(config_module, field):
config = config._replace(**{field: getattr(config_module, field)})
return config | Determines the final additions and replacements.
Combines the config module with the defaults.
Args:
config_module: The loaded local configuration module.
Returns:
Config: the final configuration. | entailment |
def lint_fileset(*dirnames, **kwargs):
"""Lints a group of files using a given rcfile.
Keyword arguments are
* ``rc_filename`` (``str``): The name of the Pylint config RC file.
* ``description`` (``str``): A description of the files and configuration
currently being run.
Args:
dirnames (tuple): Directories to run Pylint in.
kwargs: The keyword arguments. The only keyword arguments
are ``rc_filename`` and ``description`` and both
are required.
Raises:
KeyError: If the wrong keyword arguments are used.
"""
try:
rc_filename = kwargs['rc_filename']
description = kwargs['description']
if len(kwargs) != 2:
raise KeyError
except KeyError:
raise KeyError(_LINT_FILESET_MSG)
pylint_shell_command = ['pylint', '--rcfile', rc_filename]
pylint_shell_command.extend(dirnames)
status_code = subprocess.call(pylint_shell_command)
if status_code != 0:
error_message = _ERROR_TEMPLATE.format(description, status_code)
print(error_message, file=sys.stderr)
sys.exit(status_code) | Lints a group of files using a given rcfile.
Keyword arguments are
* ``rc_filename`` (``str``): The name of the Pylint config RC file.
* ``description`` (``str``): A description of the files and configuration
currently being run.
Args:
dirnames (tuple): Directories to run Pylint in.
kwargs: The keyword arguments. The only keyword arguments
are ``rc_filename`` and ``description`` and both
are required.
Raises:
KeyError: If the wrong keyword arguments are used. | entailment |
def make_rc(base_cfg, target_filename,
additions=None, replacements=None):
"""Combines a base rc and additions into single file.
Args:
base_cfg (ConfigParser.ConfigParser): The configuration we are
merging into.
target_filename (str): The filename where the new configuration
will be saved.
additions (dict): (Optional) The values added to the configuration.
replacements (dict): (Optional) The wholesale replacements for
the new configuration.
Raises:
KeyError: if one of the additions or replacements does not
already exist in the current config.
"""
# Set-up the mutable default values.
if additions is None:
additions = {}
if replacements is None:
replacements = {}
# Create fresh config, which must extend the base one.
new_cfg = six.moves.configparser.ConfigParser()
# pylint: disable=protected-access
new_cfg._sections = copy.deepcopy(base_cfg._sections)
new_sections = new_cfg._sections
# pylint: enable=protected-access
for section, opts in additions.items():
curr_section = new_sections.setdefault(
section, collections.OrderedDict())
for opt, opt_val in opts.items():
curr_val = curr_section.get(opt)
if curr_val is None:
msg = _MISSING_OPTION_ADDITION.format(opt)
raise KeyError(msg)
curr_val = curr_val.rstrip(',')
opt_val = _transform_opt(opt_val)
curr_section[opt] = '%s, %s' % (curr_val, opt_val)
for section, opts in replacements.items():
curr_section = new_sections.setdefault(
section, collections.OrderedDict())
for opt, opt_val in opts.items():
curr_val = curr_section.get(opt)
if curr_val is None:
# NOTE: This doesn't need to fail, because some options
# are present in one version of pylint and not present
# in another. For example ``[BASIC].method-rgx`` is
# ``(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$`` in
# ``1.7.5`` but in ``1.8.0`` the default config has
# ``#method-rgx=`` (i.e. it is commented out in the
# ``[BASIC]`` section).
msg = _MISSING_OPTION_REPLACE.format(opt)
print(msg, file=sys.stderr)
opt_val = _transform_opt(opt_val)
curr_section[opt] = '%s' % (opt_val,)
with open(target_filename, 'w') as file_obj:
new_cfg.write(file_obj) | Combines a base rc and additions into single file.
Args:
base_cfg (ConfigParser.ConfigParser): The configuration we are
merging into.
target_filename (str): The filename where the new configuration
will be saved.
additions (dict): (Optional) The values added to the configuration.
replacements (dict): (Optional) The wholesale replacements for
the new configuration.
Raises:
KeyError: if one of the additions or replacements does not
already exist in the current config. | entailment |
def run_command(args):
"""Script entry point. Lints both sets of files."""
library_rc = 'pylintrc'
test_rc = 'pylintrc.test'
if os.path.exists(library_rc):
os.remove(library_rc)
if os.path.exists(test_rc):
os.remove(test_rc)
default_config = read_config(get_default_config())
user_config = load_local_config(args.config)
configuration = determine_final_config(user_config)
make_rc(default_config, library_rc,
additions=configuration.library_additions,
replacements=configuration.library_replacements)
make_rc(default_config, test_rc,
additions=configuration.test_additions,
replacements=configuration.test_replacements)
lint_fileset(*args.library_filesets, rc_filename=library_rc,
description='Library')
lint_fileset(*args.test_filesets, rc_filename=test_rc,
description='Test') | Script entry point. Lints both sets of files. | entailment |
def u2open(self, u2request):
"""
Open a connection.
@param u2request: A urllib2 request.
@type u2request: urllib2.Requet.
@return: The opened file-like urllib2 object.
@rtype: fp
"""
tm = self.options.timeout
url = build_opener(HTTPSClientAuthHandler(self.context))
if self.u2ver() < 2.6:
socket.setdefaulttimeout(tm)
return url.open(u2request)
else:
return url.open(u2request, timeout=tm) | Open a connection.
@param u2request: A urllib2 request.
@type u2request: urllib2.Requet.
@return: The opened file-like urllib2 object.
@rtype: fp | entailment |
def login(self, username=None, password=None):
"""Login to a vSphere server.
>>> client.login(username='Administrator', password='strongpass')
:param username: The username to authenticate as.
:type username: str
:param password: The password to authenticate with.
:type password: str
"""
if username is None:
username = self.username
if password is None:
password = self.password
logger.debug("Logging into server")
self.sc.sessionManager.Login(userName=username, password=password)
self._logged_in = True | Login to a vSphere server.
>>> client.login(username='Administrator', password='strongpass')
:param username: The username to authenticate as.
:type username: str
:param password: The password to authenticate with.
:type password: str | entailment |
def logout(self):
"""Logout of a vSphere server."""
if self._logged_in is True:
self.si.flush_cache()
self.sc.sessionManager.Logout()
self._logged_in = False | Logout of a vSphere server. | entailment |
def invoke(self, method, _this, **kwargs):
"""Invoke a method on the server.
>>> client.invoke('CurrentTime', client.si)
:param method: The method to invoke, as found in the SDK.
:type method: str
:param _this: The managed object reference against which to invoke \
the method.
:type _this: ManagedObject
:param kwargs: The arguments to pass to the method, as \
found in the SDK.
:type kwargs: TODO
"""
if (self._logged_in is False and
method not in ["Login", "RetrieveServiceContent"]):
logger.critical("Cannot exec %s unless logged in", method)
raise NotLoggedInError("Cannot exec %s unless logged in" % method)
for kwarg in kwargs:
kwargs[kwarg] = self._marshal(kwargs[kwarg])
result = getattr(self.service, method)(_this=_this, **kwargs)
if hasattr(result, '__iter__') is False:
logger.debug("Returning non-iterable result")
return result
# We must traverse the result and convert any ManagedObjectReference
# to a psphere class, this will then be lazy initialised on use
logger.debug(result.__class__)
logger.debug("Result: %s", result)
logger.debug("Length: %s", len(result))
if type(result) == list:
new_result = []
for item in result:
new_result.append(self._unmarshal(item))
else:
new_result = self._unmarshal(result)
logger.debug("Finished in invoke.")
#property = self.find_and_destroy(property)
#print result
# Return the modified result to the caller
return new_result | Invoke a method on the server.
>>> client.invoke('CurrentTime', client.si)
:param method: The method to invoke, as found in the SDK.
:type method: str
:param _this: The managed object reference against which to invoke \
the method.
:type _this: ManagedObject
:param kwargs: The arguments to pass to the method, as \
found in the SDK.
:type kwargs: TODO | entailment |
def _mor_to_pobject(self, mo_ref):
"""Converts a MOR to a psphere object."""
kls = classmapper(mo_ref._type)
new_object = kls(mo_ref, self)
return new_object | Converts a MOR to a psphere object. | entailment |
def _marshal(self, obj):
"""Walks an object and marshals any psphere object into MORs."""
logger.debug("Checking if %s needs to be marshalled", obj)
if isinstance(obj, ManagedObject):
logger.debug("obj is a psphere object, converting to MOR")
return obj._mo_ref
if isinstance(obj, list):
logger.debug("obj is a list, recursing it")
new_list = []
for item in obj:
new_list.append(self._marshal(item))
return new_list
if not isinstance(obj, suds.sudsobject.Object):
logger.debug("%s is not a sudsobject subclass, skipping", obj)
return obj
if hasattr(obj, '__iter__'):
logger.debug("obj is iterable, recursing it")
for (name, value) in obj:
setattr(obj, name, self._marshal(value))
return obj
# The obj has nothing that we want to marshal or traverse, return it
logger.debug("obj doesn't need to be marshalled")
return obj | Walks an object and marshals any psphere object into MORs. | entailment |
def _unmarshal(self, obj):
"""Walks an object and unmarshals any MORs into psphere objects."""
if isinstance(obj, suds.sudsobject.Object) is False:
logger.debug("%s is not a suds instance, skipping", obj)
return obj
logger.debug("Processing:")
logger.debug(obj)
logger.debug("...with keylist:")
logger.debug(obj.__keylist__)
# If the obj that we're looking at has a _type key
# then create a class of that type and return it immediately
if "_type" in obj.__keylist__:
logger.debug("obj is a MOR, converting to psphere class")
return self._mor_to_pobject(obj)
new_object = obj.__class__()
for sub_obj in obj:
logger.debug("Looking at %s of type %s", sub_obj, type(sub_obj))
if isinstance(sub_obj[1], list):
new_embedded_objs = []
for emb_obj in sub_obj[1]:
new_emb_obj = self._unmarshal(emb_obj)
new_embedded_objs.append(new_emb_obj)
setattr(new_object, sub_obj[0], new_embedded_objs)
continue
if not issubclass(sub_obj[1].__class__, suds.sudsobject.Object):
logger.debug("%s is not a sudsobject subclass, skipping",
sub_obj[1].__class__)
setattr(new_object, sub_obj[0], sub_obj[1])
continue
logger.debug("Obj keylist: %s", sub_obj[1].__keylist__)
if "_type" in sub_obj[1].__keylist__:
logger.debug("Converting nested MOR to psphere class:")
logger.debug(sub_obj[1])
kls = classmapper(sub_obj[1]._type)
logger.debug("Setting %s.%s to %s",
new_object.__class__.__name__,
sub_obj[0],
sub_obj[1])
setattr(new_object, sub_obj[0], kls(sub_obj[1], self))
else:
logger.debug("Didn't find _type in:")
logger.debug(sub_obj[1])
setattr(new_object, sub_obj[0], self._unmarshal(sub_obj[1]))
return new_object | Walks an object and unmarshals any MORs into psphere objects. | entailment |
def create(self, type_, **kwargs):
"""Create a SOAP object of the requested type.
>>> client.create('VirtualE1000')
:param type_: The type of SOAP object to create.
:type type_: str
:param kwargs: TODO
:type kwargs: TODO
"""
obj = self.factory.create("ns0:%s" % type_)
for key, value in kwargs.items():
setattr(obj, key, value)
return obj | Create a SOAP object of the requested type.
>>> client.create('VirtualE1000')
:param type_: The type of SOAP object to create.
:type type_: str
:param kwargs: TODO
:type kwargs: TODO | entailment |
def get_view(self, mo_ref, properties=None):
"""Get a view of a vSphere managed object.
:param mo_ref: The MOR to get a view of
:type mo_ref: ManagedObjectReference
:param properties: A list of properties to retrieve from the \
server
:type properties: list
:returns: A view representing the ManagedObjectReference.
:rtype: ManagedObject
"""
# This maps the mo_ref into a psphere class and then instantiates it
kls = classmapper(mo_ref._type)
view = kls(mo_ref, self)
# Update the requested properties of the instance
#view.update_view_data(properties=properties)
return view | Get a view of a vSphere managed object.
:param mo_ref: The MOR to get a view of
:type mo_ref: ManagedObjectReference
:param properties: A list of properties to retrieve from the \
server
:type properties: list
:returns: A view representing the ManagedObjectReference.
:rtype: ManagedObject | entailment |
def get_views(self, mo_refs, properties=None):
"""Get a list of local view's for multiple managed objects.
:param mo_refs: The list of ManagedObjectReference's that views are \
to be created for.
:type mo_refs: ManagedObjectReference
:param properties: The properties to retrieve in the views.
:type properties: list
:returns: A list of local instances representing the server-side \
managed objects.
:rtype: list of ManagedObject's
"""
property_specs = []
for mo_ref in mo_refs:
property_spec = self.create('PropertySpec')
property_spec.type = str(mo_ref._type)
if properties is None:
properties = []
else:
# Only retrieve the requested properties
if properties == "all":
property_spec.all = True
else:
property_spec.all = False
property_spec.pathSet = properties
property_specs.append(property_spec)
object_specs = []
for mo_ref in mo_refs:
object_spec = self.create('ObjectSpec')
object_spec.obj = mo_ref
object_specs.append(object_spec)
pfs = self.create('PropertyFilterSpec')
pfs.propSet = property_specs
pfs.objectSet = object_specs
object_contents = self.sc.propertyCollector.RetrieveProperties(
specSet=pfs)
views = []
for object_content in object_contents:
# Update the instance with the data in object_content
object_content.obj._set_view_data(object_content=object_content)
views.append(object_content.obj)
return views | Get a list of local view's for multiple managed objects.
:param mo_refs: The list of ManagedObjectReference's that views are \
to be created for.
:type mo_refs: ManagedObjectReference
:param properties: The properties to retrieve in the views.
:type properties: list
:returns: A list of local instances representing the server-side \
managed objects.
:rtype: list of ManagedObject's | entailment |
def get_search_filter_spec(self, begin_entity, property_spec):
"""Build a PropertyFilterSpec capable of full inventory traversal.
By specifying all valid traversal specs we are creating a PFS that
can recursively select any object under the given entity.
:param begin_entity: The place in the MOB to start the search.
:type begin_entity: ManagedEntity
:param property_spec: TODO
:type property_spec: TODO
:returns: A PropertyFilterSpec, suitable for recursively searching \
under the given ManagedEntity.
:rtype: PropertyFilterSpec
"""
# The selection spec for additional objects we want to filter
ss_strings = ['resource_pool_traversal_spec',
'resource_pool_vm_traversal_spec',
'folder_traversal_spec',
'datacenter_host_traversal_spec',
'datacenter_vm_traversal_spec',
'compute_resource_rp_traversal_spec',
'compute_resource_host_traversal_spec',
'host_vm_traversal_spec',
'datacenter_datastore_traversal_spec']
# Create a selection spec for each of the strings specified above
selection_specs = [
self.create('SelectionSpec', name=ss_string)
for ss_string in ss_strings
]
# A traversal spec for deriving ResourcePool's from found VMs
rpts = self.create('TraversalSpec')
rpts.name = 'resource_pool_traversal_spec'
rpts.type = 'ResourcePool'
rpts.path = 'resourcePool'
rpts.selectSet = [selection_specs[0], selection_specs[1]]
# A traversal spec for deriving ResourcePool's from found VMs
rpvts = self.create('TraversalSpec')
rpvts.name = 'resource_pool_vm_traversal_spec'
rpvts.type = 'ResourcePool'
rpvts.path = 'vm'
crrts = self.create('TraversalSpec')
crrts.name = 'compute_resource_rp_traversal_spec'
crrts.type = 'ComputeResource'
crrts.path = 'resourcePool'
crrts.selectSet = [selection_specs[0], selection_specs[1]]
crhts = self.create('TraversalSpec')
crhts.name = 'compute_resource_host_traversal_spec'
crhts.type = 'ComputeResource'
crhts.path = 'host'
dhts = self.create('TraversalSpec')
dhts.name = 'datacenter_host_traversal_spec'
dhts.type = 'Datacenter'
dhts.path = 'hostFolder'
dhts.selectSet = [selection_specs[2]]
dsts = self.create('TraversalSpec')
dsts.name = 'datacenter_datastore_traversal_spec'
dsts.type = 'Datacenter'
dsts.path = 'datastoreFolder'
dsts.selectSet = [selection_specs[2]]
dvts = self.create('TraversalSpec')
dvts.name = 'datacenter_vm_traversal_spec'
dvts.type = 'Datacenter'
dvts.path = 'vmFolder'
dvts.selectSet = [selection_specs[2]]
hvts = self.create('TraversalSpec')
hvts.name = 'host_vm_traversal_spec'
hvts.type = 'HostSystem'
hvts.path = 'vm'
hvts.selectSet = [selection_specs[2]]
fts = self.create('TraversalSpec')
fts.name = 'folder_traversal_spec'
fts.type = 'Folder'
fts.path = 'childEntity'
fts.selectSet = [selection_specs[2], selection_specs[3],
selection_specs[4], selection_specs[5],
selection_specs[6], selection_specs[7],
selection_specs[1], selection_specs[8]]
obj_spec = self.create('ObjectSpec')
obj_spec.obj = begin_entity
obj_spec.selectSet = [fts, dvts, dhts, crhts, crrts,
rpts, hvts, rpvts, dsts]
pfs = self.create('PropertyFilterSpec')
pfs.propSet = [property_spec]
pfs.objectSet = [obj_spec]
return pfs | Build a PropertyFilterSpec capable of full inventory traversal.
By specifying all valid traversal specs we are creating a PFS that
can recursively select any object under the given entity.
:param begin_entity: The place in the MOB to start the search.
:type begin_entity: ManagedEntity
:param property_spec: TODO
:type property_spec: TODO
:returns: A PropertyFilterSpec, suitable for recursively searching \
under the given ManagedEntity.
:rtype: PropertyFilterSpec | entailment |
def invoke_task(self, method, **kwargs):
"""Execute a \*_Task method and wait for it to complete.
:param method: The \*_Task method to invoke.
:type method: str
:param kwargs: The arguments to pass to the method.
:type kwargs: TODO
"""
# Don't execute methods which don't return a Task object
if not method.endswith('_Task'):
logger.error('invoke_task can only be used for methods which '
'return a ManagedObjectReference to a Task.')
return None
task_mo_ref = self.invoke(method=method, **kwargs)
task = Task(task_mo_ref, self)
task.update_view_data(properties=['info'])
# TODO: This returns true when there is an error
while True:
if task.info.state == 'success':
return task
elif task.info.state == 'error':
# TODO: Handle error checking properly
raise TaskFailedError(task.info.error.localizedMessage)
# TODO: Implement progresscallbackfunc
# Sleep two seconds and then refresh the data from the server
time.sleep(2)
task.update_view_data(properties=['info']) | Execute a \*_Task method and wait for it to complete.
:param method: The \*_Task method to invoke.
:type method: str
:param kwargs: The arguments to pass to the method.
:type kwargs: TODO | entailment |
def find_entity_views(self, view_type, begin_entity=None, properties=None):
"""Find all ManagedEntity's of the requested type.
:param view_type: The type of ManagedEntity's to find.
:type view_type: str
:param begin_entity: The MOR to start searching for the entity. \
The default is to start the search at the root folder.
:type begin_entity: ManagedObjectReference or None
:returns: A list of ManagedEntity's
:rtype: list
"""
if properties is None:
properties = []
# Start the search at the root folder if no begin_entity was given
if not begin_entity:
begin_entity = self.sc.rootFolder._mo_ref
property_spec = self.create('PropertySpec')
property_spec.type = view_type
property_spec.all = False
property_spec.pathSet = properties
pfs = self.get_search_filter_spec(begin_entity, property_spec)
# Retrieve properties from server and update entity
obj_contents = self.sc.propertyCollector.RetrieveProperties(specSet=pfs)
views = []
for obj_content in obj_contents:
logger.debug("In find_entity_view with object of type %s",
obj_content.obj.__class__.__name__)
obj_content.obj.update_view_data(properties=properties)
views.append(obj_content.obj)
return views | Find all ManagedEntity's of the requested type.
:param view_type: The type of ManagedEntity's to find.
:type view_type: str
:param begin_entity: The MOR to start searching for the entity. \
The default is to start the search at the root folder.
:type begin_entity: ManagedObjectReference or None
:returns: A list of ManagedEntity's
:rtype: list | entailment |
def find_entity_view(self, view_type, begin_entity=None, filter={},
properties=None):
"""Find a ManagedEntity of the requested type.
Traverses the MOB looking for an entity matching the filter.
:param view_type: The type of ManagedEntity to find.
:type view_type: str
:param begin_entity: The MOR to start searching for the entity. \
The default is to start the search at the root folder.
:type begin_entity: ManagedObjectReference or None
:param filter: Key/value pairs to filter the results. The key is \
a valid parameter of the ManagedEntity type. The value is what \
that parameter should match.
:type filter: dict
:returns: If an entity is found, a ManagedEntity matching the search.
:rtype: ManagedEntity
"""
if properties is None:
properties = []
kls = classmapper(view_type)
# Start the search at the root folder if no begin_entity was given
if not begin_entity:
begin_entity = self.sc.rootFolder._mo_ref
logger.debug("Using %s", self.sc.rootFolder._mo_ref)
property_spec = self.create('PropertySpec')
property_spec.type = view_type
property_spec.all = False
property_spec.pathSet = list(filter.keys())
pfs = self.get_search_filter_spec(begin_entity, property_spec)
# Retrieve properties from server and update entity
#obj_contents = self.propertyCollector.RetrieveProperties(specSet=pfs)
obj_contents = self.sc.propertyCollector.RetrieveProperties(specSet=pfs)
# TODO: Implement filtering
if not filter:
logger.warning('No filter specified, returning first match.')
# If no filter is specified we just return the first item
# in the list of returned objects
logger.debug("Creating class in find_entity_view (filter)")
view = kls(obj_contents[0].obj._mo_ref, self)
logger.debug("Completed creating class in find_entity_view (filter)")
#view.update_view_data(properties)
return view
matched = False
# Iterate through obj_contents retrieved
for obj_content in obj_contents:
# If there are is no propSet, skip this one
if not obj_content.propSet:
continue
matches = 0
# Iterate through each property in the set
for prop in obj_content.propSet:
for key in filter.keys():
# If the property name is in the defined filter
if prop.name == key:
# ...and it matches the value specified
# TODO: Regex this?
if prop.val == filter[prop.name]:
# We've found a match
matches += 1
else:
break
else:
continue
if matches == len(filter):
filtered_obj_content = obj_content
matched = True
break
else:
continue
if matched is not True:
# There were no matches
raise ObjectNotFoundError("No matching objects for filter")
logger.debug("Creating class in find_entity_view")
view = kls(filtered_obj_content.obj._mo_ref, self)
logger.debug("Completed creating class in find_entity_view")
#view.update_view_data(properties=properties)
return view | Find a ManagedEntity of the requested type.
Traverses the MOB looking for an entity matching the filter.
:param view_type: The type of ManagedEntity to find.
:type view_type: str
:param begin_entity: The MOR to start searching for the entity. \
The default is to start the search at the root folder.
:type begin_entity: ManagedObjectReference or None
:param filter: Key/value pairs to filter the results. The key is \
a valid parameter of the ManagedEntity type. The value is what \
that parameter should match.
:type filter: dict
:returns: If an entity is found, a ManagedEntity matching the search.
:rtype: ManagedEntity | entailment |
def load_template(name=None):
"""Loads a template of the specified name.
Templates are placed in the <template_dir> directory in YAML format with
a .yaml extension.
If no name is specified then the function will return the default
template (<template_dir>/default.yaml) if it exists.
:param name: The name of the template to load.
:type name: str or None (default)
"""
if name is None:
name = "default"
logger.info("Loading template with name %s", name)
try:
template_file = open("%s/%s.yaml" % (template_path, name))
except IOError:
raise TemplateNotFoundError
template = yaml.safe_load(template_file)
template_file.close()
if "extends" in template:
logger.debug("Merging %s with %s", name, template["extends"])
template = _merge(load_template(template["extends"]), template)
return template | Loads a template of the specified name.
Templates are placed in the <template_dir> directory in YAML format with
a .yaml extension.
If no name is specified then the function will return the default
template (<template_dir>/default.yaml) if it exists.
:param name: The name of the template to load.
:type name: str or None (default) | entailment |
def list_templates():
"""Returns a list of all templates."""
templates = [f for f in glob.glob(os.path.join(template_path, '*.yaml'))]
return templates | Returns a list of all templates. | entailment |
def create_vm(client, name, compute_resource, datastore, disksize, nics,
memory, num_cpus, guest_id, host=None):
"""Create a virtual machine using the specified values.
:param name: The name of the VM to create.
:type name: str
:param compute_resource: The name of a ComputeResource in which to \
create the VM.
:type compute_resource: str
:param datastore: The name of the datastore on which to create the VM.
:type datastore: str
:param disksize: The size of the disk, specified in KB, MB or GB. e.g. \
20971520KB, 20480MB, 20GB.
:type disksize: str
:param nics: The NICs to create, specified in a list of dict's which \
contain a "network_name" and "type" key. e.g. \
{"network_name": "VM Network", "type": "VirtualE1000"}
:type nics: list of dict's
:param memory: The amount of memory for the VM. Specified in KB, MB or \
GB. e.g. 2097152KB, 2048MB, 2GB.
:type memory: str
:param num_cpus: The number of CPUs the VM will have.
:type num_cpus: int
:param guest_id: The vSphere string of the VM guest you are creating. \
The list of VMs can be found at \
http://pubs.vmware.com/vsphere-50/index.jsp?topic=/com.vmware.wssdk.apiref.doc_50/right-pane.html
:type guest_id: str
:param host: The name of the host (default: None), if you want to \
provision the VM on a \ specific host.
:type host: str
"""
print("Creating VM %s" % name)
# If the host is not set, use the ComputeResource as the target
if host is None:
target = client.find_entity_view("ComputeResource",
filter={"name": compute_resource})
resource_pool = target.resourcePool
else:
target = client.find_entity_view("HostSystem", filter={"name": host})
resource_pool = target.parent.resourcePool
disksize_pattern = re.compile("^\d+[KMG]B")
if disksize_pattern.match(disksize) is None:
print("Disk size %s is invalid. Try \"12G\" or similar" % disksize)
sys.exit(1)
if disksize.endswith("GB"):
disksize_kb = int(disksize[:-2]) * 1024 * 1024
elif disksize.endswith("MB"):
disksize_kb = int(disksize[:-2]) * 1024
elif disksize.endswith("KB"):
disksize_kb = int(disksize[:-2])
else:
print("Disk size %s is invalid. Try \"12G\" or similar" % disksize)
memory_pattern = re.compile("^\d+[KMG]B")
if memory_pattern.match(memory) is None:
print("Memory size %s is invalid. Try \"12G\" or similar" % memory)
sys.exit(1)
if memory.endswith("GB"):
memory_mb = int(memory[:-2]) * 1024
elif memory.endswith("MB"):
memory_mb = int(memory[:-2])
elif memory.endswith("KB"):
memory_mb = int(memory[:-2]) / 1024
else:
print("Memory size %s is invalid. Try \"12G\" or similar" % memory)
# A list of devices to be assigned to the VM
vm_devices = []
# Create a disk controller
controller = create_controller(client, "VirtualLsiLogicController")
vm_devices.append(controller)
ds_to_use = None
for ds in target.datastore:
if ds.name == datastore:
ds_to_use = ds
break
if ds_to_use is None:
print("Could not find datastore on %s with name %s" %
(target.name, datastore))
sys.exit(1)
# Ensure the datastore is accessible and has enough space
if ds_to_use.summary.accessible is not True:
print("Datastore (%s) exists, but is not accessible" %
ds_to_use.summary.name)
sys.exit(1)
if ds_to_use.summary.freeSpace < disksize_kb * 1024:
print("Datastore (%s) exists, but does not have sufficient"
" free space." % ds_to_use.summary.name)
sys.exit(1)
disk = create_disk(client, datastore=ds_to_use, disksize_kb=disksize_kb)
vm_devices.append(disk)
for nic in nics:
nic_spec = create_nic(client, target, nic)
if nic_spec is None:
print("Could not create spec for NIC")
sys.exit(1)
# Append the nic spec to the vm_devices list
vm_devices.append(nic_spec)
vmfi = client.create("VirtualMachineFileInfo")
vmfi.vmPathName = "[%s]" % ds_to_use.summary.name
vm_config_spec = client.create("VirtualMachineConfigSpec")
vm_config_spec.name = name
vm_config_spec.memoryMB = memory_mb
vm_config_spec.files = vmfi
vm_config_spec.annotation = "Auto-provisioned by psphere"
vm_config_spec.numCPUs = num_cpus
vm_config_spec.guestId = guest_id
vm_config_spec.deviceChange = vm_devices
# Find the datacenter of the target
if target.__class__.__name__ == "HostSystem":
datacenter = target.parent.parent.parent
else:
datacenter = target.parent.parent
try:
task = datacenter.vmFolder.CreateVM_Task(config=vm_config_spec,
pool=resource_pool)
except VimFault as e:
print("Failed to create %s: " % e)
sys.exit()
while task.info.state in ["queued", "running"]:
time.sleep(5)
task.update()
print("Waiting 5 more seconds for VM creation")
if task.info.state == "success":
elapsed_time = task.info.completeTime - task.info.startTime
print("Successfully created new VM %s. Server took %s seconds." %
(name, elapsed_time.seconds))
elif task.info.state == "error":
print("ERROR: The task for creating the VM has finished with"
" an error. If an error was reported it will follow.")
try:
print("ERROR: %s" % task.info.error.localizedMessage)
except AttributeError:
print("ERROR: There is no error message available.")
else:
print("UNKNOWN: The task reports an unknown state %s" %
task.info.state) | Create a virtual machine using the specified values.
:param name: The name of the VM to create.
:type name: str
:param compute_resource: The name of a ComputeResource in which to \
create the VM.
:type compute_resource: str
:param datastore: The name of the datastore on which to create the VM.
:type datastore: str
:param disksize: The size of the disk, specified in KB, MB or GB. e.g. \
20971520KB, 20480MB, 20GB.
:type disksize: str
:param nics: The NICs to create, specified in a list of dict's which \
contain a "network_name" and "type" key. e.g. \
{"network_name": "VM Network", "type": "VirtualE1000"}
:type nics: list of dict's
:param memory: The amount of memory for the VM. Specified in KB, MB or \
GB. e.g. 2097152KB, 2048MB, 2GB.
:type memory: str
:param num_cpus: The number of CPUs the VM will have.
:type num_cpus: int
:param guest_id: The vSphere string of the VM guest you are creating. \
The list of VMs can be found at \
http://pubs.vmware.com/vsphere-50/index.jsp?topic=/com.vmware.wssdk.apiref.doc_50/right-pane.html
:type guest_id: str
:param host: The name of the host (default: None), if you want to \
provision the VM on a \ specific host.
:type host: str | entailment |
def create_nic(client, target, nic):
"""Return a NIC spec"""
# Iterate through the networks and look for one matching
# the requested name
for network in target.network:
if network.name == nic["network_name"]:
net = network
break
else:
return None
# Success! Create a nic attached to this network
backing = client.create("VirtualEthernetCardNetworkBackingInfo")
backing.deviceName = nic["network_name"]
backing.network = net
connect_info = client.create("VirtualDeviceConnectInfo")
connect_info.allowGuestControl = True
connect_info.connected = False
connect_info.startConnected = True
new_nic = client.create(nic["type"])
new_nic.backing = backing
new_nic.key = 2
# TODO: Work out a way to automatically increment this
new_nic.unitNumber = 1
new_nic.addressType = "generated"
new_nic.connectable = connect_info
nic_spec = client.create("VirtualDeviceConfigSpec")
nic_spec.device = new_nic
nic_spec.fileOperation = None
operation = client.create("VirtualDeviceConfigSpecOperation")
nic_spec.operation = (operation.add)
return nic_spec | Return a NIC spec | entailment |
def main(name, options):
"""The main method for this script.
:param name: The name of the VM to create.
:type name: str
:param template_name: The name of the template to use for creating \
the VM.
:type template_name: str
"""
server = config._config_value("general", "server", options.server)
if server is None:
raise ValueError("server must be supplied on command line"
" or in configuration file.")
username = config._config_value("general", "username", options.username)
if username is None:
raise ValueError("username must be supplied on command line"
" or in configuration file.")
password = config._config_value("general", "password", options.password)
if password is None:
raise ValueError("password must be supplied on command line"
" or in configuration file.")
vm_template = None
if options.template is not None:
try:
vm_template = template.load_template(options.template)
except TemplateNotFoundError:
print("ERROR: Template \"%s\" could not be found." % options.template)
sys.exit(1)
expected_opts = ["compute_resource", "datastore", "disksize", "nics",
"memory", "num_cpus", "guest_id", "host"]
vm_opts = {}
for opt in expected_opts:
vm_opts[opt] = getattr(options, opt)
if vm_opts[opt] is None:
if vm_template is None:
raise ValueError("%s not specified on the command line and"
" you have not specified any template to"
" inherit the value from." % opt)
try:
vm_opts[opt] = vm_template[opt]
except AttributeError:
raise ValueError("%s not specified on the command line and"
" no value is provided in the specified"
" template." % opt)
client = Client(server=server, username=username, password=password)
create_vm(client, name, vm_opts["compute_resource"], vm_opts["datastore"],
vm_opts["disksize"], vm_opts["nics"], vm_opts["memory"],
vm_opts["num_cpus"], vm_opts["guest_id"], host=vm_opts["host"])
client.logout() | The main method for this script.
:param name: The name of the VM to create.
:type name: str
:param template_name: The name of the template to use for creating \
the VM.
:type template_name: str | entailment |
def add_ignore_patterns(self, *patterns):
"""
Adds an ignore pattern to the list for ignore patterns.
Ignore patterns are used to filter out unwanted files or directories
from the file system model.
A pattern is a Unix shell-style wildcards. See :mod:`fnmatch` for a
deeper explanation about the shell-style wildcards.
"""
for ptrn in patterns:
if isinstance(ptrn, list):
for p in ptrn:
self._ignored_patterns.append(p)
else:
self._ignored_patterns.append(ptrn) | Adds an ignore pattern to the list for ignore patterns.
Ignore patterns are used to filter out unwanted files or directories
from the file system model.
A pattern is a Unix shell-style wildcards. See :mod:`fnmatch` for a
deeper explanation about the shell-style wildcards. | entailment |
def set_context_menu(self, context_menu):
"""
Sets the context menu of the tree view.
:param context_menu: QMenu
"""
self.context_menu = context_menu
self.context_menu.tree_view = self
self.context_menu.init_actions()
for action in self.context_menu.actions():
self.addAction(action) | Sets the context menu of the tree view.
:param context_menu: QMenu | entailment |
def set_root_path(self, path, hide_extra_columns=True):
"""
Sets the root path to watch
:param path: root path - str
:param hide_extra_columns: Hide extra column (size, paths,...)
"""
if not self.isVisible():
self._path_to_set = path
self._hide_extra_colums = hide_extra_columns
return
if sys.platform == 'win32' and os.path.splitunc(path)[0]:
mdl = QtGui.QStandardItemModel(1, 1)
item = QtGui.QStandardItem(
QtGui.QIcon.fromTheme(
'dialog-warning',
QtGui.QIcon(':/pyqode-icons/rc/dialog-warning.png')),
'UNC pathnames not supported.')
mdl.setItem(0, 0, item)
self.setModel(mdl)
self.root_path = None
return
self._hide_extra_colums = hide_extra_columns
if os.path.isfile(path):
path = os.path.abspath(os.path.join(path, os.pardir))
self._fs_model_source = QtWidgets.QFileSystemModel()
self._fs_model_source.setFilter(QtCore.QDir.Dirs | QtCore.QDir.Files |
QtCore.QDir.NoDotAndDotDot |
QtCore.QDir.Hidden)
self._fs_model_source.setIconProvider(self._icon_provider)
self._fs_model_proxy = self.FilterProxyModel()
for item in self._ignored_patterns:
self._fs_model_proxy.ignored_patterns.append(item)
self._fs_model_proxy.setSourceModel(self._fs_model_source)
self._fs_model_proxy.set_root_path(path)
# takes parent of the root path, filter will keep only `path`, that
# way `path` appear as the top level node of the tree
self._root_path = os.path.dirname(path)
self.root_path = path
self._fs_model_source.directoryLoaded.connect(self._on_path_loaded)
self._fs_model_source.setRootPath(self._root_path) | Sets the root path to watch
:param path: root path - str
:param hide_extra_columns: Hide extra column (size, paths,...) | entailment |
def filePath(self, index):
"""
Gets the file path of the item at the specified ``index``.
:param index: item index - QModelIndex
:return: str
"""
return self._fs_model_source.filePath(
self._fs_model_proxy.mapToSource(index)) | Gets the file path of the item at the specified ``index``.
:param index: item index - QModelIndex
:return: str | entailment |
def fileInfo(self, index):
"""
Gets the file info of the item at the specified ``index``.
:param index: item index - QModelIndex
:return: QFileInfo
"""
return self._fs_model_source.fileInfo(
self._fs_model_proxy.mapToSource(index)) | Gets the file info of the item at the specified ``index``.
:param index: item index - QModelIndex
:return: QFileInfo | entailment |
def copy_to_clipboard(self, copy=True):
"""
Copies the selected items to the clipboard
:param copy: True to copy, False to cut.
"""
urls = self.selected_urls()
if not urls:
return
mime = self._UrlListMimeData(copy)
mime.set_list(urls)
clipboard = QtWidgets.QApplication.clipboard()
clipboard.setMimeData(mime) | Copies the selected items to the clipboard
:param copy: True to copy, False to cut. | entailment |
def selected_urls(self):
"""
Gets the list of selected items file path (url)
"""
urls = []
debug('gettings urls')
for proxy_index in self.tree_view.selectedIndexes():
finfo = self.tree_view.fileInfo(proxy_index)
urls.append(finfo.canonicalFilePath())
debug('selected urls %r' % [str(url) for url in urls])
return urls | Gets the list of selected items file path (url) | entailment |
def paste_from_clipboard(self):
"""
Pastes files from clipboard.
"""
to = self.get_current_path()
if os.path.isfile(to):
to = os.path.abspath(os.path.join(to, os.pardir))
mime = QtWidgets.QApplication.clipboard().mimeData()
paste_operation = None
if mime.hasFormat(self._UrlListMimeData.format(copy=True)):
paste_operation = True
elif mime.hasFormat(self._UrlListMimeData.format(copy=False)):
paste_operation = False
if paste_operation is not None:
self._paste(
self._UrlListMimeData.list_from(mime, copy=paste_operation),
to, copy=paste_operation) | Pastes files from clipboard. | entailment |
def _paste(self, sources, destination, copy):
"""
Copies the files listed in ``sources`` to destination. Source are
removed if copy is set to False.
"""
for src in sources:
debug('%s <%s> to <%s>' % (
'copying' if copy else 'cutting', src, destination))
perform_copy = True
ext = os.path.splitext(src)[1]
original = os.path.splitext(os.path.split(src)[1])[0]
filename, status = QtWidgets.QInputDialog.getText(
self.tree_view, _('Copy'), _('New name:'),
QtWidgets.QLineEdit.Normal, original)
if filename == '' or not status:
return
filename = filename + ext
final_dest = os.path.join(destination, filename)
if os.path.exists(final_dest):
rep = QtWidgets.QMessageBox.question(
self.tree_view, _('File exists'),
_('File <%s> already exists. Do you want to erase it?') %
final_dest,
QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No,
QtWidgets.QMessageBox.No)
if rep == QtWidgets.QMessageBox.No:
perform_copy = False
if not perform_copy:
continue
try:
if os.path.isfile(src):
shutil.copy(src, final_dest)
else:
shutil.copytree(src, final_dest)
except (IOError, OSError) as e:
QtWidgets.QMessageBox.warning(
self.tree_view, _('Copy failed'), _('Failed to copy "%s" to "%s".\n\n%s' %
(src, destination, str(e))))
_logger().exception('failed to copy "%s" to "%s', src,
destination)
else:
debug('file copied %s', src)
if not copy:
debug('removing source (cut operation)')
if os.path.isfile(src):
os.remove(src)
else:
shutil.rmtree(src)
self.tree_view.files_renamed.emit([(src, final_dest)]) | Copies the files listed in ``sources`` to destination. Source are
removed if copy is set to False. | entailment |
def _get_files(path):
"""
Returns the list of files contained in path (recursively).
"""
ret_val = []
for root, _, files in os.walk(path):
for f in files:
ret_val.append(os.path.join(root, f))
return ret_val | Returns the list of files contained in path (recursively). | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.