INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Setup the toolbar | def setup_toolbar(self):
"""Setup the toolbar"""
savefig_btn = create_toolbutton(
self, icon=ima.icon('filesave'),
tip=_("Save Image As..."),
triggered=self.save_figure)
saveall_btn = create_toolbutton(
self, icon=ima.icon('save_al... |
Create shortcuts for this widget. | def create_shortcuts(self):
"""Create shortcuts for this widget."""
# Configurable
copyfig = config_shortcut(self.copy_figure, context='plots',
name='copy', parent=self)
prevfig = config_shortcut(self.go_previous_thumbnail, context='plots',
... |
Setup the actions to show in the cog menu. | def setup_option_actions(self, mute_inline_plotting, show_plot_outline):
"""Setup the actions to show in the cog menu."""
self.setup_in_progress = True
self.mute_inline_action = create_action(
self, _("Mute inline plotting"),
tip=_("Mute inline plotting in the ipython con... |
Handle when the value of an option has changed | def option_changed(self, option, value):
"""Handle when the value of an option has changed"""
setattr(self, to_text_string(option), value)
self.shellwidget.set_namespace_view_settings()
if self.setup_in_progress is False:
self.sig_option_changed.emit(option, value) |
Draw a frame around the figure viewer if state is True. | def show_fig_outline_in_viewer(self, state):
"""Draw a frame around the figure viewer if state is True."""
if state is True:
self.figviewer.figcanvas.setStyleSheet(
"FigureCanvas{border: 1px solid lightgrey;}")
else:
self.figviewer.figcanvas.setStyleSh... |
Bind the shellwidget instance to the figure browser | def set_shellwidget(self, shellwidget):
"""Bind the shellwidget instance to the figure browser"""
self.shellwidget = shellwidget
shellwidget.set_figurebrowser(self)
shellwidget.sig_new_inline_figure.connect(self._handle_new_figure) |
Copy figure from figviewer to clipboard. | def copy_figure(self):
"""Copy figure from figviewer to clipboard."""
if self.figviewer and self.figviewer.figcanvas.fig:
self.figviewer.figcanvas.copy_figure() |
Setup the FigureCanvas. | def setup_figcanvas(self):
"""Setup the FigureCanvas."""
self.figcanvas = FigureCanvas(background_color=self.background_color)
self.figcanvas.installEventFilter(self)
self.setWidget(self.figcanvas) |
Set a new figure in the figure canvas. | def load_figure(self, fig, fmt):
"""Set a new figure in the figure canvas."""
self.figcanvas.load_figure(fig, fmt)
self.scale_image()
self.figcanvas.repaint() |
A filter to control the zooming and panning of the figure canvas. | def eventFilter(self, widget, event):
"""A filter to control the zooming and panning of the figure canvas."""
# ---- Zooming
if event.type() == QEvent.Wheel:
modifiers = QApplication.keyboardModifiers()
if modifiers == Qt.ControlModifier:
if event.angleDe... |
Scale the image up by one scale step. | def zoom_in(self):
"""Scale the image up by one scale step."""
if self._scalefactor <= self._sfmax:
self._scalefactor += 1
self.scale_image()
self._adjust_scrollbar(self._scalestep)
self.sig_zoom_changed.emit(self.get_scaling()) |
Scale the image down by one scale step. | def zoom_out(self):
"""Scale the image down by one scale step."""
if self._scalefactor >= self._sfmin:
self._scalefactor -= 1
self.scale_image()
self._adjust_scrollbar(1/self._scalestep)
self.sig_zoom_changed.emit(self.get_scaling()) |
Scale the image size. | def scale_image(self):
"""Scale the image size."""
new_width = int(self.figcanvas.fwidth *
self._scalestep ** self._scalefactor)
new_height = int(self.figcanvas.fheight *
self._scalestep ** self._scalefactor)
self.figcanvas.setFixedSize(ne... |
Adjust the scrollbar position to take into account the zooming of
the figure. | def _adjust_scrollbar(self, f):
"""
Adjust the scrollbar position to take into account the zooming of
the figure.
"""
# Adjust horizontal scrollbar :
hb = self.horizontalScrollBar()
hb.setValue(int(f * hb.value() + ((f - 1) * hb.pageStep()/2)))
# Adjust t... |
Setup the main layout of the widget. | def setup_gui(self):
"""Setup the main layout of the widget."""
scrollarea = self.setup_scrollarea()
up_btn, down_btn = self.setup_arrow_buttons()
self.setFixedWidth(150)
layout = QVBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
... |
Setup the scrollarea that will contain the FigureThumbnails. | def setup_scrollarea(self):
"""Setup the scrollarea that will contain the FigureThumbnails."""
self.view = QWidget()
self.scene = QGridLayout(self.view)
self.scene.setColumnStretch(0, 100)
self.scene.setColumnStretch(2, 100)
self.scrollarea = QScrollArea()
self.... |
Setup the up and down arrow buttons that are placed at the top and
bottom of the scrollarea. | def setup_arrow_buttons(self):
"""
Setup the up and down arrow buttons that are placed at the top and
bottom of the scrollarea.
"""
# Get the height of the up/down arrow of the default vertical
# scrollbar :
vsb = self.scrollarea.verticalScrollBar()
style ... |
Save all the figures to a file. | def save_all_figures_as(self):
"""Save all the figures to a file."""
self.redirect_stdio.emit(False)
dirname = getexistingdirectory(self, caption='Save all figures',
basedir=getcwd_or_home())
self.redirect_stdio.emit(True)
if dirname:
... |
Save all figure in dirname. | def save_all_figures_todir(self, dirname):
"""Save all figure in dirname."""
fignames = []
for thumbnail in self._thumbnails:
fig = thumbnail.canvas.fig
fmt = thumbnail.canvas.fmt
fext = {'image/png': '.png',
'image/jpeg': '.jpg',
... |
Save the currently selected figure. | def save_current_figure_as(self):
"""Save the currently selected figure."""
if self.current_thumbnail is not None:
self.save_figure_as(self.current_thumbnail.canvas.fig,
self.current_thumbnail.canvas.fmt) |
Save the figure to a file. | def save_figure_as(self, fig, fmt):
"""Save the figure to a file."""
fext, ffilt = {
'image/png': ('.png', 'PNG (*.png)'),
'image/jpeg': ('.jpg', 'JPEG (*.jpg;*.jpeg;*.jpe;*.jfif)'),
'image/svg+xml': ('.svg', 'SVG (*.svg);;PNG (*.png)')}[fmt]
figname = get_un... |
Remove all thumbnails. | def remove_all_thumbnails(self):
"""Remove all thumbnails."""
for thumbnail in self._thumbnails:
self.layout().removeWidget(thumbnail)
thumbnail.sig_canvas_clicked.disconnect()
thumbnail.sig_remove_figure.disconnect()
thumbnail.sig_save_figure.disconnect()... |
Remove thumbnail. | def remove_thumbnail(self, thumbnail):
"""Remove thumbnail."""
if thumbnail in self._thumbnails:
index = self._thumbnails.index(thumbnail)
self._thumbnails.remove(thumbnail)
self.layout().removeWidget(thumbnail)
thumbnail.deleteLater()
thumbnail.sig_canvas... |
Set the currently selected thumbnail. | def set_current_thumbnail(self, thumbnail):
"""Set the currently selected thumbnail."""
self.current_thumbnail = thumbnail
self.figure_viewer.load_figure(
thumbnail.canvas.fig, thumbnail.canvas.fmt)
for thumbnail in self._thumbnails:
thumbnail.highlight_canvas... |
Select the thumbnail previous to the currently selected one. | def go_previous_thumbnail(self):
"""Select the thumbnail previous to the currently selected one."""
if self.current_thumbnail is not None:
index = self._thumbnails.index(self.current_thumbnail) - 1
index = index if index >= 0 else len(self._thumbnails) - 1
self.set_cu... |
Select thumbnail next to the currently selected one. | def go_next_thumbnail(self):
"""Select thumbnail next to the currently selected one."""
if self.current_thumbnail is not None:
index = self._thumbnails.index(self.current_thumbnail) + 1
index = 0 if index >= len(self._thumbnails) else index
self.set_current_index(inde... |
Scroll to the selected item of ThumbnailScrollBar. | def scroll_to_item(self, index):
"""Scroll to the selected item of ThumbnailScrollBar."""
spacing_between_items = self.scene.verticalSpacing()
height_view = self.scrollarea.viewport().height()
height_item = self.scene.itemAt(index).sizeHint().height()
height_view_excluding_item =... |
Scroll the scrollbar of the scrollarea up by a single step. | def go_up(self):
"""Scroll the scrollbar of the scrollarea up by a single step."""
vsb = self.scrollarea.verticalScrollBar()
vsb.setValue(int(vsb.value() - vsb.singleStep())) |
Setup the main layout of the widget. | def setup_gui(self):
"""Setup the main layout of the widget."""
layout = QGridLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.addWidget(self.canvas, 0, 1)
layout.addLayout(self.setup_toolbar(), 0, 3, 2, 1)
layout.setColumnStretch(0, 100)
layout.setColum... |
Setup the toolbar. | def setup_toolbar(self):
"""Setup the toolbar."""
self.savefig_btn = create_toolbutton(
self, icon=ima.icon('filesave'),
tip=_("Save Image As..."),
triggered=self.emit_save_figure)
self.delfig_btn = create_toolbutton(
self, icon=ima.icon('editclear... |
Set a colored frame around the FigureCanvas if highlight is True. | def highlight_canvas(self, highlight):
"""
Set a colored frame around the FigureCanvas if highlight is True.
"""
colorname = self.canvas.palette().highlight().color().name()
if highlight:
self.canvas.setStyleSheet(
"FigureCanvas{border: 1px solid %... |
A filter that is used to send a signal when the figure canvas is
clicked. | def eventFilter(self, widget, event):
"""
A filter that is used to send a signal when the figure canvas is
clicked.
"""
if event.type() == QEvent.MouseButtonPress:
if event.button() == Qt.LeftButton:
self.sig_canvas_clicked.emit(self)
return su... |
Emit a signal when the toolbutton to save the figure is clicked. | def emit_save_figure(self):
"""
Emit a signal when the toolbutton to save the figure is clicked.
"""
self.sig_save_figure.emit(self.canvas.fig, self.canvas.fmt) |
Popup context menu. | def context_menu_requested(self, event):
"""Popup context menu."""
if self.fig:
pos = QPoint(event.x(), event.y())
context_menu = QMenu(self)
context_menu.addAction(ima.icon('editcopy'), "Copy Image",
self.copy_figure,
... |
Copy figure to clipboard. | def copy_figure(self):
"""Copy figure to clipboard."""
if self.fmt in ['image/png', 'image/jpeg']:
qpixmap = QPixmap()
qpixmap.loadFromData(self.fig, self.fmt.upper())
QApplication.clipboard().setImage(qpixmap.toImage())
elif self.fmt == 'image/svg+xml':
... |
Blink figure once. | def blink_figure(self):
"""Blink figure once."""
if self.fig:
self._blink_flag = not self._blink_flag
self.repaint()
if self._blink_flag:
timer = QTimer()
timer.singleShot(40, self.blink_figure) |
Clear the figure that was painted on the widget. | def clear_canvas(self):
"""Clear the figure that was painted on the widget."""
self.fig = None
self.fmt = None
self._qpix_buffer = []
self.repaint() |
Load the figure from a png, jpg, or svg image, convert it in
a QPixmap, and force a repaint of the widget. | def load_figure(self, fig, fmt):
"""
Load the figure from a png, jpg, or svg image, convert it in
a QPixmap, and force a repaint of the widget.
"""
self.fig = fig
self.fmt = fmt
if fmt in ['image/png', 'image/jpeg']:
self._qpix_orig = QPixmap()
... |
Qt method override to paint a custom image on the Widget. | def paintEvent(self, event):
"""Qt method override to paint a custom image on the Widget."""
super(FigureCanvas, self).paintEvent(event)
# Prepare the rect on which the image is going to be painted :
fw = self.frameWidth()
rect = QRect(0 + fw, 0 + fw,
self.si... |
Custom Python executable value has been changed | def python_executable_changed(self, pyexec):
"""Custom Python executable value has been changed"""
if not self.cus_exec_radio.isChecked():
return False
def_pyexec = get_python_executable()
if not is_text_string(pyexec):
pyexec = to_text_string(pyexec.toUtf8(... |
Set UMR excluded modules name list | def set_umr_namelist(self):
"""Set UMR excluded modules name list"""
arguments, valid = QInputDialog.getText(self, _('UMR'),
_("Set the list of excluded modules as "
"this: <i>numpy, scipy</i>"),
... |
Update the list of interpreters used and the current one. | def set_custom_interpreters_list(self, value):
"""Update the list of interpreters used and the current one."""
custom_list = self.get_option('custom_interpreters_list')
if value not in custom_list and value != get_python_executable():
custom_list.append(value)
self.s... |
Check that the used custom interpreters are still valid. | def validate_custom_interpreters_list(self):
"""Check that the used custom interpreters are still valid."""
custom_list = self.get_option('custom_interpreters_list')
valid_custom_list = []
for value in custom_list:
if (osp.isfile(value) and programs.is_python_interpreter... |
Extends :meth:`spyder.api.EditorExtension.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: spyder.plugins.editor.widgets.codeeditor.CodeE... | def on_install(self, editor):
"""
Extends :meth:`spyder.api.EditorExtension.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 edit... |
Fills the panel background using QPalette. | def paintEvent(self, event):
"""Fills the panel background using QPalette."""
if self.isVisible() and self.position != self.Position.FLOATING:
# fill background
self._background_brush = QBrush(QColor(
self.editor.sideareas_color))
self._foreground_pen ... |
Set geometry for floating panels.
Normally you don't need to override this method, you should override
`geometry` instead. | def set_geometry(self, crect):
"""Set geometry for floating panels.
Normally you don't need to override this method, you should override
`geometry` instead.
"""
x0, y0, width, height = self.geometry()
if width is None:
width = crect.width()
if height... |
Shows/Hides the panel.
Automatically call PanelsManager.refresh_panels.
:param visible: Visible state | def setVisible(self, visible):
"""
Shows/Hides the panel.
Automatically call PanelsManager.refresh_panels.
:param visible: Visible state
"""
logger.debug('%s visibility changed', self.name)
super(Panel, self).setVisible(visible)
if self.editor:
... |
We decided to replace pyzmq's openssh_tunnel method to work around
issue https://github.com/zeromq/pyzmq/issues/589 which was solved
in pyzmq https://github.com/zeromq/pyzmq/pull/615 | def openssh_tunnel(self, lport, rport, server, remoteip='127.0.0.1',
keyfile=None, password=None, timeout=0.4):
"""
We decided to replace pyzmq's openssh_tunnel method to work around
issue https://github.com/zeromq/pyzmq/issues/589 which was solved
in pyzmq https://github.com/zeromq/p... |
Configure associated namespace browser widget | def configure_namespacebrowser(self):
"""Configure associated namespace browser widget"""
# Update namespace view
self.sig_namespace_view.connect(lambda data:
self.namespacebrowser.process_remote_view(data))
# Update properties of variables
self.sig_var_properties.co... |
Set the namespace view settings | def set_namespace_view_settings(self):
"""Set the namespace view settings"""
if self.namespacebrowser:
settings = to_text_string(
self.namespacebrowser.get_view_settings())
code =(u"get_ipython().kernel.namespace_view_settings = %s" %
settings)
... |
Ask kernel for a value | def get_value(self, name):
"""Ask kernel for a value"""
code = u"get_ipython().kernel.get_value('%s')" % name
if self._reading:
method = self.kernel_client.input
code = u'!' + code
else:
method = self.silent_execute
# Wait until the kernel ret... |
Set value for a variable | def set_value(self, name, value):
"""Set value for a variable"""
value = to_text_string(value)
code = u"get_ipython().kernel.set_value('%s', %s, %s)" % (name, value,
PY2)
if self._reading:
self.kernel_client.i... |
Remove a variable | def remove_value(self, name):
"""Remove a variable"""
code = u"get_ipython().kernel.remove_value('%s')" % name
if self._reading:
self.kernel_client.input(u'!' + code)
else:
self.silent_execute(code) |
Copy a variable | def copy_value(self, orig_name, new_name):
"""Copy a variable"""
code = u"get_ipython().kernel.copy_value('%s', '%s')" % (orig_name,
new_name)
if self._reading:
self.kernel_client.input(u'!' + code)
else:
... |
Handle internal spyder messages | def _handle_spyder_msg(self, msg):
"""
Handle internal spyder messages
"""
spyder_msg_type = msg['content'].get('spyder_msg_type')
if spyder_msg_type == 'data':
# Deserialize data
try:
if PY2:
value = cloudpickle.loads(m... |
Reimplemented to handle communications between Spyder
and the kernel | def _handle_execute_reply(self, msg):
"""
Reimplemented to handle communications between Spyder
and the kernel
"""
msg_id = msg['parent_header']['msg_id']
info = self._request_info['execute'].get(msg_id)
# unset reading flag, because if execute finished, raw_input... |
Reimplemented to refresh the namespacebrowser after kernel
restarts | def _handle_status(self, msg):
"""
Reimplemented to refresh the namespacebrowser after kernel
restarts
"""
state = msg['content'].get('execution_state', '')
msg_type = msg['parent_header'].get('msg_type', '')
if state == 'starting':
# This is needed to... |
Reimplement Qt method. | def closeEvent(self, event):
"""Reimplement Qt method."""
self.plugin.dockwidget.setWidget(self.plugin)
self.plugin.dockwidget.setVisible(True)
self.plugin.switch_to_plugin()
QMainWindow.closeEvent(self, event)
self.plugin.undocked_window = None |
If this is the first time the plugin is shown, perform actions to
initialize plugin position in Spyder's window layout.
Use on_first_registration to define the actions to be run
by your plugin | def initialize_plugin_in_mainwindow_layout(self):
"""
If this is the first time the plugin is shown, perform actions to
initialize plugin position in Spyder's window layout.
Use on_first_registration to define the actions to be run
by your plugin
"""
if self.get_... |
Update plugin margins | def update_margins(self):
"""Update plugin margins"""
layout = self.layout()
if self.default_margins is None:
self.default_margins = layout.getContentsMargins()
if CONF.get('main', 'use_custom_margin'):
margin = CONF.get('main', 'custom_margin')
layout... |
Update plugin title, i.e. dockwidget or window title | def update_plugin_title(self):
"""Update plugin title, i.e. dockwidget or window title"""
if self.dockwidget is not None:
win = self.dockwidget
elif self.undocked_window is not None:
win = self.undocked_window
else:
return
win.setWindowTitle(se... |
Add to parent QMainWindow as a dock widget | def create_dockwidget(self):
"""Add to parent QMainWindow as a dock widget"""
# Creating dock widget
dock = SpyderDockWidget(self.get_plugin_title(), self.main)
# Set properties
dock.setObjectName(self.__class__.__name__+"_dw")
dock.setAllowedAreas(self.ALLOWED_AREAS)
... |
Create configuration dialog box page widget | def create_configwidget(self, parent):
"""Create configuration dialog box page widget"""
if self.CONFIGWIDGET_CLASS is not None:
configwidget = self.CONFIGWIDGET_CLASS(self, parent)
configwidget.initialize()
return configwidget |
Return plugin font option.
All plugins in Spyder use a global font. This is a convenience method
in case some plugins will have a delta size based on the default size. | def get_plugin_font(self, rich_text=False):
"""
Return plugin font option.
All plugins in Spyder use a global font. This is a convenience method
in case some plugins will have a delta size based on the default size.
"""
if rich_text:
option = 'rich_font'
... |
Show message in main window's status bar | def show_message(self, message, timeout=0):
"""Show message in main window's status bar"""
self.main.statusBar().showMessage(message, timeout) |
Associate a toggle view action with each plugin | def create_toggle_view_action(self):
"""Associate a toggle view action with each plugin"""
title = self.get_plugin_title()
if self.CONF_SECTION == 'editor':
title = _('Editor')
if self.shortcut is not None:
action = create_action(self, title,
... |
Toggle view | def toggle_view(self, checked):
"""Toggle view"""
if not self.dockwidget:
return
if checked:
self.dockwidget.show()
self.dockwidget.raise_()
else:
self.dockwidget.hide() |
Close QMainWindow instance that contains this plugin. | def close_window(self):
"""Close QMainWindow instance that contains this plugin."""
if self.undocked_window is not None:
self.undocked_window.close()
self.undocked_window = None
# Oddly, these actions can appear disabled after the Dock
# action is pressed... |
Create a QMainWindow instance containing this plugin. | def create_window(self):
"""Create a QMainWindow instance containing this plugin."""
self.undocked_window = window = PluginWindow(self)
window.setAttribute(Qt.WA_DeleteOnClose)
icon = self.get_plugin_icon()
if is_text_string(icon):
icon = self.get_icon(icon)
w... |
Actions to perform when a plugin is undocked to be moved. | def on_top_level_changed(self, top_level):
"""Actions to perform when a plugin is undocked to be moved."""
if top_level:
self.undock_action.setDisabled(True)
else:
self.undock_action.setDisabled(False) |
Reimplemented Qt Method to avoid removing the header. | def keyPressEvent(self, event):
"""Reimplemented Qt Method to avoid removing the header."""
event, text, key, ctrl, shift = restore_keyevent(event)
cursor_position = self.get_position('cursor')
if cursor_position < self.header_end_pos:
self.restrict_cursor_position(self.head... |
Cut text | def cut(self):
"""Cut text"""
self.truncate_selection(self.header_end_pos)
if self.has_selected_text():
CodeEditor.cut(self) |
Action to take when pressing the submit button. | def _submit_to_github(self):
"""Action to take when pressing the submit button."""
# Get reference to the main window
if self.parent() is not None:
if getattr(self.parent(), 'main', False):
# This covers the case when the dialog is attached
# to the in... |
Show traceback on its own dialog | def _show_details(self):
"""Show traceback on its own dialog"""
if self.details.isVisible():
self.details.hide()
self.details_btn.setText(_('Show details'))
else:
self.resize(570, 700)
self.details.document().setPlainText('')
self.detai... |
Activate submit_btn. | def _contents_changed(self):
"""Activate submit_btn."""
desc_chars = (len(self.input_description.toPlainText()) -
self.initial_chars)
if desc_chars < DESC_MIN_CHARS:
self.desc_chars_label.setText(
u"{} {}".format(DESC_MIN_CHARS - desc_chars,
... |
Checks if there is an unmatched brackets in the 'text'.
The brackets type can be general or specified by closing_brackets_type
(')', ']' or '}') | def unmatched_brackets_in_line(self, text, closing_brackets_type=None):
"""
Checks if there is an unmatched brackets in the 'text'.
The brackets type can be general or specified by closing_brackets_type
(')', ']' or '}')
"""
if closing_brackets_type is None:
... |
Control automatic insertation of brackets in various situations. | def _autoinsert_brackets(self, key):
"""Control automatic insertation of brackets in various situations."""
char = self.BRACKETS_CHAR[key]
pair = self.BRACKETS_PAIR[key]
line_text = self.editor.get_text('sol', 'eol')
line_to_cursor = self.editor.get_text('sol', 'cursor')
... |
---------------------------------------------------------------------------------------------
author: Kyle Hounslow
---------------------------------------------------------------------------------------------
Converts a list of single images into a list of 'montage' images of specified rows and columns.
... | def build_montages(image_list, image_shape, montage_shape):
"""
---------------------------------------------------------------------------------------------
author: Kyle Hounslow
---------------------------------------------------------------------------------------------
Converts a list of single ... |
Adjust the brightness and/or contrast of an image
:param image: OpenCV BGR image
:param contrast: Float, contrast adjustment with 0 meaning no change
:param brightness: Float, brightness adjustment with 0 meaning no change | def adjust_brightness_contrast(image, brightness=0., contrast=0.):
"""
Adjust the brightness and/or contrast of an image
:param image: OpenCV BGR image
:param contrast: Float, contrast adjustment with 0 meaning no change
:param brightness: Float, brightness adjustment with 0 meaning no change
"... |
Utility for drawing text with line breaks
:param img: Image.
:param text: Text string to be drawn.
:param org: Bottom-left corner of the first line of the text string in the image.
:param font_face: Font type. One of FONT_HERSHEY_SIMPLEX, FONT_HERSHEY_PLAIN, FONT_HERSHEY_DUPLEX,
... | def put_text(img, text, org, font_face, font_scale, color, thickness=1, line_type=8, bottom_left_origin=False):
"""Utility for drawing text with line breaks
:param img: Image.
:param text: Text string to be drawn.
:param org: Bottom-left corner of the first line of the text string in the image.
:pa... |
Utility for drawing vertically & horizontally centered text with line breaks
:param img: Image.
:param text: Text string to be drawn.
:param font_face: Font type. One of FONT_HERSHEY_SIMPLEX, FONT_HERSHEY_PLAIN, FONT_HERSHEY_DUPLEX,
FONT_HERSHEY_COMPLEX, FONT_HERSHEY_TRIPLEX, FONT... | def put_centered_text(img, text, font_face, font_scale, color, thickness=1, line_type=8):
"""Utility for drawing vertically & horizontally centered text with line breaks
:param img: Image.
:param text: Text string to be drawn.
:param font_face: Font type. One of FONT_HERSHEY_SIMPLEX, FONT_HERSHEY_PLAIN... |
function to take the corners from cv2.GoodFeaturesToTrack and return cv2.KeyPoints | def corners_to_keypoints(corners):
"""function to take the corners from cv2.GoodFeaturesToTrack and return cv2.KeyPoints"""
if corners is None:
keypoints = []
else:
keypoints = [cv2.KeyPoint(kp[0][0], kp[0][1], 1) for kp in corners]
return keypoints |
Convert a path to a file: URL. The path will be made absolute and have
quoted path parts. | def path_to_url(path):
"""
Convert a path to a file: URL. The path will be made absolute and have
quoted path parts.
"""
path = os.path.normpath(os.path.abspath(path))
url = urlparse.urljoin("file:", urllib2.pathname2url(path))
return url |
Return True if `path` is a directory containing a setup.py file. | def is_installable_dir(path):
"""Return True if `path` is a directory containing a setup.py file."""
if not os.path.isdir(path):
return False
setup_py = os.path.join(path, "setup.py")
if os.path.isfile(setup_py):
return True
return False |
Retrieve a setting value. | def setting(self, setting_name, default=None): # type: (str) -> Any
"""
Retrieve a setting value.
"""
keys = setting_name.split(".")
config = self._content
for key in keys:
if key not in config:
return default
config = config[key... |
Returns a list of requirements for building, as strings | def get_requires_for_build_wheel(config_settings=None):
"""
Returns a list of requirements for building, as strings
"""
poetry = Poetry.create(".")
main, _ = SdistBuilder.convert_dependencies(poetry.package, poetry.package.requires)
return main |
Builds a wheel, places it in wheel_directory | def build_wheel(wheel_directory, config_settings=None, metadata_directory=None):
"""Builds a wheel, places it in wheel_directory"""
poetry = Poetry.create(".")
return unicode(
WheelBuilder.make_in(
poetry, SystemEnv(Path(sys.prefix)), NullIO(), Path(wheel_directory)
)
) |
Builds an sdist, places it in sdist_directory | def build_sdist(sdist_directory, config_settings=None):
"""Builds an sdist, places it in sdist_directory"""
poetry = Poetry.create(".")
path = SdistBuilder(poetry, SystemEnv(Path(sys.prefix)), NullIO()).build(
Path(sdist_directory)
)
return unicode(path.name) |
Returns all external incompatibilities in this incompatibility's
derivation graph. | def external_incompatibilities(self): # type: () -> Generator[Incompatibility]
"""
Returns all external incompatibilities in this incompatibility's
derivation graph.
"""
if isinstance(self._cause, ConflictCause):
cause = self._cause # type: ConflictCause
... |
Adds an assignment of package as a decision
and increments the decision level. | def decide(self, package): # type: (Package) -> None
"""
Adds an assignment of package as a decision
and increments the decision level.
"""
# When we make a new decision after backtracking, count an additional
# attempted solution. If we backtrack multiple times in a row... |
Adds an assignment of package as a derivation. | def derive(
self, dependency, is_positive, cause
): # type: (Dependency, bool, Incompatibility) -> None
"""
Adds an assignment of package as a derivation.
"""
self._assign(
Assignment.derivation(
dependency,
is_positive,
... |
Adds an Assignment to _assignments and _positive or _negative. | def _assign(self, assignment): # type: (Assignment) -> None
"""
Adds an Assignment to _assignments and _positive or _negative.
"""
self._assignments.append(assignment)
self._register(assignment) |
Resets the current decision level to decision_level, and removes all
assignments made after that level. | def backtrack(self, decision_level): # type: (int) -> None
"""
Resets the current decision level to decision_level, and removes all
assignments made after that level.
"""
self._backtracking = True
packages = set()
while self._assignments[-1].decision_level > dec... |
Registers an Assignment in _positive or _negative. | def _register(self, assignment): # type: (Assignment) -> None
"""
Registers an Assignment in _positive or _negative.
"""
name = assignment.dependency.name
old_positive = self._positive.get(name)
if old_positive is not None:
self._positive[name] = old_positive... |
Returns the first Assignment in this solution such that the sublist of
assignments up to and including that entry collectively satisfies term. | def satisfier(self, term): # type: (Term) -> Assignment
"""
Returns the first Assignment in this solution such that the sublist of
assignments up to and including that entry collectively satisfies term.
"""
assigned_term = None # type: Term
for assignment in self._assi... |
Checks the validity of a configuration | def check(cls, config, strict=False): # type: (dict, bool) -> Dict[str, List[str]]
"""
Checks the validity of a configuration
"""
result = {"errors": [], "warnings": []}
# Schema validation errors
validation_errors = validate_object(config, "poetry-schema")
resu... |
Discover subpackages and data.
It also retrieves necessary files. | def find_packages(self, include):
"""
Discover subpackages and data.
It also retrieves necessary files.
"""
pkgdir = None
if include.source is not None:
pkgdir = str(include.base)
base = str(include.elements[0].parent)
pkg_name = include.pac... |
Clean metadata from a TarInfo object to make it more reproducible.
- Set uid & gid to 0
- Set uname and gname to ""
- Normalise permissions to 644 or 755
- Set mtime if not None | def clean_tarinfo(cls, tar_info):
"""
Clean metadata from a TarInfo object to make it more reproducible.
- Set uid & gid to 0
- Set uname and gname to ""
- Normalise permissions to 644 or 755
- Set mtime if not None
"""
ti = copy(tar_info)... |
Retrieve the current shell. | def get(cls): # type: () -> Shell
"""
Retrieve the current shell.
"""
if cls._shell is not None:
return cls._shell
try:
name, path = detect_shell(os.getpid())
except (RuntimeError, ShellDetectionFailure):
raise RuntimeError("Unable to... |
Search for the specifications that match the given dependency.
The specifications in the returned list will be considered in reverse
order, so the latest version ought to be last. | def search_for(self, dependency): # type: (Dependency) -> List[Package]
"""
Search for the specifications that match the given dependency.
The specifications in the returned list will be considered in reverse
order, so the latest version ought to be last.
"""
if depende... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.