desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Day of the month, 2 digits with leading zeros; i.e. \'01\' to \'31\''
def d(self):
return (u'%02d' % self.data.day)
'Day of the week, textual, 3 letters; e.g. \'Fri\''
def D(self):
return WEEKDAYS_ABBR[self.data.weekday()]
'Month, textual, long; e.g. \'January\''
def F(self):
return MONTHS[self.data.month]
'\'1\' if Daylight Savings Time, \'0\' otherwise.'
def I(self):
if (self.timezone and self.timezone.dst(self.data)): return u'1' else: return u'0'
'Day of the month without leading zeros; i.e. \'1\' to \'31\''
def j(self):
return self.data.day
'Day of the week, textual, long; e.g. \'Friday\''
def l(self):
return WEEKDAYS[self.data.weekday()]
'Boolean for whether it is a leap year; i.e. True or False'
def L(self):
return calendar.isleap(self.data.year)
'Month; i.e. \'01\' to \'12\''
def m(self):
return (u'%02d' % self.data.month)
'Month, textual, 3 letters; e.g. \'Jan\''
def M(self):
return MONTHS_3[self.data.month].title()
'Month without leading zeros; i.e. \'1\' to \'12\''
def n(self):
return self.data.month
'Month abbreviation in Associated Press style. Proprietary extension.'
def N(self):
return MONTHS_AP[self.data.month]
'Difference to Greenwich time in hours; e.g. \'+0200\''
def O(self):
seconds = self.Z() return (u'%+03d%02d' % ((seconds // 3600), ((seconds // 60) % 60)))
'RFC 2822 formatted date; e.g. \'Thu, 21 Dec 2000 16:01:07 +0200\''
def r(self):
return self.format('D, j M Y H:i:s O')
'English ordinal suffix for the day of the month, 2 characters; i.e. \'st\', \'nd\', \'rd\' or \'th\''
def S(self):
if (self.data.day in (11, 12, 13)): return u'th' last = (self.data.day % 10) if (last == 1): return u'st' if (last == 2): return u'nd' if (last == 3): return u'rd' return u'th'
'Number of days in the given month; i.e. \'28\' to \'31\''
def t(self):
return (u'%02d' % calendar.monthrange(self.data.year, self.data.month)[1])
'Time zone of this machine; e.g. \'EST\' or \'MDT\''
def T(self):
name = ((self.timezone and self.timezone.tzname(self.data)) or None) if (name is None): name = self.format('O') return unicode(name)
'Seconds since the Unix epoch (January 1 1970 00:00:00 GMT)'
def U(self):
if getattr(self.data, 'tzinfo', None): return int(calendar.timegm(self.data.utctimetuple())) else: return int(time.mktime(self.data.timetuple()))
'Day of the week, numeric, i.e. \'0\' (Sunday) to \'6\' (Saturday)'
def w(self):
return ((self.data.weekday() + 1) % 7)
'ISO-8601 week number of year, weeks starting on Monday'
def W(self):
week_number = None jan1_weekday = (self.data.replace(month=1, day=1).weekday() + 1) weekday = (self.data.weekday() + 1) day_of_year = self.z() if ((day_of_year <= (8 - jan1_weekday)) and (jan1_weekday > 4)): if ((jan1_weekday == 5) or ((jan1_weekday == 6) and calendar.isleap((self.data.year ...
'Year, 2 digits; e.g. \'99\''
def y(self):
return unicode(self.data.year)[2:]
'Year, 4 digits; e.g. \'1999\''
def Y(self):
return self.data.year
'Day of the year; i.e. \'0\' to \'365\''
def z(self):
doy = (self.year_days[self.data.month] + self.data.day) if (self.L() and (self.data.month > 2)): doy += 1 return doy
'Time zone offset in seconds (i.e. \'-43200\' to \'43200\'). The offset for timezones west of UTC is always negative, and for those east of UTC is always positive.'
def Z(self):
if (not self.timezone): return 0 offset = self.timezone.utcoffset(self.data) return ((offset.days * 86400) + offset.seconds)
'Construct a LineStyle. See class docstring for details on args.'
def __init__(self, width, on, off, color=None):
self.width = width self.on = on self.off = off self.color = color
'Add a new line to the chart. This is a convenience method which constructs the DataSeries and appends it for you. It returns the new series. points: List of equally-spaced y-values for the line label: Name of the line (used for the legend) color: Hex string, like \'ff0000\' for red pattern: Tuple for (length of ...
def AddLine(self, points, label=None, color=None, pattern=LineStyle.SOLID, width=LineStyle.THIN, markers=None):
if ((color is not None) and isinstance(color[0], common.Marker)): warnings.warn('Your code may be broken! You passed a list of Markers instead of a color. The old argument order (markers before color) is deprecated.', DeprecationWarning, s...
'DEPRECATED'
def AddSeries(self, points, color=None, style=LineStyle.solid, markers=None, label=None):
warnings.warn('LineChart.AddSeries is deprecated. Call AddLine instead. ', DeprecationWarning, stacklevel=2) return self.AddLine(points, color=color, width=style.width, pattern=(style.on, style.off), markers=markers, label=label)
'Get the URL for our graph. Args: use_html_entities: If True, reserved HTML characters (&, <, >, ") in the URL are replaced with HTML entities (&amp;, &lt;, etc.). Default is False.'
def Url(self, width, height, use_html_entities=False):
self._width = width self._height = height params = self._Params(self.chart) return util.EncodeUrl(self.url_base, params, self.escape_url, use_html_entities)
'Get an image tag for our graph.'
def Img(self, width, height):
url = self.Url(width, height, use_html_entities=True) tag = '<img src="%s" width="%s" height="%s" alt="chart"/>' return (tag % (url, width, height))
'Return the correct chart_type param for the chart.'
def _GetType(self, chart):
raise NotImplementedError
'Get a list of formatter functions to use for encoding.'
def _GetFormatters(self):
formatters = [self._GetLegendParams, self._GetDataSeriesParams, self._GetColors, self._GetAxisParams, self._GetGridParams, self._GetType, self._GetExtraParams, self._GetSizeParams] return formatters
'Collect all the different params we need for the URL. Collecting all params as a dict before converting to a URL makes testing easier.'
def _Params(self, chart):
chart = chart.GetFormattedChart() params = {} def Add(new_params): params.update(util.ShortenParameterNames(new_params)) for formatter in self.formatters: Add(formatter(chart)) for key in params: params[key] = str(params[key]) return params
'Get the size param.'
def _GetSizeParams(self, chart):
return {'size': ('%sx%s' % (int(self._width), int(self._height)))}
'Get any extra params (from extra_params).'
def _GetExtraParams(self, chart):
return self.extra_params
'Collect params related to the data series.'
def _GetDataSeriesParams(self, chart):
(y_min, y_max) = (chart.GetDependentAxis().min, chart.GetDependentAxis().max) series_data = [] markers = [] for (i, series) in enumerate(chart.data): data = series.data if (not data): continue series_data.append(data) for (x, marker) in series.markers: ...
'Color series color parameter.'
def _GetColors(self, chart):
colors = [] for series in chart.data: if (not series.data): continue colors.append(series.style.color) return util.JoinLists(color=colors)
'Get a class which can encode the data the way the user requested.'
def _GetDataEncoder(self, chart):
if (not self.enhanced_encoding): return util.SimpleDataEncoder() return util.EnhancedDataEncoder()
'Get params for showing a legend.'
def _GetLegendParams(self, chart):
if chart._show_legend: return util.JoinLists(data_series_label=chart._legend_labels) return {}
'Return axis.labels & axis.label_positions.'
def _GetAxisLabelsAndPositions(self, axis, chart):
return (axis.labels, axis.label_positions)
'Collect params related to our various axes (x, y, right-hand).'
def _GetAxisParams(self, chart):
axis_types = [] axis_ranges = [] axis_labels = [] axis_label_positions = [] axis_label_gridlines = [] mark_length = max(self._width, self._height) for (i, axis_pair) in enumerate((a for a in chart._GetAxes() if a[1].labels)): (axis_type_code, axis) = axis_pair axis_types.appe...
'Collect params related to grid lines.'
def _GetGridParams(self, chart):
x = 0 y = 0 if chart.bottom.grid_spacing: assert (chart.bottom.min is not None) assert (chart.bottom.max is not None) total = float((chart.bottom.max - chart.bottom.min)) x = ((100 * chart.bottom.grid_spacing) / total) if chart.left.grid_spacing: assert (chart.lef...
'Get LineStyle parameters.'
def _GetLineStyles(self, chart):
styles = [] for series in chart.data: style = series.style if style: styles.append(('%s,%s,%s' % (style.width, style.on, style.off))) else: assert (not styles) return util.JoinLists(line_style=styles)
'Construct a new BarChartEncoder. Args: style: DEPRECATED. Set style on the chart object itself.'
def __init__(self, chart, style=None):
super(BarChartEncoder, self).__init__(chart) if (style is not None): warnings.warn(self.__STYLE_DEPRECATION, DeprecationWarning, stacklevel=2) chart.style = style
'Reverse labels on the y-axis in horizontal bar charts. (Otherwise the labels come out backwards from what you would expect)'
def _GetAxisLabelsAndPositions(self, axis, chart):
if ((not chart.vertical) and (axis == chart.left)): return (reversed(axis.labels), reversed(axis.label_positions)) return (axis.labels, axis.label_positions)
'Get the zero-point if any bars are negative.'
def _ZeroPoint(self, chart):
(min, max) = (chart.GetDependentAxis().min, chart.GetDependentAxis().max) out = {} if (min < 0): if (max < 0): out['chp'] = 1 else: out['chp'] = ((- min) / float((max - min))) return out
'If bar style is specified, fill in the missing data and apply it.'
def _ApplyBarChartStyle(self, chart):
if ((chart.style is None) or (not chart.data)): return {} (bar_thickness, bar_gap, group_gap) = (chart.style.bar_thickness, chart.style.bar_gap, chart.style.group_gap) if ((bar_gap is None) and (group_gap is not None)): bar_gap = max(0, (group_gap / 2)) if (not chart.style.use_fracti...
'Construct a new PieChartEncoder. Args: is3d: If True, draw a 3d pie chart. Default is False. If the pie chart includes multiple pies, is3d must be set to False. angle: Angle of rotation of the pie chart, in radians.'
def __init__(self, chart, is3d=False, angle=None):
super(PieChartEncoder, self).__init__(chart) self.is3d = is3d self.angle = None
'Add a formatter for the chart angle.'
def _GetFormatters(self):
formatters = super(PieChartEncoder, self)._GetFormatters() formatters.append(self._GetAngleParams) return formatters
'Collect params related to the data series.'
def _GetDataSeriesParams(self, chart):
pie_points = [] labels = [] max_val = 1 for pie in chart.data: points = [] for segment in pie: if segment: points.append(segment.size) max_val = max(max_val, segment.size) labels.append((segment.label or '')) if points: ...
'If the user specified an angle, add it to the params.'
def _GetAngleParams(self, chart):
if self.angle: return {'chp': str(self.angle)} return {}
'Construct a Marker. See class docstring for details on args.'
def __init__(self, shape, color, size):
self.shape = shape self.color = color self.size = size
'Construct a DataSeries. See class docstring for details on args.'
def __init__(self, points, label=None, style=None, markers=None, color=None):
if ((label is not None) and util._IsColor(label)): warnings.warn('Your code may be broken! Label is a hex triplet. Maybe it is a color? The old argument order (color & style before label) is deprecated.', DeprecationWarning, stac...
'Construct a new Axis. Args: axis_min: smallest value on the axis axis_max: largest value on the axis'
def __init__(self, axis_min=None, axis_max=None):
self.min = axis_min self.max = axis_max self.labels = [] self.label_positions = [] self.grid_spacing = 0 self.label_gridlines = False
'Construct a BaseChart object.'
def __init__(self):
self.data = [] self._axes = {} for code in self._POSITION_CODES: self._axes[code] = [Axis()] self._legend_labels = [] self._show_legend = False self.auto_color = formatters.AutoColor() self.auto_scale = formatters.AutoScale() self.auto_legend = formatters.AutoLegend self.form...
'Add a new formatter to the chart (convenience method).'
def AddFormatter(self, formatter):
self.formatters.append(formatter)
'DEPRECATED Add a new series of data to the chart; return the DataSeries object.'
def AddSeries(self, points, color=None, style=None, markers=None, label=None):
warnings.warn('AddSeries is deprecated. Instead, call AddLine for LineCharts, AddBars for BarCharts, AddSegment for PieCharts ', DeprecationWarning, stacklevel=2) series = DataSeries(points, color=color, style=style, markers=markers, label=label) self.data.appen...
'Return any dependent axes (\'left\' and \'right\' by default for LineCharts, although bar charts would use \'bottom\' and \'top\').'
def GetDependentAxes(self):
return (self._axes[AxisPosition.LEFT] + self._axes[AxisPosition.RIGHT])
'Return any independent axes (normally top & bottom, although horizontal bar charts use left & right by default).'
def GetIndependentAxes(self):
return (self._axes[AxisPosition.TOP] + self._axes[AxisPosition.BOTTOM])
'Return this chart\'s main dependent axis (often \'left\', but horizontal bar-charts use \'bottom\').'
def GetDependentAxis(self):
return self.left
'Return this chart\'s main independent axis (often \'bottom\', but horizontal bar-charts use \'left\').'
def GetIndependentAxis(self):
return self.bottom
'Make a deep copy this chart. Formatters & display will be missing from the copy, due to limitations in deepcopy.'
def _Clone(self):
orig_values = {} uncopyables = ['formatters', 'display', 'auto_color', 'auto_scale', 'auto_legend'] for name in uncopyables: orig_values[name] = getattr(self, name) setattr(self, name, None) clone = copy.deepcopy(self) for (name, orig_value) in orig_values.iteritems(): setatt...
'Get a copy of the chart with formatting applied.'
def GetFormattedChart(self):
scratchpad = self._Clone() for formatter in self.formatters: formatter(scratchpad) return scratchpad
'Get the largest & smallest values in this chart, returned as (min_value, max_value). Takes into account complciations like stacked data series. For example, with non-stacked series, a chart with [1, 2, 3] and [4, 5, 6] would return (1, 6). If the same chart was stacking the data series, it would return (5, 9).'
def GetMinMaxValues(self):
MinPoint = (lambda data: min((x for x in data if (x is not None)))) MaxPoint = (lambda data: max((x for x in data if (x is not None)))) mins = [MinPoint(series.data) for series in self.data if series.data] maxes = [MaxPoint(series.data) for series in self.data if series.data] if ((not mins) or (not ...
'Add an axis to this chart in the given position. Args: position: an AxisPosition object specifying the axis\'s position axis: The axis to add, an Axis object Returns: the value of the axis parameter'
def AddAxis(self, position, axis):
self._axes.setdefault(position, []).append(axis) return axis
'Get or create the first available axis in the given position. This is a helper method for the left, right, top, and bottom properties. If the specified axis does not exist, it will be created. Args: position: the position to search for Returns: The first axis in the given position'
def GetAxis(self, position):
if (position in self._axes): return self._axes[position][0] else: axis = Axis() self._axes[position] = [axis] return axis
'Set the first axis in the given position to the given value. This is a helper method for the left, right, top, and bottom properties. Args: position: an AxisPosition object specifying the axis\'s position axis: The axis to set, an Axis object Returns: the value of the axis parameter'
def SetAxis(self, position, axis):
self._axes.setdefault(position, [None])[0] = axis return axis
'Return a generator of (position_code, Axis) tuples for this chart\'s axes. The axes will be sorted by position using the canonical ordering sequence, _POSITION_CODES.'
def _GetAxes(self):
for code in self._POSITION_CODES: for axis in self._axes.get(code, []): (yield (code, axis))
'Create a new BarChartStyle. Args: bar_thickness: The thickness of a bar, in pixels. Set this to None if you want the bar thickness to be auto-calculated (this is the default behaviour). bar_gap: The gap between bars, in pixels. Default is 4. group_gap: The gap between groups of bars, in pixels. Default is 8.'
def __init__(self, bar_thickness=None, bar_gap=_DEFAULT_BAR_GAP, group_gap=_DEFAULT_GROUP_GAP, use_fractional_gap_spacing=False):
self.bar_thickness = bar_thickness self.bar_gap = bar_gap self.group_gap = group_gap self.use_fractional_gap_spacing = use_fractional_gap_spacing
'Constructor for BarChart objects.'
def __init__(self, points=None):
super(BarChart, self).__init__() if (points is not None): self.AddBars(points) self.vertical = True self.stacked = False self.style = BarChartStyle(None, None, None)
'Add a series of bars to the chart. points: List of y-values for the bars in this series label: Name of the series (used in the legend) color: Hex string, like \'00ff00\' for green This is a convenience method which constructs & appends the DataSeries for you.'
def AddBars(self, points, label=None, color=None):
if ((label is not None) and util._IsColor(label)): warnings.warn('Your code may be broken! Label is a hex triplet. Maybe it is a color? The old argument order (color before label) is deprecated.', DeprecationWarning, stacklevel=2) ...
'Get the dependendant axes, which depend on orientation.'
def GetDependentAxes(self):
if self.vertical: return (self._axes[common.AxisPosition.LEFT] + self._axes[common.AxisPosition.RIGHT]) else: return (self._axes[common.AxisPosition.TOP] + self._axes[common.AxisPosition.BOTTOM])
'Get the independendant axes, which depend on orientation.'
def GetIndependentAxes(self):
if self.vertical: return (self._axes[common.AxisPosition.TOP] + self._axes[common.AxisPosition.BOTTOM]) else: return (self._axes[common.AxisPosition.LEFT] + self._axes[common.AxisPosition.RIGHT])
'Get the main dependendant axis, which depends on orientation.'
def GetDependentAxis(self):
if self.vertical: return self.left else: return self.bottom
'Get the main independendant axis, which depends on orientation.'
def GetIndependentAxis(self):
if self.vertical: return self.bottom else: return self.left
'Get the largest & smallest bar values as (min_value, max_value).'
def GetMinMaxValues(self):
if (not self.stacked): return super(BarChart, self).GetMinMaxValues() if (not self.data): return (None, None) num_bars = max((len(series.data) for series in self.data)) positives = [0 for i in xrange(0, num_bars)] negatives = list(positives) for series in self.data: for (...
'Constructor for PieChart objects. Creates a pie chart with a single pie. Args: points: A list of data points for the pie chart; i.e., relative sizes of the pie segments labels: A list of labels for the pie segments. TODO: Allow the user to pass in None as one of the labels in order to skip that label. colors: A list o...
def __init__(self, points=None, labels=None, colors=None):
super(PieChart, self).__init__() self.formatters = [] self._colors = None if points: self.AddPie(points, labels, colors)
'Add a whole pie to the chart. Args: points: A list of pie segment sizes labels: A list of labels for the pie segments colors: A list of colors for the segments. Missing colors will be chosen automatically. Return: The index of the newly added pie.'
def AddPie(self, points, labels=None, colors=None):
num_colors = len((colors or [])) num_labels = len((labels or [])) pie_index = len(self.data) self.data.append([]) for (i, pt) in enumerate(points): label = None if (i < num_labels): label = labels[i] color = None if (i < num_colors): color = co...
'DEPRECATED.'
def AddSegments(self, points, labels, colors):
warnings.warn('PieChart.AddSegments is deprecated. Call AddPie instead. ', DeprecationWarning, stacklevel=2) num_colors = len((colors or [])) for (i, pt) in enumerate(points): assert (pt >= 0) label = labels[i] color = None if (i < num_colors): c...
'Add a pie segment to this chart, and return the segment. size: The size of the segment. label: The label for the segment. color: The color of the segment, or None to automatically choose the color. pie_index: The index of the pie that will receive the new segment. By default, the chart has one pie (pie #0); use the Ad...
def AddSegment(self, size, label=None, color=None, pie_index=0):
if isinstance(size, Segment): warnings.warn('AddSegment(segment) is deprecated. Use AddSegment(size, label, color) instead', DeprecationWarning, stacklevel=2) segment = size else: segment = Segment(size, label=label, color=color) assert (segment.size >= 0) ...
'DEPRECATED Add a new segment to the chart and return it. The segment must contain exactly one data point; all parameters other than color and label are ignored.'
def AddSeries(self, points, color=None, style=None, markers=None, label=None):
warnings.warn('PieChart.AddSeries is deprecated. Call AddSegment or AddSegments instead.', DeprecationWarning) return self.AddSegment(Segment(points[0], color=color, label=label))
'Change the colors of this chart to the specified list of colors. Note that this will completely override the individual colors specified in the pie segments. Missing colors will be interpolated, so that the list of colors covers all segments in all the pies.'
def SetColors(self, *colors):
self._colors = colors
'Create a new AutoScale formatter. Args: buffer: percentage of extra space to allocate around the chart\'s axes.'
def __init__(self, buffer=0.05):
self.buffer = buffer
'Format the chart by setting the min/max values on its dependent axis.'
def __call__(self, chart):
if (not chart.data): return (min_value, max_value) = chart.GetMinMaxValues() if (None in (min_value, max_value)): return for axis in chart.GetDependentAxes(): if (axis.min is not None): min_value = axis.min if (axis.max is not None): max_value = ax...
'Return the token type or char of the unexpected input element'
def getUnexpectedType(self):
from google.appengine._internal.antlr3.streams import TokenStream from google.appengine._internal.antlr3.tree import TreeNodeStream if isinstance(self.input, TokenStream): return self.token.type elif isinstance(self.input, TreeNodeStream): adaptor = self.input.treeAdaptor return ...
'Tree tracks parent and child index now > 3.0'
def getParent(self):
raise NotImplementedError
'Tree tracks parent and child index now > 3.0'
def setParent(self, t):
raise NotImplementedError
'This node is what child index? 0..n-1'
def getChildIndex(self):
raise NotImplementedError
'This node is what child index? 0..n-1'
def setChildIndex(self, index):
raise NotImplementedError
'Set the parent and child index values for all children'
def freshenParentAndChildIndexes(self):
raise NotImplementedError
'Add t as a child to this node. If t is null, do nothing. If t is nil, add all children of t to this\' children.'
def addChild(self, t):
raise NotImplementedError
'Set ith child (0..n-1) to t; t must be non-null and non-nil node'
def setChild(self, i, t):
raise NotImplementedError
'Delete children from start to stop and replace with t even if t is a list (nil-root tree). num of children can increase or decrease. For huge child lists, inserting children can force walking rest of children to set their childindex; could be slow.'
def replaceChildren(self, startChildIndex, stopChildIndex, t):
raise NotImplementedError
'Indicates the node is a nil node but may still have children, meaning the tree is a flat list.'
def isNil(self):
raise NotImplementedError
'What is the smallest token index (indexing from 0) for this node and its children?'
def getTokenStartIndex(self):
raise NotImplementedError
'What is the largest token index (indexing from 0) for this node and its children?'
def getTokenStopIndex(self):
raise NotImplementedError
'Return a token type; needed for tree parsing.'
def getType(self):
raise NotImplementedError
'In case we don\'t have a token payload, what is the line for errors?'
def getLine(self):
raise NotImplementedError
'Create a tree node from Token object; for CommonTree type trees, then the token just becomes the payload. This is the most common create call. Override if you want another kind of node to be built.'
def createWithPayload(self, payload):
raise NotImplementedError
'Duplicate a single tree node. Override if you want another kind of node to be built.'
def dupNode(self, treeNode):
raise NotImplementedError
'Duplicate tree recursively, using dupNode() for each node'
def dupTree(self, tree):
raise NotImplementedError
'Return a nil node (an empty but non-null node) that can hold a list of element as the children. If you want a flat tree (a list) use "t=adaptor.nil(); t.addChild(x); t.addChild(y);"'
def nil(self):
raise NotImplementedError