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.width  = w<EOL>self.height = h<EOL>self.depth  = d<EOL>


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 render_filled_rect(self, x1, y1, x2, y2):

raise NotImplementedError()<EOL>

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


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


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 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 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 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 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


return Suppress( self )<EOL>

Suppresses the output of this ParserElement; useful to keep punctuation from
           cluttering up returned output.


self.checkRecursion( [] )<EOL>

Check defined expressions for valid structure, check for infinite recursive definitions.


if self.__name:<EOL><INDENT>return self.__name<EOL><DEDENT>elif self.__parent:<EOL><INDENT>par = self.__parent()<EOL>if par:<EOL><INDENT>return par.__lookup(self)<EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT><DEDENT>elif (len(self) == <NUM_LIT:1> and<EOL>len(self.__tokdict) == <NUM_LIT:1> and<EOL>list(self.__tokdict.values())[<NUM_LIT:0>][<NUM_LIT:0>][<NUM_LIT:1>] in (<NUM_LIT:0>,-<NUM_LIT:1>)):<EOL><INDENT>return list(self.__tokdict.keys())[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>

Returns the results name for this token expression.


if isinstance( other, str ):<EOL><INDENT>other = Literal( other )<EOL><DEDENT>if not isinstance( other, ParserElement ):<EOL><INDENT>warnings.warn("<STR_LIT>" % type(other),<EOL>SyntaxWarning, stacklevel=<NUM_LIT:2>)<EOL>return None<EOL><DEDENT>return other | self<EOL>

Implementation of | operator when left operand is not a ParserElement


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.


self.skipWhitespace = False<EOL>return self<EOL>

Disables the skipping of whitespace before matching the characters in the
           ParserElement's defined pattern.  This is normally only used internally by
           the pyparsing module, but may be needed in some whitespace-sensitive grammars.


out = []<EOL>for res in self.__toklist:<EOL><INDENT>if isinstance(res,ParseResults):<EOL><INDENT>out.append( res.asList() )<EOL><DEDENT>else:<EOL><INDENT>out.append( res )<EOL><DEDENT><DEDENT>return out<EOL>

Returns the parse results as a nested list of matching tokens, all converted to strings.


out = []<EOL>out.append( indent+_ustr(self.asList()) )<EOL>keys = list(self.items())<EOL>keys.sort()<EOL>for k,v in keys:<EOL><INDENT>if out:<EOL><INDENT>out.append('<STR_LIT:\n>')<EOL><DEDENT>out.append( "<STR_LIT>" % (indent,('<STR_LIT:U+0020>'*depth), k) )<EOL>if isinstance(v,ParseResults):<EOL><INDENT>if list(v.keys()):<EOL><INDENT>out.append( v.dump(indent,depth+<NUM_LIT:1>) )<EOL><DEDENT>else:<EOL><INDENT>out.append(_ustr(v))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>out.append(_ustr(v))<EOL><DEDENT><DEDENT>return "<STR_LIT>".join(out)<EOL>

Diagnostic method for listing out the contents of a ParseResults.
           Accepts an optional indent argument so that this string can be embedded
           in a nested display of other data.


try:<EOL><INDENT>return "<STR_LIT>".join([_expanded(part) for part in _reBracketExpr.parseString(s).body])<EOL><DEDENT>except:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>

r"""Helper to easily define string ranges for use in Word construction.  Borrows
       syntax from regexp '[]' string range definitions::
          srange("[0-9]")   -> "0123456789"
          srange("[a-z]")   -> "abcdefghijklmnopqrstuvwxyz"
          srange("[a-z$_]") -> "abcdefghijklmnopqrstuvwxyz$_"
       The input string must be enclosed in []'s, and the returned string is the expanded
       character set joined into a single string.
       The values enclosed in the []'s may be::
          a single character
          an escaped character with a leading backslash (such as \- or \])
          an escaped hex character with a leading '\0x' (\0x21, which is a '!' character)
          an escaped octal character with a leading '\0' (\041, which is a '!' character)
          a range of any of the above, separated by a dash ('a-z', etc.)
          any combination of the above ('aeiouy', 'a-zA-Z0-9_$', etc.)


def oneOf( strs, caseless=False, useRegex=True ):

if caseless:<EOL><INDENT>isequal = ( lambda a,b: a.upper() == b.upper() )<EOL>masks = ( lambda a,b: b.upper().startswith(a.upper()) )<EOL>parseElementClass = CaselessLiteral<EOL><DEDENT>else:<EOL><INDENT>isequal = ( lambda a,b: a == b )<EOL>masks = ( lambda a,b: b.startswith(a) )<EOL>parseElementClass = Literal<EOL><DEDENT>if isinstance(strs,(list,tuple)):<EOL><INDENT>symbols = strs[:]<EOL><DEDENT>elif isinstance(strs,str):<EOL><INDENT>symbols = strs.split()<EOL><DEDENT>else:<EOL><INDENT>warnings.warn("<STR_LIT>",<EOL>SyntaxWarning, stacklevel=<NUM_LIT:2>)<EOL><DEDENT>i = <NUM_LIT:0><EOL>while i < len(symbols)-<NUM_LIT:1>:<EOL><INDENT>cur = symbols[i]<EOL>for j,other in enumerate(symbols[i+<NUM_LIT:1>:]):<EOL><INDENT>if ( isequal(other, cur) ):<EOL><INDENT>del symbols[i+j+<NUM_LIT:1>]<EOL>break<EOL><DEDENT>elif ( masks(cur, other) ):<EOL><INDENT>del symbols[i+j+<NUM_LIT:1>]<EOL>symbols.insert(i,other)<EOL>cur = other<EOL>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>i += <NUM_LIT:1><EOL><DEDENT><DEDENT>if not caseless and useRegex:<EOL><INDENT>try:<EOL><INDENT>if len(symbols)==len("<STR_LIT>".join(symbols)):<EOL><INDENT>return Regex( "<STR_LIT>" % "<STR_LIT>".join( [ _escapeRegexRangeChars(sym) for sym in symbols] ) )<EOL><DEDENT>else:<EOL><INDENT>return Regex( "<STR_LIT:|>".join( [ re.escape(sym) for sym in symbols] ) )<EOL><DEDENT><DEDENT>except:<EOL><INDENT>warnings.warn("<STR_LIT>",<EOL>SyntaxWarning, stacklevel=<NUM_LIT:2>)<EOL><DEDENT><DEDENT>return MatchFirst( [ parseElementClass(sym) for sym in symbols ] )<EOL>

Helper to quickly define a set of alternative Literals, and makes sure to do
       longest-first testing when there is a conflict, regardless of the input order,
       but returns a MatchFirst for best performance.

       Parameters:
        - strs - a string of space-delimited literals, or a list of string literals
        - caseless - (default=False) - treat all literals as caseless
        - useRegex - (default=True) - as an optimization, will generate a Regex
          object; otherwise, will generate a MatchFirst object (if caseless=True, or
          if creating a Regex raises an exception)


if isinstance( other, str ):<EOL><INDENT>other = Literal( other )<EOL><DEDENT>if not isinstance( other, ParserElement ):<EOL><INDENT>warnings.warn("<STR_LIT>" % type(other),<EOL>SyntaxWarning, stacklevel=<NUM_LIT:2>)<EOL>return None<EOL><DEDENT>return other ^ self<EOL>

Implementation of ^ operator when left operand is not a ParserElement


if isinstance( other, str ):<EOL><INDENT>other = Literal( other )<EOL><DEDENT>if not isinstance( other, ParserElement ):<EOL><INDENT>warnings.warn("<STR_LIT>" % type(other),<EOL>SyntaxWarning, stacklevel=<NUM_LIT:2>)<EOL>return None<EOL><DEDENT>return And( [ self, other ] )<EOL>

Implementation of + operator - returns And


return dict( list(self.items()) )<EOL>

Returns the named parse results as dictionary.


def parseFile( self, file_or_filename ):

try:<EOL><INDENT>file_contents = file_or_filename.read()<EOL><DEDENT>except AttributeError:<EOL><INDENT>f = open(file_or_filename, "<STR_LIT:rb>")<EOL>file_contents = f.read()<EOL>f.close()<EOL><DEDENT>return self.parseString(file_contents)<EOL>

Execute the parse expression on the given file or filename.
           If a filename is specified (instead of a file object),
           the entire file is opened, read, and closed before parsing.


rep = Forward()<EOL>def copyTokenToRepeater(s,l,t):<EOL><INDENT>if t:<EOL><INDENT>if len(t) == <NUM_LIT:1>:<EOL><INDENT>rep << t[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>tflat = _flatten(t.asList())<EOL>rep << And( [ Literal(tt) for tt in tflat ] )<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rep << Empty()<EOL><DEDENT><DEDENT>expr.addParseAction(copyTokenToRepeater, callDuringTry=True)<EOL>return rep<EOL>

Helper to define an expression that is indirectly defined from
       the tokens matched in a previous expression, that is, it looks
       for a 'repeat' of a previous expression.  For example::
           first = Word(nums)
           second = matchPreviousLiteral(first)
           matchExpr = first + ":" + second
       will match "1:1", but not "1:2".  Because this matches a
       previous literal, will also match the leading "1:1" in "1:10".
       If this is not desired, use matchPreviousExpr.
       Do *not* use with packrat parsing enabled.


if isinstance( other, str ):<EOL><INDENT>other = Literal( other )<EOL><DEDENT>if not isinstance( other, ParserElement ):<EOL><INDENT>warnings.warn("<STR_LIT>" % type(other),<EOL>SyntaxWarning, stacklevel=<NUM_LIT:2>)<EOL>return None<EOL><DEDENT>return And( [ self, And._ErrorStop(), other ] )<EOL>

Implementation of - operator, returns And with error stop


if isinstance( other, str ):<EOL><INDENT>other = Literal( other )<EOL><DEDENT>if not isinstance( other, ParserElement ):<EOL><INDENT>warnings.warn("<STR_LIT>" % type(other),<EOL>SyntaxWarning, stacklevel=<NUM_LIT:2>)<EOL>return None<EOL><DEDENT>return MatchFirst( [ self, other ] )<EOL>

Implementation of | operator - returns MatchFirst


def __init__( self, quoteChar, escChar=None, escQuote=None, multiline=False, unquoteResults=True, endQuoteChar=None):

super(QuotedString,self).__init__()<EOL>quoteChar = quoteChar.strip()<EOL>if len(quoteChar) == <NUM_LIT:0>:<EOL><INDENT>warnings.warn("<STR_LIT>",SyntaxWarning,stacklevel=<NUM_LIT:2>)<EOL>raise SyntaxError()<EOL><DEDENT>if endQuoteChar is None:<EOL><INDENT>endQuoteChar = quoteChar<EOL><DEDENT>else:<EOL><INDENT>endQuoteChar = endQuoteChar.strip()<EOL>if len(endQuoteChar) == <NUM_LIT:0>:<EOL><INDENT>warnings.warn("<STR_LIT>",SyntaxWarning,stacklevel=<NUM_LIT:2>)<EOL>raise SyntaxError()<EOL><DEDENT><DEDENT>self.quoteChar = quoteChar<EOL>self.quoteCharLen = len(quoteChar)<EOL>self.firstQuoteChar = quoteChar[<NUM_LIT:0>]<EOL>self.endQuoteChar = endQuoteChar<EOL>self.endQuoteCharLen = len(endQuoteChar)<EOL>self.escChar = escChar<EOL>self.escQuote = escQuote<EOL>self.unquoteResults = unquoteResults<EOL>if multiline:<EOL><INDENT>self.flags = re.MULTILINE | re.DOTALL<EOL>self.pattern = r'<STR_LIT>' %( re.escape(self.quoteChar),<EOL>_escapeRegexRangeChars(self.endQuoteChar[<NUM_LIT:0>]),<EOL>(escChar is not None and _escapeRegexRangeChars(escChar) or '<STR_LIT>') )<EOL><DEDENT>else:<EOL><INDENT>self.flags = <NUM_LIT:0><EOL>self.pattern = r'<STR_LIT>' %( re.escape(self.quoteChar),<EOL>_escapeRegexRangeChars(self.endQuoteChar[<NUM_LIT:0>]),<EOL>(escChar is not None and _escapeRegexRangeChars(escChar) or '<STR_LIT>') )<EOL><DEDENT>if len(self.endQuoteChar) > <NUM_LIT:1>:<EOL><INDENT>self.pattern += (<EOL>'<STR_LIT>' + '<STR_LIT>'.join(["<STR_LIT>" % (re.escape(self.endQuoteChar[:i]),<EOL>_escapeRegexRangeChars(self.endQuoteChar[i]))<EOL>for i in range(len(self.endQuoteChar)-<NUM_LIT:1>,<NUM_LIT:0>,-<NUM_LIT:1>)]) + '<STR_LIT:)>'<EOL>)<EOL><DEDENT>if escQuote:<EOL><INDENT>self.pattern += (r'<STR_LIT>' % re.escape(escQuote))<EOL><DEDENT>if escChar:<EOL><INDENT>self.pattern += (r'<STR_LIT>' % re.escape(escChar))<EOL>self.escCharReplacePattern = re.escape(self.escChar)+"<STR_LIT>"<EOL><DEDENT>self.pattern += (r'<STR_LIT>' % re.escape(self.endQuoteChar))<EOL>try:<EOL><INDENT>self.re = re.compile(self.pattern, self.flags)<EOL>self.reString = self.pattern<EOL><DEDENT>except sre_constants.error:<EOL><INDENT>warnings.warn("<STR_LIT>" % self.pattern,<EOL>SyntaxWarning, stacklevel=<NUM_LIT:2>)<EOL>raise<EOL><DEDENT>self.name = _ustr(self)<EOL>self.errmsg = "<STR_LIT>" + self.name<EOL>self.mayIndexError = False<EOL>self.mayReturnEmpty = True<EOL>

Defined with the following parameters:
 - quoteChar - string of one or more characters defining the quote delimiting string
 - escChar - character to escape quotes, typically backslash (default=None)
 - escQuote - special quote sequence to escape an embedded quote string (such as SQL's "" to escape an embedded ") (default=None)
 - multiline - boolean indicating whether quotes can span multiple lines (default=False)
 - unquoteResults - boolean indicating whether the matched text should be unquoted (default=True)
 - endQuoteChar - string of one or more characters defining the end of the quote delimited string (default=None => same as quoteChar)


Keyword.DEFAULT_KEYWORD_CHARS = chars<EOL>


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>


return list(self.__tokdict.keys())<EOL>


self.name = name<EOL>self.errmsg = "<STR_LIT>" + self.name<EOL>if hasattr(self,"<STR_LIT>"):<EOL><INDENT>self.exception.msg = self.errmsg<EOL><DEDENT>return self<EOL>

Define name for this expression, for use in debugging.


return _makeTags( tagStr, True )<EOL>

Helper to construct opening and closing tag expressions for XML, given a tag name


try:<EOL><INDENT>endloc = getTokensEndLoc()<EOL><DEDENT>except ParseException:<EOL><INDENT>raise ParseFatalException("<STR_LIT>")<EOL><DEDENT>del t[:]<EOL>t += ParseResults(s[startLoc:endloc])<EOL>return t<EOL>

Helper parse action to preserve original parsed text,
       overriding any nested parse actions.


out = []<EOL>lastE = <NUM_LIT:0><EOL>self.keepTabs = True<EOL>for t,s,e in self.scanString( instring ):<EOL><INDENT>out.append( instring[lastE:s] )<EOL>if t:<EOL><INDENT>if isinstance(t,ParseResults):<EOL><INDENT>out += t.asList()<EOL><DEDENT>elif isinstance(t,list):<EOL><INDENT>out += t<EOL><DEDENT>else:<EOL><INDENT>out.append(t)<EOL><DEDENT><DEDENT>lastE = e<EOL><DEDENT>out.append(instring[lastE:])<EOL>return "<STR_LIT>".join(map(_ustr,out))<EOL>

Extension to scanString, to modify matching text with modified tokens that may
           be returned from a parse action.  To use transformString, define a grammar and
           attach a parse action to it that modifies the returned token list.
           Invoking transformString() on a target string will then scan for matches,
           and replace the matched text patterns according to the logic in the parse
           action.  transformString() returns the resulting transformed string.


if flag:<EOL><INDENT>self.setDebugActions( _defaultStartDebugAction, _defaultSuccessDebugAction, _defaultExceptionDebugAction )<EOL><DEDENT>else:<EOL><INDENT>self.debug = False<EOL><DEDENT>return self<EOL>

Enable display of debugging messages while doing pattern matching.
           Set flag to True to enable, False to disable.


if isinstance( other, str ):<EOL><INDENT>other = Literal( other )<EOL><DEDENT>if not isinstance( other, ParserElement ):<EOL><INDENT>warnings.warn("<STR_LIT>" % type(other),<EOL>SyntaxWarning, stacklevel=<NUM_LIT:2>)<EOL>return None<EOL><DEDENT>return Or( [ self, other ] )<EOL>

Implementation of ^ operator - returns Or


def delimitedList( expr, delim="<STR_LIT:U+002C>", combine=False ):

dlName = _ustr(expr)+"<STR_LIT>"+_ustr(delim)+"<STR_LIT:U+0020>"+_ustr(expr)+"<STR_LIT>"<EOL>if combine:<EOL><INDENT>return Combine( expr + ZeroOrMore( delim + expr ) ).setName(dlName)<EOL><DEDENT>else:<EOL><INDENT>return ( expr + ZeroOrMore( Suppress( delim ) + expr ) ).setName(dlName)<EOL><DEDENT>

Helper to define a delimited list of expressions - the delimiter defaults to ','.
       By default, the list elements and delimiters can have intervening whitespace, and
       comments, but this can be overridden by passing 'combine=True' in the constructor.
       If combine is set to True, the matching tokens are returned as a single token
       string, with the delimiters included; otherwise, the matching tokens are returned
       as a list of tokens, with the delimiters suppressed.


def setResultsName( self, name, listAllMatches=False ):

newself = self.copy()<EOL>newself.resultsName = name<EOL>newself.modalResults = not listAllMatches<EOL>return newself<EOL>

Define name for referencing matching tokens as a nested attribute
           of the returned parse results.
           NOTE: this returns a *copy* of the original ParserElement object;
           this is so that the client can define a basic element, such as an
           integer, and reference it in multiple places with different names.


import inspect<EOL>fstack = inspect.stack()<EOL>try:<EOL><INDENT>for f in fstack[<NUM_LIT:2>:]:<EOL><INDENT>if f[<NUM_LIT:3>] == "<STR_LIT>":<EOL><INDENT>endloc = f[<NUM_LIT:0>].f_locals["<STR_LIT>"]<EOL>return endloc<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise ParseFatalException("<STR_LIT>")<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>del fstack<EOL><DEDENT>

Method to be called from within a parse action to determine the end
       location of the parsed tokens.


return [ v[-<NUM_LIT:1>][<NUM_LIT:0>] for v in list(self.__tokdict.values()) ]<EOL>


def asXML( self, doctag=None, namedItemsOnly=False, indent="<STR_LIT>", formatted=True ):

nl = "<STR_LIT:\n>"<EOL>out = []<EOL>namedItems = dict( [ (v[<NUM_LIT:1>],k) for (k,vlist) in list(self.__tokdict.items())<EOL>for v in vlist ] )<EOL>nextLevelIndent = indent + "<STR_LIT:U+0020>"<EOL>if not formatted:<EOL><INDENT>indent = "<STR_LIT>"<EOL>nextLevelIndent = "<STR_LIT>"<EOL>nl = "<STR_LIT>"<EOL><DEDENT>selfTag = None<EOL>if doctag is not None:<EOL><INDENT>selfTag = doctag<EOL><DEDENT>else:<EOL><INDENT>if self.__name:<EOL><INDENT>selfTag = self.__name<EOL><DEDENT><DEDENT>if not selfTag:<EOL><INDENT>if namedItemsOnly:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>selfTag = "<STR_LIT>"<EOL><DEDENT><DEDENT>out += [ nl, indent, "<STR_LIT:<>", selfTag, "<STR_LIT:>>" ]<EOL>worklist = self.__toklist<EOL>for i,res in enumerate(worklist):<EOL><INDENT>if isinstance(res,ParseResults):<EOL><INDENT>if i in namedItems:<EOL><INDENT>out += [ res.asXML(namedItems[i],<EOL>namedItemsOnly and doctag is None,<EOL>nextLevelIndent,<EOL>formatted)]<EOL><DEDENT>else:<EOL><INDENT>out += [ res.asXML(None,<EOL>namedItemsOnly and doctag is None,<EOL>nextLevelIndent,<EOL>formatted)]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>resTag = None<EOL>if i in namedItems:<EOL><INDENT>resTag = namedItems[i]<EOL><DEDENT>if not resTag:<EOL><INDENT>if namedItemsOnly:<EOL><INDENT>continue<EOL><DEDENT>else:<EOL><INDENT>resTag = "<STR_LIT>"<EOL><DEDENT><DEDENT>xmlBodyText = xml.sax.saxutils.escape(_ustr(res))<EOL>out += [ nl, nextLevelIndent, "<STR_LIT:<>", resTag, "<STR_LIT:>>",<EOL>xmlBodyText,<EOL>"<STR_LIT>", resTag, "<STR_LIT:>>" ]<EOL><DEDENT><DEDENT>out += [ nl, indent, "<STR_LIT>", selfTag, "<STR_LIT:>>" ]<EOL>return "<STR_LIT>".join(out)<EOL>

Returns the parse results as XML. Tags are created for tokens and lists that have defined results names.


ParserElement.DEFAULT_WHITE_CHARS = chars<EOL>


return _makeTags( tagStr, False )<EOL>

Helper to construct opening and closing tag expressions for HTML, given a tag name


if not ParserElement._packratEnabled:<EOL><INDENT>ParserElement._packratEnabled = True<EOL>ParserElement._parse = ParserElement._parseCache<EOL><DEDENT>

Enables "packrat" parsing, which adds memoizing to the parsing logic.
           Repeated parse attempts at the same string location (which happens
           often in many complex grammars) can immediately return a cached value,
           instead of re-executing parsing/validating code.  Memoizing is done of
           both valid results and parsing exceptions.

           This speedup may break existing programs that use parse actions that
           have side-effects.  For this reason, packrat parsing is disabled when
           you first import pyparsing.  To activate the packrat feature, your
           program must call the class method ParserElement.enablePackrat().  If
           your program uses psyco to "compile as you go", you must call
           enablePackrat before calling psyco.full().  If you do not do this,
           Python will crash.  For best results, call enablePackrat() immediately
           after importing pyparsing.


return [(k,self[k]) for k in self.__tokdict]<EOL>

Returns all named result keys and values as a list of tuples.


def markInputline( self, markerString = "<STR_LIT>" ):

line_str = self.line<EOL>line_column = self.column - <NUM_LIT:1><EOL>if markerString:<EOL><INDENT>line_str = "<STR_LIT>".join( [line_str[:line_column],<EOL>markerString, line_str[line_column:]])<EOL><DEDENT>return line_str.strip()<EOL>

Extracts the exception line from the input string, and marks
           the location of the exception with a special symbol.


if args:<EOL><INDENT>attrs = args[:]<EOL><DEDENT>else:<EOL><INDENT>attrs = list(attrDict.items())<EOL><DEDENT>attrs = [(k,v) for k,v in attrs]<EOL>def pa(s,l,tokens):<EOL><INDENT>for attrName,attrValue in attrs:<EOL><INDENT>if attrName not in tokens:<EOL><INDENT>raise ParseException(s,l,"<STR_LIT>" + attrName)<EOL><DEDENT>if attrValue != withAttribute.ANY_VALUE and tokens[attrName] != attrValue:<EOL><INDENT>raise ParseException(s,l,"<STR_LIT>" %<EOL>(attrName, tokens[attrName], attrValue))<EOL><DEDENT><DEDENT><DEDENT>return pa<EOL>

Helper to create a validating parse action to be used with start tags created
       with makeXMLTags or makeHTMLTags. Use withAttribute to qualify a starting tag
       with a required attribute value, to avoid false matches on common tags such as
       <TD> or <DIV>.

       Call withAttribute with a series of attribute names and values. Specify the list
       of filter attributes names and values as:
        - keyword arguments, as in (class="Customer",align="right"), or
        - a list of name-value tuples, as in ( ("ns1:class", "Customer"), ("ns2:align","right") )
       For attribute names with a namespace prefix, you must use the second form.  Attribute
       names are matched insensitive to upper/lower case.

       To verify that the attribute exists, but without specifying a value, pass
       withAttribute.ANY_VALUE as the value.


def parseString( self, instring, parseAll=False ):

ParserElement.resetCache()<EOL>if not self.streamlined:<EOL><INDENT>self.streamline()<EOL><DEDENT>for e in self.ignoreExprs:<EOL><INDENT>e.streamline()<EOL><DEDENT>if not self.keepTabs:<EOL><INDENT>instring = instring.expandtabs()<EOL><DEDENT>loc, tokens = self._parse( instring, <NUM_LIT:0> )<EOL>if parseAll:<EOL><INDENT>StringEnd()._parse( instring, loc )<EOL><DEDENT>return tokens<EOL>

Execute the parse expression with the given string.
           This is the main interface to the client code, once the complete
           expression has been built.

           If you want the grammar to require that the entire input string be
           successfully parsed, then set parseAll to True (equivalent to ending
           the grammar with StringEnd()).

           Note: parseString implicitly calls expandtabs() on the input string,
           in order to report proper column numbers in parse actions.
           If the input string contains tabs and
           the grammar uses parse actions that use the loc argument to index into the
           string being parsed, you can ensure you have a consistent view of the input
           string by:
            - calling parseWithTabs on your grammar before calling parseString
              (see L{I{parseWithTabs}<parseWithTabs>})
            - define your parse action using the full (s,loc,toks) signature, and
              reference the input string using the parse action's s argument
            - explictly expand the tabs in your input string before calling
              parseString


arrayExpr = Forward()<EOL>def countFieldParseAction(s,l,t):<EOL><INDENT>n = int(t[<NUM_LIT:0>])<EOL>arrayExpr << (n and Group(And([expr]*n)) or Group(empty))<EOL>return []<EOL><DEDENT>return ( Word(nums).setName("<STR_LIT>").setParseAction(countFieldParseAction, callDuringTry=True) + arrayExpr )<EOL>

Helper to define a counted list of expressions.
       This helper defines a pattern of the form::
           integer expr expr expr...
       where the leading integer tells how many expr expressions follow.
       The matched tokens returns the array of expr tokens as a list - the leading count token is suppressed.


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.


if key in self:<EOL><INDENT>return self[key]<EOL><DEDENT>else:<EOL><INDENT>return defaultValue<EOL><DEDENT>

Returns named result matching the given key, or if there is no
           such name, then returns the given defaultValue or None if no
           defaultValue is specified.


def setDebugActions( self, startAction, successAction, exceptionAction ):

self.debugActions = (startAction or _defaultStartDebugAction,<EOL>successAction or _defaultSuccessDebugAction,<EOL>exceptionAction or _defaultExceptionDebugAction)<EOL>self.debug = True<EOL>return self<EOL>

Enable display of debugging messages while doing pattern matching.


ret = ParseResults( self.__toklist )<EOL>ret.__tokdict = self.__tokdict.copy()<EOL>ret.__parent = self.__parent<EOL>ret.__accumNames.update( self.__accumNames )<EOL>ret.__name = self.__name<EOL>return ret<EOL>

Returns a new copy of a ParseResults object.


self.skipWhitespace = False<EOL>self.exprs = [ e.copy() for e in self.exprs ]<EOL>for e in self.exprs:<EOL><INDENT>e.leaveWhitespace()<EOL><DEDENT>return self<EOL>

Extends leaveWhitespace defined in base class, and also invokes leaveWhitespace on
           all contained expressions.


def __init__( self, pattern, flags=<NUM_LIT:0>):

super(Regex,self).__init__()<EOL>if len(pattern) == <NUM_LIT:0>:<EOL><INDENT>warnings.warn("<STR_LIT>",<EOL>SyntaxWarning, stacklevel=<NUM_LIT:2>)<EOL><DEDENT>self.pattern = pattern<EOL>self.flags = flags<EOL>try:<EOL><INDENT>self.re = re.compile(self.pattern, self.flags)<EOL>self.reString = self.pattern<EOL><DEDENT>except sre_constants.error:<EOL><INDENT>warnings.warn("<STR_LIT>" % pattern,<EOL>SyntaxWarning, stacklevel=<NUM_LIT:2>)<EOL>raise<EOL><DEDENT>self.name = _ustr(self)<EOL>self.errmsg = "<STR_LIT>" + self.name<EOL>self.mayIndexError = False<EOL>self.mayReturnEmpty = True<EOL>

The parameters pattern and flags are passed to the re.compile() function as-is. See the Python re module for an explanation of the acceptable patterns and flags.


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.


Set the aspect ratio of the bbox mutation.

ACCEPTS: float


def set_connectionstyle(self, connectionstyle, **kw):

if connectionstyle==None:<EOL><INDENT>return ConnectionStyle.pprint_styles()<EOL><DEDENT>if isinstance(connectionstyle, ConnectionStyle._Base):<EOL><INDENT>self._connector = connectionstyle<EOL><DEDENT>elif callable(connectionstyle):<EOL><INDENT>self._connector = connectionstyle<EOL><DEDENT>else:<EOL><INDENT>self._connector = ConnectionStyle(connectionstyle, **kw)<EOL><DEDENT>

Set the connection style.

*connectionstyle* can be a string with connectionstyle name with optional
 comma-separated attributes. Alternatively, the attrs can
 be probided as keywords.

 set_connectionstyle("arc,angleA=0,armA=30,rad=10")
 set_connectionstyle("arc", angleA=0,armA=30,rad=10)

Old attrs simply are forgotten.

Without argument (or with connectionstyle=None), return
available styles as a list of strings.


self._x = x<EOL>

Set the left coord of the rectangle

ACCEPTS: float


def __init__(self, xy, width, height, angle=<NUM_LIT:0.0>, theta1=<NUM_LIT:0.0>, theta2=<NUM_LIT>, **kwargs):

fill = kwargs.pop('<STR_LIT>')<EOL>if fill:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>kwargs['<STR_LIT>'] = False<EOL>Ellipse.__init__(self, xy, width, height, angle, **kwargs)<EOL>self.theta1 = theta1<EOL>self.theta2 = theta2<EOL>

The following args are supported:

*xy*
  center of ellipse

*width*
  length of horizontal axis

*height*
  length of vertical axis

*angle*
  rotation in degrees (anti-clockwise)

*theta1*
  starting angle of the arc in degrees

*theta2*
  ending angle of the arc in degrees

If *theta1* and *theta2* are not provided, the arc will form a
complete ellipse.

Valid kwargs are:

%(Patch)s


def __init__(self, xy, radius=<NUM_LIT:5>,<EOL>resolution=<NUM_LIT:20>,  <EOL>**kwargs):

RegularPolygon.__init__(self, xy,<EOL>resolution,<EOL>radius,<EOL>orientation=<NUM_LIT:0>,<EOL>**kwargs)<EOL>

Create a circle at *xy* = (*x*, *y*) with given *radius*.
This circle is approximated by a regular polygon with
*resolution* sides.  For a smoother circle drawn with splines,
see :class:`~matplotlib.patches.Circle`.

Valid kwargs are:
%(Patch)s


Patch.__init__(self, **kwargs)<EOL>self._x = xy[<NUM_LIT:0>]<EOL>self._y = xy[<NUM_LIT:1>]<EOL>self._width = width<EOL>self._height = height<EOL>if boxstyle == "<STR_LIT>":<EOL><INDENT>if bbox_transmuter is None:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>self._bbox_transmuter = bbox_transmuter<EOL><DEDENT>else:<EOL><INDENT>self.set_boxstyle(boxstyle)<EOL><DEDENT>self._mutation_scale=mutation_scale<EOL>self._mutation_aspect=mutation_aspect<EOL>

*xy* = lower left corner

*width*, *height*

*boxstyle* determines what kind of fancy box will be drawn. It
can be a string of the style name with a comma separated
attribute, or an instance of :class:`BoxStyle`. Following box
styles are available.

%(AvailableBoxstyles)s

*mutation_scale* : a value with which attributes of boxstyle
(e.g., pad) will be scaled. default=1.

*mutation_aspect* : The height of the rectangle will be
squeezed by this value before the mutation and the mutated
box will be stretched by the inverse of it. default=None.

Valid kwargs are:
%(Patch)s


return self.set_edgecolor(color)<EOL>


if len(args)==<NUM_LIT:0>:<EOL><INDENT>l,b,w,h = args[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>l,b,w,h = args<EOL><DEDENT>self._x = l<EOL>self._y = b<EOL>self._width = w<EOL>self._height = h<EOL>

Set the bounds of the rectangle: l,b,w,h

ACCEPTS: (left, bottom, width, height)


return self._width<EOL>


return self.get_patch_transform() + artist.Artist.get_transform(self)<EOL>

Return the :class:`~matplotlib.transforms.Transform` applied
to the :class:`Patch`.


self._y = y<EOL>

Set the bottom coord of the rectangle

ACCEPTS: float


if not self.get_visible(): return<EOL>gc = renderer.new_gc()<EOL>if cbook.is_string_like(self._edgecolor) and self._edgecolor.lower()=='<STR_LIT:none>':<EOL><INDENT>gc.set_linewidth(<NUM_LIT:0>)<EOL><DEDENT>else:<EOL><INDENT>gc.set_foreground(self._edgecolor)<EOL>gc.set_linewidth(self._linewidth)<EOL>gc.set_linestyle(self._linestyle)<EOL><DEDENT>gc.set_antialiased(self._antialiased)<EOL>self._set_gc_clip(gc)<EOL>gc.set_capstyle('<STR_LIT>')<EOL>gc.set_url(self._url)<EOL>gc.set_snap(self._snap)<EOL>if (not self.fill or self._facecolor is None or<EOL>(cbook.is_string_like(self._facecolor) and self._facecolor.lower()=='<STR_LIT:none>')):<EOL><INDENT>rgbFace = None<EOL>gc.set_alpha(<NUM_LIT:1.0>)<EOL><DEDENT>else:<EOL><INDENT>r, g, b, a = colors.colorConverter.to_rgba(self._facecolor, self._alpha)<EOL>rgbFace = (r, g, b)<EOL>gc.set_alpha(a)<EOL><DEDENT>if self._hatch:<EOL><INDENT>gc.set_hatch(self._hatch )<EOL><DEDENT>path = self.get_path()<EOL>transform = self.get_transform()<EOL>tpath = transform.transform_path_non_affine(path)<EOL>affine = transform.get_affine()<EOL>renderer.draw_path(gc, tpath, affine, rgbFace)<EOL>

Draw the :class:`Patch` to the given *renderer*.


def __patch__init__(self,<EOL>edgecolor=None,<EOL>facecolor=None,<EOL>linewidth=None,<EOL>linestyle=None,<EOL>antialiased = None,<EOL>hatch = None,<EOL>fill=True,<EOL>**kwargs<EOL>):

artist.Artist.__init__(self)<EOL>if linewidth is None: linewidth = mpl.rcParams['<STR_LIT>']<EOL>if linestyle is None: linestyle = "<STR_LIT>"<EOL>if antialiased is None: antialiased = mpl.rcParams['<STR_LIT>']<EOL>self.set_edgecolor(edgecolor)<EOL>self.set_facecolor(facecolor)<EOL>self.set_linewidth(linewidth)<EOL>self.set_linestyle(linestyle)<EOL>self.set_antialiased(antialiased)<EOL>self.set_hatch(hatch)<EOL>self.fill = fill<EOL>self._combined_transform = transforms.IdentityTransform()<EOL>if len(kwargs): artist.setp(self, **kwargs)<EOL>

The following kwarg properties are supported

%(Patch)s


def __init__(self, figure, xytip, xybase, width=<NUM_LIT:4>, frac=<NUM_LIT:0.1>, headwidth=<NUM_LIT:12>, **kwargs):

self.figure = figure<EOL>self.xytip = xytip<EOL>self.xybase = xybase<EOL>self.width = width<EOL>self.frac = frac<EOL>self.headwidth = headwidth<EOL>Patch.__init__(self, **kwargs)<EOL>

Constructor arguments:

*xytip*
  (*x*, *y*) location of arrow tip

*xybase*
  (*x*, *y*) location the arrow base mid point

*figure*
  The :class:`~matplotlib.figure.Figure` instance
  (fig.dpi)

*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

Valid kwargs are:
%(Patch)s


_path = self.get_path_in_displaycoord()<EOL>return self.get_transform().inverted().transform_path(_path)<EOL>

return the path of the arrow in the data coordinate. Use
get_path_in_displaycoord() medthod to retrieve the arrow path
in the disaply coord.


trans = self.get_transform()<EOL>path = self.get_path()<EOL>polygons = path.to_polygons(trans)<EOL>if len(polygons):<EOL><INDENT>return polygons[<NUM_LIT:0>]<EOL><DEDENT>return []<EOL>

Return a copy of the vertices used in this patch

If the patch contains Bézier curves, the curves will be
interpolated by line segments.  To access the curves as
curves, use :meth:`get_path`.


return self.set_facecolor(color)<EOL>


self._height = h<EOL>


<EOL>if callable(self._contains): return self._contains(self,mouseevent)<EOL>inside = self.get_path().contains_point(<EOL>(mouseevent.x, mouseevent.y), self.get_transform())<EOL>return inside, {}<EOL>

Test whether the mouse event occurred in the patch.

        Returns T/F, {}


def __init__(self, xy, radius=<NUM_LIT:5>, **kwargs):

if '<STR_LIT>' in kwargs:<EOL><INDENT>import warnings<EOL>warnings.warn('<STR_LIT>', DeprecationWarning)<EOL>kwargs.pop('<STR_LIT>')<EOL><DEDENT>self.radius = radius<EOL>Ellipse.__init__(self, xy, radius*<NUM_LIT:2>, radius*<NUM_LIT:2>, **kwargs)<EOL>

Create true circle at center *xy* = (*x*, *y*) with given
*radius*.  Unlike :class:`~matplotlib.patches.CirclePolygon`
which is a polygonal approximation, this uses Bézier splines
and is much closer to a scale-free circle.

Valid kwargs are:
%(Patch)s


def __init__( self, x, y, dx, dy, width=<NUM_LIT:1.0>, **kwargs ):

Patch.__init__(self, **kwargs)<EOL>L = np.sqrt(dx**<NUM_LIT:2>+dy**<NUM_LIT:2>) or <NUM_LIT:1> <EOL>cx = float(dx)/L<EOL>sx = float(dy)/L<EOL>trans1 = transforms.Affine2D().scale(L, width)<EOL>trans2 = transforms.Affine2D.from_values(cx, sx, -sx, cx, <NUM_LIT:0.0>, <NUM_LIT:0.0>)<EOL>trans3 = transforms.Affine2D().translate(x, y)<EOL>trans = trans1 + trans2 + trans3<EOL>self._patch_transform = trans.frozen()<EOL>

Draws an arrow, starting at (*x*, *y*), direction and length
given by (*dx*, *dy*) the width of the arrow is scaled by *width*.

Valid kwargs are:
%(Patch)s


self._y = y<EOL>


def __init__(self, center, r, theta1, theta2, width=None, **kwargs):

Patch.__init__(self, **kwargs)<EOL>self.center = center<EOL>self.r,self.width = r,width<EOL>self.theta1,self.theta2 = theta1,theta2<EOL>delta=theta2-theta1<EOL>if abs((theta2-theta1) - <NUM_LIT>) <= <NUM_LIT>:<EOL><INDENT>theta1,theta2 = <NUM_LIT:0>,<NUM_LIT><EOL>connector = Path.MOVETO<EOL><DEDENT>else:<EOL><INDENT>connector = Path.LINETO<EOL><DEDENT>arc = Path.arc(theta1,theta2)<EOL>if width is not None:<EOL><INDENT>v1 = arc.vertices<EOL>v2 = arc.vertices[::-<NUM_LIT:1>]*float(r-width)/r<EOL>v = np.vstack([v1,v2,v1[<NUM_LIT:0>,:],(<NUM_LIT:0>,<NUM_LIT:0>)])<EOL>c = np.hstack([arc.codes,arc.codes,connector,Path.CLOSEPOLY])<EOL>c[len(arc.codes)]=connector<EOL><DEDENT>else:<EOL><INDENT>v = np.vstack([arc.vertices,[(<NUM_LIT:0>,<NUM_LIT:0>),arc.vertices[<NUM_LIT:0>,:],(<NUM_LIT:0>,<NUM_LIT:0>)]])<EOL>c = np.hstack([arc.codes,[connector,connector,Path.CLOSEPOLY]])<EOL><DEDENT>v *= r<EOL>v += np.asarray(center)<EOL>self._path = Path(v,c)<EOL>self._patch_transform = transforms.IdentityTransform()<EOL>

Draw a wedge centered at *x*, *y* center with radius *r* that
sweeps *theta1* to *theta2* (in degrees).  If *width* is given,
then a partial wedge is drawn from inner radius *r* - *width*
to outer radius *r*.

Valid kwargs are:

%(Patch)s


def set_arrowstyle(self, arrowstyle=None, **kw):

if arrowstyle==None:<EOL><INDENT>return ArrowStyle.pprint_styles()<EOL><DEDENT>if isinstance(arrowstyle, ConnectionStyle._Base):<EOL><INDENT>self._arrow_transmuter = arrowstyle<EOL><DEDENT>else:<EOL><INDENT>self._arrow_transmuter = ArrowStyle(arrowstyle, **kw)<EOL><DEDENT>

Set the arrow style.

*arrowstyle* can be a string with arrowstyle name with optional
 comma-separated attributes. Alternatively, the attrs can
 be provided as keywords.

 set_arrowstyle("Fancy,head_length=0.2")
 set_arrowstyle("fancy", head_length=0.2)

Old attrs simply are forgotten.

Without argument (or with arrowstyle=None), return
available box styles as a list of strings.


return self.fill<EOL>


return self._y<EOL>

Return the bottom coord of the rectangle


_path = self.get_boxstyle()(self._x, self._y,<EOL>self._width, self._height,<EOL>self.get_mutation_scale(),<EOL>self.get_mutation_aspect())<EOL>return _path<EOL>

Return the mutated path of the rectangle


return self._x, self._y<EOL>

Return the left and bottom coords of the rectangle


self._width = w<EOL>


def __init__(self, patch, ox, oy, props=None, **kwargs):

Patch.__init__(self)<EOL>self.patch = patch<EOL>self.props = props<EOL>self._ox, self._oy = ox, oy<EOL>self._update_transform()<EOL>self._update()<EOL>

Create a shadow of the given *patch* offset by *ox*, *oy*.
*props*, if not *None*, is a patch property update dictionary.
If *None*, the shadow will have have the same color as the face,
but darkened.

kwargs are
%(Patch)s


def __init__(self, xy, width, height, angle=<NUM_LIT:0.0>, **kwargs):

Patch.__init__(self, **kwargs)<EOL>self.center = xy<EOL>self.width, self.height = width, height<EOL>self.angle = angle<EOL>self._path = Path.unit_circle()<EOL>self._patch_transform = transforms.IdentityTransform()<EOL>

*xy*
  center of ellipse

*width*
  length of horizontal axis

*height*
  length of vertical axis

*angle*
  rotation in degrees (anti-clockwise)

Valid kwargs are:
%(Patch)s


return Path.unit_rectangle()<EOL>


def bbox_artist(artist, renderer, props=None, fill=True):

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 = artist.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>fill=fill,<EOL>)<EOL>r.set_transform(transforms.IdentityTransform())<EOL>r.set_clip_on( False )<EOL>r.update(props)<EOL>r.draw(renderer)<EOL>

This is a debug function to draw a rectangle around the bounding
box returned by
:meth:`~matplotlib.artist.Artist.get_window_extent` of an artist,
to test whether the artist is returning the correct bbox.

*props* is a dict of rectangle props with the additional property
'pad' that sets the padding around the bbox in points.


return self.get_path().get_extents(self.get_transform())<EOL>

Return a :class:`~matplotlib.transforms.Bbox` object defining
the axis-aligned extents of the :class:`Patch`.


if color is None: color = mpl.rcParams['<STR_LIT>']<EOL>self._facecolor = color<EOL>

Set the patch face color

ACCEPTS: mpl color spec, or None for default, or 'none' for no color


if w is None: w = mpl.rcParams['<STR_LIT>']<EOL>self._linewidth = w<EOL>

Set the patch linewidth in points

ACCEPTS: float or None for default


return self.set_linestyle(ls)<EOL>


return self._height<EOL>


return self._linestyle<EOL>

Return the linestyle.  Will be one of ['solid' | 'dashed' |
'dashdot' | 'dotted']


return _pprint_styles(klass._style_list)<EOL>

A class method which returns a string of the available styles.


if ls is None: ls = "<STR_LIT>"<EOL>self._linestyle = ls<EOL>

Set the patch linestyle

ACCEPTS: ['solid' | 'dashed' | 'dashdot' | 'dotted']


return self._edgecolor<EOL>

Return the edge color of the :class:`Patch`.


x = self.convert_xunits(self._x)<EOL>y = self.convert_yunits(self._y)<EOL>width = self.convert_xunits(self._width)<EOL>height = self.convert_yunits(self._height)<EOL>bbox = transforms.Bbox.from_bounds(x, y, width, height)<EOL>self._rect_transform = transforms.BboxTransformTo(bbox)<EOL>

NOTE: This cannot be called until after this has been added
                 to an Axes, otherwise unit conversion will fail. This
                 maxes it very important to call the accessor method and
                 not directly access the transformation member variable.


return self._bbox_transmuter<EOL>


Updates this :class:`Patch` from the properties of *other*.


Patch.__init__(self, **kwargs)<EOL>self._path = path<EOL>

*path* is a :class:`matplotlib.path.Path` object.

Valid kwargs are:
%(Patch)s

.. seealso::
    :class:`Patch`:
        For additional kwargs


return self._mutation_scale<EOL>


self.patchA = patchA<EOL>


return self._x<EOL>


def __init__(self, xy, closed=True, **kwargs):

Patch.__init__(self, **kwargs)<EOL>xy = np.asarray(xy, np.float_)<EOL>self._path = Path(xy)<EOL>self.set_closed(closed)<EOL>

*xy* is a numpy array with shape Nx2.

If *closed* is *True*, the polygon will be closed so the
starting and ending points are the same.

Valid kwargs are:
%(Patch)s

.. seealso::
    :class:`Patch`:
        For additional kwargs


return self._mutation_aspect<EOL>

Return the aspect ratio of the bbox mutation.


def set_ticks(self, ticks, minor=False):

<EOL>ticks = self.convert_units(ticks)<EOL>if len(ticks) > <NUM_LIT:1>:<EOL><INDENT>xleft, xright = self.get_view_interval()<EOL>if xright > xleft:<EOL><INDENT>self.set_view_interval(min(ticks), max(ticks))<EOL><DEDENT>else:<EOL><INDENT>self.set_view_interval(max(ticks), min(ticks))<EOL><DEDENT><DEDENT>if minor:<EOL><INDENT>self.set_minor_locator(mticker.FixedLocator(ticks))<EOL>return self.get_minor_ticks(len(ticks))<EOL><DEDENT>else:<EOL><INDENT>self.set_major_locator( mticker.FixedLocator(ticks) )<EOL>return self.get_major_ticks(len(ticks))<EOL><DEDENT>

Set the locations of the tick marks from sequence ticks

ACCEPTS: sequence of floats


assert position == '<STR_LIT>' or position == '<STR_LIT>'<EOL>if position == '<STR_LIT>':<EOL><INDENT>self.label.set_verticalalignment('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>self.label.set_verticalalignment('<STR_LIT>')<EOL><DEDENT>self.label_position=position<EOL>

Set the label position (top or bottom)

ACCEPTS: [ 'top' | 'bottom' ]


<EOL>trans, vert, horiz = self.axes.get_xaxis_text2_transform(self._pad)<EOL>t = mtext.Text(<EOL>x=<NUM_LIT:0>, y=<NUM_LIT:1>,<EOL>fontproperties=font_manager.FontProperties(size=rcParams['<STR_LIT>']),<EOL>color=rcParams['<STR_LIT>'],<EOL>verticalalignment=vert,<EOL>horizontalalignment=horiz,<EOL>)<EOL>t.set_transform(trans)<EOL>self._set_artist_props(t)<EOL>return t<EOL>


<EOL>trans, vert, horiz = self.axes.get_yaxis_text1_transform(self._pad)<EOL>t = mtext.Text(<EOL>x=<NUM_LIT:0>, y=<NUM_LIT:0>,<EOL>fontproperties=font_manager.FontProperties(size=rcParams['<STR_LIT>']),<EOL>color=rcParams['<STR_LIT>'],<EOL>verticalalignment=vert,<EOL>horizontalalignment=horiz,<EOL>)<EOL>t.set_transform(trans)<EOL>self._set_artist_props(t)<EOL>return t<EOL>


if callable(self._contains): return self._contains(self,mouseevent)<EOL>x,y = mouseevent.x,mouseevent.y<EOL>try:<EOL><INDENT>trans = self.axes.transAxes.inverted()<EOL>xaxes,yaxes = trans.transform_point((x,y))<EOL><DEDENT>except ValueError:<EOL><INDENT>return False, {}<EOL><DEDENT>l,b = self.axes.transAxes.transform_point((<NUM_LIT:0>,<NUM_LIT:0>))<EOL>r,t = self.axes.transAxes.transform_point((<NUM_LIT:1>,<NUM_LIT:1>))<EOL>inaxis = xaxes>=<NUM_LIT:0> and xaxes<=<NUM_LIT:1> and (<EOL>(y<b and y>b-self.pickradius) or<EOL>(y>t and y<t+self.pickradius))<EOL>return inaxis, {}<EOL>

Test whether the mouse event occured in the x axis.


if self.converter is None:<EOL><INDENT>return<EOL><DEDENT>info = self.converter.axisinfo(self.units)<EOL>if info is None:<EOL><INDENT>return<EOL><DEDENT>if info.majloc is not None and self.major.locator!=info.majloc:<EOL><INDENT>self.set_major_locator(info.majloc)<EOL><DEDENT>if info.minloc is not None and self.minor.locator!=info.minloc:<EOL><INDENT>self.set_minor_locator(info.minloc)<EOL><DEDENT>if info.majfmt is not None and self.major.formatter!=info.majfmt:<EOL><INDENT>self.set_major_formatter(info.majfmt)<EOL><DEDENT>if info.minfmt is not None and self.minor.formatter!=info.minfmt:<EOL><INDENT>self.set_minor_formatter(info.minfmt)<EOL><DEDENT>if info.label is not None:<EOL><INDENT>label = self.get_label()<EOL>label.set_text(info.label)<EOL><DEDENT>

check the axis converter for the stored units to see if the
axis info needs to be updated


raise NotImplementedError('<STR_LIT>')<EOL>

return the view Interval instance for the axis this tick is ticking


return self.axes.dataLim.intervalx<EOL>

return the Interval instance for this axis data limits


self.major.formatter = formatter<EOL>formatter.set_axis(self)<EOL>

Set the formatter of the major ticker

ACCEPTS: A :class:`~matplotlib.ticker.Formatter` instance


pass<EOL>

Get the default line2D instance for tick2


return self.axes.dataLim.intervaly<EOL>


return self._pad<EOL>

Get the value of the tick label pad in points


<EOL>l = mlines.Line2D( xdata=(<NUM_LIT:0>,), ydata=(<NUM_LIT:1>,),<EOL>color='<STR_LIT:k>',<EOL>linestyle = '<STR_LIT:None>',<EOL>marker = self._xtickmarkers[<NUM_LIT:1>],<EOL>markersize=self._size,<EOL>)<EOL>l.set_transform(self.axes.get_xaxis_transform())<EOL>self._set_artist_props(l)<EOL>return l<EOL>


def set_ticklabels(self, ticklabels, *args, **kwargs):

<EOL>minor = kwargs.pop('<STR_LIT>', False)<EOL>if minor:<EOL><INDENT>self.set_minor_formatter(mticker.FixedFormatter(ticklabels))<EOL>ticks = self.get_minor_ticks()<EOL><DEDENT>else:<EOL><INDENT>self.set_major_formatter( mticker.FixedFormatter(ticklabels) )<EOL>ticks = self.get_major_ticks()<EOL><DEDENT>self.set_major_formatter( mticker.FixedFormatter(ticklabels) )<EOL>ret = []<EOL>for i, tick in enumerate(ticks):<EOL><INDENT>if i<len(ticklabels):<EOL><INDENT>tick.label1.set_text(ticklabels[i])<EOL>ret.append(tick.label1)<EOL><DEDENT>tick.label1.update(kwargs)<EOL><DEDENT>return ret<EOL>

Set the text values of the tick labels. Return a list of Text
instances.  Use *kwarg* *minor=True* to select minor ticks.

ACCEPTS: sequence of strings


self.set_major_locator(mticker.AutoLocator())<EOL>self.set_major_formatter(mticker.ScalarFormatter())<EOL>self.set_minor_locator(mticker.NullLocator())<EOL>self.set_minor_formatter(mticker.NullFormatter())<EOL>self.callbacks = cbook.CallbackRegistry(('<STR_LIT>', '<STR_LIT>'))<EOL>self._gridOnMajor = rcParams['<STR_LIT>']<EOL>self._gridOnMinor = False<EOL>self.label.set_text('<STR_LIT>')<EOL>self._set_artist_props(self.label)<EOL>cbook.popall(self.majorTicks)<EOL>cbook.popall(self.minorTicks)<EOL>self.majorTicks.extend([self._get_tick(major=True)])<EOL>self.minorTicks.extend([self._get_tick(major=False)])<EOL>self._lastNumMajorTicks = <NUM_LIT:1><EOL>self._lastNumMinorTicks = <NUM_LIT:1><EOL>self.converter = None<EOL>self.units = None<EOL>self.set_units(None)<EOL>


def _update_offset_text_position(self, bboxes, bboxes2):

x,y = self.offsetText.get_position()<EOL>if not len(bboxes):<EOL><INDENT>bottom = self.axes.bbox.ymin<EOL><DEDENT>else:<EOL><INDENT>bbox = mtransforms.Bbox.union(bboxes)<EOL>bottom = bbox.y0<EOL><DEDENT>self.offsetText.set_position((x, bottom-self.OFFSETTEXTPAD*self.figure.dpi/<NUM_LIT>))<EOL>

Update the offset_text position based on the sequence of bounding
boxes of all the ticklabels


majt=self.majorTicks[<NUM_LIT:0>]<EOL>mT=self.minorTicks[<NUM_LIT:0>]<EOL>majorRight=(not majt.tick1On) and majt.tick2On and (not majt.label1On) and majt.label2On<EOL>minorRight=(not mT.tick1On) and mT.tick2On and (not mT.label1On) and mT.label2On<EOL>if majorRight and minorRight: return '<STR_LIT:right>'<EOL>majorLeft=majt.tick1On and (not majt.tick2On) and majt.label1On and (not majt.label2On)<EOL>minorLeft=mT.tick1On and (not mT.tick2On) and mT.label1On and (not mT.label2On)<EOL>if majorLeft and minorLeft: return '<STR_LIT:left>'<EOL>majorDefault=majt.tick1On and majt.tick2On and majt.label1On and (not majt.label2On)<EOL>minorDefault=mT.tick1On and mT.tick2On and mT.label1On and (not mT.label2On)<EOL>if majorDefault and minorDefault: return '<STR_LIT:default>'<EOL>return '<STR_LIT>'<EOL>

Return the ticks position (left, right, both or unknown)


bbox, bbox2 = self.get_ticklabel_extents(renderer)<EOL>padPixels = self.majorTicks[<NUM_LIT:0>].get_pad_pixels()<EOL>above = <NUM_LIT:0.0><EOL>if bbox2.height:<EOL><INDENT>above += bbox2.height + padPixels<EOL><DEDENT>below = <NUM_LIT:0.0><EOL>if bbox.height:<EOL><INDENT>below += bbox.height + padPixels<EOL><DEDENT>if self.get_label_position() == '<STR_LIT>':<EOL><INDENT>above += self.label.get_window_extent(renderer).height + padPixels<EOL><DEDENT>else:<EOL><INDENT>below += self.label.get_window_extent(renderer).height + padPixels<EOL><DEDENT>return above, below<EOL>

Returns the amount of space one should reserve for text
above and below the axes.  Returns a tuple (above, below)


return self.major.formatter<EOL>


def _update_label_position(self, bboxes, bboxes2):

if not self._autolabelpos: return<EOL>x,y = self.label.get_position()<EOL>if self.label_position == '<STR_LIT:left>':<EOL><INDENT>if not len(bboxes):<EOL><INDENT>left = self.axes.bbox.xmin<EOL><DEDENT>else:<EOL><INDENT>bbox = mtransforms.Bbox.union(bboxes)<EOL>left = bbox.x0<EOL><DEDENT>self.label.set_position( (left-self.LABELPAD*self.figure.dpi/<NUM_LIT>, y))<EOL><DEDENT>else:<EOL><INDENT>if not len(bboxes2):<EOL><INDENT>right = self.axes.bbox.xmax<EOL><DEDENT>else:<EOL><INDENT>bbox = mtransforms.Bbox.union(bboxes2)<EOL>right = bbox.x1<EOL><DEDENT>self.label.set_position( (right+self.LABELPAD*self.figure.dpi/<NUM_LIT>, y))<EOL><DEDENT>

Update the label position based on the sequence of bounding
boxes of all the ticklabels


ticks = self.get_minor_ticks()<EOL>labels1 = [tick.label1 for tick in ticks if tick.label1On]<EOL>labels2 = [tick.label2 for tick in ticks if tick.label2On]<EOL>return cbook.silent_list('<STR_LIT>', labels1+labels2)<EOL>

Return a list of Text instances for the minor ticklabels


self._pad = val<EOL>

Set the tick label pad in points

ACCEPTS: float


if numticks is None:<EOL><INDENT>numticks = len(self.get_major_locator()())<EOL><DEDENT>if len(self.majorTicks) < numticks:<EOL><INDENT>for i in range(numticks - len(self.majorTicks)):<EOL><INDENT>tick = self._get_tick(major=True)<EOL>self.majorTicks.append(tick)<EOL><DEDENT><DEDENT>if self._lastNumMajorTicks < numticks:<EOL><INDENT>protoTick = self.majorTicks[<NUM_LIT:0>]<EOL>for i in range(self._lastNumMajorTicks, len(self.majorTicks)):<EOL><INDENT>tick = self.majorTicks[i]<EOL>if self._gridOnMajor: tick.gridOn = True<EOL>self._copy_tick_props(protoTick, tick)<EOL><DEDENT><DEDENT>self._lastNumMajorTicks = numticks<EOL>ticks = self.majorTicks[:numticks]<EOL>return ticks<EOL>

get the tick instances; grow as necessary


def draw(self, renderer, *args, **kwargs):

ticklabelBoxes = []<EOL>ticklabelBoxes2 = []<EOL>if not self.get_visible(): return<EOL>renderer.open_group(__name__)<EOL>interval = self.get_view_interval()<EOL>for tick, loc, label in self.iter_ticks():<EOL><INDENT>if tick is None: continue<EOL>if not mtransforms.interval_contains(interval, loc): continue<EOL>tick.update_position(loc)<EOL>tick.set_label1(label)<EOL>tick.set_label2(label)<EOL>tick.draw(renderer)<EOL>if tick.label1On and tick.label1.get_visible():<EOL><INDENT>extent = tick.label1.get_window_extent(renderer)<EOL>ticklabelBoxes.append(extent)<EOL><DEDENT>if tick.label2On and tick.label2.get_visible():<EOL><INDENT>extent = tick.label2.get_window_extent(renderer)<EOL>ticklabelBoxes2.append(extent)<EOL><DEDENT><DEDENT>self._update_label_position(ticklabelBoxes, ticklabelBoxes2)<EOL>self.label.draw(renderer)<EOL>self._update_offset_text_position(ticklabelBoxes, ticklabelBoxes2)<EOL>self.offsetText.set_text( self.major.formatter.get_offset() )<EOL>self.offsetText.draw(renderer)<EOL>if <NUM_LIT:0>: <EOL><INDENT>for tick in majorTicks:<EOL><INDENT>label = tick.label1<EOL>mpatches.bbox_artist(label, renderer)<EOL><DEDENT>mpatches.bbox_artist(self.label, renderer)<EOL><DEDENT>renderer.close_group(__name__)<EOL>

Draw the axis lines, grid lines, tick lines and labels


pass<EOL>

Get the default line2D instance for tick1


self.major.locator = locator<EOL>locator.set_axis(self)<EOL>

Set the locator of the major ticker

ACCEPTS: a :class:`~matplotlib.ticker.Locator` instance


return self.axes.viewLim.intervalx<EOL>

return the Interval instance for this axis view limits


return self.offsetText<EOL>

Return the axis offsetText as a Text instance


return self.minor.locator()<EOL>

Get the minor tick locations in data coordinates as a numpy array


lines = []<EOL>ticks = self.get_minor_ticks()<EOL>for tick in ticks:<EOL><INDENT>lines.append(tick.tick1line)<EOL>lines.append(tick.tick2line)<EOL><DEDENT>return cbook.silent_list('<STR_LIT>', lines)<EOL>

Return the minor tick lines as a list of Line2D instances


self.minor.locator = locator<EOL>locator.set_axis(self)<EOL>

Set the locator of the minor ticker

ACCEPTS: a :class:`~matplotlib.ticker.Locator` instance


self.minor.formatter = formatter<EOL>formatter.set_axis(self)<EOL>

Set the formatter of the minor ticker

ACCEPTS: A :class:`~matplotlib.ticker.Formatter` instance


if not self._autolabelpos: return<EOL>x,y = self.label.get_position()<EOL>if self.label_position == '<STR_LIT>':<EOL><INDENT>if not len(bboxes):<EOL><INDENT>bottom = self.axes.bbox.ymin<EOL><DEDENT>else:<EOL><INDENT>bbox = mtransforms.Bbox.union(bboxes)<EOL>bottom = bbox.y0<EOL><DEDENT>self.label.set_position( (x, bottom - self.LABELPAD*self.figure.dpi / <NUM_LIT>))<EOL><DEDENT>else:<EOL><INDENT>if not len(bboxes2):<EOL><INDENT>top = self.axes.bbox.ymax<EOL><DEDENT>else:<EOL><INDENT>bbox = mtransforms.Bbox.union(bboxes2)<EOL>top = bbox.y1<EOL><DEDENT>self.label.set_position( (x, top+self.LABELPAD*self.figure.dpi / <NUM_LIT>))<EOL><DEDENT>


ticklabelBoxes = []<EOL>ticklabelBoxes2 = []<EOL>interval = self.get_view_interval()<EOL>for tick, loc, label in self.iter_ticks():<EOL><INDENT>if tick is None: continue<EOL>if not mtransforms.interval_contains(interval, loc): continue<EOL>tick.update_position(loc)<EOL>tick.set_label1(label)<EOL>tick.set_label2(label)<EOL>if tick.label1On and tick.label1.get_visible():<EOL><INDENT>extent = tick.label1.get_window_extent(renderer)<EOL>ticklabelBoxes.append(extent)<EOL><DEDENT>if tick.label2On and tick.label2.get_visible():<EOL><INDENT>extent = tick.label2.get_window_extent(renderer)<EOL>ticklabelBoxes2.append(extent)<EOL><DEDENT><DEDENT>if len(ticklabelBoxes):<EOL><INDENT>bbox = mtransforms.Bbox.union(ticklabelBoxes)<EOL><DEDENT>else:<EOL><INDENT>bbox = mtransforms.Bbox.from_extents(<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>)<EOL><DEDENT>if len(ticklabelBoxes2):<EOL><INDENT>bbox2 = mtransforms.Bbox.union(ticklabelBoxes2)<EOL><DEDENT>else:<EOL><INDENT>bbox2 = mtransforms.Bbox.from_extents(<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>)<EOL><DEDENT>return bbox, bbox2<EOL>

Get the extents of the tick labels on either side
of the axes.


self.set_ticks_position('<STR_LIT:right>')<EOL>


<EOL>l = mlines.Line2D( (<NUM_LIT:1>,), (<NUM_LIT:0>,), color='<STR_LIT:k>',<EOL>marker = self._ytickmarkers[<NUM_LIT:1>],<EOL>linestyle = '<STR_LIT:None>',<EOL>markersize=self._size,<EOL>)<EOL>l.set_transform(self.axes.get_yaxis_transform())<EOL>self._set_artist_props(l)<EOL>return l<EOL>


self.set_ticks_position('<STR_LIT:left>')<EOL>


def __init__(self, axes, loc, label,<EOL>size   = None,  <EOL>gridOn = None, <EOL>tick1On = True,<EOL>tick2On = True,<EOL>label1On = True,<EOL>label2On = False,<EOL>major = True,<EOL>):

artist.Artist.__init__(self)<EOL>if gridOn is None: gridOn = rcParams['<STR_LIT>']<EOL>self.set_figure(axes.figure)<EOL>self.axes = axes<EOL>name = self.__name__.lower()<EOL>if size is None:<EOL><INDENT>if major:<EOL><INDENT>size = rcParams['<STR_LIT>'%name]<EOL>pad = rcParams['<STR_LIT>'%name]<EOL><DEDENT>else:<EOL><INDENT>size = rcParams['<STR_LIT>'%name]<EOL>pad = rcParams['<STR_LIT>'%name]<EOL><DEDENT><DEDENT>self._tickdir = rcParams['<STR_LIT>'%name]<EOL>if self._tickdir == '<STR_LIT>':<EOL><INDENT>self._xtickmarkers = (mlines.TICKUP, mlines.TICKDOWN)<EOL>self._ytickmarkers = (mlines.TICKRIGHT, mlines.TICKLEFT)<EOL>self._pad = pad<EOL><DEDENT>else:<EOL><INDENT>self._xtickmarkers = (mlines.TICKDOWN, mlines.TICKUP)<EOL>self._ytickmarkers = (mlines.TICKLEFT, mlines.TICKRIGHT)<EOL>self._pad = pad + size<EOL><DEDENT>self._loc = loc<EOL>self._size = size<EOL>self.tick1line = self._get_tick1line()<EOL>self.tick2line = self._get_tick2line()<EOL>self.gridline = self._get_gridline()<EOL>self.label1 = self._get_text1()<EOL>self.label = self.label1  <EOL>self.label2 = self._get_text2()<EOL>self.gridOn = gridOn<EOL>self.tick1On = tick1On<EOL>self.tick2On = tick2On<EOL>self.label1On = label1On<EOL>self.label2On = label2On<EOL>self.update_position(loc)<EOL>

bbox is the Bound2D bounding box in display coords of the Axes
loc is the tick location in data coords
size is the tick size in relative, axes coords


self.set_ticks_position('<STR_LIT>')<EOL>


return self.axes.viewLim.intervaly<EOL>


pass<EOL>

Get the default grid Line2d instance for this tick


raise NotImplementedError('<STR_LIT>')<EOL>


x,y = self.offsetText.get_position()<EOL>top = self.axes.bbox.ymax<EOL>self.offsetText.set_position((x, top+self.OFFSETTEXTPAD*self.figure.dpi/<NUM_LIT>))<EOL>

Update the offset_text position based on the sequence of bounding
boxes of all the ticklabels


return self.minor.formatter<EOL>


if minor:<EOL><INDENT>return self.get_minorticklines()<EOL><DEDENT>return self.get_majorticklines()<EOL>

Return the tick lines as a list of Line2D instances


<EOL>trans, vert, horiz = self.axes.get_yaxis_text2_transform(self._pad)<EOL>t = mtext.Text(<EOL>x=<NUM_LIT:1>, y=<NUM_LIT:0>,<EOL>fontproperties=font_manager.FontProperties(size=rcParams['<STR_LIT>']),<EOL>color=rcParams['<STR_LIT>'],<EOL>verticalalignment=vert,<EOL>horizontalalignment=horiz,<EOL>)<EOL>t.set_transform(trans)<EOL>self._set_artist_props(t)<EOL>return t<EOL>


def __init__(self, axes, pickradius=<NUM_LIT:15>):

artist.Artist.__init__(self)<EOL>self.set_figure(axes.figure)<EOL>self.axes = axes<EOL>self.major = Ticker()<EOL>self.minor = Ticker()<EOL>self.callbacks = cbook.CallbackRegistry(('<STR_LIT>', '<STR_LIT>'))<EOL>self._autolabelpos = True<EOL>self.label = self._get_label()<EOL>self.offsetText = self._get_offset_text()<EOL>self.majorTicks = []<EOL>self.minorTicks = []<EOL>self.pickradius = pickradius<EOL>self.cla()<EOL>self.set_scale('<STR_LIT>')<EOL>

Init the axis with the parent Axes instance


if numticks is None:<EOL><INDENT>numticks = len(self.get_minor_locator()())<EOL><DEDENT>if len(self.minorTicks) < numticks:<EOL><INDENT>for i in range(numticks - len(self.minorTicks)):<EOL><INDENT>tick = self._get_tick(major=False)<EOL>self.minorTicks.append(tick)<EOL><DEDENT><DEDENT>if self._lastNumMinorTicks < numticks:<EOL><INDENT>protoTick = self.minorTicks[<NUM_LIT:0>]<EOL>for i in range(self._lastNumMinorTicks, len(self.minorTicks)):<EOL><INDENT>tick = self.minorTicks[i]<EOL>if self._gridOnMinor: tick.gridOn = True<EOL>self._copy_tick_props(protoTick, tick)<EOL><DEDENT><DEDENT>self._lastNumMinorTicks = numticks<EOL>ticks = self.minorTicks[:numticks]<EOL>return ticks<EOL>

get the minor tick instances; grow as necessary


if callable(self._contains): return self._contains(self,mouseevent)<EOL>x,y = mouseevent.x,mouseevent.y<EOL>try:<EOL><INDENT>trans = self.axes.transAxes.inverted()<EOL>xaxes,yaxes = trans.transform_point((x,y))<EOL><DEDENT>except ValueError:<EOL><INDENT>return False, {}<EOL><DEDENT>l,b = self.axes.transAxes.transform_point((<NUM_LIT:0>,<NUM_LIT:0>))<EOL>r,t = self.axes.transAxes.transform_point((<NUM_LIT:1>,<NUM_LIT:1>))<EOL>inaxis = yaxes>=<NUM_LIT:0> and yaxes<=<NUM_LIT:1> and (<EOL>(x<l and x>l-self.pickradius) or<EOL>(x>r and x<r+self.pickradius))<EOL>return inaxis, {}<EOL>

Test whether the mouse event occurred in the y axis.

        Returns *True* | *False*


if ((len(key) != <NUM_LIT:2>) or<EOL>(not isinstance(key[<NUM_LIT:0>], slice)) or<EOL>(not isinstance(key[<NUM_LIT:1>], slice))):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>x0 = key[<NUM_LIT:1>].start<EOL>x1 = key[<NUM_LIT:1>].stop<EOL>xstep = key[<NUM_LIT:1>].step<EOL>if not isinstance(xstep, complex) or int(xstep.real) != xstep.real:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>xstep = int(xstep.imag)<EOL>y0 = key[<NUM_LIT:0>].start<EOL>y1 = key[<NUM_LIT:0>].stop<EOL>ystep = key[<NUM_LIT:0>].step<EOL>if not isinstance(ystep, complex) or int(ystep.real) != ystep.real:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>ystep = int(ystep.imag)<EOL>return x0, x1, xstep, y0, y1, ystep<EOL>

Convert a 2-tuple of slices to start,stop,steps for x and y.

    key -- (slice(ystart,ystop,ystep), slice(xtart, xstop, xstep))

    For now, the only accepted step values are imaginary integers (interpreted
    in the same way numpy.mgrid, etc. do).


def nn_interpolator(self, z, default_value=np.nan):

z = np.asarray(z, dtype=np.float64)<EOL>if z.shape != self.old_shape:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if self.j_unique is not None:<EOL><INDENT>z = z[self.j_unique]<EOL><DEDENT>return NNInterpolator(self, z, default_value)<EOL>

Get an object which can interpolate within the convex hull by
        the natural neighbors method.

        z -- an array of floats giving the known function values at each point
          in the triangulation.


Extract the convex hull from the triangulation information.

        The output will be a list of point_id's in counter-clockwise order
        forming the convex hull of the data set.


g = {}<EOL>for i, j in self.edge_db:<EOL><INDENT>s = g.setdefault(i, set())<EOL>s.add(j)<EOL>s = g.setdefault(j, set())<EOL>s.add(i)<EOL><DEDENT>return g<EOL>

Return a graph of node_id's pointing to node_id's.

        The arcs of the graph correspond to the edges in the triangulation.

        {node_id: set([node_id, ...]), ...}


def linear_interpolator(self, z, default_value=np.nan):

z = np.asarray(z, dtype=np.float64)<EOL>if z.shape != self.old_shape:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if self.j_unique is not None:<EOL><INDENT>z = z[self.j_unique]<EOL><DEDENT>return LinearInterpolator(self, z, default_value)<EOL>

Get an object which can interpolate within the convex hull by
        assigning a plane to each triangle.

        z -- an array of floats giving the known function values at each point
          in the triangulation.


<EOL>j_sorted = np.lexsort(keys=(self.x, self.y))<EOL>mask_unique = np.hstack([<EOL>True,<EOL>(np.diff(self.x[j_sorted]) != <NUM_LIT:0>) | (np.diff(self.y[j_sorted]) != <NUM_LIT:0>),<EOL>])<EOL>return j_sorted[mask_unique]<EOL>

Generate index array that picks out unique x,y points.

        This appears to be required by the underlying delaunay triangulation
        code.


if iterable(x):<EOL><INDENT>for thisx in x:<EOL><INDENT>return is_numlike(thisx)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return is_numlike(x)<EOL><DEDENT>

The matplotlib datalim, autoscaling, locators etc work with
scalars which are the units converted to floats given the
current unit.  The converter may be passed these floats, or
arrays of them, even when units are set.  Derived conversion
interfaces may opt to pass plain-ol unitless numbers through
the conversion interface and this is a helper function for
them.


return obj<EOL>

convert obj using unit.  If obj is a sequence, return the
converted sequence.  The ouput must be a sequence of scalars
that can be used by the numpy array layer


def __init__(self, majloc=None, minloc=None,<EOL>majfmt=None, minfmt=None, label=None):

self.majloc = majloc<EOL>self.minloc = minloc<EOL>self.majfmt = majfmt<EOL>self.minfmt = minfmt<EOL>self.label = label<EOL>

majloc and minloc: TickLocators for the major and minor ticks
majfmt and minfmt: TickFormatters for the major and minor ticks
label: the default axis label

If any of the above are None, the axis will simply use the default


if not len(self): return None <EOL>converter = None<EOL>classx = getattr(x, '<STR_LIT>', None)<EOL>if classx is not None:<EOL><INDENT>converter = self.get(classx)<EOL><DEDENT>if converter is None and iterable(x):<EOL><INDENT>if isinstance(x, np.ndarray) and x.dtype != np.object:<EOL><INDENT>return None<EOL><DEDENT>for thisx in x:<EOL><INDENT>converter = self.get_converter( thisx )<EOL>return converter<EOL><DEDENT><DEDENT>return converter<EOL>

get the converter interface instance for x, or None


return rcParams['<STR_LIT>']<EOL>


if '<STR_LIT>' in os.environ:<EOL><INDENT>path = os.environ['<STR_LIT>']<EOL>if not os.path.isdir(path):<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>return path<EOL><DEDENT>path = os.sep.join([os.path.dirname(__file__), '<STR_LIT>'])<EOL>if os.path.isdir(path): return path<EOL>import matplotlib.afm<EOL>path = os.sep.join([os.path.dirname(matplotlib.afm.__file__), '<STR_LIT>'])<EOL>if os.path.isdir(path): return path<EOL>if getattr(sys,'<STR_LIT>',None):<EOL><INDENT>path = os.path.join(os.path.split(sys.path[<NUM_LIT:0>])[<NUM_LIT:0>], '<STR_LIT>')<EOL>if os.path.isdir(path): return path<EOL>else:<EOL><INDENT>path = os.path.join(os.path.split(os.path.split(sys.path[<NUM_LIT:0>])[<NUM_LIT:0>])[<NUM_LIT:0>],<EOL>'<STR_LIT>')<EOL><DEDENT>if os.path.isdir(path): return path<EOL>else:<EOL><INDENT>path = os.path.join(sys.path[<NUM_LIT:0>], '<STR_LIT>')<EOL>if os.path.isdir(path): return path<EOL><DEDENT><DEDENT>raise RuntimeError('<STR_LIT>')<EOL>


datadir = os.path.join(get_data_path(), '<STR_LIT>')<EOL>fullpath = os.path.join(datadir, fname)<EOL>if not os.path.exists(fullpath):<EOL><INDENT>raise IOError('<STR_LIT>'%(<EOL>fname, datadir))<EOL><DEDENT>return file(fullpath, '<STR_LIT:rb>')<EOL>

return a filehandle to one of the example files in mpl-data/example

*fname*
    the name of one of the files in mpl-data/example


rcParams.update(rcParamsDefault)<EOL>

Restore the default rc params - the ones that were created at
matplotlib load time.


path='<STR_LIT>'<EOL>try:<EOL><INDENT>path=os.path.expanduser("<STR_LIT>")<EOL><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT>if not os.path.isdir(path):<EOL><INDENT>for evar in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>try:<EOL><INDENT>path = os.environ[evar]<EOL>if os.path.isdir(path):<EOL><INDENT>break<EOL><DEDENT><DEDENT>except: pass<EOL><DEDENT><DEDENT>if path:<EOL><INDENT>return path<EOL><DEDENT>else:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>

Find user's home directory if possible.
    Otherwise raise error.

    :see:  http://mail.python.org/pipermail/python-list/2005-February/263921.html


if a:<EOL><INDENT>a = distutils.version.LooseVersion(a)<EOL>b = distutils.version.LooseVersion(b)<EOL>if a>=b: return True<EOL>else: return False<EOL><DEDENT>else: return False<EOL>

return True if a is greater than or equal to b


fname = matplotlib_fname()<EOL>if not os.path.exists(fname):<EOL><INDENT>message = '<STR_LIT>'<EOL>ret = RcParams([ (key, default) for key, (default, converter) indefaultParams.items() ])<EOL>warnings.warn(message)<EOL>return ret<EOL><DEDENT>cnt = <NUM_LIT:0><EOL>rc_temp = {}<EOL>for line in file(fname):<EOL><INDENT>cnt += <NUM_LIT:1><EOL>strippedline = line.split('<STR_LIT:#>',<NUM_LIT:1>)[<NUM_LIT:0>].strip()<EOL>if not strippedline: continue<EOL>tup = strippedline.split('<STR_LIT::>',<NUM_LIT:1>)<EOL>if len(tup) !=<NUM_LIT:2>:<EOL><INDENT>warnings.warn('<STR_LIT>'%(cnt, line, fname))<EOL>continue<EOL><DEDENT>key, val = tup<EOL>key = key.strip()<EOL>val = val.strip()<EOL>if key in rc_temp:<EOL><INDENT>warnings.warn('<STR_LIT>'%(fname,cnt))<EOL><DEDENT>rc_temp[key] = (val, line, cnt)<EOL><DEDENT>ret = RcParams([ (key, default) for key, (default, converter) indefaultParams.items() ])<EOL>for key in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>if key in rc_temp:<EOL><INDENT>val, line, cnt = rc_temp.pop(key)<EOL>if fail_on_error:<EOL><INDENT>ret[key] = val <EOL><DEDENT>else:<EOL><INDENT>try: ret[key] = val <EOL>except Exception as msg:<EOL><INDENT>warnings.warn('<STR_LIT>' % (val, cnt, line, fname, msg))<EOL><DEDENT><DEDENT><DEDENT><DEDENT>verbose.set_level(ret['<STR_LIT>'])<EOL>verbose.set_fileo(ret['<STR_LIT>'])<EOL>for key, (val, line, cnt) in rc_temp.items():<EOL><INDENT>if key in defaultParams:<EOL><INDENT>if fail_on_error:<EOL><INDENT>ret[key] = val <EOL><DEDENT>else:<EOL><INDENT>try: ret[key] = val <EOL>except Exception as msg:<EOL><INDENT>warnings.warn('<STR_LIT>' % (val, cnt, line, fname, msg))<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>print("""<STR_LIT>""" % (key, cnt, fname), file=sys.stderr)<EOL><DEDENT><DEDENT>if ret['<STR_LIT>'] is None:<EOL><INDENT>ret['<STR_LIT>'] = get_data_path()<EOL><DEDENT>if not ret['<STR_LIT>'] == ['<STR_LIT>']:<EOL><INDENT>verbose.report(

Return the default params updated from the values in the rc file


try: p + '<STR_LIT>'  <EOL>except TypeError: return False<EOL>try:<EOL><INDENT>t = tempfile.TemporaryFile(dir=p)<EOL>t.write('<STR_LIT:1>')<EOL>t.close()<EOL><DEDENT>except OSError: return False<EOL>else: return True<EOL>

p is a string pointing to a putative writable dir -- return True p
is such a string, else False


oldname = os.path.join( os.getcwd(), '<STR_LIT>')<EOL>if os.path.exists(oldname):<EOL><INDENT>print("""<STR_LIT>""", file=sys.stderr)<EOL>shutil.move('<STR_LIT>', '<STR_LIT>')<EOL><DEDENT>home = get_home()<EOL>oldname = os.path.join( home, '<STR_LIT>')<EOL>if os.path.exists(oldname):<EOL><INDENT>configdir = get_configdir()<EOL>newname = os.path.join(configdir, '<STR_LIT>')<EOL>print("""<STR_LIT>"""%(oldname, newname), file=sys.stderr)<EOL>shutil.move(oldname, newname)<EOL><DEDENT>fname = os.path.join( os.getcwd(), '<STR_LIT>')<EOL>if os.path.exists(fname): return fname<EOL>if '<STR_LIT>' in os.environ:<EOL><INDENT>path =  os.environ['<STR_LIT>']<EOL>if os.path.exists(path):<EOL><INDENT>fname = os.path.join(path, '<STR_LIT>')<EOL>if os.path.exists(fname):<EOL><INDENT>return fname<EOL><DEDENT><DEDENT><DEDENT>fname = os.path.join(get_configdir(), '<STR_LIT>')<EOL>if os.path.exists(fname): return fname<EOL>path =  get_data_path() <EOL>fname = os.path.join(path, '<STR_LIT>')<EOL>if not os.path.exists(fname):<EOL><INDENT>warnings.warn('<STR_LIT>')<EOL><DEDENT>return fname<EOL>

Return the path to the rc file

Search order:

 * current working dir
 * environ var MATPLOTLIBRC
 * HOME/.matplotlib/matplotlibrc
 * MATPLOTLIBDATA/matplotlibrc


configdir = os.environ.get('<STR_LIT>')<EOL>if configdir is not None:<EOL><INDENT>if not _is_writable_dir(configdir):<EOL><INDENT>raise RuntimeError('<STR_LIT>'%configdir)<EOL><DEDENT>return configdir<EOL><DEDENT>h = get_home()<EOL>p = os.path.join(get_home(), '<STR_LIT>')<EOL>if os.path.exists(p):<EOL><INDENT>if not _is_writable_dir(p):<EOL><INDENT>raise RuntimeError("<STR_LIT>"% (h, h))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if not _is_writable_dir(h):<EOL><INDENT>raise RuntimeError("<STR_LIT>"%h)<EOL><DEDENT>os.mkdir(p)<EOL><DEDENT>return p<EOL>

Return the string representing the configuration dir.

default is HOME/.matplotlib.  you can override this with the
MPLCONFIGDIR environment variable


self._alpha = alpha<EOL>

Set the alpha value used for blending - not supported on
all backends


newCanvas = FigureCanvasClass(self.figure)<EOL>return newCanvas<EOL>

instantiate an instance of FigureCanvasClass

This is used for backend switching, eg, to instantiate a
FigureCanvasPS from a FigureCanvasGTK.  Note, deep copying is
not done, so any changes to one of the instances (eg, setting
figure size or line props), will be reflected in the other


self._snap = snap<EOL>

Sets the snap setting which may be:

  * True: snap vertices to the nearest pixel center

  * False: leave vertices as-is

  * None: (auto) If the path contains only rectilinear line
    segments, round to the nearest pixel center


self._views.forward()<EOL>self._positions.forward()<EOL>self.set_history_buttons()<EOL>self._update_view()<EOL>


def _iter_collection_raw_paths(self, master_transform, paths, all_transforms):

Npaths      = len(paths)<EOL>Ntransforms = len(all_transforms)<EOL>N           = max(Npaths, Ntransforms)<EOL>if Npaths == <NUM_LIT:0>:<EOL><INDENT>return<EOL><DEDENT>transform = transforms.IdentityTransform()<EOL>for i in range(N):<EOL><INDENT>path = paths[i % Npaths]<EOL>if Ntransforms:<EOL><INDENT>transform = all_transforms[i % Ntransforms]<EOL><DEDENT>yield path, transform + master_transform<EOL><DEDENT>

This is a helper method (along with :meth:`_iter_collection`) to make
it easier to write a space-efficent :meth:`draw_path_collection`
implementation in a backend.

This method yields all of the base path/transform
combinations, given a master transform, a list of paths and
list of transforms.

The arguments should be exactly what is passed in to
:meth:`draw_path_collection`.

The backend should take each yielded path and transform and
create an object that can be referenced (reused) later.


return True<EOL>

Return true if y small numbers are top for renderer Is used
for drawing text (:mod:`matplotlib.text`) and images
(:mod:`matplotlib.image`) only


pass<EOL>

this will be called whenever mouse button is released


self._cliprect = rectangle<EOL>

Set the clip rectangle with sequence (left, bottom, width, height)


def key_release_event(self, key, guiEvent=None):

s = '<STR_LIT>'<EOL>event = KeyEvent(s, self, key, self._lastx, self._lasty, guiEvent=guiEvent)<EOL>self.callbacks.process(s, event)<EOL>self._key = None<EOL>

This method will be call all functions connected to the
'key_release_event' with a :class:`KeyEvent`


pass<EOL>


for a, ind in self._xypress:<EOL><INDENT>a.drag_pan(self._button_pressed, event.key, event.x, event.y)<EOL><DEDENT>self.dynamic_update()<EOL>


try:<EOL><INDENT>offset, dashes = self.dashd[style]<EOL><DEDENT>except:<EOL><INDENT>raise ValueError('<STR_LIT>' % style)<EOL><DEDENT>self._linestyle = style<EOL>self.set_dashes(offset, dashes)<EOL>

Set the linestyle to be one of ('solid', 'dashed', 'dashdot',
'dotted').


event = Event('<STR_LIT>', self, guiEvent)<EOL>self.callbacks.process('<STR_LIT>', event)<EOL>

Backend derived classes should call this function when entering
canvas

*guiEvent*
    the native UI event that generated the mpl event


return self._url<EOL>

returns a url if one is set, None otherwise


return self.callbacks.disconnect(cid)<EOL>

disconnect callback id cid

Example usage::

    cid = canvas.mpl_connect('button_press_event', on_press)
    #...later
    canvas.mpl_disconnect(cid)


s = '<STR_LIT>'<EOL>event = IdleEvent(s, self, guiEvent=guiEvent)<EOL>self.callbacks.process(s, event)<EOL>


if self._active == '<STR_LIT>':<EOL><INDENT>self._active = None<EOL><DEDENT>else:<EOL><INDENT>self._active = '<STR_LIT>'<EOL><DEDENT>if self._idPress is not None:<EOL><INDENT>self._idPress=self.canvas.mpl_disconnect(self._idPress)<EOL>self.mode = '<STR_LIT>'<EOL><DEDENT>if self._idRelease is not None:<EOL><INDENT>self._idRelease=self.canvas.mpl_disconnect(self._idRelease)<EOL>self.mode = '<STR_LIT>'<EOL><DEDENT>if  self._active:<EOL><INDENT>self._idPress = self.canvas.mpl_connect('<STR_LIT>', self.press_zoom)<EOL>self._idRelease = self.canvas.mpl_connect('<STR_LIT>', self.release_zoom)<EOL>self.mode = '<STR_LIT>'<EOL>self.canvas.widgetlock(self)<EOL><DEDENT>else:<EOL><INDENT>self.canvas.widgetlock.release(self)<EOL><DEDENT>for a in self.canvas.figure.get_axes():<EOL><INDENT>a.set_navigate_mode(self._active)<EOL><DEDENT>self.set_message(self.mode)<EOL>


self._alpha = gc._alpha<EOL>self._antialiased = gc._antialiased<EOL>self._capstyle = gc._capstyle<EOL>self._cliprect = gc._cliprect<EOL>self._clippath = gc._clippath<EOL>self._dashes = gc._dashes<EOL>self._joinstyle = gc._joinstyle<EOL>self._linestyle = gc._linestyle<EOL>self._linewidth = gc._linewidth<EOL>self._rgb = gc._rgb<EOL>self._hatch = gc._hatch<EOL>self._url = gc._url<EOL>self._snap = gc._snap<EOL>


if cs in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>self._capstyle = cs<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>' % cs)<EOL><DEDENT>

Set the capstyle as a string in ('butt', 'round', 'projecting')


def key_press_event(self, key, guiEvent=None):

self._key = key<EOL>s = '<STR_LIT>'<EOL>event = KeyEvent(s, self, key, self._lastx, self._lasty, guiEvent=guiEvent)<EOL>self.callbacks.process(s, event)<EOL>

This method will be call all functions connected to the
'key_press_event' with a :class:`KeyEvent`


pass<EOL>

Open a grouping element with label *s*. Is only currently used by
:mod:`~matplotlib.backends.backend_svg`


self._linewidth = w<EOL>


s = '<STR_LIT>'<EOL>event = ResizeEvent(s, self)<EOL>self.callbacks.process(s, event)<EOL>

This method will be call all functions connected to the
'resize_event' with a :class:`ResizeEvent`


def pick_event(self, mouseevent, artist, **kwargs):

s = '<STR_LIT>'<EOL>event = PickEvent(s, self, mouseevent, artist, **kwargs)<EOL>self.callbacks.process(s, event)<EOL>

This method will be called by artists who are picked and will
fire off :class:`PickEvent` callbacks registered listeners


self._views.back()<EOL>self._positions.back()<EOL>self.set_history_buttons()<EOL>self._update_view()<EOL>


self._rgb = (frac, frac, frac)<EOL>

Set the foreground color to be a gray level with *frac*


return GraphicsContextBase()<EOL>

Return an instance of a :class:`GraphicsContextBase`


self._hatch = hatch<EOL>


self.canvas.mpl_disconnect(self._idDrag)<EOL>self._idDrag=self.canvas.mpl_connect('<STR_LIT>', self.mouse_move)<EOL>for a, ind in self._xypress:<EOL><INDENT>a.end_pan()<EOL><DEDENT>if not self._xypress: return<EOL>self._xypress = []<EOL>self._button_pressed=None<EOL>self.push_current()<EOL>self.release(event)<EOL>self.draw()<EOL>

the release mouse button callback in pan/zoom mode


def sort_artists(artists):<EOL><INDENT>L = [ (h.zorder, h) for h in artists ]<EOL>L.sort()<EOL>return [ h for zorder, h in L ]<EOL><DEDENT>under = sort_artists(self.figure.hitlist(ev))<EOL>h = None<EOL>if under: h = under[-<NUM_LIT:1>]<EOL>while h:<EOL><INDENT>print("<STR_LIT>",h)<EOL>if h.remove():<EOL><INDENT>self.draw_idle()<EOL>break<EOL><DEDENT>parent = None<EOL>for p in under:<EOL><INDENT>if h in p.get_children():<EOL><INDENT>parent = p<EOL>break<EOL><DEDENT><DEDENT>h = parent<EOL><DEDENT>

Mouse event processor which removes the top artist
under the cursor.  Connect this to the 'mouse_press_event'
using::

    canvas.mpl_connect('mouse_press_event',canvas.onRemove)


pass<EOL>


return self._joinstyle<EOL>

Return the line join style as one of ('miter', 'round', 'bevel')


if not hasattr(self,'<STR_LIT>'): self._active = dict()<EOL>under = self.figure.hitlist(ev)<EOL>enter = [a for a in under if a not in self._active]<EOL>leave = [a for a in self._active if a not in under]<EOL>print("<STR_LIT>","<STR_LIT:U+0020>".join([str(x) for x in under]))<EOL>for a in leave:<EOL><INDENT>if hasattr(a,'<STR_LIT>'):<EOL><INDENT>a.set_color(self._active[a])<EOL><DEDENT>elif hasattr(a,'<STR_LIT>'):<EOL><INDENT>a.set_edgecolor(self._active[a][<NUM_LIT:0>])<EOL>a.set_facecolor(self._active[a][<NUM_LIT:1>])<EOL><DEDENT>del self._active[a]<EOL><DEDENT>for a in enter:<EOL><INDENT>if hasattr(a,'<STR_LIT>'):<EOL><INDENT>self._active[a] = a.get_color()<EOL><DEDENT>elif hasattr(a,'<STR_LIT>'):<EOL><INDENT>self._active[a] = (a.get_edgecolor(),a.get_facecolor())<EOL><DEDENT>else: self._active[a] = None<EOL><DEDENT>for a in enter:<EOL><INDENT>if hasattr(a,'<STR_LIT>'):<EOL><INDENT>a.set_color('<STR_LIT>')<EOL><DEDENT>elif hasattr(a,'<STR_LIT>'):<EOL><INDENT>a.set_edgecolor('<STR_LIT>')<EOL>a.set_facecolor('<STR_LIT>')<EOL><DEDENT>else: self._active[a] = None<EOL><DEDENT>self.draw_idle()<EOL>

Mouse event processor which highlights the artists
under the cursor.  Connect this to the 'motion_notify_event'
using::

    canvas.mpl_connect('motion_notify_event',canvas.onHilite)


if event.button == <NUM_LIT:1>:<EOL><INDENT>self._button_pressed=<NUM_LIT:1><EOL><DEDENT>elif  event.button == <NUM_LIT:3>:<EOL><INDENT>self._button_pressed=<NUM_LIT:3><EOL><DEDENT>else:<EOL><INDENT>self._button_pressed=None<EOL>return<EOL><DEDENT>x, y = event.x, event.y<EOL>if self._views.empty(): self.push_current()<EOL>self._xypress=[]<EOL>for i, a in enumerate(self.canvas.figure.get_axes()):<EOL><INDENT>if x is not None and y is not None and a.in_axes(event)and a.get_navigate() and a.can_zoom():<EOL><INDENT>self._xypress.append(( x, y, a, i, a.viewLim.frozen(), a.transData.frozen()))<EOL><DEDENT><DEDENT>self.press(event)<EOL>

the press mouse button in zoom to rect mode callback


def draw_quad_mesh(self, master_transform, cliprect, clippath,<EOL>clippath_trans, meshWidth, meshHeight, coordinates,<EOL>offsets, offsetTrans, facecolors, antialiased,<EOL>showedges):

from matplotlib.collections import QuadMesh<EOL>paths = QuadMesh.convert_mesh_to_paths(<EOL>meshWidth, meshHeight, coordinates)<EOL>if showedges:<EOL><INDENT>edgecolors = np.array([[<NUM_LIT:0.0>, <NUM_LIT:0.0>, <NUM_LIT:0.0>, <NUM_LIT:1.0>]], np.float_)<EOL>linewidths = np.array([<NUM_LIT:1.0>], np.float_)<EOL><DEDENT>else:<EOL><INDENT>edgecolors = facecolors<EOL>linewidths = np.array([<NUM_LIT:0.0>], np.float_)<EOL><DEDENT>return self.draw_path_collection(<EOL>master_transform, cliprect, clippath, clippath_trans,<EOL>paths, [], offsets, offsetTrans, facecolors, edgecolors,<EOL>linewidths, [], [antialiased], [None])<EOL>

This provides a fallback implementation of
:meth:`draw_quad_mesh` that generates paths and then calls
:meth:`draw_path_collection`.


return <NUM_LIT:1.0><EOL>

Get the factor by which to magnify images passed to :meth:`draw_image`.
Allows a backend to have images at a different resolution to other
artists.


s = '<STR_LIT>'<EOL>event = DrawEvent(s, self, renderer)<EOL>self.callbacks.process(s, event)<EOL>

This method will be call all functions connected to the
'draw_event' with a :class:`DrawEvent`


raise NotImplementedError<EOL>

Flush the GUI events for the figure. Implemented only for
backends with GUIs.


if event.button == <NUM_LIT:1>:<EOL><INDENT>self._button_pressed=<NUM_LIT:1><EOL><DEDENT>elif  event.button == <NUM_LIT:3>:<EOL><INDENT>self._button_pressed=<NUM_LIT:3><EOL><DEDENT>else:<EOL><INDENT>self._button_pressed=None<EOL>return<EOL><DEDENT>x, y = event.x, event.y<EOL>if self._views.empty(): self.push_current()<EOL>self._xypress=[]<EOL>for i, a in enumerate(self.canvas.figure.get_axes()):<EOL><INDENT>if x is not None and y is not None and a.in_axes(event) and a.get_navigate():<EOL><INDENT>a.start_pan(x, y, event.button)<EOL>self._xypress.append((a, i))<EOL>self.canvas.mpl_disconnect(self._idDrag)<EOL>self._idDrag=self.canvas.mpl_connect('<STR_LIT>', self.drag_pan)<EOL><DEDENT><DEDENT>self.press(event)<EOL>

the press mouse button in pan/zoom mode callback


def motion_notify_event(self, x, y, guiEvent=None):

self._lastx, self._lasty = x, y<EOL>s = '<STR_LIT>'<EOL>event = MouseEvent(s, self, x, y, self._button, self._key,<EOL>guiEvent=guiEvent)<EOL>self.callbacks.process(s, event)<EOL>

Backend derived classes should call this function on any
motion-notify-event.

*x*
    the canvas coordinates where 0=left

*y*
    the canvas coordinates where 0=bottom

*guiEvent*
    the native UI event that generated the mpl event

This method will be call all functions connected to the
'motion_notify_event' with a :class:`MouseEvent` instance.


self._views.clear()<EOL>self._positions.clear()<EOL>self.set_history_buttons()<EOL>


def button_press_event(self, x, y, button, guiEvent=None):

self._button = button<EOL>s = '<STR_LIT>'<EOL>mouseevent = MouseEvent(s, self, x, y, button, self._key, guiEvent=guiEvent)<EOL>self.callbacks.process(s, mouseevent)<EOL>

Backend derived classes should call this function on any mouse
button press.  x,y are the canvas coords: 0,0 is lower, left.
button and key are as defined in :class:`MouseEvent`.

This method will be call all functions connected to the
'button_press_event' with a :class:`MouseEvent` instance.


return int(self.figure.bbox.width), int(self.figure.bbox.height)<EOL>

return the figure width and height in points or pixels
(depending on the backend), truncated to integers