def __init__(self,  byhour=None, interval=<NUM_LIT:1>, tz=None):

if byhour is None: byhour=list(range(<NUM_LIT>))<EOL>rule = rrulewrapper(HOURLY, byhour=byhour, interval=interval,<EOL>byminute=<NUM_LIT:0>, bysecond=<NUM_LIT:0>)<EOL>RRuleLocator.__init__(self, rule, tz)<EOL>

Mark every hour in *byhour*; *byhour* can be an int or sequence.
Default is to tick every hour: ``byhour=range(24)``

*interval* is the interval between each iteration.  For
example, if ``interval=2``, mark every second occurrence.


return <NUM_LIT:1>/<NUM_LIT><EOL>

return how many days a unit of the locator is; use for
intelligent autoscaling


def __init__(self,  byminute=None, interval=<NUM_LIT:1>, tz=None):

if byminute is None: byminute=list(range(<NUM_LIT>))<EOL>rule = rrulewrapper(MINUTELY, byminute=byminute, interval=interval,<EOL>bysecond=<NUM_LIT:0>)<EOL>RRuleLocator.__init__(self, rule, tz)<EOL>

Mark every minute in *byminute*; *byminute* can be an int or
sequence.  Default is to tick every minute: ``byminute=range(60)``

*interval* is the interval between each iteration.  For
example, if ``interval=2``, mark every second occurrence.


return <NUM_LIT:1.>/(<NUM_LIT>*<NUM_LIT>)<EOL>

Return how many days a unit of the locator is; used for
intelligent autoscaling.


def __init__(self,  bysecond=None, interval=<NUM_LIT:1>, tz=None):

if bysecond is None: bysecond=list(range(<NUM_LIT>))<EOL>rule = rrulewrapper(SECONDLY, bysecond=bysecond, interval=interval)<EOL>RRuleLocator.__init__(self, rule, tz)<EOL>

Mark every second in *bysecond*; *bysecond* can be an int or
sequence.  Default is to tick every second: ``bysecond = range(60)``

*interval* is the interval between each iteration.  For
example, if ``interval=2``, mark every second occurrence.


return <NUM_LIT:1.>/(<NUM_LIT>*<NUM_LIT>*<NUM_LIT>)<EOL>


if unit=='<STR_LIT:date>':<EOL><INDENT>majloc = AutoDateLocator()<EOL>majfmt = AutoDateFormatter(majloc)<EOL>return units.AxisInfo(<EOL>majloc = majloc,<EOL>majfmt = majfmt,<EOL>label='<STR_LIT>',<EOL>)<EOL><DEDENT>else: return None<EOL>


return '<STR_LIT:date>'<EOL>


def _process_text_args(override, fontdict=None, **kwargs):

if fontdict is not None:<EOL><INDENT>override.update(fontdict)<EOL><DEDENT>override.update(kwargs)<EOL>return override<EOL>

Return an override dict.  See :func:`~pyplot.text' docstring for info


if rotation in ('<STR_LIT>', None):<EOL><INDENT>angle = <NUM_LIT:0.><EOL><DEDENT>elif rotation == '<STR_LIT>':<EOL><INDENT>angle = <NUM_LIT><EOL><DEDENT>else:<EOL><INDENT>angle = float(rotation)<EOL><DEDENT>return angle%<NUM_LIT><EOL>

Return the text angle as float.

*rotation* may be 'horizontal', 'vertical', or a numeric value in degrees.


projected_xs = []<EOL>projected_ys = []<EOL>theta = text.get_rotation()/<NUM_LIT>*math.pi<EOL>tr = mtransforms.Affine2D().rotate(-theta)<EOL>for t, wh, x, y in text._get_layout(renderer)[<NUM_LIT:1>]:<EOL><INDENT>w, h = wh<EOL>xt1, yt1 = tr.transform_point((x, y))<EOL>xt2, yt2 = xt1+w, yt1+h<EOL>projected_xs.extend([xt1, xt2])<EOL>projected_ys.extend([yt1, yt2])<EOL><DEDENT>xt_box, yt_box = min(projected_xs), min(projected_ys)<EOL>w_box, h_box = max(projected_xs) - xt_box, max(projected_ys) - yt_box<EOL>tr = mtransforms.Affine2D().rotate(theta)<EOL>x_box, y_box = tr.transform_point((xt_box, yt_box))<EOL>return x_box, y_box, w_box, h_box<EOL>

Calculate the bounding box of the text. Unlike
:meth:`matplotlib.text.Text.get_extents` method, The bbox size of
the text before the rotation is calculated.


def __init__(self,<EOL>x=<NUM_LIT:0>, y=<NUM_LIT:0>, text='<STR_LIT>',<EOL>color=None,          <EOL>verticalalignment='<STR_LIT>',<EOL>horizontalalignment='<STR_LIT:left>',<EOL>multialignment=None,<EOL>fontproperties=None, <EOL>rotation=None,<EOL>linespacing=None,<EOL>**kwargs<EOL>):

Artist.__init__(self)<EOL>self.cached = maxdict(<NUM_LIT:5>)<EOL>self._x, self._y = x, y<EOL>if color is None: color = rcParams['<STR_LIT>']<EOL>if fontproperties is None: fontproperties=FontProperties()<EOL>elif is_string_like(fontproperties): fontproperties=FontProperties(fontproperties)<EOL>self.set_text(text)<EOL>self.set_color(color)<EOL>self._verticalalignment = verticalalignment<EOL>self._horizontalalignment = horizontalalignment<EOL>self._multialignment = multialignment<EOL>self._rotation = rotation<EOL>self._fontproperties = fontproperties<EOL>self._bbox = None<EOL>self._bbox_patch = None <EOL>self._renderer = None<EOL>if linespacing is None:<EOL><INDENT>linespacing = <NUM_LIT>   <EOL><DEDENT>self._linespacing = linespacing<EOL>self.update(kwargs)<EOL>

Create a :class:`~matplotlib.text.Text` instance at *x*, *y*
with string *text*.

Valid kwargs are
%(Text)s


if callable(self._contains): return self._contains(self,mouseevent)<EOL>if not self.get_visible() or self._renderer is None:<EOL><INDENT>return False,{}<EOL><DEDENT>l,b,w,h = self.get_window_extent().bounds<EOL>r = l+w<EOL>t = b+h<EOL>xyverts = (l,b), (l, t), (r, t), (r, b)<EOL>x, y = mouseevent.x, mouseevent.y<EOL>inside = nxutils.pnpoly(x, y, xyverts)<EOL>return inside,{}<EOL>

Test whether the mouse event occurred in the patch.

        In the case of text, a hit is true anywhere in the
        axis-aligned bounding-box containing the text.

        Returns True or False.


x, y = self.get_position()<EOL>return self.get_transform().transform_point((x,y))<EOL>

get the (possibly unit converted) transformed x, y in display coords


return get_rotation(self._rotation)<EOL>

return the text angle as float in degrees


Artist.update_from(self, other)<EOL>self._color = other._color<EOL>self._multialignment = other._multialignment<EOL>self._verticalalignment = other._verticalalignment<EOL>self._horizontalalignment = other._horizontalalignment<EOL>self._fontproperties = other._fontproperties.copy()<EOL>self._rotation = other._rotation<EOL>self._picker = other._picker<EOL>self._linespacing = other._linespacing<EOL>


<EOL>if rectprops is not None and "<STR_LIT>" in rectprops:<EOL><INDENT>props = rectprops.copy()<EOL>boxstyle = props.pop("<STR_LIT>")<EOL>bbox_transmuter = props.pop("<STR_LIT>", None)<EOL>self._bbox_patch = FancyBboxPatch((<NUM_LIT:0.>, <NUM_LIT:0.>),<EOL><NUM_LIT:1.>, <NUM_LIT:1.>,<EOL>boxstyle=boxstyle,<EOL>bbox_transmuter=bbox_transmuter,<EOL>transform=mtransforms.IdentityTransform(),<EOL>**props)<EOL>self._bbox = None<EOL><DEDENT>else:<EOL><INDENT>self._bbox_patch = None<EOL>self._bbox = rectprops<EOL><DEDENT>

Draw a bounding box around self.  rectprops are any settable
properties for a rectangle, eg facecolor='red', alpha=0.5.

  t.set_bbox(dict(facecolor='red', alpha=0.5))

If rectprops has "boxstyle" key. A FancyBboxPatch
is initialized with rectprops and will be drawn. The mutation
scale of the FancyBboxPath is set to the fontsize.

ACCEPTS: rectangle prop dict


return self._bbox_patch<EOL>

Return the bbox Patch object. Returns None if the the
FancyBboxPatch is not made.


<EOL>if not isinstance(self.arrow_patch, FancyArrowPatch):<EOL><INDENT>return<EOL><DEDENT>if self._bbox_patch:<EOL><INDENT>trans = self.get_transform()<EOL>posx = float(self.convert_xunits(self._x))<EOL>posy = float(self.convert_yunits(self._y))<EOL>posx, posy = trans.transform_point((posx, posy))<EOL>x_box, y_box, w_box, h_box = _get_textbox(self, renderer)<EOL>self._bbox_patch.set_bounds(<NUM_LIT:0.>, <NUM_LIT:0.>,<EOL>w_box, h_box)<EOL>theta = self.get_rotation()/<NUM_LIT>*math.pi<EOL>tr = mtransforms.Affine2D().rotate(theta)<EOL>tr = tr.translate(posx+x_box, posy+y_box)<EOL>self._bbox_patch.set_transform(tr)<EOL>fontsize_in_pixel = renderer.points_to_pixels(self.get_size())<EOL>self._bbox_patch.set_mutation_scale(fontsize_in_pixel)<EOL><DEDENT>else:<EOL><INDENT>props = self._bbox<EOL>if props is None: props = {}<EOL>props = props.copy() <EOL>pad = props.pop('<STR_LIT>', <NUM_LIT:4>)<EOL>pad = renderer.points_to_pixels(pad)<EOL>bbox = self.get_window_extent(renderer)<EOL>l,b,w,h = bbox.bounds<EOL>l-=pad/<NUM_LIT><EOL>b-=pad/<NUM_LIT><EOL>w+=pad<EOL>h+=pad<EOL>r = Rectangle(xy=(l,b),<EOL>width=w,<EOL>height=h,<EOL>)<EOL>r.set_transform(mtransforms.IdentityTransform())<EOL>r.set_clip_on( False )<EOL>r.update(props)<EOL>self.arrow_patch.set_patchA(r)<EOL><DEDENT>

Update the location and the size of the bbox. This method
should be used when the position and size of the bbox needs to
be updated before actually drawing the bbox.


def _draw_bbox(self, renderer, posx, posy):

x_box, y_box, w_box, h_box = _get_textbox(self, renderer)<EOL>self._bbox_patch.set_bounds(<NUM_LIT:0.>, <NUM_LIT:0.>,<EOL>w_box, h_box)<EOL>theta = self.get_rotation()/<NUM_LIT>*math.pi<EOL>tr = mtransforms.Affine2D().rotate(theta)<EOL>tr = tr.translate(posx+x_box, posy+y_box)<EOL>self._bbox_patch.set_transform(tr)<EOL>fontsize_in_pixel = renderer.points_to_pixels(self.get_size())<EOL>self._bbox_patch.set_mutation_scale(fontsize_in_pixel)<EOL>self._bbox_patch.draw(renderer)<EOL>

Update the location and the size of the bbox
        (FancyBoxPatch), and draw


if renderer is not None:<EOL><INDENT>self._renderer = renderer<EOL><DEDENT>if not self.get_visible(): return<EOL>if self._text=='<STR_LIT>': return<EOL>bbox, info = self._get_layout(renderer)<EOL>trans = self.get_transform()<EOL>posx = float(self.convert_xunits(self._x))<EOL>posy = float(self.convert_yunits(self._y))<EOL>posx, posy = trans.transform_point((posx, posy))<EOL>canvasw, canvash = renderer.get_canvas_width_height()<EOL>if self._bbox_patch:<EOL><INDENT>self._draw_bbox(renderer, posx, posy)<EOL><DEDENT>gc = renderer.new_gc()<EOL>gc.set_foreground(self._color)<EOL>gc.set_alpha(self._alpha)<EOL>gc.set_url(self._url)<EOL>if self.get_clip_on():<EOL><INDENT>gc.set_clip_rectangle(self.clipbox)<EOL><DEDENT>if self._bbox:<EOL><INDENT>bbox_artist(self, renderer, self._bbox)<EOL><DEDENT>angle = self.get_rotation()<EOL>if rcParams['<STR_LIT>']:<EOL><INDENT>for line, wh, x, y in info:<EOL><INDENT>x = x + posx<EOL>y = y + posy<EOL>if renderer.flipy():<EOL><INDENT>y = canvash-y<EOL><DEDENT>clean_line, ismath = self.is_math_text(line)<EOL>renderer.draw_tex(gc, x, y, clean_line,<EOL>self._fontproperties, angle)<EOL><DEDENT>return<EOL><DEDENT>for line, wh, x, y in info:<EOL><INDENT>x = x + posx<EOL>y = y + posy<EOL>if renderer.flipy():<EOL><INDENT>y = canvash-y<EOL><DEDENT>clean_line, ismath = self.is_math_text(line)<EOL>renderer.draw_text(gc, x, y, clean_line,<EOL>self._fontproperties, angle,<EOL>ismath=ismath)<EOL><DEDENT>

Draws the :class:`Text` object to the given *renderer*.


return self._color<EOL>


return self._fontproperties<EOL>

Return the :class:`~font_manager.FontProperties` object


return self.get_fontproperties<EOL>


return self._fontproperties.get_family()<EOL>

Return the list of font families used for font lookup


return self.get_family()<EOL>


return self._fontproperties.get_name()<EOL>


return self._fontproperties.get_style()<EOL>


return self._fontproperties.get_size_in_points()<EOL>


return self._fontproperties.get_variant()<EOL>


return self.get_variant()<EOL>


return self._fontproperties.get_weight()<EOL>


return self.get_name()<EOL>


return self.get_style()<EOL>


return self.get_size()<EOL>


return self.get_weight()<EOL>


return self._fontproperties.get_stretch()<EOL>

Get the font stretch as a string or number


return self.get_stretch()<EOL>


return self.get_horizontalalignment()<EOL>


return self._horizontalalignment<EOL>

Return the horizontal alignment as string.  Will be one of
'left', 'center' or 'right'.


x = float(self.convert_xunits(self._x))<EOL>y = float(self.convert_yunits(self._y))<EOL>return x, y<EOL>

Return the position of the text as a tuple (*x*, *y*)


x, y = self.get_position()<EOL>return (x, y, self._text, self._color,<EOL>self._verticalalignment, self._horizontalalignment,<EOL>hash(self._fontproperties), self._rotation,<EOL>self.figure.dpi, id(self._renderer),<EOL>)<EOL>

Return a hashable tuple of properties.

Not intended to be human readable, but useful for backends who
want to cache derived information about text (eg layouts) and
need to know if the text has changed.


return self._text<EOL>


return self.get_verticalalignment()<EOL>


return self._verticalalignment<EOL>

Return the vertical alignment as string.  Will be one of
'top', 'center', 'bottom' or 'baseline'.


def get_window_extent(self, renderer=None, dpi=None):

<EOL>if not self.get_visible(): return Bbox.unit()<EOL>if dpi is not None:<EOL><INDENT>dpi_orig = self.figure.dpi<EOL>self.figure.dpi = dpi<EOL><DEDENT>if self._text == '<STR_LIT>':<EOL><INDENT>tx, ty = self._get_xy_display()<EOL>return Bbox.from_bounds(tx,ty,<NUM_LIT:0>,<NUM_LIT:0>)<EOL><DEDENT>if renderer is not None:<EOL><INDENT>self._renderer = renderer<EOL><DEDENT>if self._renderer is None:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>bbox, info = self._get_layout(self._renderer)<EOL>x, y = self.get_position()<EOL>x, y = self.get_transform().transform_point((x, y))<EOL>bbox = bbox.translated(x, y)<EOL>if dpi is not None:<EOL><INDENT>self.figure.dpi = dpi_orig<EOL><DEDENT>return bbox<EOL>

Return a :class:`~matplotlib.transforms.Bbox` object bounding
the text, in display units.

In addition to being used internally, this is useful for
specifying clickable regions in a png file on a web page.

*renderer* defaults to the _renderer attribute of the text
object.  This is not assigned until the first execution of
:meth:`draw`, so you must use this kwarg if you want
to call :meth:`get_window_extent` prior to the first
:meth:`draw`.  For getting web page regions, it is
simpler to call the method after saving the figure.

*dpi* defaults to self.figure.dpi; the renderer dpi is
irrelevant.  For the web application, if figure.dpi is not
the value used when saving the figure, then the value that
was used must be specified as the *dpi* argument.


if self._bbox is None:<EOL><INDENT>self._bbox = dict(facecolor=color, edgecolor=color)<EOL><DEDENT>else:<EOL><INDENT>self._bbox.update(dict(facecolor=color))<EOL><DEDENT>

Set the background color of the text by updating the bbox.

.. seealso::
    :meth:`set_bbox`

ACCEPTS: any matplotlib color


<EOL>try:<EOL><INDENT>hash(color)<EOL><DEDENT>except TypeError:<EOL><INDENT>color = tuple(color)<EOL><DEDENT>self._color = color<EOL>

Set the foreground color of the text

ACCEPTS: any matplotlib color


self.set_horizontalalignment(align)<EOL>


legal = ('<STR_LIT>', '<STR_LIT:right>', '<STR_LIT:left>')<EOL>if align not in legal:<EOL><INDENT>raise ValueError('<STR_LIT>' % str(legal))<EOL><DEDENT>self._horizontalalignment = align<EOL>

Set the horizontal alignment to one of

ACCEPTS: [ 'center' | 'right' | 'left' ]


legal = ('<STR_LIT>', '<STR_LIT:right>', '<STR_LIT:left>')<EOL>if align not in legal:<EOL><INDENT>raise ValueError('<STR_LIT>' % str(legal))<EOL><DEDENT>self._multialignment = align<EOL>

Set the alignment for multiple lines layout.  The layout of the
bounding box of all the lines is determined bu the horizontalalignment
and verticalalignment properties, but the multiline text within that
box can be

ACCEPTS: ['left' | 'right' | 'center' ]


self._linespacing = spacing<EOL>

Set the line spacing as a multiple of the font size.
Default is 1.2.

ACCEPTS: float (multiple of font size)


self._fontproperties.set_family(fontname)<EOL>

Set the font family.  May be either a single string, or a list
of strings in decreasing priority.  Each string may be either
a real font name or a generic font class name.  If the latter,
the specific font names will be looked up in the
:file:`matplotlibrc` file.

ACCEPTS: [ FONTNAME | 'serif' | 'sans-serif' | 'cursive' | 'fantasy' | 'monospace' ]


self._fontproperties.set_variant(variant)<EOL>

Set the font variant, either 'normal' or 'small-caps'.

ACCEPTS: [ 'normal' | 'small-caps' ]


return self.set_variant(variant)<EOL>


return self.set_family(fontname)<EOL>


self._fontproperties.set_style(fontstyle)<EOL>

Set the font style.

ACCEPTS: [ 'normal' | 'italic' | 'oblique']


return self.set_style(fontstyle)<EOL>


self._fontproperties.set_size(fontsize)<EOL>

Set the font size.  May be either a size string, relative to
the default font size, or an absolute font size in points.

ACCEPTS: [ size in points | 'xx-small' | 'x-small' | 'small' | 'medium' | 'large' | 'x-large' | 'xx-large' ]


return self.set_size(fontsize)<EOL>


self._fontproperties.set_weight(weight)<EOL>

Set the font weight.

ACCEPTS: [ a numeric value in range 0-1000 | 'ultralight' | 'light' | 'normal' | 'regular' | 'book' | 'medium' | 'roman' | 'semibold' | 'demibold' | 'demi' | 'bold' | 'heavy' | 'extra bold' | 'black' ]


return self.set_weight(weight)<EOL>


self._fontproperties.set_stretch(stretch)<EOL>

Set the font stretch (horizontal condensation or expansion).

ACCEPTS: [ a numeric value in range 0-1000 | 'ultra-condensed' | 'extra-condensed' | 'condensed' | 'semi-condensed' | 'normal' | 'semi-expanded' | 'expanded' | 'extra-expanded' | 'ultra-expanded' ]


return self.set_stretch(stretch)<EOL>


self.set_x(xy[<NUM_LIT:0>])<EOL>self.set_y(xy[<NUM_LIT:1>])<EOL>

Set the (*x*, *y*) position of the text

ACCEPTS: (x,y)


self._x = x<EOL>

Set the *x* position of the text

ACCEPTS: float


self._y = y<EOL>

Set the *y* position of the text

ACCEPTS: float


self._rotation = s<EOL>

Set the rotation of the text

ACCEPTS: [ angle in degrees | 'vertical' | 'horizontal' ]


legal = ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>')<EOL>if align not in legal:<EOL><INDENT>raise ValueError('<STR_LIT>' % str(legal))<EOL><DEDENT>self._verticalalignment = align<EOL>

Set the vertical alignment

ACCEPTS: [ 'center' | 'top' | 'bottom' | 'baseline' ]


self._text = '<STR_LIT:%s>' % (s,)<EOL>

Set the text string *s*

It may contain newlines (``\\n``) or math in LaTeX syntax.

ACCEPTS: string or anything printable with '%s' conversion.


<EOL>dollar_count = s.count(r'<STR_LIT:$>') - s.count(r'<STR_LIT>')<EOL>even_dollars = (dollar_count > <NUM_LIT:0> and dollar_count % <NUM_LIT:2> == <NUM_LIT:0>)<EOL>if rcParams['<STR_LIT>']:<EOL><INDENT>return s, '<STR_LIT>'<EOL><DEDENT>if even_dollars:<EOL><INDENT>return s, True<EOL><DEDENT>else:<EOL><INDENT>return s.replace(r'<STR_LIT>', '<STR_LIT:$>'), False<EOL><DEDENT>

Returns True if the given string *s* contains any mathtext.


if is_string_like(fp):<EOL><INDENT>fp = FontProperties(fp)<EOL><DEDENT>self._fontproperties = fp.copy()<EOL>

Set the font properties that control the text.  *fp* must be a
:class:`matplotlib.font_manager.FontProperties` object.

ACCEPTS: a :class:`matplotlib.font_manager.FontProperties` instance


x = float(self.convert_xunits(self._dashx))<EOL>y = float(self.convert_yunits(self._dashy))<EOL>return x, y<EOL>

Return the position of the text as a tuple (*x*, *y*)


props = [p for p in Text.get_prop_tup(self)]<EOL>props.extend([self._x, self._y, self._dashlength, self._dashdirection, self._dashrotation, self._dashpad, self._dashpush])<EOL>return tuple(props)<EOL>

Return a hashable tuple of properties.

Not intended to be human readable, but useful for backends who
want to cache derived information about text (eg layouts) and
need to know if the text has changed.


self.update_coords(renderer)<EOL>Text.draw(self, renderer)<EOL>if self.get_dashlength() > <NUM_LIT:0.0>:<EOL><INDENT>self.dashline.draw(renderer)<EOL><DEDENT>

Draw the :class:`TextWithDash` object to the given *renderer*.


dashx, dashy = self.get_position()<EOL>dashlength = self.get_dashlength()<EOL>if dashlength == <NUM_LIT:0.0>:<EOL><INDENT>self._x, self._y = dashx, dashy<EOL>return<EOL><DEDENT>dashrotation = self.get_dashrotation()<EOL>dashdirection = self.get_dashdirection()<EOL>dashpad = self.get_dashpad()<EOL>dashpush = self.get_dashpush()<EOL>angle = get_rotation(dashrotation)<EOL>theta = np.pi*(angle/<NUM_LIT>+dashdirection-<NUM_LIT:1>)<EOL>cos_theta, sin_theta = np.cos(theta), np.sin(theta)<EOL>transform = self.get_transform()<EOL>cxy = transform.transform_point((dashx, dashy))<EOL>cd = np.array([cos_theta, sin_theta])<EOL>c1 = cxy+dashpush*cd<EOL>c2 = cxy+(dashpush+dashlength)*cd<EOL>inverse = transform.inverted()<EOL>(x1, y1) = inverse.transform_point(tuple(c1))<EOL>(x2, y2) = inverse.transform_point(tuple(c2))<EOL>self.dashline.set_data((x1, x2), (y1, y2))<EOL>we = Text.get_window_extent(self, renderer=renderer)<EOL>w, h = we.width, we.height<EOL>if sin_theta == <NUM_LIT:0.0>:<EOL><INDENT>dx = w<EOL>dy = <NUM_LIT:0.0><EOL><DEDENT>elif cos_theta == <NUM_LIT:0.0>:<EOL><INDENT>dx = <NUM_LIT:0.0><EOL>dy = h<EOL><DEDENT>else:<EOL><INDENT>tan_theta = sin_theta/cos_theta<EOL>dx = w<EOL>dy = w*tan_theta<EOL>if dy > h or dy < -h:<EOL><INDENT>dy = h<EOL>dx = h/tan_theta<EOL><DEDENT><DEDENT>cwd = np.array([dx, dy])/<NUM_LIT:2><EOL>cwd *= <NUM_LIT:1>+dashpad/np.sqrt(np.dot(cwd,cwd))<EOL>cw = c2+(dashdirection*<NUM_LIT:2>-<NUM_LIT:1>)*cwd<EOL>newx, newy = inverse.transform_point(tuple(cw))<EOL>self._x, self._y = newx, newy<EOL>we = Text.get_window_extent(self, renderer=renderer)<EOL>self._twd_window_extent = we.frozen()<EOL>self._twd_window_extent.update_from_data_xy(np.array([c1]), False)<EOL>Text.set_horizontalalignment(self, '<STR_LIT>')<EOL>Text.set_verticalalignment(self, '<STR_LIT>')<EOL>

Computes the actual *x*, *y* coordinates for text based on the
input *x*, *y* and the *dashlength*. Since the rotation is
with respect to the actual canvas's coordinates we need to map
back and forth.


self.update_coords(renderer)<EOL>if self.get_dashlength() == <NUM_LIT:0.0>:<EOL><INDENT>return Text.get_window_extent(self, renderer=renderer)<EOL><DEDENT>else:<EOL><INDENT>return self._twd_window_extent<EOL><DEDENT>

Return a :class:`~matplotlib.transforms.Bbox` object bounding
the text, in display units.

In addition to being used internally, this is useful for
specifying clickable regions in a png file on a web page.

*renderer* defaults to the _renderer attribute of the text
object.  This is not assigned until the first execution of
:meth:`draw`, so you must use this kwarg if you want
to call :meth:`get_window_extent` prior to the first
:meth:`draw`.  For getting web page regions, it is
simpler to call the method after saving the figure.


return self._dashlength<EOL>


self._dashlength = dl<EOL>

Set the length of the dash.

ACCEPTS: float (canvas units)


return self._dashdirection<EOL>

Get the direction dash.  1 is before the text and 0 is after.


self._dashdirection = dd<EOL>

Set the direction of the dash following the text.
1 is before the text and 0 is after. The default
is 0, which is what you'd want for the typical
case of ticks below and on the left of the figure.

ACCEPTS: int (1 is before, 0 is after)


if self._dashrotation == None:<EOL><INDENT>return self.get_rotation()<EOL><DEDENT>else:<EOL><INDENT>return self._dashrotation<EOL><DEDENT>

Get the rotation of the dash in degrees.


self._dashrotation = dr<EOL>

Set the rotation of the dash, in degrees

ACCEPTS: float (degrees)


return self._dashpad<EOL>

Get the extra spacing between the dash and the text, in canvas units.


self._dashpad = dp<EOL>

Set the "pad" of the TextWithDash, which is the extra spacing
between the dash and the text, in canvas units.

ACCEPTS: float (canvas units)


return self._dashpush<EOL>

Get the extra spacing between the dash and the specified text
position, in canvas units.


self._dashpush = dp<EOL>

Set the "push" of the TextWithDash, which
is the extra spacing between the beginning
of the dash and the specified position.

ACCEPTS: float (canvas units)


Set the (*x*, *y*) position of the :class:`TextWithDash`.

ACCEPTS: (x, y)


self._dashx = float(x)<EOL>

Set the *x* position of the :class:`TextWithDash`.

ACCEPTS: float


self._dashy = float(y)<EOL>

Set the *y* position of the :class:`TextWithDash`.

ACCEPTS: float


Text.set_transform(self, t)<EOL>self.dashline.set_transform(t)<EOL>

Set the :class:`matplotlib.transforms.Transform` instance used
by this artist.

ACCEPTS: a :class:`matplotlib.transforms.Transform` instance


return self.figure<EOL>

return the figure instance the artist belongs to


Text.set_figure(self, fig)<EOL>self.dashline.set_figure(fig)<EOL>

Set the figure instance the artist belong to.

ACCEPTS: a :class:`matplotlib.figure.Figure` instance


if xytext is None:<EOL><INDENT>xytext = xy<EOL><DEDENT>if textcoords is None:<EOL><INDENT>textcoords = xycoords<EOL><DEDENT>x,y = self.xytext = xytext<EOL>Text.__init__(self, x, y, s, **kwargs)<EOL>self.xy = xy<EOL>self.xycoords = xycoords<EOL>self.textcoords = textcoords<EOL>self.arrowprops = arrowprops<EOL>self.arrow = None<EOL>if arrowprops and "<STR_LIT>" in arrowprops:<EOL><INDENT>self._arrow_relpos = arrowprops.pop("<STR_LIT>", (<NUM_LIT:0.5>, <NUM_LIT:0.5>))<EOL>self.arrow_patch = FancyArrowPatch((<NUM_LIT:0>, <NUM_LIT:0>), (<NUM_LIT:1>,<NUM_LIT:1>),<EOL>**arrowprops)<EOL><DEDENT>else:<EOL><INDENT>self.arrow_patch = None<EOL><DEDENT>

Annotate the *x*, *y* point *xy* with text *s* at *x*, *y*
location *xytext*.  (If *xytext* = *None*, defaults to *xy*,
and if *textcoords* = *None*, defaults to *xycoords*).

*arrowprops*, if not *None*, is a dictionary of line properties
(see :class:`matplotlib.lines.Line2D`) for the arrow that connects
annotation to the point.

If the dictionary has a key *arrowstyle*, a FancyArrowPatch
instance is created with the given dictionary and is
drawn. Otherwise, a YAArow patch instance is created and
drawn. Valid keys for YAArow are

=========   =============================================================
Key         Description
=========   =============================================================
width       the width of the arrow in points
frac        the fraction of the arrow length occupied by the head
headwidth   the width of the base of the arrow head in points
shrink      oftentimes it is convenient to have the arrowtip
            and base a bit away from the text and point being
            annotated.  If *d* is the distance between the text and
            annotated point, shrink will shorten the arrow so the tip
            and base are shink percent of the distance *d* away from the
            endpoints.  ie, ``shrink=0.05 is 5%%``
?           any key for :class:`matplotlib.patches.polygon`
=========   =============================================================

Valid keys for FancyArrowPatch are

===============  ======================================================
Key              Description
===============  ======================================================
arrowstyle       the arrow style
connectionstyle  the connection style
relpos           default is (0.5, 0.5)
patchA           default is bounding box of the text
patchB           default is None
shrinkA          default is 2 points
shrinkB          default is 2 points
mutation_scale   default is text size (in points)
mutation_aspect  default is 1.
?                any key for :class:`matplotlib.patches.PathPatch`
===============  ======================================================

*xycoords* and *textcoords* are strings that indicate the
coordinates of *xy* and *xytext*.

=================   ===================================================
Property            Description
=================   ===================================================
'figure points'     points from the lower left corner of the figure
'figure pixels'     pixels from the lower left corner of the figure
'figure fraction'   0,0 is lower left of figure and 1,1 is upper, right
'axes points'       points from lower left corner of axes
'axes pixels'       pixels from lower left corner of axes
'axes fraction'     0,1 is lower left of axes and 1,1 is upper right
'data'              use the coordinate system of the object being
                    annotated (default)
'offset points'     Specify an offset (in points) from the *xy* value

'polar'             you can specify *theta*, *r* for the annotation,
                    even in cartesian plots.  Note that if you
                    are using a polar axes, you do not need
                    to specify polar for the coordinate
                    system since that is the native "data" coordinate
                    system.
=================   ===================================================

If a 'points' or 'pixels' option is specified, values will be
added to the bottom-left and if negative, values will be
subtracted from the top-right.  Eg::

  # 10 points to the right of the left border of the axes and
  # 5 points below the top border
  xy=(10,-5), xycoords='axes points'

Additional kwargs are Text properties:

%(Text)s


self.update_positions(renderer)<EOL>self.update_bbox_position_size(renderer)<EOL>if self.arrow is not None:<EOL><INDENT>if self.arrow.figure is None and self.figure is not None:<EOL><INDENT>self.arrow.figure = self.figure<EOL><DEDENT>self.arrow.draw(renderer)<EOL><DEDENT>if self.arrow_patch is not None:<EOL><INDENT>if self.arrow_patch.figure is None and self.figure is not None:<EOL><INDENT>self.arrow_patch.figure = self.figure<EOL><DEDENT>self.arrow_patch.draw(renderer)<EOL><DEDENT>Text.draw(self, renderer)<EOL>

Draw the :class:`Annotation` object to the given *renderer*.


<EOL>pos = fh.tell()<EOL>try:<EOL><INDENT>line = fh.readline()<EOL><DEDENT>finally:<EOL><INDENT>fh.seek(pos, <NUM_LIT:0>)<EOL><DEDENT>if not line.startswith('<STR_LIT>'):<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>

Check if the file at least looks like AFM.
If not, raise :exc:`RuntimeError`.


headerConverters = {<EOL>'<STR_LIT>': _to_float,<EOL>'<STR_LIT>': _to_str,<EOL>'<STR_LIT>': _to_str,<EOL>'<STR_LIT>': _to_str,<EOL>'<STR_LIT>': _to_str,<EOL>'<STR_LIT>': _to_float,<EOL>'<STR_LIT>': _to_bool,<EOL>'<STR_LIT>': _to_list_of_ints,<EOL>'<STR_LIT>': _to_int,<EOL>'<STR_LIT>': _to_int,<EOL>'<STR_LIT>': _to_str,<EOL>'<STR_LIT>': _to_str,<EOL>'<STR_LIT>': _to_str,<EOL>'<STR_LIT>': _to_float, <EOL>'<STR_LIT>': _to_float, <EOL>'<STR_LIT>': _to_float,<EOL>'<STR_LIT>': _to_float,<EOL>'<STR_LIT>': _to_float,<EOL>'<STR_LIT>': _to_float,<EOL>'<STR_LIT>': _to_float,<EOL>'<STR_LIT>': _to_int,<EOL>'<STR_LIT>': _to_str,<EOL>'<STR_LIT>': _to_int,<EOL>}<EOL>d = {}<EOL>while <NUM_LIT:1>:<EOL><INDENT>line = fh.readline()<EOL>if not line: break<EOL>line = line.rstrip()<EOL>if line.startswith('<STR_LIT>'): continue<EOL>lst = line.split( '<STR_LIT:U+0020>', <NUM_LIT:1> )<EOL>key = lst[<NUM_LIT:0>]<EOL>if len( lst ) == <NUM_LIT:2>:<EOL><INDENT>val = lst[<NUM_LIT:1>]<EOL><DEDENT>else:<EOL><INDENT>val = '<STR_LIT>'<EOL><DEDENT>try: d[key] = headerConverters[key](val)<EOL>except ValueError:<EOL><INDENT>print >>sys.stderr, '<STR_LIT>', key, val<EOL>continue<EOL><DEDENT>except KeyError:<EOL><INDENT>print >>sys.stderr, '<STR_LIT>' % key<EOL>continue<EOL><DEDENT>if key=='<STR_LIT>': return d<EOL><DEDENT>raise RuntimeError('<STR_LIT>')<EOL>

Reads the font metrics header (up to the char metrics) and returns
a dictionary mapping *key* to *val*.  *val* will be converted to the
appropriate python type as necessary; eg:

    * 'False'->False
    * '0'->0
    * '-168 -218 1000 898'-> [-168, -218, 1000, 898]

Dictionary keys are

  StartFontMetrics, FontName, FullName, FamilyName, Weight,
  ItalicAngle, IsFixedPitch, FontBBox, UnderlinePosition,
  UnderlineThickness, Version, Notice, EncodingScheme, CapHeight,
  XHeight, Ascender, Descender, StartCharMetrics


ascii_d = {}<EOL>name_d  = {}<EOL>while <NUM_LIT:1>:<EOL><INDENT>line = fh.readline()<EOL>if not line: break<EOL>line = line.rstrip()<EOL>if line.startswith('<STR_LIT>'): return ascii_d, name_d<EOL>vals = line.split('<STR_LIT:;>')[:<NUM_LIT:4>]<EOL>if len(vals) !=<NUM_LIT:4> : raise RuntimeError('<STR_LIT>' % line)<EOL>num = _to_int(vals[<NUM_LIT:0>].split()[<NUM_LIT:1>])<EOL>wx = _to_float(vals[<NUM_LIT:1>].split()[<NUM_LIT:1>])<EOL>name = vals[<NUM_LIT:2>].split()[<NUM_LIT:1>]<EOL>bbox = _to_list_of_ints(vals[<NUM_LIT:3>][<NUM_LIT:2>:])<EOL>if name == '<STR_LIT>':<EOL><INDENT>num = <NUM_LIT><EOL><DEDENT>if num != -<NUM_LIT:1>:<EOL><INDENT>ascii_d[num] = (wx, name, bbox)<EOL><DEDENT>name_d[name] = (wx, bbox)<EOL><DEDENT>raise RuntimeError('<STR_LIT>')<EOL>

Return a character metric dictionary.  Keys are the ASCII num of
the character, values are a (*wx*, *name*, *bbox*) tuple, where
*wx* is the character width, *name* is the postscript language
name, and *bbox* is a (*llx*, *lly*, *urx*, *ury*) tuple.

This function is incomplete per the standard, but thus far parses
all the sample afm files tried.


line = fh.readline()<EOL>if not line.startswith('<STR_LIT>'):<EOL><INDENT>raise RuntimeError('<STR_LIT>'%line)<EOL><DEDENT>d = {}<EOL>while <NUM_LIT:1>:<EOL><INDENT>line = fh.readline()<EOL>if not line: break<EOL>line = line.rstrip()<EOL>if len(line)==<NUM_LIT:0>: continue<EOL>if line.startswith('<STR_LIT>'):<EOL><INDENT>fh.readline()  <EOL>return d<EOL><DEDENT>vals = line.split()<EOL>if len(vals)!=<NUM_LIT:4> or vals[<NUM_LIT:0>]!='<STR_LIT>':<EOL><INDENT>raise RuntimeError('<STR_LIT>'%line)<EOL><DEDENT>c1, c2, val = vals[<NUM_LIT:1>], vals[<NUM_LIT:2>], _to_float(vals[<NUM_LIT:3>])<EOL>d[(c1,c2)] = val<EOL><DEDENT>raise RuntimeError('<STR_LIT>')<EOL>

Return a kern pairs dictionary; keys are (*char1*, *char2*) tuples and
values are the kern pair value.  For example, a kern pairs line like
``KPX A y -50``

will be represented as::

  d[ ('A', 'y') ] = -50


d = {}<EOL>while <NUM_LIT:1>:<EOL><INDENT>line = fh.readline()<EOL>if not line: break<EOL>line = line.rstrip()<EOL>if len(line)==<NUM_LIT:0>: continue<EOL>if line.startswith('<STR_LIT>'):<EOL><INDENT>return d<EOL><DEDENT>vals = line.split('<STR_LIT:;>')<EOL>cc = vals[<NUM_LIT:0>].split()<EOL>name, numParts = cc[<NUM_LIT:1>], _to_int(cc[<NUM_LIT:2>])<EOL>pccParts = []<EOL>for s in vals[<NUM_LIT:1>:-<NUM_LIT:1>]:<EOL><INDENT>pcc = s.split()<EOL>name, dx, dy = pcc[<NUM_LIT:1>], _to_float(pcc[<NUM_LIT:2>]), _to_float(pcc[<NUM_LIT:3>])<EOL>pccParts.append( (name, dx, dy) )<EOL><DEDENT>d[name] = pccParts<EOL><DEDENT>raise RuntimeError('<STR_LIT>')<EOL>

Return a composites dictionary.  Keys are the names of the
composites.  Values are a num parts list of composite information,
with each element being a (*name*, *dx*, *dy*) tuple.  Thus a
composites line reading:

  CC Aacute 2 ; PCC A 0 0 ; PCC acute 160 170 ;

will be represented as::

  d['Aacute'] = [ ('A', 0, 0), ('acute', 160, 170) ]


optional = {<EOL>'<STR_LIT>' : _parse_kern_pairs,<EOL>'<STR_LIT>' :  _parse_composites,<EOL>}<EOL>d = {'<STR_LIT>':{}, '<STR_LIT>':{}}<EOL>while <NUM_LIT:1>:<EOL><INDENT>line = fh.readline()<EOL>if not line: break<EOL>line = line.rstrip()<EOL>if len(line)==<NUM_LIT:0>: continue<EOL>key = line.split()[<NUM_LIT:0>]<EOL>if key in optional: d[key] = optional[key](fh)<EOL><DEDENT>l = ( d['<STR_LIT>'], d['<STR_LIT>'] )<EOL>return l<EOL>

Parse the optional fields for kern pair data and composites

return value is a (*kernDict*, *compositeDict*) which are the
return values from :func:`_parse_kern_pairs`, and
:func:`_parse_composites` if the data exists, or empty dicts
otherwise


_sanity_check(fh)<EOL>dhead =  _parse_header(fh)<EOL>dcmetrics_ascii, dcmetrics_name = _parse_char_metrics(fh)<EOL>doptional = _parse_optional(fh)<EOL>return dhead, dcmetrics_ascii, dcmetrics_name, doptional[<NUM_LIT:0>], doptional[<NUM_LIT:1>]<EOL>

Parse the Adobe Font Metics file in file handle *fh*. Return value
is a (*dhead*, *dcmetrics*, *dkernpairs*, *dcomposite*) tuple where
*dhead* is a :func:`_parse_header` dict, *dcmetrics* is a
:func:`_parse_composites` dict, *dkernpairs* is a
:func:`_parse_kern_pairs` dict (possibly {}), and *dcomposite* is a
:func:`_parse_composites` dict (possibly {})


(dhead, dcmetrics_ascii, dcmetrics_name, dkernpairs, dcomposite) =parse_afm(fh)<EOL>self._header = dhead<EOL>self._kern = dkernpairs<EOL>self._metrics = dcmetrics_ascii<EOL>self._metrics_by_name = dcmetrics_name<EOL>self._composite = dcomposite<EOL>


if not len(s): return <NUM_LIT:0>,<NUM_LIT:0><EOL>totalw = <NUM_LIT:0><EOL>namelast = None<EOL>miny = <NUM_LIT><EOL>maxy = <NUM_LIT:0><EOL>for c in s:<EOL><INDENT>if c == '<STR_LIT:\n>': continue<EOL>wx, name, bbox = self._metrics[ord(c)]<EOL>l,b,w,h = bbox<EOL>try: kp = self._kern[ (namelast, name) ]<EOL>except KeyError: kp = <NUM_LIT:0><EOL>totalw += wx + kp<EOL>thismax = b+h<EOL>if thismax>maxy: maxy = thismax<EOL>thismin = b<EOL>if thismin<miny: miny = thismin<EOL><DEDENT>return totalw, maxy-miny<EOL>

Return the string width (including kerning) and string height
as a (*w*, *h*) tuple.


if not len(s): return <NUM_LIT:0>,<NUM_LIT:0>,<NUM_LIT:0>,<NUM_LIT:0><EOL>totalw = <NUM_LIT:0><EOL>namelast = None<EOL>miny = <NUM_LIT><EOL>maxy = <NUM_LIT:0><EOL>left = <NUM_LIT:0><EOL>if not isinstance(s, unicode):<EOL><INDENT>s = s.decode()<EOL><DEDENT>for c in s:<EOL><INDENT>if c == '<STR_LIT:\n>': continue<EOL>name = uni2type1.get(ord(c), '<STR_LIT>')<EOL>try:<EOL><INDENT>wx, bbox = self._metrics_by_name[name]<EOL><DEDENT>except KeyError:<EOL><INDENT>name = '<STR_LIT>'<EOL>wx, bbox = self._metrics_by_name[name]<EOL><DEDENT>l,b,w,h = bbox<EOL>if l<left: left = l<EOL>try: kp = self._kern[ (namelast, name) ]<EOL>except KeyError: kp = <NUM_LIT:0><EOL>totalw += wx + kp<EOL>thismax = b+h<EOL>if thismax>maxy: maxy = thismax<EOL>thismin = b<EOL>if thismin<miny: miny = thismin<EOL><DEDENT>return left, miny, totalw, maxy-miny, -miny<EOL>


return self.get_str_bbox_and_descent(s)[:<NUM_LIT:4>]<EOL>


def get_name_char(self, c, isord=False):

if not isord: c=ord(c)<EOL>wx, name, bbox = self._metrics[c]<EOL>return name<EOL>

Get the name of the character, ie, ';' is 'semicolon'


def get_width_char(self, c, isord=False):

if not isord: c=ord(c)<EOL>wx, name, bbox = self._metrics[c]<EOL>return wx<EOL>

Get the width of the character from the character metric WX
field


wx, bbox = self._metrics_by_name[name]<EOL>return wx<EOL>

Get the width of the character from a type1 character name


def get_height_char(self, c, isord=False):

if not isord: c=ord(c)<EOL>wx, name, bbox = self._metrics[c]<EOL>return bbox[-<NUM_LIT:1>]<EOL>

Get the height of character *c* from the bounding box.  This
is the ink height (space is 0)


name1, name2 = self.get_name_char(c1), self.get_name_char(c2)<EOL>return self.get_kern_dist_from_name(name1, name2)<EOL>

Return the kerning pair distance (possibly 0) for chars *c1*
and *c2*


def get_kern_dist_from_name(self, name1, name2):

try: return self._kern[ (name1, name2) ]<EOL>except: return <NUM_LIT:0><EOL>

Return the kerning pair distance (possibly 0) for chars
*name1* and *name2*


return self._header['<STR_LIT>']<EOL>


name = self._header.get('<STR_LIT>')<EOL>if name is None: <EOL><INDENT>name = self._header['<STR_LIT>']<EOL><DEDENT>return name<EOL>

Return the font full name, eg, 'Times-Roman


name = self._header.get('<STR_LIT>')<EOL>if name is not None:<EOL><INDENT>return name<EOL><DEDENT>name = self.get_fullname()<EOL>extras = r'<STR_LIT>'<EOL>return re.sub(extras, '<STR_LIT>', name)<EOL>


return self._header['<STR_LIT>']<EOL>

Return the font weight, eg, 'Bold' or 'Roman


return self._header.get('<STR_LIT>', None)<EOL>

Return the standard horizontal stem width as float, or *None* if
not specified in AFM file.


Return the standard vertical stem width as float, or *None* if
not specified in AFM file.


"""<STR_LIT>"""<EOL>fontsize = kwargs.get('<STR_LIT>', None)<EOL>inline = kwargs.get('<STR_LIT>', <NUM_LIT:1>)<EOL>inline_spacing = kwargs.get('<STR_LIT>', <NUM_LIT:5>)<EOL>self.labelFmt = kwargs.get('<STR_LIT>', '<STR_LIT>')<EOL>_colors = kwargs.get('<STR_LIT>', None)<EOL>self.labelManual=kwargs.get('<STR_LIT>',False)<EOL>if len(args) == <NUM_LIT:0>:<EOL><INDENT>levels = self.levels<EOL>indices = list(range(len(self.levels)))<EOL><DEDENT>elif len(args) == <NUM_LIT:1>:<EOL><INDENT>levlabs = list(args[<NUM_LIT:0>])<EOL>indices, levels = [], []<EOL>for i, lev in enumerate(self.levels):<EOL><INDENT>if lev in levlabs:<EOL><INDENT>indices.append(i)<EOL>levels.append(lev)<EOL><DEDENT><DEDENT>if len(levels) < len(levlabs):<EOL><INDENT>msg = "<STR_LIT>" + str(levlabs)<EOL>msg += "<STR_LIT>"<EOL>msg += str(self.levels)<EOL>raise ValueError(msg)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>self.labelLevelList = levels<EOL>self.labelIndiceList = indices<EOL>self.labelFontProps = font_manager.FontProperties()<EOL>if fontsize == None:<EOL><INDENT>font_size = int(self.labelFontProps.get_size_in_points())<EOL><DEDENT>else:<EOL><INDENT>if type(fontsize) not in [int, float, str]:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>if type(fontsize) == str:<EOL><INDENT>font_size = int(self.labelFontProps.get_size_in_points())<EOL><DEDENT>else:<EOL><INDENT>self.labelFontProps.set_size(fontsize)<EOL>font_size = fontsize<EOL><DEDENT><DEDENT><DEDENT>self.labelFontSizeList = [font_size] * len(levels)<EOL>if _colors == None:<EOL><INDENT>self.labelMappable = self<EOL>self.labelCValueList = np.take(self.cvalues, self.labelIndiceList)<EOL><DEDENT>else:<EOL><INDENT>cmap = colors.ListedColormap(_colors, N=len(self.labelLevelList))<EOL>self.labelCValueList = list(range(len(self.labelLevelList)))<EOL>self.labelMappable = cm.ScalarMappable(cmap = cmap,<EOL>norm = colors.NoNorm())<EOL><DEDENT>self.labelXYs = []<EOL>if self.labelManual:<EOL><INDENT>print('<STR_LIT>')<EOL>print('<STR_LIT>')<EOL>if not inline:<EOL><INDENT>print('<STR_LIT>')<EOL><DEDENT>blocking_contour_labeler = BlockingContourLabeler(self)<EOL>blocking_contour_labeler(inline,inline_spacing)<EOL><DEDENT>else:<EOL><INDENT>self.labels(inline,inline_spacing)<EOL><DEDENT>self.cl = self.labelTexts<EOL>self.cl_xy = self.labelXYs<EOL>self.cl_cvalues = self.labelCValues<EOL>self.labelTextsList =  cbook.silent_list('<STR_LIT>', self.labelTexts)<EOL>return self.labelTextsList<EOL>

call signature::

  clabel(cs, **kwargs)

adds labels to line contours in *cs*, where *cs* is a
:class:`~matplotlib.contour.ContourSet` object returned by
contour.

::

  clabel(cs, v, **kwargs)

only labels contours listed in *v*.

Optional keyword arguments:

  *fontsize*:
    See http://matplotlib.sf.net/fonts.html

  *colors*:
    - if *None*, the color of each label matches the color of
      the corresponding contour

    - if one string color, e.g. *colors* = 'r' or *colors* =
      'red', all labels will be plotted in this color

    - if a tuple of matplotlib color args (string, float, rgb, etc),
      different labels will be plotted in different colors in the order
      specified

  *inline*:
    controls whether the underlying contour is removed or
    not. Default is *True*.

  *inline_spacing*:
    space in pixels to leave on each side of label when
    placing inline.  Defaults to 5.  This spacing will be
    exact for labels at locations where the contour is
    straight, less so for labels on curved contours.

  *fmt*:
    a format string for the label. Default is '%1.3f'
    Alternatively, this can be a dictionary matching contour
    levels with arbitrary strings to use for each contour level
    (i.e., fmt[level]=string)

  *manual*:
    if *True*, contour labels will be placed manually using
    mouse clicks.  Click the first button near a contour to
    add a label, click the second button (or potentially both
    mouse buttons at once) to finish adding labels.  The third
    button can be used to remove the last label added, but
    only if labels are not inline.  Alternatively, the keyboard
    can be used to select label locations (enter to end label
    placement, delete or backspace act like the third mouse button,
    and any other key will select a label location).

.. plot:: mpl_examples/pylab_examples/contour_demo.py


lcsize = len(linecontour)<EOL>if lcsize > <NUM_LIT:10> * labelwidth:<EOL><INDENT>return <NUM_LIT:1><EOL><DEDENT>xmax = np.amax(linecontour[:,<NUM_LIT:0>])<EOL>xmin = np.amin(linecontour[:,<NUM_LIT:0>])<EOL>ymax = np.amax(linecontour[:,<NUM_LIT:1>])<EOL>ymin = np.amin(linecontour[:,<NUM_LIT:1>])<EOL>lw = labelwidth<EOL>if (xmax - xmin) > <NUM_LIT>* lw or (ymax - ymin) > <NUM_LIT> * lw:<EOL><INDENT>return <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>

if contours are too short, don't plot a label


if self.labelXYs != []:<EOL><INDENT>dist = [np.sqrt((x-loc[<NUM_LIT:0>]) ** <NUM_LIT:2> + (y-loc[<NUM_LIT:1>]) ** <NUM_LIT:2>)<EOL>for loc in self.labelXYs]<EOL>for d in dist:<EOL><INDENT>if d < <NUM_LIT>*lw:<EOL><INDENT>return <NUM_LIT:1><EOL><DEDENT>else: return <NUM_LIT:0><EOL><DEDENT><DEDENT>else: return <NUM_LIT:0><EOL>

if there's a label already nearby, find a better place


def get_label_coords(self, distances, XX, YY, ysize, lw):

hysize = int(ysize/<NUM_LIT:2>)<EOL>adist = np.argsort(distances)<EOL>for ind in adist:<EOL><INDENT>x, y = XX[ind][hysize], YY[ind][hysize]<EOL>if self.too_close(x,y, lw):<EOL><INDENT>continue<EOL><DEDENT>else:<EOL><INDENT>return x,y, ind<EOL><DEDENT><DEDENT>ind = adist[<NUM_LIT:0>]<EOL>x, y = XX[ind][hysize], YY[ind][hysize]<EOL>return x,y, ind<EOL>

labels are ploted at a location with the smallest
        dispersion of the contour from a straight line
        unless there's another label nearby, in which case
        the second best place on the contour is picked up
        if there's no good place a label isplotted at the
        beginning of the contour


def get_label_width(self, lev, fmt, fsize):

if cbook.is_string_like(lev):<EOL><INDENT>lw = (len(lev)) * fsize<EOL><DEDENT>else:<EOL><INDENT>lw = (len(self.get_text(lev,fmt))) * fsize<EOL><DEDENT>return lw<EOL>


def get_real_label_width( self, lev, fmt, fsize ):

<EOL>xx = np.mean( np.asarray(self.ax.axis()).reshape(<NUM_LIT:2>,<NUM_LIT:2>), axis=<NUM_LIT:1> )<EOL>t = text.Text( xx[<NUM_LIT:0>], xx[<NUM_LIT:1>] )<EOL>self.set_label_props( t, self.get_text(lev,fmt), '<STR_LIT:k>' )<EOL>bbox = t.get_window_extent(renderer=self.ax.figure.canvas.renderer)<EOL>lw = np.diff(bbox.corners()[<NUM_LIT:0>::<NUM_LIT:2>,<NUM_LIT:0>])[<NUM_LIT:0>]<EOL>return lw<EOL>

This computes actual onscreen label width.
This uses some black magic to determine onscreen extent of non-drawn
label.  This magic may not be very robust.


def set_label_props(self, label, text, color):

label.set_text(text)<EOL>label.set_color(color)<EOL>label.set_fontproperties(self.labelFontProps)<EOL>label.set_clip_box(self.ax.bbox)<EOL>

set the label properties - color, fontsize, text


if cbook.is_string_like(lev):<EOL><INDENT>return lev<EOL><DEDENT>else:<EOL><INDENT>if isinstance(fmt,dict):<EOL><INDENT>return fmt[lev]<EOL><DEDENT>else:<EOL><INDENT>return fmt%lev<EOL><DEDENT><DEDENT>


def locate_label(self, linecontour, labelwidth):

nsize= len(linecontour)<EOL>if labelwidth > <NUM_LIT:1>:<EOL><INDENT>xsize = int(np.ceil(nsize/labelwidth))<EOL><DEDENT>else:<EOL><INDENT>xsize = <NUM_LIT:1><EOL><DEDENT>if xsize == <NUM_LIT:1>:<EOL><INDENT>ysize = nsize<EOL><DEDENT>else:<EOL><INDENT>ysize = labelwidth<EOL><DEDENT>XX = np.resize(linecontour[:,<NUM_LIT:0>],(xsize, ysize))<EOL>YY = np.resize(linecontour[:,<NUM_LIT:1>],(xsize, ysize))<EOL>yfirst = YY[:,<NUM_LIT:0>].reshape(xsize, <NUM_LIT:1>)<EOL>ylast = YY[:,-<NUM_LIT:1>].reshape(xsize, <NUM_LIT:1>)<EOL>xfirst = XX[:,<NUM_LIT:0>].reshape(xsize, <NUM_LIT:1>)<EOL>xlast = XX[:,-<NUM_LIT:1>].reshape(xsize, <NUM_LIT:1>)<EOL>s = (yfirst-YY) * (xlast-xfirst) - (xfirst-XX) * (ylast-yfirst)<EOL>L = np.sqrt((xlast-xfirst)**<NUM_LIT:2>+(ylast-yfirst)**<NUM_LIT:2>).ravel()<EOL>dist = np.add.reduce(([(abs(s)[i]/L[i]) for i in range(xsize)]),-<NUM_LIT:1>)<EOL>x,y,ind = self.get_label_coords(dist, XX, YY, ysize, labelwidth)<EOL>lc = [tuple(l) for l in linecontour]<EOL>dind = lc.index((x,y))<EOL>return x, y, dind<EOL>

find a good place to plot a label (relatively flat
        part of the contour) and the angle of rotation for the
        text object


def calc_label_rot_and_inline( self, slc, ind, lw, lc=None, spacing=<NUM_LIT:5> ):

if lc is None: lc = []<EOL>hlw = lw/<NUM_LIT><EOL>closed = mlab.is_closed_polygon(slc)<EOL>if closed:<EOL><INDENT>slc = np.r_[ slc[ind:-<NUM_LIT:1>], slc[:ind+<NUM_LIT:1>] ]<EOL>if len(lc): <EOL><INDENT>lc = np.r_[ lc[ind:-<NUM_LIT:1>], lc[:ind+<NUM_LIT:1>] ]<EOL><DEDENT>ind = <NUM_LIT:0><EOL><DEDENT>pl = mlab.path_length(slc)<EOL>pl = pl-pl[ind]<EOL>xi = np.array( [ -hlw, hlw ] )<EOL>if closed: <EOL><INDENT>dp = np.array([pl[-<NUM_LIT:1>],<NUM_LIT:0>])<EOL><DEDENT>else:<EOL><INDENT>dp = np.zeros_like(xi)<EOL><DEDENT>ll = mlab.less_simple_linear_interpolation( pl, slc, dp+xi,<EOL>extrap=True )<EOL>dd = np.diff( ll, axis=<NUM_LIT:0> ).ravel()<EOL>if np.all(dd==<NUM_LIT:0>): <EOL><INDENT>rotation = <NUM_LIT:0.0><EOL><DEDENT>else:<EOL><INDENT>rotation = np.arctan2(dd[<NUM_LIT:1>], dd[<NUM_LIT:0>]) * <NUM_LIT> / np.pi<EOL><DEDENT>if rotation > <NUM_LIT>:<EOL><INDENT>rotation = rotation - <NUM_LIT><EOL><DEDENT>if rotation < -<NUM_LIT>:<EOL><INDENT>rotation = <NUM_LIT> + rotation<EOL><DEDENT>nlc = []<EOL>if len(lc):<EOL><INDENT>xi = dp + xi + np.array([-spacing,spacing])<EOL>I = mlab.less_simple_linear_interpolation(<EOL>pl, np.arange(len(pl)), xi, extrap=False )<EOL>if (not np.isnan(I[<NUM_LIT:0>])) and int(I[<NUM_LIT:0>])!=I[<NUM_LIT:0>]:<EOL><INDENT>xy1 = mlab.less_simple_linear_interpolation(<EOL>pl, lc, [ xi[<NUM_LIT:0>] ] )<EOL><DEDENT>if (not np.isnan(I[<NUM_LIT:1>])) and int(I[<NUM_LIT:1>])!=I[<NUM_LIT:1>]:<EOL><INDENT>xy2 = mlab.less_simple_linear_interpolation(<EOL>pl, lc, [ xi[<NUM_LIT:1>] ] )<EOL><DEDENT>I = [ np.floor(I[<NUM_LIT:0>]), np.ceil(I[<NUM_LIT:1>]) ]<EOL>if closed:<EOL><INDENT>if np.all(~np.isnan(I)):<EOL><INDENT>nlc.append( np.r_[ xy2, lc[I[<NUM_LIT:1>]:I[<NUM_LIT:0>]+<NUM_LIT:1>], xy1 ] )<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if not np.isnan(I[<NUM_LIT:0>]):<EOL><INDENT>nlc.append( np.r_[ lc[:I[<NUM_LIT:0>]+<NUM_LIT:1>], xy1 ] )<EOL><DEDENT>if not np.isnan(I[<NUM_LIT:1>]):<EOL><INDENT>nlc.append( np.r_[ xy2, lc[I[<NUM_LIT:1>]:] ] )<EOL><DEDENT><DEDENT><DEDENT>return (rotation,nlc)<EOL>

This function calculates the appropriate label rotation given
the linecontour coordinates in screen units, the index of the
label location and the label width.

It will also break contour and calculate inlining if *lc* is
not empty (lc defaults to the empty list if None).  *spacing*
is the space around the label in pixels to leave empty.

Do both of these tasks at once to avoid calling mlab.path_length
multiple times, which is relatively costly.

The method used here involves calculating the path length
along the contour in pixel coordinates and then looking
approximately label width / 2 away from central point to
determine rotation and then to break contour if desired.


self.labelCValues.pop(index)<EOL>t = self.labelTexts.pop(index)<EOL>t.remove()<EOL>

Defaults to removing last label, but any index can be supplied


def __init__(self, ax, *args, **kwargs):

self.ax = ax<EOL>self.levels = kwargs.get('<STR_LIT>', None)<EOL>self.filled = kwargs.get('<STR_LIT>', False)<EOL>self.linewidths = kwargs.get('<STR_LIT>', None)<EOL>self.linestyles = kwargs.get('<STR_LIT>', '<STR_LIT>')<EOL>self.alpha = kwargs.get('<STR_LIT>', <NUM_LIT:1.0>)<EOL>self.origin = kwargs.get('<STR_LIT>', None)<EOL>self.extent = kwargs.get('<STR_LIT>', None)<EOL>cmap = kwargs.get('<STR_LIT>', None)<EOL>self.colors = kwargs.get('<STR_LIT>', None)<EOL>norm = kwargs.get('<STR_LIT>', None)<EOL>self.extend = kwargs.get('<STR_LIT>', '<STR_LIT>')<EOL>self.antialiased = kwargs.get('<STR_LIT>', True)<EOL>self.nchunk = kwargs.get('<STR_LIT>', <NUM_LIT:0>)<EOL>self.locator = kwargs.get('<STR_LIT>', None)<EOL>if (isinstance(norm, colors.LogNorm)<EOL>or isinstance(self.locator, ticker.LogLocator)):<EOL><INDENT>self.logscale = True<EOL>if norm is None:<EOL><INDENT>norm = colors.LogNorm()<EOL><DEDENT>if self.extend is not '<STR_LIT>':<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.logscale = False<EOL><DEDENT>if self.origin is not None: assert(self.origin in<EOL>['<STR_LIT>', '<STR_LIT>', '<STR_LIT:image>'])<EOL>if self.extent is not None: assert(len(self.extent) == <NUM_LIT:4>)<EOL>if cmap is not None: assert(isinstance(cmap, colors.Colormap))<EOL>if self.colors is not None and cmap is not None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if self.origin == '<STR_LIT:image>': self.origin = mpl.rcParams['<STR_LIT>']<EOL>x, y, z = self._contour_args(*args)        <EOL>if self.colors is not None:<EOL><INDENT>cmap = colors.ListedColormap(self.colors, N=len(self.layers))<EOL><DEDENT>if self.filled:<EOL><INDENT>self.collections = cbook.silent_list('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>self.collections = cbook.silent_list('<STR_LIT>')<EOL><DEDENT>self.labelTexts = []<EOL>self.labelCValues = []<EOL>kw = {'<STR_LIT>': cmap}<EOL>if norm is not None:<EOL><INDENT>kw['<STR_LIT>'] = norm<EOL><DEDENT>cm.ScalarMappable.__init__(self, **kw) <EOL>self._process_colors()<EOL>_mask = ma.getmask(z)<EOL>if _mask is ma.nomask:<EOL><INDENT>_mask = None<EOL><DEDENT>if self.filled:<EOL><INDENT>if self.linewidths is not None:<EOL><INDENT>warnings.warn('<STR_LIT>')<EOL><DEDENT>C = _cntr.Cntr(x, y, z.filled(), _mask)<EOL>lowers = self._levels[:-<NUM_LIT:1>]<EOL>uppers = self._levels[<NUM_LIT:1>:]<EOL>for level, level_upper in zip(lowers, uppers):<EOL><INDENT>nlist = C.trace(level, level_upper, points = <NUM_LIT:0>,<EOL>nchunk = self.nchunk)<EOL>col = collections.PolyCollection(nlist,<EOL>antialiaseds = (self.antialiased,),<EOL>edgecolors= '<STR_LIT:none>',<EOL>alpha=self.alpha)<EOL>self.ax.add_collection(col)<EOL>self.collections.append(col)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>tlinewidths = self._process_linewidths()<EOL>self.tlinewidths = tlinewidths<EOL>tlinestyles = self._process_linestyles()<EOL>C = _cntr.Cntr(x, y, z.filled(), _mask)<EOL>for level, width, lstyle in zip(self.levels, tlinewidths, tlinestyles):<EOL><INDENT>nlist = C.trace(level, points = <NUM_LIT:0>)<EOL>col = collections.LineCollection(nlist,<EOL>linewidths = width,<EOL>linestyle = lstyle,<EOL>alpha=self.alpha)<EOL>if level < <NUM_LIT:0.0> and self.monochrome:<EOL><INDENT>ls = mpl.rcParams['<STR_LIT>']<EOL>col.set_linestyle(ls)<EOL><DEDENT>col.set_label('<STR_LIT>')<EOL>self.ax.add_collection(col, False)<EOL>self.collections.append(col)<EOL><DEDENT><DEDENT>self.changed() <EOL>x0 = ma.minimum(x)<EOL>x1 = ma.maximum(x)<EOL>y0 = ma.minimum(y)<EOL>y1 = ma.maximum(y)<EOL>self.ax.update_datalim([(x0,y0), (x1,y1)])<EOL>self.ax.autoscale_view()<EOL>

Draw contour lines or filled regions, depending on
whether keyword arg 'filled' is False (default) or True.

The first argument of the initializer must be an axes
object.  The remaining arguments and keyword arguments
are described in ContourSet.contour_doc.


if self.locator is None:<EOL><INDENT>if self.logscale:<EOL><INDENT>self.locator = ticker.LogLocator()<EOL><DEDENT>else:<EOL><INDENT>self.locator = ticker.MaxNLocator(N+<NUM_LIT:1>)<EOL><DEDENT><DEDENT>self.locator.create_dummy_axis()<EOL>zmax = self.zmax<EOL>zmin = self.zmin<EOL>self.locator.set_bounds(zmin, zmax)<EOL>lev = self.locator()<EOL>zmargin = (zmax - zmin) * <NUM_LIT> <EOL>if zmax >= lev[-<NUM_LIT:1>]:<EOL><INDENT>lev[-<NUM_LIT:1>] += zmargin<EOL><DEDENT>if zmin <= lev[<NUM_LIT:0>]:<EOL><INDENT>if self.logscale:<EOL><INDENT>lev[<NUM_LIT:0>] = <NUM_LIT> * zmin<EOL><DEDENT>else:<EOL><INDENT>lev[<NUM_LIT:0>] -= zmargin<EOL><DEDENT><DEDENT>self._auto = True<EOL>if self.filled:<EOL><INDENT>return lev<EOL><DEDENT>return lev[<NUM_LIT:1>:-<NUM_LIT:1>]<EOL>

Select contour levels to span the data.

We need two more levels for filled contours than for
line contours, because for the latter we need to specify
the lower and upper boundary of each range. For example,
a single contour boundary, say at z = 0, requires only
one contour line, but two filled regions, and therefore
three levels to provide boundaries for both regions.


if z.ndim != <NUM_LIT:2>:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>Ny, Nx = z.shape<EOL><DEDENT>if self.origin is None:  <EOL><INDENT>if self.extent is None:<EOL><INDENT>return np.meshgrid(np.arange(Nx), np.arange(Ny))<EOL><DEDENT>else:<EOL><INDENT>x0,x1,y0,y1 = self.extent<EOL>x = np.linspace(x0, x1, Nx)<EOL>y = np.linspace(y0, y1, Ny)<EOL>return np.meshgrid(x, y)<EOL><DEDENT><DEDENT>if self.extent is None:<EOL><INDENT>x0,x1,y0,y1 = (<NUM_LIT:0>, Nx, <NUM_LIT:0>, Ny)<EOL><DEDENT>else:<EOL><INDENT>x0,x1,y0,y1 = self.extent<EOL><DEDENT>dx = float(x1 - x0)/Nx<EOL>dy = float(y1 - y0)/Ny<EOL>x = x0 + (np.arange(Nx) + <NUM_LIT:0.5>) * dx<EOL>y = y0 + (np.arange(Ny) + <NUM_LIT:0.5>) * dy<EOL>if self.origin == '<STR_LIT>':<EOL><INDENT>y = y[::-<NUM_LIT:1>]<EOL><DEDENT>return np.meshgrid(x,y)<EOL>

Return X, Y arrays such that contour(Z) will match imshow(Z)
if origin is not None.
The center of pixel Z[i,j] depends on origin:
if origin is None, x = j, y = i;
if origin is 'lower', x = j + 0.5, y = i + 0.5;
if origin is 'upper', x = j + 0.5, y = Nrows - i - 0.5
If extent is not None, x and y will be scaled to match,
as in imshow.
If origin is None and extent is not None, then extent
will give the minimum and maximum values of x and y.


<EOL>x = self.ax.convert_xunits( args[<NUM_LIT:0>] )<EOL>y = self.ax.convert_yunits( args[<NUM_LIT:1>] )<EOL>x = np.asarray(x, dtype=np.float64)<EOL>y = np.asarray(y, dtype=np.float64)<EOL>z = ma.asarray(args[<NUM_LIT:2>], dtype=np.float64)<EOL>if z.ndim != <NUM_LIT:2>:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>else: Ny, Nx = z.shape<EOL>if x.shape == z.shape and y.shape == z.shape:<EOL><INDENT>return x,y,z<EOL><DEDENT>if x.ndim != <NUM_LIT:1> or y.ndim != <NUM_LIT:1>:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>nx, = x.shape<EOL>ny, = y.shape<EOL>if nx != Nx or ny != Ny:<EOL><INDENT>raise TypeError("<STR_LIT>" +<EOL>"<STR_LIT>")<EOL><DEDENT>x,y = np.meshgrid(x,y)<EOL>return x,y,z<EOL>

For functions like contour, check that the dimensions
of the input arrays match; if x and y are 1D, convert
them to 2D using meshgrid.

Possible change: I think we should make and use an ArgumentError
Exception class (here and elsewhere).


self.monochrome = self.cmap.monochrome<EOL>if self.colors is not None:<EOL><INDENT>i0, i1 = <NUM_LIT:0>, len(self.layers)<EOL>if self.extend in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>i0 = -<NUM_LIT:1><EOL><DEDENT>if self.extend in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>i1 = i1 + <NUM_LIT:1><EOL><DEDENT>self.cvalues = list(range(i0, i1))<EOL>self.set_norm(colors.NoNorm())<EOL><DEDENT>else:<EOL><INDENT>self.cvalues = self.layers<EOL><DEDENT>if not self.norm.scaled():<EOL><INDENT>self.set_clim(self.vmin, self.vmax)<EOL><DEDENT>if self.extend in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>self.norm.clip = False<EOL><DEDENT>self.set_array(self.layers)<EOL>

Color argument processing for contouring.

Note that we base the color mapping on the contour levels,
not on the actual range of the Z values.  This means we
don't have to worry about bad values in Z, and we always have
the full dynamic range available for the selected levels.

The color is based on the midpoint of the layer, except for
an extended end layers.


return self.alpha<EOL>

returns alpha to be applied to all ContourSet artists


self.alpha = alpha<EOL>self.changed()<EOL>


def find_nearest_contour( self, x, y, indices=None, pixel=True ):

<EOL>if indices==None:<EOL><INDENT>indices = list(range(len(self.levels)))<EOL><DEDENT>dmin = <NUM_LIT><EOL>conmin = None<EOL>segmin = None<EOL>xmin = None<EOL>ymin = None<EOL>for icon in indices:<EOL><INDENT>con = self.collections[icon]<EOL>paths = con.get_paths()<EOL>for segNum, linepath in enumerate(paths):<EOL><INDENT>lc = linepath.vertices<EOL>if pixel:<EOL><INDENT>lc = self.ax.transData.transform(lc)<EOL><DEDENT>ds = (lc[:,<NUM_LIT:0>]-x)**<NUM_LIT:2> + (lc[:,<NUM_LIT:1>]-y)**<NUM_LIT:2><EOL>d = min( ds )<EOL>if d < dmin:<EOL><INDENT>dmin = d<EOL>conmin = icon<EOL>segmin = segNum<EOL>imin = mpl.mlab.find( ds == d )[<NUM_LIT:0>]<EOL>xmin = lc[imin,<NUM_LIT:0>]<EOL>ymin = lc[imin,<NUM_LIT:1>]<EOL><DEDENT><DEDENT><DEDENT>return (conmin,segmin,imin,xmin,ymin,dmin)<EOL>

Finds contour that is closest to a point.  Defaults to
measuring distance in pixels (screen space - useful for manual
contour labeling), but this can be controlled via a keyword
argument.

Returns a tuple containing the contour, segment, index of
segment, x & y of segment point and distance to minimum point.

Call signature::

  conmin,segmin,imin,xmin,ymin,dmin = find_nearest_contour(
             self, x, y, indices=None, pixel=True )

Optional keyword arguments::

*indices*:
   Indexes of contour levels to consider when looking for
   nearest point.  Defaults to using all levels.

*pixel*:
   If *True*, measure distance in pixel space, if not, measure
   distance in axes space.  Defaults to *True*.


<EOL>if symbol == '<STR_LIT:->':<EOL><INDENT>return <NUM_LIT><EOL><DEDENT>try:<EOL><INDENT>return ord(symbol)<EOL><DEDENT>except TypeError:<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>return tex2uni[symbol.strip("<STR_LIT:\\>")]<EOL><DEDENT>except KeyError:<EOL><INDENT>message = """<STR_LIT>"""%locals()<EOL>raise ValueError(message)<EOL><DEDENT>

get_unicode_index(symbol) -> integer

Return the integer index (from the Unicode table) of symbol.  *symbol*
can be a single unicode character, a TeX command (i.e. r'\pi'), or a
Type1 symbol name (i.e. 'phi').


return MathtextBackendBbox(MathtextBackendBitmapRender())<EOL>

A backend to generate standalone mathtext images.  No additional
matplotlib backend is required.


def raise_error(s, loc, toks):<EOL><INDENT>raise ParseFatalException(msg + "<STR_LIT:\n>" + s)<EOL><DEDENT>empty = Empty()<EOL>empty.setParseAction(raise_error)<EOL>return empty<EOL>


self.width  = w<EOL>self.height = h<EOL>self.depth  = d<EOL>


raise NotImplementedError()<EOL>

Draw a glyph described by *info* to the reference point (*ox*,
*oy*).


def render_filled_rect(self, x1, y1, x2, y2):

raise NotImplementedError()<EOL>

Draw a filled black rectangle from (*x1*, *y1*) to (*x2*, *y2*).


raise NotImplementedError()<EOL>

Return a backend-specific tuple to return to the backend after
all processing is done.


return LOAD_NO_HINTING<EOL>

Get the Freetype hinting type to use with this particular
backend.


def __init__(self, default_font_prop, mathtext_backend):

self.default_font_prop = default_font_prop<EOL>self.mathtext_backend = mathtext_backend<EOL>self.mathtext_backend.fonts_object = self<EOL>self.used_characters = {}<EOL>

*default_font_prop*: A
:class:`~matplotlib.font_manager.FontProperties` object to use
for the default non-math font, or the base font for Unicode
(generic) font rendering.

*mathtext_backend*: A subclass of :class:`MathTextBackend`
used to delegate the actual rendering.


self.used_characters = None<EOL>

Fix any cyclical references before the object is about
to be destroyed.


def get_kern(self, font1, fontclass1, sym1, fontsize1,<EOL>font2, fontclass2, sym2, fontsize2, dpi):

return <NUM_LIT:0.><EOL>

Get the kerning distance for font between *sym1* and *sym2*.

*fontX*: one of the TeX font names::

  tt, it, rm, cal, sf, bf or default (non-math)

*fontclassX*: TODO

*symX*: a symbol in raw TeX form. e.g. '1', 'x' or '\sigma'

*fontsizeX*: the fontsize in points

*dpi*: the current dots-per-inch


def get_metrics(self, font, font_class, sym, fontsize, dpi):

info = self._get_info(font, font_class, sym, fontsize, dpi)<EOL>return info.metrics<EOL>

*font*: one of the TeX font names::

  tt, it, rm, cal, sf, bf or default (non-math)

*font_class*: TODO

*sym*:  a symbol in raw TeX form. e.g. '1', 'x' or '\sigma'

*fontsize*: font size in points

*dpi*: current dots-per-inch

Returns an object with the following attributes:

  - *advance*: The advance distance (in points) of the glyph.

  - *height*: The height of the glyph in points.

  - *width*: The width of the glyph in points.

  - *xmin*, *xmax*, *ymin*, *ymax* - the ink rectangle of the glyph

  - *iceberg* - the distance from the baseline to the top of
    the glyph.  This corresponds to TeX's definition of
    "height".


self.width, self.height, self.depth = ceil(w), ceil(h), ceil(d)<EOL>self.mathtext_backend.set_canvas_size(self.width, self.height, self.depth)<EOL>

Set the size of the buffer used to render the math expression.
Only really necessary for the bitmap backends.


def render_glyph(self, ox, oy, facename, font_class, sym, fontsize, dpi):

info = self._get_info(facename, font_class, sym, fontsize, dpi)<EOL>realpath, stat_key = get_realpath_and_stat(info.font.fname)<EOL>used_characters = self.used_characters.setdefault(<EOL>stat_key, (realpath, set()))<EOL>used_characters[<NUM_LIT:1>].add(info.num)<EOL>self.mathtext_backend.render_glyph(ox, oy, info)<EOL>

Draw a glyph at

  - *ox*, *oy*: position

  - *facename*: One of the TeX face names

  - *font_class*:

  - *sym*: TeX symbol name or single character

  - *fontsize*: fontsize in points

  - *dpi*: The dpi to draw at.


def render_rect_filled(self, x1, y1, x2, y2):

self.mathtext_backend.render_rect_filled(x1, y1, x2, y2)<EOL>

Draw a filled rectangle from (*x1*, *y1*) to (*x2*, *y2*).


def get_xheight(self, font, fontsize, dpi):

raise NotImplementedError()<EOL>

Get the xheight for the given *font* and *fontsize*.


def get_underline_thickness(self, font, fontsize, dpi):

raise NotImplementedError()<EOL>

Get the line thickness that matches the given font.  Used as a
base unit for drawing lines such as in a fraction or radical.


return self.used_characters<EOL>

Get the set of characters that were used in the math
expression.  Used by backends that need to subset fonts so
they know which glyphs to include.


return self.mathtext_backend.get_results(box)<EOL>

Get the data needed by the backend to render the math
expression.  The return value is backend-specific.


def get_sized_alternatives_for_symbol(self, fontname, sym):

return [(fontname, sym)]<EOL>

Override if your font provides multiple sizes of the same
symbol.  Should return a list of symbols matching *sym* in
various sizes.  The expression renderer will select the most
appropriate size for a given situation from this list.


def _get_info (self, fontname, font_class, sym, fontsize, dpi):

key = fontname, sym, fontsize, dpi<EOL>tup = self.glyphd.get(key)<EOL>if tup is not None:<EOL><INDENT>return tup<EOL><DEDENT>if (fontname == '<STR_LIT>' and<EOL>(len(sym) > <NUM_LIT:1> or<EOL>not unicodedata.category(str(sym)).startswith("<STR_LIT:L>"))):<EOL><INDENT>fontname = '<STR_LIT>'<EOL><DEDENT>found_symbol = False<EOL>if sym in latex_to_standard:<EOL><INDENT>fontname, num = latex_to_standard[sym]<EOL>glyph = chr(num)<EOL>found_symbol = True<EOL><DEDENT>elif len(sym) == <NUM_LIT:1>:<EOL><INDENT>glyph = sym<EOL>num = ord(glyph)<EOL>found_symbol = True<EOL><DEDENT>else:<EOL><INDENT>warn("<STR_LIT>" % sym,<EOL>MathTextWarning)<EOL><DEDENT>slanted = (fontname == '<STR_LIT>')<EOL>font = self._get_font(fontname)<EOL>if found_symbol:<EOL><INDENT>try:<EOL><INDENT>symbol_name = font.get_name_char(glyph)<EOL><DEDENT>except KeyError:<EOL><INDENT>warn("<STR_LIT>" %<EOL>(font.postscript_name, sym),<EOL>MathTextWarning)<EOL>found_symbol = False<EOL><DEDENT><DEDENT>if not found_symbol:<EOL><INDENT>glyph = sym = '<STR_LIT:?>'<EOL>num = ord(glyph)<EOL>symbol_name = font.get_name_char(glyph)<EOL><DEDENT>offset = <NUM_LIT:0><EOL>scale = <NUM_LIT> * fontsize<EOL>xmin, ymin, xmax, ymax = [val * scale<EOL>for val in font.get_bbox_char(glyph)]<EOL>metrics = Bunch(<EOL>advance  = font.get_width_char(glyph) * scale,<EOL>width    = font.get_width_char(glyph) * scale,<EOL>height   = font.get_height_char(glyph) * scale,<EOL>xmin = xmin,<EOL>xmax = xmax,<EOL>ymin = ymin+offset,<EOL>ymax = ymax+offset,<EOL>iceberg = ymax + offset,<EOL>slanted = slanted<EOL>)<EOL>self.glyphd[key] = Bunch(<EOL>font            = font,<EOL>fontsize        = fontsize,<EOL>postscript_name = font.get_fontname(),<EOL>metrics         = metrics,<EOL>symbol_name     = symbol_name,<EOL>num             = num,<EOL>glyph           = glyph,<EOL>offset          = offset<EOL>)<EOL>return self.glyphd[key]<EOL>

load the cmfont, metrics and glyph with caching


self.size += <NUM_LIT:1><EOL>

Shrinks one level smaller.  There are only three levels of
sizes, after which things will no longer get smaller.


self.size -= <NUM_LIT:1><EOL>

Grows one level larger.  There is no limit to how big
something can get.


advance = self._metrics.advance - self.width<EOL>kern = <NUM_LIT:0.><EOL>if isinstance(next, Char):<EOL><INDENT>kern = self.font_output.get_kern(<EOL>self.font, self.font_class, self.c, self.fontsize,<EOL>next.font, next.font_class, next.c, next.fontsize,<EOL>self.dpi)<EOL><DEDENT>return advance + kern<EOL>

Return the amount of kerning between this and the given
character.  Called when characters are strung together into
:class:`Hlist` to create :class:`Kern` nodes.


self.font_output.render_glyph(<EOL>x, y,<EOL>self.font, self.font_class, self.c, self.fontsize, self.dpi)<EOL>


self.font_output.render_glyph(<EOL>x - self._metrics.xmin, y + self._metrics.ymin,<EOL>self.font, self.font_class, self.c, self.fontsize, self.dpi)<EOL>


o = <NUM_LIT:0><EOL>for i in range(len(totals) - <NUM_LIT:1>, <NUM_LIT:0>, -<NUM_LIT:1>):<EOL><INDENT>if totals[i] != <NUM_LIT:0.0>:<EOL><INDENT>o = i<EOL>break<EOL><DEDENT><DEDENT>return o<EOL>

A helper function to determine the highest order of glue
used by the members of this list.  Used by vpack and hpack.


new_children = []<EOL>num_children = len(self.children)<EOL>if num_children:<EOL><INDENT>for i in range(num_children):<EOL><INDENT>elem = self.children[i]<EOL>if i < num_children - <NUM_LIT:1>:<EOL><INDENT>next = self.children[i + <NUM_LIT:1>]<EOL><DEDENT>else:<EOL><INDENT>next = None<EOL><DEDENT>new_children.append(elem)<EOL>kerning_distance = elem.get_kerning(next)<EOL>if kerning_distance != <NUM_LIT:0.>:<EOL><INDENT>kern = Kern(kerning_distance)<EOL>new_children.append(kern)<EOL><DEDENT><DEDENT>self.children = new_children<EOL><DEDENT>

Insert :class:`Kern` nodes between :class:`Char` nodes to set
kerning.  The :class:`Char` nodes themselves determine the
amount of kerning they need (in :meth:`~Char.get_kerning`),
and this function just creates the linked list in the correct
way.


def hpack(self, w=<NUM_LIT:0.>, m='<STR_LIT>'):

<EOL>h = <NUM_LIT:0.><EOL>d = <NUM_LIT:0.><EOL>x = <NUM_LIT:0.><EOL>total_stretch = [<NUM_LIT:0.>] * <NUM_LIT:4><EOL>total_shrink = [<NUM_LIT:0.>] * <NUM_LIT:4><EOL>for p in self.children:<EOL><INDENT>if isinstance(p, Char):<EOL><INDENT>x += p.width<EOL>h = max(h, p.height)<EOL>d = max(d, p.depth)<EOL><DEDENT>elif isinstance(p, Box):<EOL><INDENT>x += p.width<EOL>if not isinf(p.height) and not isinf(p.depth):<EOL><INDENT>s = getattr(p, '<STR_LIT>', <NUM_LIT:0.>)<EOL>h = max(h, p.height - s)<EOL>d = max(d, p.depth + s)<EOL><DEDENT><DEDENT>elif isinstance(p, Glue):<EOL><INDENT>glue_spec = p.glue_spec<EOL>x += glue_spec.width<EOL>total_stretch[glue_spec.stretch_order] += glue_spec.stretch<EOL>total_shrink[glue_spec.shrink_order] += glue_spec.shrink<EOL><DEDENT>elif isinstance(p, Kern):<EOL><INDENT>x += p.width<EOL><DEDENT><DEDENT>self.height = h<EOL>self.depth = d<EOL>if m == '<STR_LIT>':<EOL><INDENT>w += x<EOL><DEDENT>self.width = w<EOL>x = w - x<EOL>if x == <NUM_LIT:0.>:<EOL><INDENT>self.glue_sign = <NUM_LIT:0><EOL>self.glue_order = <NUM_LIT:0><EOL>self.glue_ratio = <NUM_LIT:0.><EOL>return<EOL><DEDENT>if x > <NUM_LIT:0.>:<EOL><INDENT>self._set_glue(x, <NUM_LIT:1>, total_stretch, "<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>self._set_glue(x, -<NUM_LIT:1>, total_shrink, "<STR_LIT>")<EOL><DEDENT>

The main duty of :meth:`hpack` is to compute the dimensions of
the resulting boxes, and to adjust the glue if one of those
dimensions is pre-specified.  The computed sizes normally
enclose all of the material inside the new box; but some items
may stick out if negative glue is used, if the box is
overfull, or if a ``\\vbox`` includes other boxes that have
been shifted left.

  - *w*: specifies a width

  - *m*: is either 'exactly' or 'additional'.

Thus, ``hpack(w, 'exactly')`` produces a box whose width is
exactly *w*, while ``hpack(w, 'additional')`` yields a box
whose width is the natural width plus *w*.  The default values
produce a box with the natural width.


def vpack(self, h=<NUM_LIT:0.>, m='<STR_LIT>', l=float(inf)):

<EOL>w = <NUM_LIT:0.><EOL>d = <NUM_LIT:0.><EOL>x = <NUM_LIT:0.><EOL>total_stretch = [<NUM_LIT:0.>] * <NUM_LIT:4><EOL>total_shrink = [<NUM_LIT:0.>] * <NUM_LIT:4><EOL>for p in self.children:<EOL><INDENT>if isinstance(p, Box):<EOL><INDENT>x += d + p.height<EOL>d = p.depth<EOL>if not isinf(p.width):<EOL><INDENT>s = getattr(p, '<STR_LIT>', <NUM_LIT:0.>)<EOL>w = max(w, p.width + s)<EOL><DEDENT><DEDENT>elif isinstance(p, Glue):<EOL><INDENT>x += d<EOL>d = <NUM_LIT:0.><EOL>glue_spec = p.glue_spec<EOL>x += glue_spec.width<EOL>total_stretch[glue_spec.stretch_order] += glue_spec.stretch<EOL>total_shrink[glue_spec.shrink_order] += glue_spec.shrink<EOL><DEDENT>elif isinstance(p, Kern):<EOL><INDENT>x += d + p.width<EOL>d = <NUM_LIT:0.><EOL><DEDENT>elif isinstance(p, Char):<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT><DEDENT>self.width = w<EOL>if d > l:<EOL><INDENT>x += d - l<EOL>self.depth = l<EOL><DEDENT>else:<EOL><INDENT>self.depth = d<EOL><DEDENT>if m == '<STR_LIT>':<EOL><INDENT>h += x<EOL><DEDENT>self.height = h<EOL>x = h - x<EOL>if x == <NUM_LIT:0>:<EOL><INDENT>self.glue_sign = <NUM_LIT:0><EOL>self.glue_order = <NUM_LIT:0><EOL>self.glue_ratio = <NUM_LIT:0.><EOL>return<EOL><DEDENT>if x > <NUM_LIT:0.>:<EOL><INDENT>self._set_glue(x, <NUM_LIT:1>, total_stretch, "<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>self._set_glue(x, -<NUM_LIT:1>, total_shrink, "<STR_LIT>")<EOL><DEDENT>

The main duty of :meth:`vpack` is to compute the dimensions of
the resulting boxes, and to adjust the glue if one of those
dimensions is pre-specified.

  - *h*: specifies a height
  - *m*: is either 'exactly' or 'additional'.
  - *l*: a maximum height

Thus, ``vpack(h, 'exactly')`` produces a box whose height is
exactly *h*, while ``vpack(h, 'additional')`` yields a box
whose height is the natural height plus *h*.  The default
values produce a box with the natural width.


self._expr = None<EOL>self._state_stack = None<EOL>self._em_width_cache = {}<EOL>


def parse(self, s, fonts_object, fontsize, dpi):

self._state_stack = [self.State(fonts_object, '<STR_LIT:default>', '<STR_LIT>', fontsize, dpi)]<EOL>try:<EOL><INDENT>self._expression.parseString(s)<EOL><DEDENT>except ParseException as err:<EOL><INDENT>raise ValueError("<STR_LIT:\n>".join([<EOL>"<STR_LIT>",<EOL>err.line,<EOL>"<STR_LIT:U+0020>" * (err.column - <NUM_LIT:1>) + "<STR_LIT>",<EOL>str(err)]))<EOL><DEDENT>return self._expr<EOL>

Parse expression *s* using the given *fonts_object* for
output, at the given *fontsize* and *dpi*.

Returns the parse tree of :class:`Node` instances.


return self._state_stack[-<NUM_LIT:1>]<EOL>

Get the current :class:`State` of the parser.


self._state_stack.append(self.get_state().copy())<EOL>

Push a new :class:`State` onto the stack which is just a copy
of the current state.


self._output = output.lower()<EOL>self._cache = maxdict(<NUM_LIT:50>)<EOL>

Create a MathTextParser for the given backend *output*.


def parse(self, s, dpi = <NUM_LIT>, prop = None):

if prop is None:<EOL><INDENT>prop = FontProperties()<EOL><DEDENT>cacheKey = (s, dpi, hash(prop))<EOL>result = self._cache.get(cacheKey)<EOL>if result is not None:<EOL><INDENT>return result<EOL><DEDENT>if self._output == '<STR_LIT>' and rcParams['<STR_LIT>']:<EOL><INDENT>font_output = StandardPsFonts(prop)<EOL><DEDENT>else:<EOL><INDENT>backend = self._backend_mapping[self._output]()<EOL>fontset = rcParams['<STR_LIT>']<EOL>fontset_class = self._font_type_mapping.get(fontset.lower())<EOL>if fontset_class is not None:<EOL><INDENT>font_output = fontset_class(prop, backend)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT><DEDENT>fontsize = prop.get_size_in_points()<EOL>if self._parser is None:<EOL><INDENT>self.__class__._parser = Parser()<EOL><DEDENT>box = self._parser.parse(s, font_output, fontsize, dpi)<EOL>font_output.set_canvas_size(box.width, box.height, box.depth)<EOL>result = font_output.get_results(box)<EOL>self._cache[cacheKey] = result<EOL>self._parser.clear()<EOL>font_output.destroy()<EOL>font_output.mathtext_backend.fonts_object = None<EOL>font_output.mathtext_backend = None<EOL>return result<EOL>

Parse the given math expression *s* at the given *dpi*.  If
*prop* is provided, it is a
:class:`~matplotlib.font_manager.FontProperties` object
specifying the "default" font to use in the math expression,
used for all non-math text.

The results are cached, so multiple calls to :meth:`parse`
with the same expression should be fast.


def to_mask(self, texstr, dpi=<NUM_LIT>, fontsize=<NUM_LIT>):

assert(self._output=="<STR_LIT>")<EOL>prop = FontProperties(size=fontsize)<EOL>ftimage, depth = self.parse(texstr, dpi=dpi, prop=prop)<EOL>x = ftimage.as_array()<EOL>return x, depth<EOL>

*texstr*
    A valid mathtext string, eg r'IQ: $\sigma_i=15$'

*dpi*
    The dots-per-inch to render the text

*fontsize*
    The font size in points

Returns a tuple (*array*, *depth*)

  - *array* is an NxM uint8 alpha ubyte mask array of
    rasterized tex.

  - depth is the offset of the baseline from the bottom of the
    image in pixels.


def to_rgba(self, texstr, color='<STR_LIT>', dpi=<NUM_LIT>, fontsize=<NUM_LIT>):

x, depth = self.to_mask(texstr, dpi=dpi, fontsize=fontsize)<EOL>r, g, b = mcolors.colorConverter.to_rgb(color)<EOL>RGBA = np.zeros((x.shape[<NUM_LIT:0>], x.shape[<NUM_LIT:1>], <NUM_LIT:4>), dtype=np.uint8)<EOL>RGBA[:,:,<NUM_LIT:0>] = int(<NUM_LIT:255>*r)<EOL>RGBA[:,:,<NUM_LIT:1>] = int(<NUM_LIT:255>*g)<EOL>RGBA[:,:,<NUM_LIT:2>] = int(<NUM_LIT:255>*b)<EOL>RGBA[:,:,<NUM_LIT:3>] = x<EOL>return RGBA, depth<EOL>

*texstr*
    A valid mathtext string, eg r'IQ: $\sigma_i=15$'

*color*
    Any matplotlib color argument

*dpi*
    The dots-per-inch to render the text

*fontsize*
    The font size in points

Returns a tuple (*array*, *depth*)

  - *array* is an NxM uint8 alpha ubyte mask array of
    rasterized tex.

  - depth is the offset of the baseline from the bottom of the
    image in pixels.


def to_png(self, filename, texstr, color='<STR_LIT>', dpi=<NUM_LIT>, fontsize=<NUM_LIT>):

rgba, depth = self.to_rgba(texstr, color=color, dpi=dpi, fontsize=fontsize)<EOL>numrows, numcols, tmp = rgba.shape<EOL>_png.write_png(rgba.tostring(), numcols, numrows, filename)<EOL>return depth<EOL>

Writes a tex expression to a PNG file.

Returns the offset of the baseline from the bottom of the
image in pixels.

*filename*
    A writable filename or fileobject

*texstr*
    A valid mathtext string, eg r'IQ: $\sigma_i=15$'

*color*
    A valid matplotlib color argument

*dpi*
    The dots-per-inch to render the text

*fontsize*
    The font size in points

Returns the offset of the baseline from the bottom of the
image in pixels.


def get_depth(self, texstr, dpi=<NUM_LIT>, fontsize=<NUM_LIT>):

assert(self._output=="<STR_LIT>")<EOL>prop = FontProperties(size=fontsize)<EOL>ftimage, depth = self.parse(texstr, dpi=dpi, prop=prop)<EOL>return depth<EOL>

Returns the offset of the baseline from the bottom of the
image in pixels.

*texstr*
    A valid mathtext string, eg r'IQ: $\sigma_i=15$'

*dpi*
    The dots-per-inch to render the text

*fontsize*
    The font size in points


def parse_yahoo_historical(fh, asobject=False, adjusted=True):

results = []<EOL>lines = fh.readlines()<EOL>datefmt = None<EOL>for line in lines[<NUM_LIT:1>:]:<EOL><INDENT>vals = line.split('<STR_LIT:U+002C>')<EOL>if len(vals)!=<NUM_LIT:7>: continue<EOL>datestr = vals[<NUM_LIT:0>]<EOL>if datefmt is None:<EOL><INDENT>try:<EOL><INDENT>datefmt = '<STR_LIT>'<EOL>dt = datetime.date(*time.strptime(datestr, datefmt)[:<NUM_LIT:3>])<EOL><DEDENT>except ValueError:<EOL><INDENT>datefmt = '<STR_LIT>'  <EOL><DEDENT><DEDENT>dt = datetime.date(*time.strptime(datestr, datefmt)[:<NUM_LIT:3>])<EOL>d = date2num(dt)<EOL>open, high, low, close =  [float(val) for val in vals[<NUM_LIT:1>:<NUM_LIT:5>]]<EOL>volume = int(vals[<NUM_LIT:5>])<EOL>if adjusted:<EOL><INDENT>aclose = float(vals[<NUM_LIT:6>])<EOL>m = aclose/close<EOL>open *= m<EOL>high *= m<EOL>low *= m<EOL>close = aclose<EOL><DEDENT>results.append((d, open, close, high, low, volume))<EOL><DEDENT>results.reverse()<EOL>if asobject:<EOL><INDENT>if len(results)==<NUM_LIT:0>: return None<EOL>else:<EOL><INDENT>date, open, close, high, low, volume = list(map(np.asarray, list(zip(*results))))<EOL><DEDENT>return Bunch(date=date, open=open, close=close, high=high, low=low, volume=volume)<EOL><DEDENT>else:<EOL><INDENT>return results<EOL><DEDENT>

Parse the historical data in file handle fh from yahoo finance and return
results as a list of

d, open, close, high, low, volume

where d is a floating poing representation of date, as returned by date2num

if adjust=True, use adjusted prices


def fetch_historical_yahoo(ticker, date1, date2, cachename=None):

ticker = ticker.upper()<EOL>d1 = (date1.month-<NUM_LIT:1>, date1.day, date1.year)<EOL>d2 = (date2.month-<NUM_LIT:1>, date2.day, date2.year)<EOL>urlFmt = '<STR_LIT>'<EOL>url =  urlFmt % (d1[<NUM_LIT:0>], d1[<NUM_LIT:1>], d1[<NUM_LIT:2>],<EOL>d2[<NUM_LIT:0>], d2[<NUM_LIT:1>], d2[<NUM_LIT:2>], ticker)<EOL>if cachename is None:<EOL><INDENT>cachename = os.path.join(cachedir, md5(url).hexdigest())<EOL><DEDENT>if os.path.exists(cachename):<EOL><INDENT>fh = file(cachename)<EOL>verbose.report('<STR_LIT>'%(cachename, ticker))<EOL><DEDENT>else:<EOL><INDENT>if not os.path.isdir(cachedir): os.mkdir(cachedir)<EOL>fh = file(cachename, '<STR_LIT:w>')<EOL>fh.write(urlopen(url).read())<EOL>fh.close()<EOL>verbose.report('<STR_LIT>'%(ticker, cachename))<EOL>fh = file(cachename, '<STR_LIT:r>')<EOL><DEDENT>return fh<EOL>

Fetch historical data for ticker between date1 and date2.  date1 and
date2 are datetime instances

Ex:
fh = fetch_historical_yahoo('^GSPC', d1, d2)

cachename is the name of the local file cache.  If None, will
default to the md5 hash or the url (which incorporates the ticker
and date range)

a file handle is returned


def quotes_historical_yahoo(ticker, date1, date2, asobject=False, adjusted=True, cachename=None):

fh = fetch_historical_yahoo(ticker, date1, date2, cachename)<EOL>try: ret = parse_yahoo_historical(fh, asobject, adjusted)<EOL>except IOError as exc:<EOL><INDENT>warnings.warn('<STR_LIT>' + url + '<STR_LIT:\n>' + exc.strerror[<NUM_LIT:1>])<EOL>return None<EOL><DEDENT>return ret<EOL>

Get historical data for ticker between date1 and date2.  date1 and
date2 are datetime instances

results are a list of tuples

  (d, open, close, high, low, volume)

where d is a floating poing representation of date, as returned by date2num

if asobject is True, the return val is an object with attrs date,
open, close, high, low, volume, which are equal length arrays

if adjust=True, use adjusted prices

Ex:
sp = f.quotes_historical_yahoo('^GSPC', d1, d2, asobject=True, adjusted=True)
returns = (sp.open[1:] - sp.open[:-1])/sp.open[1:]
[n,bins,patches] = hist(returns, 100)
mu = mean(returns)
sigma = std(returns)
x = normpdf(bins, mu, sigma)
plot(bins, x, color='red', lw=2)

cachename is the name of the local file cache.  If None, will
default to the md5 hash or the url (which incorporates the ticker
and date range)


def plot_day_summary(ax, quotes, ticksize=<NUM_LIT:3>,<EOL>colorup='<STR_LIT:k>', colordown='<STR_LIT:r>',<EOL>):

lines = []<EOL>for q in quotes:<EOL><INDENT>t, open, close, high, low = q[:<NUM_LIT:5>]<EOL>if close>=open : color = colorup<EOL>else           : color = colordown<EOL>vline = Line2D(<EOL>xdata=(t, t), ydata=(low, high),<EOL>color=color,<EOL>antialiased=False,   <EOL>)<EOL>oline = Line2D(<EOL>xdata=(t, t), ydata=(open, open),<EOL>color=color,<EOL>antialiased=False,<EOL>marker=TICKLEFT,<EOL>markersize=ticksize,<EOL>)<EOL>cline = Line2D(<EOL>xdata=(t, t), ydata=(close, close),<EOL>color=color,<EOL>antialiased=False,<EOL>markersize=ticksize,<EOL>marker=TICKRIGHT)<EOL>lines.extend((vline, oline, cline))<EOL>ax.add_line(vline)<EOL>ax.add_line(oline)<EOL>ax.add_line(cline)<EOL><DEDENT>ax.autoscale_view()<EOL>return lines<EOL>

quotes is a list of (time, open, close, high, low, ...) tuples

Represent the time, open, close, high, low as a vertical line
ranging from low to high.  The left tick is the open and the right
tick is the close.

time must be in float date format - see date2num

ax          : an Axes instance to plot to
ticksize    : open/close tick marker in points
colorup     : the color of the lines where close >= open
colordown   : the color of the lines where close <  open
return value is a list of lines added


def candlestick(ax, quotes, width=<NUM_LIT>, colorup='<STR_LIT:k>', colordown='<STR_LIT:r>',<EOL>alpha=<NUM_LIT:1.0>):

OFFSET = width/<NUM_LIT><EOL>lines = []<EOL>patches = []<EOL>for q in quotes:<EOL><INDENT>t, open, close, high, low = q[:<NUM_LIT:5>]<EOL>if close>=open :<EOL><INDENT>color = colorup<EOL>lower = open<EOL>height = close-open<EOL><DEDENT>else           :<EOL><INDENT>color = colordown<EOL>lower = close<EOL>height = open-close<EOL><DEDENT>vline = Line2D(<EOL>xdata=(t, t), ydata=(low, high),<EOL>color='<STR_LIT:k>',<EOL>linewidth=<NUM_LIT:0.5>,<EOL>antialiased=True,<EOL>)<EOL>rect = Rectangle(<EOL>xy    = (t-OFFSET, lower),<EOL>width = width,<EOL>height = height,<EOL>facecolor = color,<EOL>edgecolor = color,<EOL>)<EOL>rect.set_alpha(alpha)<EOL>lines.append(vline)<EOL>patches.append(rect)<EOL>ax.add_line(vline)<EOL>ax.add_patch(rect)<EOL><DEDENT>ax.autoscale_view()<EOL>return lines, patches<EOL>

quotes is a list of (time, open, close, high, low, ...)  tuples.
As long as the first 5 elements of the tuples are these values,
the tuple can be as long as you want (eg it may store volume).

time must be in float days format - see date2num

Plot the time, open, close, high, low as a vertical line ranging
from low to high.  Use a rectangular bar to represent the
open-close span.  If close >= open, use colorup to color the bar,
otherwise use colordown

ax          : an Axes instance to plot to
width       : fraction of a day for the rectangle width
colorup     : the color of the rectangle where close >= open
colordown   : the color of the rectangle where close <  open
alpha       : the rectangle alpha level

return value is lines, patches where lines is a list of lines
added and patches is a list of the rectangle patches added


def plot_day_summary2(ax, opens, closes, highs, lows, ticksize=<NUM_LIT:4>,<EOL>colorup='<STR_LIT:k>', colordown='<STR_LIT:r>',<EOL>):

<EOL>rangeSegments = [ ((i, low), (i, high)) for i, low, high in zip(range(len(lows)), lows, highs) if low != -<NUM_LIT:1> ]<EOL>openSegments = [  ((-ticksize, <NUM_LIT:0>), (<NUM_LIT:0>, <NUM_LIT:0>)) ]<EOL>closeSegments = [ ((<NUM_LIT:0>, <NUM_LIT:0>), (ticksize, <NUM_LIT:0>)) ]<EOL>offsetsOpen = [ (i, open) for i, open in zip(range(len(opens)), opens) if open != -<NUM_LIT:1> ]<EOL>offsetsClose = [ (i, close) for i, close in zip(range(len(closes)), closes) if close != -<NUM_LIT:1> ]<EOL>scale = ax.figure.dpi * (<NUM_LIT:1.0>/<NUM_LIT>)<EOL>tickTransform = Affine2D().scale(scale, <NUM_LIT:0.0>)<EOL>r,g,b = colorConverter.to_rgb(colorup)<EOL>colorup = r,g,b,<NUM_LIT:1><EOL>r,g,b = colorConverter.to_rgb(colordown)<EOL>colordown = r,g,b,<NUM_LIT:1><EOL>colord = { True : colorup,<EOL>False : colordown,<EOL>}<EOL>colors = [colord[open<close] for open, close in zip(opens, closes) if open!=-<NUM_LIT:1> and close !=-<NUM_LIT:1>]<EOL>assert(len(rangeSegments)==len(offsetsOpen))<EOL>assert(len(offsetsOpen)==len(offsetsClose))<EOL>assert(len(offsetsClose)==len(colors))<EOL>useAA = <NUM_LIT:0>,   <EOL>lw = <NUM_LIT:1>,      <EOL>rangeCollection = LineCollection(rangeSegments,<EOL>colors       = colors,<EOL>linewidths   = lw,<EOL>antialiaseds = useAA,<EOL>)<EOL>openCollection = LineCollection(openSegments,<EOL>colors       = colors,<EOL>antialiaseds = useAA,<EOL>linewidths   = lw,<EOL>offsets      = offsetsOpen,<EOL>transOffset  = ax.transData,<EOL>)<EOL>openCollection.set_transform(tickTransform)<EOL>closeCollection = LineCollection(closeSegments,<EOL>colors       = colors,<EOL>antialiaseds = useAA,<EOL>linewidths   = lw,<EOL>offsets      = offsetsClose,<EOL>transOffset  = ax.transData,<EOL>)<EOL>closeCollection.set_transform(tickTransform)<EOL>minpy, maxx = (<NUM_LIT:0>, len(rangeSegments))<EOL>miny = min([low for low in lows if low !=-<NUM_LIT:1>])<EOL>maxy = max([high for high in highs if high != -<NUM_LIT:1>])<EOL>corners = (minpy, miny), (maxx, maxy)<EOL>ax.update_datalim(corners)<EOL>ax.autoscale_view()<EOL>ax.add_collection(rangeCollection)<EOL>ax.add_collection(openCollection)<EOL>ax.add_collection(closeCollection)<EOL>return rangeCollection, openCollection, closeCollection<EOL>

Represent the time, open, close, high, low as a vertical line
ranging from low to high.  The left tick is the open and the right
tick is the close.

ax          : an Axes instance to plot to
ticksize    : size of open and close ticks in points
colorup     : the color of the lines where close >= open
colordown   : the color of the lines where close <  open

return value is a list of lines added


def candlestick2(ax, opens, closes, highs, lows, width=<NUM_LIT:4>,<EOL>colorup='<STR_LIT:k>', colordown='<STR_LIT:r>',<EOL>alpha=<NUM_LIT>,<EOL>):

<EOL>delta = width/<NUM_LIT><EOL>barVerts = [ ( (i-delta, open), (i-delta, close), (i+delta, close), (i+delta, open) ) for i, open, close in zip(range(len(opens)), opens, closes) if open != -<NUM_LIT:1> and close!=-<NUM_LIT:1> ]<EOL>rangeSegments = [ ((i, low), (i, high)) for i, low, high in zip(range(len(lows)), lows, highs) if low != -<NUM_LIT:1> ]<EOL>r,g,b = colorConverter.to_rgb(colorup)<EOL>colorup = r,g,b,alpha<EOL>r,g,b = colorConverter.to_rgb(colordown)<EOL>colordown = r,g,b,alpha<EOL>colord = { True : colorup,<EOL>False : colordown,<EOL>}<EOL>colors = [colord[open<close] for open, close in zip(opens, closes) if open!=-<NUM_LIT:1> and close !=-<NUM_LIT:1>]<EOL>assert(len(barVerts)==len(rangeSegments))<EOL>useAA = <NUM_LIT:0>,  <EOL>lw = <NUM_LIT:0.5>,   <EOL>rangeCollection = LineCollection(rangeSegments,<EOL>colors       = ( (<NUM_LIT:0>,<NUM_LIT:0>,<NUM_LIT:0>,<NUM_LIT:1>), ),<EOL>linewidths   = lw,<EOL>antialiaseds = useAA,<EOL>)<EOL>barCollection = PolyCollection(barVerts,<EOL>facecolors   = colors,<EOL>edgecolors   = ( (<NUM_LIT:0>,<NUM_LIT:0>,<NUM_LIT:0>,<NUM_LIT:1>), ),<EOL>antialiaseds = useAA,<EOL>linewidths   = lw,<EOL>)<EOL>minx, maxx = <NUM_LIT:0>, len(rangeSegments)<EOL>miny = min([low for low in lows if low !=-<NUM_LIT:1>])<EOL>maxy = max([high for high in highs if high != -<NUM_LIT:1>])<EOL>corners = (minx, miny), (maxx, maxy)<EOL>ax.update_datalim(corners)<EOL>ax.autoscale_view()<EOL>ax.add_collection(barCollection)<EOL>ax.add_collection(rangeCollection)<EOL>return rangeCollection, barCollection<EOL>

Represent the open, close as a bar line and high low range as a
vertical line.

ax          : an Axes instance to plot to
width       : the bar width in points
colorup     : the color of the lines where close >= open
colordown   : the color of the lines where close <  open
alpha       : bar transparency

return value is lineCollection, barCollection


def volume_overlay(ax, opens, closes, volumes,<EOL>colorup='<STR_LIT:k>', colordown='<STR_LIT:r>',<EOL>width=<NUM_LIT:4>, alpha=<NUM_LIT:1.0>):

r,g,b = colorConverter.to_rgb(colorup)<EOL>colorup = r,g,b,alpha<EOL>r,g,b = colorConverter.to_rgb(colordown)<EOL>colordown = r,g,b,alpha<EOL>colord = { True : colorup,<EOL>False : colordown,<EOL>}<EOL>colors = [colord[open<close] for open, close in zip(opens, closes) if open!=-<NUM_LIT:1> and close !=-<NUM_LIT:1>]<EOL>delta = width/<NUM_LIT><EOL>bars = [ ( (i-delta, <NUM_LIT:0>), (i-delta, v), (i+delta, v), (i+delta, <NUM_LIT:0>)) for i, v in enumerate(volumes) if v != -<NUM_LIT:1> ]<EOL>barCollection = PolyCollection(bars,<EOL>facecolors   = colors,<EOL>edgecolors   = ( (<NUM_LIT:0>,<NUM_LIT:0>,<NUM_LIT:0>,<NUM_LIT:1>), ),<EOL>antialiaseds = (<NUM_LIT:0>,),<EOL>linewidths   = (<NUM_LIT:0.5>,),<EOL>)<EOL>corners = (<NUM_LIT:0>, <NUM_LIT:0>), (len(bars), max(volumes))<EOL>ax.update_datalim(corners)<EOL>ax.autoscale_view()<EOL>return barCollection<EOL>

Add a volume overlay to the current axes.  The opens and closes
are used to determine the color of the bar.  -1 is missing.  If a
value is missing on one it must be missing on all

ax          : an Axes instance to plot to
width       : the bar width in points
colorup     : the color of the lines where close >= open
colordown   : the color of the lines where close <  open
alpha       : bar transparency


def volume_overlay2(ax, closes, volumes,<EOL>colorup='<STR_LIT:k>', colordown='<STR_LIT:r>',<EOL>width=<NUM_LIT:4>, alpha=<NUM_LIT:1.0>):

return volume_overlay(ax,closes[:-<NUM_LIT:1>],closes[<NUM_LIT:1>:],volumes[<NUM_LIT:1>:],colorup,colordown,width,alpha)<EOL>

Add a volume overlay to the current axes.  The closes are used to
determine the color of the bar.  -1 is missing.  If a value is
missing on one it must be missing on all

ax          : an Axes instance to plot to
width       : the bar width in points
colorup     : the color of the lines where close >= open
colordown   : the color of the lines where close <  open
alpha       : bar transparency

nb: first point is not displayed - it is used only for choosing the
right color


def volume_overlay3(ax, quotes,<EOL>colorup='<STR_LIT:k>', colordown='<STR_LIT:r>',<EOL>width=<NUM_LIT:4>, alpha=<NUM_LIT:1.0>):

r,g,b = colorConverter.to_rgb(colorup)<EOL>colorup = r,g,b,alpha<EOL>r,g,b = colorConverter.to_rgb(colordown)<EOL>colordown = r,g,b,alpha<EOL>colord = { True : colorup,<EOL>False : colordown,<EOL>}<EOL>dates, opens, closes, highs, lows, volumes = list(zip(*quotes))<EOL>colors = [colord[close1>=close0] for close0, close1 in zip(closes[:-<NUM_LIT:1>], closes[<NUM_LIT:1>:]) if close0!=-<NUM_LIT:1> and close1 !=-<NUM_LIT:1>]<EOL>colors.insert(<NUM_LIT:0>,colord[closes[<NUM_LIT:0>]>=opens[<NUM_LIT:0>]])<EOL>right = width/<NUM_LIT><EOL>left = -width/<NUM_LIT><EOL>bars = [ ( (left, <NUM_LIT:0>), (left, volume), (right, volume), (right, <NUM_LIT:0>)) for d, open, close, high, low, volume in quotes]<EOL>sx = ax.figure.dpi * (<NUM_LIT:1.0>/<NUM_LIT>)  <EOL>sy = ax.bbox.height / ax.viewLim.height<EOL>barTransform = Affine2D().scale(sx,sy)<EOL>dates = [d for d, open, close, high, low, volume in quotes]<EOL>offsetsBars = [(d, <NUM_LIT:0>) for d in dates]<EOL>useAA = <NUM_LIT:0>,  <EOL>lw = <NUM_LIT:0.5>,   <EOL>barCollection = PolyCollection(bars,<EOL>facecolors   = colors,<EOL>edgecolors   = ( (<NUM_LIT:0>,<NUM_LIT:0>,<NUM_LIT:0>,<NUM_LIT:1>), ),<EOL>antialiaseds = useAA,<EOL>linewidths   = lw,<EOL>offsets      = offsetsBars,<EOL>transOffset  = ax.transData,<EOL>)<EOL>barCollection.set_transform(barTransform)<EOL>minpy, maxx = (min(dates), max(dates))<EOL>miny = <NUM_LIT:0><EOL>maxy = max([volume for d, open, close, high, low, volume in quotes])<EOL>corners = (minpy, miny), (maxx, maxy)<EOL>ax.update_datalim(corners)<EOL>ax.add_collection(barCollection)<EOL>ax.autoscale_view()<EOL>return barCollection<EOL>

Add a volume overlay to the current axes.  quotes is a list of (d,
open, close, high, low, volume) and close-open is used to
determine the color of the bar

kwarg
width       : the bar width in points
colorup     : the color of the lines where close1 >= close0
colordown   : the color of the lines where close1 <  close0
alpha       : bar transparency


def index_bar(ax, vals,<EOL>facecolor='<STR_LIT:b>', edgecolor='<STR_LIT:l>',<EOL>width=<NUM_LIT:4>, alpha=<NUM_LIT:1.0>, ):

facecolors = (colorConverter.to_rgba(facecolor, alpha),)<EOL>edgecolors = (colorConverter.to_rgba(edgecolor, alpha),)<EOL>right = width/<NUM_LIT><EOL>left = -width/<NUM_LIT><EOL>bars = [ ( (left, <NUM_LIT:0>), (left, v), (right, v), (right, <NUM_LIT:0>)) for v in vals if v != -<NUM_LIT:1> ]<EOL>sx = ax.figure.dpi * (<NUM_LIT:1.0>/<NUM_LIT>)  <EOL>sy = ax.bbox.height / ax.viewLim.height<EOL>barTransform = Affine2D().scale(sx,sy)<EOL>offsetsBars = [ (i, <NUM_LIT:0>) for i,v in enumerate(vals) if v != -<NUM_LIT:1> ]<EOL>barCollection = PolyCollection(bars,<EOL>facecolors   = facecolors,<EOL>edgecolors   = edgecolors,<EOL>antialiaseds = (<NUM_LIT:0>,),<EOL>linewidths   = (<NUM_LIT:0.5>,),<EOL>offsets      = offsetsBars,<EOL>transOffset  = ax.transData,<EOL>)<EOL>barCollection.set_transform(barTransform)<EOL>minpy, maxx = (<NUM_LIT:0>, len(offsetsBars))<EOL>miny = <NUM_LIT:0><EOL>maxy = max([v for v in vals if v!=-<NUM_LIT:1>])<EOL>corners = (minpy, miny), (maxx, maxy)<EOL>ax.update_datalim(corners)<EOL>ax.autoscale_view()<EOL>ax.add_collection(barCollection)<EOL>return barCollection<EOL>

Add a bar collection graph with height vals (-1 is missing).

ax          : an Axes instance to plot to
width       : the bar width in points
alpha       : bar transparency


return (loc<len(strg) and strg[loc] == '<STR_LIT:\n>') and <NUM_LIT:1> or loc - strg.rfind("<STR_LIT:\n>", <NUM_LIT:0>, loc)<EOL>

Returns current column within a string, counting newlines as line separators.
   The first column is number 1.

   Note: the default parsing behavior is to expand tabs in the input string
   before starting the parsing process.  See L{I{ParserElement.parseString}<ParserElement.parseString>} for more information
   on parsing strings containing <TAB>s, and suggested methods to maintain a
   consistent view of the parsed string, the parse location, and line and column
   positions within the parsed string.


return strg.count("<STR_LIT:\n>",<NUM_LIT:0>,loc) + <NUM_LIT:1><EOL>

Returns current line number within a string, counting newlines as line separators.
   The first line is number 1.

   Note: the default parsing behavior is to expand tabs in the input string
   before starting the parsing process.  See L{I{ParserElement.parseString}<ParserElement.parseString>} for more information
   on parsing strings containing <TAB>s, and suggested methods to maintain a
   consistent view of the parsed string, the parse location, and line and column
   positions within the parsed string.


lastCR = strg.rfind("<STR_LIT:\n>", <NUM_LIT:0>, loc)<EOL>nextCR = strg.find("<STR_LIT:\n>", loc)<EOL>if nextCR > <NUM_LIT:0>:<EOL><INDENT>return strg[lastCR+<NUM_LIT:1>:nextCR]<EOL><DEDENT>else:<EOL><INDENT>return strg[lastCR+<NUM_LIT:1>:]<EOL><DEDENT>

Returns the line of text containing loc within a string, counting newlines as line separators.


pass<EOL>

Do-nothing' debug action, to suppress debugging output during parsing.


f = ParserElement._normalizeParseActionArgs(f)<EOL>def z(*paArgs):<EOL><INDENT>thisFunc = f.__name__<EOL>s,l,t = paArgs[-<NUM_LIT:3>:]<EOL>if len(paArgs)><NUM_LIT:3>:<EOL><INDENT>thisFunc = paArgs[<NUM_LIT:0>].__class__.__name__ + '<STR_LIT:.>' + thisFunc<EOL><DEDENT>sys.stderr.write( "<STR_LIT>" % (thisFunc,line(l,s),l,t) )<EOL>try:<EOL><INDENT>ret = f(*paArgs)<EOL><DEDENT>except Exception as exc:<EOL><INDENT>sys.stderr.write( "<STR_LIT>" % (thisFunc,exc) )<EOL>raise<EOL><DEDENT>sys.stderr.write( "<STR_LIT>" % (thisFunc,ret) )<EOL>return ret<EOL><DEDENT>try:<EOL><INDENT>z.__name__ = f.__name__<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT>return z<EOL>