diff --git "a/codeparrot-valid_1036.txt" "b/codeparrot-valid_1036.txt" new file mode 100644--- /dev/null +++ "b/codeparrot-valid_1036.txt" @@ -0,0 +1,10000 @@ + left, right = split_path_inout(path, insideA) + except ValueError: + right = path + + path = right + + if patchB: + def insideB(xy_display): + xy_event = ConnectionStyle._Base.SimpleEvent(xy_display) + return patchB.contains(xy_event)[0] + + try: + left, right = split_path_inout(path, insideB) + except ValueError: + left = path + + path = left + + return path + + def _shrink(self, path, shrinkA, shrinkB): + """ + Shrink the path by fixed size (in points) with shrinkA and shrinkB + """ + if shrinkA: + x, y = path.vertices[0] + insideA = inside_circle(x, y, shrinkA) + + try: + left, right = split_path_inout(path, insideA) + path = right + except ValueError: + pass + + if shrinkB: + x, y = path.vertices[-1] + insideB = inside_circle(x, y, shrinkB) + + try: + left, right = split_path_inout(path, insideB) + path = left + except ValueError: + pass + + return path + + def __call__(self, posA, posB, + shrinkA=2., shrinkB=2., patchA=None, patchB=None): + """ + Calls the *connect* method to create a path between *posA* + and *posB*. The path is clipped and shrunken. + """ + + path = self.connect(posA, posB) + + clipped_path = self._clip(path, patchA, patchB) + shrunk_path = self._shrink(clipped_path, shrinkA, shrinkB) + + return shrunk_path + + def __reduce__(self): + # because we have decided to nest these classes, we need to + # add some more information to allow instance pickling. + import matplotlib.cbook as cbook + return (cbook._NestedClassGetter(), + (ConnectionStyle, self.__class__.__name__), + self.__dict__ + ) + + class Arc3(_Base): + """ + Creates a simple quadratic bezier curve between two + points. The curve is created so that the middle contol points + (C1) is located at the same distance from the start (C0) and + end points(C2) and the distance of the C1 to the line + connecting C0-C2 is *rad* times the distance of C0-C2. + """ + + def __init__(self, rad=0.): + """ + *rad* + curvature of the curve. + """ + self.rad = rad + + def connect(self, posA, posB): + x1, y1 = posA + x2, y2 = posB + x12, y12 = (x1 + x2) / 2., (y1 + y2) / 2. + dx, dy = x2 - x1, y2 - y1 + + f = self.rad + + cx, cy = x12 + f * dy, y12 - f * dx + + vertices = [(x1, y1), + (cx, cy), + (x2, y2)] + codes = [Path.MOVETO, + Path.CURVE3, + Path.CURVE3] + + return Path(vertices, codes) + + _style_list["arc3"] = Arc3 + + class Angle3(_Base): + """ + Creates a simple quadratic bezier curve between two + points. The middle control points is placed at the + intersecting point of two lines which crosses the start (or + end) point and has a angle of angleA (or angleB). + """ + + def __init__(self, angleA=90, angleB=0): + """ + *angleA* + starting angle of the path + + *angleB* + ending angle of the path + """ + + self.angleA = angleA + self.angleB = angleB + + def connect(self, posA, posB): + x1, y1 = posA + x2, y2 = posB + + cosA, sinA = (math.cos(self.angleA / 180. * math.pi), + math.sin(self.angleA / 180. * math.pi)) + cosB, sinB = (math.cos(self.angleB / 180. * math.pi), + math.sin(self.angleB / 180. * math.pi)) + + cx, cy = get_intersection(x1, y1, cosA, sinA, + x2, y2, cosB, sinB) + + vertices = [(x1, y1), (cx, cy), (x2, y2)] + codes = [Path.MOVETO, Path.CURVE3, Path.CURVE3] + + return Path(vertices, codes) + + _style_list["angle3"] = Angle3 + + class Angle(_Base): + """ + Creates a picewise continuous quadratic bezier path between + two points. The path has a one passing-through point placed at + the intersecting point of two lines which crosses the start + (or end) point and has a angle of angleA (or angleB). The + connecting edges are rounded with *rad*. + """ + + def __init__(self, angleA=90, angleB=0, rad=0.): + """ + *angleA* + starting angle of the path + + *angleB* + ending angle of the path + + *rad* + rounding radius of the edge + """ + + self.angleA = angleA + self.angleB = angleB + + self.rad = rad + + def connect(self, posA, posB): + x1, y1 = posA + x2, y2 = posB + + cosA, sinA = (math.cos(self.angleA / 180. * math.pi), + math.sin(self.angleA / 180. * math.pi)) + cosB, sinB = (math.cos(self.angleB / 180. * math.pi), + math.sin(self.angleB / 180. * math.pi)) + + cx, cy = get_intersection(x1, y1, cosA, sinA, + x2, y2, cosB, sinB) + + vertices = [(x1, y1)] + codes = [Path.MOVETO] + + if self.rad == 0.: + vertices.append((cx, cy)) + codes.append(Path.LINETO) + else: + dx1, dy1 = x1 - cx, y1 - cy + d1 = (dx1 ** 2 + dy1 ** 2) ** .5 + f1 = self.rad / d1 + dx2, dy2 = x2 - cx, y2 - cy + d2 = (dx2 ** 2 + dy2 ** 2) ** .5 + f2 = self.rad / d2 + vertices.extend([(cx + dx1 * f1, cy + dy1 * f1), + (cx, cy), + (cx + dx2 * f2, cy + dy2 * f2)]) + codes.extend([Path.LINETO, Path.CURVE3, Path.CURVE3]) + + vertices.append((x2, y2)) + codes.append(Path.LINETO) + + return Path(vertices, codes) + + _style_list["angle"] = Angle + + class Arc(_Base): + """ + Creates a picewise continuous quadratic bezier path between + two points. The path can have two passing-through points, a + point placed at the distance of armA and angle of angleA from + point A, another point with respect to point B. The edges are + rounded with *rad*. + """ + + def __init__(self, angleA=0, angleB=0, armA=None, armB=None, rad=0.): + """ + *angleA* : + starting angle of the path + + *angleB* : + ending angle of the path + + *armA* : + length of the starting arm + + *armB* : + length of the ending arm + + *rad* : + rounding radius of the edges + """ + + self.angleA = angleA + self.angleB = angleB + self.armA = armA + self.armB = armB + + self.rad = rad + + def connect(self, posA, posB): + x1, y1 = posA + x2, y2 = posB + + vertices = [(x1, y1)] + rounded = [] + codes = [Path.MOVETO] + + if self.armA: + cosA = math.cos(self.angleA / 180. * math.pi) + sinA = math.sin(self.angleA / 180. * math.pi) + # x_armA, y_armB + d = self.armA - self.rad + rounded.append((x1 + d * cosA, y1 + d * sinA)) + d = self.armA + rounded.append((x1 + d * cosA, y1 + d * sinA)) + + if self.armB: + cosB = math.cos(self.angleB / 180. * math.pi) + sinB = math.sin(self.angleB / 180. * math.pi) + x_armB, y_armB = x2 + self.armB * cosB, y2 + self.armB * sinB + + if rounded: + xp, yp = rounded[-1] + dx, dy = x_armB - xp, y_armB - yp + dd = (dx * dx + dy * dy) ** .5 + + rounded.append((xp + self.rad * dx / dd, + yp + self.rad * dy / dd)) + vertices.extend(rounded) + codes.extend([Path.LINETO, + Path.CURVE3, + Path.CURVE3]) + else: + xp, yp = vertices[-1] + dx, dy = x_armB - xp, y_armB - yp + dd = (dx * dx + dy * dy) ** .5 + + d = dd - self.rad + rounded = [(xp + d * dx / dd, yp + d * dy / dd), + (x_armB, y_armB)] + + if rounded: + xp, yp = rounded[-1] + dx, dy = x2 - xp, y2 - yp + dd = (dx * dx + dy * dy) ** .5 + + rounded.append((xp + self.rad * dx / dd, + yp + self.rad * dy / dd)) + vertices.extend(rounded) + codes.extend([Path.LINETO, + Path.CURVE3, + Path.CURVE3]) + + vertices.append((x2, y2)) + codes.append(Path.LINETO) + + return Path(vertices, codes) + + _style_list["arc"] = Arc + + class Bar(_Base): + """ + A line with *angle* between A and B with *armA* and + *armB*. One of the arms is extended so that they are connected in + a right angle. The length of armA is determined by (*armA* + + *fraction* x AB distance). Same for armB. + """ + + def __init__(self, armA=0., armB=0., fraction=0.3, angle=None): + """ + Parameters + ---------- + armA : float + minimum length of armA + + armB : float + minimum length of armB + + fraction : float + a fraction of the distance between two points that + will be added to armA and armB. + + angle : float or None + angle of the connecting line (if None, parallel + to A and B) + """ + self.armA = armA + self.armB = armB + self.fraction = fraction + self.angle = angle + + def connect(self, posA, posB): + x1, y1 = posA + x20, y20 = x2, y2 = posB + + x12, y12 = (x1 + x2) / 2., (y1 + y2) / 2. + + theta1 = math.atan2(y2 - y1, x2 - x1) + dx, dy = x2 - x1, y2 - y1 + dd = (dx * dx + dy * dy) ** .5 + ddx, ddy = dx / dd, dy / dd + + armA, armB = self.armA, self.armB + + if self.angle is not None: + #angle = self.angle % 180. + #if angle < 0. or angle > 180.: + # angle + #theta0 = (self.angle%180.)/180.*math.pi + theta0 = self.angle / 180. * math.pi + #theta0 = (((self.angle+90)%180.) - 90.)/180.*math.pi + dtheta = theta1 - theta0 + dl = dd * math.sin(dtheta) + + dL = dd * math.cos(dtheta) + + #x2, y2 = x2 + dl*ddy, y2 - dl*ddx + x2, y2 = x1 + dL * math.cos(theta0), y1 + dL * math.sin(theta0) + + armB = armB - dl + + # update + dx, dy = x2 - x1, y2 - y1 + dd2 = (dx * dx + dy * dy) ** .5 + ddx, ddy = dx / dd2, dy / dd2 + + else: + dl = 0. + + #if armA > armB: + # armB = armA + dl + #else: + # armA = armB - dl + + arm = max(armA, armB) + f = self.fraction * dd + arm + #fB = self.fraction*dd + armB + + cx1, cy1 = x1 + f * ddy, y1 - f * ddx + cx2, cy2 = x2 + f * ddy, y2 - f * ddx + + vertices = [(x1, y1), + (cx1, cy1), + (cx2, cy2), + (x20, y20)] + codes = [Path.MOVETO, + Path.LINETO, + Path.LINETO, + Path.LINETO] + + return Path(vertices, codes) + + _style_list["bar"] = Bar + + if __doc__: + __doc__ = cbook.dedent(__doc__) % \ + {"AvailableConnectorstyles": _pprint_styles(_style_list)} + + +def _point_along_a_line(x0, y0, x1, y1, d): + """ + find a point along a line connecting (x0, y0) -- (x1, y1) whose + distance from (x0, y0) is d. + """ + dx, dy = x0 - x1, y0 - y1 + ff = d / (dx * dx + dy * dy) ** .5 + x2, y2 = x0 - ff * dx, y0 - ff * dy + + return x2, y2 + + +class ArrowStyle(_Style): + """ + :class:`ArrowStyle` is a container class which defines several + arrowstyle classes, which is used to create an arrow path along a + given path. These are mainly used with :class:`FancyArrowPatch`. + + A arrowstyle object can be either created as:: + + ArrowStyle.Fancy(head_length=.4, head_width=.4, tail_width=.4) + + or:: + + ArrowStyle("Fancy", head_length=.4, head_width=.4, tail_width=.4) + + or:: + + ArrowStyle("Fancy, head_length=.4, head_width=.4, tail_width=.4") + + The following classes are defined + + %(AvailableArrowstyles)s + + + An instance of any arrow style class is a callable object, + whose call signature is:: + + __call__(self, path, mutation_size, linewidth, aspect_ratio=1.) + + and it returns a tuple of a :class:`Path` instance and a boolean + value. *path* is a :class:`Path` instance along which the arrow + will be drawn. *mutation_size* and *aspect_ratio* have the same + meaning as in :class:`BoxStyle`. *linewidth* is a line width to be + stroked. This is meant to be used to correct the location of the + head so that it does not overshoot the destination point, but not all + classes support it. + + .. plot:: mpl_examples/pylab_examples/fancyarrow_demo.py + """ + + _style_list = {} + + class _Base(object): + """ + Arrow Transmuter Base class + + ArrowTransmuterBase and its derivatives are used to make a fancy + arrow around a given path. The __call__ method returns a path + (which will be used to create a PathPatch instance) and a boolean + value indicating the path is open therefore is not fillable. This + class is not an artist and actual drawing of the fancy arrow is + done by the FancyArrowPatch class. + + """ + + # The derived classes are required to be able to be initialized + # w/o arguments, i.e., all its argument (except self) must have + # the default values. + + def __init__(self): + super(ArrowStyle._Base, self).__init__() + + @staticmethod + def ensure_quadratic_bezier(path): + """ Some ArrowStyle class only wokrs with a simple + quaratic bezier curve (created with Arc3Connetion or + Angle3Connector). This static method is to check if the + provided path is a simple quadratic bezier curve and returns + its control points if true. + """ + segments = list(path.iter_segments()) + if ((len(segments) != 2) or (segments[0][1] != Path.MOVETO) or + (segments[1][1] != Path.CURVE3)): + msg = "'path' it's not a valid quadratic bezier curve" + raise ValueError(msg) + + return list(segments[0][0]) + list(segments[1][0]) + + def transmute(self, path, mutation_size, linewidth): + """ + The transmute method is the very core of the ArrowStyle + class and must be overriden in the subclasses. It receives + the path object along which the arrow will be drawn, and + the mutation_size, with which the arrow head etc. + will be scaled. The linewidth may be used to adjust + the path so that it does not pass beyond the given + points. It returns a tuple of a Path instance and a + boolean. The boolean value indicate whether the path can + be filled or not. The return value can also be a list of paths + and list of booleans of a same length. + """ + + raise NotImplementedError('Derived must override') + + def __call__(self, path, mutation_size, linewidth, + aspect_ratio=1.): + """ + The __call__ method is a thin wrapper around the transmute method + and take care of the aspect ratio. + """ + + path = make_path_regular(path) + + if aspect_ratio is not None: + # Squeeze the given height by the aspect_ratio + + vertices, codes = path.vertices[:], path.codes[:] + # Squeeze the height + vertices[:, 1] = vertices[:, 1] / aspect_ratio + path_shrunk = Path(vertices, codes) + # call transmute method with squeezed height. + path_mutated, fillable = self.transmute(path_shrunk, + linewidth, + mutation_size) + if cbook.iterable(fillable): + path_list = [] + for p in zip(path_mutated): + v, c = p.vertices, p.codes + # Restore the height + v[:, 1] = v[:, 1] * aspect_ratio + path_list.append(Path(v, c)) + return path_list, fillable + else: + return path_mutated, fillable + else: + return self.transmute(path, mutation_size, linewidth) + + def __reduce__(self): + # because we have decided to nest thes classes, we need to + # add some more information to allow instance pickling. + import matplotlib.cbook as cbook + return (cbook._NestedClassGetter(), + (ArrowStyle, self.__class__.__name__), + self.__dict__ + ) + + class _Curve(_Base): + """ + A simple arrow which will work with any path instance. The + returned path is simply concatenation of the original path + at + most two paths representing the arrow head at the begin point and the + at the end point. The arrow heads can be either open or closed. + """ + + def __init__(self, beginarrow=None, endarrow=None, + fillbegin=False, fillend=False, + head_length=.2, head_width=.1): + """ + The arrows are drawn if *beginarrow* and/or *endarrow* are + true. *head_length* and *head_width* determines the size + of the arrow relative to the *mutation scale*. The + arrowhead at the begin (or end) is closed if fillbegin (or + fillend) is True. + """ + self.beginarrow, self.endarrow = beginarrow, endarrow + self.head_length, self.head_width = head_length, head_width + self.fillbegin, self.fillend = fillbegin, fillend + super(ArrowStyle._Curve, self).__init__() + + def _get_arrow_wedge(self, x0, y0, x1, y1, + head_dist, cos_t, sin_t, linewidth + ): + """ + Return the paths for arrow heads. Since arrow lines are + drawn with capstyle=projected, The arrow goes beyond the + desired point. This method also returns the amount of the path + to be shrunken so that it does not overshoot. + """ + + # arrow from x0, y0 to x1, y1 + dx, dy = x0 - x1, y0 - y1 + + cp_distance = np.hypot(dx, dy) + + # pad_projected : amount of pad to account the + # overshooting of the projection of the wedge + pad_projected = (.5 * linewidth / sin_t) + + # Account for division by zero + if cp_distance == 0: + cp_distance = 1 + + # apply pad for projected edge + ddx = pad_projected * dx / cp_distance + ddy = pad_projected * dy / cp_distance + + # offset for arrow wedge + dx = dx / cp_distance * head_dist + dy = dy / cp_distance * head_dist + + dx1, dy1 = cos_t * dx + sin_t * dy, -sin_t * dx + cos_t * dy + dx2, dy2 = cos_t * dx - sin_t * dy, sin_t * dx + cos_t * dy + + vertices_arrow = [(x1 + ddx + dx1, y1 + ddy + dy1), + (x1 + ddx, y1 + ddy), + (x1 + ddx + dx2, y1 + ddy + dy2)] + codes_arrow = [Path.MOVETO, + Path.LINETO, + Path.LINETO] + + return vertices_arrow, codes_arrow, ddx, ddy + + def transmute(self, path, mutation_size, linewidth): + + head_length, head_width = self.head_length * mutation_size, \ + self.head_width * mutation_size + head_dist = math.sqrt(head_length ** 2 + head_width ** 2) + cos_t, sin_t = head_length / head_dist, head_width / head_dist + + # begin arrow + x0, y0 = path.vertices[0] + x1, y1 = path.vertices[1] + + # If there is no room for an arrow and a line, then skip the arrow + has_begin_arrow = (self.beginarrow and + not ((x0 == x1) and (y0 == y1))) + if has_begin_arrow: + verticesA, codesA, ddxA, ddyA = \ + self._get_arrow_wedge(x1, y1, x0, y0, + head_dist, cos_t, sin_t, + linewidth) + else: + verticesA, codesA = [], [] + ddxA, ddyA = 0., 0. + + # end arrow + x2, y2 = path.vertices[-2] + x3, y3 = path.vertices[-1] + + # If there is no room for an arrow and a line, then skip the arrow + has_end_arrow = (self.endarrow and not ((x2 == x3) and (y2 == y3))) + if has_end_arrow: + verticesB, codesB, ddxB, ddyB = \ + self._get_arrow_wedge(x2, y2, x3, y3, + head_dist, cos_t, sin_t, + linewidth) + else: + verticesB, codesB = [], [] + ddxB, ddyB = 0., 0. + + # this simple code will not work if ddx, ddy is greater than + # separation bettern vertices. + _path = [Path(np.concatenate([[(x0 + ddxA, y0 + ddyA)], + path.vertices[1:-1], + [(x3 + ddxB, y3 + ddyB)]]), + path.codes)] + _fillable = [False] + + if has_begin_arrow: + if self.fillbegin: + p = np.concatenate([verticesA, [verticesA[0], + verticesA[0]], ]) + c = np.concatenate([codesA, [Path.LINETO, Path.CLOSEPOLY]]) + _path.append(Path(p, c)) + _fillable.append(True) + else: + _path.append(Path(verticesA, codesA)) + _fillable.append(False) + + if has_end_arrow: + if self.fillend: + _fillable.append(True) + p = np.concatenate([verticesB, [verticesB[0], + verticesB[0]], ]) + c = np.concatenate([codesB, [Path.LINETO, Path.CLOSEPOLY]]) + _path.append(Path(p, c)) + else: + _fillable.append(False) + _path.append(Path(verticesB, codesB)) + + return _path, _fillable + + class Curve(_Curve): + """ + A simple curve without any arrow head. + """ + + def __init__(self): + super(ArrowStyle.Curve, self).__init__( + beginarrow=False, endarrow=False) + + _style_list["-"] = Curve + + class CurveA(_Curve): + """ + An arrow with a head at its begin point. + """ + + def __init__(self, head_length=.4, head_width=.2): + """ + *head_length* + length of the arrow head + + *head_width* + width of the arrow head + """ + + super(ArrowStyle.CurveA, self).__init__( + beginarrow=True, endarrow=False, + head_length=head_length, head_width=head_width) + + _style_list["<-"] = CurveA + + class CurveB(_Curve): + """ + An arrow with a head at its end point. + """ + + def __init__(self, head_length=.4, head_width=.2): + """ + *head_length* + length of the arrow head + + *head_width* + width of the arrow head + """ + + super(ArrowStyle.CurveB, self).__init__( + beginarrow=False, endarrow=True, + head_length=head_length, head_width=head_width) + + _style_list["->"] = CurveB + + class CurveAB(_Curve): + """ + An arrow with heads both at the begin and the end point. + """ + + def __init__(self, head_length=.4, head_width=.2): + """ + *head_length* + length of the arrow head + + *head_width* + width of the arrow head + """ + + super(ArrowStyle.CurveAB, self).__init__( + beginarrow=True, endarrow=True, + head_length=head_length, head_width=head_width) + + _style_list["<->"] = CurveAB + + class CurveFilledA(_Curve): + """ + An arrow with filled triangle head at the begin. + """ + + def __init__(self, head_length=.4, head_width=.2): + """ + *head_length* + length of the arrow head + + *head_width* + width of the arrow head + """ + + super(ArrowStyle.CurveFilledA, self).__init__( + beginarrow=True, endarrow=False, + fillbegin=True, fillend=False, + head_length=head_length, head_width=head_width) + + _style_list["<|-"] = CurveFilledA + + class CurveFilledB(_Curve): + """ + An arrow with filled triangle head at the end. + """ + + def __init__(self, head_length=.4, head_width=.2): + """ + *head_length* + length of the arrow head + + *head_width* + width of the arrow head + """ + + super(ArrowStyle.CurveFilledB, self).__init__( + beginarrow=False, endarrow=True, + fillbegin=False, fillend=True, + head_length=head_length, head_width=head_width) + + _style_list["-|>"] = CurveFilledB + + class CurveFilledAB(_Curve): + """ + An arrow with filled triangle heads both at the begin and the end + point. + """ + + def __init__(self, head_length=.4, head_width=.2): + """ + *head_length* + length of the arrow head + + *head_width* + width of the arrow head + """ + + super(ArrowStyle.CurveFilledAB, self).__init__( + beginarrow=True, endarrow=True, + fillbegin=True, fillend=True, + head_length=head_length, head_width=head_width) + + _style_list["<|-|>"] = CurveFilledAB + + class _Bracket(_Base): + + def __init__(self, bracketA=None, bracketB=None, + widthA=1., widthB=1., + lengthA=0.2, lengthB=0.2, + angleA=None, angleB=None, + scaleA=None, scaleB=None): + self.bracketA, self.bracketB = bracketA, bracketB + self.widthA, self.widthB = widthA, widthB + self.lengthA, self.lengthB = lengthA, lengthB + self.angleA, self.angleB = angleA, angleB + self.scaleA, self.scaleB = scaleA, scaleB + + def _get_bracket(self, x0, y0, + cos_t, sin_t, width, length): + + # arrow from x0, y0 to x1, y1 + from matplotlib.bezier import get_normal_points + x1, y1, x2, y2 = get_normal_points(x0, y0, cos_t, sin_t, width) + + dx, dy = length * cos_t, length * sin_t + + vertices_arrow = [(x1 + dx, y1 + dy), + (x1, y1), + (x2, y2), + (x2 + dx, y2 + dy)] + codes_arrow = [Path.MOVETO, + Path.LINETO, + Path.LINETO, + Path.LINETO] + + return vertices_arrow, codes_arrow + + def transmute(self, path, mutation_size, linewidth): + + if self.scaleA is None: + scaleA = mutation_size + else: + scaleA = self.scaleA + + if self.scaleB is None: + scaleB = mutation_size + else: + scaleB = self.scaleB + + vertices_list, codes_list = [], [] + + if self.bracketA: + x0, y0 = path.vertices[0] + x1, y1 = path.vertices[1] + cos_t, sin_t = get_cos_sin(x1, y1, x0, y0) + verticesA, codesA = self._get_bracket(x0, y0, cos_t, sin_t, + self.widthA * scaleA, + self.lengthA * scaleA) + vertices_list.append(verticesA) + codes_list.append(codesA) + + vertices_list.append(path.vertices) + codes_list.append(path.codes) + + if self.bracketB: + x0, y0 = path.vertices[-1] + x1, y1 = path.vertices[-2] + cos_t, sin_t = get_cos_sin(x1, y1, x0, y0) + verticesB, codesB = self._get_bracket(x0, y0, cos_t, sin_t, + self.widthB * scaleB, + self.lengthB * scaleB) + vertices_list.append(verticesB) + codes_list.append(codesB) + + vertices = np.concatenate(vertices_list) + codes = np.concatenate(codes_list) + + p = Path(vertices, codes) + + return p, False + + class BracketAB(_Bracket): + """ + An arrow with a bracket(]) at both ends. + """ + + def __init__(self, + widthA=1., lengthA=0.2, angleA=None, + widthB=1., lengthB=0.2, angleB=None): + """ + *widthA* + width of the bracket + + *lengthA* + length of the bracket + + *angleA* + angle between the bracket and the line + + *widthB* + width of the bracket + + *lengthB* + length of the bracket + + *angleB* + angle between the bracket and the line + """ + + super(ArrowStyle.BracketAB, self).__init__( + True, True, widthA=widthA, lengthA=lengthA, + angleA=angleA, widthB=widthB, lengthB=lengthB, + angleB=angleB) + + _style_list["]-["] = BracketAB + + class BracketA(_Bracket): + """ + An arrow with a bracket(]) at its end. + """ + + def __init__(self, widthA=1., lengthA=0.2, angleA=None): + """ + *widthA* + width of the bracket + + *lengthA* + length of the bracket + + *angleA* + angle between the bracket and the line + """ + + super(ArrowStyle.BracketA, self).__init__(True, None, + widthA=widthA, + lengthA=lengthA, + angleA=angleA) + + _style_list["]-"] = BracketA + + class BracketB(_Bracket): + """ + An arrow with a bracket([) at its end. + """ + + def __init__(self, widthB=1., lengthB=0.2, angleB=None): + """ + *widthB* + width of the bracket + + *lengthB* + length of the bracket + + *angleB* + angle between the bracket and the line + """ + + super(ArrowStyle.BracketB, self).__init__(None, True, + widthB=widthB, + lengthB=lengthB, + angleB=angleB) + + _style_list["-["] = BracketB + + class BarAB(_Bracket): + """ + An arrow with a bar(|) at both ends. + """ + + def __init__(self, + widthA=1., angleA=None, + widthB=1., angleB=None): + """ + *widthA* + width of the bracket + + *lengthA* + length of the bracket + + *angleA* + angle between the bracket and the line + + *widthB* + width of the bracket + + *lengthB* + length of the bracket + + *angleB* + angle between the bracket and the line + """ + + super(ArrowStyle.BarAB, self).__init__( + True, True, widthA=widthA, lengthA=0, angleA=angleA, + widthB=widthB, lengthB=0, angleB=angleB) + + _style_list["|-|"] = BarAB + + class Simple(_Base): + """ + A simple arrow. Only works with a quadratic bezier curve. + """ + + def __init__(self, head_length=.5, head_width=.5, tail_width=.2): + """ + *head_length* + length of the arrow head + + *head_with* + width of the arrow head + + *tail_width* + width of the arrow tail + + """ + + self.head_length, self.head_width, self.tail_width = \ + head_length, head_width, tail_width + super(ArrowStyle.Simple, self).__init__() + + def transmute(self, path, mutation_size, linewidth): + + x0, y0, x1, y1, x2, y2 = self.ensure_quadratic_bezier(path) + + # divide the path into a head and a tail + head_length = self.head_length * mutation_size + in_f = inside_circle(x2, y2, head_length) + arrow_path = [(x0, y0), (x1, y1), (x2, y2)] + + from .bezier import NonIntersectingPathException + + try: + arrow_out, arrow_in = \ + split_bezier_intersecting_with_closedpath(arrow_path, + in_f, + tolerence=0.01) + except NonIntersectingPathException: + # if this happens, make a straight line of the head_length + # long. + x0, y0 = _point_along_a_line(x2, y2, x1, y1, head_length) + x1n, y1n = 0.5 * (x0 + x2), 0.5 * (y0 + y2) + arrow_in = [(x0, y0), (x1n, y1n), (x2, y2)] + arrow_out = None + + # head + head_width = self.head_width * mutation_size + head_left, head_right = make_wedged_bezier2(arrow_in, + head_width / 2., wm=.5) + + # tail + if arrow_out is not None: + tail_width = self.tail_width * mutation_size + tail_left, tail_right = get_parallels(arrow_out, + tail_width / 2.) + + patch_path = [(Path.MOVETO, tail_right[0]), + (Path.CURVE3, tail_right[1]), + (Path.CURVE3, tail_right[2]), + (Path.LINETO, head_right[0]), + (Path.CURVE3, head_right[1]), + (Path.CURVE3, head_right[2]), + (Path.CURVE3, head_left[1]), + (Path.CURVE3, head_left[0]), + (Path.LINETO, tail_left[2]), + (Path.CURVE3, tail_left[1]), + (Path.CURVE3, tail_left[0]), + (Path.LINETO, tail_right[0]), + (Path.CLOSEPOLY, tail_right[0]), + ] + else: + patch_path = [(Path.MOVETO, head_right[0]), + (Path.CURVE3, head_right[1]), + (Path.CURVE3, head_right[2]), + (Path.CURVE3, head_left[1]), + (Path.CURVE3, head_left[0]), + (Path.CLOSEPOLY, head_left[0]), + ] + + path = Path([p for c, p in patch_path], [c for c, p in patch_path]) + + return path, True + + _style_list["simple"] = Simple + + class Fancy(_Base): + """ + A fancy arrow. Only works with a quadratic bezier curve. + """ + + def __init__(self, head_length=.4, head_width=.4, tail_width=.4): + """ + *head_length* + length of the arrow head + + *head_with* + width of the arrow head + + *tail_width* + width of the arrow tail + + """ + + self.head_length, self.head_width, self.tail_width = \ + head_length, head_width, tail_width + super(ArrowStyle.Fancy, self).__init__() + + def transmute(self, path, mutation_size, linewidth): + + x0, y0, x1, y1, x2, y2 = self.ensure_quadratic_bezier(path) + + # divide the path into a head and a tail + head_length = self.head_length * mutation_size + arrow_path = [(x0, y0), (x1, y1), (x2, y2)] + + from .bezier import NonIntersectingPathException + + # path for head + in_f = inside_circle(x2, y2, head_length) + try: + path_out, path_in = \ + split_bezier_intersecting_with_closedpath( + arrow_path, + in_f, + tolerence=0.01) + except NonIntersectingPathException: + # if this happens, make a straight line of the head_length + # long. + x0, y0 = _point_along_a_line(x2, y2, x1, y1, head_length) + x1n, y1n = 0.5 * (x0 + x2), 0.5 * (y0 + y2) + arrow_path = [(x0, y0), (x1n, y1n), (x2, y2)] + path_head = arrow_path + else: + path_head = path_in + + # path for head + in_f = inside_circle(x2, y2, head_length * .8) + path_out, path_in = split_bezier_intersecting_with_closedpath( + arrow_path, + in_f, + tolerence=0.01 + ) + path_tail = path_out + + # head + head_width = self.head_width * mutation_size + head_l, head_r = make_wedged_bezier2(path_head, + head_width / 2., + wm=.6) + + # tail + tail_width = self.tail_width * mutation_size + tail_left, tail_right = make_wedged_bezier2(path_tail, + tail_width * .5, + w1=1., wm=0.6, w2=0.3) + + # path for head + in_f = inside_circle(x0, y0, tail_width * .3) + path_in, path_out = split_bezier_intersecting_with_closedpath( + arrow_path, + in_f, + tolerence=0.01 + ) + tail_start = path_in[-1] + + head_right, head_left = head_r, head_l + patch_path = [(Path.MOVETO, tail_start), + (Path.LINETO, tail_right[0]), + (Path.CURVE3, tail_right[1]), + (Path.CURVE3, tail_right[2]), + (Path.LINETO, head_right[0]), + (Path.CURVE3, head_right[1]), + (Path.CURVE3, head_right[2]), + (Path.CURVE3, head_left[1]), + (Path.CURVE3, head_left[0]), + (Path.LINETO, tail_left[2]), + (Path.CURVE3, tail_left[1]), + (Path.CURVE3, tail_left[0]), + (Path.LINETO, tail_start), + (Path.CLOSEPOLY, tail_start), + ] + path = Path([p for c, p in patch_path], [c for c, p in patch_path]) + + return path, True + + _style_list["fancy"] = Fancy + + class Wedge(_Base): + """ + Wedge(?) shape. Only works with a quadratic bezier curve. The + begin point has a width of the tail_width and the end point has a + width of 0. At the middle, the width is shrink_factor*tail_width. + + """ + + def __init__(self, tail_width=.3, shrink_factor=0.5): + """ + *tail_width* + width of the tail + + *shrink_factor* + fraction of the arrow width at the middle point + """ + + self.tail_width = tail_width + self.shrink_factor = shrink_factor + super(ArrowStyle.Wedge, self).__init__() + + def transmute(self, path, mutation_size, linewidth): + + x0, y0, x1, y1, x2, y2 = self.ensure_quadratic_bezier(path) + + arrow_path = [(x0, y0), (x1, y1), (x2, y2)] + b_plus, b_minus = make_wedged_bezier2( + arrow_path, + self.tail_width * mutation_size / 2., + wm=self.shrink_factor) + + patch_path = [(Path.MOVETO, b_plus[0]), + (Path.CURVE3, b_plus[1]), + (Path.CURVE3, b_plus[2]), + (Path.LINETO, b_minus[2]), + (Path.CURVE3, b_minus[1]), + (Path.CURVE3, b_minus[0]), + (Path.CLOSEPOLY, b_minus[0]), + ] + path = Path([p for c, p in patch_path], [c for c, p in patch_path]) + + return path, True + + _style_list["wedge"] = Wedge + + if __doc__: + __doc__ = cbook.dedent(__doc__) % \ + {"AvailableArrowstyles": _pprint_styles(_style_list)} + + +docstring.interpd.update( + AvailableArrowstyles=_pprint_styles(ArrowStyle._style_list), + AvailableConnectorstyles=_pprint_styles(ConnectionStyle._style_list), +) + + +class FancyArrowPatch(Patch): + """ + A fancy arrow patch. It draws an arrow using the :class:ArrowStyle. + """ + _edge_default = True + + def __str__(self): + + if self._posA_posB is not None: + (x1, y1), (x2, y2) = self._posA_posB + return self.__class__.__name__ \ + + "(%g,%g->%g,%g)" % (x1, y1, x2, y2) + else: + return self.__class__.__name__ \ + + "(%s)" % (str(self._path_original),) + + @docstring.dedent_interpd + def __init__(self, posA=None, posB=None, + path=None, + arrowstyle="simple", + arrow_transmuter=None, + connectionstyle="arc3", + connector=None, + patchA=None, + patchB=None, + shrinkA=2., + shrinkB=2., + mutation_scale=1., + mutation_aspect=None, + dpi_cor=1., + **kwargs): + """ + If *posA* and *posB* is given, a path connecting two point are + created according to the connectionstyle. The path will be + clipped with *patchA* and *patchB* and further shrunken by + *shrinkA* and *shrinkB*. An arrow is drawn along this + resulting path using the *arrowstyle* parameter. If *path* + provided, an arrow is drawn along this path and *patchA*, + *patchB*, *shrinkA*, and *shrinkB* are ignored. + + The *connectionstyle* describes how *posA* and *posB* are + connected. It can be an instance of the ConnectionStyle class + (matplotlib.patches.ConnectionStlye) or a string of the + connectionstyle name, with optional comma-separated + attributes. The following connection styles are available. + + %(AvailableConnectorstyles)s + + + The *arrowstyle* describes how the fancy arrow will be + drawn. It can be string of the available arrowstyle names, + with optional comma-separated attributes, or one of the + ArrowStyle instance. The optional attributes are meant to be + scaled with the *mutation_scale*. The following arrow styles are + available. + + %(AvailableArrowstyles)s + + *mutation_scale* : a value with which attributes of arrowstyle + (e.g., head_length) 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 + """ + Patch.__init__(self, **kwargs) + + if posA is not None and posB is not None and path is None: + self._posA_posB = [posA, posB] + + if connectionstyle is None: + connectionstyle = "arc3" + self.set_connectionstyle(connectionstyle) + + elif posA is None and posB is None and path is not None: + self._posA_posB = None + self._connetors = None + else: + raise ValueError("either posA and posB, or path need to provided") + + self.patchA = patchA + self.patchB = patchB + self.shrinkA = shrinkA + self.shrinkB = shrinkB + + self._path_original = path + + self.set_arrowstyle(arrowstyle) + + self._mutation_scale = mutation_scale + self._mutation_aspect = mutation_aspect + + self.set_dpi_cor(dpi_cor) + #self._draw_in_display_coordinate = True + + def set_dpi_cor(self, dpi_cor): + """ + dpi_cor is currently used for linewidth-related things and + shrink factor. Mutation scale is affected by this. + """ + + self._dpi_cor = dpi_cor + self.stale = True + + def get_dpi_cor(self): + """ + dpi_cor is currently used for linewidth-related things and + shrink factor. Mutation scale is affected by this. + """ + + return self._dpi_cor + + def set_positions(self, posA, posB): + """ set the begin and end positions of the connecting + path. Use current value if None. + """ + if posA is not None: + self._posA_posB[0] = posA + if posB is not None: + self._posA_posB[1] = posB + self.stale = True + + def set_patchA(self, patchA): + """ set the begin patch. + """ + self.patchA = patchA + self.stale = True + + def set_patchB(self, patchB): + """ set the begin patch + """ + self.patchB = patchB + self.stale = True + + def set_connectionstyle(self, connectionstyle, **kw): + """ + Set the connection style. + + *connectionstyle* can be a string with connectionstyle name with + optional comma-separated attributes. Alternatively, the attrs can be + provided 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. + """ + + if connectionstyle is None: + return ConnectionStyle.pprint_styles() + + if isinstance(connectionstyle, ConnectionStyle._Base): + self._connector = connectionstyle + elif six.callable(connectionstyle): + # we may need check the calling convention of the given function + self._connector = connectionstyle + else: + self._connector = ConnectionStyle(connectionstyle, **kw) + self.stale = True + + def get_connectionstyle(self): + """ + Return the ConnectionStyle instance + """ + return self._connector + + def set_arrowstyle(self, arrowstyle=None, **kw): + """ + 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. + """ + + if arrowstyle is None: + return ArrowStyle.pprint_styles() + + if isinstance(arrowstyle, ArrowStyle._Base): + self._arrow_transmuter = arrowstyle + else: + self._arrow_transmuter = ArrowStyle(arrowstyle, **kw) + self.stale = True + + def get_arrowstyle(self): + """ + Return the arrowstyle object + """ + return self._arrow_transmuter + + def set_mutation_scale(self, scale): + """ + Set the mutation scale. + + ACCEPTS: float + """ + self._mutation_scale = scale + self.stale = True + + def get_mutation_scale(self): + """ + Return the mutation scale. + """ + return self._mutation_scale + + def set_mutation_aspect(self, aspect): + """ + Set the aspect ratio of the bbox mutation. + + ACCEPTS: float + """ + self._mutation_aspect = aspect + self.stale = True + + def get_mutation_aspect(self): + """ + Return the aspect ratio of the bbox mutation. + """ + return self._mutation_aspect + + def get_path(self): + """ + return the path of the arrow in the data coordinate. Use + get_path_in_displaycoord() method to retrieve the arrow path + in the display coord. + """ + _path, fillable = self.get_path_in_displaycoord() + + if cbook.iterable(fillable): + _path = concatenate_paths(_path) + + return self.get_transform().inverted().transform_path(_path) + + def get_path_in_displaycoord(self): + """ + Return the mutated path of the arrow in the display coord + """ + + dpi_cor = self.get_dpi_cor() + + if self._posA_posB is not None: + posA = self.get_transform().transform_point(self._posA_posB[0]) + posB = self.get_transform().transform_point(self._posA_posB[1]) + _path = self.get_connectionstyle()(posA, posB, + patchA=self.patchA, + patchB=self.patchB, + shrinkA=self.shrinkA * dpi_cor, + shrinkB=self.shrinkB * dpi_cor + ) + else: + _path = self.get_transform().transform_path(self._path_original) + + _path, fillable = self.get_arrowstyle()( + _path, + self.get_mutation_scale() * dpi_cor, + self.get_linewidth() * dpi_cor, + self.get_mutation_aspect() + ) + + #if not fillable: + # self._fill = False + + return _path, fillable + + def draw(self, renderer): + if not self.get_visible(): + return + + renderer.open_group('patch', self.get_gid()) + gc = renderer.new_gc() + + gc.set_foreground(self._edgecolor, isRGBA=True) + + lw = self._linewidth + if self._edgecolor[3] == 0: + lw = 0 + gc.set_linewidth(lw) + gc.set_dashes(self._dashoffset, self._dashes) + + gc.set_antialiased(self._antialiased) + self._set_gc_clip(gc) + gc.set_capstyle('round') + gc.set_snap(self.get_snap()) + + rgbFace = self._facecolor + if rgbFace[3] == 0: + rgbFace = None # (some?) renderers expect this as no-fill signal + + gc.set_alpha(self._alpha) + + if self._hatch: + gc.set_hatch(self._hatch) + + if self.get_sketch_params() is not None: + gc.set_sketch_params(*self.get_sketch_params()) + + # FIXME : dpi_cor is for the dpi-dependecy of the + # linewidth. There could be room for improvement. + # + #dpi_cor = renderer.points_to_pixels(1.) + self.set_dpi_cor(renderer.points_to_pixels(1.)) + path, fillable = self.get_path_in_displaycoord() + + if not cbook.iterable(fillable): + path = [path] + fillable = [fillable] + + affine = transforms.IdentityTransform() + + if self.get_path_effects(): + from matplotlib.patheffects import PathEffectRenderer + renderer = PathEffectRenderer(self.get_path_effects(), renderer) + + for p, f in zip(path, fillable): + if f: + renderer.draw_path(gc, p, affine, rgbFace) + else: + renderer.draw_path(gc, p, affine, None) + + gc.restore() + renderer.close_group('patch') + self.stale = False + + +class ConnectionPatch(FancyArrowPatch): + """ + A :class:`~matplotlib.patches.ConnectionPatch` class is to make + connecting lines between two points (possibly in different axes). + """ + def __str__(self): + return "ConnectionPatch((%g,%g),(%g,%g))" % \ + (self.xy1[0], self.xy1[1], self.xy2[0], self.xy2[1]) + + @docstring.dedent_interpd + def __init__(self, xyA, xyB, coordsA, coordsB=None, + axesA=None, axesB=None, + arrowstyle="-", + arrow_transmuter=None, + connectionstyle="arc3", + connector=None, + patchA=None, + patchB=None, + shrinkA=0., + shrinkB=0., + mutation_scale=10., + mutation_aspect=None, + clip_on=False, + dpi_cor=1., + **kwargs): + """ + Connect point *xyA* in *coordsA* with point *xyB* in *coordsB* + + + Valid keys are + + + =============== ====================================================== + Key Description + =============== ====================================================== + arrowstyle the arrow style + connectionstyle the connection style + relpos default is (0.5, 0.5) + patchA default is bounding box of the text + patchB default is None + shrinkA default is 2 points + shrinkB default is 2 points + mutation_scale default is text size (in points) + mutation_aspect default is 1. + ? any key for :class:`matplotlib.patches.PathPatch` + =============== ====================================================== + + + *coordsA* and *coordsB* are strings that indicate the + coordinates of *xyA* and *xyB*. + + ================= =================================================== + Property Description + ================= =================================================== + 'figure points' points from the lower left corner of the figure + 'figure pixels' pixels from the lower left corner of the figure + 'figure fraction' 0,0 is lower left of figure and 1,1 is upper, right + 'axes points' points from lower left corner of axes + 'axes pixels' pixels from lower left corner of axes + 'axes fraction' 0,1 is lower left of axes and 1,1 is upper right + 'data' use the coordinate system of the object being + annotated (default) + 'offset points' Specify an offset (in points) from the *xy* value + + 'polar' you can specify *theta*, *r* for the annotation, + even in cartesian plots. Note that if you + are using a polar axes, you do not need + to specify polar for the coordinate + system since that is the native "data" coordinate + system. + ================= =================================================== + + """ + if coordsB is None: + coordsB = coordsA + # we'll draw ourself after the artist we annotate by default + self.xy1 = xyA + self.xy2 = xyB + self.coords1 = coordsA + self.coords2 = coordsB + + self.axesA = axesA + self.axesB = axesB + + FancyArrowPatch.__init__(self, + posA=(0, 0), posB=(1, 1), + arrowstyle=arrowstyle, + arrow_transmuter=arrow_transmuter, + connectionstyle=connectionstyle, + connector=connector, + patchA=patchA, + patchB=patchB, + shrinkA=shrinkA, + shrinkB=shrinkB, + mutation_scale=mutation_scale, + mutation_aspect=mutation_aspect, + clip_on=clip_on, + dpi_cor=dpi_cor, + **kwargs) + + # if True, draw annotation only if self.xy is inside the axes + self._annotation_clip = None + + def _get_xy(self, x, y, s, axes=None): + """ + caculate the pixel position of given point + """ + + if axes is None: + axes = self.axes + + if s == 'data': + trans = axes.transData + x = float(self.convert_xunits(x)) + y = float(self.convert_yunits(y)) + return trans.transform_point((x, y)) + elif s == 'offset points': + # convert the data point + dx, dy = self.xy + + # prevent recursion + if self.xycoords == 'offset points': + return self._get_xy(dx, dy, 'data') + + dx, dy = self._get_xy(dx, dy, self.xycoords) + + # convert the offset + dpi = self.figure.get_dpi() + x *= dpi / 72. + y *= dpi / 72. + + # add the offset to the data point + x += dx + y += dy + + return x, y + elif s == 'polar': + theta, r = x, y + x = r * np.cos(theta) + y = r * np.sin(theta) + trans = axes.transData + return trans.transform_point((x, y)) + elif s == 'figure points': + # points from the lower left corner of the figure + dpi = self.figure.dpi + l, b, w, h = self.figure.bbox.bounds + r = l + w + t = b + h + + x *= dpi / 72. + y *= dpi / 72. + if x < 0: + x = r + x + if y < 0: + y = t + y + return x, y + elif s == 'figure pixels': + # pixels from the lower left corner of the figure + l, b, w, h = self.figure.bbox.bounds + r = l + w + t = b + h + if x < 0: + x = r + x + if y < 0: + y = t + y + return x, y + elif s == 'figure fraction': + # (0,0) is lower left, (1,1) is upper right of figure + trans = self.figure.transFigure + return trans.transform_point((x, y)) + elif s == 'axes points': + # points from the lower left corner of the axes + dpi = self.figure.dpi + l, b, w, h = axes.bbox.bounds + r = l + w + t = b + h + if x < 0: + x = r + x * dpi / 72. + else: + x = l + x * dpi / 72. + if y < 0: + y = t + y * dpi / 72. + else: + y = b + y * dpi / 72. + return x, y + elif s == 'axes pixels': + #pixels from the lower left corner of the axes + + l, b, w, h = axes.bbox.bounds + r = l + w + t = b + h + if x < 0: + x = r + x + else: + x = l + x + if y < 0: + y = t + y + else: + y = b + y + return x, y + elif s == 'axes fraction': + #(0,0) is lower left, (1,1) is upper right of axes + trans = axes.transAxes + return trans.transform_point((x, y)) + + def set_annotation_clip(self, b): + """ + set *annotation_clip* attribute. + + * True: the annotation will only be drawn when self.xy is inside the + axes. + * False: the annotation will always be drawn regardless of its + position. + * None: the self.xy will be checked only if *xycoords* is "data" + """ + self._annotation_clip = b + self.stale = True + + def get_annotation_clip(self): + """ + Return *annotation_clip* attribute. + See :meth:`set_annotation_clip` for the meaning of return values. + """ + return self._annotation_clip + + def get_path_in_displaycoord(self): + """ + Return the mutated path of the arrow in the display coord + """ + + dpi_cor = self.get_dpi_cor() + + x, y = self.xy1 + posA = self._get_xy(x, y, self.coords1, self.axesA) + + x, y = self.xy2 + posB = self._get_xy(x, y, self.coords2, self.axesB) + + _path = self.get_connectionstyle()(posA, posB, + patchA=self.patchA, + patchB=self.patchB, + shrinkA=self.shrinkA * dpi_cor, + shrinkB=self.shrinkB * dpi_cor + ) + + _path, fillable = self.get_arrowstyle()( + _path, + self.get_mutation_scale() * dpi_cor, + self.get_linewidth() * dpi_cor, + self.get_mutation_aspect() + ) + + return _path, fillable + + def _check_xy(self, renderer): + """ + check if the annotation need to + be drawn. + """ + + b = self.get_annotation_clip() + + if b or (b is None and self.coords1 == "data"): + x, y = self.xy1 + xy_pixel = self._get_xy(x, y, self.coords1, self.axesA) + if not self.axes.contains_point(xy_pixel): + return False + + if b or (b is None and self.coords2 == "data"): + x, y = self.xy2 + xy_pixel = self._get_xy(x, y, self.coords2, self.axesB) + if self.axesB is None: + axes = self.axes + else: + axes = self.axesB + if not axes.contains_point(xy_pixel): + return False + + return True + + def draw(self, renderer): + """ + Draw. + """ + + if renderer is not None: + self._renderer = renderer + if not self.get_visible(): + return + + if not self._check_xy(renderer): + return + + FancyArrowPatch.draw(self, renderer) + +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +# implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import itertools +import time +import unittest + +import mock + +from swift.account import utils, backend +from swift.common.storage_policy import POLICIES +from swift.common.utils import Timestamp +from swift.common.swob import HeaderKeyDict + +from test.unit import patch_policies + + +class TestFakeAccountBroker(unittest.TestCase): + + def test_fake_broker_get_info(self): + broker = utils.FakeAccountBroker() + now = time.time() + with mock.patch('time.time', new=lambda: now): + info = broker.get_info() + timestamp = Timestamp(now) + expected = { + 'container_count': 0, + 'object_count': 0, + 'bytes_used': 0, + 'created_at': timestamp.internal, + 'put_timestamp': timestamp.internal, + } + self.assertEqual(info, expected) + + def test_fake_broker_list_containers_iter(self): + broker = utils.FakeAccountBroker() + self.assertEqual(broker.list_containers_iter(), []) + + def test_fake_broker_metadata(self): + broker = utils.FakeAccountBroker() + self.assertEqual(broker.metadata, {}) + + def test_fake_broker_get_policy_stats(self): + broker = utils.FakeAccountBroker() + self.assertEqual(broker.get_policy_stats(), {}) + + +class TestAccountUtils(unittest.TestCase): + + def test_get_response_headers_fake_broker(self): + broker = utils.FakeAccountBroker() + now = time.time() + expected = { + 'X-Account-Container-Count': 0, + 'X-Account-Object-Count': 0, + 'X-Account-Bytes-Used': 0, + 'X-Timestamp': Timestamp(now).normal, + 'X-PUT-Timestamp': Timestamp(now).normal, + } + with mock.patch('time.time', new=lambda: now): + resp_headers = utils.get_response_headers(broker) + self.assertEqual(resp_headers, expected) + + def test_get_response_headers_empty_memory_broker(self): + broker = backend.AccountBroker(':memory:', account='a') + now = time.time() + with mock.patch('time.time', new=lambda: now): + broker.initialize(Timestamp(now).internal) + expected = { + 'X-Account-Container-Count': 0, + 'X-Account-Object-Count': 0, + 'X-Account-Bytes-Used': 0, + 'X-Timestamp': Timestamp(now).normal, + 'X-PUT-Timestamp': Timestamp(now).normal, + } + resp_headers = utils.get_response_headers(broker) + self.assertEqual(resp_headers, expected) + + @patch_policies + def test_get_response_headers_with_data(self): + broker = backend.AccountBroker(':memory:', account='a') + now = time.time() + with mock.patch('time.time', new=lambda: now): + broker.initialize(Timestamp(now).internal) + # add some container data + ts = (Timestamp(t).internal for t in itertools.count(int(now))) + total_containers = 0 + total_objects = 0 + total_bytes = 0 + for policy in POLICIES: + delete_timestamp = ts.next() + put_timestamp = ts.next() + object_count = int(policy) + bytes_used = int(policy) * 10 + broker.put_container('c-%s' % policy.name, put_timestamp, + delete_timestamp, object_count, bytes_used, + int(policy)) + total_containers += 1 + total_objects += object_count + total_bytes += bytes_used + expected = HeaderKeyDict({ + 'X-Account-Container-Count': total_containers, + 'X-Account-Object-Count': total_objects, + 'X-Account-Bytes-Used': total_bytes, + 'X-Timestamp': Timestamp(now).normal, + 'X-PUT-Timestamp': Timestamp(now).normal, + }) + for policy in POLICIES: + prefix = 'X-Account-Storage-Policy-%s-' % policy.name + expected[prefix + 'Object-Count'] = int(policy) + expected[prefix + 'Bytes-Used'] = int(policy) * 10 + resp_headers = utils.get_response_headers(broker) + for key, value in resp_headers.items(): + expected_value = expected.pop(key) + self.assertEqual(expected_value, str(value), + 'value for %r was %r not %r' % ( + key, value, expected_value)) + self.assertFalse(expected) + +# -*- coding: utf-8 -*- +# Generated by Django 1.11.16 on 2019-08-18 18:10 +from __future__ import unicode_literals + +import import_string + +import chamber.models.fields +from django.conf import settings +from django.db import migrations, models +import django.db.models.deletion +import is_core.contrib.background_export.models +from is_core.config import settings as is_core_settings + + +class Migration(migrations.Migration): + initial = True + + dependencies = [ + ('contenttypes', '0002_remove_content_type_name'), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name='ExportedFile', + fields=[ + ('created_at', models.DateTimeField(auto_now_add=True, db_index=True, verbose_name='created at')), + ('changed_at', models.DateTimeField(auto_now=True, db_index=True, verbose_name='changed at')), + ('slug', models.SlugField(max_length=32, primary_key=True, serialize=False, verbose_name='slug')), + ('file', chamber.models.fields.FileField( + blank=True, null=True, upload_to=is_core.contrib.background_export.models.generate_filename, + verbose_name='file', storage=import_string(is_core_settings.BACKGROUND_EXPORT_STORAGE_CLASS)() + )), + ('content_type', + models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='contenttypes.ContentType')), + ('created_by', + models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='created_exported_files', + to=settings.AUTH_USER_MODEL, verbose_name='created by')), + ('downloaded_by', models.ManyToManyField(blank=True, related_name='downloaded_exported_files', + to=settings.AUTH_USER_MODEL, verbose_name='downloaded by')), + ], + options={ + 'verbose_name': 'exported file', + 'verbose_name_plural': 'exported files', + 'ordering': ('-created_at',), + }, + ), + ] + +from __future__ import absolute_import +from ..packages.six.moves import http_client as httplib + +from ..exceptions import HeaderParsingError + + +def is_fp_closed(obj): + """ + Checks whether a given file-like object is closed. + + :param obj: + The file-like object to check. + """ + + try: + # Check via the official file-like-object way. + return obj.closed + except AttributeError: + pass + + try: + # Check if the object is a container for another file-like object that + # gets released on exhaustion (e.g. HTTPResponse). + return obj.fp is None + except AttributeError: + pass + + raise ValueError("Unable to determine whether fp is closed.") + + +def assert_header_parsing(headers): + """ + Asserts whether all headers have been successfully parsed. + Extracts encountered errors from the result of parsing headers. + + Only works on Python 3. + + :param headers: Headers to verify. + :type headers: `httplib.HTTPMessage`. + + :raises urllib3.exceptions.HeaderParsingError: + If parsing errors are found. + """ + + # This will fail silently if we pass in the wrong kind of parameter. + # To make debugging easier add an explicit check. + if not isinstance(headers, httplib.HTTPMessage): + raise TypeError('expected httplib.Message, got {0}.'.format( + type(headers))) + + defects = getattr(headers, 'defects', None) + get_payload = getattr(headers, 'get_payload', None) + + unparsed_data = None + if get_payload: # Platform-specific: Python 3. + unparsed_data = get_payload() + + if defects or unparsed_data: + raise HeaderParsingError(defects=defects, unparsed_data=unparsed_data) + + +def is_response_to_head(response): + """ + Checks whether the request of a response has been a HEAD-request. + Handles the quirks of AppEngine. + + :param conn: + :type conn: :class:`httplib.HTTPResponse` + """ + # FIXME: Can we do this somehow without accessing private httplib _method? + method = response._method + if isinstance(method, int): # Platform-specific: Appengine + return method == 3 + return method.upper() == 'HEAD' + +from __future__ import absolute_import +from __future__ import print_function + +from typing import Any + +from argparse import ArgumentParser +from django.core.management.base import BaseCommand +from django.db.models import Q +from zerver.models import Realm, Stream, Message, Subscription, Recipient, get_realm + +class Command(BaseCommand): + help = "Generate statistics on the streams for a realm." + + def add_arguments(self, parser): + # type: (ArgumentParser) -> None + parser.add_argument('realms', metavar='', type=str, nargs='*', + help="realm to generate statistics for") + + def handle(self, *args, **options): + # type: (*Any, **str) -> None + if options['realms']: + try: + realms = [get_realm(string_id) for string_id in options['realms']] + except Realm.DoesNotExist as e: + print(e) + exit(1) + else: + realms = Realm.objects.all() + + for realm in realms: + print(realm.string_id) + print("------------") + print("%25s %15s %10s" % ("stream", "subscribers", "messages")) + streams = Stream.objects.filter(realm=realm).exclude(Q(name__istartswith="tutorial-")) + invite_only_count = 0 + for stream in streams: + if stream.invite_only: + invite_only_count += 1 + continue + print("%25s" % (stream.name,), end=' ') + recipient = Recipient.objects.filter(type=Recipient.STREAM, type_id=stream.id) + print("%10d" % (len(Subscription.objects.filter(recipient=recipient, active=True)),), end=' ') + num_messages = len(Message.objects.filter(recipient=recipient)) + print("%12d" % (num_messages,)) + print("%d invite-only streams" % (invite_only_count,)) + print("") + +#!/usr/bin/python +from __future__ import (absolute_import, division, print_function) +# Copyright 2019 Fortinet, Inc. +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +# the lib use python logging can get it if the following is set in your +# Ansible config. + +__metaclass__ = type + +ANSIBLE_METADATA = {'status': ['preview'], + 'supported_by': 'community', + 'metadata_version': '1.1'} + +DOCUMENTATION = ''' +--- +module: fortios_firewall_ssh_setting +short_description: SSH proxy settings in Fortinet's FortiOS and FortiGate. +description: + - This module is able to configure a FortiGate or FortiOS by + allowing the user to configure firewall_ssh feature and setting category. + Examples includes all options and need to be adjusted to datasources before usage. + Tested with FOS v6.0.2 +version_added: "2.8" +author: + - Miguel Angel Munoz (@mamunozgonzalez) + - Nicolas Thomas (@thomnico) +notes: + - Requires fortiosapi library developed by Fortinet + - Run as a local_action in your playbook +requirements: + - fortiosapi>=0.9.8 +options: + host: + description: + - FortiOS or FortiGate ip adress. + required: true + username: + description: + - FortiOS or FortiGate username. + required: true + password: + description: + - FortiOS or FortiGate password. + default: "" + vdom: + description: + - Virtual domain, among those defined previously. A vdom is a + virtual instance of the FortiGate that can be configured and + used as a different unit. + default: root + https: + description: + - Indicates if the requests towards FortiGate must use HTTPS + protocol + type: bool + default: true + firewall_ssh_setting: + description: + - SSH proxy settings. + default: null + suboptions: + caname: + description: + - CA certificate used by SSH Inspection. Source firewall.ssh.local-ca.name. + host-trusted-checking: + description: + - Enable/disable host trusted checking. + choices: + - enable + - disable + hostkey-dsa1024: + description: + - DSA certificate used by SSH proxy. Source firewall.ssh.local-key.name. + hostkey-ecdsa256: + description: + - ECDSA nid256 certificate used by SSH proxy. Source firewall.ssh.local-key.name. + hostkey-ecdsa384: + description: + - ECDSA nid384 certificate used by SSH proxy. Source firewall.ssh.local-key.name. + hostkey-ecdsa521: + description: + - ECDSA nid384 certificate used by SSH proxy. Source firewall.ssh.local-key.name. + hostkey-ed25519: + description: + - ED25519 hostkey used by SSH proxy. Source firewall.ssh.local-key.name. + hostkey-rsa2048: + description: + - RSA certificate used by SSH proxy. Source firewall.ssh.local-key.name. + untrusted-caname: + description: + - Untrusted CA certificate used by SSH Inspection. Source firewall.ssh.local-ca.name. +''' + +EXAMPLES = ''' +- hosts: localhost + vars: + host: "192.168.122.40" + username: "admin" + password: "" + vdom: "root" + tasks: + - name: SSH proxy settings. + fortios_firewall_ssh_setting: + host: "{{ host }}" + username: "{{ username }}" + password: "{{ password }}" + vdom: "{{ vdom }}" + https: "False" + firewall_ssh_setting: + caname: " (source firewall.ssh.local-ca.name)" + host-trusted-checking: "enable" + hostkey-dsa1024: "myhostname (source firewall.ssh.local-key.name)" + hostkey-ecdsa256: "myhostname (source firewall.ssh.local-key.name)" + hostkey-ecdsa384: "myhostname (source firewall.ssh.local-key.name)" + hostkey-ecdsa521: "myhostname (source firewall.ssh.local-key.name)" + hostkey-ed25519: "myhostname (source firewall.ssh.local-key.name)" + hostkey-rsa2048: "myhostname (source firewall.ssh.local-key.name)" + untrusted-caname: " (source firewall.ssh.local-ca.name)" +''' + +RETURN = ''' +build: + description: Build number of the fortigate image + returned: always + type: str + sample: '1547' +http_method: + description: Last method used to provision the content into FortiGate + returned: always + type: str + sample: 'PUT' +http_status: + description: Last result given by FortiGate on last operation applied + returned: always + type: str + sample: "200" +mkey: + description: Master key (id) used in the last call to FortiGate + returned: success + type: str + sample: "id" +name: + description: Name of the table used to fulfill the request + returned: always + type: str + sample: "urlfilter" +path: + description: Path of the table used to fulfill the request + returned: always + type: str + sample: "webfilter" +revision: + description: Internal revision number + returned: always + type: str + sample: "17.0.2.10658" +serial: + description: Serial number of the unit + returned: always + type: str + sample: "FGVMEVYYQT3AB5352" +status: + description: Indication of the operation's result + returned: always + type: str + sample: "success" +vdom: + description: Virtual domain used + returned: always + type: str + sample: "root" +version: + description: Version of the FortiGate + returned: always + type: str + sample: "v5.6.3" + +''' + +from ansible.module_utils.basic import AnsibleModule + +fos = None + + +def login(data): + host = data['host'] + username = data['username'] + password = data['password'] + + fos.debug('on') + if 'https' in data and not data['https']: + fos.https('off') + else: + fos.https('on') + + fos.login(host, username, password) + + +def filter_firewall_ssh_setting_data(json): + option_list = ['caname', 'host-trusted-checking', 'hostkey-dsa1024', + 'hostkey-ecdsa256', 'hostkey-ecdsa384', 'hostkey-ecdsa521', + 'hostkey-ed25519', 'hostkey-rsa2048', 'untrusted-caname'] + dictionary = {} + + for attribute in option_list: + if attribute in json and json[attribute] is not None: + dictionary[attribute] = json[attribute] + + return dictionary + + +def firewall_ssh_setting(data, fos): + vdom = data['vdom'] + firewall_ssh_setting_data = data['firewall_ssh_setting'] + filtered_data = filter_firewall_ssh_setting_data(firewall_ssh_setting_data) + return fos.set('firewall.ssh', + 'setting', + data=filtered_data, + vdom=vdom) + + +def fortios_firewall_ssh(data, fos): + login(data) + + methodlist = ['firewall_ssh_setting'] + for method in methodlist: + if data[method]: + resp = eval(method)(data, fos) + break + + fos.logout() + return not resp['status'] == "success", resp['status'] == "success", resp + + +def main(): + fields = { + "host": {"required": True, "type": "str"}, + "username": {"required": True, "type": "str"}, + "password": {"required": False, "type": "str", "no_log": True}, + "vdom": {"required": False, "type": "str", "default": "root"}, + "https": {"required": False, "type": "bool", "default": True}, + "firewall_ssh_setting": { + "required": False, "type": "dict", + "options": { + "caname": {"required": False, "type": "str"}, + "host-trusted-checking": {"required": False, "type": "str", + "choices": ["enable", "disable"]}, + "hostkey-dsa1024": {"required": False, "type": "str"}, + "hostkey-ecdsa256": {"required": False, "type": "str"}, + "hostkey-ecdsa384": {"required": False, "type": "str"}, + "hostkey-ecdsa521": {"required": False, "type": "str"}, + "hostkey-ed25519": {"required": False, "type": "str"}, + "hostkey-rsa2048": {"required": False, "type": "str"}, + "untrusted-caname": {"required": False, "type": "str"} + + } + } + } + + module = AnsibleModule(argument_spec=fields, + supports_check_mode=False) + try: + from fortiosapi import FortiOSAPI + except ImportError: + module.fail_json(msg="fortiosapi module is required") + + global fos + fos = FortiOSAPI() + + is_error, has_changed, result = fortios_firewall_ssh(module.params, fos) + + if not is_error: + module.exit_json(changed=has_changed, meta=result) + else: + module.fail_json(msg="Error in repo", meta=result) + + +if __name__ == '__main__': + main() + +# Copyright 2012 Nebula, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. + +"""The Flavor Swap API extension.""" + +from nova.api.openstack import extensions +from nova.api.openstack import wsgi + + +authorize = extensions.soft_extension_authorizer('compute', 'flavor_swap') + + +class FlavorSwapController(wsgi.Controller): + def _extend_flavors(self, req, flavors): + for flavor in flavors: + db_flavor = req.get_db_flavor(flavor['id']) + key = 'swap' + flavor[key] = db_flavor['swap'] or "" + + def _show(self, req, resp_obj): + if not authorize(req.environ['nova.context']): + return + if 'flavor' in resp_obj.obj: + self._extend_flavors(req, [resp_obj.obj['flavor']]) + + @wsgi.extends + def show(self, req, resp_obj, id): + return self._show(req, resp_obj) + + @wsgi.extends(action='create') + def create(self, req, resp_obj, body): + return self._show(req, resp_obj) + + @wsgi.extends + def detail(self, req, resp_obj): + if not authorize(req.environ['nova.context']): + return + self._extend_flavors(req, list(resp_obj.obj['flavors'])) + + +class Flavor_swap(extensions.ExtensionDescriptor): + """Support to show the swap status of a flavor.""" + + name = "FlavorSwap" + alias = "os-flavor-swap" + namespace = ("http://docs.openstack.org/compute/ext/" + "flavor_swap/api/v1.1") + updated = "2012-08-29T00:00:00Z" + + def get_controller_extensions(self): + controller = FlavorSwapController() + extension = extensions.ControllerExtension(self, 'flavors', controller) + return [extension] + +# +# Copyright 2015 Google Inc. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +==== TTX/FontTools Compreffor ==== +This module automatically subroutines the CFF table in +a TTFont object, for the purposes of compressing the +outputted font file. In addition to providing a Python +interface, this tool can be used on the command line. + +Usage (python): +>> from fontTools.ttLib import TTFont +>> import compreffor +>> font = TTFont(filename) +>> options = { ... } +>> compreffor.compress(font, **options) +>> font.save(filename) + +Compression Backends: +There are 2 different ways the compreffor can be run. + - The default method is backed by a C++ extension module. The logic is + in cxxCompressor.py, cffCompressor.h, cffCompressor.cc and + _compreffor.pyx. + - The second is a pure Python approach, and can be selected from `compress` + by passing `method_python=True`. This is significantly slower than the + the other backend (~10-20x). The logic can be found in pyCompressor.py. + +Options: +When running `compreffor.compress`, options can be set using keyword arguments: + - nrounds (integer) -- the number of market iterations to run (default: 4) + - max_subrs (integer) -- limit to number of subrs per INDEX + (default: 65533) + +With `method_python=True`, the following additional options are available: + - chunk_ratio (float) -- set the percentage of charstrings + to be run by each process. The value must be a + float between 0 < n <= 1 (default: 0.1) + - processes (integer) -- the number of simultaneous processes to run. + Use value 1 to perform operation serially. + +Usage (command line): +From the command line, you can either run the package as a module, + +$ python -m compreffor --help + +Or call the `compreffor` console script installed with the package. +Use -h/--help to list all the available options. +""" + +import logging +from fontTools.misc.loggingTools import Timer + +log = logging.getLogger(__name__) +timer = Timer(logger=logging.getLogger(log.name + ".timer")) + +from compreffor import cxxCompressor, pyCompressor + + +def compress(ttFont, method_python=False, **options): + """ Subroutinize TTFont instance in-place using the C++ Compreffor. + If 'method_python' is True, use the slower, pure-Python Compreffor. + If the font already contains subroutines, it is first decompressed. + """ + if has_subrs(ttFont): + log.warning( + "There are subroutines in font; must decompress it first") + decompress(ttFont) + if method_python: + pyCompressor.compreff(ttFont, **options) + else: + cxxCompressor.compreff(ttFont, **options) + + +def decompress(ttFont, **kwargs): + """ Use the FontTools Subsetter to desubroutinize the font's CFF table. + Any keyword arguments are passed on as options to the Subsetter. + Skip if the font contains no subroutines. + """ + if not has_subrs(ttFont): + log.debug('No subroutines found; skip decompress') + return + + from fontTools import subset + + # The FontTools subsetter modifies many tables by default; here + # we only want to desubroutinize, so we run the subsetter on a + # temporary copy and extract the resulting CFF table from it + make_temp = kwargs.pop('make_temp', True) + if make_temp: + from io import BytesIO + from fontTools.ttLib import TTFont, newTable + + stream = BytesIO() + ttFont.save(stream, reorderTables=None) + stream.flush() + stream.seek(0) + tmpfont = TTFont(stream) + else: + tmpfont = ttFont # run subsetter on the original font + + options = subset.Options(**kwargs) + options.desubroutinize = True + subsetter = subset.Subsetter(options=options) + subsetter.populate(glyphs=tmpfont.getGlyphOrder()) + subsetter.subset(tmpfont) + + if make_temp: + # copy modified CFF table to original font + data = tmpfont['CFF '].compile(tmpfont) + table = newTable('CFF ') + table.decompile(data, ttFont) + ttFont['CFF '] = table + tmpfont.close() + + +def has_subrs(ttFont): + """ Return True if the font's CFF table contains any subroutines. """ + if 'CFF ' not in ttFont: + raise ValueError("Invalid font: no 'CFF ' table found") + td = ttFont['CFF '].cff.topDictIndex[0] + priv_subrs = (hasattr(td, 'FDArray') and + any((hasattr(fd, 'Subrs') and len(fd.Subrs) > 0) + for fd in td.FDArray)) + return len(td.GlobalSubrs) > 0 or priv_subrs + + +def check(original_file, compressed_file): + """ Compare the original and compressed font files to confirm they are + functionally equivalent. Also check that the Charstrings in the compressed + font's CFFFontSet don't exceed the maximum subroutine nesting level. + Return True if all checks pass, else return False. + """ + from compreffor.test.util import check_compression_integrity + from compreffor.test.util import check_call_depth + rv = check_compression_integrity(original_file, compressed_file) + rv &= check_call_depth(compressed_file) + return rv + + +# The `Methods` and `Compreffor` classes are now deprecated, but we keep +# them here for backward compatibility + + +class Methods: + Py, Cxx = range(2) + + +class Compreffor(object): + def __init__(self, font, method=Methods.Cxx, **options): + import warnings + warnings.warn("'Compreffor' class is deprecated; use 'compress' function " + "instead", UserWarning) + self.font = font + self.method = method + self.options = options + + def compress(self): + if self.method == Methods.Py: + compress(self.font, method_python=True, **self.options) + elif self.method == Methods.Cxx: + compress(self.font, method_python=False, **self.options) + else: + raise ValueError("Invalid method: %r" % self.method) + +''' +Hello student. Thank you for downloading a CORGIS library. However, you do not need to open this library. +Instead you should use the following: + + import election + +If you opened the file because you are curious how this library works, then well done! +We hope that you find it a useful learning experience. +However, you should know that this code is meant to solve somewhat esoteric pedagogical problems, +so it is often not best practices. +''' + +import sys as _sys +import os as _os +import json as _json +import sqlite3 as _sql +import difflib as _difflib + +class _Constants(object): + ''' + Global singleton object to hide some of the constants; some IDEs reveal internal module details very aggressively, and there's no other way to hide stuff. + ''' + _HEADER = {'User-Agent': + 'CORGIS Election library for educational purposes'} + _PYTHON_3 = _sys.version_info >= (3, 0) + _TEST = False + _HARDWARE = 1000 + +if _Constants._PYTHON_3: + import urllib.request as _request + from urllib.parse import quote_plus as _quote_plus + from urllib.error import HTTPError as _HTTPError +else: + import urllib2 as _urllib2 + from urllib import quote_plus as _quote_plus + from urllib2 import HTTPError as _HTTPError + +class DatasetException(Exception): + ''' Thrown when there is an error loading the dataset for some reason.''' + pass + +_Constants._DATABASE_NAME = "election.db" +if not _os.access(_Constants._DATABASE_NAME, _os.F_OK): + raise DatasetException("Error! Could not find a \"{0}\" file. Make sure that there is a \"{0}\" in the same directory as \"{1}.py\"! Spelling is very important here.".format(_Constants._DATABASE_NAME, __name__)) +elif not _os.access(_Constants._DATABASE_NAME, _os.R_OK): + raise DatasetException("Error! Could not read the \"{0}\" file. Make sure that it readable by changing its permissions. You may need to get help from your instructor.".format(_Constants._DATABASE_NAME, __name__)) +elif not _os.access(_Constants._DATABASE_NAME, _os.W_OK): + _sys.stderr.write('The local cache (\" \") will not be updated. Make sure that it is writable by changing its permissions. You may need to get help from your instructor.\n'.format(_Constants._DATABASE_NAME)) + _sys.stderr.flush() + +_Constants._DATABASE = _sql.connect(_Constants._DATABASE_NAME) + +class _Auxiliary(object): + @staticmethod + def _parse_type(value, type_func): + """ + Attempt to cast *value* into *type_func*, returning *default* if it fails. + """ + default = type_func(0) + if value is None: + return default + try: + return type_func(value) + except ValueError: + return default + + @staticmethod + def _byteify(input): + """ + Force the given input to only use `str` instead of `bytes` or `unicode`. + This works even if the input is a dict, list, + """ + if isinstance(input, dict): + return {_Auxiliary._byteify(key): _Auxiliary._byteify(value) for key, value in input.items()} + elif isinstance(input, list): + return [_Auxiliary._byteify(element) for element in input] + elif _Constants._PYTHON_3 and isinstance(input, str): + return str(input.encode('ascii', 'replace').decode('ascii')) + elif not _Constants._PYTHON_3 and isinstance(input, unicode): + return str(input.encode('ascii', 'replace').decode('ascii')) + else: + return input + + @staticmethod + def _guess_schema(input): + if isinstance(input, dict): + return {str(key.encode('ascii', 'replace').decode('ascii')): + _Auxiliary._guess_schema(value) for key, value in input.items()} + elif isinstance(input, list): + return [_Auxiliary._guess_schema(input[0])] if input else [] + else: + return type(input) + + + +################################################################################ +# Domain Objects +################################################################################ + + + + + +################################################################################ +# Interfaces +################################################################################ + + + +def get_results(test=True): + """ + Returns the result of each primary for every county from the dataset. + + """ + if _Constants._TEST or test: + rows = _Constants._DATABASE.execute("SELECT data FROM election LIMIT {hardware}".format( + hardware=_Constants._HARDWARE)) + data = [r[0] for r in rows] + data = [_Auxiliary._byteify(_json.loads(r)) for r in data] + + return _Auxiliary._byteify(data) + + else: + rows = _Constants._DATABASE.execute("SELECT data FROM election".format( + hardware=_Constants._HARDWARE)) + data = [r[0] for r in rows] + data = [_Auxiliary._byteify(_json.loads(r)) for r in data] + + return _Auxiliary._byteify(data) + + +################################################################################ +# Internalized testing code +################################################################################ + +def _test_interfaces(): + from pprint import pprint as _pprint + from timeit import default_timer as _default_timer + # Production test + print("Production get_results") + start_time = _default_timer() + result = get_results(test=False) + + print("{} entries found.".format(len(result))) + _pprint(_Auxiliary._guess_schema(result)) + + print("Time taken: {}".format(_default_timer() - start_time)) + # Test test + print("Test get_results") + start_time = _default_timer() + result = get_results() + + print("{} entries found.".format(len(result))) + _pprint(_Auxiliary._guess_schema(result)) + + print("Time taken: {}".format(_default_timer() - start_time)) + + +if __name__ == '__main__': + from optparse import OptionParser as _OptionParser + _parser = _OptionParser() + _parser.add_option("-t", "--test", action="store_true", + default=False, + help="Execute the interfaces to test them.") + _parser.add_option("-r", "--reset", action="store_true", + default=False, + help="Reset the cache") + (_options, _args) = _parser.parse_args() + + if _options.test: + _test_interfaces() + + if _options.reset: + _modify_self() +""" +Custom manager for Objects. +""" +from itertools import chain +from django.db.models import Q +from django.conf import settings +from django.db.models.fields import exceptions +from src.typeclasses.managers import TypedObjectManager +from src.typeclasses.managers import returns_typeclass, returns_typeclass_list +from src.utils import utils +from src.utils.utils import to_unicode, is_iter, make_iter, string_partial_matching + +__all__ = ("ObjectManager",) +_GA = object.__getattribute__ + +# delayed import +_ATTR = None + + +# Try to use a custom way to parse id-tagged multimatches. + +_AT_MULTIMATCH_INPUT = utils.variable_from_module(*settings.SEARCH_AT_MULTIMATCH_INPUT.rsplit('.', 1)) + + +class ObjectManager(TypedObjectManager): + """ + This ObjectManager implementes methods for searching + and manipulating Objects directly from the database. + + Evennia-specific search methods (will return Typeclasses or + lists of Typeclasses, whereas Django-general methods will return + Querysets or database objects). + + dbref (converter) + get_id (alias: dbref_search) + get_dbref_range + object_totals + typeclass_search + get_object_with_player + get_objs_with_key_and_typeclass + get_objs_with_attr + get_objs_with_attr_match + get_objs_with_db_property + get_objs_with_db_property_match + get_objs_with_key_or_alias + get_contents + object_search (interface to many of the above methods, + equivalent to ev.search_object) + copy_object + + """ + + # + # ObjectManager Get methods + # + + # player related + + @returns_typeclass + def get_object_with_player(self, ostring, exact=True, candidates=None): + """ + Search for an object based on its player's name or dbref. + This search + is sometimes initiated by appending a * to the beginning of + the search criterion (e.g. in local_and_global_search). + search_string: (string) The name or dbref to search for. + """ + ostring = to_unicode(ostring).lstrip('*') + # simplest case - search by dbref + dbref = self.dbref(ostring) + if dbref: + return dbref + # not a dbref. Search by name. + cand_restriction = candidates != None and Q(pk__in=[_GA(obj, "id") for obj in make_iter(candidates) if obj]) or Q() + if exact: + return self.filter(cand_restriction & Q(db_player__username__iexact=ostring)) + else: # fuzzy matching + ply_cands = self.filter(cand_restriction & Q(playerdb__username__istartswith=ostring)).values_list("db_key", flat=True) + if candidates: + index_matches = string_partial_matching(ply_cands, ostring, ret_index=True) + return [obj for ind, obj in enumerate(make_iter(candidates)) if ind in index_matches] + else: + return string_partial_matching(ply_cands, ostring, ret_index=False) + + @returns_typeclass_list + def get_objs_with_key_and_typeclass(self, oname, otypeclass_path, candidates=None): + """ + Returns objects based on simultaneous key and typeclass match. + """ + cand_restriction = candidates != None and Q(pk__in=[_GA(obj, "id") for obj in make_iter(candidates) if obj]) or Q() + return self.filter(cand_restriction & Q(db_key__iexact=oname, db_typeclass_path__exact=otypeclass_path)) + + # attr/property related + + @returns_typeclass_list + def get_objs_with_attr(self, attribute_name, candidates=None): + """ + Returns all objects having the given attribute_name defined at all. + Location should be a valid location object. + """ + cand_restriction = candidates != None and Q(db_attributes__db_obj__pk__in=[_GA(obj, "id") for obj in make_iter(candidates) if obj]) or Q() + return list(self.filter(cand_restriction & Q(db_attributes__db_key=attribute_name))) + + @returns_typeclass_list + def get_objs_with_attr_value(self, attribute_name, attribute_value, candidates=None, typeclasses=None): + """ + Returns all objects having the valid attrname set to the given value. + + candidates - list of candidate objects to search + typeclasses - list of typeclass-path strings to restrict matches with + + This uses the Attribute's PickledField to transparently search the database by matching + the internal representation. This is reasonably effective but since Attribute values + cannot be indexed, searching by Attribute key is to be preferred whenever possible. + """ + cand_restriction = candidates != None and Q(pk__in=[_GA(obj, "id") for obj in make_iter(candidates) if obj]) or Q() + type_restriction = typeclasses and Q(db_typeclass_path__in=make_iter(typeclasses)) or Q() + + ## This doesn't work if attribute_value is an object. Workaround below + + if isinstance(attribute_value, (basestring, int, float, bool, long)): + return self.filter(cand_restriction & type_restriction & Q(db_attributes__db_key=attribute_name, db_attributes__db_value=attribute_value)) + else: + # We have to loop for safety since the referenced lookup gives deepcopy error if attribute value is an object. + global _ATTR + if not _ATTR: + from src.typeclasses.models import Attribute as _ATTR + cands = list(self.filter(cand_restriction & type_restriction & Q(db_attributes__db_key=attribute_name))) + results = [attr.objectdb_set.all() for attr in _ATTR.objects.filter(objectdb__in=cands, db_value=attribute_value)] + return chain(*results) + + @returns_typeclass_list + def get_objs_with_db_property(self, property_name, candidates=None): + """ + Returns all objects having a given db field property. + property_name = search string + candidates - list of candidate objects to search + """ + property_name = "db_%s" % property_name.lstrip('db_') + cand_restriction = candidates != None and Q(pk__in=[_GA(obj, "id") for obj in make_iter(candidates) if obj]) or Q() + querykwargs = {property_name:None} + try: + return list(self.filter(cand_restriction).exclude(Q(**querykwargs))) + except exceptions.FieldError: + return [] + + @returns_typeclass_list + def get_objs_with_db_property_value(self, property_name, property_value, candidates=None, typeclasses=None): + """ + Returns all objects having a given db field property. + candidates - list of objects to search + typeclasses - list of typeclass-path strings to restrict matches with + """ + if isinstance(property_value, basestring): + property_value = to_unicode(property_value) + if isinstance(property_name, basestring): + if not property_name.startswith('db_'): + property_name = "db_%s" % property_name + if hasattr(property_value, 'dbobj'): + property_value = property_value.dbobj + querykwargs = {property_name:property_value} + cand_restriction = candidates != None and Q(pk__in=[_GA(obj, "id") for obj in make_iter(candidates) if obj]) or Q() + type_restriction = typeclasses and Q(db_typeclass_path__in=make_iter(typeclasses)) or Q() + try: + return list(self.filter(cand_restriction & type_restriction & Q(**querykwargs))) + except exceptions.FieldError: + return [] + except ValueError: + from src.utils import logger + logger.log_errmsg("The property '%s' does not support search criteria of the type %s." % (property_name, type(property_value))) + return [] + + @returns_typeclass_list + def get_contents(self, location, excludeobj=None): + """ + Get all objects that has a location + set to this one. + + excludeobj - one or more object keys to exclude from the match + """ + exclude_restriction = Q(pk__in=[_GA(obj, "id") for obj in make_iter(excludeobj)]) if excludeobj else Q() + return self.filter(db_location=location).exclude(exclude_restriction) + + @returns_typeclass_list + def get_objs_with_key_or_alias(self, ostring, exact=True, + candidates=None, typeclasses=None): + """ + Returns objects based on key or alias match. Will also do fuzzy + matching based on the utils.string_partial_matching function. + candidates - list of candidate objects to restrict on + typeclasses - list of typeclass path strings to restrict on + """ + if not isinstance(ostring, basestring): + if hasattr(ostring, "key"): + ostring = ostring.key + else: + return [] + if is_iter(candidates) and not len(candidates): + # if candidates is an empty iterable there can be no matches + # Exit early. + return [] + + # build query objects + candidates_id = [_GA(obj, "id") for obj in make_iter(candidates) if obj] + cand_restriction = candidates != None and Q(pk__in=make_iter(candidates_id)) or Q() + type_restriction = typeclasses and Q(db_typeclass_path__in=make_iter(typeclasses)) or Q() + if exact: + # exact match - do direct search + return self.filter(cand_restriction & type_restriction & (Q(db_key__iexact=ostring) | + Q(db_tags__db_key__iexact=ostring) & Q(db_tags__db_tagtype__iexact="alias"))).distinct() + elif candidates: + # fuzzy with candidates + key_candidates = self.filter(cand_restriction & type_restriction) + else: + # fuzzy without supplied candidates - we select our own candidates + key_candidates = self.filter(type_restriction & (Q(db_key__istartswith=ostring) | Q(db_tags__db_key__istartswith=ostring))).distinct() + candidates_id = [_GA(obj, "id") for obj in key_candidates] + # fuzzy matching + key_strings = key_candidates.values_list("db_key", flat=True).order_by("id") + + index_matches = string_partial_matching(key_strings, ostring, ret_index=True) + if index_matches: + return [obj for ind, obj in enumerate(key_candidates) if ind in index_matches] + else: + alias_candidates = self.filter(id__in=candidates_id, db_tags__db_tagtype__iexact="alias") + alias_strings = alias_candidates.values_list("db_key", flat=True) + index_matches = string_partial_matching(alias_strings, ostring, ret_index=True) + if index_matches: + return [alias.db_obj for ind, alias in enumerate(alias_candidates) if ind in index_matches] + return [] + + # main search methods and helper functions + + @returns_typeclass_list + def object_search(self, searchdata, + attribute_name=None, + typeclass=None, + candidates=None, + exact=True): + """ + Search as an object globally or in a list of candidates and return + results. The result is always an Object. Always returns a list. + + Arguments: + searchdata: (str or obj) The entity to match for. This is usually a + key string but may also be an object itself. By default (if + not attribute_name is set), this will search object.key and + object.aliases in order. Can also be on the form #dbref, + which will, if exact=True be matched against primary key. + attribute_name: (str): Use this named ObjectAttribute to match + searchdata against, instead of the defaults. If this is + the name of a database field (with or without the db_ prefix), + that will be matched too. + typeclass (str or TypeClass): restrict matches to objects having this + typeclass. This will help speed up global searches. + candidates (list obj ObjectDBs): If supplied, search will only be + performed among the candidates in this list. A common list + of candidates is the contents of the current location + searched. + exact (bool): Match names/aliases exactly or partially. Partial + matching matches the beginning of words in the names/aliases, + using a matching routine to separate multiple matches in + names with multiple components (so "bi sw" will match + "Big sword"). Since this is more expensive than exact + matching, it is recommended to be used together with the + objlist keyword to limit the number of possibilities. This + value has no meaning if searching for attributes/properties. + + Returns: + A list of matching objects (or a list with one unique match) + """ + def _searcher(searchdata, candidates, typeclass, exact=False): + """ + Helper method for searching objects. typeclass is only used + for global searching (no candidates) + """ + if attribute_name: + # attribute/property search (always exact). + matches = self.get_objs_with_db_property_value(attribute_name, searchdata, candidates=candidates, typeclasses=typeclass) + if matches: + return matches + return self.get_objs_with_attr_value(attribute_name, searchdata, candidates=candidates, typeclasses=typeclass) + else: + # normal key/alias search + return self.get_objs_with_key_or_alias(searchdata, exact=exact, candidates=candidates, typeclasses=typeclass) + + if not searchdata and searchdata != 0: + return [] + + if typeclass: + # typeclass may also be a list + typeclasses = make_iter(typeclass) + for i, typeclass in enumerate(make_iter(typeclasses)): + if callable(typeclass): + typeclasses[i] = u"%s.%s" % (typeclass.__module__, typeclass.__name__) + else: + typeclasses[i] = u"%s" % typeclass + typeclass = typeclasses + + if candidates: + # Convenience check to make sure candidates are really dbobjs + candidates = [cand.dbobj for cand in make_iter(candidates) if cand] + if typeclass: + candidates = [cand for cand in candidates + if _GA(cand, "db_typeclass_path") in typeclass] + + dbref = not attribute_name and exact and self.dbref(searchdata) + if dbref is not None: + # Easiest case - dbref matching (always exact) + dbref_match = self.dbref_search(dbref) + if dbref_match: + if not candidates or dbref_match.dbobj in candidates: + return [dbref_match] + else: + return [] + + # Search through all possibilities. + match_number = None + # always run first check exact - we don't want partial matches + # if on the form of 1-keyword etc. + matches = _searcher(searchdata, candidates, typeclass, exact=True) + if not matches: + # no matches found - check if we are dealing with N-keyword + # query - if so, strip it. + match_number, searchdata = _AT_MULTIMATCH_INPUT(searchdata) + # run search again, with the exactness set by call + if match_number is not None or not exact: + matches = _searcher(searchdata, candidates, typeclass, exact=exact) + + # deal with result + if len(matches) > 1 and match_number is not None: + # multiple matches, but a number was given to separate them + try: + matches = [matches[match_number]] + except IndexError: + pass + # return a list (possibly empty) + return matches + + # + # ObjectManager Copy method + # + + def copy_object(self, original_object, new_key=None, + new_location=None, new_home=None, + new_permissions=None, new_locks=None, + new_aliases=None, new_destination=None): + """ + Create and return a new object as a copy of the original object. All + will be identical to the original except for the arguments given + specifically to this method. + + original_object (obj) - the object to make a copy from + new_key (str) - name the copy differently from the original. + new_location (obj) - if not None, change the location + new_home (obj) - if not None, change the Home + new_aliases (list of strings) - if not None, change object aliases. + new_destination (obj) - if not None, change destination + """ + + # get all the object's stats + typeclass_path = original_object.typeclass_path + if not new_key: + new_key = original_object.key + if not new_location: + new_location = original_object.location + if not new_home: + new_home = original_object.home + if not new_aliases: + new_aliases = original_object.aliases.all() + if not new_locks: + new_locks = original_object.db_lock_storage + if not new_permissions: + new_permissions = original_object.permissions.all() + if not new_destination: + new_destination = original_object.destination + + # create new object + from src.utils import create + from src.scripts.models import ScriptDB + new_object = create.create_object(typeclass_path, + key=new_key, + location=new_location, + home=new_home, + permissions=new_permissions, + locks=new_locks, + aliases=new_aliases, + destination=new_destination) + if not new_object: + return None + + # copy over all attributes from old to new. + for attr in original_object.attributes.all(): + new_object.attributes.add(attr.key, attr.value) + + # copy over all cmdsets, if any + for icmdset, cmdset in enumerate(original_object.cmdset.all()): + if icmdset == 0: + new_object.cmdset.add_default(cmdset) + else: + new_object.cmdset.add(cmdset) + + # copy over all scripts, if any + for script in original_object.scripts.all(): + ScriptDB.objects.copy_script(script, new_obj=new_object.dbobj) + + return new_object + + def clear_all_sessids(self): + """ + Clear the db_sessid field of all objects having also the db_player field + set. + """ + self.filter(db_sessid__isnull=False).update(db_sessid=None) + + + +#~ url = "http://cmsdoc.cern.ch/cms/test/aprom/phedex/dev/gowri/datasvc/tbedi/requestDetails" +#~ params = {'format':'json'} +#~ import urllib +#~ eparams = urllib.urlencode(params) +#~ import urllib2 +#~ request = urllib2.Request(url,eparams) +#~ response = urllib2.urlopen(request) +#~ s = response.read() +#~ response.close() + +#~ print s + +s = """ +{"phedex":{"request":[{"last_update":"1188037561", "numofapproved":"1", +"id":"7425"}, {"last_update":"1188751826", "numofapproved":"1", +"id":"8041"}, {"last_update":"1190116795", "numofapproved":"1", +"id":"9281"}, {"last_update":"1190248781", "numofapproved":"1", +"id":"9521"}, {"last_update":"1192615612", "numofapproved":"1", +"id":"12821"}, {"last_update":"1192729887", "numofapproved":"1", +"id":"13121"}, {"last_update":"1193152971", "numofapproved":"1", +"id":"13501"}, {"last_update":"1194022054", "numofapproved":"1", +"id":"14782"}, {"last_update":"1194429365", "numofapproved":"1", +"id":"15081"}, {"last_update":"1195069848", "numofapproved":"1", +"id":"16661"}, {"last_update":"1178403225", "numofapproved":"1", +"id":"1281"}, {"last_update":"1179239056", "numofapproved":"1", +"id":"1387"}, {"last_update":"1179842205", "numofapproved":"1", +"id":"1665"}, {"last_update":"1179842040", "numofapproved":"1", +"id":"1661"}, {"last_update":"1179935333", "numofapproved":"1", +"id":"1741"}, {"last_update":"1183151195", "numofapproved":"1", +"id":"3841"}, {"last_update":"1187031531", "numofapproved":"1", +"id":"6601"}, {"last_update":"1188820478", "numofapproved":"1", +"id":"8121"}, {"last_update":"1190652719", "numofapproved":"1", +"id":"9983"}, {"last_update":"1192628950", "numofapproved":"1", +"id":"12841"}, {"last_update":"1193075426", "numofapproved":"1", +"id":"13341"}, {"last_update":"1194214609", "numofapproved":"1", +"id":"14882"}, {"last_update":"1194387864", "numofapproved":"1", +"id":"15062"}, {"last_update":"1195134504", "numofapproved":"1", +"id":"16741"}, {"last_update":"1182431453", "numofapproved":"1", +"id":"3421"}, {"last_update":"1183448188", "numofapproved":"1", +"id":"4061"}, {"last_update":"1184588081", "numofapproved":"1", +"id":"4908"}, {"last_update":"1184681258", "numofapproved":"1", +"id":"4913"}, {"last_update":"1188039048", "numofapproved":"1", +"id":"7426"}, {"last_update":"1192699041", "numofapproved":"1", +"id":"12982"}, {"last_update":"1193219685", "numofapproved":"1", +"id":"13529"}, {"last_update":"1193401408", "numofapproved":"1", +"id":"14081"}, {"last_update":"1194454724", "numofapproved":"1", +"id":"15201"}, {"last_update":"1194937690", "numofapproved":"1", +"id":"16044"}, {"last_update":"1194947125", "numofapproved":"1", +"id":"16103"}, {"last_update":"1195134890", "numofapproved":"1", +"id":"16761"}, {"last_update":"1195486898", "numofapproved":"1", +"id":"17301"}, {"last_update":"1195497774", "numofapproved":"1", +"id":"17341"}, {"last_update":"1184744080", "numofapproved":"1", +"id":"4941"}, {"last_update":"1186558911", "numofapproved":"1", +"id":"6321"}, {"last_update":"1189524520", "numofapproved":"1", +"id":"8802"}, {"last_update":"1192683178", "numofapproved":"1", +"id":"12921"}, {"last_update":"1193260655", "numofapproved":"1", +"id":"13530"}, {"last_update":"1194280038", "numofapproved":"1", +"id":"15002"}, {"last_update":"1182077478", "numofapproved":"1", +"id":"3162"}, {"last_update":"1183386650", "numofapproved":"1", +"id":"3961"}, {"last_update":"1192063369", "numofapproved":"1", +"id":"12182"}, {"last_update":"1181931262", "numofapproved":"1", +"id":"3101"}, {"last_update":"1178648271", "numofapproved":"1", +"id":"1308"}, {"last_update":"1179239923", "numofapproved":"1", +"id":"1405"}, {"last_update":"1184370745", "numofapproved":"1", +"id":"4861"}, {"last_update":"1185280568", "numofapproved":"1", +"id":"5302"}, {"last_update":"1187875115", "numofapproved":"1", +"id":"7344"}, {"last_update":"1189140441", "numofapproved":"1", +"id":"8541"}, {"last_update":"1189180903", "numofapproved":"1", +"id":"8661"}, {"last_update":"1189767643", "numofapproved":"1", +"id":"9001"}, {"last_update":"1190726167", "numofapproved":"1", +"id":"10101"}, {"last_update":"1190972990", "numofapproved":"1", +"id":"10661"}, {"last_update":"1190990720", "numofapproved":"1", +"id":"10712"}, {"last_update":"1192004838", "numofapproved":"1", +"id":"12021"}, {"last_update":"1192612211", "numofapproved":"1", +"id":"12803"}, {"last_update":"1194441407", "numofapproved":"1", +"id":"15103"}, {"last_update":"1194792356", "numofapproved":"1", +"id":"15681"}, {"last_update":"1194860650", "numofapproved":"1", +"id":"15801"}, {"last_update":"1194877395", "numofapproved":"1", +"id":"15881"}, {"last_update":"1194950552", "numofapproved":"1", +"id":"16124"}, {"last_update":"1194992714", "numofapproved":"1", +"id":"16421"}, {"last_update":"1195054500", "numofapproved":"1", +"id":"16581"}, {"last_update":"1195228524", "numofapproved":"1", +"id":"17001"}, {"last_update":"1195469382", "numofapproved":"1", +"id":"17161"}, {"last_update":"1178035947", "numofapproved":"1", +"id":"1202"}, {"last_update":"1178869668", "numofapproved":"1", +"id":"1356"}, {"last_update":"1183563268", "numofapproved":"1", +"id":"4201"}, {"last_update":"1185314677", "numofapproved":"1", +"id":"5361"}, {"last_update":"1188467567", "numofapproved":"1", +"id":"7781"}, {"last_update":"1190011821", "numofapproved":"1", +"id":"9202"}, {"last_update":"1190206214", "numofapproved":"1", +"id":"9481"}, {"last_update":"1190973037", "numofapproved":"1", +"id":"10663"}, {"last_update":"1190819127", "numofapproved":"1", +"id":"10342"}, {"last_update":"1192154959", "numofapproved":"1", +"id":"12381"}, {"last_update":"1192634509", "numofapproved":"1", +"id":"12862"}, {"last_update":"1194004677", "numofapproved":"1", +"id":"14722"}, {"last_update":"1195548191", "numofapproved":"1", +"id":"17501"}, {"last_update":"1195548953", "numofapproved":"1", +"id":"17502"}, {"last_update":"1195559809", "numofapproved":"1", +"id":"17541"}, {"last_update":"1177589103", "numofapproved":"1", +"id":"1044"}, {"last_update":"1183416879", "numofapproved":"1", +"id":"4041"}, {"last_update":"1186646977", "numofapproved":"1", +"id":"6342"}, {"last_update":"1189656586", "numofapproved":"1", +"id":"8902"}, {"last_update":"1190150645", "numofapproved":"1", +"id":"9421"}, {"last_update":"1190409040", "numofapproved":"1", +"id":"9741"}, {"last_update":"1190973011", "numofapproved":"1", +"id":"10662"}, {"last_update":"1190993896", "numofapproved":"1", +"id":"10761"}, {"last_update":"1193973610", "numofapproved":"1", +"id":"14661"}, {"last_update":"1193973848", "numofapproved":"1", +"id":"14664"}, {"last_update":"1194539978", "numofapproved":"1", +"id":"15381"}, {"last_update":"1194947356", "numofapproved":"1", +"id":"16105"}, {"last_update":"1195399589", "numofapproved":"1", +"id":"17101"}, {"last_update":"1195464953", "numofapproved":"1", +"id":"17141"}, {"last_update":"1171962221", "numofapproved":"1", +"id":"109"}, {"last_update":"1173113812", "numofapproved":"1", +"id":"247"}, {"last_update":"1173975435", "numofapproved":"1", +"id":"343"}, {"last_update":"1174050971", "numofapproved":"1", +"id":"353"}, {"last_update":"1174301484", "numofapproved":"1", +"id":"393"}, {"last_update":"1172565853", "numofapproved":"1", +"id":"208"}, {"last_update":"1172593328", "numofapproved":"1", +"id":"215"}, {"last_update":"1175267391", "numofapproved":"1", +"id":"565"}, {"last_update":"1171379845", "numofapproved":"1", +"id":"25"}, {"last_update":"1171477466", "numofapproved":"1", +"id":"53"}, {"last_update":"1171799296", "numofapproved":"1", +"id":"77"}, {"last_update":"1172671474", "numofapproved":"1", +"id":"223"}, {"last_update":"1174301354", "numofapproved":"1", +"id":"388"}, {"last_update":"1174899552", "numofapproved":"1", +"id":"511"}, {"last_update":"1174899458", "numofapproved":"1", +"id":"505"}, {"last_update":"1175502936", "numofapproved":"1", +"id":"604"}, {"last_update":"1175613825", "numofapproved":"1", +"id":"665"}, {"last_update":"1175776232", "numofapproved":"1", +"id":"673"}, {"last_update":"1171621302", "numofapproved":"1", +"id":"68"}, {"last_update":"1171904738", "numofapproved":"1", +"id":"98"}, {"last_update":"1171968012", "numofapproved":"1", +"id":"115"}, {"last_update":"1172145037", "numofapproved":"1", +"id":"168"}, {"last_update":"1172246599", "numofapproved":"1", +"id":"185"}, {"last_update":"1173886280", "numofapproved":"1", +"id":"318"}, {"last_update":"1174562010", "numofapproved":"1", +"id":"423"}, {"last_update":"1176308974", "numofapproved":"1", +"id":"884"}, {"last_update":"1176482150", "numofapproved":"1", +"id":"943"}, {"last_update":"1176702424", "numofapproved":"1", +"id":"1001"}, {"last_update":"1176748776", "numofapproved":"1", +"id":"984"}, {"last_update":"1172669745", "numofapproved":"1", +"id":"222"}, {"last_update":"1174899538", "numofapproved":"1", +"id":"510"}, {"last_update":"1174899143", "numofapproved":"1", +"id":"493"}, {"last_update":"1174899043", "numofapproved":"1", +"id":"488"}, {"last_update":"1175711780", "numofapproved":"1", +"id":"667"}, {"last_update":"1175712851", "numofapproved":"1", +"id":"705"}, {"last_update":"1176296548", "numofapproved":"1", +"id":"841"}, {"last_update":"1175862269", "numofapproved":"1", +"id":"781"}, {"last_update":"1171483107", "numofapproved":"1", +"id":"54"}, {"last_update":"1171645737", "numofapproved":"1", +"id":"71"}, {"last_update":"1172253423", "numofapproved":"1", +"id":"188"}, {"last_update":"1173888726", "numofapproved":"1", +"id":"321"}, {"last_update":"1173975649", "numofapproved":"1", +"id":"346"}, {"last_update":"1174299379", "numofapproved":"1", +"id":"363"}, {"last_update":"1174301359", "numofapproved":"1", +"id":"389"}, {"last_update":"1174301073", "numofapproved":"1", +"id":"379"}, {"last_update":"1174300650", "numofapproved":"1", +"id":"371"}, {"last_update":"1171485069", "numofapproved":"1", +"id":"55"}, {"last_update":"1171799178", "numofapproved":"1", +"id":"73"}, {"last_update":"1171896809", "numofapproved":"1", +"id":"95"}, {"last_update":"1172672959", "numofapproved":"1", +"id":"224"}, {"last_update":"1172693619", "numofapproved":"1", +"id":"230"}, {"last_update":"1173207656", "numofapproved":"1", +"id":"253"}, {"last_update":"1174059533", "numofapproved":"1", +"id":"356"}, {"last_update":"1174300538", "numofapproved":"1", +"id":"368"}, {"last_update":"1176137457", "numofapproved":"1", +"id":"807"}, {"last_update":"1173728124", "numofapproved":"1", +"id":"305"}, {"last_update":"1172507633", "numofapproved":"1", +"id":"198"}, {"last_update":"1174301173", "numofapproved":"1", +"id":"383"}, {"last_update":"1174899102", "numofapproved":"1", +"id":"491"}, {"last_update":"1174301362", "numofapproved":"1", +"id":"390"}, {"last_update":"1175254095", "numofapproved":"1", +"id":"561"}, {"last_update":"1174037250", "numofapproved":"1", +"id":"348"}, {"last_update":"1175865081", "numofapproved":"1", +"id":"782"}, {"last_update":"1177591942", "numofapproved":"1", +"id":"1046"}, {"last_update":"1177989191", "numofapproved":"1", +"id":"1201"}, {"last_update":"1178743279", "numofapproved":"1", +"id":"1323"}, {"last_update":"1178876587", "numofapproved":"1", +"id":"1357"}, {"last_update":"1179239620", "numofapproved":"1", +"id":"1401"}, {"last_update":"1180725458", "numofapproved":"1", +"id":"2141"}, {"last_update":"1181205209", "numofapproved":"1", +"id":"2421"}, {"last_update":"1181575615", "numofapproved":"1", +"id":"2761"}, {"last_update":"1182184775", "numofapproved":"1", +"id":"3201"}, {"last_update":"1182963728", "numofapproved":"1", +"id":"3661"}, {"last_update":"1178727735", "numofapproved":"1", +"id":"1349"}, {"last_update":"1182497720", "numofapproved":"1", +"id":"3441"}, {"last_update":"1184381847", "numofapproved":"1", +"id":"4881"}, {"last_update":"1184568423", "numofapproved":"1", +"id":"4904"}, {"last_update":"1185364813", "numofapproved":"1", +"id":"5421"}, {"last_update":"1188043594", "numofapproved":"1", +"id":"7441"}, {"last_update":"1188675287", "numofapproved":"1", +"id":"7981"}, {"last_update":"1188741594", "numofapproved":"1", +"id":"8021"}, {"last_update":"1189144234", "numofapproved":"1", +"id":"8561"}, {"last_update":"1189170150", "numofapproved":"1", +"id":"8641"}, {"last_update":"1189501508", "numofapproved":"1", +"id":"8761"}, {"last_update":"1189811918", "numofapproved":"1", +"id":"9041"}, {"last_update":"1189812095", "numofapproved":"1", +"id":"9042"}, {"last_update":"1177591716", "numofapproved":"1", +"id":"1045"}, {"last_update":"1178040595", "numofapproved":"1", +"id":"1203"}, {"last_update":"1182437936", "numofapproved":"1", +"id":"3423"}, {"last_update":"1190480042", "numofapproved":"1", +"id":"9781"}, {"last_update":"1190821494", "numofapproved":"1", +"id":"10361"}, {"last_update":"1190959672", "numofapproved":"1", +"id":"10602"}, {"last_update":"1190964023", "numofapproved":"1", +"id":"10621"}, {"last_update":"1190991147", "numofapproved":"1", +"id":"10721"}, {"last_update":"1190992132", "numofapproved":"1", +"id":"10741"}, {"last_update":"1190990410", "numofapproved":"1", +"id":"10706"}, {"last_update":"1181667132", "numofapproved":"1", +"id":"2861"}, {"last_update":"1183746653", "numofapproved":"1", +"id":"4321"}, {"last_update":"1191184539", "numofapproved":"1", +"id":"10861"}, {"last_update":"1191490599", "numofapproved":"1", +"id":"11261"}, {"last_update":"1191834884", "numofapproved":"1", +"id":"11801"}, {"last_update":"1191834899", "numofapproved":"1", +"id":"11802"}, {"last_update":"1191940759", "numofapproved":"1", +"id":"11961"}, {"last_update":"1179971250", "numofapproved":"1", +"id":"1643"}, {"last_update":"1181663618", "numofapproved":"1", +"id":"2841"}, {"last_update":"1181932994", "numofapproved":"1", +"id":"3102"}, {"last_update":"1182420732", "numofapproved":"1", +"id":"3382"}, {"last_update":"1192118127", "numofapproved":"1", +"id":"12281"}, {"last_update":"1192222036", "numofapproved":"1", +"id":"12481"}, {"last_update":"1192155814", "numofapproved":"1", +"id":"12364"}, {"last_update":"1192563924", "numofapproved":"1", +"id":"12761"}, {"last_update":"1193124530", "numofapproved":"1", +"id":"13441"}, {"last_update":"1193345545", "numofapproved":"1", +"id":"13921"}, {"last_update":"1193396927", "numofapproved":"1", +"id":"14041"}, {"last_update":"1180015411", "numofapproved":"1", +"id":"1651"}, {"last_update":"1180107815", "numofapproved":"1", +"id":"1658"}, {"last_update":"1186050394", "numofapproved":"1", +"id":"6021"}, {"last_update":"1188519417", "numofapproved":"1", +"id":"7841"}, {"last_update":"1193222002", "numofapproved":"1", +"id":"13541"}, {"last_update":"1193965081", "numofapproved":"1", +"id":"14641"}, {"last_update":"1193660582", "numofapproved":"1", +"id":"14381"}, {"last_update":"1194088240", "numofapproved":"1", +"id":"14821"}, {"last_update":"1194110475", "numofapproved":"1", +"id":"14841"}, {"last_update":"1194246367", "numofapproved":"1", +"id":"14902"}, {"last_update":"1194464283", "numofapproved":"1", +"id":"15221"}, {"last_update":"1194622250", "numofapproved":"1", +"id":"15461"}, {"last_update":"1194635632", "numofapproved":"1", +"id":"15601"}, {"last_update":"1179147506", "numofapproved":"1", +"id":"1382"}, {"last_update":"1179240025", "numofapproved":"1", +"id":"1388"}, {"last_update":"1179748089", "numofapproved":"1", +"id":"1561"}, {"last_update":"1179868997", "numofapproved":"1", +"id":"1681"}, {"last_update":"1183019667", "numofapproved":"1", +"id":"3702"}, {"last_update":"1184531598", "numofapproved":"1", +"id":"4902"}, {"last_update":"1187294472", "numofapproved":"1", +"id":"6841"}, {"last_update":"1189521494", "numofapproved":"1", +"id":"8801"}, {"last_update":"1192726867", "numofapproved":"1", +"id":"13081"}, {"last_update":"1193049178", "numofapproved":"1", +"id":"13301"}, {"last_update":"1193387050", "numofapproved":"1", +"id":"13947"}, {"last_update":"1194277280", "numofapproved":"1", +"id":"14981"}, {"last_update":"1179150720", "numofapproved":"1", +"id":"1383"}, {"last_update":"1179842104", "numofapproved":"1", +"id":"1663"}, {"last_update":"1183766887", "numofapproved":"1", +"id":"4341"}, {"last_update":"1185542132", "numofapproved":"1", +"id":"5682"}, {"last_update":"1186737114", "numofapproved":"1", +"id":"6382"}, {"last_update":"1187015679", "numofapproved":"1", +"id":"6521"}, {"last_update":"1190326980", "numofapproved":"1", +"id":"9641"}, {"last_update":"1191595711", "numofapproved":"1", +"id":"11622"}, {"last_update":"1192106288", "numofapproved":"1", +"id":"12221"}, {"last_update":"1192454432", "numofapproved":"1", +"id":"12622"}, {"last_update":"1194339640", "numofapproved":"1", +"id":"15021"}, {"last_update":"1177758209", "numofapproved":"1", +"id":"1181"}, {"last_update":"1179842392", "numofapproved":"1", +"id":"1669"}, {"last_update":"1179872870", "numofapproved":"1", +"id":"1682"}, {"last_update":"1181233887", "numofapproved":"1", +"id":"2541"}, {"last_update":"1182349297", "numofapproved":"1", +"id":"3342"}, {"last_update":"1182375421", "numofapproved":"1", +"id":"3350"}, {"last_update":"1183485259", "numofapproved":"1", +"id":"4081"}, {"last_update":"1184319308", "numofapproved":"1", +"id":"4821"}, {"last_update":"1187626648", "numofapproved":"1", +"id":"6981"}, {"last_update":"1193153090", "numofapproved":"1", +"id":"13502"}, {"last_update":"1194366368", "numofapproved":"1", +"id":"15041"}, {"last_update":"1194617018", "numofapproved":"1", +"id":"15421"}, {"last_update":"1195230640", "numofapproved":"1", +"id":"17021"}, {"last_update":"1179908379", "numofapproved":"1", +"id":"1701"}, {"last_update":"1188049228", "numofapproved":"1", +"id":"7427"}, {"last_update":"1177581166", "numofapproved":"1", +"id":"1061"}, {"last_update":"1187160654", "numofapproved":"1", +"id":"6661"}, {"last_update":"1192983992", "numofapproved":"1", +"id":"13222"}, {"last_update":"1193388978", "numofapproved":"1", +"id":"13954"}, {"last_update":"1194617112", "numofapproved":"1", +"id":"15422"}, {"last_update":"1195398876", "numofapproved":"1", +"id":"17081"}, {"last_update":"1184262511", "numofapproved":"1", +"id":"4801"}, {"last_update":"1192112284", "numofapproved":"1", +"id":"12241"}, {"last_update":"1193082767", "numofapproved":"1", +"id":"13401"}, {"last_update":"1193179243", "numofapproved":"1", +"id":"13526"}, {"last_update":"1178142915", "numofapproved":"1", +"id":"1206"}, {"last_update":"1178648333", "numofapproved":"1", +"id":"1310"}, {"last_update":"1179279626", "numofapproved":"1", +"id":"1391"}, {"last_update":"1182882268", "numofapproved":"1", +"id":"3584"}, {"last_update":"1183128448", "numofapproved":"1", +"id":"3823"}, {"last_update":"1183377394", "numofapproved":"1", +"id":"3941"}, {"last_update":"1188582729", "numofapproved":"1", +"id":"7902"}, {"last_update":"1189695063", "numofapproved":"1", +"id":"8962"}, {"last_update":"1192001165", "numofapproved":"1", +"id":"12001"}, {"last_update":"1192155647", "numofapproved":"1", +"id":"12363"}, {"last_update":"1193418304", "numofapproved":"1", +"id":"14202"}, {"last_update":"1193632105", "numofapproved":"1", +"id":"14341"}, {"last_update":"1194011106", "numofapproved":"1", +"id":"14741"}, {"last_update":"1194818628", "numofapproved":"1", +"id":"15701"}, {"last_update":"1194875153", "numofapproved":"1", +"id":"15861"}, {"last_update":"1194727029", "numofapproved":"1", +"id":"15665"}, {"last_update":"1194950210", "numofapproved":"1", +"id":"16122"}, {"last_update":"1194976681", "numofapproved":"1", +"id":"16241"}, {"last_update":"1194979189", "numofapproved":"1", +"id":"16281"}, {"last_update":"1194962224", "numofapproved":"1", +"id":"16201"}, {"last_update":"1195046085", "numofapproved":"1", +"id":"16481"}, {"last_update":"1195399919", "numofapproved":"1", +"id":"17102"}, {"last_update":"1183113736", "numofapproved":"1", +"id":"3782"}, {"last_update":"1183114202", "numofapproved":"1", +"id":"3783"}, {"last_update":"1189017904", "numofapproved":"1", +"id":"8441"}, {"last_update":"1189694944", "numofapproved":"1", +"id":"8961"}, {"last_update":"1190766842", "numofapproved":"1", +"id":"10181"}, {"last_update":"1190973066", "numofapproved":"1", +"id":"10665"}, {"last_update":"1190990264", "numofapproved":"1", +"id":"10702"}, {"last_update":"1193043204", "numofapproved":"1", +"id":"13281"}, {"last_update":"1194627082", "numofapproved":"1", +"id":"15561"}, {"last_update":"1194894589", "numofapproved":"1", +"id":"15941"}, {"last_update":"1195485915", "numofapproved":"1", +"id":"17281"}, {"last_update":"1195485806", "numofapproved":"1", +"id":"17261"}, {"last_update":"1195498836", "numofapproved":"1", +"id":"17361"}, {"last_update":"1195514951", "numofapproved":"1", +"id":"17421"}, {"last_update":"1183722351", "numofapproved":"1", +"id":"4261"}, {"last_update":"1184218083", "numofapproved":"1", +"id":"4682"}, {"last_update":"1186848968", "numofapproved":"1", +"id":"6441"}, {"last_update":"1187023846", "numofapproved":"1", +"id":"6561"}, {"last_update":"1187870812", "numofapproved":"1", +"id":"7342"}, {"last_update":"1188657717", "numofapproved":"1", +"id":"7961"}, {"last_update":"1190541897", "numofapproved":"1", +"id":"9841"}, {"last_update":"1190629135", "numofapproved":"1", +"id":"9922"}, {"last_update":"1191226530", "numofapproved":"1", +"id":"10922"}, {"last_update":"1191505214", "numofapproved":"1", +"id":"11321"}, {"last_update":"1192304524", "numofapproved":"1", +"id":"12541"}, {"last_update":"1193948730", "numofapproved":"1", +"id":"14601"}, {"last_update":"1194073812", "numofapproved":"1", +"id":"14801"}, {"last_update":"1194387224", "numofapproved":"1", +"id":"14892"}, {"last_update":"1194464384", "numofapproved":"1", +"id":"15223"}, {"last_update":"1194726799", "numofapproved":"1", +"id":"15663"}, {"last_update":"1171969969", "numofapproved":"1", +"id":"119"}, {"last_update":"1174444717", "numofapproved":"1", +"id":"405"}, {"last_update":"1174899431", "numofapproved":"1", +"id":"504"}, {"last_update":"1174899204", "numofapproved":"1", +"id":"496"}, {"last_update":"1174925591", "numofapproved":"1", +"id":"530"}, {"last_update":"1176902523", "numofapproved":"1", +"id":"1008"}, {"last_update":"1172765523", "numofapproved":"1", +"id":"232"}, {"last_update":"1173315950", "numofapproved":"1", +"id":"260"}, {"last_update":"1174899524", "numofapproved":"1", +"id":"509"}, {"last_update":"1174300691", "numofapproved":"1", +"id":"373"}, {"last_update":"1175502917", "numofapproved":"1", +"id":"625"}, {"last_update":"1175601578", "numofapproved":"1", +"id":"662"}, {"last_update":"1175608600", "numofapproved":"1", +"id":"684"}, {"last_update":"1176755309", "numofapproved":"1", +"id":"985"}, {"last_update":"1171386411", "numofapproved":"1", +"id":"45"}, {"last_update":"1171800366", "numofapproved":"1", +"id":"81"}, {"last_update":"1172847417", "numofapproved":"1", +"id":"241"}, {"last_update":"1174734904", "numofapproved":"1", +"id":"462"}, {"last_update":"1174735234", "numofapproved":"1", +"id":"469"}, {"last_update":"1174735074", "numofapproved":"1", +"id":"465"}, {"last_update":"1175267646", "numofapproved":"1", +"id":"566"}, {"last_update":"1176331857", "numofapproved":"1", +"id":"888"}, {"last_update":"1176387926", "numofapproved":"1", +"id":"890"}, {"last_update":"1176458401", "numofapproved":"1", +"id":"904"}, {"last_update":"1173088626", "numofapproved":"1", +"id":"244"}, {"last_update":"1173109009", "numofapproved":"1", +"id":"246"}, {"last_update":"1173671557", "numofapproved":"1", +"id":"284"}, {"last_update":"1174927658", "numofapproved":"1", +"id":"532"}, {"last_update":"1175592399", "numofapproved":"1", +"id":"661"}, {"last_update":"1176480402", "numofapproved":"1", +"id":"941"}, {"last_update":"1176561564", "numofapproved":"1", +"id":"945"}, {"last_update":"1172218707", "numofapproved":"1", +"id":"180"}, {"last_update":"1172771475", "numofapproved":"1", +"id":"233"}, {"last_update":"1173267863", "numofapproved":"1", +"id":"257"}, {"last_update":"1176493803", "numofapproved":"1", +"id":"963"}, {"last_update":"1171449646", "numofapproved":"1", +"id":"49"}, {"last_update":"1171471549", "numofapproved":"1", +"id":"51"}, {"last_update":"1171800487", "numofapproved":"1", +"id":"88"}, {"last_update":"1171800431", "numofapproved":"1", +"id":"85"}, {"last_update":"1175502995", "numofapproved":"1", +"id":"627"}, {"last_update":"1175712797", "numofapproved":"1", +"id":"704"}, {"last_update":"1171122384", "numofapproved":"1", +"id":"3"}, {"last_update":"1171380774", "numofapproved":"1", "id":"26"}, +{"last_update":"1171904757", "numofapproved":"1", "id":"99"}, +{"last_update":"1174300705", "numofapproved":"1", "id":"374"}, +{"last_update":"1174924802", "numofapproved":"1", "id":"526"}, +{"last_update":"1175935441", "numofapproved":"1", "id":"801"}, +{"last_update":"1175610915", "numofapproved":"1", "id":"686"}, +{"last_update":"1171977081", "numofapproved":"1", "id":"125"}, +{"last_update":"1173165324", "numofapproved":"1", "id":"249"}, +{"last_update":"1173888337", "numofapproved":"1", "id":"319"}, +{"last_update":"1173889473", "numofapproved":"1", "id":"331"}, +{"last_update":"1172180902", "numofapproved":"1", "id":"175"}, +{"last_update":"1174058063", "numofapproved":"1", "id":"354"}, +{"last_update":"1174300674", "numofapproved":"1", "id":"372"}, +{"last_update":"1171886332", "numofapproved":"1", "id":"93"}, +{"last_update":"1176731068", "numofapproved":"1", "id":"1003"}, +{"last_update":"1178645848", "numofapproved":"1", "id":"1306"}, +{"last_update":"1178706683", "numofapproved":"1", "id":"1321"}, +{"last_update":"1179240076", "numofapproved":"1", "id":"1406"}, +{"last_update":"1180380411", "numofapproved":"1", "id":"1862"}, +{"last_update":"1180683561", "numofapproved":"1", "id":"2041"}, +{"last_update":"1181229731", "numofapproved":"1", "id":"2521"}, +{"last_update":"1182210982", "numofapproved":"1", "id":"3203"}, +{"last_update":"1182421105", "numofapproved":"1", "id":"3401"}, +{"last_update":"1182199404", "numofapproved":"1", "id":"3202"}, +{"last_update":"1182258596", "numofapproved":"1", "id":"3241"}, +{"last_update":"1183556842", "numofapproved":"1", "id":"4161"}, +{"last_update":"1184146825", "numofapproved":"1", "id":"4601"}, +{"last_update":"1184771229", "numofapproved":"1", "id":"4981"}, +{"last_update":"1185355415", "numofapproved":"1", "id":"5401"}, +{"last_update":"1185377130", "numofapproved":"1", "id":"5481"}, +{"last_update":"1185483994", "numofapproved":"1", "id":"5621"}, +{"last_update":"1186496707", "numofapproved":"1", "id":"6261"}, +{"last_update":"1187704347", "numofapproved":"1", "id":"7001"}, +{"last_update":"1187758331", "numofapproved":"1", "id":"7101"}, +{"last_update":"1187765716", "numofapproved":"1", "id":"7161"}, +{"last_update":"1188284185", "numofapproved":"1", "id":"7581"}, +{"last_update":"1188463286", "numofapproved":"1", "id":"7761"}, +{"last_update":"1189012058", "numofapproved":"1", "id":"8421"}, +{"last_update":"1189814265", "numofapproved":"1", "id":"9061"}, +{"last_update":"1180880867", "numofapproved":"1", "id":"2161"}, +{"last_update":"1181218244", "numofapproved":"1", "id":"2463"}, +{"last_update":"1183515137", "numofapproved":"1", "id":"4141"}, +{"last_update":"1183515248", "numofapproved":"1", "id":"4142"}, +{"last_update":"1188311100", "numofapproved":"1", "id":"7641"}, +{"last_update":"1190011501", "numofapproved":"1", "id":"9201"}, +{"last_update":"1190012299", "numofapproved":"1", "id":"9221"}, +{"last_update":"1190149196", "numofapproved":"1", "id":"9382"}, +{"last_update":"1190202046", "numofapproved":"1", "id":"9461"}, +{"last_update":"1190626607", "numofapproved":"1", "id":"9881"}, +{"last_update":"1190632230", "numofapproved":"1", "id":"9941"}, +{"last_update":"1190660429", "numofapproved":"1", "id":"10002"}, +{"last_update":"1190819102", "numofapproved":"1", "id":"10341"}, +{"last_update":"1190824319", "numofapproved":"1", "id":"10382"}, +{"last_update":"1190825791", "numofapproved":"1", "id":"10402"}, +{"last_update":"1190847397", "numofapproved":"1", "id":"10421"}, +{"last_update":"1190876679", "numofapproved":"1", "id":"10441"}, +{"last_update":"1190918894", "numofapproved":"1", "id":"10541"}, +{"last_update":"1190924961", "numofapproved":"1", "id":"10582"}, +{"last_update":"1190991179", "numofapproved":"1", "id":"10723"}, +{"last_update":"1190663960", "numofapproved":"1", "id":"10042"}, +{"last_update":"1191222270", "numofapproved":"1", "id":"10881"}, +{"last_update":"1178869580", "numofapproved":"1", "id":"1355"}, +{"last_update":"1180054057", "numofapproved":"1", "id":"1655"}, +{"last_update":"1180428815", "numofapproved":"1", "id":"1881"}, +{"last_update":"1183369278", "numofapproved":"1", "id":"3901"}, +{"last_update":"1185018445", "numofapproved":"1", "id":"5163"}, +{"last_update":"1185201628", "numofapproved":"1", "id":"5221"}, +{"last_update":"1189345395", "numofapproved":"1", "id":"8741"}, +{"last_update":"1191406141", "numofapproved":"1", "id":"11041"}, +{"last_update":"1191410914", "numofapproved":"1", "id":"11067"}, +{"last_update":"1191558362", "numofapproved":"1", "id":"11461"}, +{"last_update":"1191584539", "numofapproved":"1", "id":"11541"}, +{"last_update":"1191584660", "numofapproved":"1", "id":"11542"}, +{"last_update":"1191599491", "numofapproved":"1", "id":"11661"}, +{"last_update":"1191813292", "numofapproved":"1", "id":"11781"}, +{"last_update":"1191856553", "numofapproved":"1", "id":"11842"}, +{"last_update":"1191861142", "numofapproved":"1", "id":"11862"}, +{"last_update":"1177509523", "numofapproved":"1", "id":"1041"}, +{"last_update":"1190627650", "numofapproved":"1", "id":"9901"}, +{"last_update":"1192034749", "numofapproved":"1", "id":"12141"}, +{"last_update":"1192165574", "numofapproved":"1", "id":"12401"}, +{"last_update":"1192431750", "numofapproved":"1", "id":"12581"}, +{"last_update":"1192536591", "numofapproved":"1", "id":"12721"}, +{"last_update":"1193035428", "numofapproved":"1", "id":"13261"}, +{"last_update":"1193239266", "numofapproved":"1", "id":"13581"}, +{"last_update":"1193314455", "numofapproved":"1", "id":"13841"}, +{"last_update":"1193333733", "numofapproved":"1", "id":"13901"}, +{"last_update":"1193389116", "numofapproved":"1", "id":"14001"}, +{"last_update":"1184970339", "numofapproved":"1", "id":"5121"}, +{"last_update":"1190892760", "numofapproved":"1", "id":"10481"}, +{"last_update":"1192823398", "numofapproved":"1", "id":"13182"}, +{"last_update":"1193911671", "numofapproved":"1", "id":"14541"}, +{"last_update":"1193916761", "numofapproved":"1", "id":"14543"}, +{"last_update":"1194212665", "numofapproved":"1", "id":"14881"}, +{"last_update":"1194248205", "numofapproved":"1", "id":"14921"}, +{"last_update":"1194513600", "numofapproved":"1", "id":"15110"}, +{"last_update":"1194539704", "numofapproved":"1", "id":"15361"}, +{"last_update":"1194569643", "numofapproved":"1", "id":"15112"}, +{"last_update":"1194619794", "numofapproved":"1", "id":"15441"}, +{"last_update":"1194623621", "numofapproved":"1", "id":"15501"}, +{"last_update":"1194624477", "numofapproved":"1", "id":"15521"}, +{"last_update":"1194635685", "numofapproved":"1", "id":"15602"}, +{"last_update":"1179311539", "numofapproved":"1", "id":"1393"}, +{"last_update":"1179672561", "numofapproved":"1", "id":"1521"}, +{"last_update":"1180712413", "numofapproved":"1", "id":"2101"}, +{"last_update":"1181646264", "numofapproved":"1", "id":"2821"}, +{"last_update":"1181807696", "numofapproved":"1", "id":"2921"}, +{"last_update":"1181824523", "numofapproved":"1", "id":"2942"}, +{"last_update":"1181835089", "numofapproved":"1", "id":"2981"}, +{"last_update":"1182000147", "numofapproved":"1", "id":"3141"}, +{"last_update":"1182952133", "numofapproved":"1", "id":"3641"}, +{"last_update":"1188811518", "numofapproved":"1", "id":"8101"}, +{"last_update":"1188975549", "numofapproved":"1", "id":"8321"}, +{"last_update":"1190122760", "numofapproved":"1", "id":"9301"}, +{"last_update":"1190124712", "numofapproved":"1", "id":"9321"}, +{"last_update":"1194526560", "numofapproved":"1", "id":"15281"}, +{"last_update":"1195149112", "numofapproved":"1", "id":"16821"}, +{"last_update":"1179823256", "numofapproved":"1", "id":"1602"}, +{"last_update":"1186332011", "numofapproved":"1", "id":"6165"}, +{"last_update":"1187263451", "numofapproved":"1", "id":"6781"}, +{"last_update":"1190312346", "numofapproved":"1", "id":"9621"}, +{"last_update":"1193178728", "numofapproved":"1", "id":"13525"}, +{"last_update":"1193908534", "numofapproved":"1", "id":"14524"}, +{"last_update":"1194279992", "numofapproved":"1", "id":"15001"}, +{"last_update":"1194947169", "numofapproved":"1", "id":"16104"}, +{"last_update":"1195139978", "numofapproved":"1", "id":"16801"}, +{"last_update":"1195152323", "numofapproved":"1", "id":"16841"}, +{"last_update":"1188086146", "numofapproved":"1", "id":"7428"}, +{"last_update":"1192143475", "numofapproved":"1", "id":"12341"}, +{"last_update":"1192529949", "numofapproved":"1", "id":"12664"}, +{"last_update":"1192721072", "numofapproved":"1", "id":"13041"}, +{"last_update":"1193844156", "numofapproved":"1", "id":"14501"}, +{"last_update":"1177597683", "numofapproved":"1", "id":"1063"}, +{"last_update":"1180975406", "numofapproved":"1", "id":"2184"}, +{"last_update":"1184681435", "numofapproved":"1", "id":"4914"}, +{"last_update":"1187596457", "numofapproved":"1", "id":"6922"}, +{"last_update":"1190661113", "numofapproved":"1", "id":"10003"}, +{"last_update":"1192721357", "numofapproved":"1", "id":"13042"}, +{"last_update":"1193130120", "numofapproved":"1", "id":"13461"}, +{"last_update":"1193388868", "numofapproved":"1", "id":"13953"}, +{"last_update":"1194861534", "numofapproved":"1", "id":"15821"}, +{"last_update":"1182357592", "numofapproved":"1", "id":"3345"}, +{"last_update":"1183722862", "numofapproved":"1", "id":"4262"}, +{"last_update":"1186066354", "numofapproved":"1", "id":"6041"}, +{"last_update":"1192698982", "numofapproved":"1", "id":"12981"}, +{"last_update":"1181237191", "numofapproved":"1", "id":"2561"}, +{"last_update":"1184569090", "numofapproved":"1", "id":"4906"}, +{"last_update":"1185397555", "numofapproved":"1", "id":"5501"}, +{"last_update":"1185541935", "numofapproved":"1", "id":"5681"}, +{"last_update":"1193385832", "numofapproved":"1", "id":"13941"}, +{"last_update":"1185482424", "numofapproved":"1", "id":"5581"}, +{"last_update":"1195508796", "numofapproved":"1", "id":"17401"}, +{"last_update":"1178718386", "numofapproved":"1", "id":"1347"}, +{"last_update":"1178788813", "numofapproved":"1", "id":"1351"}, +{"last_update":"1178877332", "numofapproved":"1", "id":"1358"}, +{"last_update":"1183208679", "numofapproved":"1", "id":"3861"}, +{"last_update":"1187885439", "numofapproved":"1", "id":"7347"}, +{"last_update":"1188985190", "numofapproved":"1", "id":"8341"}, +{"last_update":"1189687132", "numofapproved":"1", "id":"8941"}, +{"last_update":"1189864330", "numofapproved":"1", "id":"9121"}, +{"last_update":"1190990605", "numofapproved":"1", "id":"10709"}, +{"last_update":"1192634449", "numofapproved":"1", "id":"12861"}, +{"last_update":"1194723756", "numofapproved":"1", "id":"15641"}, +{"last_update":"1194792428", "numofapproved":"1", "id":"15682"}, +{"last_update":"1194725734", "numofapproved":"1", "id":"15661"}, +{"last_update":"1194945618", "numofapproved":"1", "id":"16061"}, +{"last_update":"1194946006", "numofapproved":"1", "id":"16081"}, +{"last_update":"1194949774", "numofapproved":"1", "id":"16121"}, +{"last_update":"1194950925", "numofapproved":"1", "id":"16126"}, +{"last_update":"1194979238", "numofapproved":"1", "id":"16282"}, +{"last_update":"1195051013", "numofapproved":"1", "id":"16543"}, +{"last_update":"1195050956", "numofapproved":"1", "id":"16542"}, +{"last_update":"1195047036", "numofapproved":"1", "id":"16501"}, +{"last_update":"1195221919", "numofapproved":"1", "id":"16942"}, +{"last_update":"1178035892", "numofapproved":"1", "id":"1221"}, +{"last_update":"1178570265", "numofapproved":"1", "id":"1302"}, +{"last_update":"1178811921", "numofapproved":"1", "id":"1354"}, +{"last_update":"1182344326", "numofapproved":"1", "id":"3321"}, +{"last_update":"1184999048", "numofapproved":"1", "id":"5141"}, +{"last_update":"1188994511", "numofapproved":"1", "id":"8361"}, +{"last_update":"1189161726", "numofapproved":"1", "id":"8601"}, +{"last_update":"1190500875", "numofapproved":"1", "id":"9803"}, +{"last_update":"1190817424", "numofapproved":"1", "id":"10321"}, +{"last_update":"1191327796", "numofapproved":"1", "id":"11001"}, +{"last_update":"1191410544", "numofapproved":"1", "id":"11062"}, +{"last_update":"1192009739", "numofapproved":"1", "id":"12062"}, +{"last_update":"1193973669", "numofapproved":"1", "id":"14662"}, +{"last_update":"1194035149", "numofapproved":"1", "id":"14783"}, +{"last_update":"1194465519", "numofapproved":"1", "id":"15106"}, +{"last_update":"1194464336", "numofapproved":"1", "id":"15222"}, +{"last_update":"1194861398", "numofapproved":"1", "id":"15802"}, +{"last_update":"1194950791", "numofapproved":"1", "id":"16125"}, +{"last_update":"1195501394", "numofapproved":"1", "id":"17381"}, +{"last_update":"1195546583", "numofapproved":"1", "id":"17461"}, +{"last_update":"1177607652", "numofapproved":"1", "id":"1048"}, +{"last_update":"1182349136", "numofapproved":"1", "id":"3322"}, +{"last_update":"1184217665", "numofapproved":"1", "id":"4681"}, +{"last_update":"1185510733", "numofapproved":"1", "id":"5641"}, +{"last_update":"1187875988", "numofapproved":"1", "id":"7345"}, +{"last_update":"1188384227", "numofapproved":"1", "id":"7701"}, +{"last_update":"1188935650", "numofapproved":"1", "id":"8261"}, +{"last_update":"1188951982", "numofapproved":"1", "id":"8301"}, +{"last_update":"1190391010", "numofapproved":"1", "id":"9701"}, +{"last_update":"1191169581", "numofapproved":"1", "id":"10841"}, +{"last_update":"1194435269", "numofapproved":"1", "id":"15101"}, +{"last_update":"1171800457", "numofapproved":"1", "id":"86"}, +{"last_update":"1171968036", "numofapproved":"1", "id":"116"}, +{"last_update":"1171984640", "numofapproved":"1", "id":"129"}, +{"last_update":"1171987101", "numofapproved":"1", "id":"130"}, +{"last_update":"1172588327", "numofapproved":"1", "id":"213"}, +{"last_update":"1173736730", "numofapproved":"1", "id":"306"}, +{"last_update":"1174735009", "numofapproved":"1", "id":"463"}, +{"last_update":"1172314484", "numofapproved":"1", "id":"192"}, +{"last_update":"1172580739", "numofapproved":"1", "id":"212"}, +{"last_update":"1173889335", "numofapproved":"1", "id":"328"}, +{"last_update":"1171799339", "numofapproved":"1", "id":"79"}, +{"last_update":"1171882669", "numofapproved":"1", "id":"91"}, +{"last_update":"1172561300", "numofapproved":"1", "id":"207"}, +{"last_update":"1172565919", "numofapproved":"1", "id":"209"}, +{"last_update":"1172600401", "numofapproved":"1", "id":"217"}, +{"last_update":"1174040553", "numofapproved":"1", "id":"350"}, +{"last_update":"1174300376", "numofapproved":"1", "id":"365"}, +{"last_update":"1171800419", "numofapproved":"1", "id":"84"}, +{"last_update":"1171800471", "numofapproved":"1", "id":"87"}, +{"last_update":"1171904826", "numofapproved":"1", "id":"102"}, +{"last_update":"1171962248", "numofapproved":"1", "id":"110"}, +{"last_update":"1171968056", "numofapproved":"1", "id":"117"}, +{"last_update":"1172180757", "numofapproved":"1", "id":"174"}, +{"last_update":"1172249286", "numofapproved":"1", "id":"186"}, +{"last_update":"1172331355", "numofapproved":"1", "id":"194"}, +{"last_update":"1172838799", "numofapproved":"1", "id":"235"}, +{"last_update":"1173839361", "numofapproved":"1", "id":"316"}, +{"last_update":"1176141087", "numofapproved":"1", "id":"809"}, +{"last_update":"1176293168", "numofapproved":"1", "id":"827"}, +{"last_update":"1176314927", "numofapproved":"1", "id":"887"}, +{"last_update":"1172147490", "numofapproved":"1", "id":"169"}, +{"last_update":"1172673371", "numofapproved":"1", "id":"225"}, +{"last_update":"1175021309", "numofapproved":"1", "id":"539"}, +{"last_update":"1175719394", "numofapproved":"1", "id":"708"}, +{"last_update":"1175797177", "numofapproved":"1", "id":"741"}, +{"last_update":"1175797204", "numofapproved":"1", "id":"761"}, +{"last_update":"1173888948", "numofapproved":"1", "id":"323"}, +{"last_update":"1171050355", "numofapproved":"1", "id":"1"}, +{"last_update":"1171904868", "numofapproved":"1", "id":"104"}, +{"last_update":"1174301476", "numofapproved":"1", "id":"392"}, +{"last_update":"1174396679", "numofapproved":"1", "id":"401"}, +{"last_update":"1174735025", "numofapproved":"1", "id":"464"}, +{"last_update":"1171894147", "numofapproved":"1", "id":"94"}, +{"last_update":"1172226240", "numofapproved":"1", "id":"181"}, +{"last_update":"1172442130", "numofapproved":"1", "id":"195"}, +{"last_update":"1174300588", "numofapproved":"1", "id":"370"}, +{"last_update":"1174899082", "numofapproved":"1", "id":"490"}, +{"last_update":"1174899309", "numofapproved":"1", "id":"501"}, +{"last_update":"1173724444", "numofapproved":"1", "id":"304"}, +{"last_update":"1176314883", "numofapproved":"1", "id":"886"}, +{"last_update":"1173284377", "numofapproved":"1", "id":"259"}, +{"last_update":"1172244974", "numofapproved":"1", "id":"184"}, +{"last_update":"1173825356", "numofapproved":"1", "id":"315"}, +{"last_update":"1174898980", "numofapproved":"1", "id":"485"}, +{"last_update":"1175713133", "numofapproved":"1", "id":"706"}, +{"last_update":"1175872869", "numofapproved":"1", "id":"784"}, +{"last_update":"1174301161", "numofapproved":"1", "id":"380"}, +{"last_update":"1176710519", "numofapproved":"1", "id":"1002"}, +{"last_update":"1176776871", "numofapproved":"1", "id":"1006"}, +{"last_update":"1176383102", "numofapproved":"1", "id":"901"}, +{"last_update":"1176391153", "numofapproved":"1", "id":"902"}, +{"last_update":"1176562039", "numofapproved":"1", "id":"946"}, +{"last_update":"1175713172", "numofapproved":"1", "id":"668"}, +{"last_update":"1178045208", "numofapproved":"1", "id":"1204"}, +{"last_update":"1178648231", "numofapproved":"1", "id":"1307"}, +{"last_update":"1178876638", "numofapproved":"1", "id":"1362"}, +{"last_update":"1181120419", "numofapproved":"1", "id":"2341"}, +{"last_update":"1181217997", "numofapproved":"1", "id":"2462"}, +{"last_update":"1181292688", "numofapproved":"1", "id":"2622"}, +{"last_update":"1182246090", "numofapproved":"1", "id":"3205"}, +{"last_update":"1182982710", "numofapproved":"1", "id":"3681"}, +{"last_update":"1177496084", "numofapproved":"1", "id":"1021"}, +{"last_update":"1177496190", "numofapproved":"1", "id":"1022"}, +{"last_update":"1178310654", "numofapproved":"1", "id":"1261"}, +{"last_update":"1182861963", "numofapproved":"1", "id":"3582"}, +{"last_update":"1183392466", "numofapproved":"1", "id":"3981"}, +{"last_update":"1183971409", "numofapproved":"1", "id":"4404"}, +{"last_update":"1183984082", "numofapproved":"1", "id":"4421"}, +{"last_update":"1184101764", "numofapproved":"1", "id":"4581"}, +{"last_update":"1185805036", "numofapproved":"1", "id":"5821"}, +{"last_update":"1186071563", "numofapproved":"1", "id":"6061"}, +{"last_update":"1186331614", "numofapproved":"1", "id":"6221"}, +{"last_update":"1187103429", "numofapproved":"1", "id":"6623"}, +{"last_update":"1187359405", "numofapproved":"1", "id":"6901"}, +{"last_update":"1187764462", "numofapproved":"1", "id":"7121"}, +{"last_update":"1187765742", "numofapproved":"1", "id":"7181"}, +{"last_update":"1187821663", "numofapproved":"1", "id":"7281"}, +{"last_update":"1187851593", "numofapproved":"1", "id":"7301"}, +{"last_update":"1188829369", "numofapproved":"1", "id":"8141"}, +{"last_update":"1189006834", "numofapproved":"1", "id":"8401"}, +{"last_update":"1189656411", "numofapproved":"1", "id":"8901"}, +{"last_update":"1181824325", "numofapproved":"1", "id":"2961"}, +{"last_update":"1184699326", "numofapproved":"1", "id":"4922"}, +{"last_update":"1185981618", "numofapproved":"1", "id":"5981"}, +{"last_update":"1186476979", "numofapproved":"1", "id":"6169"}, +{"last_update":"1186501212", "numofapproved":"1", "id":"6301"}, +{"last_update":"1187111728", "numofapproved":"1", "id":"6624"}, +{"last_update":"1187275194", "numofapproved":"1", "id":"6821"}, +{"last_update":"1190232587", "numofapproved":"1", "id":"9501"}, +{"last_update":"1190379779", "numofapproved":"1", "id":"9661"}, +{"last_update":"1190500551", "numofapproved":"1", "id":"9801"}, +{"last_update":"1190555711", "numofapproved":"1", "id":"9861"}, +{"last_update":"1190664200", "numofapproved":"1", "id":"10061"}, +{"last_update":"1190662067", "numofapproved":"1", "id":"10021"}, +{"last_update":"1190887692", "numofapproved":"1", "id":"10461"}, +{"last_update":"1190887880", "numofapproved":"1", "id":"10462"}, +{"last_update":"1190924576", "numofapproved":"1", "id":"10581"}, +{"last_update":"1190990748", "numofapproved":"1", "id":"10713"}, +{"last_update":"1190990297", "numofapproved":"1", "id":"10703"}, +{"last_update":"1182792178", "numofapproved":"1", "id":"3541"}, +{"last_update":"1189505682", "numofapproved":"1", "id":"8781"}, +{"last_update":"1191410630", "numofapproved":"1", "id":"11081"}, +{"last_update":"1191431148", "numofapproved":"1", "id":"11141"}, +{"last_update":"1191446393", "numofapproved":"1", "id":"11181"}, +{"last_update":"1191559326", "numofapproved":"1", "id":"11481"}, +{"last_update":"1191860159", "numofapproved":"1", "id":"11861"}, +{"last_update":"1191933842", "numofapproved":"1", "id":"11901"}, +{"last_update":"1181765760", "numofapproved":"1", "id":"2901"}, +{"last_update":"1187098770", "numofapproved":"1", "id":"6622"}, +{"last_update":"1192155125", "numofapproved":"1", "id":"12382"}, +{"last_update":"1192449036", "numofapproved":"1", "id":"12601"}, +{"last_update":"1192604489", "numofapproved":"1", "id":"12781"}, +{"last_update":"1193265229", "numofapproved":"1", "id":"13681"}, +{"last_update":"1193304550", "numofapproved":"1", "id":"13781"}, +{"last_update":"1193401945", "numofapproved":"1", "id":"14101"}, +{"last_update":"1193305327", "numofapproved":"1", "id":"13801"}, +{"last_update":"1179912412", "numofapproved":"1", "id":"1722"}, +{"last_update":"1188295203", "numofapproved":"1", "id":"7621"}, +{"last_update":"1188580008", "numofapproved":"1", "id":"7881"}, +{"last_update":"1189115708", "numofapproved":"1", "id":"8521"}, +{"last_update":"1193864375", "numofapproved":"1", "id":"14522"}, +{"last_update":"1193973963", "numofapproved":"1", "id":"14666"}, +{"last_update":"1194003054", "numofapproved":"1", "id":"14701"}, +{"last_update":"1194262755", "numofapproved":"1", "id":"14885"}, +{"last_update":"1194262860", "numofapproved":"1", "id":"14886"}, +{"last_update":"1194366475", "numofapproved":"1", "id":"15042"}, +{"last_update":"1194505568", "numofapproved":"1", "id":"15108"}, +{"last_update":"1194507434", "numofapproved":"1", "id":"15109"}, +{"last_update":"1194625505", "numofapproved":"1", "id":"15542"}, +{"last_update":"1194635569", "numofapproved":"1", "id":"15583"}, +{"last_update":"1179319405", "numofapproved":"1", "id":"1394"}, +{"last_update":"1179409867", "numofapproved":"1", "id":"1441"}, +{"last_update":"1179431647", "numofapproved":"1", "id":"1481"}, +{"last_update":"1179842302", "numofapproved":"1", "id":"1667"}, +{"last_update":"1180710254", "numofapproved":"1", "id":"2081"}, +{"last_update":"1181855583", "numofapproved":"1", "id":"3041"}, +{"last_update":"1182100211", "numofapproved":"1", "id":"3182"}, +{"last_update":"1183377220", "numofapproved":"1", "id":"3921"}, +{"last_update":"1184677615", "numofapproved":"1", "id":"4910"}, +{"last_update":"1184679060", "numofapproved":"1", "id":"4911"}, +{"last_update":"1184679348", "numofapproved":"1", "id":"4912"}, +{"last_update":"1184749371", "numofapproved":"1", "id":"4943"}, +{"last_update":"1186734180", "numofapproved":"1", "id":"6381"}, +{"last_update":"1187012463", "numofapproved":"1", "id":"6501"}, +{"last_update":"1187209404", "numofapproved":"1", "id":"6741"}, +{"last_update":"1192687257", "numofapproved":"1", "id":"12941"}, +{"last_update":"1193385868", "numofapproved":"1", "id":"13942"}, +{"last_update":"1193386346", "numofapproved":"1", "id":"13943"}, +{"last_update":"1194937571", "numofapproved":"1", "id":"16042"}, +{"last_update":"1194855975", "numofapproved":"1", "id":"15761"}, +{"last_update":"1194960221", "numofapproved":"1", "id":"16161"}, +{"last_update":"1184058679", "numofapproved":"1", "id":"4541"}, +{"last_update":"1185865315", "numofapproved":"1", "id":"5842"}, +{"last_update":"1187178780", "numofapproved":"1", "id":"6681"}, +{"last_update":"1194884625", "numofapproved":"1", "id":"15921"}, +{"last_update":"1195134032", "numofapproved":"1", "id":"16721"}, +{"last_update":"1195164570", "numofapproved":"1", "id":"16901"}, +{"last_update":"1182336429", "numofapproved":"1", "id":"3301"}, +{"last_update":"1182415670", "numofapproved":"1", "id":"3353"}, +{"last_update":"1184575801", "numofapproved":"1", "id":"4907"}, +{"last_update":"1185483718", "numofapproved":"1", "id":"5601"}, +{"last_update":"1186402874", "numofapproved":"1", "id":"6166"}, +{"last_update":"1186750969", "numofapproved":"1", "id":"6383"}, +{"last_update":"1192725360", "numofapproved":"1", "id":"13061"}, +{"last_update":"1193314911", "numofapproved":"1", "id":"13822"}, +{"last_update":"1183448275", "numofapproved":"1", "id":"4062"}, +{"last_update":"1187321039", "numofapproved":"1", "id":"6861"}, +{"last_update":"1188287578", "numofapproved":"1", "id":"7601"}, +{"last_update":"1194464420", "numofapproved":"1", "id":"15224"}, +{"last_update":"1195139641", "numofapproved":"1", "id":"16781"}, +{"last_update":"1186147124", "numofapproved":"1", "id":"6107"}, +{"last_update":"1188821750", "numofapproved":"1", "id":"8122"}, +{"last_update":"1192531864", "numofapproved":"1", "id":"12665"}, +{"last_update":"1192984220", "numofapproved":"1", "id":"13223"}, +{"last_update":"1195225246", "numofapproved":"1", "id":"16982"}, +{"last_update":"1182410787", "numofapproved":"1", "id":"3351"}, +{"last_update":"1184531419", "numofapproved":"1", "id":"4901"}, +{"last_update":"1188801472", "numofapproved":"1", "id":"8081"}, +{"last_update":"1192524288", "numofapproved":"1", "id":"12661"}, +{"last_update":"1180950691", "numofapproved":"1", "id":"2181"}, +{"last_update":"1184016732", "numofapproved":"1", "id":"4501"}, +{"last_update":"1186074085", "numofapproved":"1", "id":"6081"}, +{"last_update":"1194937650", "numofapproved":"1", "id":"16043"}, +{"last_update":"1182937178", "numofapproved":"1", "id":"3623"}, +{"last_update":"1191419601", "numofapproved":"1", "id":"11101"}, +{"last_update":"1191856562", "numofapproved":"1", "id":"11843"}, +{"last_update":"1192525042", "numofapproved":"1", "id":"12681"}, +{"last_update":"1194625494", "numofapproved":"1", "id":"15541"}, +{"last_update":"1194982850", "numofapproved":"1", "id":"16361"}, +{"last_update":"1194989219", "numofapproved":"1", "id":"16401"}, +{"last_update":"1195066723", "numofapproved":"1", "id":"16641"}, +{"last_update":"1183971226", "numofapproved":"1", "id":"4403"}, +{"last_update":"1185526866", "numofapproved":"1", "id":"5661"}, +{"last_update":"1185741495", "numofapproved":"1", "id":"5741"}, +{"last_update":"1185905429", "numofapproved":"1", "id":"5881"}, +{"last_update":"1186137969", "numofapproved":"1", "id":"6104"}, +{"last_update":"1189267536", "numofapproved":"1", "id":"8701"}, +{"last_update":"1190115042", "numofapproved":"1", "id":"9261"}, +{"last_update":"1190664258", "numofapproved":"1", "id":"10062"}, +{"last_update":"1190774949", "numofapproved":"1", "id":"10201"}, +{"last_update":"1190965042", "numofapproved":"1", "id":"10641"}, +{"last_update":"1191493379", "numofapproved":"1", "id":"11301"}, +{"last_update":"1191578051", "numofapproved":"1", "id":"11501"}, +{"last_update":"1192188840", "numofapproved":"1", "id":"12421"}, +{"last_update":"1194000252", "numofapproved":"1", "id":"14682"}, +{"last_update":"1194622556", "numofapproved":"1", "id":"15462"}, +{"last_update":"1194981068", "numofapproved":"1", "id":"16341"}, +{"last_update":"1185795733", "numofapproved":"1", "id":"5782"}, +{"last_update":"1186646854", "numofapproved":"1", "id":"6341"}, +{"last_update":"1187087291", "numofapproved":"1", "id":"6621"}, +{"last_update":"1187951800", "numofapproved":"1", "id":"7401"}, +{"last_update":"1189170373", "numofapproved":"1", "id":"8642"}, +{"last_update":"1191007934", "numofapproved":"1", "id":"10781"}, +{"last_update":"1190985695", "numofapproved":"1", "id":"10681"}, +{"last_update":"1192009758", "numofapproved":"1", "id":"12063"}, +{"last_update":"1193062543", "numofapproved":"1", "id":"13321"}, +{"last_update":"1194950304", "numofapproved":"1", "id":"16123"}, +{"last_update":"1171882085", "numofapproved":"1", "id":"90"}, +{"last_update":"1171962264", "numofapproved":"1", "id":"111"}, +{"last_update":"1172646556", "numofapproved":"1", "id":"219"}, +{"last_update":"1174040139", "numofapproved":"1", "id":"349"}, +{"last_update":"1174059263", "numofapproved":"1", "id":"355"}, +{"last_update":"1174899063", "numofapproved":"1", "id":"489"}, +{"last_update":"1173797557", "numofapproved":"1", "id":"310"}, +{"last_update":"1174735191", "numofapproved":"1", "id":"468"}, +{"last_update":"1174899259", "numofapproved":"1", "id":"499"}, +{"last_update":"1174899354", "numofapproved":"1", "id":"502"}, +{"last_update":"1175254120", "numofapproved":"1", "id":"562"}, +{"last_update":"1171126391", "numofapproved":"1", "id":"4"}, +{"last_update":"1171800381", "numofapproved":"1", "id":"82"}, +{"last_update":"1171799224", "numofapproved":"1", "id":"75"}, +{"last_update":"1171972550", "numofapproved":"1", "id":"123"}, +{"last_update":"1174301165", "numofapproved":"1", "id":"381"}, +{"last_update":"1171904847", "numofapproved":"1", "id":"103"}, +{"last_update":"1172260956", "numofapproved":"1", "id":"190"}, +{"last_update":"1172803368", "numofapproved":"1", "id":"234"}, +{"last_update":"1173199576", "numofapproved":"1", "id":"250"}, +{"last_update":"1173206201", "numofapproved":"1", "id":"252"}, +{"last_update":"1175258941", "numofapproved":"1", "id":"563"}, +{"last_update":"1176232231", "numofapproved":"1", "id":"825"}, +{"last_update":"1176475088", "numofapproved":"1", "id":"921"}, +{"last_update":"1172082181", "numofapproved":"1", "id":"166"}, +{"last_update":"1172595205", "numofapproved":"1", "id":"216"}, +{"last_update":"1174898892", "numofapproved":"1", "id":"481"}, +{"last_update":"1174899696", "numofapproved":"1", "id":"518"}, +{"last_update":"1174924777", "numofapproved":"1", "id":"525"}, +{"last_update":"1175598588", "numofapproved":"1", "id":"682"}, +{"last_update":"1175602572", "numofapproved":"1", "id":"683"}, +{"last_update":"1175707879", "numofapproved":"1", "id":"666"}, +{"last_update":"1175710528", "numofapproved":"1", "id":"703"}, +{"last_update":"1175715728", "numofapproved":"1", "id":"707"}, +{"last_update":"1176137267", "numofapproved":"1", "id":"806"}, +{"last_update":"1176306491", "numofapproved":"1", "id":"883"}, +{"last_update":"1172069972", "numofapproved":"1", "id":"134"}, +{"last_update":"1173889144", "numofapproved":"1", "id":"324"}, +{"last_update":"1175502804", "numofapproved":"1", "id":"623"}, +{"last_update":"1175772530", "numofapproved":"1", "id":"711"}, +{"last_update":"1176297526", "numofapproved":"1", "id":"861"}, +{"last_update":"1171445818", "numofapproved":"1", "id":"47"}, +{"last_update":"1171884505", "numofapproved":"1", "id":"92"}, +{"last_update":"1172250708", "numofapproved":"1", "id":"187"}, +{"last_update":"1173749631", "numofapproved":"1", "id":"307"}, +{"last_update":"1173889164", "numofapproved":"1", "id":"325"}, +{"last_update":"1174301168", "numofapproved":"1", "id":"382"}, +{"last_update":"1171904807", "numofapproved":"1", "id":"101"}, +{"last_update":"1171970405", "numofapproved":"1", "id":"120"}, +{"last_update":"1172218677", "numofapproved":"1", "id":"179"}, +{"last_update":"1173125028", "numofapproved":"1", "id":"248"}, +{"last_update":"1171978122", "numofapproved":"1", "id":"126"}, +{"last_update":"1172676736", "numofapproved":"1", "id":"226"}, +{"last_update":"1173975473", "numofapproved":"1", "id":"344"}, +{"last_update":"1172072582", "numofapproved":"1", "id":"165"}, +{"last_update":"1173888774", "numofapproved":"1", "id":"322"}, +{"last_update":"1174560347", "numofapproved":"1", "id":"422"}, +{"last_update":"1174899242", "numofapproved":"1", "id":"498"}, +{"last_update":"1174735110", "numofapproved":"1", "id":"466"}, +{"last_update":"1176735630", "numofapproved":"1", "id":"1004"}, +{"last_update":"1175725931", "numofapproved":"1", "id":"670"}, +{"last_update":"1176498072", "numofapproved":"1", "id":"944"}, +{"last_update":"1178264233", "numofapproved":"1", "id":"1241"}, +{"last_update":"1178746727", "numofapproved":"1", "id":"1350"}, +{"last_update":"1178798992", "numofapproved":"1", "id":"1352"}, +{"last_update":"1180011647", "numofapproved":"1", "id":"1649"}, +{"last_update":"1180430823", "numofapproved":"1", "id":"1901"}, +{"last_update":"1180649952", "numofapproved":"1", "id":"2021"}, +{"last_update":"1180966506", "numofapproved":"1", "id":"2183"}, +{"last_update":"1180987142", "numofapproved":"1", "id":"2241"}, +{"last_update":"1181127788", "numofapproved":"1", "id":"2322"}, +{"last_update":"1181217668", "numofapproved":"1", "id":"2461"}, +{"last_update":"1182789542", "numofapproved":"1", "id":"3522"}, +{"last_update":"1182851714", "numofapproved":"1", "id":"3581"}, +{"last_update":"1179268837", "numofapproved":"1", "id":"1407"}, +{"last_update":"1179999486", "numofapproved":"1", "id":"1645"}, +{"last_update":"1180019568", "numofapproved":"1", "id":"1653"}, +{"last_update":"1180082061", "numofapproved":"1", "id":"1821"}, +{"last_update":"1184181871", "numofapproved":"1", "id":"4642"}, +{"last_update":"1184251955", "numofapproved":"1", "id":"4741"}, +{"last_update":"1184346893", "numofapproved":"1", "id":"4841"}, +{"last_update":"1184773981", "numofapproved":"1", "id":"5001"}, +{"last_update":"1185272905", "numofapproved":"1", "id":"5281"}, +{"last_update":"1185484083", "numofapproved":"1", "id":"5622"}, +{"last_update":"1185897961", "numofapproved":"1", "id":"5861"}, +{"last_update":"1186951708", "numofapproved":"1", "id":"6462"}, +{"last_update":"1187596311", "numofapproved":"1", "id":"6941"}, +{"last_update":"1187766852", "numofapproved":"1", "id":"7201"}, +{"last_update":"1188158133", "numofapproved":"1", "id":"7481"}, +{"last_update":"1188233835", "numofapproved":"1", "id":"7501"}, +{"last_update":"1188269273", "numofapproved":"1", "id":"7561"}, +{"last_update":"1177672684", "numofapproved":"1", "id":"1141"}, +{"last_update":"1178042016", "numofapproved":"1", "id":"1222"}, +{"last_update":"1181646022", "numofapproved":"1", "id":"2801"}, +{"last_update":"1181853920", "numofapproved":"1", "id":"3021"}, +{"last_update":"1183715836", "numofapproved":"1", "id":"4241"}, +{"last_update":"1183726859", "numofapproved":"1", "id":"4281"}, +{"last_update":"1189860355", "numofapproved":"1", "id":"9101"}, +{"last_update":"1189871747", "numofapproved":"1", "id":"9141"}, +{"last_update":"1190380660", "numofapproved":"1", "id":"9681"}, +{"last_update":"1190510808", "numofapproved":"1", "id":"9821"}, +{"last_update":"1190542013", "numofapproved":"1", "id":"9843"}, +{"last_update":"1190665412", "numofapproved":"1", "id":"10081"}, +{"last_update":"1190299519", "numofapproved":"1", "id":"9601"}, +{"last_update":"1191410594", "numofapproved":"1", "id":"11063"}, +{"last_update":"1191505786", "numofapproved":"1", "id":"11341"}, +{"last_update":"1191583652", "numofapproved":"1", "id":"11522"}, +{"last_update":"1191599712", "numofapproved":"1", "id":"11681"}, +{"last_update":"1191602931", "numofapproved":"1", "id":"11721"}, +{"last_update":"1191762572", "numofapproved":"1", "id":"11761"}, +{"last_update":"1191856256", "numofapproved":"1", "id":"11841"}, +{"last_update":"1191937041", "numofapproved":"1", "id":"11921"}, +{"last_update":"1179325639", "numofapproved":"1", "id":"1409"}, +{"last_update":"1179912165", "numofapproved":"1", "id":"1721"}, +{"last_update":"1181119430", "numofapproved":"1", "id":"2321"}, +{"last_update":"1184696743", "numofapproved":"1", "id":"4921"}, +{"last_update":"1192154847", "numofapproved":"1", "id":"12361"}, +{"last_update":"1192237071", "numofapproved":"1", "id":"12501"}, +{"last_update":"1178637394", "numofapproved":"1", "id":"1304"}, +{"last_update":"1178716778", "numofapproved":"1", "id":"1344"}, +{"last_update":"1182937057", "numofapproved":"1", "id":"3622"}, +{"last_update":"1183113642", "numofapproved":"1", "id":"3781"}, +{"last_update":"1183995467", "numofapproved":"1", "id":"4461"}, +{"last_update":"1184223331", "numofapproved":"1", "id":"4721"}, +{"last_update":"1190990692", "numofapproved":"1", "id":"10711"}, +{"last_update":"1193269310", "numofapproved":"1", "id":"13761"}, +{"last_update":"1193735756", "numofapproved":"1", "id":"14441"}, +{"last_update":"1194635738", "numofapproved":"1", "id":"15603"}, +{"last_update":"1194901721", "numofapproved":"1", "id":"15961"}, +{"last_update":"1194949951", "numofapproved":"1", "id":"16141"}, +{"last_update":"1194960695", "numofapproved":"1", "id":"16182"}, +{"last_update":"1194973974", "numofapproved":"1", "id":"16221"}, +{"last_update":"1194946810", "numofapproved":"1", "id":"16102"}, +{"last_update":"1194977452", "numofapproved":"1", "id":"16261"}, +{"last_update":"1195040385", "numofapproved":"1", "id":"16461"}, +{"last_update":"1195053483", "numofapproved":"1", "id":"16561"}, +{"last_update":"1195053518", "numofapproved":"1", "id":"16562"}, +{"last_update":"1195218698", "numofapproved":"1", "id":"16921"}, +{"last_update":"1195225049", "numofapproved":"1", "id":"16961"}, +{"last_update":"1195164270", "numofapproved":"1", "id":"16881"}, +{"last_update":"1195080947", "numofapproved":"1", "id":"16681"}, +{"last_update":"1195469884", "numofapproved":"1", "id":"17181"}, +{"last_update":"1185314804", "numofapproved":"1", "id":"5381"}, +{"last_update":"1188401767", "numofapproved":"1", "id":"7721"}, +{"last_update":"1190286841", "numofapproved":"1", "id":"9582"}, +{"last_update":"1190733096", "numofapproved":"1", "id":"10141"}, +{"last_update":"1190847451", "numofapproved":"1", "id":"10422"}, +{"last_update":"1190990526", "numofapproved":"1", "id":"10707"}, +{"last_update":"1192009711", "numofapproved":"1", "id":"12061"}, +{"last_update":"1192155478", "numofapproved":"1", "id":"12362"}, +{"last_update":"1192468382", "numofapproved":"1", "id":"12641"}, +{"last_update":"1193332032", "numofapproved":"1", "id":"13881"}, +{"last_update":"1195497290", "numofapproved":"1", "id":"17321"}, +{"last_update":"1195519935", "numofapproved":"1", "id":"17441"}, +{"last_update":"1195549826", "numofapproved":"1", "id":"17521"}, +{"last_update":"1177668131", "numofapproved":"1", "id":"1101"}, +{"last_update":"1186835348", "numofapproved":"1", "id":"6421"}, +{"last_update":"1191057903", "numofapproved":"1", "id":"10802"}, +{"last_update":"1193973906", "numofapproved":"1", "id":"14665"}, +{"last_update":"1171904780", "numofapproved":"1", "id":"100"}, +{"last_update":"1172677750", "numofapproved":"1", "id":"227"}, +{"last_update":"1172686704", "numofapproved":"1", "id":"229"}, +{"last_update":"1173101684", "numofapproved":"1", "id":"245"}, +{"last_update":"1173466151", "numofapproved":"1", "id":"282"}, +{"last_update":"1174301263", "numofapproved":"1", "id":"386"}, +{"last_update":"1174302366", "numofapproved":"1", "id":"399"}, +{"last_update":"1174501294", "numofapproved":"1", "id":"421"}, +{"last_update":"1174899635", "numofapproved":"1", "id":"515"}, +{"last_update":"1174924556", "numofapproved":"1", "id":"523"}, +{"last_update":"1175141200", "numofapproved":"1", "id":"541"}, +{"last_update":"1171799271", "numofapproved":"1", "id":"76"}, +{"last_update":"1171900163", "numofapproved":"1", "id":"97"}, +{"last_update":"1174301267", "numofapproved":"1", "id":"387"}, +{"last_update":"1174735156", "numofapproved":"1", "id":"467"}, +{"last_update":"1174899569", "numofapproved":"1", "id":"512"}, +{"last_update":"1174926970", "numofapproved":"1", "id":"531"}, +{"last_update":"1175502757", "numofapproved":"1", "id":"602"}, +{"last_update":"1175603425", "numofapproved":"1", "id":"663"}, +{"last_update":"1176194967", "numofapproved":"1", "id":"822"}, +{"last_update":"1171800398", "numofapproved":"1", "id":"83"}, +{"last_update":"1171968376", "numofapproved":"1", "id":"118"}, +{"last_update":"1172070063", "numofapproved":"1", "id":"135"}, +{"last_update":"1173821159", "numofapproved":"1", "id":"314"}, +{"last_update":"1176559052", "numofapproved":"1", "id":"964"}, +{"last_update":"1171299245", "numofapproved":"1", "id":"23"}, +{"last_update":"1171535160", "numofapproved":"1", "id":"57"}, +{"last_update":"1171564542", "numofapproved":"1", "id":"65"}, +{"last_update":"1172646592", "numofapproved":"1", "id":"220"}, +{"last_update":"1174899489", "numofapproved":"1", "id":"507"}, +{"last_update":"1174924890", "numofapproved":"1", "id":"528"}, +{"last_update":"1175687005", "numofapproved":"1", "id":"701"}, +{"last_update":"1176132888", "numofapproved":"1", "id":"805"}, +{"last_update":"1171286610", "numofapproved":"1", "id":"21"}, +{"last_update":"1172184441", "numofapproved":"1", "id":"176"}, +{"last_update":"1172187221", "numofapproved":"1", "id":"178"}, +{"last_update":"1173386668", "numofapproved":"1", "id":"261"}, +{"last_update":"1173809115", "numofapproved":"1", "id":"312"}, +{"last_update":"1175609126", "numofapproved":"1", "id":"685"}, +{"last_update":"1175791369", "numofapproved":"1", "id":"712"}, +{"last_update":"1176480434", "numofapproved":"1", "id":"942"}, +{"last_update":"1171503567", "numofapproved":"1", "id":"56"}, +{"last_update":"1171799204", "numofapproved":"1", "id":"74"}, +{"last_update":"1172236765", "numofapproved":"1", "id":"183"}, +{"last_update":"1175598013", "numofapproved":"1", "id":"681"}, +{"last_update":"1175610956", "numofapproved":"1", "id":"687"}, +{"last_update":"1175725436", "numofapproved":"1", "id":"710"}, +{"last_update":"1171905052", "numofapproved":"1", "id":"105"}, +{"last_update":"1172268920", "numofapproved":"1", "id":"191"}, +{"last_update":"1173264110", "numofapproved":"1", "id":"256"}, +{"last_update":"1173889179", "numofapproved":"1", "id":"326"}, +{"last_update":"1174301066", "numofapproved":"1", "id":"378"}, +{"last_update":"1174300399", "numofapproved":"1", "id":"366"}, +{"last_update":"1174387980", "numofapproved":"1", "id":"400"}, +{"last_update":"1176823766", "numofapproved":"1", "id":"1007"}, +{"last_update":"1171970585", "numofapproved":"1", "id":"122"}, +{"last_update":"1172071500", "numofapproved":"1", "id":"145"}, +{"last_update":"1172580279", "numofapproved":"1", "id":"211"}, +{"last_update":"1172658493", "numofapproved":"1", "id":"221"}, +{"last_update":"1174301611", "numofapproved":"1", "id":"397"}, +{"last_update":"1176900132", "numofapproved":"1", "id":"989"}, +{"last_update":"1171965754", "numofapproved":"1", "id":"114"}, +{"last_update":"1173797482", "numofapproved":"1", "id":"309"}, +{"last_update":"1174300513", "numofapproved":"1", "id":"367"}, +{"last_update":"1174301493", "numofapproved":"1", "id":"395"}, +{"last_update":"1174899124", "numofapproved":"1", "id":"492"}, +{"last_update":"1174899677", "numofapproved":"1", "id":"517"}, +{"last_update":"1174924235", "numofapproved":"1", "id":"522"}, +{"last_update":"1174925568", "numofapproved":"1", "id":"529"}, +{"last_update":"1174933088", "numofapproved":"1", "id":"533"}, +{"last_update":"1174933338", "numofapproved":"1", "id":"538"}, +{"last_update":"1174044629", "numofapproved":"1", "id":"352"}, +{"last_update":"1175713207", "numofapproved":"1", "id":"669"}, +{"last_update":"1178339569", "numofapproved":"1", "id":"1262"}, +{"last_update":"1178611427", "numofapproved":"1", "id":"1303"}, +{"last_update":"1178707269", "numofapproved":"1", "id":"1341"}, +{"last_update":"1179411388", "numofapproved":"1", "id":"1461"}, +{"last_update":"1180000879", "numofapproved":"1", "id":"1648"}, +{"last_update":"1180097993", "numofapproved":"1", "id":"1657"}, +{"last_update":"1180107947", "numofapproved":"1", "id":"1659"}, +{"last_update":"1180515935", "numofapproved":"1", "id":"1922"}, +{"last_update":"1180712418", "numofapproved":"1", "id":"2102"}, +{"last_update":"1180731895", "numofapproved":"1", "id":"2063"}, +{"last_update":"1180731763", "numofapproved":"1", "id":"2143"}, +{"last_update":"1180951519", "numofapproved":"1", "id":"2201"}, +{"last_update":"1180954763", "numofapproved":"1", "id":"2182"}, +{"last_update":"1181134185", "numofapproved":"1", "id":"2361"}, +{"last_update":"1181206368", "numofapproved":"1", "id":"2441"}, +{"last_update":"1181207556", "numofapproved":"1", "id":"2442"}, +{"last_update":"1183065868", "numofapproved":"1", "id":"3741"}, +{"last_update":"1183124436", "numofapproved":"1", "id":"3822"}, +{"last_update":"1183118631", "numofapproved":"1", "id":"3802"}, +{"last_update":"1183515629", "numofapproved":"1", "id":"4144"}, +{"last_update":"1184169495", "numofapproved":"1", "id":"4621"}, +{"last_update":"1184777700", "numofapproved":"1", "id":"5021"}, +{"last_update":"1185371099", "numofapproved":"1", "id":"5441"}, +{"last_update":"1185460060", "numofapproved":"1", "id":"5521"}, +{"last_update":"1185462514", "numofapproved":"1", "id":"5541"}, +{"last_update":"1185573050", "numofapproved":"1", "id":"5721"}, +{"last_update":"1185795586", "numofapproved":"1", "id":"5781"}, +{"last_update":"1185962181", "numofapproved":"1", "id":"5901"}, +{"last_update":"1185987024", "numofapproved":"1", "id":"6001"}, +{"last_update":"1186138150", "numofapproved":"1", "id":"6105"}, +{"last_update":"1186500528", "numofapproved":"1", "id":"6281"}, +{"last_update":"1187765075", "numofapproved":"1", "id":"7141"}, +{"last_update":"1188158263", "numofapproved":"1", "id":"7482"}, +{"last_update":"1189094579", "numofapproved":"1", "id":"8461"}, +{"last_update":"1189327635", "numofapproved":"1", "id":"8721"}, +{"last_update":"1182356521", "numofapproved":"1", "id":"3344"}, +{"last_update":"1185017921", "numofapproved":"1", "id":"5161"}, +{"last_update":"1185271167", "numofapproved":"1", "id":"5261"}, +{"last_update":"1190663796", "numofapproved":"1", "id":"10041"}, +{"last_update":"1190726728", "numofapproved":"1", "id":"10121"}, +{"last_update":"1190801144", "numofapproved":"1", "id":"10241"}, +{"last_update":"1190894441", "numofapproved":"1", "id":"10502"}, +{"last_update":"1190973098", "numofapproved":"1", "id":"10667"}, +{"last_update":"1190925124", "numofapproved":"1", "id":"10584"}, +{"last_update":"1191249884", "numofapproved":"1", "id":"10961"}, +{"last_update":"1187732431", "numofapproved":"1", "id":"7081"}, +{"last_update":"1189259179", "numofapproved":"1", "id":"8681"}, +{"last_update":"1191446517", "numofapproved":"1", "id":"11183"}, +{"last_update":"1191510643", "numofapproved":"1", "id":"11381"}, +{"last_update":"1191529640", "numofapproved":"1", "id":"11421"}, +{"last_update":"1191588726", "numofapproved":"1", "id":"11602"}, +{"last_update":"1191903050", "numofapproved":"1", "id":"11881"}, +{"last_update":"1181218459", "numofapproved":"1", "id":"2464"}, +{"last_update":"1187024536", "numofapproved":"1", "id":"6581"}, +{"last_update":"1192009094", "numofapproved":"1", "id":"12041"}, +{"last_update":"1192064048", "numofapproved":"1", "id":"12183"}, +{"last_update":"1192061973", "numofapproved":"1", "id":"12181"}, +{"last_update":"1193026780", "numofapproved":"1", "id":"13241"}, +{"last_update":"1193416409", "numofapproved":"1", "id":"14161"}, +{"last_update":"1186992495", "numofapproved":"1", "id":"6481"}, +{"last_update":"1191410811", "numofapproved":"1", "id":"11066"}, +{"last_update":"1193440748", "numofapproved":"1", "id":"14241"}, +{"last_update":"1194252005", "numofapproved":"1", "id":"14884"}, +{"last_update":"1194362364", "numofapproved":"1", "id":"14889"}, +{"last_update":"1179240103", "numofapproved":"1", "id":"1389"}, +{"last_update":"1181812262", "numofapproved":"1", "id":"2922"}, +{"last_update":"1182093916", "numofapproved":"1", "id":"3181"}, +{"last_update":"1182767688", "numofapproved":"1", "id":"3501"}, +{"last_update":"1184181747", "numofapproved":"1", "id":"4661"}, +{"last_update":"1186505570", "numofapproved":"1", "id":"6170"}, +{"last_update":"1186751068", "numofapproved":"1", "id":"6384"}, +{"last_update":"1187558925", "numofapproved":"1", "id":"6921"}, +{"last_update":"1188037477", "numofapproved":"1", "id":"7424"}, +{"last_update":"1194937530", "numofapproved":"1", "id":"16041"}, +{"last_update":"1179754250", "numofapproved":"1", "id":"1562"}, +{"last_update":"1183416194", "numofapproved":"1", "id":"4021"}, +{"last_update":"1185835616", "numofapproved":"1", "id":"5841"}, +{"last_update":"1192731190", "numofapproved":"1", "id":"13141"}, +{"last_update":"1193178120", "numofapproved":"1", "id":"13523"}, +{"last_update":"1193844805", "numofapproved":"1", "id":"14503"}, +{"last_update":"1193909242", "numofapproved":"1", "id":"14525"}, +{"last_update":"1195474767", "numofapproved":"1", "id":"17221"}, +{"last_update":"1177690781", "numofapproved":"1", "id":"1142"}, +{"last_update":"1185373614", "numofapproved":"1", "id":"5461"}, +{"last_update":"1192520088", "numofapproved":"1", "id":"12624"}, +{"last_update":"1193194444", "numofapproved":"1", "id":"13527"}, +{"last_update":"1193387684", "numofapproved":"1", "id":"13950"}, +{"last_update":"1193388786", "numofapproved":"1", "id":"13952"}, +{"last_update":"1194616895", "numofapproved":"1", "id":"15401"}, +{"last_update":"1195034817", "numofapproved":"1", "id":"16441"}, +{"last_update":"1183107374", "numofapproved":"1", "id":"3761"}, +{"last_update":"1183515040", "numofapproved":"1", "id":"4121"}, +{"last_update":"1184744160", "numofapproved":"1", "id":"4942"}, +{"last_update":"1192094830", "numofapproved":"1", "id":"12201"}, +{"last_update":"1193314411", "numofapproved":"1", "id":"13821"}, +{"last_update":"1193391901", "numofapproved":"1", "id":"13957"}, +{"last_update":"1193399824", "numofapproved":"1", "id":"14043"}, +{"last_update":"1194450353", "numofapproved":"1", "id":"15181"}, +{"last_update":"1194474719", "numofapproved":"1", "id":"15241"}, +{"last_update":"1194622799", "numofapproved":"1", "id":"15481"}, +{"last_update":"1194880827", "numofapproved":"1", "id":"15901"}, +{"last_update":"1182363929", "numofapproved":"1", "id":"3347"}, +{"last_update":"1182952243", "numofapproved":"1", "id":"3642"}, +{"last_update":"1183386876", "numofapproved":"1", "id":"3962"}, +{"last_update":"1193178314", "numofapproved":"1", "id":"13524"}, +{"last_update":"1195376577", "numofapproved":"1", "id":"17061"}, +{"last_update":"1179832847", "numofapproved":"1", "id":"1621"}, +{"last_update":"1184053269", "numofapproved":"1", "id":"4521"}, +{"last_update":"1185024744", "numofapproved":"1", "id":"5181"}, +{"last_update":"1186130324", "numofapproved":"1", "id":"6101"}, +{"last_update":"1192529640", "numofapproved":"1", "id":"12662"}, +{"last_update":"1193158482", "numofapproved":"1", "id":"13521"}, +{"last_update":"1194247788", "numofapproved":"1", "id":"14883"}, +{"last_update":"1182363717", "numofapproved":"1", "id":"3346"}, +{"last_update":"1193386824", "numofapproved":"1", "id":"13944"}, +{"last_update":"1193844655", "numofapproved":"1", "id":"14502"}, +{"last_update":"1180732326", "numofapproved":"1", "id":"2064"}, +{"last_update":"1182247493", "numofapproved":"1", "id":"3222"}, +{"last_update":"1183515318", "numofapproved":"1", "id":"4143"}, +{"last_update":"1184840285", "numofapproved":"1", "id":"5061"}, +{"last_update":"1188458821", "numofapproved":"1", "id":"7741"}, +{"last_update":"1188919582", "numofapproved":"1", "id":"8241"}, +{"last_update":"1190990231", "numofapproved":"1", "id":"10701"}, +{"last_update":"1190990557", "numofapproved":"1", "id":"10708"}, +{"last_update":"1191583611", "numofapproved":"1", "id":"11521"}, +{"last_update":"1192031263", "numofapproved":"1", "id":"12102"}, +{"last_update":"1192431349", "numofapproved":"1", "id":"12563"}, +{"last_update":"1192608972", "numofapproved":"1", "id":"12801"}, +{"last_update":"1193244196", "numofapproved":"1", "id":"13641"}, +{"last_update":"1193733530", "numofapproved":"1", "id":"14422"}, +{"last_update":"1194988770", "numofapproved":"1", "id":"16381"}, +{"last_update":"1195050890", "numofapproved":"1", "id":"16541"}, +{"last_update":"1195047262", "numofapproved":"1", "id":"16502"}, +{"last_update":"1195221672", "numofapproved":"1", "id":"16941"}, +{"last_update":"1195400016", "numofapproved":"1", "id":"17103"}, +{"last_update":"1178716622", "numofapproved":"1", "id":"1343"}, +{"last_update":"1183563126", "numofapproved":"1", "id":"4181"}, +{"last_update":"1183970953", "numofapproved":"1", "id":"4402"}, +{"last_update":"1190149151", "numofapproved":"1", "id":"9381"}, +{"last_update":"1190628937", "numofapproved":"1", "id":"9921"}, +{"last_update":"1190908511", "numofapproved":"1", "id":"10521"}, +{"last_update":"1191365468", "numofapproved":"1", "id":"11021"}, +{"last_update":"1192431054", "numofapproved":"1", "id":"12561"}, +{"last_update":"1188938163", "numofapproved":"1", "id":"8281"}, +{"last_update":"1192155298", "numofapproved":"1", "id":"12383"}, +{"last_update":"1193223714", "numofapproved":"1", "id":"13561"}, +{"last_update":"1171799359", "numofapproved":"1", "id":"80"}, +{"last_update":"1171962550", "numofapproved":"1", "id":"112"}, +{"last_update":"1171965210", "numofapproved":"1", "id":"113"}, +{"last_update":"1171980888", "numofapproved":"1", "id":"128"}, +{"last_update":"1174299174", "numofapproved":"1", "id":"361"}, +{"last_update":"1174301053", "numofapproved":"1", "id":"376"}, +{"last_update":"1174899661", "numofapproved":"1", "id":"516"}, +{"last_update":"1172646493", "numofapproved":"1", "id":"218"}, +{"last_update":"1174899018", "numofapproved":"1", "id":"487"}, +{"last_update":"1175091201", "numofapproved":"1", "id":"540"}, +{"last_update":"1175267243", "numofapproved":"1", "id":"564"}, +{"last_update":"1176293117", "numofapproved":"1", "id":"826"}, +{"last_update":"1171602873", "numofapproved":"1", "id":"67"}, +{"last_update":"1172568714", "numofapproved":"1", "id":"210"}, +{"last_update":"1174300556", "numofapproved":"1", "id":"369"}, +{"last_update":"1174301614", "numofapproved":"1", "id":"398"}, +{"last_update":"1174429050", "numofapproved":"1", "id":"404"}, +{"last_update":"1175547821", "numofapproved":"1", "id":"641"}, +{"last_update":"1175696551", "numofapproved":"1", "id":"702"}, +{"last_update":"1176223342", "numofapproved":"1", "id":"823"}, +{"last_update":"1176459077", "numofapproved":"1", "id":"905"}, +{"last_update":"1172169117", "numofapproved":"1", "id":"172"}, +{"last_update":"1172259821", "numofapproved":"1", "id":"189"}, +{"last_update":"1172847347", "numofapproved":"1", "id":"237"}, +{"last_update":"1176485274", "numofapproved":"1", "id":"961"}, +{"last_update":"1176739199", "numofapproved":"1", "id":"983"}, +{"last_update":"1171710108", "numofapproved":"1", "id":"72"}, +{"last_update":"1172147854", "numofapproved":"1", "id":"170"}, +{"last_update":"1172178657", "numofapproved":"1", "id":"173"}, +{"last_update":"1174933210", "numofapproved":"1", "id":"535"}, +{"last_update":"1175502973", "numofapproved":"1", "id":"626"}, +{"last_update":"1172071610", "numofapproved":"1", "id":"146"}, +{"last_update":"1172847402", "numofapproved":"1", "id":"240"}, +{"last_update":"1173282970", "numofapproved":"1", "id":"258"}, +{"last_update":"1175502729", "numofapproved":"1", "id":"621"}, +{"last_update":"1173889203", "numofapproved":"1", "id":"327"}, +{"last_update":"1174301604", "numofapproved":"1", "id":"396"}, +{"last_update":"1176738556", "numofapproved":"1", "id":"1005"}, +{"last_update":"1171287066", "numofapproved":"1", "id":"22"}, +{"last_update":"1171388951", "numofapproved":"1", "id":"46"}, +{"last_update":"1171645099", "numofapproved":"1", "id":"70"}, +{"last_update":"1174301489", "numofapproved":"1", "id":"394"}, +{"last_update":"1176109438", "numofapproved":"1", "id":"804"}, +{"last_update":"1173203622", "numofapproved":"1", "id":"251"}, +{"last_update":"1174300337", "numofapproved":"1", "id":"364"}, +{"last_update":"1174898999", "numofapproved":"1", "id":"486"}, +{"last_update":"1174899221", "numofapproved":"1", "id":"497"}, +{"last_update":"1174899505", "numofapproved":"1", "id":"508"}, +{"last_update":"1171905996", "numofapproved":"1", "id":"106"}, +{"last_update":"1172003938", "numofapproved":"1", "id":"131"}, +{"last_update":"1172134183", "numofapproved":"1", "id":"167"}, +{"last_update":"1178550080", "numofapproved":"1", "id":"1301"}, +{"last_update":"1178718229", "numofapproved":"1", "id":"1346"}, +{"last_update":"1178725187", "numofapproved":"1", "id":"1322"}, +{"last_update":"1179302219", "numofapproved":"1", "id":"1392"}, +{"last_update":"1180015260", "numofapproved":"1", "id":"1650"}, +{"last_update":"1180088452", "numofapproved":"1", "id":"1656"}, +{"last_update":"1180719498", "numofapproved":"1", "id":"2121"}, +{"last_update":"1180731930", "numofapproved":"1", "id":"2145"}, +{"last_update":"1180731601", "numofapproved":"1", "id":"2142"}, +{"last_update":"1181034337", "numofapproved":"1", "id":"2281"}, +{"last_update":"1181222113", "numofapproved":"1", "id":"2501"}, +{"last_update":"1181254636", "numofapproved":"1", "id":"2601"}, +{"last_update":"1181578682", "numofapproved":"1", "id":"2762"}, +{"last_update":"1181731051", "numofapproved":"1", "id":"2881"}, +{"last_update":"1177673345", "numofapproved":"1", "id":"1162"}, +{"last_update":"1183741680", "numofapproved":"1", "id":"4301"}, +{"last_update":"1183988623", "numofapproved":"1", "id":"4441"}, +{"last_update":"1184217947", "numofapproved":"1", "id":"4701"}, +{"last_update":"1186260146", "numofapproved":"1", "id":"6181"}, +{"last_update":"1186289860", "numofapproved":"1", "id":"6163"}, +{"last_update":"1186235477", "numofapproved":"1", "id":"6161"}, +{"last_update":"1186508996", "numofapproved":"1", "id":"6171"}, +{"last_update":"1187626570", "numofapproved":"1", "id":"6961"}, +{"last_update":"1187713755", "numofapproved":"1", "id":"7041"}, +{"last_update":"1187769208", "numofapproved":"1", "id":"7222"}, +{"last_update":"1187856827", "numofapproved":"1", "id":"7341"}, +{"last_update":"1188053850", "numofapproved":"1", "id":"7461"}, +{"last_update":"1188264856", "numofapproved":"1", "id":"7541"}, +{"last_update":"1188319841", "numofapproved":"1", "id":"7681"}, +{"last_update":"1188582632", "numofapproved":"1", "id":"7901"}, +{"last_update":"1188734330", "numofapproved":"1", "id":"8001"}, +{"last_update":"1189003562", "numofapproved":"1", "id":"8381"}, +{"last_update":"1179787121", "numofapproved":"1", "id":"1581"}, +{"last_update":"1181998896", "numofapproved":"1", "id":"3121"}, +{"last_update":"1182274782", "numofapproved":"1", "id":"3261"}, +{"last_update":"1186350397", "numofapproved":"1", "id":"6241"}, +{"last_update":"1187354512", "numofapproved":"1", "id":"6881"}, +{"last_update":"1188918086", "numofapproved":"1", "id":"8221"}, +{"last_update":"1190392989", "numofapproved":"1", "id":"9721"}, +{"last_update":"1190925022", "numofapproved":"1", "id":"10583"}, +{"last_update":"1190959571", "numofapproved":"1", "id":"10601"}, +{"last_update":"1190990357", "numofapproved":"1", "id":"10705"}, +{"last_update":"1190990656", "numofapproved":"1", "id":"10710"}, +{"last_update":"1191226364", "numofapproved":"1", "id":"10921"}, +{"last_update":"1180011741", "numofapproved":"1", "id":"1761"}, +{"last_update":"1180533694", "numofapproved":"1", "id":"1961"}, +{"last_update":"1180731839", "numofapproved":"1", "id":"2144"}, +{"last_update":"1181461876", "numofapproved":"1", "id":"2681"}, +{"last_update":"1181855690", "numofapproved":"1", "id":"3061"}, +{"last_update":"1189537687", "numofapproved":"1", "id":"8821"}, +{"last_update":"1189937430", "numofapproved":"1", "id":"9161"}, +{"last_update":"1190803903", "numofapproved":"1", "id":"10261"}, +{"last_update":"1190973051", "numofapproved":"1", "id":"10664"}, +{"last_update":"1191410739", "numofapproved":"1", "id":"11064"}, +{"last_update":"1191426697", "numofapproved":"1", "id":"11121"}, +{"last_update":"1191446459", "numofapproved":"1", "id":"11182"}, +{"last_update":"1191450891", "numofapproved":"1", "id":"11201"}, +{"last_update":"1191550000", "numofapproved":"1", "id":"11441"}, +{"last_update":"1191588714", "numofapproved":"1", "id":"11601"}, +{"last_update":"1191596815", "numofapproved":"1", "id":"11641"}, +{"last_update":"1191647971", "numofapproved":"1", "id":"11741"}, +{"last_update":"1191949660", "numofapproved":"1", "id":"11981"}, +{"last_update":"1180641844", "numofapproved":"1", "id":"2001"}, +{"last_update":"1188319710", "numofapproved":"1", "id":"7661"}, +{"last_update":"1189169640", "numofapproved":"1", "id":"8621"}, +{"last_update":"1192028009", "numofapproved":"1", "id":"12081"}, +{"last_update":"1192116783", "numofapproved":"1", "id":"12261"}, +{"last_update":"1192558715", "numofapproved":"1", "id":"12741"}, +{"last_update":"1192727702", "numofapproved":"1", "id":"13101"}, +{"last_update":"1193035517", "numofapproved":"1", "id":"13262"}, +{"last_update":"1193080239", "numofapproved":"1", "id":"13381"}, +{"last_update":"1193268912", "numofapproved":"1", "id":"13722"}, +{"last_update":"1193386894", "numofapproved":"1", "id":"13946"}, +{"last_update":"1193388087", "numofapproved":"1", "id":"13982"}, +{"last_update":"1179841973", "numofapproved":"1", "id":"1642"}, +{"last_update":"1179842066", "numofapproved":"1", "id":"1662"}, +{"last_update":"1185971695", "numofapproved":"1", "id":"5941"}, +{"last_update":"1186137440", "numofapproved":"1", "id":"6103"}, +{"last_update":"1192823224", "numofapproved":"1", "id":"13181"}, +{"last_update":"1193921116", "numofapproved":"1", "id":"14581"}, +{"last_update":"1193918035", "numofapproved":"1", "id":"14544"}, +{"last_update":"1193973759", "numofapproved":"1", "id":"14663"}, +{"last_update":"1194004166", "numofapproved":"1", "id":"14721"}, +{"last_update":"1194020795", "numofapproved":"1", "id":"14761"}, +{"last_update":"1194021069", "numofapproved":"1", "id":"14781"}, +{"last_update":"1194283444", "numofapproved":"1", "id":"14887"}, +{"last_update":"1194436909", "numofapproved":"1", "id":"15141"}, +{"last_update":"1194538247", "numofapproved":"1", "id":"15341"}, +{"last_update":"1180031440", "numofapproved":"1", "id":"1801"}, +{"last_update":"1181823965", "numofapproved":"1", "id":"2941"}, +{"last_update":"1182846565", "numofapproved":"1", "id":"3561"}, +{"last_update":"1185872587", "numofapproved":"1", "id":"5843"}, +{"last_update":"1186472951", "numofapproved":"1", "id":"6168"}, +{"last_update":"1189937606", "numofapproved":"1", "id":"9181"}, +{"last_update":"1193389026", "numofapproved":"1", "id":"13955"}, +{"last_update":"1192130592", "numofapproved":"1", "id":"12321"}, +{"last_update":"1194387386", "numofapproved":"1", "id":"15061"}, +{"last_update":"1179336536", "numofapproved":"1", "id":"1396"}, +{"last_update":"1182280246", "numofapproved":"1", "id":"3281"}, +{"last_update":"1183394591", "numofapproved":"1", "id":"4001"}, +{"last_update":"1184677502", "numofapproved":"1", "id":"4909"}, +{"last_update":"1186144184", "numofapproved":"1", "id":"6106"}, +{"last_update":"1187191683", "numofapproved":"1", "id":"6701"}, +{"last_update":"1193909594", "numofapproved":"1", "id":"14527"}, +{"last_update":"1194435747", "numofapproved":"1", "id":"15121"}, +{"last_update":"1184252278", "numofapproved":"1", "id":"4761"}, +{"last_update":"1194854996", "numofapproved":"1", "id":"15721"}, +{"last_update":"1194937730", "numofapproved":"1", "id":"16045"}, +{"last_update":"1193076864", "numofapproved":"1", "id":"13361"}, +{"last_update":"1194904087", "numofapproved":"1", "id":"15981"}, +{"last_update":"1181853751", "numofapproved":"1", "id":"3001"}, +{"last_update":"1182075529", "numofapproved":"1", "id":"3161"}, +{"last_update":"1184883226", "numofapproved":"1", "id":"5081"}, +{"last_update":"1186136013", "numofapproved":"1", "id":"6102"}, +{"last_update":"1193147983", "numofapproved":"1", "id":"13481"}, +{"last_update":"1194532658", "numofapproved":"1", "id":"15301"}, +{"last_update":"1194937763", "numofapproved":"1", "id":"16046"}, +{"last_update":"1195225183", "numofapproved":"1", "id":"16981"}, +{"last_update":"1180616624", "numofapproved":"1", "id":"1981"}, +{"last_update":"1183019269", "numofapproved":"1", "id":"3701"}, +{"last_update":"1188656338", "numofapproved":"1", "id":"7941"}, +{"last_update":"1178799062", "numofapproved":"1", "id":"1353"}, +{"last_update":"1178905809", "numofapproved":"1", "id":"1360"}, +{"last_update":"1179311575", "numofapproved":"1", "id":"1408"}, +{"last_update":"1182507595", "numofapproved":"1", "id":"3461"}, +{"last_update":"1184254004", "numofapproved":"1", "id":"4781"}, +{"last_update":"1187938257", "numofapproved":"1", "id":"7381"}, +{"last_update":"1188473327", "numofapproved":"1", "id":"7801"}, +{"last_update":"1189102174", "numofapproved":"1", "id":"8481"}, +{"last_update":"1191419747", "numofapproved":"1", "id":"11102"}, +{"last_update":"1193389169", "numofapproved":"1", "id":"14002"}, +{"last_update":"1194440930", "numofapproved":"1", "id":"15102"}, +{"last_update":"1194855848", "numofapproved":"1", "id":"15741"}, +{"last_update":"1194862162", "numofapproved":"1", "id":"15841"}, +{"last_update":"1194923605", "numofapproved":"1", "id":"16021"}, +{"last_update":"1194950051", "numofapproved":"1", "id":"16142"}, +{"last_update":"1194960554", "numofapproved":"1", "id":"16181"}, +{"last_update":"1194988868", "numofapproved":"1", "id":"16382"}, +{"last_update":"1195058276", "numofapproved":"1", "id":"16601"}, +{"last_update":"1195469960", "numofapproved":"1", "id":"17201"}, +{"last_update":"1178648361", "numofapproved":"1", "id":"1311"}, +{"last_update":"1183970840", "numofapproved":"1", "id":"4401"}, +{"last_update":"1184838534", "numofapproved":"1", "id":"5041"}, +{"last_update":"1190745858", "numofapproved":"1", "id":"10161"}, +{"last_update":"1191587968", "numofapproved":"1", "id":"11581"}, +{"last_update":"1189773687", "numofapproved":"1", "id":"9021"}, +{"last_update":"1192612866", "numofapproved":"1", "id":"12804"}, +{"last_update":"1193746024", "numofapproved":"1", "id":"14461"}, +{"last_update":"1193918117", "numofapproved":"1", "id":"14561"}, +{"last_update":"1194981013", "numofapproved":"1", "id":"16321"}, +{"last_update":"1195546695", "numofapproved":"1", "id":"17481"}, +{"last_update":"1177592107", "numofapproved":"1", "id":"1047"}, +{"last_update":"1183569612", "numofapproved":"1", "id":"4221"}, +{"last_update":"1186770649", "numofapproved":"1", "id":"6401"}, +{"last_update":"1187707518", "numofapproved":"1", "id":"7021"}, +{"last_update":"1187769297", "numofapproved":"1", "id":"7223"}, +{"last_update":"1187798945", "numofapproved":"1", "id":"7241"}, +{"last_update":"1187820883", "numofapproved":"1", "id":"7261"}, +{"last_update":"1190286816", "numofapproved":"1", "id":"9581"}, +{"last_update":"1190541964", "numofapproved":"1", "id":"9842"}, +{"last_update":"1190500569", "numofapproved":"1", "id":"9802"}, +{"last_update":"1190800190", "numofapproved":"1", "id":"10222"}, +{"last_update":"1190965460", "numofapproved":"1", "id":"10642"}, +{"last_update":"1192120899", "numofapproved":"1", "id":"12301"}, +{"last_update":"1193265675", "numofapproved":"1", "id":"13701"}, +{"last_update":"1194508196", "numofapproved":"1", "id":"15261"}, +{"last_update":"1172503197", "numofapproved":"1", "id":"196"}, +{"last_update":"1172847366", "numofapproved":"1", "id":"238"}, +{"last_update":"1173975764", "numofapproved":"1", "id":"347"}, +{"last_update":"1174301010", "numofapproved":"1", "id":"375"}, +{"last_update":"1174899614", "numofapproved":"1", "id":"514"}, +{"last_update":"1174924853", "numofapproved":"1", "id":"527"}, +{"last_update":"1175270318", "numofapproved":"1", "id":"567"}, +{"last_update":"1174933246", "numofapproved":"1", "id":"536"}, +{"last_update":"1176369900", "numofapproved":"1", "id":"889"}, +{"last_update":"1171102836", "numofapproved":"1", "id":"2"}, +{"last_update":"1171970451", "numofapproved":"1", "id":"121"}, +{"last_update":"1174898953", "numofapproved":"1", "id":"484"}, +{"last_update":"1175610845", "numofapproved":"1", "id":"664"}, +{"last_update":"1176313569", "numofapproved":"1", "id":"885"}, +{"last_update":"1171878648", "numofapproved":"1", "id":"89"}, +{"last_update":"1171897268", "numofapproved":"1", "id":"96"}, +{"last_update":"1172326187", "numofapproved":"1", "id":"193"}, +{"last_update":"1176106905", "numofapproved":"1", "id":"802"}, +{"last_update":"1176389540", "numofapproved":"1", "id":"891"}, +{"last_update":"1171318806", "numofapproved":"1", "id":"24"}, +{"last_update":"1171601548", "numofapproved":"1", "id":"66"}, +{"last_update":"1172148331", "numofapproved":"1", "id":"171"}, +{"last_update":"1172686680", "numofapproved":"1", "id":"228"}, +{"last_update":"1173793572", "numofapproved":"1", "id":"308"}, +{"last_update":"1174899594", "numofapproved":"1", "id":"513"}, +{"last_update":"1174898936", "numofapproved":"1", "id":"483"}, +{"last_update":"1175502773", "numofapproved":"1", "id":"622"}, +{"last_update":"1175722537", "numofapproved":"1", "id":"709"}, +{"last_update":"1175764633", "numofapproved":"1", "id":"672"}, +{"last_update":"1175797156", "numofapproved":"1", "id":"721"}, +{"last_update":"1175899070", "numofapproved":"1", "id":"785"}, +{"last_update":"1176106959", "numofapproved":"1", "id":"803"}, +{"last_update":"1176228460", "numofapproved":"1", "id":"824"}, +{"last_update":"1176488163", "numofapproved":"1", "id":"962"}, +{"last_update":"1172068869", "numofapproved":"1", "id":"133"}, +{"last_update":"1172847381", "numofapproved":"1", "id":"239"}, +{"last_update":"1173888657", "numofapproved":"1", "id":"320"}, +{"last_update":"1171449446", "numofapproved":"1", "id":"48"}, +{"last_update":"1175287424", "numofapproved":"1", "id":"581"}, +{"last_update":"1175502897", "numofapproved":"1", "id":"624"}, +{"last_update":"1175503020", "numofapproved":"1", "id":"605"}, +{"last_update":"1172848367", "numofapproved":"1", "id":"243"}, +{"last_update":"1174301060", "numofapproved":"1", "id":"377"}, +{"last_update":"1176824481", "numofapproved":"1", "id":"986"}, +{"last_update":"1171275893", "numofapproved":"1", "id":"6"}, +{"last_update":"1172546216", "numofapproved":"1", "id":"206"}, +{"last_update":"1175502705", "numofapproved":"1", "id":"601"}, +{"last_update":"1173962671", "numofapproved":"1", "id":"341"}, +{"last_update":"1173975403", "numofapproved":"1", "id":"342"}, +{"last_update":"1173816295", "numofapproved":"1", "id":"313"}, +{"last_update":"1174301256", "numofapproved":"1", "id":"384"}, +{"last_update":"1174933293", "numofapproved":"1", "id":"537"}, +{"last_update":"1176899419", "numofapproved":"1", "id":"988"}, +{"last_update":"1173975599", "numofapproved":"1", "id":"345"}, +{"last_update":"1174041960", "numofapproved":"1", "id":"351"}, +{"last_update":"1175759476", "numofapproved":"1", "id":"671"}, +{"last_update":"1178195644", "numofapproved":"1", "id":"1207"}, +{"last_update":"1178725318", "numofapproved":"1", "id":"1348"}, +{"last_update":"1179333492", "numofapproved":"1", "id":"1421"}, +{"last_update":"1179999737", "numofapproved":"1", "id":"1646"}, +{"last_update":"1180710770", "numofapproved":"1", "id":"2062"}, +{"last_update":"1182868347", "numofapproved":"1", "id":"3601"}, +{"last_update":"1182932927", "numofapproved":"1", "id":"3621"}, +{"last_update":"1183115054", "numofapproved":"1", "id":"3784"}, +{"last_update":"1180000741", "numofapproved":"1", "id":"1647"}, +{"last_update":"1181292582", "numofapproved":"1", "id":"2621"}, +{"last_update":"1184181581", "numofapproved":"1", "id":"4641"}, +{"last_update":"1185280501", "numofapproved":"1", "id":"5301"}, +{"last_update":"1185471699", "numofapproved":"1", "id":"5561"}, +{"last_update":"1185542771", "numofapproved":"1", "id":"5701"}, +{"last_update":"1186650650", "numofapproved":"1", "id":"6361"}, +{"last_update":"1186951065", "numofapproved":"1", "id":"6461"}, +{"last_update":"1187769080", "numofapproved":"1", "id":"7221"}, +{"last_update":"1187887905", "numofapproved":"1", "id":"7348"}, +{"last_update":"1188001607", "numofapproved":"1", "id":"7423"}, +{"last_update":"1188463414", "numofapproved":"1", "id":"7762"}, +{"last_update":"1188555813", "numofapproved":"1", "id":"7861"}, +{"last_update":"1188634622", "numofapproved":"1", "id":"7921"}, +{"last_update":"1189543954", "numofapproved":"1", "id":"8841"}, +{"last_update":"1177511009", "numofapproved":"1", "id":"1043"}, +{"last_update":"1181898808", "numofapproved":"1", "id":"3081"}, +{"last_update":"1182247483", "numofapproved":"1", "id":"3221"}, +{"last_update":"1187024005", "numofapproved":"1", "id":"6562"}, +{"last_update":"1189839471", "numofapproved":"1", "id":"9081"}, +{"last_update":"1190018380", "numofapproved":"1", "id":"9241"}, +{"last_update":"1190149586", "numofapproved":"1", "id":"9401"}, +{"last_update":"1190652684", "numofapproved":"1", "id":"9981"}, +{"last_update":"1190662296", "numofapproved":"1", "id":"10022"}, +{"last_update":"1190813509", "numofapproved":"1", "id":"10281"}, +{"last_update":"1190826005", "numofapproved":"1", "id":"10403"}, +{"last_update":"1190991166", "numofapproved":"1", "id":"10722"}, +{"last_update":"1191057700", "numofapproved":"1", "id":"10801"}, +{"last_update":"1191161241", "numofapproved":"1", "id":"10821"}, +{"last_update":"1191227885", "numofapproved":"1", "id":"10941"}, +{"last_update":"1182537005", "numofapproved":"1", "id":"3481"}, +{"last_update":"1185018401", "numofapproved":"1", "id":"5162"}, +{"last_update":"1186752963", "numofapproved":"1", "id":"6386"}, +{"last_update":"1190660077", "numofapproved":"1", "id":"10001"}, +{"last_update":"1191319062", "numofapproved":"1", "id":"10981"}, +{"last_update":"1191446097", "numofapproved":"1", "id":"11161"}, +{"last_update":"1191446587", "numofapproved":"1", "id":"11184"}, +{"last_update":"1191470824", "numofapproved":"1", "id":"11221"}, +{"last_update":"1191526821", "numofapproved":"1", "id":"11401"}, +{"last_update":"1191585471", "numofapproved":"1", "id":"11561"}, +{"last_update":"1191602213", "numofapproved":"1", "id":"11701"}, +{"last_update":"1191845720", "numofapproved":"1", "id":"11821"}, +{"last_update":"1191933874", "numofapproved":"1", "id":"11902"}, +{"last_update":"1191933897", "numofapproved":"1", "id":"11903"}, +{"last_update":"1177673238", "numofapproved":"1", "id":"1161"}, +{"last_update":"1181601542", "numofapproved":"1", "id":"2781"}, +{"last_update":"1182869532", "numofapproved":"1", "id":"3583"}, +{"last_update":"1183315879", "numofapproved":"1", "id":"3881"}, +{"last_update":"1187097870", "numofapproved":"1", "id":"6641"}, +{"last_update":"1190148660", "numofapproved":"1", "id":"9361"}, +{"last_update":"1192248648", "numofapproved":"1", "id":"12521"}, +{"last_update":"1192702958", "numofapproved":"1", "id":"13001"}, +{"last_update":"1193387721", "numofapproved":"1", "id":"13981"}, +{"last_update":"1193391276", "numofapproved":"1", "id":"14021"}, +{"last_update":"1193397051", "numofapproved":"1", "id":"14061"}, +{"last_update":"1193592081", "numofapproved":"1", "id":"14321"}, +{"last_update":"1188474438", "numofapproved":"1", "id":"7821"}, +{"last_update":"1190158372", "numofapproved":"1", "id":"9441"}, +{"last_update":"1193648459", "numofapproved":"1", "id":"14361"}, +{"last_update":"1193999834", "numofapproved":"1", "id":"14681"}, +{"last_update":"1194200119", "numofapproved":"1", "id":"14861"}, +{"last_update":"1194528747", "numofapproved":"1", "id":"15111"}, +{"last_update":"1179150787", "numofapproved":"1", "id":"1384"}, +{"last_update":"1179266496", "numofapproved":"1", "id":"1390"}, +{"last_update":"1179508139", "numofapproved":"1", "id":"1501"}, +{"last_update":"1179842157", "numofapproved":"1", "id":"1664"}, +{"last_update":"1179842347", "numofapproved":"1", "id":"1668"}, +{"last_update":"1181245388", "numofapproved":"1", "id":"2562"}, +{"last_update":"1181311044", "numofapproved":"1", "id":"2661"}, +{"last_update":"1181545818", "numofapproved":"1", "id":"2701"}, +{"last_update":"1181934881", "numofapproved":"1", "id":"3103"}, +{"last_update":"1187020798", "numofapproved":"1", "id":"6541"}, +{"last_update":"1187271377", "numofapproved":"1", "id":"6801"}, +{"last_update":"1196086904", "numofapproved":"1", "id":"17545"}, +{"last_update":"1196266437", "numofapproved":"2", "id":"17662"}, +{"last_update":"1196266638", "numofapproved":"2", "id":"17663"}, +{"last_update":"1197533251", "numofapproved":"1", "id":"17901"}, +{"last_update":"1197533384", "numofapproved":"1", "id":"17923"}, +{"last_update":"1197556776", "numofapproved":"2", "id":"17941"}, +{"last_update":"1200059354", "numofapproved":"1", "id":"17981"}, +{"last_update":"1200576144", "numofapproved":"1", "id":"18001"}, +{"last_update":"1200576230", "numofapproved":"1", "id":"18002"}, +{"last_update":"1200657266", "numofapproved":"1", "id":"18041"}, +{"last_update":"1201510556", "numofapproved":"1", "id":"18061"}, +{"last_update":"1196087136", "numofapproved":"1", "id":"17546"}, +{"last_update":"1196087269", "numofapproved":"1", "id":"17547"}, +{"last_update":"1196087335", "numofapproved":"1", "id":"17548"}, +{"last_update":"1196087379", "numofapproved":"1", "id":"17549"}, +{"last_update":"1196087427", "numofapproved":"1", "id":"17550"}, +{"last_update":"1196096347", "numofapproved":"1", "id":"17581"}, +{"last_update":"1196265997", "numofapproved":"2", "id":"17661"}, +{"last_update":"1196266785", "numofapproved":"1", "id":"17664"}, +{"last_update":"1196270058", "numofapproved":"1", "id":"17701"}, +{"last_update":"1196431875", "numofapproved":"1", "id":"17804"}, +{"last_update":"1197635044", "numofapproved":"1", "id":"17961"}, +{"last_update":"1202720206", "numofapproved":"2", "id":"18084"}, +{"last_update":"1196267153", "numofapproved":"1", "id":"17681"}, +{"last_update":"1196090749", "numofapproved":"1", "id":"17569"}, +{"last_update":"1196162163", "numofapproved":"2", "id":"17641"}, +{"last_update":"1196345846", "numofapproved":"1", "id":"17721"}, +{"last_update":"1196088254", "numofapproved":"1", "id":"17552"}, +{"last_update":"1196088437", "numofapproved":"1", "id":"17564"}, +{"last_update":"1196088477", "numofapproved":"1", "id":"17565"}, +{"last_update":"1196088537", "numofapproved":"1", "id":"17566"}, +{"last_update":"1196088894", "numofapproved":"1", "id":"17567"}, +{"last_update":"1196090414", "numofapproved":"1", "id":"17554"}, +{"last_update":"1196097621", "numofapproved":"1", "id":"17601"}, +{"last_update":"1196097710", "numofapproved":"1", "id":"17602"}, +{"last_update":"1196098047", "numofapproved":"1", "id":"17603"}, +{"last_update":"1196358376", "numofapproved":"2", "id":"17761"}, +{"last_update":"1196358647", "numofapproved":"1", "id":"17762"}, +{"last_update":"1196427604", "numofapproved":"1", "id":"17781"}, +{"last_update":"1196429856", "numofapproved":"1", "id":"17782"}, +{"last_update":"1196431068", "numofapproved":"2", "id":"17783"}, +{"last_update":"1196435953", "numofapproved":"2", "id":"17821"}, +{"last_update":"1204027277", "numofapproved":"1", "id":"18104"}, +{"last_update":"1196090201", "numofapproved":"1", "id":"17553"}, +{"last_update":"1196097095", "numofapproved":"1", "id":"17582"}, +{"last_update":"1196097215", "numofapproved":"1", "id":"17583"}, +{"last_update":"1196430140", "numofapproved":"2", "id":"17803"}, +{"last_update":"1196436411", "numofapproved":"2", "id":"17841"}, +{"last_update":"1196692298", "numofapproved":"1", "id":"17861"}, +{"last_update":"1196692342", "numofapproved":"2", "id":"17862"}, +{"last_update":"1196695231", "numofapproved":"2", "id":"17865"}, +{"last_update":"1197533316", "numofapproved":"1", "id":"17921"}, +{"last_update":"1201512744", "numofapproved":"1", "id":"18082"}, +{"last_update":"1201513438", "numofapproved":"2", "id":"18083"}, +{"last_update":"1196087540", "numofapproved":"1", "id":"17551"}, +{"last_update":"1196156416", "numofapproved":"2", "id":"17621"}, +{"last_update":"1196356717", "numofapproved":"1", "id":"17741"}, +{"last_update":"1196428544", "numofapproved":"2", "id":"17801"}, +{"last_update":"1196429000", "numofapproved":"2", "id":"17802"}, +{"last_update":"1196692578", "numofapproved":"1", "id":"17863"}, +{"last_update":"1196693445", "numofapproved":"2", "id":"17881"}, +{"last_update":"1196693804", "numofapproved":"2", "id":"17864"}, +{"last_update":"1197533347", "numofapproved":"1", "id":"17922"}, +{"last_update":"1200591782", "numofapproved":"1", "id":"18021"}, +{"last_update":"1201510930", "numofapproved":"1", "id":"18081"}, +{"last_update":"1192432005", "numofapproved":"1", "id":"12582"}, +{"last_update":"1192614291", "numofapproved":"1", "id":"12805"}, +{"last_update":"1192624421", "numofapproved":"1", "id":"12806"}, +{"last_update":"1192983623", "numofapproved":"1", "id":"13221"}, +{"last_update":"1193043248", "numofapproved":"1", "id":"13282"}, +{"last_update":"1193223892", "numofapproved":"1", "id":"13562"}, +{"last_update":"1193239943", "numofapproved":"1", "id":"13601"}, +{"last_update":"1193385960", "numofapproved":"1", "id":"13961"}, +{"last_update":"1193386863", "numofapproved":"1", "id":"13945"}, +{"last_update":"1193399770", "numofapproved":"1", "id":"14042"}, +{"last_update":"1193417684", "numofapproved":"1", "id":"14181"}, +{"last_update":"1193458402", "numofapproved":"1", "id":"14261"}, +{"last_update":"1193555071", "numofapproved":"1", "id":"14301"}, +{"last_update":"1185285506", "numofapproved":"1", "id":"5321"}, +{"last_update":"1188250869", "numofapproved":"1", "id":"7521"}, +{"last_update":"1191410480", "numofapproved":"1", "id":"11061"}, +{"last_update":"1193763056", "numofapproved":"1", "id":"14482"}, +{"last_update":"1193913886", "numofapproved":"1", "id":"14542"}, +{"last_update":"1194366001", "numofapproved":"1", "id":"14890"}, +{"last_update":"1194454607", "numofapproved":"1", "id":"15105"}, +{"last_update":"1194255904", "numofapproved":"1", "id":"14941"}, +{"last_update":"1179328986", "numofapproved":"1", "id":"1395"}, +{"last_update":"1180377628", "numofapproved":"1", "id":"1861"}, +{"last_update":"1181250011", "numofapproved":"1", "id":"2563"}, +{"last_update":"1181572386", "numofapproved":"1", "id":"2741"}, +{"last_update":"1183967114", "numofapproved":"1", "id":"4381"}, +{"last_update":"1192512712", "numofapproved":"1", "id":"12623"}, +{"last_update":"1193172621", "numofapproved":"1", "id":"13522"}, +{"last_update":"1193868932", "numofapproved":"1", "id":"14523"}, +{"last_update":"1194980345", "numofapproved":"1", "id":"16301"}, +{"last_update":"1182280312", "numofapproved":"1", "id":"3282"}, +{"last_update":"1184058726", "numofapproved":"1", "id":"4542"}, +{"last_update":"1188829875", "numofapproved":"1", "id":"8161"}, +{"last_update":"1190129857", "numofapproved":"1", "id":"9341"}, +{"last_update":"1190652687", "numofapproved":"1", "id":"9982"}, +{"last_update":"1193389082", "numofapproved":"1", "id":"13956"}, +{"last_update":"1195400591", "numofapproved":"1", "id":"17121"}, +{"last_update":"1184420846", "numofapproved":"1", "id":"4882"}, +{"last_update":"1184532219", "numofapproved":"1", "id":"4903"}, +{"last_update":"1192030476", "numofapproved":"1", "id":"12101"}, +{"last_update":"1192202239", "numofapproved":"1", "id":"12461"}, +{"last_update":"1192688302", "numofapproved":"1", "id":"12961"}, +{"last_update":"1192703266", "numofapproved":"1", "id":"13021"}, +{"last_update":"1193387096", "numofapproved":"1", "id":"13948"}, +{"last_update":"1193387200", "numofapproved":"1", "id":"13949"}, +{"last_update":"1193909837", "numofapproved":"1", "id":"14528"}, +{"last_update":"1181062093", "numofapproved":"1", "id":"2301"}, +{"last_update":"1182364431", "numofapproved":"1", "id":"3348"}, +{"last_update":"1182364589", "numofapproved":"1", "id":"3349"}, +{"last_update":"1184942429", "numofapproved":"1", "id":"5101"}, +{"last_update":"1192682522", "numofapproved":"1", "id":"12901"}, +{"last_update":"1184756287", "numofapproved":"1", "id":"4944"}, +{"last_update":"1190274411", "numofapproved":"1", "id":"9541"}, +{"last_update":"1193324229", "numofapproved":"1", "id":"13861"}, +{"last_update":"1195163999", "numofapproved":"1", "id":"16861"}, +{"last_update":"1181553321", "numofapproved":"1", "id":"2721"}, +{"last_update":"1178869453", "numofapproved":"1", "id":"1361"}, +{"last_update":"1181219788", "numofapproved":"1", "id":"2481"}, +{"last_update":"1178140002", "numofapproved":"1", "id":"1205"}, +{"last_update":"1178716891", "numofapproved":"1", "id":"1345"}, +{"last_update":"1180691957", "numofapproved":"1", "id":"2061"}, +{"last_update":"1182246242", "numofapproved":"1", "id":"3206"}, +{"last_update":"1182882314", "numofapproved":"1", "id":"3585"}, +{"last_update":"1183124192", "numofapproved":"1", "id":"3821"}, +{"last_update":"1183905634", "numofapproved":"1", "id":"4361"}, +{"last_update":"1191225755", "numofapproved":"1", "id":"10901"}, +{"last_update":"1192635977", "numofapproved":"1", "id":"12881"}, +{"last_update":"1193268752", "numofapproved":"1", "id":"13721"}, +{"last_update":"1193242245", "numofapproved":"1", "id":"13621"}, +{"last_update":"1193949751", "numofapproved":"1", "id":"14621"}, +{"last_update":"1194635892", "numofapproved":"1", "id":"15621"}, +{"last_update":"1194726918", "numofapproved":"1", "id":"15664"}, +{"last_update":"1194726371", "numofapproved":"1", "id":"15662"}, +{"last_update":"1194858043", "numofapproved":"1", "id":"15781"}, +{"last_update":"1194946522", "numofapproved":"1", "id":"16101"}, +{"last_update":"1195047359", "numofapproved":"1", "id":"16521"}, +{"last_update":"1195050812", "numofapproved":"1", "id":"16503"}, +{"last_update":"1195058811", "numofapproved":"1", "id":"16621"}, +{"last_update":"1195476161", "numofapproved":"1", "id":"17241"}, +{"last_update":"1178645683", "numofapproved":"1", "id":"1305"}, +{"last_update":"1183118619", "numofapproved":"1", "id":"3801"}, +{"last_update":"1186150376", "numofapproved":"1", "id":"6121"}, +{"last_update":"1189114226", "numofapproved":"1", "id":"8501"}, +{"last_update":"1190973079", "numofapproved":"1", "id":"10666"}, +{"last_update":"1190990329", "numofapproved":"1", "id":"10704"}, +{"last_update":"1191508485", "numofapproved":"1", "id":"11361"}, +{"last_update":"1183054560", "numofapproved":"1", "id":"3721"}, +{"last_update":"1185263889", "numofapproved":"1", "id":"5241"}, +{"last_update":"1187876083", "numofapproved":"1", "id":"7346"}, +{"last_update":"1189550218", "numofapproved":"1", "id":"8861"}, +{"last_update":"1190800088", "numofapproved":"1", "id":"10221"}, +{"last_update":"1193260528", "numofapproved":"1", "id":"13661"}, +{"last_update":"1172509002", "numofapproved":"1", "id":"199"}, +{"last_update":"1172509846", "numofapproved":"1", "id":"200"}, +{"last_update":"1172589855", "numofapproved":"1", "id":"214"}, +{"last_update":"1172847322", "numofapproved":"1", "id":"236"}, +{"last_update":"1172847433", "numofapproved":"1", "id":"242"}, +{"last_update":"1173607050", "numofapproved":"1", "id":"283"}, +{"last_update":"1173703535", "numofapproved":"1", "id":"301"}, +{"last_update":"1173719825", "numofapproved":"1", "id":"302"}, +{"last_update":"1174414845", "numofapproved":"1", "id":"403"}, +{"last_update":"1174650542", "numofapproved":"1", "id":"441"}, +{"last_update":"1171475944", "numofapproved":"1", "id":"52"}, +{"last_update":"1172746278", "numofapproved":"1", "id":"231"}, +{"last_update":"1173251095", "numofapproved":"1", "id":"254"}, +{"last_update":"1173259501", "numofapproved":"1", "id":"255"}, +{"last_update":"1174899183", "numofapproved":"1", "id":"495"}, +{"last_update":"1174924714", "numofapproved":"1", "id":"524"}, +{"last_update":"1171962179", "numofapproved":"1", "id":"108"}, +{"last_update":"1172522401", "numofapproved":"1", "id":"205"}, +{"last_update":"1174299349", "numofapproved":"1", "id":"362"}, +{"last_update":"1174899291", "numofapproved":"1", "id":"500"}, +{"last_update":"1175617661", "numofapproved":"1", "id":"688"}, +{"last_update":"1176302948", "numofapproved":"1", "id":"881"}, +{"last_update":"1176467393", "numofapproved":"1", "id":"893"}, +{"last_update":"1176737599", "numofapproved":"1", "id":"982"}, +{"last_update":"1171465517", "numofapproved":"1", "id":"50"}, +{"last_update":"1171924670", "numofapproved":"1", "id":"107"}, +{"last_update":"1173880505", "numofapproved":"1", "id":"317"}, +{"last_update":"1173889350", "numofapproved":"1", "id":"329"}, +{"last_update":"1173889557", "numofapproved":"1", "id":"332"}, +{"last_update":"1176391285", "numofapproved":"1", "id":"892"}, +{"last_update":"1176673529", "numofapproved":"1", "id":"981"}, +{"last_update":"1171643442", "numofapproved":"1", "id":"69"}, +{"last_update":"1172226841", "numofapproved":"1", "id":"182"}, +{"last_update":"1174899475", "numofapproved":"1", "id":"506"}, +{"last_update":"1174915327", "numofapproved":"1", "id":"521"}, +{"last_update":"1176194461", "numofapproved":"1", "id":"821"}, +{"last_update":"1172013837", "numofapproved":"1", "id":"132"}, +{"last_update":"1172184974", "numofapproved":"1", "id":"177"}, +{"last_update":"1175777908", "numofapproved":"1", "id":"674"}, +{"last_update":"1173460745", "numofapproved":"1", "id":"281"}, +{"last_update":"1174401746", "numofapproved":"1", "id":"402"}, +{"last_update":"1171274691", "numofapproved":"1", "id":"5"}, +{"last_update":"1171799314", "numofapproved":"1", "id":"78"}, +{"last_update":"1171979089", "numofapproved":"1", "id":"127"}, +{"last_update":"1172503571", "numofapproved":"1", "id":"197"}, +{"last_update":"1174301365", "numofapproved":"1", "id":"391"}, +{"last_update":"1174301259", "numofapproved":"1", "id":"385"}, +{"last_update":"1174899163", "numofapproved":"1", "id":"494"}, +{"last_update":"1174933167", "numofapproved":"1", "id":"534"}, +{"last_update":"1176139704", "numofapproved":"1", "id":"808"}, +{"last_update":"1175502855", "numofapproved":"1", "id":"603"}, +{"last_update":"1173721122", "numofapproved":"1", "id":"303"}, +{"last_update":"1173809079", "numofapproved":"1", "id":"311"}, +{"last_update":"1174734352", "numofapproved":"1", "id":"461"}, +{"last_update":"1174898917", "numofapproved":"1", "id":"482"}, +{"last_update":"1174899374", "numofapproved":"1", "id":"503"}, +{"last_update":"1176392495", "numofapproved":"1", "id":"903"}, +{"last_update":"1176829535", "numofapproved":"1", "id":"987"}, +{"last_update":"1173889385", "numofapproved":"1", "id":"330"}, +{"last_update":"1175869070", "numofapproved":"1", "id":"783"}, +{"last_update":"1177510634", "numofapproved":"1", "id":"1042"}, +{"last_update":"1177585810", "numofapproved":"1", "id":"1062"}, +{"last_update":"1178648303", "numofapproved":"1", "id":"1309"}, +{"last_update":"1178883682", "numofapproved":"1", "id":"1363"}, +{"last_update":"1179239792", "numofapproved":"1", "id":"1402"}, +{"last_update":"1179997715", "numofapproved":"1", "id":"1644"}, +{"last_update":"1180031289", "numofapproved":"1", "id":"1654"}, +{"last_update":"1180440758", "numofapproved":"1", "id":"1921"}, +{"last_update":"1180972413", "numofapproved":"1", "id":"2221"}, +{"last_update":"1181032741", "numofapproved":"1", "id":"2261"}, +{"last_update":"1181198104", "numofapproved":"1", "id":"2401"}, +{"last_update":"1181237541", "numofapproved":"1", "id":"2581"}, +{"last_update":"1181293731", "numofapproved":"1", "id":"2641"}, +{"last_update":"1182231158", "numofapproved":"1", "id":"3204"}, +{"last_update":"1177668412", "numofapproved":"1", "id":"1121"}, +{"last_update":"1178713554", "numofapproved":"1", "id":"1342"}, +{"last_update":"1179239886", "numofapproved":"1", "id":"1404"}, +{"last_update":"1184766561", "numofapproved":"1", "id":"4961"}, +{"last_update":"1185293883", "numofapproved":"1", "id":"5341"}, +{"last_update":"1185781181", "numofapproved":"1", "id":"5761"}, +{"last_update":"1185898126", "numofapproved":"1", "id":"5862"}, +{"last_update":"1186290486", "numofapproved":"1", "id":"6164"}, +{"last_update":"1186260193", "numofapproved":"1", "id":"6162"}, +{"last_update":"1186305362", "numofapproved":"1", "id":"6201"}, +{"last_update":"1187024035", "numofapproved":"1", "id":"6563"}, +{"last_update":"1187245873", "numofapproved":"1", "id":"6761"}, +{"last_update":"1187765176", "numofapproved":"1", "id":"7142"}, +{"last_update":"1187872548", "numofapproved":"1", "id":"7343"}, +{"last_update":"1188774634", "numofapproved":"1", "id":"8061"}, +{"last_update":"1188838929", "numofapproved":"1", "id":"8181"}, +{"last_update":"1189608461", "numofapproved":"1", "id":"8881"}, +{"last_update":"1189667694", "numofapproved":"1", "id":"8921"}, +{"last_update":"1179747423", "numofapproved":"1", "id":"1541"}, +{"last_update":"1181142187", "numofapproved":"1", "id":"2381"}, +{"last_update":"1185965227", "numofapproved":"1", "id":"5921"}, +{"last_update":"1190476977", "numofapproved":"1", "id":"9761"}, +{"last_update":"1190648889", "numofapproved":"1", "id":"9961"}, +{"last_update":"1190824195", "numofapproved":"1", "id":"10381"}, +{"last_update":"1190825530", "numofapproved":"1", "id":"10401"}, +{"last_update":"1190894398", "numofapproved":"1", "id":"10501"}, +{"last_update":"1178271031", "numofapproved":"1", "id":"1242"}, +{"last_update":"1178878052", "numofapproved":"1", "id":"1359"}, +{"last_update":"1178967516", "numofapproved":"1", "id":"1364"}, +{"last_update":"1180018261", "numofapproved":"1", "id":"1652"}, +{"last_update":"1180107922", "numofapproved":"1", "id":"1841"}, +{"last_update":"1180514196", "numofapproved":"1", "id":"1941"}, +{"last_update":"1181901023", "numofapproved":"1", "id":"3082"}, +{"last_update":"1182417878", "numofapproved":"1", "id":"3361"}, +{"last_update":"1182785340", "numofapproved":"1", "id":"3521"}, +{"last_update":"1183485766", "numofapproved":"1", "id":"4101"}, +{"last_update":"1189526136", "numofapproved":"1", "id":"8803"}, +{"last_update":"1191446636", "numofapproved":"1", "id":"11185"}, +{"last_update":"1191489743", "numofapproved":"1", "id":"11241"}, +{"last_update":"1191903141", "numofapproved":"1", "id":"11882"}, +{"last_update":"1191940049", "numofapproved":"1", "id":"11941"}, +{"last_update":"1179239857", "numofapproved":"1", "id":"1403"}, +{"last_update":"1185799202", "numofapproved":"1", "id":"5801"}, +{"last_update":"1190924823", "numofapproved":"1", "id":"10562"}, +{"last_update":"1191410783", "numofapproved":"1", "id":"11065"}, +{"last_update":"1192031578", "numofapproved":"1", "id":"12121"}, +{"last_update":"1192431234", "numofapproved":"1", "id":"12562"}, +{"last_update":"1192609228", "numofapproved":"1", "id":"12802"}, +{"last_update":"1192742243", "numofapproved":"1", "id":"13161"}, +{"last_update":"1192942532", "numofapproved":"1", "id":"13201"}, +{"last_update":"1193386303", "numofapproved":"1", "id":"13962"}, +{"last_update":"1193406158", "numofapproved":"1", "id":"14121"}, +{"last_update":"1193418273", "numofapproved":"1", "id":"14201"}, +{"last_update":"1193519213", "numofapproved":"1", "id":"14281"}, +{"last_update":"1193666593", "numofapproved":"1", "id":"14401"}, +{"last_update":"1193733296", "numofapproved":"1", "id":"14421"}, +{"last_update":"1193760981", "numofapproved":"1", "id":"14481"}, +{"last_update":"1182436569", "numofapproved":"1", "id":"3422"}, +{"last_update":"1184012598", "numofapproved":"1", "id":"4481"}, +{"last_update":"1189715279", "numofapproved":"1", "id":"8981"}, +{"last_update":"1192528903", "numofapproved":"1", "id":"12701"}, +{"last_update":"1194246273", "numofapproved":"1", "id":"14901"}, +{"last_update":"1194354217", "numofapproved":"1", "id":"14888"}, +{"last_update":"1194366787", "numofapproved":"1", "id":"14891"}, +{"last_update":"1194445768", "numofapproved":"1", "id":"15104"}, +{"last_update":"1194467580", "numofapproved":"1", "id":"15107"}, +{"last_update":"1194508237", "numofapproved":"1", "id":"15262"}, +{"last_update":"1194635341", "numofapproved":"1", "id":"15581"}, +{"last_update":"1194635508", "numofapproved":"1", "id":"15582"}, +{"last_update":"1179214538", "numofapproved":"1", "id":"1386"}, +{"last_update":"1186433530", "numofapproved":"1", "id":"6167"}, +{"last_update":"1187853435", "numofapproved":"1", "id":"7321"}, +{"last_update":"1187972012", "numofapproved":"1", "id":"7421"}, +{"last_update":"1188895906", "numofapproved":"1", "id":"8201"}, +{"last_update":"1190284020", "numofapproved":"1", "id":"9561"}, +{"last_update":"1190924163", "numofapproved":"1", "id":"10561"}, +{"last_update":"1192529770", "numofapproved":"1", "id":"12663"}, +{"last_update":"1192536538", "numofapproved":"1", "id":"12666"}, +{"last_update":"1193269090", "numofapproved":"1", "id":"13741"}, +{"last_update":"1193428819", "numofapproved":"1", "id":"14221"}, +{"last_update":"1193860091", "numofapproved":"1", "id":"14521"}, +{"last_update":"1193909426", "numofapproved":"1", "id":"14526"}, +{"last_update":"1194533708", "numofapproved":"1", "id":"15321"}, +{"last_update":"1179822723", "numofapproved":"1", "id":"1601"}, +{"last_update":"1179842248", "numofapproved":"1", "id":"1666"}, +{"last_update":"1182412362", "numofapproved":"1", "id":"3352"}, +{"last_update":"1185980065", "numofapproved":"1", "id":"5961"}, +{"last_update":"1186751100", "numofapproved":"1", "id":"6385"}, +{"last_update":"1187202714", "numofapproved":"1", "id":"6721"}, +{"last_update":"1187601864", "numofapproved":"1", "id":"6923"}, +{"last_update":"1191490727", "numofapproved":"1", "id":"11281"}, +{"last_update":"1194449840", "numofapproved":"1", "id":"15161"}, +{"last_update":"1180028166", "numofapproved":"1", "id":"1781"}, +{"last_update":"1185025939", "numofapproved":"1", "id":"5201"}, +{"last_update":"1192454400", "numofapproved":"1", "id":"12621"}, +{"last_update":"1193414234", "numofapproved":"1", "id":"14141"}, +{"last_update":"1194270682", "numofapproved":"1", "id":"14961"}, +{"last_update":"1184061669", "numofapproved":"1", "id":"4561"}, +{"last_update":"1186161284", "numofapproved":"1", "id":"6141"}, +{"last_update":"1187714492", "numofapproved":"1", "id":"7061"}, +{"last_update":"1187893562", "numofapproved":"1", "id":"7361"}, +{"last_update":"1190815311", "numofapproved":"1", "id":"10301"}, +{"last_update":"1193388120", "numofapproved":"1", "id":"13951"}, +{"last_update":"1195239956", "numofapproved":"1", "id":"17041"}, +{"last_update":"1179147467", "numofapproved":"1", "id":"1381"}, +{"last_update":"1182346611", "numofapproved":"1", "id":"3341"}, +{"last_update":"1184267506", "numofapproved":"1", "id":"4802"}, +{"last_update":"1192047087", "numofapproved":"1", "id":"12161"}, +{"last_update":"1192198948", "numofapproved":"1", "id":"12441"}, +{"last_update":"1193208717", "numofapproved":"1", "id":"13528"}, +{"last_update":"1194907182", "numofapproved":"1", "id":"16001"}, +{"last_update":"1179153020", "numofapproved":"1", "id":"1385"}, +{"last_update":"1179835655", "numofapproved":"1", "id":"1641"}, +{"last_update":"1181234739", "numofapproved":"1", "id":"2542"}, +{"last_update":"1182356477", "numofapproved":"1", "id":"3343"}, +{"last_update":"1182418583", "numofapproved":"1", "id":"3381"}, +{"last_update":"1184568502", "numofapproved":"1", "id":"4905"}, +{"last_update":"1189151603", "numofapproved":"1", "id":"8581"}, +{"last_update":"1191595695", "numofapproved":"1", "id":"11621"}, +{"last_update":"1193105000", "numofapproved":"1", "id":"13421"}, +{"last_update":"1195104657", "numofapproved":"1", "id":"16701"}], +"request_timestamp":1206363392.08521, "request_call":"requestDetails", +"instance":"tbedi", "call_time":"0.10059", "request_date":"2008-03-2412:56:32 UTC", "request_url":"http://cmsdoc.cern.ch/cms/test/aprom/phedex/dev/gowri/datasvc/tbedi/requestDetails?format=json"}} +""" + +from jsonParser import jsonObject + +data = jsonObject.parseString(s) + +#~ from pprint import pprint +#~ pprint( data[0].asList() ) +#~ print +#~ print data.dump() +print(data.phedex.call_time) +print(data.phedex.instance) +print(data.phedex.request_call) +print(len(data.phedex.request)) +for req in data.phedex.request[:10]: + #~ print req.dump() + print("-", req.id, req.last_update) + +from io import StringIO +TEMPLATES = {} +TEMPLATES['long'] = """ +{{- start.plan_type }} ['{{ start.uid[:6] }}'] (scan num: {{ start.scan_id }}) + +Scan Plan +--------- +{{ start.plan_type }} +{%- for k, v in start.plan_args | dictsort %} + {{ k }}: {{ v }} +{%- endfor %} + +{% if 'signature' in start -%} +Call: + {{ start.signature }} +{% endif %} +Metaadata +--------- +{% for k, v in start.items() -%} +{%- if k not in ['plan_type', 'plan_args'] -%}{{ k }} : {{ v }} +{% endif -%} +{%- endfor -%}""" +TEMPLATES['desc'] = """ +{{- start.plan_type }} ['{{ start.uid[:6] }}'] (scan num: {{ start.scan_id }})""" +TEMPLATES['call'] = """RE({{ start.plan_type }}( +{%- for k, v in start.plan_args.items() %}{%- if not loop.first %} {% endif %}{{ k }}={{ v }} +{%- if not loop.last %}, +{% endif %}{% endfor %})) +""" + +def logbook_cb_factory(logbook_func, desc_template=None, long_template=None): + """Create a logbook run_start callback + + The returned function is suitable for registering as + a 'start' callback on the the BlueSky run engine. + + Parameters + ---------- + + logbook_func : callable + The required signature is :: + + def logbok_func(text=None, logbooks=None, tags=None, properties=None, + attachments=None, verify=True, ensure=False): + ''' + + Parameters + ---------- + text : string + The body of the log entry. + logbooks : string or list of strings + The logbooks which to add the log entry to. + tags : string or list of strings + The tags to add to the log entry. + properties : dict of property dicts + The properties to add to the log entry + attachments : list of file like objects + The attachments to add to the log entry + verify : bool + Check that properties, tags and logbooks are in the Olog + instance. + ensure : bool + If a property, tag or logbook is not in the Olog then + create the property, tag or logbook before making the log +s entry. Seting ensure to True will set verify to False. + + ''' + pass + + This matches the API on `SimpleOlogClient.log` + + """ + import jinja2 + env = jinja2.Environment() + if long_template is None: + long_template = TEMPLATES['long'] + if desc_template is None: + desc_template = TEMPLATES['desc'] + # It seems that the olog only has one text field, which it calls + # `text` on the python side and 'description' on the olog side. + # There are some CSS applications that try to shove the entire + # thing into a single line. We work around this by doing two + # strings, a long one which will get put in a as an attachment + # and a short one to go in as the 'text' which will be used as the + # description + long_msg = env.from_string(long_template) + desc_msg = env.from_string(desc_template) + + def lbcb(name, doc): + # This only applies to 'start' Documents. + if name != 'start': + return + + atch = StringIO(long_msg.render(start=doc)) + desc = desc_msg.render(start=doc) + logbook_func(text=desc, properties={'start':doc}, + attachments=[atch], + ensure=True) + return lbcb + +def call_str(start, call_template=None): + """Given a start document generate an evalable call scring + + The default template assumes that `plan_args` and `plan_type` + are at the top level of the document. + + Parameter + --------- + start : dict + A document which follows the runstart schema + + call_template : str, optional + A jinja2 template rendered with `cr.render(start=start)` + + If not provided defaults to `CALL_TEMPLATE` + """ + import jinja2 + env = jinja2.Environment() + if call_template is None: + call_template = TEMPLATES['call'] + call_renderer = env.from_string(call_template) + return call_renderer.render(start=start) + +from __future__ import division, absolute_import, print_function + +from subprocess import call, PIPE, Popen +import sys +import re + +import numpy as np +from numpy.linalg import lapack_lite +from numpy.testing import TestCase, dec + +from numpy.compat import asbytes_nested + +class FindDependenciesLdd(object): + def __init__(self): + self.cmd = ['ldd'] + + try: + p = Popen(self.cmd, stdout=PIPE, stderr=PIPE) + stdout, stderr = p.communicate() + except OSError: + raise RuntimeError("command %s cannot be run" % self.cmd) + + def get_dependencies(self, lfile): + p = Popen(self.cmd + [lfile], stdout=PIPE, stderr=PIPE) + stdout, stderr = p.communicate() + if not (p.returncode == 0): + raise RuntimeError("failed dependencies check for %s" % lfile) + + return stdout + + def grep_dependencies(self, lfile, deps): + stdout = self.get_dependencies(lfile) + + rdeps = dict([(dep, re.compile(dep)) for dep in deps]) + founds = [] + for l in stdout.splitlines(): + for k, v in rdeps.items(): + if v.search(l): + founds.append(k) + + return founds + +class TestF77Mismatch(TestCase): + @dec.skipif(not(sys.platform[:5] == 'linux'), + "Skipping fortran compiler mismatch on non Linux platform") + def test_lapack(self): + f = FindDependenciesLdd() + deps = f.grep_dependencies(lapack_lite.__file__, + asbytes_nested(['libg2c', 'libgfortran'])) + self.assertFalse(len(deps) > 1, +"""Both g77 and gfortran runtimes linked in lapack_lite ! This is likely to +cause random crashes and wrong results. See numpy INSTALL.txt for more +information.""") + +import logging +from unittest import TestResult + +logger = logging.getLogger(__name__) + + +class CustomTestReport(TestResult): + + def __init__(self, change_callback=None): + super(CustomTestReport, self).__init__() + logger.debug('__init__') + self.running = False + self.change_callback = change_callback + self.success = 0 + + def startTest(self, test): + super(CustomTestReport, self).startTest(test) + logger.debug('startTest') + self.running = True + if self.change_callback: + self.change_callback({ + "errors": len(self.errors), + "failures": len(self.failures), + "skipped": len(self.skipped), + "expectedFailures": len(self.expectedFailures), + "unexpectedSuccesses": len(self.unexpectedSuccesses), + "testsRun": self.testsRun, + "success": self.success + }) + + def stopTest(self, test): + super(CustomTestReport, self).stopTest(test) + logger.debug("stopTest %s", test) + self.running = False + + def startTestRun(self): + super(CustomTestReport, self).startTestRun() + logger.debug("startTestRun") + self.running = True + + def stopTestRun(self): + super(CustomTestReport, self).stopTestRun() + logger.debug("stopTestRun") + self.running = False + + def addError(self, test, err): + super(CustomTestReport, self).addError(test, err) + logger.debug("[E] %s %s", test, err) + + def addFailure(self, test, err): + super(CustomTestReport, self).addFailure(test, err) + logger.debug("[F] %s %s", test, err) + + def addSuccess(self, test): + super(CustomTestReport, self).addSuccess(test) + logger.debug("[S] %s", test) + self.success += 1 + + def addSkip(self, test, reason): + super(CustomTestReport, self).addSkip(test, reason) + logger.debug("[s] %s %s", test, reason) + + def addExpectedFailure(self, test, err): + super(CustomTestReport, self).addExpectedFailure(test, err) + logger.debug("[EF] %s %s", test, err) + + def addUnexpectedSuccess(self, test): + super(CustomTestReport, self).addUnexpectedSuccess(test) + logger.debug("[US] %s", test) + + def addSubTest(self, test, subtest, outcome): + super(CustomTestReport, self).addSubTest(test, subtest, outcome) + logger.debug("[ST] %s %s %s", test, subtest, outcome) + +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +# pylint: disable=protected-access +"""Recurrent layers. +""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import numpy as np + +from tensorflow.python.framework import tensor_shape +from tensorflow.python.keras._impl.keras import activations +from tensorflow.python.keras._impl.keras import backend as K +from tensorflow.python.keras._impl.keras import constraints +from tensorflow.python.keras._impl.keras import initializers +from tensorflow.python.keras._impl.keras import regularizers +from tensorflow.python.keras._impl.keras.engine import InputSpec +from tensorflow.python.keras._impl.keras.engine import Layer + + +# pylint: disable=access-member-before-definition + + +def _time_distributed_dense(x, + w, + b=None, + dropout=None, + input_dim=None, + output_dim=None, + timesteps=None, + training=None): + """Apply `y . w + b` for every temporal slice y of x. + + Arguments: + x: input tensor. + w: weight matrix. + b: optional bias vector. + dropout: whether to apply dropout (same dropout mask + for every temporal slice of the input). + input_dim: integer; optional dimensionality of the input. + output_dim: integer; optional dimensionality of the output. + timesteps: integer; optional number of timesteps. + training: training phase tensor or boolean. + + Returns: + Output tensor. + """ + if not input_dim: + input_dim = K.shape(x)[2] + if not timesteps: + timesteps = K.shape(x)[1] + if not output_dim: + output_dim = K.shape(w)[1] + + if dropout is not None and 0. < dropout < 1.: + # apply the same dropout pattern at every timestep + ones = K.ones_like(K.reshape(x[:, 0, :], (-1, input_dim))) + dropout_matrix = K.dropout(ones, dropout) + expanded_dropout_matrix = K.repeat(dropout_matrix, timesteps) + x = K.in_train_phase(x * expanded_dropout_matrix, x, training=training) + + # collapse time dimension and batch dimension together + x = K.reshape(x, (-1, input_dim)) + x = K.dot(x, w) + if b is not None: + x = K.bias_add(x, b) + # reshape to 3D tensor + if K.backend() == 'tensorflow': + x = K.reshape(x, K.stack([-1, timesteps, output_dim])) + x.set_shape([None, None, output_dim]) + else: + x = K.reshape(x, (-1, timesteps, output_dim)) + return x + + +class Recurrent(Layer): + """Abstract base class for recurrent layers. + + Do not use in a model -- it's not a valid layer! + Use its children classes `LSTM`, `GRU` and `SimpleRNN` instead. + + All recurrent layers (`LSTM`, `GRU`, `SimpleRNN`) also + follow the specifications of this class and accept + the keyword arguments listed below. + + Example: + + ```python + # as the first layer in a Sequential model + model = Sequential() + model.add(LSTM(32, input_shape=(10, 64))) + # now model.output_shape == (None, 32) + # note: `None` is the batch dimension. + + # for subsequent layers, no need to specify the input size: + model.add(LSTM(16)) + + # to stack recurrent layers, you must use return_sequences=True + # on any recurrent layer that feeds into another recurrent layer. + # note that you only need to specify the input size on the first layer. + model = Sequential() + model.add(LSTM(64, input_dim=64, input_length=10, return_sequences=True)) + model.add(LSTM(32, return_sequences=True)) + model.add(LSTM(10)) + ``` + + Arguments: + weights: list of Numpy arrays to set as initial weights. + The list should have 3 elements, of shapes: + `[(input_dim, output_dim), (output_dim, output_dim), (output_dim,)]`. + return_sequences: Boolean. Whether to return the last output + in the output sequence, or the full sequence. + return_state: Boolean. Whether to return the last state + in addition to the output. + go_backwards: Boolean (default False). + If True, process the input sequence backwards and return the + reversed sequence. + stateful: Boolean (default False). If True, the last state + for each sample at index i in a batch will be used as initial + state for the sample of index i in the following batch. + unroll: Boolean (default False). + If True, the network will be unrolled, + else a symbolic loop will be used. + Unrolling can speed-up a RNN, + although it tends to be more memory-intensive. + Unrolling is only suitable for short sequences. + implementation: one of {0, 1, or 2}. + If set to 0, the RNN will use + an implementation that uses fewer, larger matrix products, + thus running faster on CPU but consuming more memory. + If set to 1, the RNN will use more matrix products, + but smaller ones, thus running slower + (may actually be faster on GPU) while consuming less memory. + If set to 2 (LSTM/GRU only), + the RNN will combine the input gate, + the forget gate and the output gate into a single matrix, + enabling more time-efficient parallelization on the GPU. + Note: RNN dropout must be shared for all gates, + resulting in a slightly reduced regularization. + input_dim: dimensionality of the input (integer). + This argument (or alternatively, the keyword argument `input_shape`) + is required when using this layer as the first layer in a model. + input_length: Length of input sequences, to be specified + when it is constant. + This argument is required if you are going to connect + `Flatten` then `Dense` layers upstream + (without it, the shape of the dense outputs cannot be computed). + Note that if the recurrent layer is not the first layer + in your model, you would need to specify the input length + at the level of the first layer + (e.g. via the `input_shape` argument) + + Input shape:s + 3D tensor with shape `(batch_size, timesteps, input_dim)`, + (Optional) 2D tensors with shape `(batch_size, output_dim)`. + + Output shape: + - if `return_state`: a list of tensors. The first tensor is + the output. The remaining tensors are the last states, + each with shape `(batch_size, units)`. + - if `return_sequences`: 3D tensor with shape + `(batch_size, timesteps, units)`. + - else, 2D tensor with shape `(batch_size, units)`. + + # Masking + This layer supports masking for input data with a variable number + of timesteps. To introduce masks to your data, + use an `Embedding` layer with the `mask_zero` parameter + set to `True`. + + # Note on using statefulness in RNNs + You can set RNN layers to be 'stateful', which means that the states + computed for the samples in one batch will be reused as initial states + for the samples in the next batch. This assumes a one-to-one mapping + between samples in different successive batches. + + To enable statefulness: + - specify `stateful=True` in the layer constructor. + - specify a fixed batch size for your model, by passing + if sequential model: + `batch_input_shape=(...)` to the first layer in your model. + else for functional model with 1 or more Input layers: + `batch_shape=(...)` to all the first layers in your model. + This is the expected shape of your inputs + *including the batch size*. + It should be a tuple of integers, e.g. `(32, 10, 100)`. + - specify `shuffle=False` when calling fit(). + + To reset the states of your model, call `.reset_states()` on either + a specific layer, or on your entire model. + + # Note on specifying the initial state of RNNs + You can specify the initial state of RNN layers symbolically by + calling them with the keyword argument `initial_state`. The value of + `initial_state` should be a tensor or list of tensors representing + the initial state of the RNN layer. + + You can specify the initial state of RNN layers numerically by + calling `reset_states` with the keyword argument `states`. The value of + `states` should be a numpy array or list of numpy arrays representing + the initial state of the RNN layer. + """ + + def __init__(self, + return_sequences=False, + return_state=False, + go_backwards=False, + stateful=False, + unroll=False, + implementation=0, + **kwargs): + super(Recurrent, self).__init__(**kwargs) + self.return_sequences = return_sequences + self.return_state = return_state + self.go_backwards = go_backwards + self.stateful = stateful + self.unroll = unroll + self.implementation = implementation + self.supports_masking = True + self.input_spec = [InputSpec(ndim=3)] + self.state_spec = None + self.dropout = 0 + self.recurrent_dropout = 0 + + def _compute_output_shape(self, input_shape): + if isinstance(input_shape, list): + input_shape = input_shape[0] + input_shape = tensor_shape.TensorShape(input_shape).as_list() + if self.return_sequences: + output_shape = (input_shape[0], input_shape[1], self.units) + else: + output_shape = (input_shape[0], self.units) + + if self.return_state: + state_shape = [tensor_shape.TensorShape( + (input_shape[0], self.units)) for _ in self.states] + return [tensor_shape.TensorShape(output_shape)] + state_shape + return tensor_shape.TensorShape(output_shape) + + def compute_mask(self, inputs, mask): + if isinstance(mask, list): + mask = mask[0] + output_mask = mask if self.return_sequences else None + if self.return_state: + state_mask = [None for _ in self.states] + return [output_mask] + state_mask + return output_mask + + def step(self, inputs, states): + raise NotImplementedError + + def get_constants(self, inputs, training=None): + return [] + + def get_initial_state(self, inputs): + # build an all-zero tensor of shape (samples, output_dim) + initial_state = K.zeros_like(inputs) # (samples, timesteps, input_dim) + initial_state = K.sum(initial_state, axis=(1, 2)) # (samples,) + initial_state = K.expand_dims(initial_state) # (samples, 1) + initial_state = K.tile(initial_state, [1, + self.units]) # (samples, output_dim) + initial_state = [initial_state for _ in range(len(self.states))] + return initial_state + + def preprocess_input(self, inputs, training=None): + return inputs + + def __call__(self, inputs, initial_state=None, **kwargs): + if (isinstance(inputs, (list, tuple)) and + len(inputs) > 1 + and initial_state is None): + initial_state = inputs[1:] + inputs = inputs[0] + + # If `initial_state` is specified, + # and if it a Keras tensor, + # then add it to the inputs and temporarily + # modify the input spec to include the state. + if initial_state is None: + return super(Recurrent, self).__call__(inputs, **kwargs) + + if not isinstance(initial_state, (list, tuple)): + initial_state = [initial_state] + + is_keras_tensor = hasattr(initial_state[0], '_keras_history') + for tensor in initial_state: + if hasattr(tensor, '_keras_history') != is_keras_tensor: + raise ValueError('The initial state of an RNN layer cannot be' + ' specified with a mix of Keras tensors and' + ' non-Keras tensors') + + if is_keras_tensor: + # Compute the full input spec, including state + input_spec = self.input_spec + state_spec = self.state_spec + if not isinstance(input_spec, list): + input_spec = [input_spec] + if not isinstance(state_spec, list): + state_spec = [state_spec] + self.input_spec = input_spec + state_spec + + # Compute the full inputs, including state + inputs = [inputs] + list(initial_state) + + # Perform the call + output = super(Recurrent, self).__call__(inputs, **kwargs) + + # Restore original input spec + self.input_spec = input_spec + return output + else: + kwargs['initial_state'] = initial_state + return super(Recurrent, self).__call__(inputs, **kwargs) + + def call(self, inputs, mask=None, training=None, initial_state=None): + # input shape: `(samples, time (padded with zeros), input_dim)` + # note that the .build() method of subclasses MUST define + # self.input_spec and self.state_spec with complete input shapes. + if isinstance(inputs, list): + initial_state = inputs[1:] + inputs = inputs[0] + elif initial_state is not None: + pass + elif self.stateful: + initial_state = self.states + else: + initial_state = self.get_initial_state(inputs) + + if isinstance(mask, list): + mask = mask[0] + + if len(initial_state) != len(self.states): + raise ValueError('Layer has ' + str(len(self.states)) + + ' states but was passed ' + str(len(initial_state)) + + ' initial states.') + input_shape = K.int_shape(inputs) + if self.unroll and input_shape[1] is None: + raise ValueError('Cannot unroll a RNN if the ' + 'time dimension is undefined. \n' + '- If using a Sequential model, ' + 'specify the time dimension by passing ' + 'an `input_shape` or `batch_input_shape` ' + 'argument to your first layer. If your ' + 'first layer is an Embedding, you can ' + 'also use the `input_length` argument.\n' + '- If using the functional API, specify ' + 'the time dimension by passing a `shape` ' + 'or `batch_shape` argument to your Input layer.') + constants = self.get_constants(inputs, training=None) + preprocessed_input = self.preprocess_input(inputs, training=None) + last_output, outputs, states = K.rnn( + self.step, + preprocessed_input, + initial_state, + go_backwards=self.go_backwards, + mask=mask, + constants=constants, + unroll=self.unroll) + if self.stateful: + updates = [] + for i in range(len(states)): + updates.append((self.states[i], states[i])) + self.add_update(updates, inputs) + + # Properly set learning phase + if 0 < self.dropout + self.recurrent_dropout: + last_output._uses_learning_phase = True + outputs._uses_learning_phase = True + + if not self.return_sequences: + outputs = last_output + + if self.return_state: + if not isinstance(states, (list, tuple)): + states = [states] + else: + states = list(states) + return [outputs] + states + return outputs + + def reset_states(self, states=None): + if not self.stateful: + raise AttributeError('Layer must be stateful.') + batch_size = self.input_spec[0].shape[0] + if not batch_size: + raise ValueError('If a RNN is stateful, it needs to know ' + 'its batch size. Specify the batch size ' + 'of your input tensors: \n' + '- If using a Sequential model, ' + 'specify the batch size by passing ' + 'a `batch_input_shape` ' + 'argument to your first layer.\n' + '- If using the functional API, specify ' + 'the time dimension by passing a ' + '`batch_shape` argument to your Input layer.') + # initialize state if None + if self.states[0] is None: + self.states = [K.zeros((batch_size, self.units)) for _ in self.states] + elif states is None: + for state in self.states: + K.set_value(state, np.zeros((batch_size, self.units))) + else: + if not isinstance(states, (list, tuple)): + states = [states] + if len(states) != len(self.states): + raise ValueError('Layer ' + self.name + ' expects ' + + str(len(self.states)) + ' states, ' + 'but it received ' + str(len(states)) + + ' state values. Input received: ' + str(states)) + for index, (value, state) in enumerate(zip(states, self.states)): + if value.shape != (batch_size, self.units): + raise ValueError('State ' + str(index) + + ' is incompatible with layer ' + self.name + + ': expected shape=' + str((batch_size, self.units)) + + ', found shape=' + str(value.shape)) + K.set_value(state, value) + + def get_config(self): + config = { + 'return_sequences': self.return_sequences, + 'return_state': self.return_state, + 'go_backwards': self.go_backwards, + 'stateful': self.stateful, + 'unroll': self.unroll, + 'implementation': self.implementation + } + base_config = super(Recurrent, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +class SimpleRNN(Recurrent): + """Fully-connected RNN where the output is to be fed back to input. + + Arguments: + units: Positive integer, dimensionality of the output space. + activation: Activation function to use. + If you don't specify anything, no activation is applied + If you pass None, no activation is applied + (ie. "linear" activation: `a(x) = x`). + use_bias: Boolean, whether the layer uses a bias vector. + kernel_initializer: Initializer for the `kernel` weights matrix, + used for the linear transformation of the inputs.. + recurrent_initializer: Initializer for the `recurrent_kernel` + weights matrix, + used for the linear transformation of the recurrent state.. + bias_initializer: Initializer for the bias vector. + kernel_regularizer: Regularizer function applied to + the `kernel` weights matrix. + recurrent_regularizer: Regularizer function applied to + the `recurrent_kernel` weights matrix. + bias_regularizer: Regularizer function applied to the bias vector. + activity_regularizer: Regularizer function applied to + the output of the layer (its "activation").. + kernel_constraint: Constraint function applied to + the `kernel` weights matrix. + recurrent_constraint: Constraint function applied to + the `recurrent_kernel` weights matrix. + bias_constraint: Constraint function applied to the bias vector. + dropout: Float between 0 and 1. + Fraction of the units to drop for + the linear transformation of the inputs. + recurrent_dropout: Float between 0 and 1. + Fraction of the units to drop for + the linear transformation of the recurrent state. + + References: + - [A Theoretically Grounded Application of Dropout in Recurrent Neural + Networks](http://arxiv.org/abs/1512.05287) + """ + + def __init__(self, + units, + activation='tanh', + use_bias=True, + kernel_initializer='glorot_uniform', + recurrent_initializer='orthogonal', + bias_initializer='zeros', + kernel_regularizer=None, + recurrent_regularizer=None, + bias_regularizer=None, + activity_regularizer=None, + kernel_constraint=None, + recurrent_constraint=None, + bias_constraint=None, + dropout=0., + recurrent_dropout=0., + **kwargs): + super(SimpleRNN, self).__init__(**kwargs) + self.units = units + self.activation = activations.get(activation) + self.use_bias = use_bias + + self.kernel_initializer = initializers.get(kernel_initializer) + self.recurrent_initializer = initializers.get(recurrent_initializer) + self.bias_initializer = initializers.get(bias_initializer) + + self.kernel_regularizer = regularizers.get(kernel_regularizer) + self.recurrent_regularizer = regularizers.get(recurrent_regularizer) + self.bias_regularizer = regularizers.get(bias_regularizer) + self.activity_regularizer = regularizers.get(activity_regularizer) + + self.kernel_constraint = constraints.get(kernel_constraint) + self.recurrent_constraint = constraints.get(recurrent_constraint) + self.bias_constraint = constraints.get(bias_constraint) + + self.dropout = min(1., max(0., dropout)) + self.recurrent_dropout = min(1., max(0., recurrent_dropout)) + self.state_spec = InputSpec(shape=(None, self.units)) + + def build(self, input_shape): + if isinstance(input_shape, list): + input_shape = input_shape[0] + input_shape = tensor_shape.TensorShape(input_shape).as_list() + + batch_size = input_shape[0] if self.stateful else None + self.input_dim = input_shape[2] + self.input_spec[0] = InputSpec(shape=(batch_size, None, self.input_dim)) + + self.states = [None] + if self.stateful: + self.reset_states() + + self.kernel = self.add_weight( + shape=(self.input_dim, self.units), + name='kernel', + initializer=self.kernel_initializer, + regularizer=self.kernel_regularizer, + constraint=self.kernel_constraint) + self.recurrent_kernel = self.add_weight( + shape=(self.units, self.units), + name='recurrent_kernel', + initializer=self.recurrent_initializer, + regularizer=self.recurrent_regularizer, + constraint=self.recurrent_constraint) + if self.use_bias: + self.bias = self.add_weight( + shape=(self.units,), + name='bias', + initializer=self.bias_initializer, + regularizer=self.bias_regularizer, + constraint=self.bias_constraint) + else: + self.bias = None + self.built = True + + def preprocess_input(self, inputs, training=None): + if self.implementation > 0: + return inputs + else: + input_shape = inputs.get_shape().as_list() + input_dim = input_shape[2] + timesteps = input_shape[1] + return _time_distributed_dense( + inputs, + self.kernel, + self.bias, + self.dropout, + input_dim, + self.units, + timesteps, + training=training) + + def step(self, inputs, states): + if self.implementation == 0: + h = inputs + else: + if 0 < self.dropout < 1: + h = K.dot(inputs * states[1], self.kernel) + else: + h = K.dot(inputs, self.kernel) + if self.bias is not None: + h = K.bias_add(h, self.bias) + + prev_output = states[0] + if 0 < self.recurrent_dropout < 1: + prev_output *= states[2] + output = h + K.dot(prev_output, self.recurrent_kernel) + if self.activation is not None: + output = self.activation(output) + + # Properly set learning phase on output tensor. + if 0 < self.dropout + self.recurrent_dropout: + output._uses_learning_phase = True + return output, [output] + + def get_constants(self, inputs, training=None): + constants = [] + if self.implementation != 0 and 0 < self.dropout < 1: + input_shape = K.int_shape(inputs) + input_dim = input_shape[-1] + ones = K.ones_like(K.reshape(inputs[:, 0, 0], (-1, 1))) + ones = K.tile(ones, (1, int(input_dim))) + + def dropped_inputs(): + return K.dropout(ones, self.dropout) + + dp_mask = K.in_train_phase(dropped_inputs, ones, training=training) + constants.append(dp_mask) + else: + constants.append(K.cast_to_floatx(1.)) + + if 0 < self.recurrent_dropout < 1: + ones = K.ones_like(K.reshape(inputs[:, 0, 0], (-1, 1))) + ones = K.tile(ones, (1, self.units)) + + def dropped_inputs(): # pylint: disable=function-redefined + return K.dropout(ones, self.recurrent_dropout) + + rec_dp_mask = K.in_train_phase(dropped_inputs, ones, training=training) + constants.append(rec_dp_mask) + else: + constants.append(K.cast_to_floatx(1.)) + return constants + + def get_config(self): + config = { + 'units': self.units, + 'activation': activations.serialize(self.activation), + 'use_bias': self.use_bias, + 'kernel_initializer': initializers.serialize(self.kernel_initializer), + 'recurrent_initializer': + initializers.serialize(self.recurrent_initializer), + 'bias_initializer': initializers.serialize(self.bias_initializer), + 'kernel_regularizer': regularizers.serialize(self.kernel_regularizer), + 'recurrent_regularizer': + regularizers.serialize(self.recurrent_regularizer), + 'bias_regularizer': regularizers.serialize(self.bias_regularizer), + 'activity_regularizer': + regularizers.serialize(self.activity_regularizer), + 'kernel_constraint': constraints.serialize(self.kernel_constraint), + 'recurrent_constraint': + constraints.serialize(self.recurrent_constraint), + 'bias_constraint': constraints.serialize(self.bias_constraint), + 'dropout': self.dropout, + 'recurrent_dropout': self.recurrent_dropout + } + base_config = super(SimpleRNN, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +class GRU(Recurrent): + """Gated Recurrent Unit - Cho et al. + + 2014. + + Arguments: + units: Positive integer, dimensionality of the output space. + activation: Activation function to use. + If you pass None, no activation is applied + (ie. "linear" activation: `a(x) = x`). + recurrent_activation: Activation function to use + for the recurrent step. + use_bias: Boolean, whether the layer uses a bias vector. + kernel_initializer: Initializer for the `kernel` weights matrix, + used for the linear transformation of the inputs.. + recurrent_initializer: Initializer for the `recurrent_kernel` + weights matrix, + used for the linear transformation of the recurrent state.. + bias_initializer: Initializer for the bias vector. + kernel_regularizer: Regularizer function applied to + the `kernel` weights matrix. + recurrent_regularizer: Regularizer function applied to + the `recurrent_kernel` weights matrix. + bias_regularizer: Regularizer function applied to the bias vector. + activity_regularizer: Regularizer function applied to + the output of the layer (its "activation").. + kernel_constraint: Constraint function applied to + the `kernel` weights matrix. + recurrent_constraint: Constraint function applied to + the `recurrent_kernel` weights matrix. + bias_constraint: Constraint function applied to the bias vector. + dropout: Float between 0 and 1. + Fraction of the units to drop for + the linear transformation of the inputs. + recurrent_dropout: Float between 0 and 1. + Fraction of the units to drop for + the linear transformation of the recurrent state. + + References: + - [On the Properties of Neural Machine Translation: Encoder-Decoder + Approaches](https://arxiv.org/abs/1409.1259) + - [Empirical Evaluation of Gated Recurrent Neural Networks on Sequence + Modeling](http://arxiv.org/abs/1412.3555v1) + - [A Theoretically Grounded Application of Dropout in Recurrent Neural + Networks](http://arxiv.org/abs/1512.05287) + """ + + def __init__(self, + units, + activation='tanh', + recurrent_activation='hard_sigmoid', + use_bias=True, + kernel_initializer='glorot_uniform', + recurrent_initializer='orthogonal', + bias_initializer='zeros', + kernel_regularizer=None, + recurrent_regularizer=None, + bias_regularizer=None, + activity_regularizer=None, + kernel_constraint=None, + recurrent_constraint=None, + bias_constraint=None, + dropout=0., + recurrent_dropout=0., + **kwargs): + super(GRU, self).__init__(**kwargs) + self.units = units + self.activation = activations.get(activation) + self.recurrent_activation = activations.get(recurrent_activation) + self.use_bias = use_bias + + self.kernel_initializer = initializers.get(kernel_initializer) + self.recurrent_initializer = initializers.get(recurrent_initializer) + self.bias_initializer = initializers.get(bias_initializer) + + self.kernel_regularizer = regularizers.get(kernel_regularizer) + self.recurrent_regularizer = regularizers.get(recurrent_regularizer) + self.bias_regularizer = regularizers.get(bias_regularizer) + self.activity_regularizer = regularizers.get(activity_regularizer) + + self.kernel_constraint = constraints.get(kernel_constraint) + self.recurrent_constraint = constraints.get(recurrent_constraint) + self.bias_constraint = constraints.get(bias_constraint) + + self.dropout = min(1., max(0., dropout)) + self.recurrent_dropout = min(1., max(0., recurrent_dropout)) + self.state_spec = InputSpec(shape=(None, self.units)) + + def build(self, input_shape): + if isinstance(input_shape, list): + input_shape = input_shape[0] + input_shape = tensor_shape.TensorShape(input_shape).as_list() + batch_size = input_shape[0] if self.stateful else None + self.input_dim = input_shape[2] + self.input_spec[0] = InputSpec(shape=(batch_size, None, self.input_dim)) + + self.states = [None] + if self.stateful: + self.reset_states() + + self.kernel = self.add_weight( + shape=(self.input_dim, self.units * 3), + name='kernel', + initializer=self.kernel_initializer, + regularizer=self.kernel_regularizer, + constraint=self.kernel_constraint) + self.recurrent_kernel = self.add_weight( + shape=(self.units, self.units * 3), + name='recurrent_kernel', + initializer=self.recurrent_initializer, + regularizer=self.recurrent_regularizer, + constraint=self.recurrent_constraint) + + if self.use_bias: + self.bias = self.add_weight( + shape=(self.units * 3,), + name='bias', + initializer=self.bias_initializer, + regularizer=self.bias_regularizer, + constraint=self.bias_constraint) + else: + self.bias = None + + self.kernel_z = self.kernel[:, :self.units] + self.recurrent_kernel_z = self.recurrent_kernel[:, :self.units] + self.kernel_r = self.kernel[:, self.units:self.units * 2] + self.recurrent_kernel_r = self.recurrent_kernel[:, self.units: + self.units * 2] + self.kernel_h = self.kernel[:, self.units * 2:] + self.recurrent_kernel_h = self.recurrent_kernel[:, self.units * 2:] + + if self.use_bias: + self.bias_z = self.bias[:self.units] + self.bias_r = self.bias[self.units:self.units * 2] + self.bias_h = self.bias[self.units * 2:] + else: + self.bias_z = None + self.bias_r = None + self.bias_h = None + self.built = True + + def preprocess_input(self, inputs, training=None): + if self.implementation == 0: + input_shape = inputs.get_shape().as_list() + input_dim = input_shape[2] + timesteps = input_shape[1] + + x_z = _time_distributed_dense( + inputs, + self.kernel_z, + self.bias_z, + self.dropout, + input_dim, + self.units, + timesteps, + training=training) + x_r = _time_distributed_dense( + inputs, + self.kernel_r, + self.bias_r, + self.dropout, + input_dim, + self.units, + timesteps, + training=training) + x_h = _time_distributed_dense( + inputs, + self.kernel_h, + self.bias_h, + self.dropout, + input_dim, + self.units, + timesteps, + training=training) + return K.concatenate([x_z, x_r, x_h], axis=2) + else: + return inputs + + def get_constants(self, inputs, training=None): + constants = [] + if self.implementation != 0 and 0 < self.dropout < 1: + input_shape = K.int_shape(inputs) + input_dim = input_shape[-1] + ones = K.ones_like(K.reshape(inputs[:, 0, 0], (-1, 1))) + ones = K.tile(ones, (1, int(input_dim))) + + def dropped_inputs(): + return K.dropout(ones, self.dropout) + + dp_mask = [ + K.in_train_phase(dropped_inputs, ones, training=training) + for _ in range(3) + ] + constants.append(dp_mask) + else: + constants.append([K.cast_to_floatx(1.) for _ in range(3)]) + + if 0 < self.recurrent_dropout < 1: + ones = K.ones_like(K.reshape(inputs[:, 0, 0], (-1, 1))) + ones = K.tile(ones, (1, self.units)) + + def dropped_inputs(): # pylint: disable=function-redefined + return K.dropout(ones, self.recurrent_dropout) + + rec_dp_mask = [ + K.in_train_phase(dropped_inputs, ones, training=training) + for _ in range(3) + ] + constants.append(rec_dp_mask) + else: + constants.append([K.cast_to_floatx(1.) for _ in range(3)]) + return constants + + def step(self, inputs, states): + h_tm1 = states[0] # previous memory + dp_mask = states[1] # dropout matrices for recurrent units + rec_dp_mask = states[2] + + if self.implementation == 2: + matrix_x = K.dot(inputs * dp_mask[0], self.kernel) + if self.use_bias: + matrix_x = K.bias_add(matrix_x, self.bias) + matrix_inner = K.dot(h_tm1 * rec_dp_mask[0], + self.recurrent_kernel[:, :2 * self.units]) + + x_z = matrix_x[:, :self.units] + x_r = matrix_x[:, self.units:2 * self.units] + recurrent_z = matrix_inner[:, :self.units] + recurrent_r = matrix_inner[:, self.units:2 * self.units] + + z = self.recurrent_activation(x_z + recurrent_z) + r = self.recurrent_activation(x_r + recurrent_r) + + x_h = matrix_x[:, 2 * self.units:] + recurrent_h = K.dot(r * h_tm1 * rec_dp_mask[0], + self.recurrent_kernel[:, 2 * self.units:]) + hh = self.activation(x_h + recurrent_h) + else: + if self.implementation == 0: + x_z = inputs[:, :self.units] + x_r = inputs[:, self.units:2 * self.units] + x_h = inputs[:, 2 * self.units:] + elif self.implementation == 1: + x_z = K.dot(inputs * dp_mask[0], self.kernel_z) + x_r = K.dot(inputs * dp_mask[1], self.kernel_r) + x_h = K.dot(inputs * dp_mask[2], self.kernel_h) + if self.use_bias: + x_z = K.bias_add(x_z, self.bias_z) + x_r = K.bias_add(x_r, self.bias_r) + x_h = K.bias_add(x_h, self.bias_h) + else: + raise ValueError('Unknown `implementation` mode.') + z = self.recurrent_activation(x_z + K.dot(h_tm1 * rec_dp_mask[0], + self.recurrent_kernel_z)) + r = self.recurrent_activation(x_r + K.dot(h_tm1 * rec_dp_mask[1], + self.recurrent_kernel_r)) + + hh = self.activation(x_h + K.dot(r * h_tm1 * rec_dp_mask[2], + self.recurrent_kernel_h)) + h = z * h_tm1 + (1 - z) * hh + if 0 < self.dropout + self.recurrent_dropout: + h._uses_learning_phase = True + return h, [h] + + def get_config(self): + config = { + 'units': self.units, + 'activation': activations.serialize(self.activation), + 'recurrent_activation': + activations.serialize(self.recurrent_activation), + 'use_bias': self.use_bias, + 'kernel_initializer': initializers.serialize(self.kernel_initializer), + 'recurrent_initializer': + initializers.serialize(self.recurrent_initializer), + 'bias_initializer': initializers.serialize(self.bias_initializer), + 'kernel_regularizer': regularizers.serialize(self.kernel_regularizer), + 'recurrent_regularizer': + regularizers.serialize(self.recurrent_regularizer), + 'bias_regularizer': regularizers.serialize(self.bias_regularizer), + 'activity_regularizer': + regularizers.serialize(self.activity_regularizer), + 'kernel_constraint': constraints.serialize(self.kernel_constraint), + 'recurrent_constraint': + constraints.serialize(self.recurrent_constraint), + 'bias_constraint': constraints.serialize(self.bias_constraint), + 'dropout': self.dropout, + 'recurrent_dropout': self.recurrent_dropout + } + base_config = super(GRU, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +class LSTM(Recurrent): + """Long-Short Term Memory unit - Hochreiter 1997. + + For a step-by-step description of the algorithm, see + [this tutorial](http://deeplearning.net/tutorial/lstm.html). + + Arguments: + units: Positive integer, dimensionality of the output space. + activation: Activation function to use. + If you pass None, no activation is applied + (ie. "linear" activation: `a(x) = x`). + recurrent_activation: Activation function to use + for the recurrent step. + use_bias: Boolean, whether the layer uses a bias vector. + kernel_initializer: Initializer for the `kernel` weights matrix, + used for the linear transformation of the inputs.. + recurrent_initializer: Initializer for the `recurrent_kernel` + weights matrix, + used for the linear transformation of the recurrent state.. + bias_initializer: Initializer for the bias vector. + unit_forget_bias: Boolean. + If True, add 1 to the bias of the forget gate at initialization. + Setting it to true will also force `bias_initializer="zeros"`. + This is recommended in [Jozefowicz et + al.](http://www.jmlr.org/proceedings/papers/v37/jozefowicz15.pdf) + kernel_regularizer: Regularizer function applied to + the `kernel` weights matrix. + recurrent_regularizer: Regularizer function applied to + the `recurrent_kernel` weights matrix. + bias_regularizer: Regularizer function applied to the bias vector. + activity_regularizer: Regularizer function applied to + the output of the layer (its "activation").. + kernel_constraint: Constraint function applied to + the `kernel` weights matrix. + recurrent_constraint: Constraint function applied to + the `recurrent_kernel` weights matrix. + bias_constraint: Constraint function applied to the bias vector. + dropout: Float between 0 and 1. + Fraction of the units to drop for + the linear transformation of the inputs. + recurrent_dropout: Float between 0 and 1. + Fraction of the units to drop for + the linear transformation of the recurrent state. + + References: + - [Long short-term + memory]((http://www.bioinf.jku.at/publications/older/2604.pdf) + (original 1997 paper) + - [Supervised sequence labeling with recurrent neural + networks](http://www.cs.toronto.edu/~graves/preprint.pdf) + - [A Theoretically Grounded Application of Dropout in Recurrent Neural + Networks](http://arxiv.org/abs/1512.05287) + """ + + def __init__(self, + units, + activation='tanh', + recurrent_activation='hard_sigmoid', + use_bias=True, + kernel_initializer='glorot_uniform', + recurrent_initializer='orthogonal', + bias_initializer='zeros', + unit_forget_bias=True, + kernel_regularizer=None, + recurrent_regularizer=None, + bias_regularizer=None, + activity_regularizer=None, + kernel_constraint=None, + recurrent_constraint=None, + bias_constraint=None, + dropout=0., + recurrent_dropout=0., + **kwargs): + super(LSTM, self).__init__(**kwargs) + self.units = units + self.activation = activations.get(activation) + self.recurrent_activation = activations.get(recurrent_activation) + self.use_bias = use_bias + + self.kernel_initializer = initializers.get(kernel_initializer) + self.recurrent_initializer = initializers.get(recurrent_initializer) + self.bias_initializer = initializers.get(bias_initializer) + self.unit_forget_bias = unit_forget_bias + + self.kernel_regularizer = regularizers.get(kernel_regularizer) + self.recurrent_regularizer = regularizers.get(recurrent_regularizer) + self.bias_regularizer = regularizers.get(bias_regularizer) + self.activity_regularizer = regularizers.get(activity_regularizer) + + self.kernel_constraint = constraints.get(kernel_constraint) + self.recurrent_constraint = constraints.get(recurrent_constraint) + self.bias_constraint = constraints.get(bias_constraint) + + self.dropout = min(1., max(0., dropout)) + self.recurrent_dropout = min(1., max(0., recurrent_dropout)) + self.state_spec = [ + InputSpec(shape=(None, self.units)), + InputSpec(shape=(None, self.units)) + ] + + def build(self, input_shape): + if isinstance(input_shape, list): + input_shape = input_shape[0] + input_shape = tensor_shape.TensorShape(input_shape).as_list() + batch_size = input_shape[0] if self.stateful else None + self.input_dim = input_shape[2] + self.input_spec[0] = InputSpec(shape=(batch_size, None, self.input_dim)) + + self.states = [None, None] + if self.stateful: + self.reset_states() + + self.kernel = self.add_weight( + shape=(self.input_dim, self.units * 4), + name='kernel', + initializer=self.kernel_initializer, + regularizer=self.kernel_regularizer, + constraint=self.kernel_constraint) + self.recurrent_kernel = self.add_weight( + shape=(self.units, self.units * 4), + name='recurrent_kernel', + initializer=self.recurrent_initializer, + regularizer=self.recurrent_regularizer, + constraint=self.recurrent_constraint) + + if self.use_bias: + if self.unit_forget_bias: + + def bias_initializer(_, *args, **kwargs): + return K.concatenate([ + self.bias_initializer((self.units,), *args, **kwargs), + initializers.Ones()((self.units,), *args, **kwargs), + self.bias_initializer((self.units * 2,), *args, **kwargs), + ]) + else: + bias_initializer = self.bias_initializer + self.bias = self.add_weight( + shape=(self.units * 4,), + name='bias', + initializer=bias_initializer, + regularizer=self.bias_regularizer, + constraint=self.bias_constraint) + else: + self.bias = None + + self.kernel_i = self.kernel[:, :self.units] + self.kernel_f = self.kernel[:, self.units:self.units * 2] + self.kernel_c = self.kernel[:, self.units * 2:self.units * 3] + self.kernel_o = self.kernel[:, self.units * 3:] + + self.recurrent_kernel_i = self.recurrent_kernel[:, :self.units] + self.recurrent_kernel_f = self.recurrent_kernel[:, self.units: + self.units * 2] + self.recurrent_kernel_c = self.recurrent_kernel[:, self.units * 2: + self.units * 3] + self.recurrent_kernel_o = self.recurrent_kernel[:, self.units * 3:] + + if self.use_bias: + self.bias_i = self.bias[:self.units] + self.bias_f = self.bias[self.units:self.units * 2] + self.bias_c = self.bias[self.units * 2:self.units * 3] + self.bias_o = self.bias[self.units * 3:] + else: + self.bias_i = None + self.bias_f = None + self.bias_c = None + self.bias_o = None + self.built = True + + def preprocess_input(self, inputs, training=None): + if self.implementation == 0: + input_shape = inputs.get_shape().as_list() + input_dim = input_shape[2] + timesteps = input_shape[1] + + x_i = _time_distributed_dense( + inputs, + self.kernel_i, + self.bias_i, + self.dropout, + input_dim, + self.units, + timesteps, + training=training) + x_f = _time_distributed_dense( + inputs, + self.kernel_f, + self.bias_f, + self.dropout, + input_dim, + self.units, + timesteps, + training=training) + x_c = _time_distributed_dense( + inputs, + self.kernel_c, + self.bias_c, + self.dropout, + input_dim, + self.units, + timesteps, + training=training) + x_o = _time_distributed_dense( + inputs, + self.kernel_o, + self.bias_o, + self.dropout, + input_dim, + self.units, + timesteps, + training=training) + return K.concatenate([x_i, x_f, x_c, x_o], axis=2) + else: + return inputs + + def get_constants(self, inputs, training=None): + constants = [] + if self.implementation != 0 and 0 < self.dropout < 1: + input_shape = K.int_shape(inputs) + input_dim = input_shape[-1] + ones = K.ones_like(K.reshape(inputs[:, 0, 0], (-1, 1))) + ones = K.tile(ones, (1, int(input_dim))) + + def dropped_inputs(): + return K.dropout(ones, self.dropout) + + dp_mask = [ + K.in_train_phase(dropped_inputs, ones, training=training) + for _ in range(4) + ] + constants.append(dp_mask) + else: + constants.append([K.cast_to_floatx(1.) for _ in range(4)]) + + if 0 < self.recurrent_dropout < 1: + ones = K.ones_like(K.reshape(inputs[:, 0, 0], (-1, 1))) + ones = K.tile(ones, (1, self.units)) + + def dropped_inputs(): # pylint: disable=function-redefined + return K.dropout(ones, self.recurrent_dropout) + + rec_dp_mask = [ + K.in_train_phase(dropped_inputs, ones, training=training) + for _ in range(4) + ] + constants.append(rec_dp_mask) + else: + constants.append([K.cast_to_floatx(1.) for _ in range(4)]) + return constants + + def step(self, inputs, states): + h_tm1 = states[0] + c_tm1 = states[1] + dp_mask = states[2] + rec_dp_mask = states[3] + + if self.implementation == 2: + z = K.dot(inputs * dp_mask[0], self.kernel) + z += K.dot(h_tm1 * rec_dp_mask[0], self.recurrent_kernel) + if self.use_bias: + z = K.bias_add(z, self.bias) + + z0 = z[:, :self.units] + z1 = z[:, self.units:2 * self.units] + z2 = z[:, 2 * self.units:3 * self.units] + z3 = z[:, 3 * self.units:] + + i = self.recurrent_activation(z0) + f = self.recurrent_activation(z1) + c = f * c_tm1 + i * self.activation(z2) + o = self.recurrent_activation(z3) + else: + if self.implementation == 0: + x_i = inputs[:, :self.units] + x_f = inputs[:, self.units:2 * self.units] + x_c = inputs[:, 2 * self.units:3 * self.units] + x_o = inputs[:, 3 * self.units:] + elif self.implementation == 1: + x_i = K.dot(inputs * dp_mask[0], self.kernel_i) + self.bias_i + x_f = K.dot(inputs * dp_mask[1], self.kernel_f) + self.bias_f + x_c = K.dot(inputs * dp_mask[2], self.kernel_c) + self.bias_c + x_o = K.dot(inputs * dp_mask[3], self.kernel_o) + self.bias_o + else: + raise ValueError('Unknown `implementation` mode.') + + i = self.recurrent_activation(x_i + K.dot(h_tm1 * rec_dp_mask[0], + self.recurrent_kernel_i)) + f = self.recurrent_activation(x_f + K.dot(h_tm1 * rec_dp_mask[1], + self.recurrent_kernel_f)) + c = f * c_tm1 + i * self.activation( + x_c + K.dot(h_tm1 * rec_dp_mask[2], self.recurrent_kernel_c)) + o = self.recurrent_activation(x_o + K.dot(h_tm1 * rec_dp_mask[3], + self.recurrent_kernel_o)) + h = o * self.activation(c) + if 0 < self.dropout + self.recurrent_dropout: + h._uses_learning_phase = True + return h, [h, c] + + def get_config(self): + config = { + 'units': self.units, + 'activation': activations.serialize(self.activation), + 'recurrent_activation': + activations.serialize(self.recurrent_activation), + 'use_bias': self.use_bias, + 'kernel_initializer': initializers.serialize(self.kernel_initializer), + 'recurrent_initializer': + initializers.serialize(self.recurrent_initializer), + 'bias_initializer': initializers.serialize(self.bias_initializer), + 'unit_forget_bias': self.unit_forget_bias, + 'kernel_regularizer': regularizers.serialize(self.kernel_regularizer), + 'recurrent_regularizer': + regularizers.serialize(self.recurrent_regularizer), + 'bias_regularizer': regularizers.serialize(self.bias_regularizer), + 'activity_regularizer': + regularizers.serialize(self.activity_regularizer), + 'kernel_constraint': constraints.serialize(self.kernel_constraint), + 'recurrent_constraint': + constraints.serialize(self.recurrent_constraint), + 'bias_constraint': constraints.serialize(self.bias_constraint), + 'dropout': self.dropout, + 'recurrent_dropout': self.recurrent_dropout + } + base_config = super(LSTM, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + +#!/usr/bin/python + +"""Delete file not in Solr ...""" +import os +import requests +import json +import sys +import os.path +import sys +import argparse +import shutil +from common import splitString +from DirectoryWalker import DirectoryWalker +import itertools +from OmeroPropertiesParser import OmeroPropertiesParser + + +responseFailed=0 +numberOfImageDownloadAttemps=0 +totalNumberOfImagesWeHave=0 +numFoundInSolr=0 + +uniquePathsFromSolr=set() +uniqueFilesWithPathsFromNfs=set() + +def main(argv): + parser = argparse.ArgumentParser( + description='Delete files not in Solr' + ) + parser.add_argument('-d', '--rootDestinationDir', dest='rootDestinationDir', + help='Directory for root of destination to store images' ) + parser.add_argument('-s', '--rootSolrUrl', dest='rootSolrUrl', + help='URL to root of solr index' + ) + parser.add_argument('-H', '--host', dest='komp2Host', + help='Hostname for server hosting komp2 db' + ) + parser.add_argument('-p', '--port', dest='komp2Port', + help='Port by which to connect to komp2 db' + ) + parser.add_argument('-u', '--user', dest='komp2User', + help='Username for connecting to komp2 db' + ) + parser.add_argument('-db', '--database', dest='komp2Db', + help='Database to connect to for komp2db' + ) + parser.add_argument('--pass', dest='komp2Pass', + help='Password for komp2db' + ) + parser.add_argument('--profile', dest='profile', default='dev', + help='profile from which to read config: dev, prod, live, ...') + + args = parser.parse_args() + + # Get values from property file and use as defaults that can be overridden + # by command line parameters + try: + pp = OmeroPropertiesParser(args.profile) + omeroProps = pp.getOmeroProps() + except: + omeroProps = {} + + rootSolrUrl = args.rootSolrUrl if args.rootSolrUrl <> None else omeroProps['solrurl'] + komp2Host = args.komp2Host if args.komp2Host<>None else omeroProps['komp2host'] + komp2Port = args.komp2Port if args.komp2Port<>None else omeroProps['komp2port'] + komp2db = args.komp2Db if args.komp2Db<>None else omeroProps['komp2db'] + komp2User = args.komp2User if args.komp2User<>None else omeroProps['komp2user'] + komp2Pass = args.komp2Pass if args.komp2Pass<>None else omeroProps['komp2pass'] + rootDestinationDir = args.rootDestinationDir if args.rootDestinationDir<>None else omeroProps['rootdestinationdir'] + + #note cant split this url over a few lines as puts in newlines into url which doesn't work + #solrQuery="""experiment/select?q=observation_type:image_record&fq=download_file_path:(download_file_path:*bhjlk01.jax.org/images/IMPC_ALZ_001/*%20AND%20!download_file_path:*.mov)&fl=id,download_file_path,phenotyping_center,pipeline_stable_id,procedure_stable_id,datasource_name,parameter_stable_id&wt=json&indent=on&rows=10000000""" + solrQuery="""experiment/select?q=observation_type:image_record&fq=(download_file_path:*mousephenotype.org*%20AND%20!download_file_path:*.mov)&fl=id,download_file_path,phenotyping_center,pipeline_stable_id,procedure_stable_id,datasource_name,parameter_stable_id&wt=json&indent=on&rows=1000000""" + + print("running python image copy script for impc images") + + print 'rootDestinationDir is "', rootDestinationDir + solrUrl=rootSolrUrl+solrQuery; + print 'solrUrl', solrUrl + getPathsFromSolr(solrUrl, rootDestinationDir) + #for solrPath in itertools.islice(uniquePathsFromSolr, 3): + #print "solrPath="+solrPath + dirWalker=DirectoryWalker() + rel_directory_to_filenames_map=dirWalker.getFilesFromDir(rootDestinationDir) + n=10 + for key, value in rel_directory_to_filenames_map.items(): + count=0 + for name in value: + filePath=rootDestinationDir+key+"/"+name + uniqueFilesWithPathsFromNfs.add(filePath) + count+=1 + #if count<= n: print "filePath="+str(filePath) + print "uniquePathsFromSolr length=",len(uniquePathsFromSolr) + print "uniqueFilesWithPathsFromNfs=", len(uniqueFilesWithPathsFromNfs) + filesNotInSolrAnymore=uniqueFilesWithPathsFromNfs.difference(uniquePathsFromSolr) + print "files not in solr anymore size=",len(filesNotInSolrAnymore) + for currentPath in filesNotInSolrAnymore: + print "trying to move this file="+currentPath + destinationPath=currentPath.replace("/nfs/komp2/web/images/clean/impc/", "/nfs/komp2/web/images/impc/") + print "destPath="+destinationPath + moveFile(currentPath, destinationPath) + #os.remove(filePath) maybe move to another directory rather than delete + + + #runWithSolrAsDataSource(solrUrl, cnx, rootDestinationDir) + + +def getPathsFromSolr(solrUrl, rootDestinationDir): + """ + need to get these passed in as arguments - the host and db name etc for jenkins to run + first get the list of download urls and the data source, experiment, procdure and parameter and observation id for the images + """ + v = json.loads(requests.get(solrUrl).text) + docs=v['response']['docs'] + numFoundInSolr=v['response']['numFound'] + for doc in docs: + download_file_path=doc['download_file_path'] + datasource_id=doc['datasource_name'] + phenotyping_center=doc['phenotyping_center'] + #experiment=doc['experiment'] + pipeline_stable_id=doc['pipeline_stable_id'] + observation_id=doc['id'] + procedure_stable_id=doc['procedure_stable_id'] + parameter_stable_id=doc['parameter_stable_id'] + global rootDesitinationdir + getUniqueFilePathsFromSolr(observation_id, rootDestinationDir,phenotyping_center,pipeline_stable_id, procedure_stable_id, parameter_stable_id, download_file_path) + + print 'number found in solr='+str(numFoundInSolr)+' number of failed responses='+str(responseFailed)+' number of requests='+str(numberOfImageDownloadAttemps)+' total totalNumberOfImagesWeHave='+str(totalNumberOfImagesWeHave) + +def createDestinationFilePath(rootDestinationDir, phenotyping_center, pipeline_stable_id, procedure, parameter, download_file_path): + directory="/".join([rootDestinationDir,phenotyping_center, pipeline_stable_id,procedure,parameter]) + return directory + +def getUniqueFilePathsFromSolr(observation_id, rootDestinationDir, phenotyping_center,pipeline_stable_id, procedure, parameter, downloadFilePath): + global totalNumberOfImagesWeHave + global responseFailed + global numberOfImageDownloadAttemps + directory = createDestinationFilePath(rootDestinationDir, phenotyping_center, pipeline_stable_id, procedure,parameter, downloadFilePath) + #print "directory "+str(directory) + dstfilename=directory+"/"+str(downloadFilePath.split('/')[-1]) + #print "dstfilename="+str(dstfilename) + #/nfs/komp2/web/images/impc/MRC Harwell/HRWL_001/IMPC_XRY_001/IMPC_XRY_034_001/114182.dcm + # new file paths are /nfs/public/ro/pheno-archive-images/images/impc + if dstfilename in uniquePathsFromSolr: + print '---------------------!!!!!!!!!!error the filePath is not unique and has been specified before:'+dstfilename + uniquePathsFromSolr.add(dstfilename.replace("impc//", "impc/"))#hack to remove the extra slash after impc but don't want to effect other module used by other code + #destDirectory=os.path.dirname(destPath) + #print "destination directory for copy is "+destDirectory + #if not os.path.exists(destDirectory): + # os.makedirs(destDirectory) + #print 'saving file to '+destPath + #if not os.path.isfile(destPath): + # try: + # shutil.copyfile(dstfilename,destPath) + # except IOError: + # print "file does not exist "+str(dstfilename)+" continuing" + #totalNumberOfImagesWeHave=totalNumberOfImagesWeHave+1 + #if totalNumberOfImagesWeHave%1000==0 : + # print "totalNumber of images we have="+str(totalNumberOfImagesWeHave) + +def moveFile(currentPath, destinationPath): + + filename=str(destinationPath.split('/')[-1]) + destDirectory=destinationPath.replace(filename, "") + print "making directory="+destDirectory + if not os.path.exists(destDirectory): + os.makedirs(destDirectory) + print 'moving file to '+destinationPath + if not os.path.isfile(destinationPath): + try: + shutil.move(currentPath,destinationPath) + except IOError: + print "file does not exist "+str(currentPath)+" continuing" + +if __name__ == "__main__": + main(sys.argv[1:]) + +######################## BEGIN LICENSE BLOCK ######################## +# The Original Code is mozilla.org code. +# +# The Initial Developer of the Original Code is +# Netscape Communications Corporation. +# Portions created by the Initial Developer are Copyright (C) 1998 +# the Initial Developer. All Rights Reserved. +# +# Contributor(s): +# Mark Pilgrim - port to Python +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA +# 02110-1301 USA +######################### END LICENSE BLOCK ######################### + +from .mbcharsetprober import MultiByteCharSetProber +from .codingstatemachine import CodingStateMachine +from .chardistribution import EUCTWDistributionAnalysis +from .mbcssm import EUCTWSMModel + +class EUCTWProber(MultiByteCharSetProber): + def __init__(self): + MultiByteCharSetProber.__init__(self) + self._mCodingSM = CodingStateMachine(EUCTWSMModel) + self._mDistributionAnalyzer = EUCTWDistributionAnalysis() + self.reset() + + def get_charset_name(self): + return "EUC-TW" + +# encoding: utf-8 +import datetime +from south.db import db +from south.v2 import SchemaMigration +from django.db import models + +class Migration(SchemaMigration): + + def forwards(self, orm): + + # Adding field 'Workflow.managed' + db.add_column('oozie_workflow', 'managed', self.gf('django.db.models.fields.BooleanField')(default=True, blank=True), keep_default=False) + + + def backwards(self, orm): + + # Deleting field 'Workflow.managed' + db.delete_column('oozie_workflow', 'managed') + + + models = { + 'auth.group': { + 'Meta': {'object_name': 'Group'}, + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), + 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) + }, + 'auth.permission': { + 'Meta': {'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, + 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), + 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) + }, + 'auth.user': { + 'Meta': {'object_name': 'User'}, + 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), + 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), + 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), + 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}), + 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), + 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), + 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), + 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), + 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), + 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), + 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) + }, + 'contenttypes.contenttype': { + 'Meta': {'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, + 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), + 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) + }, + 'oozie.bundle': { + 'Meta': {'object_name': 'Bundle', '_ormbases': ['oozie.Job']}, + 'coordinators': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['oozie.Coordinator']", 'through': "orm['oozie.BundledCoordinator']", 'symmetrical': 'False'}), + 'job_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['oozie.Job']", 'unique': 'True', 'primary_key': 'True'}), + 'kick_off_time': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 2, 28, 13, 56, 0, 347089)'}) + }, + 'oozie.bundledcoordinator': { + 'Meta': {'object_name': 'BundledCoordinator'}, + 'bundle': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['oozie.Bundle']"}), + 'coordinator': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['oozie.Coordinator']"}), + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'parameters': ('django.db.models.fields.TextField', [], {'default': '\'[{"name":"oozie.use.system.libpath","value":"true"}]\''}) + }, + 'oozie.coordinator': { + 'Meta': {'object_name': 'Coordinator', '_ormbases': ['oozie.Job']}, + 'concurrency': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True', 'blank': 'True'}), + 'end': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 3, 3, 13, 56, 0, 344924)'}), + 'execution': ('django.db.models.fields.CharField', [], {'max_length': '10', 'null': 'True', 'blank': 'True'}), + 'frequency_number': ('django.db.models.fields.SmallIntegerField', [], {'default': '1'}), + 'frequency_unit': ('django.db.models.fields.CharField', [], {'default': "'days'", 'max_length': '20'}), + 'job_properties': ('django.db.models.fields.TextField', [], {'default': "'[]'"}), + 'job_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['oozie.Job']", 'unique': 'True', 'primary_key': 'True'}), + 'start': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 2, 28, 13, 56, 0, 344893)'}), + 'throttle': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True', 'blank': 'True'}), + 'timeout': ('django.db.models.fields.SmallIntegerField', [], {'null': 'True', 'blank': 'True'}), + 'timezone': ('django.db.models.fields.CharField', [], {'default': "'America/Los_Angeles'", 'max_length': '24'}), + 'workflow': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['oozie.Workflow']", 'null': 'True'}) + }, + 'oozie.datainput': { + 'Meta': {'object_name': 'DataInput'}, + 'coordinator': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['oozie.Coordinator']"}), + 'dataset': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['oozie.Dataset']", 'unique': 'True'}), + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'name': ('django.db.models.fields.CharField', [], {'max_length': '40'}) + }, + 'oozie.dataoutput': { + 'Meta': {'object_name': 'DataOutput'}, + 'coordinator': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['oozie.Coordinator']"}), + 'dataset': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['oozie.Dataset']", 'unique': 'True'}), + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'name': ('django.db.models.fields.CharField', [], {'max_length': '40'}) + }, + 'oozie.dataset': { + 'Meta': {'object_name': 'Dataset'}, + 'advanced_end_instance': ('django.db.models.fields.CharField', [], {'default': "'0'", 'max_length': '128', 'blank': 'True'}), + 'advanced_start_instance': ('django.db.models.fields.CharField', [], {'default': "'0'", 'max_length': '128'}), + 'coordinator': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['oozie.Coordinator']"}), + 'description': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '1024', 'blank': 'True'}), + 'done_flag': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '64', 'blank': 'True'}), + 'frequency_number': ('django.db.models.fields.SmallIntegerField', [], {'default': '1'}), + 'frequency_unit': ('django.db.models.fields.CharField', [], {'default': "'days'", 'max_length': '20'}), + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'instance_choice': ('django.db.models.fields.CharField', [], {'default': "'default'", 'max_length': '10'}), + 'name': ('django.db.models.fields.CharField', [], {'max_length': '40'}), + 'start': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 2, 28, 13, 56, 0, 345574)'}), + 'timezone': ('django.db.models.fields.CharField', [], {'default': "'America/Los_Angeles'", 'max_length': '24'}), + 'uri': ('django.db.models.fields.CharField', [], {'default': "'/data/${YEAR}${MONTH}${DAY}'", 'max_length': '1024'}) + }, + 'oozie.decision': { + 'Meta': {'object_name': 'Decision'}, + 'node_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['oozie.Node']", 'unique': 'True', 'primary_key': 'True'}) + }, + 'oozie.decisionend': { + 'Meta': {'object_name': 'DecisionEnd'}, + 'node_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['oozie.Node']", 'unique': 'True', 'primary_key': 'True'}) + }, + 'oozie.distcp': { + 'Meta': {'object_name': 'DistCp'}, + 'job_properties': ('django.db.models.fields.TextField', [], {'default': "'[]'"}), + 'job_xml': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '512', 'blank': 'True'}), + 'node_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['oozie.Node']", 'unique': 'True', 'primary_key': 'True'}), + 'params': ('django.db.models.fields.TextField', [], {'default': "'[]'"}), + 'prepares': ('django.db.models.fields.TextField', [], {'default': "'[]'"}) + }, + 'oozie.email': { + 'Meta': {'object_name': 'Email'}, + 'body': ('django.db.models.fields.TextField', [], {'default': "''"}), + 'cc': ('django.db.models.fields.TextField', [], {'default': "''", 'blank': 'True'}), + 'node_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['oozie.Node']", 'unique': 'True', 'primary_key': 'True'}), + 'subject': ('django.db.models.fields.TextField', [], {'default': "''"}), + 'to': ('django.db.models.fields.TextField', [], {'default': "''"}) + }, + 'oozie.end': { + 'Meta': {'object_name': 'End'}, + 'node_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['oozie.Node']", 'unique': 'True', 'primary_key': 'True'}) + }, + 'oozie.fork': { + 'Meta': {'object_name': 'Fork'}, + 'node_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['oozie.Node']", 'unique': 'True', 'primary_key': 'True'}) + }, + 'oozie.fs': { + 'Meta': {'object_name': 'Fs'}, + 'chmods': ('django.db.models.fields.TextField', [], {'default': "'[]'", 'blank': 'True'}), + 'deletes': ('django.db.models.fields.TextField', [], {'default': "'[]'", 'blank': 'True'}), + 'mkdirs': ('django.db.models.fields.TextField', [], {'default': "'[]'", 'blank': 'True'}), + 'moves': ('django.db.models.fields.TextField', [], {'default': "'[]'", 'blank': 'True'}), + 'node_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['oozie.Node']", 'unique': 'True', 'primary_key': 'True'}), + 'touchzs': ('django.db.models.fields.TextField', [], {'default': "'[]'", 'blank': 'True'}) + }, + 'oozie.generic': { + 'Meta': {'object_name': 'Generic'}, + 'node_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['oozie.Node']", 'unique': 'True', 'primary_key': 'True'}), + 'xml': ('django.db.models.fields.TextField', [], {'default': "''"}) + }, + 'oozie.history': { + 'Meta': {'object_name': 'History'}, + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'job': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['oozie.Job']"}), + 'oozie_job_id': ('django.db.models.fields.CharField', [], {'max_length': '128'}), + 'properties': ('django.db.models.fields.TextField', [], {}), + 'submission_date': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'db_index': 'True', 'blank': 'True'}), + 'submitter': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) + }, + 'oozie.hive': { + 'Meta': {'object_name': 'Hive'}, + 'archives': ('django.db.models.fields.TextField', [], {'default': "'[]'"}), + 'files': ('django.db.models.fields.TextField', [], {'default': "'[]'"}), + 'job_properties': ('django.db.models.fields.TextField', [], {'default': '\'[{"name":"oozie.hive.defaults","value":"hive-site.xml"}]\''}), + 'job_xml': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '512', 'blank': 'True'}), + 'node_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['oozie.Node']", 'unique': 'True', 'primary_key': 'True'}), + 'params': ('django.db.models.fields.TextField', [], {'default': "'[]'"}), + 'prepares': ('django.db.models.fields.TextField', [], {'default': "'[]'"}), + 'script_path': ('django.db.models.fields.CharField', [], {'max_length': '256'}) + }, + 'oozie.java': { + 'Meta': {'object_name': 'Java'}, + 'archives': ('django.db.models.fields.TextField', [], {'default': "'[]'"}), + 'args': ('django.db.models.fields.CharField', [], {'max_length': '4096', 'blank': 'True'}), + 'files': ('django.db.models.fields.TextField', [], {'default': "'[]'"}), + 'jar_path': ('django.db.models.fields.CharField', [], {'max_length': '512'}), + 'java_opts': ('django.db.models.fields.CharField', [], {'max_length': '256', 'blank': 'True'}), + 'job_properties': ('django.db.models.fields.TextField', [], {'default': "'[]'"}), + 'job_xml': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '512', 'blank': 'True'}), + 'main_class': ('django.db.models.fields.CharField', [], {'max_length': '256'}), + 'node_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['oozie.Node']", 'unique': 'True', 'primary_key': 'True'}), + 'prepares': ('django.db.models.fields.TextField', [], {'default': "'[]'"}) + }, + 'oozie.job': { + 'Meta': {'object_name': 'Job'}, + 'deployment_dir': ('django.db.models.fields.CharField', [], {'max_length': '1024', 'blank': 'True'}), + 'description': ('django.db.models.fields.CharField', [], {'max_length': '1024', 'blank': 'True'}), + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'is_shared': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True', 'blank': 'True'}), + 'last_modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'db_index': 'True', 'blank': 'True'}), + 'name': ('django.db.models.fields.CharField', [], {'max_length': '40'}), + 'owner': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}), + 'parameters': ('django.db.models.fields.TextField', [], {'default': '\'[{"name":"oozie.use.system.libpath","value":"true"}]\''}), + 'schema_version': ('django.db.models.fields.CharField', [], {'max_length': '128'}) + }, + 'oozie.join': { + 'Meta': {'object_name': 'Join'}, + 'node_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['oozie.Node']", 'unique': 'True', 'primary_key': 'True'}) + }, + 'oozie.kill': { + 'Meta': {'object_name': 'Kill'}, + 'message': ('django.db.models.fields.CharField', [], {'default': "'Action failed, error message[${wf:errorMessage(wf:lastErrorNode())}]'", 'max_length': '256'}), + 'node_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['oozie.Node']", 'unique': 'True', 'primary_key': 'True'}) + }, + 'oozie.link': { + 'Meta': {'object_name': 'Link'}, + 'child': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'parent_node'", 'to': "orm['oozie.Node']"}), + 'comment': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '1024', 'blank': 'True'}), + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'name': ('django.db.models.fields.CharField', [], {'max_length': '40'}), + 'parent': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'child_node'", 'to': "orm['oozie.Node']"}) + }, + 'oozie.mapreduce': { + 'Meta': {'object_name': 'Mapreduce'}, + 'archives': ('django.db.models.fields.TextField', [], {'default': "'[]'"}), + 'files': ('django.db.models.fields.TextField', [], {'default': "'[]'"}), + 'jar_path': ('django.db.models.fields.CharField', [], {'max_length': '512'}), + 'job_properties': ('django.db.models.fields.TextField', [], {'default': "'[]'"}), + 'job_xml': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '512', 'blank': 'True'}), + 'node_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['oozie.Node']", 'unique': 'True'}), + 'prepares': ('django.db.models.fields.TextField', [], {'default': "'[]'"}) + }, + 'oozie.node': { + 'Meta': {'object_name': 'Node'}, + 'children': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'parents'", 'symmetrical': 'False', 'through': "orm['oozie.Link']", 'to': "orm['oozie.Node']"}), + 'description': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '1024', 'blank': 'True'}), + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'name': ('django.db.models.fields.CharField', [], {'max_length': '40'}), + 'node_type': ('django.db.models.fields.CharField', [], {'max_length': '64'}), + 'workflow': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['oozie.Workflow']"}) + }, + 'oozie.pig': { + 'Meta': {'object_name': 'Pig'}, + 'archives': ('django.db.models.fields.TextField', [], {'default': "'[]'"}), + 'files': ('django.db.models.fields.TextField', [], {'default': "'[]'"}), + 'job_properties': ('django.db.models.fields.TextField', [], {'default': "'[]'"}), + 'job_xml': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '512', 'blank': 'True'}), + 'node_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['oozie.Node']", 'unique': 'True', 'primary_key': 'True'}), + 'params': ('django.db.models.fields.TextField', [], {'default': "'[]'"}), + 'prepares': ('django.db.models.fields.TextField', [], {'default': "'[]'"}), + 'script_path': ('django.db.models.fields.CharField', [], {'max_length': '256'}) + }, + 'oozie.shell': { + 'Meta': {'object_name': 'Shell'}, + 'archives': ('django.db.models.fields.TextField', [], {'default': "'[]'"}), + 'capture_output': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), + 'command': ('django.db.models.fields.CharField', [], {'max_length': '256'}), + 'files': ('django.db.models.fields.TextField', [], {'default': "'[]'"}), + 'job_properties': ('django.db.models.fields.TextField', [], {'default': "'[]'"}), + 'job_xml': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '512', 'blank': 'True'}), + 'node_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['oozie.Node']", 'unique': 'True', 'primary_key': 'True'}), + 'params': ('django.db.models.fields.TextField', [], {'default': "'[]'"}), + 'prepares': ('django.db.models.fields.TextField', [], {'default': "'[]'"}) + }, + 'oozie.sqoop': { + 'Meta': {'object_name': 'Sqoop'}, + 'archives': ('django.db.models.fields.TextField', [], {'default': "'[]'"}), + 'files': ('django.db.models.fields.TextField', [], {'default': "'[]'"}), + 'job_properties': ('django.db.models.fields.TextField', [], {'default': "'[]'"}), + 'job_xml': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '512', 'blank': 'True'}), + 'node_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['oozie.Node']", 'unique': 'True', 'primary_key': 'True'}), + 'params': ('django.db.models.fields.TextField', [], {'default': "'[]'"}), + 'prepares': ('django.db.models.fields.TextField', [], {'default': "'[]'"}), + 'script_path': ('django.db.models.fields.TextField', [], {'default': "''", 'blank': 'True'}) + }, + 'oozie.ssh': { + 'Meta': {'object_name': 'Ssh'}, + 'capture_output': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), + 'command': ('django.db.models.fields.CharField', [], {'max_length': '256'}), + 'host': ('django.db.models.fields.CharField', [], {'max_length': '256'}), + 'node_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['oozie.Node']", 'unique': 'True', 'primary_key': 'True'}), + 'params': ('django.db.models.fields.TextField', [], {'default': "'[]'"}), + 'user': ('django.db.models.fields.CharField', [], {'max_length': '64'}) + }, + 'oozie.start': { + 'Meta': {'object_name': 'Start'}, + 'node_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['oozie.Node']", 'unique': 'True'}) + }, + 'oozie.streaming': { + 'Meta': {'object_name': 'Streaming'}, + 'archives': ('django.db.models.fields.TextField', [], {'default': "'[]'"}), + 'files': ('django.db.models.fields.TextField', [], {'default': "'[]'"}), + 'job_properties': ('django.db.models.fields.TextField', [], {'default': "'[]'"}), + 'mapper': ('django.db.models.fields.CharField', [], {'max_length': '512'}), + 'node_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['oozie.Node']", 'unique': 'True', 'primary_key': 'True'}), + 'reducer': ('django.db.models.fields.CharField', [], {'max_length': '512'}) + }, + 'oozie.subworkflow': { + 'Meta': {'object_name': 'SubWorkflow'}, + 'job_properties': ('django.db.models.fields.TextField', [], {'default': "'[]'"}), + 'node_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['oozie.Node']", 'unique': 'True', 'primary_key': 'True'}), + 'propagate_configuration': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}), + 'sub_workflow': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['oozie.Workflow']"}) + }, + 'oozie.workflow': { + 'Meta': {'object_name': 'Workflow', '_ormbases': ['oozie.Job']}, + 'end': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'end_workflow'", 'null': 'True', 'to': "orm['oozie.End']"}), + 'is_single': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), + 'job_properties': ('django.db.models.fields.TextField', [], {'default': "'[]'"}), + 'job_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['oozie.Job']", 'unique': 'True', 'primary_key': 'True'}), + 'job_xml': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '512', 'blank': 'True'}), + 'managed': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}), + 'start': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'start_workflow'", 'null': 'True', 'to': "orm['oozie.Start']"}) + } + } + + complete_apps = ['oozie'] + +#!/usr/bin/python +# -*- coding: utf-8 -*- +# NOTE: the shebang and encoding lines are for ScriptHeaderTests; do not remove +from unittest import TestCase, makeSuite; from pkg_resources import * +from setuptools.command.easy_install import get_script_header, is_sh +import os, pkg_resources, sys, StringIO, tempfile, shutil +try: frozenset +except NameError: + from sets import ImmutableSet as frozenset + +def safe_repr(obj, short=False): + """ copied from Python2.7""" + try: + result = repr(obj) + except Exception: + result = object.__repr__(obj) + if not short or len(result) < _MAX_LENGTH: + return result + return result[:_MAX_LENGTH] + ' [truncated]...' + +class Metadata(EmptyProvider): + """Mock object to return metadata as if from an on-disk distribution""" + + def __init__(self,*pairs): + self.metadata = dict(pairs) + + def has_metadata(self,name): + return name in self.metadata + + def get_metadata(self,name): + return self.metadata[name] + + def get_metadata_lines(self,name): + return yield_lines(self.get_metadata(name)) + +class DistroTests(TestCase): + + def testCollection(self): + # empty path should produce no distributions + ad = Environment([], platform=None, python=None) + self.assertEqual(list(ad), []) + self.assertEqual(ad['FooPkg'],[]) + ad.add(Distribution.from_filename("FooPkg-1.3_1.egg")) + ad.add(Distribution.from_filename("FooPkg-1.4-py2.4-win32.egg")) + ad.add(Distribution.from_filename("FooPkg-1.2-py2.4.egg")) + + # Name is in there now + self.assert_(ad['FooPkg']) + # But only 1 package + self.assertEqual(list(ad), ['foopkg']) + + # Distributions sort by version + self.assertEqual( + [dist.version for dist in ad['FooPkg']], ['1.4','1.3-1','1.2'] + ) + # Removing a distribution leaves sequence alone + ad.remove(ad['FooPkg'][1]) + self.assertEqual( + [dist.version for dist in ad['FooPkg']], ['1.4','1.2'] + ) + # And inserting adds them in order + ad.add(Distribution.from_filename("FooPkg-1.9.egg")) + self.assertEqual( + [dist.version for dist in ad['FooPkg']], ['1.9','1.4','1.2'] + ) + + ws = WorkingSet([]) + foo12 = Distribution.from_filename("FooPkg-1.2-py2.4.egg") + foo14 = Distribution.from_filename("FooPkg-1.4-py2.4-win32.egg") + req, = parse_requirements("FooPkg>=1.3") + + # Nominal case: no distros on path, should yield all applicable + self.assertEqual(ad.best_match(req,ws).version, '1.9') + # If a matching distro is already installed, should return only that + ws.add(foo14); self.assertEqual(ad.best_match(req,ws).version, '1.4') + + # If the first matching distro is unsuitable, it's a version conflict + ws = WorkingSet([]); ws.add(foo12); ws.add(foo14) + self.assertRaises(VersionConflict, ad.best_match, req, ws) + + # If more than one match on the path, the first one takes precedence + ws = WorkingSet([]); ws.add(foo14); ws.add(foo12); ws.add(foo14); + self.assertEqual(ad.best_match(req,ws).version, '1.4') + + def checkFooPkg(self,d): + self.assertEqual(d.project_name, "FooPkg") + self.assertEqual(d.key, "foopkg") + self.assertEqual(d.version, "1.3-1") + self.assertEqual(d.py_version, "2.4") + self.assertEqual(d.platform, "win32") + self.assertEqual(d.parsed_version, parse_version("1.3-1")) + + def testDistroBasics(self): + d = Distribution( + "/some/path", + project_name="FooPkg",version="1.3-1",py_version="2.4",platform="win32" + ) + self.checkFooPkg(d) + + d = Distribution("/some/path") + self.assertEqual(d.py_version, sys.version[:3]) + self.assertEqual(d.platform, None) + + def testDistroParse(self): + d = Distribution.from_filename("FooPkg-1.3_1-py2.4-win32.egg") + self.checkFooPkg(d) + d = Distribution.from_filename("FooPkg-1.3_1-py2.4-win32.egg-info") + self.checkFooPkg(d) + + def testDistroMetadata(self): + d = Distribution( + "/some/path", project_name="FooPkg", py_version="2.4", platform="win32", + metadata = Metadata( + ('PKG-INFO',"Metadata-Version: 1.0\nVersion: 1.3-1\n") + ) + ) + self.checkFooPkg(d) + + + def distRequires(self, txt): + return Distribution("/foo", metadata=Metadata(('depends.txt', txt))) + + def checkRequires(self, dist, txt, extras=()): + self.assertEqual( + list(dist.requires(extras)), + list(parse_requirements(txt)) + ) + + def testDistroDependsSimple(self): + for v in "Twisted>=1.5", "Twisted>=1.5\nZConfig>=2.0": + self.checkRequires(self.distRequires(v), v) + + + def testResolve(self): + ad = Environment([]); ws = WorkingSet([]) + # Resolving no requirements -> nothing to install + self.assertEqual( list(ws.resolve([],ad)), [] ) + # Request something not in the collection -> DistributionNotFound + self.assertRaises( + DistributionNotFound, ws.resolve, parse_requirements("Foo"), ad + ) + Foo = Distribution.from_filename( + "/foo_dir/Foo-1.2.egg", + metadata=Metadata(('depends.txt', "[bar]\nBaz>=2.0")) + ) + ad.add(Foo); ad.add(Distribution.from_filename("Foo-0.9.egg")) + + # Request thing(s) that are available -> list to activate + for i in range(3): + targets = list(ws.resolve(parse_requirements("Foo"), ad)) + self.assertEqual(targets, [Foo]) + map(ws.add,targets) + self.assertRaises(VersionConflict, ws.resolve, + parse_requirements("Foo==0.9"), ad) + ws = WorkingSet([]) # reset + + # Request an extra that causes an unresolved dependency for "Baz" + self.assertRaises( + DistributionNotFound, ws.resolve,parse_requirements("Foo[bar]"), ad + ) + Baz = Distribution.from_filename( + "/foo_dir/Baz-2.1.egg", metadata=Metadata(('depends.txt', "Foo")) + ) + ad.add(Baz) + + # Activation list now includes resolved dependency + self.assertEqual( + list(ws.resolve(parse_requirements("Foo[bar]"), ad)), [Foo,Baz] + ) + # Requests for conflicting versions produce VersionConflict + self.assertRaises( VersionConflict, + ws.resolve, parse_requirements("Foo==1.2\nFoo!=1.2"), ad + ) + + def testDistroDependsOptions(self): + d = self.distRequires(""" + Twisted>=1.5 + [docgen] + ZConfig>=2.0 + docutils>=0.3 + [fastcgi] + fcgiapp>=0.1""") + self.checkRequires(d,"Twisted>=1.5") + self.checkRequires( + d,"Twisted>=1.5 ZConfig>=2.0 docutils>=0.3".split(), ["docgen"] + ) + self.checkRequires( + d,"Twisted>=1.5 fcgiapp>=0.1".split(), ["fastcgi"] + ) + self.checkRequires( + d,"Twisted>=1.5 ZConfig>=2.0 docutils>=0.3 fcgiapp>=0.1".split(), + ["docgen","fastcgi"] + ) + self.checkRequires( + d,"Twisted>=1.5 fcgiapp>=0.1 ZConfig>=2.0 docutils>=0.3".split(), + ["fastcgi", "docgen"] + ) + self.assertRaises(UnknownExtra, d.requires, ["foo"]) + + def testSetuptoolsDistributeCombination(self): + # Ensure that installing a 0.7-series setuptools fails. PJE says that + # it will not co-exist. + ws = WorkingSet([]) + d = Distribution( + "/some/path", + project_name="setuptools", + version="0.7a1") + self.assertRaises(ValueError, ws.add, d) + # A 0.6-series is no problem + d2 = Distribution( + "/some/path", + project_name="setuptools", + version="0.6c9") + ws.add(d2) + + # a unexisting version needs to work + ws = WorkingSet([]) + d3 = Distribution( + "/some/path", + project_name="setuptools") + ws.add(d3) + + +class EntryPointTests(TestCase): + + def assertfields(self, ep): + self.assertEqual(ep.name,"foo") + self.assertEqual(ep.module_name,"setuptools.tests.test_resources") + self.assertEqual(ep.attrs, ("EntryPointTests",)) + self.assertEqual(ep.extras, ("x",)) + self.assert_(ep.load() is EntryPointTests) + self.assertEqual( + str(ep), + "foo = setuptools.tests.test_resources:EntryPointTests [x]" + ) + + def setUp(self): + self.dist = Distribution.from_filename( + "FooPkg-1.2-py2.4.egg", metadata=Metadata(('requires.txt','[x]'))) + + def testBasics(self): + ep = EntryPoint( + "foo", "setuptools.tests.test_resources", ["EntryPointTests"], + ["x"], self.dist + ) + self.assertfields(ep) + + def testParse(self): + s = "foo = setuptools.tests.test_resources:EntryPointTests [x]" + ep = EntryPoint.parse(s, self.dist) + self.assertfields(ep) + + ep = EntryPoint.parse("bar baz= spammity[PING]") + self.assertEqual(ep.name,"bar baz") + self.assertEqual(ep.module_name,"spammity") + self.assertEqual(ep.attrs, ()) + self.assertEqual(ep.extras, ("ping",)) + + ep = EntryPoint.parse(" fizzly = wocka:foo") + self.assertEqual(ep.name,"fizzly") + self.assertEqual(ep.module_name,"wocka") + self.assertEqual(ep.attrs, ("foo",)) + self.assertEqual(ep.extras, ()) + + def testRejects(self): + for ep in [ + "foo", "x=1=2", "x=a:b:c", "q=x/na", "fez=pish:tush-z", "x=f[a]>2", + ]: + try: EntryPoint.parse(ep) + except ValueError: pass + else: raise AssertionError("Should've been bad", ep) + + def checkSubMap(self, m): + self.assertEqual(len(m), len(self.submap_expect)) + for key, ep in self.submap_expect.iteritems(): + self.assertEqual(repr(m.get(key)), repr(ep)) + + submap_expect = dict( + feature1=EntryPoint('feature1', 'somemodule', ['somefunction']), + feature2=EntryPoint('feature2', 'another.module', ['SomeClass'], ['extra1','extra2']), + feature3=EntryPoint('feature3', 'this.module', extras=['something']) + ) + submap_str = """ + # define features for blah blah + feature1 = somemodule:somefunction + feature2 = another.module:SomeClass [extra1,extra2] + feature3 = this.module [something] + """ + + def testParseList(self): + self.checkSubMap(EntryPoint.parse_group("xyz", self.submap_str)) + self.assertRaises(ValueError, EntryPoint.parse_group, "x a", "foo=bar") + self.assertRaises(ValueError, EntryPoint.parse_group, "x", + ["foo=baz", "foo=bar"]) + + def testParseMap(self): + m = EntryPoint.parse_map({'xyz':self.submap_str}) + self.checkSubMap(m['xyz']) + self.assertEqual(m.keys(),['xyz']) + m = EntryPoint.parse_map("[xyz]\n"+self.submap_str) + self.checkSubMap(m['xyz']) + self.assertEqual(m.keys(),['xyz']) + self.assertRaises(ValueError, EntryPoint.parse_map, ["[xyz]", "[xyz]"]) + self.assertRaises(ValueError, EntryPoint.parse_map, self.submap_str) + +class RequirementsTests(TestCase): + + def testBasics(self): + r = Requirement.parse("Twisted>=1.2") + self.assertEqual(str(r),"Twisted>=1.2") + self.assertEqual(repr(r),"Requirement.parse('Twisted>=1.2')") + self.assertEqual(r, Requirement("Twisted", [('>=','1.2')], ())) + self.assertEqual(r, Requirement("twisTed", [('>=','1.2')], ())) + self.assertNotEqual(r, Requirement("Twisted", [('>=','2.0')], ())) + self.assertNotEqual(r, Requirement("Zope", [('>=','1.2')], ())) + self.assertNotEqual(r, Requirement("Zope", [('>=','3.0')], ())) + self.assertNotEqual(r, Requirement.parse("Twisted[extras]>=1.2")) + + def testOrdering(self): + r1 = Requirement("Twisted", [('==','1.2c1'),('>=','1.2')], ()) + r2 = Requirement("Twisted", [('>=','1.2'),('==','1.2c1')], ()) + self.assertEqual(r1,r2) + self.assertEqual(str(r1),str(r2)) + self.assertEqual(str(r2),"Twisted==1.2c1,>=1.2") + + def testBasicContains(self): + r = Requirement("Twisted", [('>=','1.2')], ()) + foo_dist = Distribution.from_filename("FooPkg-1.3_1.egg") + twist11 = Distribution.from_filename("Twisted-1.1.egg") + twist12 = Distribution.from_filename("Twisted-1.2.egg") + self.assert_(parse_version('1.2') in r) + self.assert_(parse_version('1.1') not in r) + self.assert_('1.2' in r) + self.assert_('1.1' not in r) + self.assert_(foo_dist not in r) + self.assert_(twist11 not in r) + self.assert_(twist12 in r) + + def testAdvancedContains(self): + r, = parse_requirements("Foo>=1.2,<=1.3,==1.9,>2.0,!=2.5,<3.0,==4.5") + for v in ('1.2','1.2.2','1.3','1.9','2.0.1','2.3','2.6','3.0c1','4.5'): + self.assert_(v in r, (v,r)) + for v in ('1.2c1','1.3.1','1.5','1.9.1','2.0','2.5','3.0','4.0'): + self.assert_(v not in r, (v,r)) + + + def testOptionsAndHashing(self): + r1 = Requirement.parse("Twisted[foo,bar]>=1.2") + r2 = Requirement.parse("Twisted[bar,FOO]>=1.2") + r3 = Requirement.parse("Twisted[BAR,FOO]>=1.2.0") + self.assertEqual(r1,r2) + self.assertEqual(r1,r3) + self.assertEqual(r1.extras, ("foo","bar")) + self.assertEqual(r2.extras, ("bar","foo")) # extras are normalized + self.assertEqual(hash(r1), hash(r2)) + self.assertEqual( + hash(r1), hash(("twisted", ((">=",parse_version("1.2")),), + frozenset(["foo","bar"]))) + ) + + def testVersionEquality(self): + r1 = Requirement.parse("foo==0.3a2") + r2 = Requirement.parse("foo!=0.3a4") + d = Distribution.from_filename + + self.assert_(d("foo-0.3a4.egg") not in r1) + self.assert_(d("foo-0.3a1.egg") not in r1) + self.assert_(d("foo-0.3a4.egg") not in r2) + + self.assert_(d("foo-0.3a2.egg") in r1) + self.assert_(d("foo-0.3a2.egg") in r2) + self.assert_(d("foo-0.3a3.egg") in r2) + self.assert_(d("foo-0.3a5.egg") in r2) + + def testDistributeSetuptoolsOverride(self): + # Plain setuptools or distribute mean we return distribute. + self.assertEqual( + Requirement.parse('setuptools').project_name, 'distribute') + self.assertEqual( + Requirement.parse('distribute').project_name, 'distribute') + # setuptools lower than 0.7 means distribute + self.assertEqual( + Requirement.parse('setuptools==0.6c9').project_name, 'distribute') + self.assertEqual( + Requirement.parse('setuptools==0.6c10').project_name, 'distribute') + self.assertEqual( + Requirement.parse('setuptools>=0.6').project_name, 'distribute') + self.assertEqual( + Requirement.parse('setuptools < 0.7').project_name, 'distribute') + # setuptools 0.7 and higher means setuptools. + self.assertEqual( + Requirement.parse('setuptools == 0.7').project_name, 'setuptools') + self.assertEqual( + Requirement.parse('setuptools == 0.7a1').project_name, 'setuptools') + self.assertEqual( + Requirement.parse('setuptools >= 0.7').project_name, 'setuptools') + + + + + + + + + + + +class ParseTests(TestCase): + + def testEmptyParse(self): + self.assertEqual(list(parse_requirements('')), []) + + def testYielding(self): + for inp,out in [ + ([], []), ('x',['x']), ([[]],[]), (' x\n y', ['x','y']), + (['x\n\n','y'], ['x','y']), + ]: + self.assertEqual(list(pkg_resources.yield_lines(inp)),out) + + def testSplitting(self): + self.assertEqual( + list( + pkg_resources.split_sections(""" + x + [Y] + z + + a + [b ] + # foo + c + [ d] + [q] + v + """ + ) + ), + [(None,["x"]), ("Y",["z","a"]), ("b",["c"]), ("d",[]), ("q",["v"])] + ) + self.assertRaises(ValueError,list,pkg_resources.split_sections("[foo")) + + def testSafeName(self): + self.assertEqual(safe_name("adns-python"), "adns-python") + self.assertEqual(safe_name("WSGI Utils"), "WSGI-Utils") + self.assertEqual(safe_name("WSGI Utils"), "WSGI-Utils") + self.assertEqual(safe_name("Money$$$Maker"), "Money-Maker") + self.assertNotEqual(safe_name("peak.web"), "peak-web") + + def testSafeVersion(self): + self.assertEqual(safe_version("1.2-1"), "1.2-1") + self.assertEqual(safe_version("1.2 alpha"), "1.2.alpha") + self.assertEqual(safe_version("2.3.4 20050521"), "2.3.4.20050521") + self.assertEqual(safe_version("Money$$$Maker"), "Money-Maker") + self.assertEqual(safe_version("peak.web"), "peak.web") + + def testSimpleRequirements(self): + self.assertEqual( + list(parse_requirements('Twis-Ted>=1.2-1')), + [Requirement('Twis-Ted',[('>=','1.2-1')], ())] + ) + self.assertEqual( + list(parse_requirements('Twisted >=1.2, \ # more\n<2.0')), + [Requirement('Twisted',[('>=','1.2'),('<','2.0')], ())] + ) + self.assertEqual( + Requirement.parse("FooBar==1.99a3"), + Requirement("FooBar", [('==','1.99a3')], ()) + ) + self.assertRaises(ValueError,Requirement.parse,">=2.3") + self.assertRaises(ValueError,Requirement.parse,"x\\") + self.assertRaises(ValueError,Requirement.parse,"x==2 q") + self.assertRaises(ValueError,Requirement.parse,"X==1\nY==2") + self.assertRaises(ValueError,Requirement.parse,"#") + + def testVersionEquality(self): + def c(s1,s2): + p1, p2 = parse_version(s1),parse_version(s2) + self.assertEqual(p1,p2, (s1,s2,p1,p2)) + + c('0.4', '0.4.0') + c('0.4.0.0', '0.4.0') + c('0.4.0-0', '0.4-0') + c('0pl1', '0.0pl1') + c('0pre1', '0.0c1') + c('0.0.0preview1', '0c1') + c('0.0c1', '0rc1') + c('1.2a1', '1.2.a.1'); c('1.2...a', '1.2a') + + def testVersionOrdering(self): + def c(s1,s2): + p1, p2 = parse_version(s1),parse_version(s2) + self.assert_(p1= (3,) and os.environ.get("LC_CTYPE") + in (None, "C", "POSIX")): + return + platform = sys.platform + sys.platform = 'java1.5.0_13' + stdout = sys.stdout + try: + # A mock sys.executable that uses a shebang line (this file) + exe = os.path.normpath(os.path.splitext(__file__)[0] + '.py') + self.assertEqual( + get_script_header('#!/usr/local/bin/python', executable=exe), + '#!/usr/bin/env %s\n' % exe) + + # Ensure we generate what is basically a broken shebang line + # when there's options, with a warning emitted + sys.stdout = sys.stderr = StringIO.StringIO() + self.assertEqual(get_script_header('#!/usr/bin/python -x', + executable=exe), + '#!%s -x\n' % exe) + self.assert_('Unable to adapt shebang line' in sys.stdout.getvalue()) + sys.stdout = sys.stderr = StringIO.StringIO() + self.assertEqual(get_script_header('#!/usr/bin/python', + executable=self.non_ascii_exe), + '#!%s -x\n' % self.non_ascii_exe) + self.assert_('Unable to adapt shebang line' in sys.stdout.getvalue()) + finally: + sys.platform = platform + sys.stdout = stdout + + + + +class NamespaceTests(TestCase): + + def setUp(self): + self._ns_pkgs = pkg_resources._namespace_packages.copy() + self._tmpdir = tempfile.mkdtemp(prefix="tests-distribute-") + os.makedirs(os.path.join(self._tmpdir, "site-pkgs")) + self._prev_sys_path = sys.path[:] + sys.path.append(os.path.join(self._tmpdir, "site-pkgs")) + + def tearDown(self): + shutil.rmtree(self._tmpdir) + pkg_resources._namespace_packages = self._ns_pkgs.copy() + sys.path = self._prev_sys_path[:] + + def _assertIn(self, member, container): + """ assertIn and assertTrue does not exist in Python2.3""" + if member not in container: + standardMsg = '%s not found in %s' % (safe_repr(member), + safe_repr(container)) + self.fail(self._formatMessage(msg, standardMsg)) + + def test_two_levels_deep(self): + """ + Test nested namespace packages + Create namespace packages in the following tree : + site-packages-1/pkg1/pkg2 + site-packages-2/pkg1/pkg2 + Check both are in the _namespace_packages dict and that their __path__ + is correct + """ + sys.path.append(os.path.join(self._tmpdir, "site-pkgs2")) + os.makedirs(os.path.join(self._tmpdir, "site-pkgs", "pkg1", "pkg2")) + os.makedirs(os.path.join(self._tmpdir, "site-pkgs2", "pkg1", "pkg2")) + ns_str = "__import__('pkg_resources').declare_namespace(__name__)\n" + for site in ["site-pkgs", "site-pkgs2"]: + pkg1_init = open(os.path.join(self._tmpdir, site, + "pkg1", "__init__.py"), "w") + pkg1_init.write(ns_str) + pkg1_init.close() + pkg2_init = open(os.path.join(self._tmpdir, site, + "pkg1", "pkg2", "__init__.py"), "w") + pkg2_init.write(ns_str) + pkg2_init.close() + import pkg1 + self._assertIn("pkg1", pkg_resources._namespace_packages.keys()) + try: + import pkg1.pkg2 + except ImportError, e: + self.fail("Distribute tried to import the parent namespace package") + # check the _namespace_packages dict + self._assertIn("pkg1.pkg2", pkg_resources._namespace_packages.keys()) + self.assertEqual(pkg_resources._namespace_packages["pkg1"], ["pkg1.pkg2"]) + # check the __path__ attribute contains both paths + self.assertEqual(pkg1.pkg2.__path__, [ + os.path.join(self._tmpdir, "site-pkgs", "pkg1", "pkg2"), + os.path.join(self._tmpdir, "site-pkgs2", "pkg1", "pkg2") ]) + + +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. + + +from openstack_dashboard.test.integration_tests import decorators +from openstack_dashboard.test.integration_tests import helpers +from openstack_dashboard.test.integration_tests.regions import messages + + +@decorators.services_required("neutron") +class TestNetworks(helpers.TestCase): + NETWORK_NAME = helpers.gen_random_resource_name("network") + SUBNET_NAME = helpers.gen_random_resource_name("subnet") + + def test_private_network_create(self): + """tests the network creation and deletion functionalities: + * creates a new private network and a new subnet associated with it + * verifies the network appears in the networks table as active + * deletes the newly created network + * verifies the network does not appear in the table after deletion + """ + + networks_page = self.home_pg.go_to_network_networkspage() + + networks_page.create_network(self.NETWORK_NAME, self.SUBNET_NAME) + self.assertTrue( + networks_page.find_message_and_dismiss(messages.SUCCESS)) + self.assertFalse( + networks_page.find_message_and_dismiss(messages.ERROR)) + self.assertTrue(networks_page.is_network_present(self.NETWORK_NAME)) + self.assertTrue(networks_page.is_network_active(self.NETWORK_NAME)) + + networks_page.delete_network(self.NETWORK_NAME) + self.assertTrue( + networks_page.find_message_and_dismiss(messages.SUCCESS)) + self.assertFalse( + networks_page.find_message_and_dismiss(messages.ERROR)) + self.assertFalse(networks_page.is_network_present(self.NETWORK_NAME)) + +# Copyright 2013 OpenStack Foundation +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. + +import datetime +import sys + +from keystoneclient.common import cms +from oslo.utils import timeutils +import six + +from keystone.common import controller +from keystone.common import dependency +from keystone.common import wsgi +from keystone import config +from keystone import exception +from keystone.i18n import _ +from keystone.models import token_model +from keystone.openstack.common import jsonutils +from keystone.openstack.common import log +from keystone.token import provider + + +CONF = config.CONF +LOG = log.getLogger(__name__) + + +class ExternalAuthNotApplicable(Exception): + """External authentication is not applicable.""" + pass + + +@dependency.requires('assignment_api', 'catalog_api', 'identity_api', + 'token_provider_api', 'trust_api') +class Auth(controller.V2Controller): + + @controller.v2_deprecated + def ca_cert(self, context, auth=None): + ca_file = open(CONF.signing.ca_certs, 'r') + data = ca_file.read() + ca_file.close() + return data + + @controller.v2_deprecated + def signing_cert(self, context, auth=None): + cert_file = open(CONF.signing.certfile, 'r') + data = cert_file.read() + cert_file.close() + return data + + @controller.v2_deprecated + def authenticate(self, context, auth=None): + """Authenticate credentials and return a token. + + Accept auth as a dict that looks like:: + + { + "auth":{ + "passwordCredentials":{ + "username":"test_user", + "password":"mypass" + }, + "tenantName":"customer-x" + } + } + + In this case, tenant is optional, if not provided the token will be + considered "unscoped" and can later be used to get a scoped token. + + Alternatively, this call accepts auth with only a token and tenant + that will return a token that is scoped to that tenant. + """ + + if auth is None: + raise exception.ValidationError(attribute='auth', + target='request body') + + if "token" in auth: + # Try to authenticate using a token + auth_info = self._authenticate_token( + context, auth) + else: + # Try external authentication + try: + auth_info = self._authenticate_external( + context, auth) + except ExternalAuthNotApplicable: + # Try local authentication + auth_info = self._authenticate_local( + context, auth) + + user_ref, tenant_ref, metadata_ref, expiry, bind, audit_id = auth_info + # Validate that the auth info is valid and nothing is disabled + try: + self.identity_api.assert_user_enabled( + user_id=user_ref['id'], user=user_ref) + self.assignment_api.assert_domain_enabled( + domain_id=user_ref['domain_id']) + if tenant_ref: + self.assignment_api.assert_project_enabled( + project_id=tenant_ref['id'], project=tenant_ref) + except AssertionError as e: + six.reraise(exception.Unauthorized, exception.Unauthorized(e), + sys.exc_info()[2]) + # NOTE(morganfainberg): Make sure the data is in correct form since it + # might be consumed external to Keystone and this is a v2.0 controller. + # The user_ref is encoded into the auth_token_data which is returned as + # part of the token data. The token provider doesn't care about the + # format. + user_ref = self.v3_to_v2_user(user_ref) + if tenant_ref: + tenant_ref = self.filter_domain_id(tenant_ref) + auth_token_data = self._get_auth_token_data(user_ref, + tenant_ref, + metadata_ref, + expiry, + audit_id) + + if tenant_ref: + catalog_ref = self.catalog_api.get_catalog( + user_ref['id'], tenant_ref['id'], metadata_ref) + else: + catalog_ref = {} + + auth_token_data['id'] = 'placeholder' + if bind: + auth_token_data['bind'] = bind + + roles_ref = [] + for role_id in metadata_ref.get('roles', []): + role_ref = self.assignment_api.get_role(role_id) + roles_ref.append(dict(name=role_ref['name'])) + + (token_id, token_data) = self.token_provider_api.issue_v2_token( + auth_token_data, roles_ref=roles_ref, catalog_ref=catalog_ref) + + # NOTE(wanghong): We consume a trust use only when we are using trusts + # and have successfully issued a token. + if CONF.trust.enabled and 'trust_id' in auth: + self.trust_api.consume_use(auth['trust_id']) + + return token_data + + def _authenticate_token(self, context, auth): + """Try to authenticate using an already existing token. + + Returns auth_token_data, (user_ref, tenant_ref, metadata_ref) + """ + if 'token' not in auth: + raise exception.ValidationError( + attribute='token', target='auth') + + if "id" not in auth['token']: + raise exception.ValidationError( + attribute="id", target="token") + + old_token = auth['token']['id'] + if len(old_token) > CONF.max_token_size: + raise exception.ValidationSizeError(attribute='token', + size=CONF.max_token_size) + + try: + token_model_ref = token_model.KeystoneToken( + token_id=old_token, + token_data=self.token_provider_api.validate_token(old_token)) + except exception.NotFound as e: + raise exception.Unauthorized(e) + + wsgi.validate_token_bind(context, token_model_ref) + + # A trust token cannot be used to get another token + if token_model_ref.trust_scoped: + raise exception.Forbidden() + + user_id = token_model_ref.user_id + tenant_id = self._get_project_id_from_auth(auth) + + if not CONF.trust.enabled and 'trust_id' in auth: + raise exception.Forbidden('Trusts are disabled.') + elif CONF.trust.enabled and 'trust_id' in auth: + trust_ref = self.trust_api.get_trust(auth['trust_id']) + if trust_ref is None: + raise exception.Forbidden() + if user_id != trust_ref['trustee_user_id']: + raise exception.Forbidden() + if (trust_ref['project_id'] and + tenant_id != trust_ref['project_id']): + raise exception.Forbidden() + if ('expires' in trust_ref) and (trust_ref['expires']): + expiry = trust_ref['expires'] + if expiry < timeutils.parse_isotime(timeutils.isotime()): + raise exception.Forbidden()() + user_id = trust_ref['trustor_user_id'] + trustor_user_ref = self.identity_api.get_user( + trust_ref['trustor_user_id']) + if not trustor_user_ref['enabled']: + raise exception.Forbidden()() + trustee_user_ref = self.identity_api.get_user( + trust_ref['trustee_user_id']) + if not trustee_user_ref['enabled']: + raise exception.Forbidden()() + + if trust_ref['impersonation'] is True: + current_user_ref = trustor_user_ref + else: + current_user_ref = trustee_user_ref + + else: + current_user_ref = self.identity_api.get_user(user_id) + + metadata_ref = {} + tenant_ref, metadata_ref['roles'] = self._get_project_roles_and_ref( + user_id, tenant_id) + + expiry = token_model_ref.expires + if CONF.trust.enabled and 'trust_id' in auth: + trust_id = auth['trust_id'] + trust_roles = [] + for role in trust_ref['roles']: + if 'roles' not in metadata_ref: + raise exception.Forbidden()() + if role['id'] in metadata_ref['roles']: + trust_roles.append(role['id']) + else: + raise exception.Forbidden() + if 'expiry' in trust_ref and trust_ref['expiry']: + trust_expiry = timeutils.parse_isotime(trust_ref['expiry']) + if trust_expiry < expiry: + expiry = trust_expiry + metadata_ref['roles'] = trust_roles + metadata_ref['trustee_user_id'] = trust_ref['trustee_user_id'] + metadata_ref['trust_id'] = trust_id + + bind = token_model_ref.bind + audit_id = token_model_ref.audit_chain_id + + return (current_user_ref, tenant_ref, metadata_ref, expiry, bind, + audit_id) + + def _authenticate_local(self, context, auth): + """Try to authenticate against the identity backend. + + Returns auth_token_data, (user_ref, tenant_ref, metadata_ref) + """ + if 'passwordCredentials' not in auth: + raise exception.ValidationError( + attribute='passwordCredentials', target='auth') + + if "password" not in auth['passwordCredentials']: + raise exception.ValidationError( + attribute='password', target='passwordCredentials') + + password = auth['passwordCredentials']['password'] + if password and len(password) > CONF.identity.max_password_length: + raise exception.ValidationSizeError( + attribute='password', size=CONF.identity.max_password_length) + + if ("userId" not in auth['passwordCredentials'] and + "username" not in auth['passwordCredentials']): + raise exception.ValidationError( + attribute='username or userId', + target='passwordCredentials') + + user_id = auth['passwordCredentials'].get('userId') + if user_id and len(user_id) > CONF.max_param_size: + raise exception.ValidationSizeError(attribute='userId', + size=CONF.max_param_size) + + username = auth['passwordCredentials'].get('username', '') + + if username: + if len(username) > CONF.max_param_size: + raise exception.ValidationSizeError(attribute='username', + size=CONF.max_param_size) + try: + user_ref = self.identity_api.get_user_by_name( + username, CONF.identity.default_domain_id) + user_id = user_ref['id'] + except exception.UserNotFound as e: + raise exception.Unauthorized(e) + + try: + user_ref = self.identity_api.authenticate( + context, + user_id=user_id, + password=password) + except AssertionError as e: + raise exception.Unauthorized(e.args[0]) + + metadata_ref = {} + tenant_id = self._get_project_id_from_auth(auth) + tenant_ref, metadata_ref['roles'] = self._get_project_roles_and_ref( + user_id, tenant_id) + + expiry = provider.default_expire_time() + bind = None + audit_id = None + return (user_ref, tenant_ref, metadata_ref, expiry, bind, audit_id) + + def _authenticate_external(self, context, auth): + """Try to authenticate an external user via REMOTE_USER variable. + + Returns auth_token_data, (user_ref, tenant_ref, metadata_ref) + """ + environment = context.get('environment', {}) + if not environment.get('REMOTE_USER'): + raise ExternalAuthNotApplicable() + + # NOTE(jamielennox): xml and json differ and get confused about what + # empty auth should look like so just reset it. + if not auth: + auth = {} + + username = environment['REMOTE_USER'] + try: + user_ref = self.identity_api.get_user_by_name( + username, CONF.identity.default_domain_id) + user_id = user_ref['id'] + except exception.UserNotFound as e: + raise exception.Unauthorized(e) + + metadata_ref = {} + tenant_id = self._get_project_id_from_auth(auth) + tenant_ref, metadata_ref['roles'] = self._get_project_roles_and_ref( + user_id, tenant_id) + + expiry = provider.default_expire_time() + bind = None + if ('kerberos' in CONF.token.bind and + environment.get('AUTH_TYPE', '').lower() == 'negotiate'): + bind = {'kerberos': username} + audit_id = None + + return (user_ref, tenant_ref, metadata_ref, expiry, bind, audit_id) + + def _get_auth_token_data(self, user, tenant, metadata, expiry, audit_id): + return dict(user=user, + tenant=tenant, + metadata=metadata, + expires=expiry, + parent_audit_id=audit_id) + + def _get_project_id_from_auth(self, auth): + """Extract tenant information from auth dict. + + Returns a valid tenant_id if it exists, or None if not specified. + """ + tenant_id = auth.get('tenantId') + if tenant_id and len(tenant_id) > CONF.max_param_size: + raise exception.ValidationSizeError(attribute='tenantId', + size=CONF.max_param_size) + + tenant_name = auth.get('tenantName') + if tenant_name and len(tenant_name) > CONF.max_param_size: + raise exception.ValidationSizeError(attribute='tenantName', + size=CONF.max_param_size) + + if tenant_name: + try: + tenant_ref = self.assignment_api.get_project_by_name( + tenant_name, CONF.identity.default_domain_id) + tenant_id = tenant_ref['id'] + except exception.ProjectNotFound as e: + raise exception.Unauthorized(e) + return tenant_id + + def _get_project_roles_and_ref(self, user_id, tenant_id): + """Returns the project roles for this user, and the project ref.""" + + tenant_ref = None + role_list = [] + if tenant_id: + try: + tenant_ref = self.assignment_api.get_project(tenant_id) + role_list = self.assignment_api.get_roles_for_user_and_project( + user_id, tenant_id) + except exception.ProjectNotFound: + pass + + if not role_list: + msg = _('User %(u_id)s is unauthorized for tenant %(t_id)s') + msg = msg % {'u_id': user_id, 't_id': tenant_id} + LOG.warning(msg) + raise exception.Unauthorized(msg) + + return (tenant_ref, role_list) + + def _get_token_ref(self, token_id, belongs_to=None): + """Returns a token if a valid one exists. + + Optionally, limited to a token owned by a specific tenant. + + """ + token_ref = token_model.KeystoneToken( + token_id=token_id, + token_data=self.token_provider_api.validate_token(token_id)) + if belongs_to: + if not token_ref.project_scoped: + raise exception.Unauthorized( + _('Token does not belong to specified tenant.')) + if token_ref.project_id != belongs_to: + raise exception.Unauthorized( + _('Token does not belong to specified tenant.')) + return token_ref + + @controller.v2_deprecated + @controller.protected() + def validate_token_head(self, context, token_id): + """Check that a token is valid. + + Optionally, also ensure that it is owned by a specific tenant. + + Identical to ``validate_token``, except does not return a response. + + The code in ``keystone.common.wsgi.render_response`` will remove + the content body. + + """ + # TODO(ayoung) validate against revocation API + belongs_to = context['query_string'].get('belongsTo') + return self.token_provider_api.validate_v2_token(token_id, belongs_to) + + @controller.v2_deprecated + @controller.protected() + def validate_token(self, context, token_id): + """Check that a token is valid. + + Optionally, also ensure that it is owned by a specific tenant. + + Returns metadata about the token along any associated roles. + + """ + belongs_to = context['query_string'].get('belongsTo') + # TODO(ayoung) validate against revocation API + return self.token_provider_api.validate_v2_token(token_id, belongs_to) + + @controller.v2_deprecated + def delete_token(self, context, token_id): + """Delete a token, effectively invalidating it for authz.""" + # TODO(termie): this stuff should probably be moved to middleware + self.assert_admin(context) + self.token_provider_api.revoke_token(token_id) + + @controller.v2_deprecated + @controller.protected() + def revocation_list(self, context, auth=None): + if not CONF.token.revoke_by_id: + raise exception.Gone() + tokens = self.token_provider_api.list_revoked_tokens() + + for t in tokens: + expires = t['expires'] + if expires and isinstance(expires, datetime.datetime): + t['expires'] = timeutils.isotime(expires) + data = {'revoked': tokens} + json_data = jsonutils.dumps(data) + signed_text = cms.cms_sign_text(json_data, + CONF.signing.certfile, + CONF.signing.keyfile) + + return {'signed': signed_text} + + @controller.v2_deprecated + def endpoints(self, context, token_id): + """Return a list of endpoints available to the token.""" + self.assert_admin(context) + + token_ref = self._get_token_ref(token_id) + + catalog_ref = None + if token_ref.project_id: + catalog_ref = self.catalog_api.get_catalog( + token_ref.user_id, + token_ref.project_id, + token_ref.metadata) + + return Auth.format_endpoint_list(catalog_ref) + + @classmethod + def format_endpoint_list(cls, catalog_ref): + """Formats a list of endpoints according to Identity API v2. + + The v2.0 API wants an endpoint list to look like:: + + { + 'endpoints': [ + { + 'id': $endpoint_id, + 'name': $SERVICE[name], + 'type': $SERVICE, + 'tenantId': $tenant_id, + 'region': $REGION, + } + ], + 'endpoints_links': [], + } + + """ + if not catalog_ref: + return {} + + endpoints = [] + for region_name, region_ref in six.iteritems(catalog_ref): + for service_type, service_ref in six.iteritems(region_ref): + endpoints.append({ + 'id': service_ref.get('id'), + 'name': service_ref.get('name'), + 'type': service_type, + 'region': region_name, + 'publicURL': service_ref.get('publicURL'), + 'internalURL': service_ref.get('internalURL'), + 'adminURL': service_ref.get('adminURL'), + }) + + return {'endpoints': endpoints, 'endpoints_links': []} + +import distutils.command.bdist_rpm as orig + + +class bdist_rpm(orig.bdist_rpm): + """ + Override the default bdist_rpm behavior to do the following: + + 1. Run egg_info to ensure the name and version are properly calculated. + 2. Always run 'install' using --single-version-externally-managed to + disable eggs in RPM distributions. + 3. Replace dash with underscore in the version numbers for better RPM + compatibility. + """ + + def run(self): + # ensure distro name is up-to-date + self.run_command('egg_info') + + orig.bdist_rpm.run(self) + + def _make_spec_file(self): + version = self.distribution.get_version() + rpmversion = version.replace('-', '_') + spec = orig.bdist_rpm._make_spec_file(self) + line23 = '%define version ' + version + line24 = '%define version ' + rpmversion + spec = [ + line.replace( + "Source0: %{name}-%{version}.tar", + "Source0: %{name}-%{unmangled_version}.tar" + ).replace( + "setup.py install ", + "setup.py install --single-version-externally-managed " + ).replace( + "%setup", + "%setup -n %{name}-%{unmangled_version}" + ).replace(line23, line24) + for line in spec + ] + insert_loc = spec.index(line24) + 1 + unmangled_version = "%define unmangled_version " + version + spec.insert(insert_loc, unmangled_version) + return spec + +# This file implements a shared lock that lets us ensure that the test cases in +# this directory run serially. Each test case obtains this lock as its first +# step, and releases it as its last. (The nel_test helper function in +# nel.sub.js automates this process.) Because the lock needs to be shared +# across all of the test cases, we use a hard-coded stash key. This hard-coded +# key is a random UUID, which should not conflict with any other auto-generated +# stash keys. + +import time + +_LOCK_KEY = "67966d2e-a847-41d8-b7c3-5f6aee3375ba" +_TIMEOUT = 5 # seconds + +def wait_for_lock(request): + t0 = time.time() + while time.time() - t0 < _TIMEOUT: + time.sleep(0.5) + value = request.server.stash.take(key=_LOCK_KEY) + if value is None: + return True + return False + +def lock(request, report_id): + with request.server.stash.lock: + # Loop until the lock is free + if not wait_for_lock(request): + return (503, [], "Cannot obtain lock") + request.server.stash.put(key=_LOCK_KEY, value=report_id) + return "Obtained lock for %s" % report_id + +def unlock(request, report_id): + with request.server.stash.lock: + lock_holder = request.server.stash.take(key=_LOCK_KEY) + if lock_holder != report_id: + # Return the lock holder to the stash + request.server.stash.put(key=_LOCK_KEY, value=lock_holder) + return (503, [], "Cannot release lock held by %s" % lock_holder) + return "Released lock for %s" % report_id + +def main(request, response): + op = request.GET.first("op") + report_id = request.GET.first("reportID") + if op == "lock": + return lock(request, report_id) + elif op == "unlock": + return unlock(request, report_id) + else: + return (400, [], "Invalid op") + +# ---------------------------------------------------------------------------- +# Copyright 2014 Nervana Systems Inc. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------- +""" +Contains various loss related metrics ex. log loss +""" + +import numpy + +from neon.metrics.metric import Metric +from neon.util.param import opt_param + + +class LogLossSum(Metric): + """ + Logistic loss (aka cross-entropy loss) for a multi-class classification + task. Defined to be the negative log of the likelihood summed across all + data points received. + + Arguments: + eps (float, optional): Amount to clip values by to prevent potential + numeric difficulties (taking log of 0). + + See Also: + LogLossMean + + References: + Bishop2006 (p. 209) + """ + def __init__(self, **kwargs): + super(LogLossSum, self).__init__(**kwargs) + opt_param(self, ['eps'], 1e-15) + + def add(self, reference, outputs): + """ + Add the the expected reference and predicted outputs passed to the set + of values used to calculate this metric. + + Arguments: + reference (neon.backend.Tensor): Ground truth, expected outcomes. + If each outcome is a vector, we + expect it to be a column vector, + with each case in a separate + (one-hot encoded) column. + outputs (neon.backend.Tensor): Predicted outputs. Must have the + same dimensions as reference. To + prevent numeric difficulties, output + probabilities will be scaled to lie + within [self.eps, 1 - self.eps] + """ + ismixed = ((reference.shape[0] == 1) and (outputs.shape[0] > 1) and + (reference.shape[1] == outputs.shape[1])) + if (reference.shape != outputs.shape) and (not ismixed): + raise ValueError("reference dimensions: %s, incompatible with " + "outputs dimensions: %s" % + (str(reference.shape), str(outputs.shape))) + # clip and normalize predictions + preds = outputs.asnumpyarray().clip(self.eps, (1.0 - self.eps)) + preds = numpy.log(preds / preds.sum(axis=0)) + if ismixed: + ref = reference.asnumpyarray().ravel().astype(int) + reference = numpy.eye(outputs.shape[0], dtype=int)[ref].T + self.logloss += (reference * preds).sum() + else: + self.logloss += (reference.asnumpyarray() * preds).sum() + + def report(self): + """ + Report the log loss value + + Returns: + float: log loss value + """ + return - self.logloss + + def clear(self): + """ + Reset this metric's calculated value + """ + self.logloss = 0.0 + + +class LogLossMean(LogLossSum): + """ + Logistic loss (aka cross-entropy loss) for a multi-class classification + task. Defined to be the negative log of the likelihood averaged across all + data points received. + + Arguments: + eps (float, optional): Amount to clip values by to prevent potential + numeric difficulties (taking log of 0). + + See Also: + LogLossSum + """ + + def add(self, reference, outputs): + """ + Add the the expected reference and predicted outputs passed to the set + of values used to calculate this metric. + + Arguments: + reference (neon.backend.Tensor): Ground truth, expected outcomes. + If each outcome is a vector, we + expect it to be a column vector, + with each case in a separate + (one-hot encoded) column. + outputs (neon.backend.Tensor): Predicted outputs. Must have the + same dimensions as reference. To + prevent numeric difficulties, output + probabilities will be scaled to lie + within [self.eps, 1 - self.eps] + """ + super(LogLossMean, self).add(reference, outputs) + self.rec_count += reference.shape[-1] + + def report(self): + """ + Report the mean log loss value + + Returns: + float: log loss mean value + """ + return super(LogLossMean, self).report() / self.rec_count + + def clear(self): + """ + Reset this metric's calculated value + """ + super(LogLossMean, self).clear() + self.rec_count = 0.0 + +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2004-2009 Tiny SPRL (). +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as +# published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +############################################################################## + +import time + +from openerp.report import report_sxw + +class ir_module_reference_print(report_sxw.rml_parse): + def __init__(self, cr, uid, name, context): + super(ir_module_reference_print, self).__init__(cr, uid, name, context=context) + self.localcontext.update({ + 'time': time, + 'findobj': self._object_find, + 'objdoc': self._object_doc, + 'objdoc2': self._object_doc2, + 'findflds': self._fields_find, + }) + def _object_doc(self, obj): + modobj = self.pool[obj] + strdocs= modobj.__doc__ + if not strdocs: + return None + else: + strdocs=strdocs.strip().splitlines(True) + res = '' + for stre in strdocs: + if not stre or stre.isspace(): + break + res += stre + return res + + def _object_doc2(self, obj): + modobj = self.pool[obj] + strdocs= modobj.__doc__ + if not strdocs: + return None + else: + strdocs=strdocs.strip().splitlines(True) + res = [] + fou = False + for stre in strdocs: + if fou: + res.append(stre.strip()) + elif not stre or stre.isspace(): + fou = True + return res + + def _object_find(self, module): + ids2 = self.pool['ir.model.data'].search(self.cr, self.uid, [('module','=',module), ('model','=','ir.model')]) + ids = [] + for mod in self.pool['ir.model.data'].browse(self.cr, self.uid, ids2): + ids.append(mod.res_id) + modobj = self.pool['ir.model'] + return modobj.browse(self.cr, self.uid, ids) + + def _fields_find(self, obj, module): + res = [] + data_obj = self.pool['ir.model.data'] + modobj = self.pool[obj] + fname_wildcard = 'field_' + modobj._name.replace('.', '_') + '_%' + module_fields_ids = data_obj.search(self.cr, self.uid, [('model', '=', 'ir.model.fields'), ('module', '=', module), ('name', 'like', fname_wildcard)]) + if module_fields_ids: + module_fields_res_ids = [x['res_id'] for x in data_obj.read(self.cr, self.uid, module_fields_ids, ['res_id'])] + module_fields_names = [x['name'] for x in self.pool['ir.model.fields'].read(self.cr, self.uid, module_fields_res_ids, ['name'])] + res = modobj.fields_get(self.cr, self.uid, allfields=module_fields_names).items() + res.sort() + return res + +report_sxw.report_sxw('report.ir.module.reference', 'ir.module.module', + 'addons/base/module/report/ir_module_reference.rml', + parser=ir_module_reference_print, header=False) + + +# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: + + +"""Gaussian Process models for Keras 2.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from keras.models import Model as KerasModel +from keras.engine.topology import _to_list +from keras.engine.training import _standardize_input_data + +from .callbacks import UpdateGP + + +class Model(KerasModel): + """Model that supports arbitrary structure with GP output layers. + + This class extends `keras.models.Model` and allows using Gaussian Processes + as output layers. The model completely inherits the function interface + of Keras and is constructed in a standard way. + + On training, GPs are optimized using empirical Bayes (log marginal + likelihood maximization) using semi-stochastic alternating scheme with + delayed kernel matrix updates [1]. Non-GP output layers can use one the + standard Keras objectives, e.g., the mean squared error. + """ + def __init__(self, inputs, outputs, name=None): + super(Model, self).__init__(inputs, outputs, name) + + # List all output GP layers + self.output_gp_layers = [layer for layer in self.output_layers + if layer.name.startswith('gp')] + + def compile(self, optimizer, loss, metrics=None, loss_weights=None, + sample_weight_mode=None, **kwargs): + super(Model, self).compile(optimizer, loss, metrics, loss_weights, + sample_weight_mode, **kwargs) + + # Remove the metrics meaningless for GP output layers + self.metrics_tensors = [ + mt for mt, mn in zip(self.metrics_tensors, self.metrics_names[1:]) + if not (mn.startswith('gp') and mn.endswith('loss')) + ] + self.metrics_names = [ + mn for mn in self.metrics_names + if not (mn.startswith('gp') and mn.endswith('loss')) + ] + + # Add MSE and NLML metrics for each output GP + for gp in self.output_gp_layers: + self.metrics_tensors.extend([gp.mse, gp.nlml]) + self.metrics_names.extend([gp.name + '_mse', gp.name + '_nlml']) + + # Add cumulative MSE & NLML metrics + self.mse = sum([gp.mse for gp in self.output_gp_layers]) + self.nlml = sum([gp.nlml for gp in self.output_gp_layers]) + self.metrics_tensors.extend([self.mse, self.nlml]) + self.metrics_names.extend(['mse', 'nlml']) + + def transform(self, x, batch_size=32, learning_phase=0., verbose=0): + h = super(Model, self).predict(x, batch_size, learning_phase, verbose) + return _to_list(h) + + def fit(self, X, Y, + batch_size=32, + epochs=1, + gp_n_iter=1, + verbose=1, + callbacks=None, + validation_split=0., + validation_data=None, + shuffle=True, + class_weight=None, + sample_weight=None, + initial_epoch=0, + **kwargs): + """Trains the model for a fixed number of epochs (iterations on a dataset). + + For argument details, refer to `keras.engine.training.Model.fit`. + + Notes: + The following arguments are currently unsupported by models with GP + output layers: + - validation_split + - class_weight + - sample_weight + """ + # Validate user data + X, Y, _ = self._standardize_user_data( + X, Y, + sample_weight=None, + class_weight=None, + check_batch_axis=False, + batch_size=batch_size) + if validation_data is not None: + X_val, Y_val, _ = self._standardize_user_data( + *validation_data, + sample_weight=None, + class_weight=None, + check_batch_axis=False, + batch_size=batch_size) + validation_data = (X_val, Y_val) + + # Setup GP updates + update_gp = UpdateGP(ins=(X, Y), + val_ins=validation_data, + batch_size=batch_size, + gp_n_iter=gp_n_iter, + verbose=verbose) + callbacks = [update_gp] + (callbacks or []) + + return super(Model, self).fit( + X, Y, + batch_size=batch_size, + epochs=epochs, + verbose=verbose, + callbacks=callbacks, + shuffle=shuffle, + initial_epoch=initial_epoch, + **kwargs) + + def finetune(self, X, Y, batch_size=32, gp_n_iter=1, verbose=1): + """Finetune the output GP layers assuming the network is pre-trained. + + Arguments: + ---------- + X : np.ndarray or list of np.ndarrays + Y : np.ndarray or list of np.ndarrays + batch_size : uint (default: 128) + Batch size used for data streaming through the network. + gp_n_iter : uint (default: 100) + Number of iterations for GP training. + verbose : uint (default: 1) + Verbosity mode, 0 or 1. + """ + # Validate user data + X = _standardize_input_data( + X, self._feed_input_names, self._feed_input_shapes, + check_batch_axis=False, exception_prefix='input') + + H = self.transform(X, batch_size=batch_size) + + if verbose: + print("Finetuning output GPs...") + + for gp, h, y in zip(self.output_gp_layers, H, Y): + # Update GP data (and grid if necessary) + gp.backend.update_data('tr', h, y) + if gp.update_grid: + gp.backend.update_grid('tr') + + # Train GP + gp.hyp = gp.backend.train(gp_n_iter, verbose=verbose) + + if verbose: + print("Done.") + + def evaluate(self, X, Y, batch_size=32, verbose=0): + """Compute NLML on the given data. + + Arguments: + ---------- + X : np.ndarray or list of np.ndarrays + Y : np.ndarray or list of np.ndarrays + batch_size : uint (default: 128) + verbose : uint (default: 0) + Verbosity mode, 0 or 1. + + Returns: + -------- + nlml : float + """ + # Validate user data + X, Y, _ = self._standardize_user_data( + X, Y, + sample_weight=None, + class_weight=None, + check_batch_axis=False, + batch_size=batch_size) + + H = self.transform(X, batch_size=batch_size) + + nlml = 0. + for gp, h, y in zip(self.output_gp_layers, H, Y): + nlml += gp.backend.evaluate('tmp', h, y) + + return nlml + + def predict(self, X, X_tr=None, Y_tr=None, + batch_size=32, return_var=False, verbose=0): + """Generate output predictions for the input samples batch by batch. + + Arguments: + ---------- + X : np.ndarray or list of np.ndarrays + batch_size : uint (default: 128) + return_var : bool (default: False) + Whether predictive variance is returned. + verbose : uint (default: 0) + Verbosity mode, 0 or 1. + + Returns: + -------- + preds : a list or a tuple of lists + Lists of output predictions and variance estimates. + """ + # Update GP data if provided (and grid if necessary) + if X_tr is not None and Y_tr is not None: + X_tr, Y_tr, _ = self._standardize_user_data( + X_tr, Y_tr, + sample_weight=None, + class_weight=None, + check_batch_axis=False, + batch_size=batch_size) + H_tr = self.transform(X_tr, batch_size=batch_size) + for gp, h, y in zip(self.output_gp_layers, H_tr, Y_tr): + gp.backend.update_data('tr', h, y) + if gp.update_grid: + gp.backend.update_grid('tr') + + # Validate user data + X = _standardize_input_data( + X, self._feed_input_names, self._feed_input_shapes, + check_batch_axis=False, exception_prefix='input') + + H = self.transform(X, batch_size=batch_size) + + preds = [] + for gp, h in zip(self.output_gp_layers, H): + preds.append(gp.backend.predict(h, return_var=return_var)) + + if return_var: + preds = map(list, zip(*preds)) + + return preds + + +# Apply tweaks +from . import tweaks + +""" Glyph renderer models for displaying simple scatter-type +markers on Bokeh plots. + +""" +from __future__ import absolute_import + +from .glyphs import Glyph +from ..enums import enumeration +from ..mixins import FillProps, LineProps +from ..properties import abstract +from ..properties import DistanceSpec, Enum, Include, NumberSpec, ScreenDistanceSpec + +@abstract +class Marker(Glyph): + """ Base class for glyphs that are simple markers with line and + fill properties, located at an (x, y) location with a specified + size. + + .. note:: + For simplicity, all markers have both line and fill properties + declared, however some markers (`Asterisk`, `Cross`, `X`) only + draw lines. For these markers, the fill values are simply + ignored. + + """ + + x = NumberSpec("x", help=""" + The x-axis coordinates for the center of the markers. + """) + + y = NumberSpec("y", help=""" + The y-axis coordinates for the center of the markers. + """) + + size = ScreenDistanceSpec(default=4, help=""" + The size (diameter) values for the markers. Interpreted as + "screen space" units by default. + """) + + angle = NumberSpec("angle", help=""" + The angles to rotate the markers. + """) + + line_props = Include(LineProps, use_prefix=False, help=""" + The %s values for the markers. + """) + + fill_props = Include(FillProps, use_prefix=False, help=""" + The %s values for the markers. + """) + +class Asterisk(Marker): + """ Render asterisk '*' markers. + + Example + ------- + + .. bokeh-plot:: ../tests/glyphs/Asterisk.py + :source-position: none + + *source:* ``tests/glyphs/Asterisk.py`` + + """ + +class Circle(Marker): + """ Render circle markers. + + Example + ------- + + .. bokeh-plot:: ../tests/glyphs/Circle.py + :source-position: none + + *source:* ``tests/glyphs/Circle.py`` + + """ + + radius = DistanceSpec("radius", help=""" + The radius values for circle markers. Interpreted in + "data space" units by default. + + .. note:: + Circle markers are slightly unusual in that they support specifying + a radius in addition to a size. Only one of ``radius`` or ``size`` + should be given. + + .. warning:: + Note that ``Circle`` glyphs are always drawn as circles on the screen, + even in cases where the data space aspect ratio is not 1-1. In all + cases where radius or size units are specified as "data", the + "distance" for the radius is measured along the horizontal axis. + If the aspect ratio is very large or small, the drawn circles may + appear much larger or smaller than expected. See :bokeh-issue:`626` + for more information. + + """) + + radius_dimension = Enum(enumeration('x', 'y'), help=""" + What dimension to measure circle radii along. + + When the data space aspect ratio is not 1-1, then the size of the drawn + circles depends on what direction is used to measure the "distance" of + the radius. This property allows that direction to be controlled. + """) + +class CircleCross(Marker): + """ Render circle markers with a '+' cross through the center. + + Example + ------- + + .. bokeh-plot:: ../tests/glyphs/CircleCross.py + :source-position: none + + *source:* ``tests/glyphs/CircleCross.py`` + + """ + +class CircleX(Marker): + """ Render circle markers with an 'X' cross through the center. + + Example + ------- + + .. bokeh-plot:: ../tests/glyphs/CircleX.py + :source-position: none + + *source:* ``tests/glyphs/CircleX.py`` + + """ + +class Cross(Marker): + """ Render '+' cross markers. + + Example + ------- + + .. bokeh-plot:: ../tests/glyphs/Cross.py + :source-position: none + + *source:* ``tests/glyphs/Cross.py`` + + """ + +class Diamond(Marker): + """ Render diamond markers. + + Example + ------- + + .. bokeh-plot:: ../tests/glyphs/Diamond.py + :source-position: none + + *source:* ``tests/glyphs/Diamond.py`` + + """ + +class DiamondCross(Marker): + """ Render diamond markers with a '+' cross through the center. + + Example + ------- + + .. bokeh-plot:: ../tests/glyphs/DiamondCross.py + :source-position: none + + *source:* ``tests/glyphs/DiamondCross.py`` + + """ + +class InvertedTriangle(Marker): + """ Render upside-down triangle markers. + + Example + ------- + + .. bokeh-plot:: ../tests/glyphs/InvertedTriangle.py + :source-position: none + + *source:* ``tests/glyphs/InvertedTriangle.py`` + + """ + +class Square(Marker): + """ Render a square marker, optionally rotated. + + Example + ------- + + .. bokeh-plot:: ../tests/glyphs/Square.py + :source-position: none + + *source:* ``tests/glyphs/Square.py`` + + """ + +class SquareCross(Marker): + """ Render square markers with a '+' cross through the center. + + Example + ------- + + .. bokeh-plot:: ../tests/glyphs/SquareCross.py + :source-position: none + + *source:* ``tests/glyphs/SquareCross.py`` + + """ + +class SquareX(Marker): + """ Render square markers with an 'X' cross through the center. + + Example + ------- + + .. bokeh-plot:: ../tests/glyphs/SquareX.py + :source-position: none + + *source:* ``tests/glyphs/SquareX.py`` + + """ + +class Triangle(Marker): + """ Render triangle markers. + + Example + ------- + + .. bokeh-plot:: ../tests/glyphs/Triangle.py + :source-position: none + + *source:* ``tests/glyphs/Triangle.py`` + + """ + +class X(Marker): + """ Render a 'X' cross markers. + + Example + ------- + + .. bokeh-plot:: ../tests/glyphs/X.py + :source-position: none + + *source:* ``tests/glyphs/X.py`` + + """ + +# (c) 2015, Ansible Inc, +# +# This file is part of Ansible +# +# Ansible is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Ansible is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Ansible. If not, see . +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + + +from ansible.plugins.action import ActionBase + + +class ActionModule(ActionBase): + + TRANSFERS_FILES = False + + UNUSED_PARAMS = { + 'systemd': ['pattern', 'runlevel', 'sleep', 'arguments', 'args'], + } + + def run(self, tmp=None, task_vars=None): + ''' handler for package operations ''' + + self._supports_check_mode = True + self._supports_async = True + + result = super(ActionModule, self).run(tmp, task_vars) + + module = self._task.args.get('use', 'auto').lower() + + if module == 'auto': + try: + if self._task.delegate_to: # if we delegate, we should use delegated host's facts + module = self._templar.template("{{hostvars['%s']['ansible_facts']['ansible_service_mgr']}}" % self._task.delegate_to) + else: + module = self._templar.template('{{ansible_facts["ansible_service_mgr"]}}') + except: + pass # could not get it from template! + + if module == 'auto': + facts = self._execute_module(module_name='setup', module_args=dict(gather_subset='!all', filter='ansible_service_mgr'), task_vars=task_vars) + self._display.debug("Facts %s" % facts) + if 'ansible_facts' in facts and 'ansible_service_mgr' in facts['ansible_facts']: + module = facts['ansible_facts']['ansible_service_mgr'] + + if not module or module == 'auto' or module not in self._shared_loader_obj.module_loader: + module = 'service' + + if module != 'auto': + # run the 'service' module + new_module_args = self._task.args.copy() + if 'use' in new_module_args: + del new_module_args['use'] + + # for backwards compatibility + if 'state' in new_module_args and new_module_args['state'] == 'running': + self._display.deprecated(msg="state=running is deprecated. Please use state=started", version="2.7") + new_module_args['state'] = 'started' + + if module in self.UNUSED_PARAMS: + for unused in self.UNUSED_PARAMS[module]: + if unused in new_module_args: + del new_module_args[unused] + self._display.warning('Ignoring "%s" as it is not used in "%s"' % (unused, module)) + + self._display.vvvv("Running %s" % module) + result.update(self._execute_module(module_name=module, module_args=new_module_args, task_vars=task_vars, wrap_async=self._task.async)) + else: + result['failed'] = True + result['msg'] = 'Could not detect which service manager to use. Try gathering facts or setting the "use" option.' + + return result + +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import sys +import time + +from pyspark.sql import SparkSession + + +if __name__ == "__main__": + """ + Usage: decommissioning + """ + print("Starting decom test") + spark = SparkSession \ + .builder \ + .appName("DecomTest") \ + .getOrCreate() + sc = spark._sc + acc = sc.accumulator(0) + + def addToAcc(x): + acc.add(1) + return x + + initialRdd = sc.parallelize(range(100), 5) + accRdd = initialRdd.map(addToAcc) + # Trigger a shuffle so there are shuffle blocks to migrate + rdd = accRdd.map(lambda x: (x, x)).groupByKey() + # Make enough shuffle files to increase the chance of the race condition. + for i in range(1, 2): + shuffleRdd = sc.parallelize(range(1, 10), 5).map(lambda x: (x, x)).groupByKey() + shuffleRdd.collect() + rdd.collect() + print("1st accumulator value is: " + str(acc.value)) + print("Waiting to give nodes time to finish migration, decom exec 1.") + print("...") + time.sleep(30) + rdd.count() + rdd.collect() + print("Final accumulator value is: " + str(acc.value)) + print("Finished waiting, stopping Spark.") + spark.stop() + print("Done, exiting Python") + sys.exit(0) + +#!/usr/bin/env python + +# Copyright (c) 2012 Google Inc. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +"""Utility functions for Windows builds. + +These functions are executed via gyp-win-tool when using the ninja generator. +""" + +import os +import re +import shutil +import subprocess +import string +import sys + +BASE_DIR = os.path.dirname(os.path.abspath(__file__)) + +# A regex matching an argument corresponding to the output filename passed to +# link.exe. +_LINK_EXE_OUT_ARG = re.compile('/OUT:(?P.+)$', re.IGNORECASE) + +def main(args): + executor = WinTool() + exit_code = executor.Dispatch(args) + if exit_code is not None: + sys.exit(exit_code) + + +class WinTool(object): + """This class performs all the Windows tooling steps. The methods can either + be executed directly, or dispatched from an argument list.""" + + def _UseSeparateMspdbsrv(self, env, args): + """Allows to use a unique instance of mspdbsrv.exe per linker instead of a + shared one.""" + if len(args) < 1: + raise Exception("Not enough arguments") + + if args[0] != 'link.exe': + return + + # Use the output filename passed to the linker to generate an endpoint name + # for mspdbsrv.exe. + endpoint_name = None + for arg in args: + m = _LINK_EXE_OUT_ARG.match(arg) + if m: + endpoint_name = '%s_%d' % (m.group('out'), os.getpid()) + break + + if endpoint_name is None: + return + + # Adds the appropriate environment variable. This will be read by link.exe + # to know which instance of mspdbsrv.exe it should connect to (if it's + # not set then the default endpoint is used). + env['_MSPDBSRV_ENDPOINT_'] = endpoint_name + + def Dispatch(self, args): + """Dispatches a string command to a method.""" + if len(args) < 1: + raise Exception("Not enough arguments") + + method = "Exec%s" % self._CommandifyName(args[0]) + return getattr(self, method)(*args[1:]) + + def _CommandifyName(self, name_string): + """Transforms a tool name like recursive-mirror to RecursiveMirror.""" + return name_string.title().replace('-', '') + + def _GetEnv(self, arch): + """Gets the saved environment from a file for a given architecture.""" + # The environment is saved as an "environment block" (see CreateProcess + # and msvs_emulation for details). We convert to a dict here. + # Drop last 2 NULs, one for list terminator, one for trailing vs. separator. + pairs = open(arch).read()[:-2].split('\0') + kvs = [item.split('=', 1) for item in pairs] + return dict(kvs) + + def ExecStamp(self, path): + """Simple stamp command.""" + open(path, 'w').close() + + def ExecRecursiveMirror(self, source, dest): + """Emulation of rm -rf out && cp -af in out.""" + if os.path.exists(dest): + if os.path.isdir(dest): + shutil.rmtree(dest) + else: + os.unlink(dest) + if os.path.isdir(source): + shutil.copytree(source, dest) + else: + shutil.copy2(source, dest) + + def ExecLinkWrapper(self, arch, use_separate_mspdbsrv, *args): + """Filter diagnostic output from link that looks like: + ' Creating library ui.dll.lib and object ui.dll.exp' + This happens when there are exports from the dll or exe. + """ + env = self._GetEnv(arch) + if use_separate_mspdbsrv == 'True': + self._UseSeparateMspdbsrv(env, args) + link = subprocess.Popen(args, + shell=True, + env=env, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT) + out, _ = link.communicate() + for line in out.splitlines(): + if not line.startswith(' Creating library '): + print line + return link.returncode + + def ExecLinkWithManifests(self, arch, embed_manifest, out, ldcmd, resname, + mt, rc, intermediate_manifest, *manifests): + """A wrapper for handling creating a manifest resource and then executing + a link command.""" + # The 'normal' way to do manifests is to have link generate a manifest + # based on gathering dependencies from the object files, then merge that + # manifest with other manifests supplied as sources, convert the merged + # manifest to a resource, and then *relink*, including the compiled + # version of the manifest resource. This breaks incremental linking, and + # is generally overly complicated. Instead, we merge all the manifests + # provided (along with one that includes what would normally be in the + # linker-generated one, see msvs_emulation.py), and include that into the + # first and only link. We still tell link to generate a manifest, but we + # only use that to assert that our simpler process did not miss anything. + variables = { + 'python': sys.executable, + 'arch': arch, + 'out': out, + 'ldcmd': ldcmd, + 'resname': resname, + 'mt': mt, + 'rc': rc, + 'intermediate_manifest': intermediate_manifest, + 'manifests': ' '.join(manifests), + } + add_to_ld = '' + if manifests: + subprocess.check_call( + '%(python)s gyp-win-tool manifest-wrapper %(arch)s %(mt)s -nologo ' + '-manifest %(manifests)s -out:%(out)s.manifest' % variables) + if embed_manifest == 'True': + subprocess.check_call( + '%(python)s gyp-win-tool manifest-to-rc %(arch)s %(out)s.manifest' + ' %(out)s.manifest.rc %(resname)s' % variables) + subprocess.check_call( + '%(python)s gyp-win-tool rc-wrapper %(arch)s %(rc)s ' + '%(out)s.manifest.rc' % variables) + add_to_ld = ' %(out)s.manifest.res' % variables + subprocess.check_call(ldcmd + add_to_ld) + + # Run mt.exe on the theoretically complete manifest we generated, merging + # it with the one the linker generated to confirm that the linker + # generated one does not add anything. This is strictly unnecessary for + # correctness, it's only to verify that e.g. /MANIFESTDEPENDENCY was not + # used in a #pragma comment. + if manifests: + # Merge the intermediate one with ours to .assert.manifest, then check + # that .assert.manifest is identical to ours. + subprocess.check_call( + '%(python)s gyp-win-tool manifest-wrapper %(arch)s %(mt)s -nologo ' + '-manifest %(out)s.manifest %(intermediate_manifest)s ' + '-out:%(out)s.assert.manifest' % variables) + assert_manifest = '%(out)s.assert.manifest' % variables + our_manifest = '%(out)s.manifest' % variables + # Load and normalize the manifests. mt.exe sometimes removes whitespace, + # and sometimes doesn't unfortunately. + with open(our_manifest, 'rb') as our_f: + with open(assert_manifest, 'rb') as assert_f: + our_data = our_f.read().translate(None, string.whitespace) + assert_data = assert_f.read().translate(None, string.whitespace) + if our_data != assert_data: + os.unlink(out) + def dump(filename): + sys.stderr.write('%s\n-----\n' % filename) + with open(filename, 'rb') as f: + sys.stderr.write(f.read() + '\n-----\n') + dump(intermediate_manifest) + dump(our_manifest) + dump(assert_manifest) + sys.stderr.write( + 'Linker generated manifest "%s" added to final manifest "%s" ' + '(result in "%s"). ' + 'Were /MANIFEST switches used in #pragma statements? ' % ( + intermediate_manifest, our_manifest, assert_manifest)) + return 1 + + def ExecManifestWrapper(self, arch, *args): + """Run manifest tool with environment set. Strip out undesirable warning + (some XML blocks are recognized by the OS loader, but not the manifest + tool).""" + env = self._GetEnv(arch) + popen = subprocess.Popen(args, shell=True, env=env, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + out, _ = popen.communicate() + for line in out.splitlines(): + if line and 'manifest authoring warning 81010002' not in line: + print line + return popen.returncode + + def ExecManifestToRc(self, arch, *args): + """Creates a resource file pointing a SxS assembly manifest. + |args| is tuple containing path to resource file, path to manifest file + and resource name which can be "1" (for executables) or "2" (for DLLs).""" + manifest_path, resource_path, resource_name = args + with open(resource_path, 'wb') as output: + output.write('#include \n%s RT_MANIFEST "%s"' % ( + resource_name, + os.path.abspath(manifest_path).replace('\\', '/'))) + + def ExecMidlWrapper(self, arch, outdir, tlb, h, dlldata, iid, proxy, idl, + *flags): + """Filter noisy filenames output from MIDL compile step that isn't + quietable via command line flags. + """ + args = ['midl', '/nologo'] + list(flags) + [ + '/out', outdir, + '/tlb', tlb, + '/h', h, + '/dlldata', dlldata, + '/iid', iid, + '/proxy', proxy, + idl] + env = self._GetEnv(arch) + popen = subprocess.Popen(args, shell=True, env=env, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + out, _ = popen.communicate() + # Filter junk out of stdout, and write filtered versions. Output we want + # to filter is pairs of lines that look like this: + # Processing C:\Program Files (x86)\Microsoft SDKs\...\include\objidl.idl + # objidl.idl + lines = out.splitlines() + prefix = 'Processing ' + processing = set(os.path.basename(x) for x in lines if x.startswith(prefix)) + for line in lines: + if not line.startswith(prefix) and line not in processing: + print line + return popen.returncode + + def ExecAsmWrapper(self, arch, *args): + """Filter logo banner from invocations of asm.exe.""" + env = self._GetEnv(arch) + # MSVS doesn't assemble x64 asm files. + if arch == 'environment.x64': + return 0 + popen = subprocess.Popen(args, shell=True, env=env, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + out, _ = popen.communicate() + for line in out.splitlines(): + if (not line.startswith('Copyright (C) Microsoft Corporation') and + not line.startswith('Microsoft (R) Macro Assembler') and + not line.startswith(' Assembling: ') and + line): + print line + return popen.returncode + + def ExecRcWrapper(self, arch, *args): + """Filter logo banner from invocations of rc.exe. Older versions of RC + don't support the /nologo flag.""" + env = self._GetEnv(arch) + popen = subprocess.Popen(args, shell=True, env=env, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + out, _ = popen.communicate() + for line in out.splitlines(): + if (not line.startswith('Microsoft (R) Windows (R) Resource Compiler') and + not line.startswith('Copyright (C) Microsoft Corporation') and + line): + print line + return popen.returncode + + def ExecActionWrapper(self, arch, rspfile, *dir): + """Runs an action command line from a response file using the environment + for |arch|. If |dir| is supplied, use that as the working directory.""" + env = self._GetEnv(arch) + # TODO(scottmg): This is a temporary hack to get some specific variables + # through to actions that are set after gyp-time. http://crbug.com/333738. + for k, v in os.environ.iteritems(): + if k not in env: + env[k] = v + args = open(rspfile).read() + dir = dir[0] if dir else None + return subprocess.call(args, shell=True, env=env, cwd=dir) + +if __name__ == '__main__': + sys.exit(main(sys.argv[1:])) + +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2004-today OpenERP SA () +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as +# published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +############################################################################## + +from openerp.osv import fields, osv +import logging +_logger = logging.getLogger(__name__) + + +class calendar_event(osv.Model): + """ Model for Calendar Event """ + _inherit = 'calendar.event' + _columns = { + 'phonecall_id': fields.many2one('crm.phonecall', 'Phonecall'), + 'opportunity_id': fields.many2one('crm.lead', 'Opportunity', domain="[('type', '=', 'opportunity')]"), + } + + def create(self, cr, uid, vals, context=None): + res = super(calendar_event, self).create(cr, uid, vals, context=context) + obj = self.browse(cr, uid, res, context=context) + if obj.opportunity_id: + self.pool.get('crm.lead').log_meeting(cr, uid, [obj.opportunity_id.id], obj.name, obj.start, obj.duration, context=context) + return res + +# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: + +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Tests for tf.contrib.training.evaluation.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import glob +import os +import time + +import numpy as np + +from tensorflow.contrib.framework.python.ops import variables +from tensorflow.contrib.layers.python.layers import layers +from tensorflow.contrib.losses.python.losses import loss_ops +from tensorflow.contrib.training.python.training import evaluation +from tensorflow.contrib.training.python.training import training +from tensorflow.core.protobuf import config_pb2 +from tensorflow.python.client import session as session_lib +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import random_seed +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import metrics +from tensorflow.python.ops import state_ops +from tensorflow.python.ops import variables as variables_lib +from tensorflow.python.platform import gfile +from tensorflow.python.platform import test +from tensorflow.python.summary import summary as summary_lib +from tensorflow.python.summary import summary_iterator +from tensorflow.python.training import basic_session_run_hooks +from tensorflow.python.training import gradient_descent +from tensorflow.python.training import saver as saver_lib + + +class CheckpointIteratorTest(test.TestCase): + + def testReturnsEmptyIfNoCheckpointsFound(self): + checkpoint_dir = os.path.join(self.get_temp_dir(), 'no_checkpoints_found') + + num_found = 0 + for _ in evaluation.checkpoints_iterator(checkpoint_dir, timeout=0): + num_found += 1 + self.assertEqual(num_found, 0) + + def testReturnsSingleCheckpointIfOneCheckpointFound(self): + checkpoint_dir = os.path.join(self.get_temp_dir(), 'one_checkpoint_found') + if not gfile.Exists(checkpoint_dir): + gfile.MakeDirs(checkpoint_dir) + + global_step = variables.get_or_create_global_step() + saver = saver_lib.Saver() # Saves the global step. + + with self.cached_session() as session: + session.run(variables_lib.global_variables_initializer()) + save_path = os.path.join(checkpoint_dir, 'model.ckpt') + saver.save(session, save_path, global_step=global_step) + + num_found = 0 + for _ in evaluation.checkpoints_iterator(checkpoint_dir, timeout=0): + num_found += 1 + self.assertEqual(num_found, 1) + + def testReturnsSingleCheckpointIfOneShardedCheckpoint(self): + checkpoint_dir = os.path.join(self.get_temp_dir(), + 'one_checkpoint_found_sharded') + if not gfile.Exists(checkpoint_dir): + gfile.MakeDirs(checkpoint_dir) + + global_step = variables.get_or_create_global_step() + + # This will result in 3 different checkpoint shard files. + with ops.device('/cpu:0'): + variables_lib.Variable(10, name='v0') + with ops.device('/cpu:1'): + variables_lib.Variable(20, name='v1') + + saver = saver_lib.Saver(sharded=True) + + with session_lib.Session( + target='', + config=config_pb2.ConfigProto(device_count={'CPU': 2})) as session: + + session.run(variables_lib.global_variables_initializer()) + save_path = os.path.join(checkpoint_dir, 'model.ckpt') + saver.save(session, save_path, global_step=global_step) + + num_found = 0 + for _ in evaluation.checkpoints_iterator(checkpoint_dir, timeout=0): + num_found += 1 + self.assertEqual(num_found, 1) + + def testTimeoutFn(self): + timeout_fn_calls = [0] + def timeout_fn(): + timeout_fn_calls[0] += 1 + return timeout_fn_calls[0] > 3 + + results = list( + evaluation.checkpoints_iterator( + '/non-existent-dir', timeout=0.1, timeout_fn=timeout_fn)) + self.assertEqual([], results) + self.assertEqual(4, timeout_fn_calls[0]) + + +class WaitForNewCheckpointTest(test.TestCase): + + def testReturnsNoneAfterTimeout(self): + start = time.time() + ret = evaluation.wait_for_new_checkpoint( + '/non-existent-dir', 'foo', timeout=1.0, seconds_to_sleep=0.5) + end = time.time() + self.assertIsNone(ret) + + # We've waited one second. + self.assertGreater(end, start + 0.5) + + # The timeout kicked in. + self.assertLess(end, start + 1.1) + + +def logistic_classifier(inputs): + return layers.fully_connected(inputs, 1, activation_fn=math_ops.sigmoid) + + +class EvaluateOnceTest(test.TestCase): + + def setUp(self): + super(EvaluateOnceTest, self).setUp() + + # Create an easy training set: + np.random.seed(0) + + self._inputs = np.zeros((16, 4)) + self._labels = np.random.randint(0, 2, size=(16, 1)).astype(np.float32) + + for i in range(16): + j = int(2 * self._labels[i] + np.random.randint(0, 2)) + self._inputs[i, j] = 1 + + def _train_model(self, checkpoint_dir, num_steps): + """Trains a simple classification model. + + Note that the data has been configured such that after around 300 steps, + the model has memorized the dataset (e.g. we can expect %100 accuracy). + + Args: + checkpoint_dir: The directory where the checkpoint is written to. + num_steps: The number of steps to train for. + """ + with ops.Graph().as_default(): + random_seed.set_random_seed(0) + tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32) + tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32) + + tf_predictions = logistic_classifier(tf_inputs) + loss = loss_ops.log_loss(tf_predictions, tf_labels) + + optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0) + train_op = training.create_train_op(loss, optimizer) + + loss = training.train( + train_op, + checkpoint_dir, + hooks=[basic_session_run_hooks.StopAtStepHook(num_steps)]) + + if num_steps >= 300: + assert loss < .015 + + def testEvaluatePerfectModel(self): + checkpoint_dir = os.path.join(self.get_temp_dir(),