_id
stringlengths 2
7
| title
stringlengths 1
88
| partition
stringclasses 3
values | text
stringlengths 75
19.8k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q24100
|
make_function
|
train
|
def make_function(function, name, arity):
"""Make a function node, a representation of a mathematical relationship.
This factory function creates a function node, one of the core nodes in any
program. The resulting object is able to be called with NumPy vectorized
arguments and return a resulting vector based on a mathematical
relationship.
Parameters
----------
function : callable
A function with signature `function(x1, *args)` that returns a Numpy
array of the same shape as its arguments.
name : str
The name for the function as it should be represented in the program
and its visualizations.
arity : int
The number of arguments that the `function` takes.
"""
if not isinstance(arity, int):
raise ValueError('arity must be an int, got %s' % type(arity))
if not isinstance(function, np.ufunc):
if function.__code__.co_argcount != arity:
raise ValueError('arity %d does not match required number of '
'function arguments of %d.'
% (arity, function.__code__.co_argcount))
if not isinstance(name, str):
raise ValueError('name must be a string, got %s' % type(name))
# Check output shape
args = [np.ones(10) for _ in range(arity)]
try:
function(*args)
except ValueError:
raise ValueError('supplied function %s does not support arity of %d.'
% (name, arity))
if not hasattr(function(*args), 'shape'):
raise ValueError('supplied function %s does not return a numpy array.'
% name)
if function(*args).shape != (10,):
raise ValueError('supplied function %s does not return same shape as '
'input vectors.' % name)
# Check closure for zero & negative input arguments
args = [np.zeros(10) for _ in range(arity)]
if not np.all(np.isfinite(function(*args))):
raise ValueError('supplied function %s does not have closure against '
'zeros in argument vectors.' % name)
args = [-1 * np.ones(10) for _ in range(arity)]
if not np.all(np.isfinite(function(*args))):
raise ValueError('supplied function %s does not have closure against '
'negatives in argument vectors.' % name)
return _Function(function, name, arity)
|
python
|
{
"resource": ""
}
|
q24101
|
_generate_segments
|
train
|
def _generate_segments(im_orig, scale, sigma, min_size):
"""
segment smallest regions by the algorithm of Felzenswalb and
Huttenlocher
"""
# open the Image
im_mask = skimage.segmentation.felzenszwalb(
skimage.util.img_as_float(im_orig), scale=scale, sigma=sigma,
min_size=min_size)
# merge mask channel to the image as a 4th channel
im_orig = numpy.append(
im_orig, numpy.zeros(im_orig.shape[:2])[:, :, numpy.newaxis], axis=2)
im_orig[:, :, 3] = im_mask
return im_orig
|
python
|
{
"resource": ""
}
|
q24102
|
_sim_colour
|
train
|
def _sim_colour(r1, r2):
"""
calculate the sum of histogram intersection of colour
"""
return sum([min(a, b) for a, b in zip(r1["hist_c"], r2["hist_c"])])
|
python
|
{
"resource": ""
}
|
q24103
|
_sim_texture
|
train
|
def _sim_texture(r1, r2):
"""
calculate the sum of histogram intersection of texture
"""
return sum([min(a, b) for a, b in zip(r1["hist_t"], r2["hist_t"])])
|
python
|
{
"resource": ""
}
|
q24104
|
_sim_fill
|
train
|
def _sim_fill(r1, r2, imsize):
"""
calculate the fill similarity over the image
"""
bbsize = (
(max(r1["max_x"], r2["max_x"]) - min(r1["min_x"], r2["min_x"]))
* (max(r1["max_y"], r2["max_y"]) - min(r1["min_y"], r2["min_y"]))
)
return 1.0 - (bbsize - r1["size"] - r2["size"]) / imsize
|
python
|
{
"resource": ""
}
|
q24105
|
_calc_colour_hist
|
train
|
def _calc_colour_hist(img):
"""
calculate colour histogram for each region
the size of output histogram will be BINS * COLOUR_CHANNELS(3)
number of bins is 25 as same as [uijlings_ijcv2013_draft.pdf]
extract HSV
"""
BINS = 25
hist = numpy.array([])
for colour_channel in (0, 1, 2):
# extracting one colour channel
c = img[:, colour_channel]
# calculate histogram for each colour and join to the result
hist = numpy.concatenate(
[hist] + [numpy.histogram(c, BINS, (0.0, 255.0))[0]])
# L1 normalize
hist = hist / len(img)
return hist
|
python
|
{
"resource": ""
}
|
q24106
|
_calc_texture_gradient
|
train
|
def _calc_texture_gradient(img):
"""
calculate texture gradient for entire image
The original SelectiveSearch algorithm proposed Gaussian derivative
for 8 orientations, but we use LBP instead.
output will be [height(*)][width(*)]
"""
ret = numpy.zeros((img.shape[0], img.shape[1], img.shape[2]))
for colour_channel in (0, 1, 2):
ret[:, :, colour_channel] = skimage.feature.local_binary_pattern(
img[:, :, colour_channel], 8, 1.0)
return ret
|
python
|
{
"resource": ""
}
|
q24107
|
_calc_texture_hist
|
train
|
def _calc_texture_hist(img):
"""
calculate texture histogram for each region
calculate the histogram of gradient for each colours
the size of output histogram will be
BINS * ORIENTATIONS * COLOUR_CHANNELS(3)
"""
BINS = 10
hist = numpy.array([])
for colour_channel in (0, 1, 2):
# mask by the colour channel
fd = img[:, colour_channel]
# calculate histogram for each orientation and concatenate them all
# and join to the result
hist = numpy.concatenate(
[hist] + [numpy.histogram(fd, BINS, (0.0, 1.0))[0]])
# L1 Normalize
hist = hist / len(img)
return hist
|
python
|
{
"resource": ""
}
|
q24108
|
Scene.reset
|
train
|
def reset(self, old_scene=None, screen=None):
"""
Reset the scene ready for playing.
:param old_scene: The previous version of this Scene that was running before the
application reset - e.g. due to a screen resize.
:param screen: New screen to use if old_scene is not None.
"""
# Always reset all the effects.
for effect in self._effects:
effect.reset()
# If we have an old Scene to recreate, get the data out of that and
# apply it where possible by cloning objects where appropriate.
if old_scene:
for old_effect in old_scene.effects:
# Using the "easier to ask forgiveness..." mantra, just try
# cloning everything and ignore any AttributeErrors.
try:
old_effect.clone(screen, self)
except AttributeError:
pass
|
python
|
{
"resource": ""
}
|
q24109
|
Scene.add_effect
|
train
|
def add_effect(self, effect, reset=True):
"""
Add an effect to the Scene.
This method can be called at any time - even when playing the Scene. The default logic
assumes that the Effect needs to be reset before being displayed. This can be overridden
using the `reset` parameter.
:param effect: The Effect to be added.
:param reset: Whether to reset the Effect that has just been added.
"""
# Reset the effect in case this is in the middle of a Scene.
if reset:
effect.reset()
effect.register_scene(self)
self._effects.append(effect)
|
python
|
{
"resource": ""
}
|
q24110
|
Scene.process_event
|
train
|
def process_event(self, event):
"""
Process a new input event.
This method will pass the event on to any Effects in reverse Z order so that the
top-most Effect has priority.
:param event: The Event that has been triggered.
:returns: None if the Scene processed the event, else the original event.
"""
for effect in reversed(self._effects):
event = effect.process_event(event)
if event is None:
break
return event
|
python
|
{
"resource": ""
}
|
q24111
|
_spline
|
train
|
def _spline(t, p0, p1, p2, p3):
"""
Catmull-Rom cubic spline to interpolate 4 given points.
:param t: Time index through the spline (must be 0-1).
:param p0: The previous point in the curve (for continuity).
:param p1: The first point to interpolate.
:param p2: The second point to interpolate.
:param p3: The last point to interpolate.
"""
return (
t * ((2 - t) * t - 1) * p0 +
(t * t * (3 * t - 5) + 2) * p1 +
t * ((4 - 3 * t) * t + 1) * p2 +
(t - 1) * t * t * p3) / 2
|
python
|
{
"resource": ""
}
|
q24112
|
Path._add_step
|
train
|
def _add_step(self, pos):
"""
Add a step to the end of the current recorded path.
:param pos: The position tuple (x, y) to add to the list.
"""
self._steps.append(pos)
self._rec_x = pos[0]
self._rec_y = pos[1]
|
python
|
{
"resource": ""
}
|
q24113
|
Path.wait
|
train
|
def wait(self, delay):
"""
Wait at the current location for the specified number of iterations.
:param delay: The time to wait (in animation frames).
"""
for _ in range(0, delay):
self._add_step((self._rec_x, self._rec_y))
|
python
|
{
"resource": ""
}
|
q24114
|
Path.move_straight_to
|
train
|
def move_straight_to(self, x, y, steps):
"""
Move straight to the newly specified location - i.e. create a straight
line Path from the current location to the specified point.
:param x: X coord for the end position.
:param y: Y coord for the end position.
:param steps: How many steps to take for the move.
"""
start_x = self._rec_x
start_y = self._rec_y
for i in range(1, steps + 1):
self._add_step((
int(start_x + (x - start_x) / float(steps) * i),
int(start_y + (y - start_y) / float(steps) * i)))
|
python
|
{
"resource": ""
}
|
q24115
|
Path.move_round_to
|
train
|
def move_round_to(self, points, steps):
"""
Follow a path pre-defined by a set of at least 4 points. This Path will
interpolate the points into a curve and follow that curve.
:param points: The list of points that defines the path.
:param steps: The number of steps to take to follow the path.
"""
# Spline interpolation needs a before and after point for the curve.
# Duplicate the first and last points to handle this. We also need
# to move from the current position to the first specified point.
points.insert(0, (self._rec_x, self._rec_y))
points.insert(0, (self._rec_x, self._rec_y))
points.append(points[-1])
# Convert the points into an interpolated set of more detailed points.
steps_per_spline = steps // (len(points) - 3)
for j in range(1, len(points) - 2):
for t in range(1, steps_per_spline + 1):
y = _spline(float(t) / steps_per_spline,
float(points[j - 1][1]),
float(points[j][1]),
float(points[j + 1][1]),
float(points[j + 2][1]))
x = int(points[j][0] + ((points[j + 1][0] - points[j][0]) *
float(t) / steps_per_spline))
self._add_step((x, int(y)))
|
python
|
{
"resource": ""
}
|
q24116
|
DynamicPath.reset
|
train
|
def reset(self):
"""
Reset the Path for use next time.
"""
self._x = self._start_x
self._y = self._start_y
|
python
|
{
"resource": ""
}
|
q24117
|
_enforce_width
|
train
|
def _enforce_width(text, width, unicode_aware=True):
"""
Enforce a displayed piece of text to be a certain number of cells wide. This takes into
account double-width characters used in CJK languages.
:param text: The text to be truncated
:param width: The screen cell width to enforce
:return: The resulting truncated text
"""
# Double-width strings cannot be more than twice the string length, so no need to try
# expensive truncation if this upper bound isn't an issue.
if 2 * len(text) < width:
return text
# Can still optimize performance if we are not handling unicode characters.
if unicode_aware:
size = 0
for i, c in enumerate(text):
w = wcwidth(c) if ord(c) >= 256 else 1
if size + w > width:
return text[0:i]
size += w
elif len(text) + 1 > width:
return text[0:width]
return text
|
python
|
{
"resource": ""
}
|
q24118
|
_find_min_start
|
train
|
def _find_min_start(text, max_width, unicode_aware=True, at_end=False):
"""
Find the starting point in the string that will reduce it to be less than or equal to the
specified width when displayed on screen.
:param text: The text to analyze.
:param max_width: The required maximum width
:param at_end: At the end of the editable line, so allow spaced for cursor.
:return: The offset within `text` to start at to reduce it to the required length.
"""
# Is the solution trivial? Worth optimizing for text heavy UIs...
if 2 * len(text) < max_width:
return 0
# OK - do it the hard way...
result = 0
string_len = wcswidth if unicode_aware else len
char_len = wcwidth if unicode_aware else lambda x: 1
display_end = string_len(text)
while display_end > max_width:
result += 1
display_end -= char_len(text[0])
text = text[1:]
if at_end and display_end == max_width:
result += 1
return result
|
python
|
{
"resource": ""
}
|
q24119
|
_split_text
|
train
|
def _split_text(text, width, height, unicode_aware=True):
"""
Split text to required dimensions.
This will first try to split the text into multiple lines, then put a "..." on the last
3 characters of the last line if this still doesn't fit.
:param text: The text to split.
:param width: The maximum width for any line.
:param height: The maximum height for the resulting text.
:return: A list of strings of the broken up text.
"""
# At a high level, just try to split on whitespace for the best results.
tokens = text.split(" ")
result = []
current_line = ""
string_len = wcswidth if unicode_aware else len
for token in tokens:
for i, line_token in enumerate(token.split("\n")):
if string_len(current_line + line_token) > width or i > 0:
# Don't bother inserting completely blank lines - which should only happen on the very first
# line (as the rest will inject whitespace/newlines)
if len(current_line) > 0:
result.append(current_line.rstrip())
current_line = line_token + " "
else:
current_line += line_token + " "
# At this point we've either split nicely or have a hugely long unbroken string (e.g. because the
# language doesn't use whitespace. Either way, break this last line up as best we can.
current_line = current_line.rstrip()
while string_len(current_line) > 0:
new_line = _enforce_width(current_line, width, unicode_aware)
result.append(new_line)
current_line = current_line[len(new_line):]
# Check for a height overrun and truncate.
if len(result) > height:
result = result[:height]
result[height - 1] = result[height - 1][:width - 3] + "..."
# Very small columns could be shorter than individual words - truncate
# each line if necessary.
for i, line in enumerate(result):
if len(line) > width:
result[i] = line[:width - 3] + "..."
return result
|
python
|
{
"resource": ""
}
|
q24120
|
Frame.add_layout
|
train
|
def add_layout(self, layout):
"""
Add a Layout to the Frame.
:param layout: The Layout to be added.
"""
layout.register_frame(self)
self._layouts.append(layout)
|
python
|
{
"resource": ""
}
|
q24121
|
Frame.add_effect
|
train
|
def add_effect(self, effect):
"""
Add an Effect to the Frame.
:param effect: The Effect to be added.
"""
effect.register_scene(self._scene)
self._effects.append(effect)
|
python
|
{
"resource": ""
}
|
q24122
|
Frame.fix
|
train
|
def fix(self):
"""
Fix the layouts and calculate the locations of all the widgets.
This function should be called once all Layouts have been added to the Frame and all
widgets added to the Layouts.
"""
# Do up to 2 passes in case we have a variable height Layout.
fill_layout = None
fill_height = y = 0
for _ in range(2):
# Pick starting point/height - varies for borders.
if self._has_border:
x = y = start_y = 1
height = self._canvas.height - 2
width = self._canvas.width - 2
else:
x = y = start_y = 0
height = self._canvas.height
width = self._canvas.width
# Process each Layout in the Frame - getting required height for
# each.
for layout in self._layouts:
if layout.fill_frame:
if fill_layout is None:
# First pass - remember it for now.
fill_layout = layout
elif fill_layout == layout:
# Second pass - pass in max height
y = layout.fix(x, y, width, fill_height)
else:
# A second filler - this is a bug in the application.
raise Highlander("Too many Layouts filling Frame")
else:
y = layout.fix(x, y, width, height)
# If we hit a variable height Layout - figure out the available
# space and reset everything to the new values.
if fill_layout is None:
break
else:
fill_height = max(1, start_y + height - y)
# Remember the resulting height of the underlying Layouts.
self._max_height = y
# Reset text
while self._focus < len(self._layouts):
try:
self._layouts[self._focus].focus(force_first=True)
break
except IndexError:
self._focus += 1
self._clear()
|
python
|
{
"resource": ""
}
|
q24123
|
Frame._clear
|
train
|
def _clear(self):
"""
Clear the current canvas.
"""
# It's orders of magnitude faster to reset with a print like this
# instead of recreating the screen buffers.
(colour, attr, bg) = self.palette["background"]
self._canvas.clear_buffer(colour, attr, bg)
|
python
|
{
"resource": ""
}
|
q24124
|
Frame.set_theme
|
train
|
def set_theme(self, theme):
"""
Pick a palette from the list of supported THEMES.
:param theme: The name of the theme to set.
"""
if theme in THEMES:
self.palette = THEMES[theme]
if self._scroll_bar:
# TODO: fix protected access.
self._scroll_bar._palette = self.palette
|
python
|
{
"resource": ""
}
|
q24125
|
Frame.focussed_widget
|
train
|
def focussed_widget(self):
"""
The widget that currently has the focus within this Frame.
"""
# If the frame has no focus, it can't have a focussed widget.
if not self._has_focus:
return None
try:
layout = self._layouts[self._focus]
return layout._columns[layout._live_col][layout._live_widget]
except IndexError:
# If the current indexing is invalid it's because no widget is selected.
return None
|
python
|
{
"resource": ""
}
|
q24126
|
Frame.frame_update_count
|
train
|
def frame_update_count(self):
"""
The number of frames before this Effect should be updated.
"""
result = 1000000
for layout in self._layouts:
if layout.frame_update_count > 0:
result = min(result, layout.frame_update_count)
for effect in self._effects:
if effect.frame_update_count > 0:
result = min(result, effect.frame_update_count)
return result
|
python
|
{
"resource": ""
}
|
q24127
|
Frame.clone
|
train
|
def clone(self, _, scene):
"""
Create a clone of this Frame into a new Screen.
:param _: ignored.
:param scene: The new Scene object to clone into.
"""
# Assume that the application creates a new set of Frames and so we need to match up the
# data from the old object to the new (using the name).
if self._name is not None:
for effect in scene.effects:
if isinstance(effect, Frame):
if effect._name == self._name:
effect.data = self.data
for layout in self._layouts:
layout.update_widgets(new_frame=effect)
|
python
|
{
"resource": ""
}
|
q24128
|
Frame.switch_focus
|
train
|
def switch_focus(self, layout, column, widget):
"""
Switch focus to the specified widget.
:param layout: The layout that owns the widget.
:param column: The column the widget is in.
:param widget: The index of the widget to take the focus.
"""
# Find the layout to own the focus.
for i, l in enumerate(self._layouts):
if l is layout:
break
else:
# No matching layout - give up now
return
self._layouts[self._focus].blur()
self._focus = i
self._layouts[self._focus].focus(force_column=column,
force_widget=widget)
|
python
|
{
"resource": ""
}
|
q24129
|
Frame.move_to
|
train
|
def move_to(self, x, y, h):
"""
Make the specified location visible. This is typically used by a widget to scroll the
canvas such that it is visible.
:param x: The x location to make visible.
:param y: The y location to make visible.
:param h: The height of the location to make visible.
"""
if self._has_border:
start_x = 1
width = self.canvas.width - 2
start_y = self.canvas.start_line + 1
height = self.canvas.height - 2
else:
start_x = 0
width = self.canvas.width
start_y = self.canvas.start_line
height = self.canvas.height
if ((x >= start_x) and (x < start_x + width) and
(y >= start_y) and (y + h < start_y + height)):
# Already OK - quit now.
return
if y < start_y:
self.canvas.scroll_to(y - 1 if self._has_border else y)
else:
line = y + h - self.canvas.height + (1 if self._has_border else 0)
self.canvas.scroll_to(max(0, line))
|
python
|
{
"resource": ""
}
|
q24130
|
Frame.rebase_event
|
train
|
def rebase_event(self, event):
"""
Rebase the coordinates of the passed event to frame-relative coordinates.
:param event: The event to be rebased.
:returns: A new event object appropriately re-based.
"""
new_event = copy(event)
if isinstance(new_event, MouseEvent):
origin = self._canvas.origin
new_event.x -= origin[0]
new_event.y -= origin[1] - self._canvas.start_line
logger.debug("New event: %s", new_event)
return new_event
|
python
|
{
"resource": ""
}
|
q24131
|
Layout.frame_update_count
|
train
|
def frame_update_count(self):
"""
The number of frames before this Layout should be updated.
"""
result = 1000000
for column in self._columns:
for widget in column:
if widget.frame_update_count > 0:
result = min(result, widget.frame_update_count)
return result
|
python
|
{
"resource": ""
}
|
q24132
|
Layout.add_widget
|
train
|
def add_widget(self, widget, column=0):
"""
Add a widget to this Layout.
If you are adding this Widget to the Layout dynamically after starting to play the Scene,
don't forget to ensure that the value is explicitly set before the next update.
:param widget: The widget to be added.
:param column: The column within the widget for this widget. Defaults to zero.
"""
# Make sure that the Layout is fully initialised before we try to add any widgets.
if self._frame is None:
raise RuntimeError("You must add the Layout to the Frame before you can add a Widget.")
# Now process the widget.
self._columns[column].append(widget)
widget.register_frame(self._frame)
if widget.name in self._frame.data:
widget.value = self._frame.data[widget.name]
|
python
|
{
"resource": ""
}
|
q24133
|
Layout.focus
|
train
|
def focus(self, force_first=False, force_last=False, force_column=None,
force_widget=None):
"""
Call this to give this Layout the input focus.
:param force_first: Optional parameter to force focus to first widget.
:param force_last: Optional parameter to force focus to last widget.
:param force_column: Optional parameter to mandate the new column index.
:param force_widget: Optional parameter to mandate the new widget index.
The force_column and force_widget parameters must both be set together or they will
otherwise be ignored.
:raises IndexError: if a force option specifies a bad column or widget, or if the whole
Layout is readonly.
"""
self._has_focus = True
if force_widget is not None and force_column is not None:
self._live_col = force_column
self._live_widget = force_widget
elif force_first:
self._live_col = 0
self._live_widget = -1
self._find_next_widget(1)
elif force_last:
self._live_col = len(self._columns) - 1
self._live_widget = len(self._columns[self._live_col])
self._find_next_widget(-1)
self._columns[self._live_col][self._live_widget].focus()
|
python
|
{
"resource": ""
}
|
q24134
|
Layout.blur
|
train
|
def blur(self):
"""
Call this to take the input focus from this Layout.
"""
self._has_focus = False
try:
self._columns[self._live_col][self._live_widget].blur()
except IndexError:
# don't worry if there are no active widgets in the Layout
pass
|
python
|
{
"resource": ""
}
|
q24135
|
Layout.fix
|
train
|
def fix(self, start_x, start_y, max_width, max_height):
"""
Fix the location and size of all the Widgets in this Layout.
:param start_x: The start column for the Layout.
:param start_y: The start line for the Layout.
:param max_width: Max width to allow this layout.
:param max_height: Max height to allow this layout.
:returns: The next line to be used for any further Layouts.
"""
x = start_x
width = max_width
y = w = 0
max_y = start_y
string_len = wcswidth if self._frame.canvas.unicode_aware else len
dimensions = []
for i, column in enumerate(self._columns):
# For each column determine if we need a tab offset for labels.
# Only allow labels to take up 1/3 of the column.
if len(column) > 0:
offset = max([0 if c.label is None else string_len(c.label) + 1 for c in column])
else:
offset = 0
offset = int(min(offset,
width * self._column_sizes[i] // 3))
# Start tracking new column
dimensions.append(_DotDict())
dimensions[i].parameters = []
dimensions[i].offset = offset
# Do first pass to figure out the gaps for widgets that want to fill remaining space.
fill_layout = None
fill_column = None
y = start_y
w = int(width * self._column_sizes[i])
for widget in column:
h = widget.required_height(offset, w)
if h == Widget.FILL_FRAME:
if fill_layout is None and fill_column is None:
dimensions[i].parameters.append([widget, x, w, h])
fill_layout = widget
else:
# Two filling widgets in one column - this is a bug.
raise Highlander("Too many Widgets filling Layout")
elif h == Widget.FILL_COLUMN:
if fill_layout is None and fill_column is None:
dimensions[i].parameters.append([widget, x, w, h])
fill_column = widget
else:
# Two filling widgets in one column - this is a bug.
raise Highlander("Too many Widgets filling Layout")
else:
dimensions[i].parameters.append([widget, x, w, h])
y += h
# Note space used by this column.
dimensions[i].height = y
# Update tracking variables fpr the next column.
max_y = max(max_y, y)
x += w
# Finally check whether the Layout is allowed to expand.
if self.fill_frame:
max_y = max(max_y, start_y + max_height)
# Now apply calculated sizes, updating any widgets that need to fill space.
for column in dimensions:
y = start_y
for widget, x, w, h in column.parameters:
if h == Widget.FILL_FRAME:
h = max(1, start_y + max_height - column.height)
elif h == Widget.FILL_COLUMN:
h = max_y - column.height
widget.set_layout(x, y, column.offset, w, h)
y += h
return max_y
|
python
|
{
"resource": ""
}
|
q24136
|
Layout.update
|
train
|
def update(self, frame_no):
"""
Redraw the widgets inside this Layout.
:param frame_no: The current frame to be drawn.
"""
for column in self._columns:
for widget in column:
widget.update(frame_no)
|
python
|
{
"resource": ""
}
|
q24137
|
Layout.update_widgets
|
train
|
def update_widgets(self, new_frame=None):
"""
Reset the values for any Widgets in this Layout based on the current Frame data store.
:param new_frame: optional old Frame - used when cloning scenes.
"""
for column in self._columns:
for widget in column:
# First handle the normal case - pull the default data from the current frame.
if widget.name in self._frame.data:
widget.value = self._frame.data[widget.name]
elif widget.is_tab_stop:
# Make sure every active widget is properly initialised, by calling the setter.
# This will fix up any dodgy NoneType values, but preserve any values overridden
# by other code.
widget.value = widget.value
# If an old frame was present, give the widget a chance to clone internal state
# from the previous view. If there is no clone function, ignore the error.
if new_frame:
try:
widget.clone(new_frame.find_widget(widget.name))
except AttributeError:
pass
|
python
|
{
"resource": ""
}
|
q24138
|
Layout.reset
|
train
|
def reset(self):
"""
Reset this Layout and the Widgets it contains.
"""
# Ensure that the widgets are using the right values.
self.update_widgets()
# Reset all the widgets.
for column in self._columns:
for widget in column:
widget.reset()
widget.blur()
# Find the focus for the first widget
self._live_widget = -1
self._find_next_widget(1)
|
python
|
{
"resource": ""
}
|
q24139
|
Widget.set_layout
|
train
|
def set_layout(self, x, y, offset, w, h):
"""
Set the size and position of the Widget.
This should not be called directly. It is used by the :py:obj:`.Layout` class to arrange
all widgets within the Frame.
:param x: The x position of the widget.
:param y: The y position of the widget.
:param offset: The allowed label size for the widget.
:param w: The width of the widget.
:param h: The height of the widget.
"""
self._x = x
self._y = y
self._offset = offset
self._w = w
self._h = h
|
python
|
{
"resource": ""
}
|
q24140
|
Widget.get_location
|
train
|
def get_location(self):
"""
Return the absolute location of this widget on the Screen, taking into account the
current state of the Frame that is displaying it and any label offsets of the Widget.
:returns: A tuple of the form (<X coordinate>, <Y coordinate>).
"""
origin = self._frame.canvas.origin
return (self._x + origin[0] + self._offset,
self._y + origin[1] - self._frame.canvas.start_line)
|
python
|
{
"resource": ""
}
|
q24141
|
Widget.focus
|
train
|
def focus(self):
"""
Call this to give this Widget the input focus.
"""
self._has_focus = True
self._frame.move_to(self._x, self._y, self._h)
if self._on_focus is not None:
self._on_focus()
|
python
|
{
"resource": ""
}
|
q24142
|
Widget.is_mouse_over
|
train
|
def is_mouse_over(self, event, include_label=True, width_modifier=0):
"""
Check if the specified mouse event is over this widget.
:param event: The MouseEvent to check.
:param include_label: Include space reserved for the label when checking.
:param width_modifier: Adjustement to width (e.g. for scroll bars).
:returns: True if the mouse is over the active parts of the widget.
"""
# Disabled widgets should not react to the mouse.
logger.debug("Widget: %s (%d, %d) (%d, %d)", self, self._x, self._y, self._w, self._h)
if self._is_disabled:
return False
# Check for any overlap
if self._y <= event.y < self._y + self._h:
if ((include_label and self._x <= event.x < self._x + self._w - width_modifier) or
(self._x + self._offset <= event.x < self._x + self._w - width_modifier)):
return True
return False
|
python
|
{
"resource": ""
}
|
q24143
|
Widget._draw_label
|
train
|
def _draw_label(self):
"""
Draw the label for this widget if needed.
"""
if self._label is not None:
# Break the label up as required.
if self._display_label is None:
# noinspection PyTypeChecker
self._display_label = _split_text(
self._label, self._offset, self._h, self._frame.canvas.unicode_aware)
# Draw the display label.
(colour, attr, bg) = self._frame.palette["label"]
for i, text in enumerate(self._display_label):
self._frame.canvas.paint(
text, self._x, self._y + i, colour, attr, bg)
|
python
|
{
"resource": ""
}
|
q24144
|
Widget._draw_cursor
|
train
|
def _draw_cursor(self, char, frame_no, x, y):
"""
Draw a flashing cursor for this widget.
:param char: The character to use for the cursor (when not a block)
:param frame_no: The current frame number.
:param x: The x coordinate for the cursor.
:param y: The y coordinate for the cursor.
"""
(colour, attr, bg) = self._pick_colours("edit_text")
if frame_no % 10 < 5 or self._frame.reduce_cpu:
attr |= Screen.A_REVERSE
self._frame.canvas.print_at(char, x, y, colour, attr, bg)
|
python
|
{
"resource": ""
}
|
q24145
|
TextBox._reflowed_text
|
train
|
def _reflowed_text(self):
"""
The text as should be formatted on the screen.
This is an array of tuples of the form (text, value line, value column offset) where
the line and column offsets are indeces into the value (not displayed glyph coordinates).
"""
if self._reflowed_text_cache is None:
if self._line_wrap:
self._reflowed_text_cache = []
limit = self._w - self._offset
for i, line in enumerate(self._value):
column = 0
while self.string_len(line) >= limit:
sub_string = _enforce_width(
line, limit, self._frame.canvas.unicode_aware)
self._reflowed_text_cache.append((sub_string, i, column))
line = line[len(sub_string):]
column += len(sub_string)
self._reflowed_text_cache.append((line, i, column))
else:
self._reflowed_text_cache = [(x, i, 0) for i, x in enumerate(self._value)]
return self._reflowed_text_cache
|
python
|
{
"resource": ""
}
|
q24146
|
_BaseListBox._add_or_remove_scrollbar
|
train
|
def _add_or_remove_scrollbar(self, width, height, dy):
"""
Add or remove a scrollbar from this listbox based on height and available options.
:param width: Width of the Listbox
:param height: Height of the Listbox.
:param dy: Vertical offset from top of widget.
"""
if self._scroll_bar is None and len(self._options) > height:
self._scroll_bar = _ScrollBar(
self._frame.canvas, self._frame.palette, self._x + width - 1, self._y + dy,
height, self._get_pos, self._set_pos)
elif self._scroll_bar is not None and len(self._options) <= height:
self._scroll_bar = None
|
python
|
{
"resource": ""
}
|
q24147
|
MultiColumnListBox._get_width
|
train
|
def _get_width(self, width, max_width):
"""
Helper function to figure out the actual column width from the various options.
:param width: The size of column requested
:param max_width: The maximum width allowed for this widget.
:return: the integer width of the column in characters
"""
if isinstance(width, float):
return int(max_width * width)
if width == 0:
width = (max_width - sum(self._spacing) -
sum([self._get_width(x, max_width) for x in self._columns if x != 0]))
return width
|
python
|
{
"resource": ""
}
|
q24148
|
FileBrowser._on_selection
|
train
|
def _on_selection(self):
"""
Internal function to handle directory traversal or bubble notifications up to user of the
Widget as needed.
"""
if self.value and os.path.isdir(self.value):
self._populate_list(self.value)
elif self._external_notification:
self._external_notification()
|
python
|
{
"resource": ""
}
|
q24149
|
FileBrowser._populate_list
|
train
|
def _populate_list(self, value):
"""
Populate the current multi-column list with the contents of the selected directory.
:param value: The new value to use.
"""
# Nothing to do if the value is rubbish.
if value is None:
return
# Stop any recursion - no more returns from here to end of fn please!
if self._in_update:
return
self._in_update = True
# We need to update the tree view.
self._root = os.path.abspath(value if os.path.isdir(value) else os.path.dirname(value))
# The absolute expansion of "/" or "\" is the root of the disk, so is a cross-platform
# way of spotting when to insert ".." or not.
tree_view = []
if len(self._root) > len(os.path.abspath(os.sep)):
tree_view.append((["|-+ .."], os.path.abspath(os.path.join(self._root, ".."))))
tree_dirs = []
tree_files = []
try:
files = os.listdir(self._root)
except OSError:
# Can fail on Windows due to access permissions
files = []
for my_file in files:
full_path = os.path.join(self._root, my_file)
try:
details = os.lstat(full_path)
except OSError:
# Can happen on Windows due to access permissions
details = namedtuple("stat_type", "st_size st_mtime")
details.st_size = 0
details.st_mtime = 0
name = "|-- {}".format(my_file)
tree = tree_files
if os.path.isdir(full_path):
tree = tree_dirs
if os.path.islink(full_path):
# Show links separately for directories
real_path = os.path.realpath(full_path)
name = "|-+ {} -> {}".format(my_file, real_path)
else:
name = "|-+ {}".format(my_file)
elif self._file_filter and not self._file_filter.match(my_file):
# Skip files that don't match the filter (if present)
continue
elif os.path.islink(full_path):
# Check if link target exists and if it does, show statistics of the
# linked file, otherwise just display the link
try:
real_path = os.path.realpath(full_path)
except OSError:
# Can fail on Linux prof file system.
real_path = None
if real_path and os.path.exists(real_path):
details = os.stat(real_path)
name = "|-- {} -> {}".format(my_file, real_path)
else:
# Both broken directory and file links fall to this case.
# Actually using the files will cause a FileNotFound exception
name = "|-- {} -> {}".format(my_file, real_path)
# Normalize names for MacOS and then add to the list.
tree.append(([unicodedata.normalize("NFC", name),
readable_mem(details.st_size),
readable_timestamp(details.st_mtime)], full_path))
tree_view.extend(sorted(tree_dirs))
tree_view.extend(sorted(tree_files))
self.options = tree_view
self._titles[0] = self._root
# We're out of the function - unset recursion flag.
self._in_update = False
|
python
|
{
"resource": ""
}
|
q24150
|
PopUpDialog.clone
|
train
|
def clone(self, screen, scene):
"""
Create a clone of this Dialog into a new Screen.
:param screen: The new Screen object to clone into.
:param scene: The new Scene object to clone into.
"""
# Only clone the object if the function is safe to do so.
if self._on_close is None or isfunction(self._on_close):
scene.add_effect(PopUpDialog(screen, self._text, self._buttons, self._on_close))
|
python
|
{
"resource": ""
}
|
q24151
|
_TempPopup.close
|
train
|
def close(self, cancelled=False):
"""
Close this temporary pop-up.
:param cancelled: Whether the pop-up was cancelled (e.g. by pressing Esc).
"""
self._on_close(cancelled)
self._scene.remove_effect(self)
|
python
|
{
"resource": ""
}
|
q24152
|
_ScrollBar.update
|
train
|
def update(self):
"""
Draw the scroll bar.
"""
# Sort out chars
cursor = u"█" if self._canvas.unicode_aware else "O"
back = u"░" if self._canvas.unicode_aware else "|"
# Now draw...
try:
sb_pos = self._get_pos()
sb_pos = min(1, max(0, sb_pos))
sb_pos = max(int(self._height * sb_pos) - 1, 0)
except ZeroDivisionError:
sb_pos = 0
(colour, attr, bg) = self._palette["scroll"]
y = self._canvas.start_line if self._absolute else 0
for dy in range(self._height):
self._canvas.print_at(cursor if dy == sb_pos else back,
self._x, y + self._y + dy,
colour, attr, bg)
|
python
|
{
"resource": ""
}
|
q24153
|
_ScrollBar.is_mouse_over
|
train
|
def is_mouse_over(self, event):
"""
Check whether a MouseEvent is over thus scroll bar.
:param event: The MouseEvent to check.
:returns: True if the mouse event is over the scroll bar.
"""
return event.x == self._x and self._y <= event.y < self._y + self._height
|
python
|
{
"resource": ""
}
|
q24154
|
_ScrollBar.process_event
|
train
|
def process_event(self, event):
"""
Handle input on the scroll bar.
:param event: the event to be processed.
:returns: True if the scroll bar handled the event.
"""
# Convert into absolute coordinates if needed.
new_event = event
if self._absolute:
new_event.y -= self._canvas.start_line
# Process event if needed.
if self.is_mouse_over(new_event) and event.buttons != 0:
self._set_pos((new_event.y - self._y) / (self._height - 1))
return True
return False
|
python
|
{
"resource": ""
}
|
q24155
|
StaticRenderer._convert_images
|
train
|
def _convert_images(self):
"""
Convert any images into a more Screen-friendly format.
"""
self._plain_images = []
self._colour_map = []
for image in self._images:
colour_map = []
new_image = []
for line in image.split("\n"):
new_line = ""
attributes = (None, None, None)
colours = []
while len(line) > 0:
match = self._colour_sequence.match(line)
if match is None:
new_line += line[0]
colours.append(attributes)
line = line[1:]
else:
# The regexp either matches:
# - 2,3,4 for ${c,a,b}
# - 5,6 for ${c,a}
# - 7 for ${c}.
if match.group(2) is not None:
attributes = (int(match.group(2)),
ATTRIBUTES[match.group(3)],
int(match.group(4)))
elif match.group(5) is not None:
attributes = (int(match.group(5)),
ATTRIBUTES[match.group(6)],
None)
else:
attributes = (int(match.group(7)), 0, None)
line = match.group(8)
new_image.append(new_line)
colour_map.append(colours)
self._plain_images.append(new_image)
self._colour_map.append(colour_map)
|
python
|
{
"resource": ""
}
|
q24156
|
DynamicRenderer._clear
|
train
|
def _clear(self):
"""
Clear the current image.
"""
self._plain_image = [" " * self._width for _ in range(self._height)]
self._colour_map = [[(None, 0, 0) for _ in range(self._width)]
for _ in range(self._height)]
|
python
|
{
"resource": ""
}
|
q24157
|
DynamicRenderer._write
|
train
|
def _write(self, text, x, y, colour=Screen.COLOUR_WHITE,
attr=Screen.A_NORMAL, bg=Screen.COLOUR_BLACK):
"""
Write some text to the specified location in the current image.
:param text: The text to be added.
:param x: The X coordinate in the image.
:param y: The Y coordinate in the image.
:param colour: The colour of the text to add.
:param attr: The attribute of the image.
:param bg: The background colour of the text to add.
"""
# Limit checks to ensure that we don't try to draw off the end of the arrays
if y >= self._height or x >= self._width:
return
# Limit text to draw to visible line
if len(text) + x > self._width:
text = text[:self._width - x]
# Now draw it!
self._plain_image[y] = text.join(
[self._plain_image[y][:x], self._plain_image[y][x + len(text):]])
for i, _ in enumerate(text):
self._colour_map[y][x + i] = (colour, attr, bg)
|
python
|
{
"resource": ""
}
|
q24158
|
Effect.update
|
train
|
def update(self, frame_no):
"""
Process the animation effect for the specified frame number.
:param frame_no: The index of the frame being generated.
"""
if (frame_no >= self._start_frame and
(self._stop_frame == 0 or frame_no < self._stop_frame)):
self._update(frame_no)
|
python
|
{
"resource": ""
}
|
q24159
|
_Star._respawn
|
train
|
def _respawn(self):
"""
Pick a random location for the star making sure it does
not overwrite an existing piece of text.
"""
self._cycle = randint(0, len(self._star_chars))
(height, width) = self._screen.dimensions
while True:
self._x = randint(0, width - 1)
self._y = self._screen.start_line + randint(0, height - 1)
if self._screen.get_from(self._x, self._y)[0] == 32:
break
self._old_char = " "
|
python
|
{
"resource": ""
}
|
q24160
|
_Star.update
|
train
|
def update(self):
"""
Draw the star.
"""
if not self._screen.is_visible(self._x, self._y):
self._respawn()
cur_char, _, _, _ = self._screen.get_from(self._x, self._y)
if cur_char not in (ord(self._old_char), 32):
self._respawn()
self._cycle += 1
if self._cycle >= len(self._star_chars):
self._cycle = 0
new_char = self._star_chars[self._cycle]
if new_char == self._old_char:
return
self._screen.print_at(new_char, self._x, self._y)
self._old_char = new_char
|
python
|
{
"resource": ""
}
|
q24161
|
_Trail._maybe_reseed
|
train
|
def _maybe_reseed(self, normal):
"""
Randomly create a new column once this one is finished.
"""
self._y += self._rate
self._life -= 1
if self._life <= 0:
self._clear = not self._clear if normal else True
self._rate = randint(1, 2)
if self._clear:
self._y = 0
self._life = self._screen.height // self._rate
else:
self._y = randint(0, self._screen.height // 2) - \
self._screen.height // 4
self._life = \
randint(1, self._screen.height - self._y) // self._rate
|
python
|
{
"resource": ""
}
|
q24162
|
_Trail.update
|
train
|
def update(self, reseed):
"""
Update that trail!
:param reseed: Whether we are in the normal reseed cycle or not.
"""
if self._clear:
for i in range(0, 3):
self._screen.print_at(" ",
self._x,
self._screen.start_line + self._y + i)
self._maybe_reseed(reseed)
else:
for i in range(0, 3):
self._screen.print_at(chr(randint(32, 126)),
self._x,
self._screen.start_line + self._y + i,
Screen.COLOUR_GREEN)
for i in range(4, 6):
self._screen.print_at(chr(randint(32, 126)),
self._x,
self._screen.start_line + self._y + i,
Screen.COLOUR_GREEN,
Screen.A_BOLD)
self._maybe_reseed(reseed)
|
python
|
{
"resource": ""
}
|
q24163
|
Sprite.overlaps
|
train
|
def overlaps(self, other, use_new_pos=False):
"""
Check whether this Sprite overlaps another.
:param other: The other Sprite to check for an overlap.
:param use_new_pos: Whether to use latest position (due to recent
update). Defaults to False.
:returns: True if the two Sprites overlap.
"""
(x, y) = self._path.next_pos() if use_new_pos else (self._old_x,
self._old_y)
w = self._old_width
h = self._old_height
x2, y2, w2, h2 = other.last_position()
if ((x > x2 + w2 - 1) or (x2 > x + w - 1) or
(y > y2 + h2 - 1) or (y2 > y + h - 1)):
return False
else:
return True
|
python
|
{
"resource": ""
}
|
q24164
|
_Flake._reseed
|
train
|
def _reseed(self):
"""
Randomly create a new snowflake once this one is finished.
"""
self._char = choice(self._snow_chars)
self._rate = randint(1, 3)
self._x = randint(0, self._screen.width - 1)
self._y = self._screen.start_line + randint(0, self._rate)
|
python
|
{
"resource": ""
}
|
q24165
|
_Flake.update
|
train
|
def update(self, reseed):
"""
Update that snowflake!
:param reseed: Whether we are in the normal reseed cycle or not.
"""
self._screen.print_at(" ", self._x, self._y)
cell = None
for _ in range(self._rate):
self._y += 1
cell = self._screen.get_from(self._x, self._y)
if cell is None or cell[0] != 32:
break
if ((cell is not None and cell[0] in [ord(x) for x in self._snow_chars + " "]) and
(self._y < self._screen.start_line + self._screen.height)):
self._screen.print_at(self._char,
self._x,
self._y)
else:
if self._y > self._screen.start_line + self._screen.height:
self._y = self._screen.start_line + self._screen.height
drift_index = -1
if cell:
drift_index = self._drift_chars.find(chr(cell[0]))
if 0 <= drift_index < len(self._drift_chars) - 1:
drift_char = self._drift_chars[drift_index + 1]
self._screen.print_at(drift_char, self._x, self._y)
else:
self._screen.print_at(",", self._x, self._y - 1)
if reseed:
self._reseed()
|
python
|
{
"resource": ""
}
|
q24166
|
_DoubleBuffer.clear
|
train
|
def clear(self, fg, attr, bg):
"""
Clear the double-buffer.
This does not clear the screen buffer and so the next call to deltas will still show all changes.
:param fg: The foreground colour to use for the new buffer.
:param attr: The attribute value to use for the new buffer.
:param bg: The background colour to use for the new buffer.
"""
line = [(ord(u" "), fg, attr, bg, 1) for _ in range(self._width)]
self._double_buffer = [line[:] for _ in range(self._height)]
|
python
|
{
"resource": ""
}
|
q24167
|
_DoubleBuffer.set
|
train
|
def set(self, x, y, value):
"""
Set the cell value from the specified location
:param x: The column (x coord) of the character.
:param y: The row (y coord) of the character.
:param value: A 5-tuple of (unicode, foreground, attributes, background, width).
"""
self._double_buffer[y][x] = value
|
python
|
{
"resource": ""
}
|
q24168
|
_DoubleBuffer.scroll
|
train
|
def scroll(self, lines):
"""
Scroll the window up or down.
:param lines: Number of lines to scroll. Negative numbers move the buffer up.
"""
line = [(ord(u" "), Screen.COLOUR_WHITE, 0, 0, 1) for _ in range(self._width)]
if lines > 0:
# Limit to buffer size - this will just invalidate all the data
lines = min(lines, self._height)
for y in range(0, self._height - lines):
self._double_buffer[y] = self._double_buffer[y + lines]
self._screen_buffer[y] = self._screen_buffer[y + lines]
for y in range(self._height - lines, self._height):
self._double_buffer[y] = line[:]
self._screen_buffer[y] = line[:]
else:
# Limit to buffer size - this will just invalidate all the data
lines = max(lines, -self._height)
for y in range(0, -lines):
self._double_buffer[self._height + lines + y] = line[:]
self._screen_buffer[y] = line[:]
for y in range(self._height - 1, -lines, -1):
self._double_buffer[y] = self._double_buffer[y + lines]
self._screen_buffer[y] = self._screen_buffer[y + lines]
|
python
|
{
"resource": ""
}
|
q24169
|
_DoubleBuffer.block_transfer
|
train
|
def block_transfer(self, buffer, x, y):
"""
Copy a buffer entirely to this double buffer.
:param buffer: The double buffer to copy
:param x: The X origin for where to place it in this buffer
:param y: The Y origin for where to place it in this buffer
"""
# Just copy the double-buffer cells - the real screen will sync on refresh.
block_min_x = max(0, x)
block_max_x = min(x + buffer.width, self._width)
# Check for trivial non-overlap
if block_min_x > block_max_x:
return
# Copy the available section
for by in range(0, self._height):
if y <= by < y + buffer.height:
self._double_buffer[by][block_min_x:block_max_x] = buffer.slice(
block_min_x - x, by - y, block_max_x - block_min_x)
|
python
|
{
"resource": ""
}
|
q24170
|
_DoubleBuffer.slice
|
train
|
def slice(self, x, y, width):
"""
Provide a slice of data from the buffer at the specified location
:param x: The X origin
:param y: The Y origin
:param width: The width of slice required
:return: The slice of tuples from the current double-buffer
"""
return self._double_buffer[y][x:x + width]
|
python
|
{
"resource": ""
}
|
q24171
|
_AbstractCanvas.clear_buffer
|
train
|
def clear_buffer(self, fg, attr, bg):
"""
Clear the current double-buffer used by this object.
:param fg: The foreground colour to use for the new buffer.
:param attr: The attribute value to use for the new buffer.
:param bg: The background colour to use for the new buffer.
"""
self._buffer.clear(fg, attr, bg)
|
python
|
{
"resource": ""
}
|
q24172
|
_AbstractCanvas.reset
|
train
|
def reset(self):
"""
Reset the internal buffers for the abstract canvas.
"""
# Reset our screen buffer
self._start_line = 0
self._x = self._y = None
self._buffer = _DoubleBuffer(self._buffer_height, self.width)
self._reset()
|
python
|
{
"resource": ""
}
|
q24173
|
_AbstractCanvas.scroll_to
|
train
|
def scroll_to(self, line):
"""
Scroll the abstract canvas to make a specific line.
:param line: The line to scroll to.
"""
self._buffer.scroll(line - self._start_line)
self._start_line = line
|
python
|
{
"resource": ""
}
|
q24174
|
_AbstractCanvas.get_from
|
train
|
def get_from(self, x, y):
"""
Get the character at the specified location.
:param x: The column (x coord) of the character.
:param y: The row (y coord) of the character.
:return: A 4-tuple of (ascii code, foreground, attributes, background)
for the character at the location.
"""
# Convert to buffer coordinates
y -= self._start_line
if y < 0 or y >= self._buffer_height or x < 0 or x >= self.width:
return None
cell = self._buffer.get(x, y)
return cell[0], cell[1], cell[2], cell[3]
|
python
|
{
"resource": ""
}
|
q24175
|
_AbstractCanvas.print_at
|
train
|
def print_at(self, text, x, y, colour=7, attr=0, bg=0, transparent=False):
"""
Print the text at the specified location using the specified colour and attributes.
:param text: The (single line) text to be printed.
:param x: The column (x coord) for the start of the text.
:param y: The line (y coord) for the start of the text.
:param colour: The colour of the text to be displayed.
:param attr: The cell attribute of the text to be displayed.
:param bg: The background colour of the text to be displayed.
:param transparent: Whether to print spaces or not, thus giving a
transparent effect.
The colours and attributes are the COLOUR_xxx and A_yyy constants
defined in the Screen class.
"""
# Convert to the logically visible window that our double-buffer provides
y -= self._start_line
# Trim text to the buffer vertically. Don't trim horizontally as we don't know whether any
# of these characters are dual-width yet. Handle it on the fly below...
if y < 0 or y >= self._buffer_height or x > self.width:
return
if len(text) > 0:
j = 0
for i, c in enumerate(text):
# Handle under-run and overrun of double-width glyphs now.
#
# Note that wcwidth uses significant resources, so only call when we have a
# unicode aware application. The rest of the time assume ASCII.
width = wcwidth(c) if self._unicode_aware and ord(c) >= 256 else 1
if x + i + j < 0:
x += (width - 1)
continue
if x + i + j + width > self.width:
return
# Now handle the update.
if c != " " or not transparent:
# Fix up orphaned double-width glyphs that we've just bisected.
if x + i + j - 1 >= 0 and self._buffer.get(x + i + j - 1, y)[4] == 2:
self._buffer.set(x + i + j - 1, y,
(ord("x"), 0, 0, 0, 1))
self._buffer.set(
x + i + j, y, (ord(c), colour, attr, bg, width))
if width == 2:
j += 1
if x + i + j < self.width:
self._buffer.set(
x + i + j, y, (ord(c), colour, attr, bg, 0))
# Now fix up any glyphs we may have bisected the other way.
if x + i + j + 1 < self.width and self._buffer.get(x + i + j + 1, y)[4] == 0:
self._buffer.set(x + i + j + 1, y,
(ord("x"), 0, 0, 0, 1))
|
python
|
{
"resource": ""
}
|
q24176
|
_AbstractCanvas.block_transfer
|
train
|
def block_transfer(self, buffer, x, y):
"""
Copy a buffer to the screen double buffer at a specified location.
:param buffer: The double buffer to copy
:param x: The X origin for where to place it in the Screen
:param y: The Y origin for where to place it in the Screen
"""
self._buffer.block_transfer(buffer, x, y)
|
python
|
{
"resource": ""
}
|
q24177
|
_AbstractCanvas.paint
|
train
|
def paint(self, text, x, y, colour=7, attr=0, bg=0, transparent=False,
colour_map=None):
"""
Paint multi-colour text at the defined location.
:param text: The (single line) text to be printed.
:param x: The column (x coord) for the start of the text.
:param y: The line (y coord) for the start of the text.
:param colour: The default colour of the text to be displayed.
:param attr: The default cell attribute of the text to be displayed.
:param bg: The default background colour of the text to be displayed.
:param transparent: Whether to print spaces or not, thus giving a
transparent effect.
:param colour_map: Colour/attribute list for multi-colour text.
The colours and attributes are the COLOUR_xxx and A_yyy constants
defined in the Screen class.
colour_map is a list of tuples (foreground, attribute, background) that
must be the same length as the passed in text (or None if no mapping is
required).
"""
if colour_map is None:
self.print_at(text, x, y, colour, attr, bg, transparent)
else:
offset = 0
for c, m in zip_longest(text, colour_map):
if m:
if len(m) > 0 and m[0] is not None:
colour = m[0]
if len(m) > 1 and m[1] is not None:
attr = m[1]
if len(m) > 2 and m[2] is not None:
bg = m[2]
if c:
self.print_at(c, x + offset, y, colour, attr, bg, transparent)
offset += wcwidth(c) if ord(c) >= 256 else 1
|
python
|
{
"resource": ""
}
|
q24178
|
_AbstractCanvas._blend
|
train
|
def _blend(self, new, old, ratio):
"""
Blend the new colour with the old according to the ratio.
:param new: The new colour (or None if not required).
:param old: The old colour.
:param ratio: The ratio to blend new and old
:returns: the new colour index to use for the required blend.
"""
# Don't bother blending if none is required.
if new is None:
return old
# Check colour blend cache for a quick answer.
key = (min(new, old), max(new, old))
if key in self._blends:
return self._blends[key]
# No quick answer - do it the long way... First lookup the RGB values
# for both colours and blend.
(r1, g1, b1) = self.palette[new * 3:new * 3 + 3]
(r2, g2, b2) = self.palette[old * 3:old * 3 + 3]
# Helper function to blend RGB values.
def f(c1, c2):
return ((c1 * ratio) + (c2 * (100 - ratio))) // 100
r = f(r1, r2)
g = f(g1, g2)
b = f(b1, b2)
# Now do the reverse lookup...
nearest = (256 ** 2) * 3
match = 0
for c in range(self.colours):
(rc, gc, bc) = self.palette[c * 3:c * 3 + 3]
diff = sqrt(((rc - r) * 0.3) ** 2 + ((gc - g) * 0.59) ** 2 +
((bc - b) * 0.11) ** 2)
if diff < nearest:
nearest = diff
match = c
# Save off the answer and return it
self._blends[key] = match
return match
|
python
|
{
"resource": ""
}
|
q24179
|
_AbstractCanvas.highlight
|
train
|
def highlight(self, x, y, w, h, fg=None, bg=None, blend=100):
"""
Highlight a specified section of the screen.
:param x: The column (x coord) for the start of the highlight.
:param y: The line (y coord) for the start of the highlight.
:param w: The width of the highlight (in characters).
:param h: The height of the highlight (in characters).
:param fg: The foreground colour of the highlight.
:param bg: The background colour of the highlight.
:param blend: How much (as a percentage) to take of the new colour
when blending.
The colours and attributes are the COLOUR_xxx and A_yyy constants
defined in the Screen class. If fg or bg are None that means don't
change the foreground/background as appropriate.
"""
# Convert to buffer coordinates
y -= self._start_line
for i in range(w):
if x + i >= self.width or x + i < 0:
continue
for j in range(h):
if y + j >= self._buffer_height or y + j < 0:
continue
old = self._buffer.get(x + i, y + j)
new_bg = self._blend(bg, old[3], blend)
new_fg = self._blend(fg, old[1], blend)
self._buffer.set(x + i, y + j, (old[0], new_fg, old[2], new_bg, old[4]))
|
python
|
{
"resource": ""
}
|
q24180
|
_AbstractCanvas.is_visible
|
train
|
def is_visible(self, x, y):
"""
Return whether the specified location is on the visible screen.
:param x: The column (x coord) for the location to check.
:param y: The line (y coord) for the location to check.
"""
return ((x >= 0) and
(x <= self.width) and
(y >= self._start_line) and
(y < self._start_line + self.height))
|
python
|
{
"resource": ""
}
|
q24181
|
_AbstractCanvas.move
|
train
|
def move(self, x, y):
"""
Move the drawing cursor to the specified position.
:param x: The column (x coord) for the location to check.
:param y: The line (y coord) for the location to check.
"""
self._x = int(round(x * 2, 0))
self._y = int(round(y * 2, 0))
|
python
|
{
"resource": ""
}
|
q24182
|
Canvas.refresh
|
train
|
def refresh(self):
"""
Flush the canvas content to the underlying screen.
"""
self._screen.block_transfer(self._buffer, self._dx, self._dy)
|
python
|
{
"resource": ""
}
|
q24183
|
Screen.wrapper
|
train
|
def wrapper(cls, func, height=None, catch_interrupt=False, arguments=None,
unicode_aware=None):
"""
Construct a new Screen for any platform. This will initialize the
Screen, call the specified function and then tidy up the system as
required when the function exits.
:param func: The function to call once the Screen has been created.
:param height: The buffer height for this Screen (only for test purposes).
:param catch_interrupt: Whether to catch and prevent keyboard
interrupts. Defaults to False to maintain backwards compatibility.
:param arguments: Optional arguments list to pass to func (after the
Screen object).
:param unicode_aware: Whether the application can use unicode or not.
If None, try to detect from the environment if UTF-8 is enabled.
"""
screen = Screen.open(height,
catch_interrupt=catch_interrupt,
unicode_aware=unicode_aware)
restore = True
try:
try:
if arguments:
return func(screen, *arguments)
else:
return func(screen)
except ResizeScreenError:
restore = False
raise
finally:
screen.close(restore)
|
python
|
{
"resource": ""
}
|
q24184
|
Screen._reset
|
train
|
def _reset(self):
"""
Reset the Screen.
"""
self._last_start_line = 0
self._colour = None
self._attr = None
self._bg = None
self._cur_x = None
self._cur_y = None
|
python
|
{
"resource": ""
}
|
q24185
|
Screen.refresh
|
train
|
def refresh(self):
"""
Refresh the screen.
"""
# Scroll the screen now - we've already sorted the double-buffer to reflect this change.
if self._last_start_line != self._start_line:
self._scroll(self._start_line - self._last_start_line)
self._last_start_line = self._start_line
# Now draw any deltas to the scrolled screen. Note that CJK character sets sometimes
# use double-width characters, so don't try to draw the next 2nd char (of 0 width).
for y, x in self._buffer.deltas(0, self.height):
new_cell = self._buffer.get(x, y)
if new_cell[4] > 0:
self._change_colours(new_cell[1], new_cell[2], new_cell[3])
self._print_at(chr(new_cell[0]), x, y, new_cell[4])
# Resynch for next refresh.
self._buffer.sync()
|
python
|
{
"resource": ""
}
|
q24186
|
Screen.clear
|
train
|
def clear(self):
"""
Clear the Screen of all content.
Note that this will instantly clear the Screen and reset all buffers to the default state,
without waiting for you to call :py:meth:`~.Screen.refresh`.
"""
# Clear the actual terminal
self.reset()
self._change_colours(Screen.COLOUR_WHITE, 0, 0)
self._clear()
|
python
|
{
"resource": ""
}
|
q24187
|
Screen._unhandled_event_default
|
train
|
def _unhandled_event_default(event):
"""
Default unhandled event handler for handling simple scene navigation.
"""
if isinstance(event, KeyboardEvent):
c = event.key_code
if c in (ord("X"), ord("x"), ord("Q"), ord("q")):
raise StopApplication("User terminated app")
if c in (ord(" "), ord("\n"), ord("\r")):
raise NextScene()
|
python
|
{
"resource": ""
}
|
q24188
|
Screen.play
|
train
|
def play(self, scenes, stop_on_resize=False, unhandled_input=None,
start_scene=None, repeat=True, allow_int=False):
"""
Play a set of scenes.
This is effectively a helper function to wrap :py:meth:`.set_scenes` and
:py:meth:`.draw_next_frame` to simplify animation for most applications.
:param scenes: a list of :py:obj:`.Scene` objects to play.
:param stop_on_resize: Whether to stop when the screen is resized.
Default is to carry on regardless - which will typically result
in an error. This is largely done for back-compatibility.
:param unhandled_input: Function to call for any input not handled
by the Scenes/Effects being played. Defaults to a function that
closes the application on "Q" or "X" being pressed.
:param start_scene: The old Scene to start from. This must have name
that matches the name of one of the Scenes passed in.
:param repeat: Whether to repeat the Scenes once it has reached the end.
Defaults to True.
:param allow_int: Allow input to interrupt frame rate delay.
:raises ResizeScreenError: if the screen is resized (and allowed by
stop_on_resize).
The unhandled input function just takes one parameter - the input
event that was not handled.
"""
# Initialise the Screen for animation.
self.set_scenes(
scenes, unhandled_input=unhandled_input, start_scene=start_scene)
# Mainline loop for animations
try:
while True:
a = time.time()
self.draw_next_frame(repeat=repeat)
if self.has_resized():
if stop_on_resize:
self._scenes[self._scene_index].exit()
raise ResizeScreenError("Screen resized",
self._scenes[self._scene_index])
b = time.time()
if b - a < 0.05:
# Just in case time has jumped (e.g. time change), ensure we only delay for 0.05s
pause = min(0.05, a + 0.05 - b)
if allow_int:
self.wait_for_input(pause)
else:
time.sleep(pause)
except StopApplication:
# Time to stop - just exit the function.
return
|
python
|
{
"resource": ""
}
|
q24189
|
Particle._default_next_char
|
train
|
def _default_next_char(particle):
"""
Default next character implementation - linear progression through
each character.
"""
return particle.chars[
(len(particle.chars) - 1) * particle.time // particle.life_time]
|
python
|
{
"resource": ""
}
|
q24190
|
Particle._default_next_colour
|
train
|
def _default_next_colour(particle):
"""
Default next colour implementation - linear progression through
each colour tuple.
"""
return particle.colours[
(len(particle.colours) - 1) * particle.time // particle.life_time]
|
python
|
{
"resource": ""
}
|
q24191
|
Particle.next
|
train
|
def next(self):
"""
The set of attributes for this particle for the next frame to be
rendered.
:returns: A tuple of (character, x, y, fg, attribute, bg)
"""
# Get next particle details
x, y = self._move(self)
colour = self._next_colour(self)
char = self._next_char(self)
self._last = char, x, y, colour[0], colour[1], colour[2]
self.time += 1
# Trigger any configured events
if self.time == 1 and self._on_create is not None:
self._on_create(self)
elif self.life_time == self.time and self._on_destroy is not None:
self._on_destroy(self)
elif self._on_each is not None:
self._on_each(self)
return self._last
|
python
|
{
"resource": ""
}
|
q24192
|
ParticleEmitter._find_colour
|
train
|
def _find_colour(particle, start_index, screen_data):
"""
Helper function to find an existing colour in the particle palette.
"""
_, fg2, attr2, bg2 = screen_data
index = start_index
for i, colours in enumerate(particle.colours):
if (fg2, attr2, bg2) == colours:
index = i
break
return index
|
python
|
{
"resource": ""
}
|
q24193
|
ParticleEmitter.update
|
train
|
def update(self):
"""
The function to draw a new frame for the particle system.
"""
# Spawn new particles if required
if self.time_left > 0:
self.time_left -= 1
for _ in range(self._count):
new_particle = self._new_particle()
if new_particle is not None:
self.particles.append(new_particle)
# Now draw them all
for particle in self.particles:
# Clear our the old particle
last = particle.last()
if last is not None:
char, x, y, fg, attr, bg = last
screen_data = self._screen.get_from(x, y)
if self._blend and screen_data:
index = self._find_colour(particle, 0, screen_data) - 1
fg, attr, bg = particle.colours[max(index, 0)]
self._screen.print_at(" ", x, y, fg, attr, bg)
if particle.time < particle.life_time:
# Draw the new one
char, x, y, fg, attr, bg = particle.next()
screen_data = self._screen.get_from(x, y)
if self._blend and screen_data:
index = self._find_colour(particle, -1, screen_data) + 1
fg, attr, bg = \
particle.colours[min(index, len(particle.colours) - 1)]
self._screen.print_at(char, x, y, fg, attr, bg)
else:
self.particles.remove(particle)
|
python
|
{
"resource": ""
}
|
q24194
|
Map._scale_coords
|
train
|
def _scale_coords(self, x, y, extent, xo, yo):
"""Convert from tile coordinates to "pixels" - i.e. text characters."""
return xo + (x * self._size * 2 / extent), yo + ((extent - y) * self._size / extent)
|
python
|
{
"resource": ""
}
|
q24195
|
Map._convert_latitude
|
train
|
def _convert_latitude(self, latitude):
"""Convert from latitude to the y position in overall map."""
return int((180 - (180 / pi * log(tan(
pi / 4 + latitude * pi / 360)))) * (2 ** self._zoom) * self._size / 360)
|
python
|
{
"resource": ""
}
|
q24196
|
Map._get_satellite_tile
|
train
|
def _get_satellite_tile(self, x_tile, y_tile, z_tile):
"""Load up a single satellite image tile."""
cache_file = "mapscache/{}.{}.{}.jpg".format(z_tile, x_tile, y_tile)
if cache_file not in self._tiles:
if not os.path.isfile(cache_file):
url = _IMAGE_URL.format(z_tile, x_tile, y_tile, _KEY)
data = requests.get(url).content
with open(cache_file, 'wb') as f:
f.write(data)
self._tiles[cache_file] = [
x_tile, y_tile, z_tile,
ColourImageFile(self._screen, cache_file, height=_START_SIZE, dither=True,
uni=self._screen.unicode_aware),
True]
if len(self._tiles) > _CACHE_SIZE:
self._tiles.popitem(False)
self._screen.force_update()
|
python
|
{
"resource": ""
}
|
q24197
|
Map._get_vector_tile
|
train
|
def _get_vector_tile(self, x_tile, y_tile, z_tile):
"""Load up a single vector tile."""
cache_file = "mapscache/{}.{}.{}.json".format(z_tile, x_tile, y_tile)
if cache_file not in self._tiles:
if os.path.isfile(cache_file):
with open(cache_file, 'rb') as f:
tile = json.loads(f.read().decode('utf-8'))
else:
url = _VECTOR_URL.format(z_tile, x_tile, y_tile, _KEY)
data = requests.get(url).content
try:
tile = mapbox_vector_tile.decode(data)
with open(cache_file, mode='w') as f:
json.dump(literal_eval(repr(tile)), f)
except DecodeError:
tile = None
if tile:
self._tiles[cache_file] = [x_tile, y_tile, z_tile, tile, False]
if len(self._tiles) > _CACHE_SIZE:
self._tiles.popitem(False)
self._screen.force_update()
|
python
|
{
"resource": ""
}
|
q24198
|
Map._get_tiles
|
train
|
def _get_tiles(self):
"""Background thread to download map tiles as required."""
while self._running:
self._updated.wait()
self._updated.clear()
# Save off current view and find the nearest tile.
satellite = self._satellite
zoom = self._zoom
size = self._size
n = 2 ** zoom
x_offset = self._convert_longitude(self._longitude)
y_offset = self._convert_latitude(self._latitude)
# Get the visible tiles around that location - getting most relevant first
for x, y, z in [(0, 0, 0), (1, 0, 0), (0, 1, 0), (-1, 0, 0), (0, -1, 0),
(0, 0, -1), (0, 0, 1),
(1, 1, 0), (1, -1, 0), (-1, -1, 0), (-1, 1, 0)]:
# Restart if we've already zoomed to another level
if self._zoom != zoom:
break
# Don't get tile if it falls off the grid
x_tile = int(x_offset // size) + x
y_tile = int(y_offset // size) + y
z_tile = zoom + z
if (x_tile < 0 or x_tile >= n or y_tile < 0 or y_tile >= n or
z_tile < 0 or z_tile > 20):
continue
# noinspection PyBroadException
try:
# Don't bother rendering if the tile is not visible
top = y_tile * size - y_offset + self._screen.height // 2
left = (x_tile * size - x_offset + self._screen.width // 4) * 2
if z == 0 and (left > self._screen.width or left + self._size * 2 < 0 or
top > self._screen.height or top + self._size < 0):
continue
if satellite:
self._get_satellite_tile(x_tile, y_tile, z_tile)
else:
self._get_vector_tile(x_tile, y_tile, z_tile)
# pylint: disable=broad-except
except Exception:
self._oops = "{} - tile loc: {} {} {}".format(
traceback.format_exc(), x_tile, y_tile, z_tile)
# Generally refresh screen after we've downloaded everything
self._screen.force_update()
|
python
|
{
"resource": ""
}
|
q24199
|
Map._get_features
|
train
|
def _get_features(self):
"""Decide which layers to render based on current zoom level and view type."""
if self._satellite:
return [("water", [], [])]
elif self._zoom <= 2:
return [
("water", [], []),
("marine_label", [], [1]),
]
elif self._zoom <= 7:
return [
("admin", [], []),
("water", [], []),
("road", ["motorway"], []),
("country_label", [], []),
("marine_label", [], [1]),
("state_label", [], []),
("place_label", [], ["city", "town"]),
]
elif self._zoom <= 10:
return [
("admin", [], []),
("water", [], []),
("road", ["motorway", "motorway_link", "trunk"], []),
("country_label", [], []),
("marine_label", [], [1]),
("state_label", [], []),
("place_label", [], ["city", "town"]),
]
else:
return [
("landuse", ["agriculture", "grass", "park"], []),
("water", [], []),
("waterway", ["river", "canal"], []),
("building", [], []),
("road",
["motorway", "motorway_link", "trunk", "primary", "secondary"]
if self._zoom <= 14 else
["motorway", "motorway_link", "trunk", "primary", "secondary", "tertiary",
"link", "street", "tunnel"],
[]),
("poi_label", [], []),
]
|
python
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.