Best JavaScript code snippet using fast-check-monorepo
legend_handler.py
Source:legend_handler.py
1"""2This module defines default legend handlers.3It is strongly encouraged to have read the :ref:`legend guide4<plotting-guide-legend>` before this documentation.5Legend handlers are expected to be a callable object with a following6signature. ::7 legend_handler(legend, orig_handle, fontsize, handlebox)8Where *legend* is the legend itself, *orig_handle* is the original9plot, *fontsize* is the fontsize in pixles, and *handlebox* is a10OffsetBox instance. Within the call, you should create relevant11artists (using relevant properties from the *legend* and/or12*orig_handle*) and add them into the handlebox. The artists needs to13be scaled according to the fontsize (note that the size is in pixel,14i.e., this is dpi-scaled value).15This module includes definition of several legend handler classes16derived from the base class (HandlerBase) with the following method.17 def legend_artist(self, legend, orig_handle, fontsize, handlebox):18"""19from __future__ import (absolute_import, division, print_function,20 unicode_literals)21import six22from six.moves import zip23from itertools import cycle24import numpy as np25from matplotlib.lines import Line2D26from matplotlib.patches import Rectangle27import matplotlib.collections as mcoll28import matplotlib.colors as mcolors29def update_from_first_child(tgt, src):30 tgt.update_from(src.get_children()[0])31class HandlerBase(object):32 """33 A Base class for default legend handlers.34 The derived classes are meant to override *create_artists* method, which35 has a following signature.::36 def create_artists(self, legend, orig_handle,37 xdescent, ydescent, width, height, fontsize,38 trans):39 The overridden method needs to create artists of the given40 transform that fits in the given dimension (xdescent, ydescent,41 width, height) that are scaled by fontsize if necessary.42 """43 def __init__(self, xpad=0., ypad=0., update_func=None):44 self._xpad, self._ypad = xpad, ypad45 self._update_prop_func = update_func46 def _update_prop(self, legend_handle, orig_handle):47 if self._update_prop_func is None:48 self._default_update_prop(legend_handle, orig_handle)49 else:50 self._update_prop_func(legend_handle, orig_handle)51 def _default_update_prop(self, legend_handle, orig_handle):52 legend_handle.update_from(orig_handle)53 def update_prop(self, legend_handle, orig_handle, legend):54 self._update_prop(legend_handle, orig_handle)55 legend._set_artist_props(legend_handle)56 legend_handle.set_clip_box(None)57 legend_handle.set_clip_path(None)58 def adjust_drawing_area(self, legend, orig_handle,59 xdescent, ydescent, width, height, fontsize,60 ):61 xdescent = xdescent - self._xpad * fontsize62 ydescent = ydescent - self._ypad * fontsize63 width = width - self._xpad * fontsize64 height = height - self._ypad * fontsize65 return xdescent, ydescent, width, height66 def legend_artist(self, legend, orig_handle,67 fontsize, handlebox):68 """69 Return the artist that this HandlerBase generates for the given70 original artist/handle.71 Parameters72 ----------73 legend : :class:`matplotlib.legend.Legend` instance74 The legend for which these legend artists are being created.75 orig_handle : :class:`matplotlib.artist.Artist` or similar76 The object for which these legend artists are being created.77 fontsize : float or int78 The fontsize in pixels. The artists being created should79 be scaled according to the given fontsize.80 handlebox : :class:`matplotlib.offsetbox.OffsetBox` instance81 The box which has been created to hold this legend entry's82 artists. Artists created in the `legend_artist` method must83 be added to this handlebox inside this method.84 """85 xdescent, ydescent, width, height = self.adjust_drawing_area(86 legend, orig_handle,87 handlebox.xdescent, handlebox.ydescent,88 handlebox.width, handlebox.height,89 fontsize)90 artists = self.create_artists(legend, orig_handle,91 xdescent, ydescent, width, height,92 fontsize, handlebox.get_transform())93 # create_artists will return a list of artists.94 for a in artists:95 handlebox.add_artist(a)96 # we only return the first artist97 return artists[0]98 def create_artists(self, legend, orig_handle,99 xdescent, ydescent, width, height, fontsize,100 trans):101 raise NotImplementedError('Derived must override')102class HandlerNpoints(HandlerBase):103 def __init__(self, marker_pad=0.3, numpoints=None, **kw):104 HandlerBase.__init__(self, **kw)105 self._numpoints = numpoints106 self._marker_pad = marker_pad107 def get_numpoints(self, legend):108 if self._numpoints is None:109 return legend.numpoints110 else:111 return self._numpoints112 def get_xdata(self, legend, xdescent, ydescent, width, height, fontsize):113 numpoints = self.get_numpoints(legend)114 if numpoints > 1:115 # we put some pad here to compensate the size of the116 # marker117 pad = self._marker_pad * fontsize118 xdata = np.linspace(-xdescent + pad,119 -xdescent + width - pad,120 numpoints)121 xdata_marker = xdata122 elif numpoints == 1:123 xdata = np.linspace(-xdescent, -xdescent+width, 2)124 xdata_marker = [-xdescent + 0.5 * width]125 return xdata, xdata_marker126class HandlerNpointsYoffsets(HandlerNpoints):127 def __init__(self, numpoints=None, yoffsets=None, **kw):128 HandlerNpoints.__init__(self, numpoints=numpoints, **kw)129 self._yoffsets = yoffsets130 def get_ydata(self, legend, xdescent, ydescent, width, height, fontsize):131 if self._yoffsets is None:132 ydata = height * legend._scatteryoffsets133 else:134 ydata = height * np.asarray(self._yoffsets)135 return ydata136class HandlerLine2D(HandlerNpoints):137 """138 Handler for Line2D instances.139 """140 def __init__(self, marker_pad=0.3, numpoints=None, **kw):141 HandlerNpoints.__init__(self, marker_pad=marker_pad, numpoints=numpoints, **kw)142 def create_artists(self, legend, orig_handle,143 xdescent, ydescent, width, height, fontsize,144 trans):145 xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent,146 width, height, fontsize)147 ydata = ((height - ydescent) / 2.) * np.ones(xdata.shape, float)148 legline = Line2D(xdata, ydata)149 self.update_prop(legline, orig_handle, legend)150 legline.set_drawstyle('default')151 legline.set_marker("")152 legline_marker = Line2D(xdata_marker, ydata[:len(xdata_marker)])153 self.update_prop(legline_marker, orig_handle, legend)154 legline_marker.set_linestyle('None')155 if legend.markerscale != 1:156 newsz = legline_marker.get_markersize() * legend.markerscale157 legline_marker.set_markersize(newsz)158 # we don't want to add this to the return list because159 # the texts and handles are assumed to be in one-to-one160 # correspondence.161 legline._legmarker = legline_marker162 legline.set_transform(trans)163 legline_marker.set_transform(trans)164 return [legline, legline_marker]165class HandlerPatch(HandlerBase):166 """167 Handler for Patch instances.168 """169 def __init__(self, patch_func=None, **kw):170 """171 The HandlerPatch class optionally takes a function ``patch_func``172 who's responsibility is to create the legend key artist. The173 ``patch_func`` should have the signature::174 def patch_func(legend=legend, orig_handle=orig_handle,175 xdescent=xdescent, ydescent=ydescent,176 width=width, height=height, fontsize=fontsize)177 Subsequently the created artist will have its ``update_prop`` method178 called and the appropriate transform will be applied.179 """180 HandlerBase.__init__(self, **kw)181 self._patch_func = patch_func182 def _create_patch(self, legend, orig_handle,183 xdescent, ydescent, width, height, fontsize):184 if self._patch_func is None:185 p = Rectangle(xy=(-xdescent, -ydescent),186 width=width, height=height)187 else:188 p = self._patch_func(legend=legend, orig_handle=orig_handle,189 xdescent=xdescent, ydescent=ydescent,190 width=width, height=height, fontsize=fontsize)191 return p192 def create_artists(self, legend, orig_handle,193 xdescent, ydescent, width, height, fontsize, trans):194 p = self._create_patch(legend, orig_handle,195 xdescent, ydescent, width, height, fontsize)196 self.update_prop(p, orig_handle, legend)197 p.set_transform(trans)198 return [p]199class HandlerLineCollection(HandlerLine2D):200 """201 Handler for LineCollection instances.202 """203 def get_numpoints(self, legend):204 if self._numpoints is None:205 return legend.scatterpoints206 else:207 return self._numpoints208 def _default_update_prop(self, legend_handle, orig_handle):209 lw = orig_handle.get_linewidths()[0]210 dashes = orig_handle._us_linestyles[0]211 color = orig_handle.get_colors()[0]212 legend_handle.set_color(color)213 legend_handle.set_linestyle(dashes)214 legend_handle.set_linewidth(lw)215 def create_artists(self, legend, orig_handle,216 xdescent, ydescent, width, height, fontsize, trans):217 xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent,218 width, height, fontsize)219 ydata = ((height - ydescent) / 2.) * np.ones(xdata.shape, float)220 legline = Line2D(xdata, ydata)221 self.update_prop(legline, orig_handle, legend)222 legline.set_transform(trans)223 return [legline]224class HandlerRegularPolyCollection(HandlerNpointsYoffsets):225 """226 Handler for RegularPolyCollections.227 """228 def __init__(self, yoffsets=None, sizes=None, **kw):229 HandlerNpointsYoffsets.__init__(self, yoffsets=yoffsets, **kw)230 self._sizes = sizes231 def get_numpoints(self, legend):232 if self._numpoints is None:233 return legend.scatterpoints234 else:235 return self._numpoints236 def get_sizes(self, legend, orig_handle,237 xdescent, ydescent, width, height, fontsize):238 if self._sizes is None:239 handle_sizes = orig_handle.get_sizes()240 if not len(handle_sizes):241 handle_sizes = [1]242 size_max = max(handle_sizes) * legend.markerscale ** 2243 size_min = min(handle_sizes) * legend.markerscale ** 2244 numpoints = self.get_numpoints(legend)245 if numpoints < 4:246 sizes = [.5 * (size_max + size_min), size_max,247 size_min][:numpoints]248 else:249 rng = (size_max - size_min)250 sizes = rng * np.linspace(0, 1, numpoints) + size_min251 else:252 sizes = self._sizes253 return sizes254 def update_prop(self, legend_handle, orig_handle, legend):255 self._update_prop(legend_handle, orig_handle)256 legend_handle.set_figure(legend.figure)257 #legend._set_artist_props(legend_handle)258 legend_handle.set_clip_box(None)259 legend_handle.set_clip_path(None)260 def create_collection(self, orig_handle, sizes, offsets, transOffset):261 p = type(orig_handle)(orig_handle.get_numsides(),262 rotation=orig_handle.get_rotation(),263 sizes=sizes,264 offsets=offsets,265 transOffset=transOffset,266 )267 return p268 def create_artists(self, legend, orig_handle,269 xdescent, ydescent, width, height, fontsize,270 trans):271 xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent,272 width, height, fontsize)273 ydata = self.get_ydata(legend, xdescent, ydescent,274 width, height, fontsize)275 sizes = self.get_sizes(legend, orig_handle, xdescent, ydescent,276 width, height, fontsize)277 p = self.create_collection(orig_handle, sizes,278 offsets=list(zip(xdata_marker, ydata)),279 transOffset=trans)280 self.update_prop(p, orig_handle, legend)281 p._transOffset = trans282 return [p]283class HandlerPathCollection(HandlerRegularPolyCollection):284 """285 Handler for PathCollections, which are used by scatter286 """287 def create_collection(self, orig_handle, sizes, offsets, transOffset):288 p = type(orig_handle)([orig_handle.get_paths()[0]],289 sizes=sizes,290 offsets=offsets,291 transOffset=transOffset,292 )293 return p294class HandlerCircleCollection(HandlerRegularPolyCollection):295 """296 Handler for CircleCollections297 """298 def create_collection(self, orig_handle, sizes, offsets, transOffset):299 p = type(orig_handle)(sizes,300 offsets=offsets,301 transOffset=transOffset,302 )303 return p304class HandlerErrorbar(HandlerLine2D):305 """306 Handler for Errorbars307 """308 def __init__(self, xerr_size=0.5, yerr_size=None,309 marker_pad=0.3, numpoints=None, **kw):310 self._xerr_size = xerr_size311 self._yerr_size = yerr_size312 HandlerLine2D.__init__(self, marker_pad=marker_pad, numpoints=numpoints,313 **kw)314 def get_err_size(self, legend, xdescent, ydescent, width, height, fontsize):315 xerr_size = self._xerr_size * fontsize316 if self._yerr_size is None:317 yerr_size = xerr_size318 else:319 yerr_size = self._yerr_size * fontsize320 return xerr_size, yerr_size321 def create_artists(self, legend, orig_handle,322 xdescent, ydescent, width, height, fontsize,323 trans):324 plotlines, caplines, barlinecols = orig_handle325 xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent,326 width, height, fontsize)327 ydata = ((height - ydescent) / 2.) * np.ones(xdata.shape, float)328 legline = Line2D(xdata, ydata)329 xdata_marker = np.asarray(xdata_marker)330 ydata_marker = np.asarray(ydata[:len(xdata_marker)])331 xerr_size, yerr_size = self.get_err_size(legend, xdescent, ydescent,332 width, height, fontsize)333 legline_marker = Line2D(xdata_marker, ydata_marker)334 # when plotlines are None (only errorbars are drawn), we just335 # make legline invisible.336 if plotlines is None:337 legline.set_visible(False)338 legline_marker.set_visible(False)339 else:340 self.update_prop(legline, plotlines, legend)341 legline.set_drawstyle('default')342 legline.set_marker('None')343 self.update_prop(legline_marker, plotlines, legend)344 legline_marker.set_linestyle('None')345 if legend.markerscale != 1:346 newsz = legline_marker.get_markersize() * legend.markerscale347 legline_marker.set_markersize(newsz)348 handle_barlinecols = []349 handle_caplines = []350 if orig_handle.has_xerr:351 verts = [ ((x - xerr_size, y), (x + xerr_size, y))352 for x, y in zip(xdata_marker, ydata_marker)]353 coll = mcoll.LineCollection(verts)354 self.update_prop(coll, barlinecols[0], legend)355 handle_barlinecols.append(coll)356 if caplines:357 capline_left = Line2D(xdata_marker - xerr_size, ydata_marker)358 capline_right = Line2D(xdata_marker + xerr_size, ydata_marker)359 self.update_prop(capline_left, caplines[0], legend)360 self.update_prop(capline_right, caplines[0], legend)361 capline_left.set_marker("|")362 capline_right.set_marker("|")363 handle_caplines.append(capline_left)364 handle_caplines.append(capline_right)365 if orig_handle.has_yerr:366 verts = [ ((x, y - yerr_size), (x, y + yerr_size))367 for x, y in zip(xdata_marker, ydata_marker)]368 coll = mcoll.LineCollection(verts)369 self.update_prop(coll, barlinecols[0], legend)370 handle_barlinecols.append(coll)371 if caplines:372 capline_left = Line2D(xdata_marker, ydata_marker - yerr_size)373 capline_right = Line2D(xdata_marker, ydata_marker + yerr_size)374 self.update_prop(capline_left, caplines[0], legend)375 self.update_prop(capline_right, caplines[0], legend)376 capline_left.set_marker("_")377 capline_right.set_marker("_")378 handle_caplines.append(capline_left)379 handle_caplines.append(capline_right)380 artists = []381 artists.extend(handle_barlinecols)382 artists.extend(handle_caplines)383 artists.append(legline)384 artists.append(legline_marker)385 for artist in artists:386 artist.set_transform(trans)387 return artists388class HandlerStem(HandlerNpointsYoffsets):389 """390 Handler for Errorbars391 """392 def __init__(self, marker_pad=0.3, numpoints=None,393 bottom=None, yoffsets=None, **kw):394 HandlerNpointsYoffsets.__init__(self, marker_pad=marker_pad,395 numpoints=numpoints,396 yoffsets=yoffsets,397 **kw)398 self._bottom = bottom399 def get_ydata(self, legend, xdescent, ydescent, width, height, fontsize):400 if self._yoffsets is None:401 ydata = height * (0.5 * legend._scatteryoffsets + 0.5)402 else:403 ydata = height * np.asarray(self._yoffsets)404 return ydata405 def create_artists(self, legend, orig_handle,406 xdescent, ydescent, width, height, fontsize,407 trans):408 markerline, stemlines, baseline = orig_handle409 xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent,410 width, height, fontsize)411 ydata = self.get_ydata(legend, xdescent, ydescent,412 width, height, fontsize)413 if self._bottom is None:414 bottom = 0.415 else:416 bottom = self._bottom417 leg_markerline = Line2D(xdata_marker, ydata[:len(xdata_marker)])418 self.update_prop(leg_markerline, markerline, legend)419 leg_stemlines = []420 for thisx, thisy in zip(xdata_marker, ydata):421 l = Line2D([thisx, thisx], [bottom, thisy])422 leg_stemlines.append(l)423 for lm, m in zip(leg_stemlines, stemlines):424 self.update_prop(lm, m, legend)425 leg_baseline = Line2D([np.min(xdata), np.max(xdata)],426 [bottom, bottom])427 self.update_prop(leg_baseline, baseline, legend)428 artists = [leg_markerline]429 artists.extend(leg_stemlines)430 artists.append(leg_baseline)431 for artist in artists:432 artist.set_transform(trans)433 return artists434class HandlerTuple(HandlerBase):435 """436 Handler for Tuple.437 Additional kwargs are passed through to `HandlerBase`.438 Parameters439 ----------440 ndivide : int, optional441 The number of sections to divide the legend area into. If None,442 use the length of the input tuple. Default is 1.443 pad : float, optional444 If None, fall back to `legend.borderpad` as the default.445 In units of fraction of font size. Default is None.446 """447 def __init__(self, ndivide=1, pad=None, **kwargs):448 self._ndivide = ndivide449 self._pad = pad450 HandlerBase.__init__(self, **kwargs)451 def create_artists(self, legend, orig_handle,452 xdescent, ydescent, width, height, fontsize,453 trans):454 handler_map = legend.get_legend_handler_map()455 if self._ndivide is None:456 ndivide = len(orig_handle)457 else:458 ndivide = self._ndivide459 if self._pad is None:460 pad = legend.borderpad * fontsize461 else:462 pad = self._pad * fontsize463 if ndivide > 1:464 width = (width - pad*(ndivide - 1)) / ndivide465 xds = [xdescent - (width + pad) * i for i in range(ndivide)]466 xds_cycle = cycle(xds)467 a_list = []468 for handle1 in orig_handle:469 handler = legend.get_legend_handler(handler_map, handle1)470 _a_list = handler.create_artists(legend, handle1,471 six.next(xds_cycle),472 ydescent,473 width, height,474 fontsize,475 trans)476 a_list.extend(_a_list)477 return a_list478class HandlerPolyCollection(HandlerBase):479 """480 Handler for PolyCollection used in fill_between and stackplot.481 """482 def _update_prop(self, legend_handle, orig_handle):483 def first_color(colors):484 colors = mcolors.to_rgba_array(colors)485 if len(colors):486 return colors[0]487 else:488 return "none"489 def get_first(prop_array):490 if len(prop_array):491 return prop_array[0]492 else:493 return None494 legend_handle.set_edgecolor(first_color(orig_handle.get_edgecolor()))495 legend_handle.set_facecolor(first_color(orig_handle.get_facecolor()))496 legend_handle.set_fill(orig_handle.get_fill())497 legend_handle.set_hatch(orig_handle.get_hatch())498 legend_handle.set_linewidth(get_first(orig_handle.get_linewidths()))499 legend_handle.set_linestyle(get_first(orig_handle.get_linestyles()))500 legend_handle.set_transform(get_first(orig_handle.get_transforms()))501 legend_handle.set_figure(orig_handle.get_figure())502 legend_handle.set_alpha(orig_handle.get_alpha())503 def create_artists(self, legend, orig_handle,504 xdescent, ydescent, width, height, fontsize, trans):505 p = Rectangle(xy=(-xdescent, -ydescent),506 width=width, height=height)507 self.update_prop(p, orig_handle, legend)508 p.set_transform(trans)...
dashboard-v2.js
Source:dashboard-v2.js
1/*2Template Name: Color Admin - Responsive Admin Dashboard Template build with Twitter Bootstrap 3 & 43Version: 4.0.04Author: Sean Ngu5Website: http://www.seantheme.com/color-admin-v4.0/admin/6*/7var getMonthName = function(number) {8 var month = [];9 month[0] = "JAN";10 month[1] = "FEB";11 month[2] = "MAR";12 month[3] = "APR";13 month[4] = "MAY";14 month[5] = "JUN";15 month[6] = "JUL";16 month[7] = "AUG";17 month[8] = "SEP";18 month[9] = "OCT";19 month[10] = "NOV";20 month[11] = "DEC";21 22 return month[number];23};24var getDate = function(date) {25 var currentDate = new Date(date);26 var dd = currentDate.getDate();27 var mm = currentDate.getMonth() + 1;28 var yyyy = currentDate.getFullYear();29 30 if (dd < 10) {31 dd = '0' + dd;32 }33 if (mm < 10) {34 mm = '0' + mm;35 }36 currentDate = yyyy+'-'+mm+'-'+dd;37 38 return currentDate;39};40var handleVisitorsAreaChart = function() {41 var handleGetDate = function(minusDate) {42 var d = new Date();43 d = d.setDate(d.getDate() - minusDate);44 return d;45 };46 var visitorAreaChartData = [{47 'key' : 'Unique Visitors',48 'color' : COLOR_AQUA,49 'values' : [ 50 [handleGetDate(77), 13], [handleGetDate(76), 13], [handleGetDate(75), 6 ], 51 [handleGetDate(73), 6 ], [handleGetDate(72), 6 ], [handleGetDate(71), 5 ], [handleGetDate(70), 5 ], 52 [handleGetDate(69), 5 ], [handleGetDate(68), 6 ], [handleGetDate(67), 7 ], [handleGetDate(66), 6 ], 53 [handleGetDate(65), 9 ], [handleGetDate(64), 9 ], [handleGetDate(63), 8 ], [handleGetDate(62), 10], 54 [handleGetDate(61), 10], [handleGetDate(60), 10], [handleGetDate(59), 10], [handleGetDate(58), 9 ], 55 [handleGetDate(57), 9 ], [handleGetDate(56), 10], [handleGetDate(55), 9 ], [handleGetDate(54), 9 ], 56 [handleGetDate(53), 8 ], [handleGetDate(52), 8 ], [handleGetDate(51), 8 ], [handleGetDate(50), 8 ], 57 [handleGetDate(49), 8 ], [handleGetDate(48), 7 ], [handleGetDate(47), 7 ], [handleGetDate(46), 6 ], 58 [handleGetDate(45), 6 ], [handleGetDate(44), 6 ], [handleGetDate(43), 6 ], [handleGetDate(42), 5 ], 59 [handleGetDate(41), 5 ], [handleGetDate(40), 4 ], [handleGetDate(39), 4 ], [handleGetDate(38), 5 ], 60 [handleGetDate(37), 5 ], [handleGetDate(36), 5 ], [handleGetDate(35), 7 ], [handleGetDate(34), 7 ], 61 [handleGetDate(33), 7 ], [handleGetDate(32), 10], [handleGetDate(31), 9 ], [handleGetDate(30), 9 ], 62 [handleGetDate(29), 10], [handleGetDate(28), 11], [handleGetDate(27), 11], [handleGetDate(26), 8 ], 63 [handleGetDate(25), 8 ], [handleGetDate(24), 7 ], [handleGetDate(23), 8 ], [handleGetDate(22), 9 ], 64 [handleGetDate(21), 8 ], [handleGetDate(20), 9 ], [handleGetDate(19), 10], [handleGetDate(18), 9 ], 65 [handleGetDate(17), 10], [handleGetDate(16), 16], [handleGetDate(15), 17], [handleGetDate(14), 16], 66 [handleGetDate(13), 17], [handleGetDate(12), 16], [handleGetDate(11), 15], [handleGetDate(10), 14], 67 [handleGetDate(9) , 24], [handleGetDate(8) , 18], [handleGetDate(7) , 15], [handleGetDate(6) , 14], 68 [handleGetDate(5) , 16], [handleGetDate(4) , 16], [handleGetDate(3) , 17], [handleGetDate(2) , 7 ], 69 [handleGetDate(1) , 7 ], [handleGetDate(0) , 7 ]70 ]71 }, {72 'key' : 'Page Views',73 'color' : COLOR_BLUE,74 'values' : [ 75 [handleGetDate(77), 14], [handleGetDate(76), 13], [handleGetDate(75), 15], 76 [handleGetDate(73), 14], [handleGetDate(72), 13], [handleGetDate(71), 15], [handleGetDate(70), 16], 77 [handleGetDate(69), 16], [handleGetDate(68), 14], [handleGetDate(67), 14], [handleGetDate(66), 13], 78 [handleGetDate(65), 12], [handleGetDate(64), 13], [handleGetDate(63), 13], [handleGetDate(62), 15], 79 [handleGetDate(61), 16], [handleGetDate(60), 16], [handleGetDate(59), 17], [handleGetDate(58), 17], 80 [handleGetDate(57), 18], [handleGetDate(56), 15], [handleGetDate(55), 15], [handleGetDate(54), 15], 81 [handleGetDate(53), 19], [handleGetDate(52), 19], [handleGetDate(51), 18], [handleGetDate(50), 18], 82 [handleGetDate(49), 17], [handleGetDate(48), 16], [handleGetDate(47), 18], [handleGetDate(46), 18], 83 [handleGetDate(45), 18], [handleGetDate(44), 16], [handleGetDate(43), 14], [handleGetDate(42), 14], 84 [handleGetDate(41), 13], [handleGetDate(40), 14], [handleGetDate(39), 13], [handleGetDate(38), 10], 85 [handleGetDate(37), 9 ], [handleGetDate(36), 10], [handleGetDate(35), 11], [handleGetDate(34), 11], 86 [handleGetDate(33), 11], [handleGetDate(32), 10], [handleGetDate(31), 9 ], [handleGetDate(30), 10], 87 [handleGetDate(29), 13], [handleGetDate(28), 14], [handleGetDate(27), 14], [handleGetDate(26), 13], 88 [handleGetDate(25), 12], [handleGetDate(24), 11], [handleGetDate(23), 13], [handleGetDate(22), 13], 89 [handleGetDate(21), 13], [handleGetDate(20), 13], [handleGetDate(19), 14], [handleGetDate(18), 13], 90 [handleGetDate(17), 13], [handleGetDate(16), 19], [handleGetDate(15), 21], [handleGetDate(14), 22],91 [handleGetDate(13), 25], [handleGetDate(12), 24], [handleGetDate(11), 24], [handleGetDate(10), 22], 92 [handleGetDate(9) , 16], [handleGetDate(8) , 15], [handleGetDate(7) , 12], [handleGetDate(6) , 12], 93 [handleGetDate(5) , 15], [handleGetDate(4) , 15], [handleGetDate(3) , 15], [handleGetDate(2) , 18], 94 [handleGetDate(2) , 18], [handleGetDate(0) , 17]95 ]96 }];97 nv.addGraph(function() {98 var stackedAreaChart = nv.models.stackedAreaChart()99 .useInteractiveGuideline(true)100 .x(function(d) { return d[0] })101 .y(function(d) { return d[1] })102 .pointSize(0.5)103 .margin({'left':35,'right': 25,'top': 20,'bottom':20})104 .controlLabels({stacked: 'Stacked'})105 .showControls(false)106 .duration(300);107 stackedAreaChart.xAxis.tickFormat(function(d) { 108 var monthsName = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];109 d = new Date(d);110 d = monthsName[d.getMonth()] + ' ' + d.getDate();111 return d ;112 });113 stackedAreaChart.yAxis.tickFormat(d3.format(',.0f'));114 d3.select('#visitors-line-chart')115 .append('svg')116 .datum(visitorAreaChartData)117 .transition().duration(1000)118 .call(stackedAreaChart)119 .each('start', function() {120 setTimeout(function() {121 d3.selectAll('#visitors-line-chart *').each(function() {122 if(this.__transition__)123 this.__transition__.duration = 1;124 })125 }, 0)126 });127 nv.utils.windowResize(stackedAreaChart.update);128 return stackedAreaChart;129 });130};131var handleVisitorsDonutChart = function() {132 var visitorDonutChartData = [133 { 'label': 'Return Visitors', 'value' : 784466, 'color': COLOR_BLUE }, 134 { 'label': 'New Visitors', 'value' : 416747, 'color': COLOR_GREEN }135 ];136 var arcRadius = [137 { inner: 0.65, outer: 0.93 },138 { inner: 0.6, outer: 1 }139 ];140 nv.addGraph(function() {141 var donutChart = nv.models.pieChart()142 .x(function(d) { return d.label })143 .y(function(d) { return d.value })144 .margin({'left': 10,'right': 10,'top': 10,'bottom': 10})145 .showLegend(false)146 .donut(true) 147 .growOnHover(false)148 .arcsRadius(arcRadius)149 .donutRatio(0.5);150 151 donutChart.labelFormat(d3.format(',.0f'));152 153 d3.select('#visitors-donut-chart').append('svg')154 .datum(visitorDonutChartData)155 .transition().duration(3000)156 .call(donutChart);157 158 return donutChart;159 });160};161var handleVisitorsVectorMap = function() {162 if ($('#visitors-map').length !== 0) {163 $('#visitors-map').vectorMap({164 map: 'world_merc_en',165 scaleColors: [COLOR_BLACK_LIGHTER, COLOR_BLACK],166 container: $('#visitors-map'),167 normalizeFunction: 'linear',168 hoverOpacity: 0.5,169 hoverColor: false,170 zoomOnScroll: false,171 markerStyle: {172 initial: {173 fill: COLOR_BLACK,174 stroke: 'transparent',175 r: 3176 }177 },178 regions: [{179 attribute: 'fill'180 }],181 regionStyle: {182 initial: {183 fill: COLOR_BLACK_LIGHTER,184 "fill-opacity": 1,185 stroke: 'none',186 "stroke-width": 0.4,187 "stroke-opacity": 1188 },189 hover: {190 "fill-opacity": 0.8191 },192 selected: {193 fill: 'yellow'194 }195 },196 series: {197 regions: [{198 values: {199 IN: COLOR_BLUE,200 US: COLOR_GREEN,201 MN: COLOR_GREY_DARKER202 }203 }]204 },205 focusOn: {206 x: 0.5,207 y: 0.5,208 scale: 1209 },210 backgroundColor: 'transparent'211 });212 }213};214var handleScheduleCalendar = function() {215 var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];216 var dayNames = ["S", "M", "T", "W", "T", "F", "S"];217 var now = new Date(),218 month = now.getMonth() + 1,219 year = now.getFullYear();220 var events = [221 [222 '2/' + month + '/' + year,223 'Popover Title',224 '#',225 COLOR_GREEN,226 'Some contents here'227 ],228 [229 '5/' + month + '/' + year,230 'Tooltip with link',231 'http://www.seantheme.com/',232 COLOR_BLACK233 ],234 [235 '18/' + month + '/' + year,236 'Popover with HTML Content',237 '#',238 COLOR_BLACK,239 'Some contents here <div class="text-right"><a href="http://www.google.com">view more >>></a></div>'240 ],241 [242 '28/' + month + '/' + year,243 'Color Admin V1.3 Launched',244 'http://www.seantheme.com/color-admin-v1.3',245 COLOR_BLACK,246 ]247 ];248 var calendarTarget = $('#schedule-calendar');249 $(calendarTarget).calendar({250 months: monthNames,251 days: dayNames,252 events: events,253 popover_options:{254 placement: 'top',255 html: true256 }257 });258 $(calendarTarget).find('td.event').each(function() {259 var backgroundColor = $(this).css('background-color');260 $(this).removeAttr('style');261 $(this).find('a').css('background-color', backgroundColor);262 });263 $(calendarTarget).find('.icon-arrow-left, .icon-arrow-right').parent().on('click', function() {264 $(calendarTarget).find('td.event').each(function() {265 var backgroundColor = $(this).css('background-color');266 $(this).removeAttr('style');267 $(this).find('a').css('background-color', backgroundColor);268 });269 });270};271var handleDashboardGritterNotification = function() {272 setTimeout(function() {273 $.gritter.add({274 title: 'Welcome back, Admin!',275 text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed tempus lacus ut lectus rutrum placerat.',276 image: '../assets/img/user/user-12.jpg',277 sticky: true,278 time: '',279 class_name: 'my-sticky-class'280 });281 }, 1000);282};283var DashboardV2 = function () {284 "use strict";285 return {286 //main function287 init: function () {288 handleVisitorsAreaChart();289 handleVisitorsDonutChart();290 handleVisitorsVectorMap();291 handleScheduleCalendar();292 handleDashboardGritterNotification();293 }294 };...
session_ops_test.py
Source:session_ops_test.py
...31 # Return a handle.32 a = constant_op.constant(10)33 b = constant_op.constant(5)34 c = math_ops.multiply(a, b)35 h = session_ops.get_session_handle(c)36 h = sess.run(h)37 # Feed a tensor handle.38 f, x = session_ops.get_session_tensor(h.handle, dtypes.int32)39 y = math_ops.multiply(x, 10)40 self.assertEqual(500, sess.run(y, feed_dict={f: h.handle}))41 def testHandleEval(self):42 with self.test_session() as sess:43 # Return a handle.44 a = constant_op.constant(10)45 b = constant_op.constant(5)46 c = math_ops.multiply(a, b)47 h = session_ops.get_session_handle(c)48 h = sess.run(h)49 # Get the tensor from its handle.50 self.assertEqual(50, h.eval())51 def testHandleAndValue(self):52 with self.test_session() as sess:53 # Return a handle and a value.54 a = constant_op.constant(10)55 b = constant_op.constant(5)56 c = math_ops.multiply(a, b)57 h = session_ops.get_session_handle(c)58 v = math_ops.multiply(a, c)59 h, v = sess.run([h, v])60 self.assertEqual(50, h.eval())61 self.assertEqual(500, v)62 def testHandleCond(self):63 with self.test_session() as sess:64 # Return a handle and a value65 a = constant_op.constant(10)66 b = constant_op.constant(5)67 p = math_ops.less(a, b)68 c = math_ops.multiply(a, b)69 h = session_ops.get_session_handle(c)70 p, h = sess.run([p, h])71 # Run by feeding a tensor handle.72 f, x = session_ops.get_session_tensor(h.handle, dtypes.int32)73 if p:74 y = math_ops.multiply(x, 10)75 else:76 y = math_ops.multiply(x, 100)77 result = sess.run(y, feed_dict={f: h.handle})78 self.assertEqual(5000, result)79 def testHandleForLoop(self):80 with self.test_session() as sess:81 # Initialize a handle.82 a = constant_op.constant(0)83 h = session_ops.get_session_handle(a)84 h = sess.run(h)85 # Do some computation.86 f, x = session_ops.get_session_tensor(h.handle, dtypes.int32)87 # Must define the loop body outside the loop.88 h_x = session_ops.get_session_handle(math_ops.add(x, 1))89 for _ in range(100):90 # This exercises garbage collection.91 h = sess.run(h_x, feed_dict={f: h.handle})92 self.assertEqual(100, h.eval())93 def testHandleWhileLoop(self):94 with self.test_session() as sess:95 # Initialize a handle.96 a = constant_op.constant(0)97 h = session_ops.get_session_handle(a)98 h = sess.run(h)99 # Do some computation.100 f, x = session_ops.get_session_tensor(h.handle, dtypes.int32)101 b = constant_op.constant(100)102 p = math_ops.less(x, b)103 # Must define the loop body outside the loop.104 h_x = session_ops.get_session_handle(math_ops.add(x, 1))105 while True:106 rp, h = sess.run([p, h_x], feed_dict={f: h.handle})107 if not rp:108 break109 self.assertEqual(101, h.eval())110 def testHandleMover(self):111 with self.test_session() as sess:112 # Return a handle.113 a = constant_op.constant(10)114 b = constant_op.constant(5)115 c = math_ops.multiply(a, b)116 h = session_ops.get_session_handle(c)117 h = sess.run(h)118 # Feed a tensor handle.119 f, x = session_ops.get_session_tensor(h.handle, dtypes.int32)120 y = math_ops.multiply(x, 10)121 self.assertEqual(500, sess.run(y, feed_dict={f: h.handle}))122 # Feed another tensor handle.123 with ops.device(test.gpu_device_name()):124 a = constant_op.constant(10)125 h = session_ops.get_session_handle(a)126 h = sess.run(h)127 self.assertEqual(100, sess.run(y, feed_dict={f: h.handle}))128 def testHandleDelete(self):129 with self.test_session() as sess:130 # Return a handle.131 a = constant_op.constant(10)132 b = constant_op.constant(5)133 c = math_ops.multiply(a, b)134 h = session_ops.get_session_handle(c)135 sess.run(h).delete()136 def testHandleDeleteRaw(self):137 with self.test_session() as sess:138 # Return a handle.139 a = constant_op.constant(10)140 b = constant_op.constant(5)141 c = math_ops.multiply(a, b)142 h = session_ops.get_session_handle(c)143 h = sess.run(h)144 # Delete using a raw tensor handle.145 raw_h = h.get_raw_handle()146 f, x = session_ops.delete_session_tensor(raw_h)147 sess.run(x, feed_dict={f: raw_h})148 def testMultiDevices(self):149 with self.test_session() as sess:150 with ops.device(test.gpu_device_name()):151 a = constant_op.constant(1.0)152 a_handle = sess.run(session_ops.get_session_handle(a))153 with ops.device("/cpu:0"):154 b = constant_op.constant(2.0)155 b_handle = sess.run(session_ops.get_session_handle(b))156 a_p, a_t = session_ops.get_session_tensor(a_handle.handle, dtypes.float32)157 b_p, b_t = session_ops.get_session_tensor(b_handle.handle, dtypes.float32)158 c = math_ops.add(a_t, b_t)159 c_handle = sess.run(160 session_ops.get_session_handle(c),161 feed_dict={a_p: a_handle.handle,162 b_p: b_handle.handle})163 self.assertEqual(3.0, c_handle.eval())164 def testHandleGC(self):165 with self.test_session() as sess:166 # initial values live on CPU167 with ops.device("/cpu:0"):168 one = constant_op.constant(1, dtype=dtypes.float32)169 one_handle = sess.run(session_ops.get_session_handle(one))170 x_handle = sess.run(session_ops.get_session_handle(one))171 # addition lives on GPU172 with ops.device(test.gpu_device_name()):173 add_h1, add_t1 = session_ops.get_session_tensor(one_handle.handle,174 dtypes.float32)175 add_h2, add_t2 = session_ops.get_session_tensor(x_handle.handle,176 dtypes.float32)177 add_op = math_ops.add(add_t1, add_t2)178 add_output = session_ops.get_session_handle(add_op)179 # add 1 to tensor 20 times180 for _ in range(20):181 x_handle = sess.run(182 add_output,183 feed_dict={add_h1: one_handle.handle,184 add_h2: x_handle.handle})185 def testHandlePlacement(self):186 with self.test_session() as sess:187 a = constant_op.constant(1.0)188 a_handle_op = session_ops.get_session_handle(a)189 b = constant_op.constant(2.0)190 b_handle_op = session_ops.get_session_handle(b)191 a_handle = sess.run(a_handle_op)192 b_handle = sess.run(b_handle_op)193 a_p, a_t = session_ops.get_session_tensor(a_handle.handle, dtypes.float32)194 b_p, b_t = session_ops.get_session_tensor(b_handle.handle, dtypes.float32)195 c = math_ops.add(a_t, b_t)196 c_handle = sess.run(197 session_ops.get_session_handle(c),198 feed_dict={a_p: a_handle.handle,199 b_p: b_handle.handle})200 self.assertEqual(3.0, c_handle.eval())201 def testFeedOneHandleDirectly(self):202 with self.test_session() as sess:203 a = constant_op.constant(10.0)204 b = constant_op.constant(5.0)205 c = math_ops.multiply(a, b)206 d = math_ops.multiply(c, c)207 h_c = sess.run(session_ops.get_session_handle(c))208 self.assertAllClose(2500.0, sess.run(d, feed_dict={c: h_c}))209 def testDirectHandleFeedOverlappingWithFetches(self):210 with self.test_session() as sess:211 a = constant_op.constant(10.0)212 b = constant_op.constant(5.0)213 c = math_ops.multiply(a, b)214 h_c = sess.run(session_ops.get_session_handle(c))215 d = array_ops.identity(c)216 c_val = sess.run(c, feed_dict={c: h_c})217 self.assertAllClose(50.0, c_val)218 d_val = sess.run(d, feed_dict={c: h_c})219 self.assertAllClose(50.0, d_val)220 c_val, d_val = sess.run([c, d], feed_dict={c: h_c, d: 60.0})221 self.assertAllClose(50.0, c_val)222 self.assertAllClose(60.0, d_val)223 c_val, d_val = sess.run([c, d], feed_dict={c: 60.0, d: h_c})224 self.assertAllClose(60.0, c_val)225 self.assertAllClose(50.0, d_val)226 c_val, d_val = sess.run([c, d], feed_dict={c: h_c, d: h_c})227 self.assertAllClose(50.0, c_val)228 self.assertAllClose(50.0, d_val)229 def testFeedTwoHandlesDirectly(self):230 with self.test_session() as sess:231 a = constant_op.constant(10.0)232 b = constant_op.constant(5.0)233 c = math_ops.multiply(a, b)234 d = math_ops.div(a, b)235 e = math_ops.subtract(c, d)236 h_c = sess.run(session_ops.get_session_handle(c))237 h_d = sess.run(session_ops.get_session_handle(d))238 self.assertAllClose(48.0, sess.run(e, feed_dict={c: h_c, d: h_d}))239 self.assertAllClose(-48.0, sess.run(e, feed_dict={c: h_d, d: h_c}))240 def testFeedHandleToVariableDirectly(self):241 with self.test_session() as sess:242 a = variables.Variable(12.0)243 inc_a = state_ops.assign_add(a, 2.0)244 b = math_ops.add(a, 5.0)245 sess.run(a.initializer)246 h_a_read = sess.run(session_ops.get_session_handle(a.read_value()))247 self.assertAllClose(12.0, sess.run(a))248 self.assertAllClose(17.0, sess.run(b, feed_dict={a: h_a_read}))249 sess.run(inc_a)250 self.assertAllClose(19.0, sess.run(b, feed_dict={a: h_a_read}))251if __name__ == "__main__":...
session_ops.py
Source:session_ops.py
...30from tensorflow.python.framework import ops31from tensorflow.python.ops import array_ops32from tensorflow.python.ops import gen_data_flow_ops33from tensorflow.python.util import compat34def encode_resource_handle(resource_handle):35 """Encode a ResourceHandle proto as custom numpy struct type."""36 return np.asarray(bytearray(resource_handle.SerializeToString()),37 dtype=dtypes.np_resource)38class TensorHandle(object):39 """Represents a handle for a live tensor in a session."""40 def __init__(self, handle, dtype, session):41 """Constructs a new tensor handle.42 A tensor handle for a persistent tensor is a python string43 that has the form of "tensor_name;unique_id;device_name".44 Args:45 handle: A tensor handle.46 dtype: The data type of the tensor represented by `handle`.47 session: The session in which the tensor is produced.48 """49 self._handle = compat.as_str_any(handle)50 self._resource_handle = None51 self._dtype = dtype52 self._session = session53 self._auto_gc_enabled = True54 def __del__(self):55 if self._auto_gc_enabled:56 self._session._register_dead_handle(self.handle)57 def __str__(self):58 return self._handle59 def _get_resource_handle(self):60 """The ResourceHandle representation of this handle."""61 if not self._resource_handle:62 self._resource_handle = resource_handle_pb2.ResourceHandleProto()63 self._resource_handle.device = self._handle.split(";")[-1]64 self._resource_handle.container = (65 pywrap_tensorflow_internal.TENSOR_HANDLE_KEY)66 self._resource_handle.name = self._handle67 return self._resource_handle68 def to_numpy_array(self):69 """Convert a TensorHandle object to a feedable numpy value.70 Returns:71 A numpy array of a custom struct type that can be used as a feed value72 to run().73 """74 return encode_resource_handle(self._get_resource_handle())75 @property76 def handle(self):77 """The string representation of this handle."""78 return self._handle79 def eval(self):80 """Return the value of the tensor represented by this handle."""81 if not self._auto_gc_enabled:82 raise TypeError("Persistent tensor %s may have already been deleted."83 % self.handle)84 holder, reader = _get_handle_reader(self._session.graph, self._handle,85 self._dtype)86 return self._session.run(reader, feed_dict={holder: self._handle})87 def delete(self):88 """Force the deletion of this persistent tensor."""89 if not self._auto_gc_enabled:90 raise TypeError("Persistent tensor %s may have already been deleted."91 % self.handle)92 self._auto_gc_enabled = False93 holder, deleter = _get_handle_deleter(self._session.graph, 0, self._handle)94 self._session.run(deleter, feed_dict={holder: self.handle})95 def get_raw_handle(self):96 """Return the raw handle of the tensor.97 Note that the method disables the automatic garbage collection of this98 persistent tensor. The caller is now responsible for managing the life99 time of the tensor.100 """101 self._auto_gc_enabled = False102 return self._handle103 @staticmethod104 def _get_device_name(handle):105 """The device name encoded in the handle."""106 handle_str = compat.as_str_any(handle)107 return pydev.canonical_name(handle_str.split(";")[-1])108 @staticmethod109 def _get_reader_key(handle):110 """The graph key for reader."""111 handle_parts = str(handle).split(";")112 return handle_parts[0] + ";" + handle_parts[-1]113 @staticmethod114 def _get_mover_key(feeder, handle):115 """The graph key for mover."""116 return feeder.op.name + ";" + TensorHandle._get_reader_key(handle)117def get_session_handle(data, name=None):118 """Return the handle of `data`.119 This is EXPERIMENTAL and subject to change.120 Keep `data` "in-place" in the runtime and create a handle that can be121 used to retrieve `data` in a subsequent run().122 Combined with `get_session_tensor`, we can keep a tensor produced in123 one run call in place, and use it as the input in a future run call.124 Args:125 data: A tensor to be stored in the session.126 name: Optional name prefix for the return tensor.127 Returns:128 A scalar string tensor representing a unique handle for `data`.129 Raises:130 TypeError: if `data` is not a Tensor.131 Example:132 ```python133 c = tf.multiply(a, b)134 h = tf.get_session_handle(c)135 h = sess.run(h)136 p, a = tf.get_session_tensor(h.handle, tf.float32)137 b = tf.multiply(a, 10)138 c = sess.run(b, feed_dict={p: h.handle})139 ```140 """141 if not isinstance(data, ops.Tensor):142 raise TypeError("`data` must be of type Tensor.")143 # Colocate this operation with data.144 with ops.colocate_with(data):145 return gen_data_flow_ops._get_session_handle(data, name=name) # pylint: disable=protected-access146def get_session_tensor(handle, dtype, name=None):147 """Get the tensor of type `dtype` by feeding a tensor handle.148 This is EXPERIMENTAL and subject to change.149 Get the value of the tensor from a tensor handle. The tensor150 is produced in a previous run() and stored in the state of the151 session.152 Args:153 handle: The string representation of a persistent tensor handle.154 dtype: The type of the output tensor.155 name: Optional name prefix for the return tensor.156 Returns:157 A pair of tensors. The first is a placeholder for feeding a158 tensor handle and the second is the tensor in the session state159 keyed by the tensor handle.160 Example:161 ```python162 c = tf.multiply(a, b)163 h = tf.get_session_handle(c)164 h = sess.run(h)165 p, a = tf.get_session_tensor(h.handle, tf.float32)166 b = tf.multiply(a, 10)167 c = sess.run(b, feed_dict={p: h.handle})168 ```169 """170 handle_device = TensorHandle._get_device_name(handle)171 with ops.device(handle_device):172 holder = array_ops.placeholder(dtypes.string)173 _register_handle_feeder(holder.graph, holder, dtype)174 tensor = gen_data_flow_ops._get_session_tensor(holder, dtype, name=name)175 return (holder, tensor)176def delete_session_tensor(handle, name=None):177 """Delete the tensor for the given tensor handle.178 This is EXPERIMENTAL and subject to change.179 Delete the tensor of a given tensor handle. The tensor is produced180 in a previous run() and stored in the state of the session.181 Args:182 handle: The string representation of a persistent tensor handle.183 name: Optional name prefix for the return tensor.184 Returns:185 A pair of graph elements. The first is a placeholder for feeding a186 tensor handle and the second is a deletion operation.187 """188 handle_device = TensorHandle._get_device_name(handle)189 with ops.device(handle_device):190 holder = array_ops.placeholder(dtypes.string)191 deleter = gen_data_flow_ops._delete_session_tensor(holder, name=name)192 return (holder, deleter)193def _register_handle_feeder(graph, feeder, dtype):194 graph._handle_feeders[feeder.op.name] = dtype195def _get_handle_feeder(graph, feeder):196 return graph._handle_feeders.get(feeder.op.name)197def _get_handle_reader(graph, handle, dtype):198 """Return a read subgraph for this handle."""199 graph_key = TensorHandle._get_reader_key(handle)200 result = graph._handle_readers.get(graph_key)201 if result is None:202 # Create reader if we haven't done it.203 handle_device = TensorHandle._get_device_name(handle)204 with graph.as_default(), graph.device(handle_device):205 holder = array_ops.placeholder(dtypes.string)206 _register_handle_feeder(holder.graph, holder, dtype)207 reader = gen_data_flow_ops._get_session_tensor(holder, dtype)208 result = (holder, reader)209 graph._handle_readers[graph_key] = result210 return result211def _get_handle_mover(graph, feeder, handle):212 """Return a move subgraph for this pair of feeder and handle."""213 dtype = _get_handle_feeder(graph, feeder)214 if dtype is None:215 return None216 handle_device = TensorHandle._get_device_name(handle)217 if feeder.op.device == handle_device:218 return None219 # Now we know we have to move the tensor.220 graph_key = TensorHandle._get_mover_key(feeder, handle)221 result = graph._handle_movers.get(graph_key)222 if result is None:223 # Create mover if we haven't done it.224 holder, reader = _get_handle_reader(graph, handle, dtype)225 with graph.as_default(), graph.device(feeder.op.device):226 mover = gen_data_flow_ops._get_session_handle(reader) # pylint: disable=protected-access227 result = (holder, mover)228 graph._handle_movers[graph_key] = result229 return result230def _get_handle_deleter(graph, deleter_key, handle):231 """Return a deletion subgraph for this handle."""232 result = graph._handle_deleters.get(deleter_key)233 if result is None:234 # Create deleter if we haven't done it.235 handle_device = TensorHandle._get_device_name(handle)236 with graph.as_default(), graph.device(handle_device):237 holder = array_ops.placeholder(dtypes.string)238 deleter = gen_data_flow_ops._delete_session_tensor(holder)239 result = (holder, deleter)240 graph._handle_deleters[deleter_key] = result...
eq_twitter.py
Source:eq_twitter.py
1# eq_twitter.py2# Description: module to interact with Twitter API3# Authors: Anthony Stone4# Alexander Talbott5# Jim Wang6import twitter7import pandas as pd8import eq_utilities9# this is not secure in any way shape or form10# but it is a dummy account that I don't use11# please don't abuse12api = twitter.Api(13 "xjBcMPKQDKtmS9YOxRjDs2v4T",14 "8sK4L0kYM0VT8UecMu8IPZgd54O8d20uaSnFwiAQvcDz0AWVRB",15 "1309554738543943684-jD3glTsDlofSFWX5DPVFSguZsBRaMp",16 "UbHoxvZky0ZcJQwQ0hpb6oIlDu01Dd3IuMslv0nzVmg2A",17)18# convert from ticker to company twitter handle19def retrieve_handle_from_ticker(ticker):20 if ticker.upper() == "AAPL":21 handle = "Apple"22 elif ticker.upper() == "ADBE":23 handle = "Adobe"24 elif ticker.upper() == "ADI":25 handle = "ADI_News"26 elif ticker.upper() == "ADSK":27 handle = "autodesk"28 elif ticker.upper() == "AMAT":29 handle = "Applied4Tech"30 elif ticker.upper() == "AMD":31 handle = "AMD"32 elif ticker.upper() == "ANSS":33 handle = "ANSYS"34 elif ticker.upper() == "ASML":35 handle = "ASMLcompany"36 elif ticker.upper() == "AVGO":37 handle = "Broadcom"38 elif ticker.upper() == "BIDU":39 handle = "Baidu_Inc"40 elif ticker.upper() == "CDNS":41 handle = "Cadence"42 elif ticker.upper() == "CDW":43 handle = "CDWCorp"44 elif ticker.upper() == "CERN":45 handle = "Cerner"46 elif ticker.upper() == "CHKP":47 handle = "CheckPointSW"48 elif ticker.upper() == "CSCO":49 handle = "Cisco"50 elif ticker.upper() == "CTSH":51 handle = "Cognizant"52 elif ticker.upper() == "CTXS":53 handle = "citrix"54 elif ticker.upper() == "DOCU":55 handle = "DocuSign"56 elif ticker.upper() == "FB":57 handle = "Facebook"58 elif ticker.upper() == "GOOG":59 handle = "Google"60 elif ticker.upper() == "GOOGL":61 handle = "Google"62 elif ticker.upper() == "INTC":63 handle = "intel"64 elif ticker.upper() == "INTU":65 handle = "Intuit"66 elif ticker.upper() == "KLAC":67 handle = "KLAcorp"68 elif ticker.upper() == "LRCX":69 handle = "LamResearch"70 elif ticker.upper() == "MCHP":71 handle = "MicrochipTech"72 elif ticker.upper() == "MSFT":73 handle = "Microsoft"74 elif ticker.upper() == "MU":75 handle = "MicronTech"76 elif ticker.upper() == "MXIM":77 handle = "maximintegrated"78 elif ticker.upper() == "NTES":79 handle = "NetEase_Global"80 elif ticker.upper() == "NVDA":81 handle = "nvidia"82 elif ticker.upper() == "NXPI":83 handle = "NXP"84 elif ticker.upper() == "QCOM":85 handle = "Qualcomm"86 elif ticker.upper() == "SNPS":87 handle = "Synopsis"88 elif ticker.upper() == "SPLK":89 handle = "splunk"90 elif ticker.upper() == "SWKS":91 handle = "SkyworksGlobal"92 elif ticker.upper() == "TXN":93 handle = "TXInstruments"94 elif ticker.upper() == "VRSN":95 handle = "VERISIGN"96 elif ticker.upper() == "WDAY":97 handle = "Workday"98 elif ticker.upper() == "WDC":99 handle = "WDCreators"100 elif ticker.upper() == "XLNX":101 handle = "XilinxInc"102 elif ticker.upper() == "BABA":103 handle = "AlibabaGroup"104 elif ticker.upper() == "TSLA":105 handle = "Tesla"106 elif ticker.upper() == "CRM":107 handle = "salesforce"108 elif ticker.upper() == "PYPL":109 handle = "PayPal"110 elif ticker.upper() == "ATVI":111 handle = "Activision"112 elif ticker.upper() == "EA":113 handle = "EA"114 elif ticker.upper() == "MTCH":115 handle = "Match"116 elif ticker.upper() == "ZG":117 handle = "zillow"118 elif ticker.upper() == "TTD":119 handle = "TheTradeDesk"120 elif ticker.upper() == "AMZN":121 handle = "Amazon"122 elif ticker.upper() == "ORCL":123 handle = "Oracle"124 elif ticker.upper() == "SAP":125 handle = "SAP"126 elif ticker.upper() == "IBM":127 handle = "IBM"128 elif ticker.upper() == "VMW":129 handle = "VMware"130 elif ticker.upper() == "HPQ":131 handle = "HP"132 elif ticker.upper() == "DDD":133 handle = "3dsystems"134 elif ticker.upper() == "ACIW":135 handle = "ACI_Worldwide"136 elif ticker.upper() == "ADTN":137 handle = "ADTRAN"138 elif ticker.upper() == "AKAM":139 handle = "Akamai"140 elif ticker.upper() == "MDRX":141 handle = "Allscripts"142 elif ticker.upper() == "ALTR":143 handle = "Altair_Inc"144 elif ticker.upper() == "DOX":145 handle = "Amdocs"146 elif ticker.upper() == "AZPN":147 handle = "AspenTech"148 elif ticker.upper() == "CACI":149 handle = "CACIIntl"150 elif ticker.upper() == "CIEN":151 handle = "Ciena"152 elif ticker.upper() == "CRUS":153 handle = "CirrusLogic"154 elif ticker.upper() == "CVLT":155 handle = "Commvault"156 elif ticker.upper() == "GLW":157 handle = "Corning"158 elif ticker.upper() == "CREE":159 handle = "Cree"160 elif ticker.upper() == "DBD":161 handle = "DieboldNixdorf"162 elif ticker.upper() == "EQIX":163 handle = "Equinix"164 elif ticker.upper() == "FFIV":165 handle = "F5Networks"166 elif ticker.upper() == "FICO":167 handle = "FICO"168 elif ticker.upper() == "GRMN":169 handle = "Garmin"170 elif ticker.upper() == "IT":171 handle = "Gartner_inc"172 elif ticker.upper() == "GWRE":173 handle = "Guidewire_PandC"174 elif ticker.upper() == "IDCC":175 handle = "InterDigitalCom"176 elif ticker.upper() == "JCOM":177 handle = "j2global"178 elif ticker.upper() == "JNPR":179 handle = "JuniperNetworks"180 elif ticker.upper() == "LHX":181 handle = "L3HarrisTech"182 elif ticker.upper() == "LDOS":183 handle = "LeidosInc"184 elif ticker.upper() == "MRVL":185 handle = "marvellsemi"186 elif ticker.upper() == "MSI":187 handle = "MotorolaUS"188 elif ticker.upper() == "NCR":189 handle = "NCRCorporation"190 elif ticker.upper() == "NTAP":191 handle = "NetApp"192 elif ticker.upper() == "NLOK":193 handle = "NortonLifelock"194 elif ticker.upper() == "NUAN":195 handle = "NuanceInc"196 elif ticker.upper() == "ON":197 handle = "onsemi"198 elif ticker.upper() == "PANW":199 handle = "PaloAltoNtwks"200 elif ticker.upper() == "PBI":201 handle = "PitneyBowes"202 elif ticker.upper() == "PLT":203 handle = "Plantronics"204 elif ticker.upper() == "PRGS":205 handle = "ProgressSW"206 elif ticker.upper() == "PTC":207 handle = "PTC"208 elif ticker.upper() == "SAIC":209 handle = "SAICinc"210 elif ticker.upper() == "STX":211 handle = "Seagate"212 elif ticker.upper() == "SMTC":213 handle = "SMTCCorporation"214 elif ticker.upper() == "NOW":215 handle = "servicenow"216 elif ticker.upper() == "SLAB":217 handle = "siliconlabs"218 elif ticker.upper() == "SSNC":219 handle = "SSCTechnologies"220 elif ticker.upper() == "SYNA":221 handle = "SynaCorp"222 elif ticker.upper() == "TDC":223 handle = "Teradata"224 elif ticker.upper() == "TER":225 handle = "Teradyneinc"226 elif ticker.upper() == "TWTR":227 handle = "Twitter"228 elif ticker.upper() == "TYL":229 handle = "tylertech"230 elif ticker.upper() == "VSAT":231 handle = "ViasatInc"232 elif ticker.upper() == "VIAV":233 handle = "ViaviSolutions"234 return handle235# scrape the twitter timeline of a given handle236def scrape_timeline(handle):237 timeline = api.GetUserTimeline(screen_name=handle, count=200)238 l = []239 for tweet in timeline:240 tweet = tweet.AsDict()241 if "in_reply_to_screen_name" not in tweet:242 l.append(tweet["text"])...
reduction.py
Source:reduction.py
...52#53if sys.platform == 'win32':54 import _subprocess55 from _multiprocessing import win3256 def send_handle(conn, handle, destination_pid):57 process_handle = win32.OpenProcess(58 win32.PROCESS_ALL_ACCESS, False, destination_pid59 )60 try:61 new_handle = duplicate(handle, process_handle)62 conn.send(new_handle)63 finally:64 close(process_handle)65 def recv_handle(conn):66 return conn.recv()67else:68 def send_handle(conn, handle, destination_pid):69 _multiprocessing.sendfd(conn.fileno(), handle)70 def recv_handle(conn):71 return _multiprocessing.recvfd(conn.fileno())72#73# Support for a per-process server thread which caches pickled handles74#75_cache = set()76def _reset(obj):77 global _lock, _listener, _cache78 for h in _cache:79 close(h)80 _cache.clear()81 _lock = threading.Lock()82 _listener = None83_reset(None)84register_after_fork(_reset, _reset)85def _get_listener():86 global _listener87 if _listener is None:88 _lock.acquire()89 try:90 if _listener is None:91 debug('starting listener and thread for sending handles')92 _listener = Listener(authkey=current_process().authkey)93 t = threading.Thread(target=_serve)94 t.daemon = True95 t.start()96 finally:97 _lock.release()98 return _listener99def _serve():100 from .util import is_exiting, sub_warning101 while 1:102 try:103 conn = _listener.accept()104 handle_wanted, destination_pid = conn.recv()105 _cache.remove(handle_wanted)106 send_handle(conn, handle_wanted, destination_pid)107 close(handle_wanted)108 conn.close()109 except:110 if not is_exiting():111 import traceback112 sub_warning(113 'thread for sharing handles raised exception :\n' +114 '-'*79 + '\n' + traceback.format_exc() + '-'*79115 )116#117# Functions to be used for pickling/unpickling objects with handles118#119def reduce_handle(handle):120 if Popen.thread_is_spawning():121 return (None, Popen.duplicate_for_child(handle), True)122 dup_handle = duplicate(handle)123 _cache.add(dup_handle)124 sub_debug('reducing handle %d', handle)125 return (_get_listener().address, dup_handle, False)126def rebuild_handle(pickled_data):127 address, handle, inherited = pickled_data128 if inherited:129 return handle130 sub_debug('rebuilding handle %d', handle)131 conn = Client(address, authkey=current_process().authkey)132 conn.send((handle, os.getpid()))133 new_handle = recv_handle(conn)134 conn.close()135 return new_handle136#137# Register `_multiprocessing.Connection` with `ForkingPickler`138#139def reduce_connection(conn):140 rh = reduce_handle(conn.fileno())141 return rebuild_connection, (rh, conn.readable, conn.writable)142def rebuild_connection(reduced_handle, readable, writable):143 handle = rebuild_handle(reduced_handle)144 return _multiprocessing.Connection(145 handle, readable=readable, writable=writable146 )147ForkingPickler.register(_multiprocessing.Connection, reduce_connection)148#149# Register `socket.socket` with `ForkingPickler`150#151def fromfd(fd, family, type_, proto=0):152 s = socket.fromfd(fd, family, type_, proto)153 if s.__class__ is not socket.socket:154 s = socket.socket(_sock=s)155 return s156def reduce_socket(s):157 reduced_handle = reduce_handle(s.fileno())158 return rebuild_socket, (reduced_handle, s.family, s.type, s.proto)159def rebuild_socket(reduced_handle, family, type_, proto):160 fd = rebuild_handle(reduced_handle)161 _sock = fromfd(fd, family, type_, proto)162 close(fd)163 return _sock164ForkingPickler.register(socket.socket, reduce_socket)165#166# Register `_multiprocessing.PipeConnection` with `ForkingPickler`167#168if sys.platform == 'win32':169 def reduce_pipe_connection(conn):170 rh = reduce_handle(conn.fileno())171 return rebuild_pipe_connection, (rh, conn.readable, conn.writable)172 def rebuild_pipe_connection(reduced_handle, readable, writable):173 handle = rebuild_handle(reduced_handle)174 return _multiprocessing.PipeConnection(175 handle, readable=readable, writable=writable176 )...
WalletBusiness.py
Source:WalletBusiness.py
1#coding=utf-82from handle.WalletHandle import WalletHandle3from handle.DetailHandle import DetailHandle4from handle.ManualHandle import ManualHandle5from handle.HomeHandle import HomeHandle6import time,re7class WalletBusiness:8 def __init__(self,driver):9 self.wallet_handle = WalletHandle(driver)10 self.detail_handle = DetailHandle(driver)11 self.manual_handle = ManualHandle(driver)12 self.home_handle = HomeHandle(driver)13 def get_invoice_num(self):14 num_text = self.wallet_handle.get_invoice_num()15 num_text = re.findall('累计å票ï¼(.*)å¼ ',num_text)[0]16 num = int(num_text)17 return num18 def swipe_invoice_delete(self,n):19 """æ»å¨å¢å¼ç¨å票å é¤"""20 for i in range(0,n):21 self.wallet_handle.get_sales_party_coordinate()22 def choose_paperInvoice_delete(self):23 """çéåºå¢å¼ç¨çº¸ç¥¨å é¤"""24 self.wallet_handle.click_invoiceClass()25 self.wallet_handle.click_paperInvoice()26 time.sleep(4)27 self.swipe_invoice_delete(2)28 self.wallet_handle.click_paperInvoice()29 self.wallet_handle.click_allInvoice()30 time.sleep(2)31 def choose_electricInvoice_delete(self):32 """çéåºå¢å¼ç¨çµç¥¨å é¤"""33 self.wallet_handle.click_invoiceClass()34 self.wallet_handle.click_electricInvoice()35 time.sleep(4)36 self.swipe_invoice_delete(2)37 self.wallet_handle.click_electricInvoice()38 self.wallet_handle.click_allInvoice()39 time.sleep(2)40 def batchIcon_open_close(self):41 """æ¹éæä½æé®å¼¹åº æ¶èµ·"""42 self.wallet_handle.click_batchOpenIcon()43 self.wallet_handle.click_batchCloseIcon()44 def batch_class(self):45 """æ¹ééæ©åç±»"""46 self.wallet_handle.click_batchOpenIcon()47 self.wallet_handle.click_batchClassIcon()48 self.wallet_handle.click_selectButton()49 self.manual_handle.click_determine()50 #éæ©åç±»çé
51 self.detail_handle.click_tobaccoButton()52 #ç¹å»ä¿å53 self.detail_handle.click_peservationButton()54 #ç¹å»ç¡®å®55 self.manual_handle.click_determine()56 time.sleep(2)57 def batch_todo(self):58 """æ¹ééæ©å¾
å"""59 self.wallet_handle.click_batchOpenIcon()60 self.wallet_handle.click_batchTodoIcon()61 self.wallet_handle.click_selectButton()62 self.manual_handle.click_determine()63 #éæ©å¾
åæ¥é64 self.detail_handle.click_reimbButton()65 #ç¹å»ä¿å66 self.detail_handle.click_peservationButton()67 #ç¹å»ç¡®å®68 #self.manual_handle.click_determine()69 time.sleep(2)70 def batch_print(self):71 """æ¹éæå°"""72 self.wallet_handle.click_batchOpenIcon()73 self.wallet_handle.click_batchPrintIcon()74 self.wallet_handle.click_selectButton()75 self.manual_handle.click_determine()76 time.sleep(12)77 def printpage_print(self):78 """æ¹éæå°é¡µé¢ç¹å»æå°"""79 self.wallet_handle.click_printInvoice()80 self.home_handle.click_confirm()81 def send_email(self):82 """æ¹éæå°é¡µé¢åéé®ç®±"""83 self.detail_handle.click_sendEmail()84 self.detail_handle.send_email('302802003@qq.com')85 self.home_handle.click_confirm()86 time.sleep(3)87 def eInvoice_choose_all(self):88 """票夹çµç¥¨é¡µé¢çéå
¨é¨å票"""89 self.wallet_handle.click_electricInvoice()90 self.wallet_handle.click_allInvoice()91 time.sleep(4)92 def paper_choose_all(self):93 """票夹纸票页é¢çéå
¨é¨å票"""94 self.wallet_handle.click_paperInvoice()95 self.wallet_handle.click_allInvoice()96 time.sleep(4)97 def taxi_choose_all(self):98 """票夹æ车票页é¢çéå
¨é¨å票"""99 self.wallet_handle.click_taxi()100 self.wallet_handle.click_allInvoice()101 time.sleep(4)102 def train_choose_all(self):103 """票夹ç«è½¦ç¥¨é¡µé¢çéå
¨é¨å票"""104 self.wallet_handle.click_train()105 self.wallet_handle.click_allInvoice()106 time.sleep(4)107 def choose_eInvoice_enter(self):108 """çéåºçµç¥¨ï¼ç¹å»è¿å
¥ä¸å¼ çµç¥¨"""109 self.wallet_handle.click_invoiceClass()110 self.wallet_handle.click_electricInvoice()111 time.sleep(4)112 self.wallet_handle.click_invoice()113 def choose_paperInvoice_enter(self):114 """çéåºçº¸ç¥¨ï¼ç¹å»è¿å
¥ä¸å¼ 纸票"""115 self.wallet_handle.click_invoiceClass()116 self.wallet_handle.click_paperInvoice()117 time.sleep(4)118 self.wallet_handle.click_invoice()119 def choose_train_enter(self):120 """çéåºç«è½¦ç¥¨ï¼ç¹å»è¿å
¥ä¸å¼ ç«è½¦ç¥¨"""121 self.wallet_handle.click_invoiceClass()122 self.wallet_handle.click_train()123 time.sleep(4)124 self.wallet_handle.click_train_invoice()125 def choose_taxi_enter(self):126 """çéåºæ车票ï¼ç¹å»è¿å
¥ä¸å¼ æ车票"""127 self.wallet_handle.click_invoiceClass()128 self.wallet_handle.click_taxi()129 time.sleep(4)...
wintypes.py
Source:wintypes.py
1######################################################################2# This file should be kept compatible with Python 2.3, see PEP 291. #3######################################################################4# The most useful windows datatypes5from ctypes import *6BYTE = c_byte7WORD = c_ushort8DWORD = c_ulong9WCHAR = c_wchar10UINT = c_uint11INT = c_int12DOUBLE = c_double13FLOAT = c_float14BOOLEAN = BYTE15BOOL = c_long16from ctypes import _SimpleCData17class VARIANT_BOOL(_SimpleCData):18 _type_ = "v"19 def __repr__(self):20 return "%s(%r)" % (self.__class__.__name__, self.value)21ULONG = c_ulong22LONG = c_long23USHORT = c_ushort24SHORT = c_short25# in the windows header files, these are structures.26_LARGE_INTEGER = LARGE_INTEGER = c_longlong27_ULARGE_INTEGER = ULARGE_INTEGER = c_ulonglong28LPCOLESTR = LPOLESTR = OLESTR = c_wchar_p29LPCWSTR = LPWSTR = c_wchar_p30LPCSTR = LPSTR = c_char_p31LPCVOID = LPVOID = c_void_p32# WPARAM is defined as UINT_PTR (unsigned type)33# LPARAM is defined as LONG_PTR (signed type)34if sizeof(c_long) == sizeof(c_void_p):35 WPARAM = c_ulong36 LPARAM = c_long37elif sizeof(c_longlong) == sizeof(c_void_p):38 WPARAM = c_ulonglong39 LPARAM = c_longlong40ATOM = WORD41LANGID = WORD42COLORREF = DWORD43LGRPID = DWORD44LCTYPE = DWORD45LCID = DWORD46################################################################47# HANDLE types48HANDLE = c_void_p # in the header files: void *49HACCEL = HANDLE50HBITMAP = HANDLE51HBRUSH = HANDLE52HCOLORSPACE = HANDLE53HDC = HANDLE54HDESK = HANDLE55HDWP = HANDLE56HENHMETAFILE = HANDLE57HFONT = HANDLE58HGDIOBJ = HANDLE59HGLOBAL = HANDLE60HHOOK = HANDLE61HICON = HANDLE62HINSTANCE = HANDLE63HKEY = HANDLE64HKL = HANDLE65HLOCAL = HANDLE66HMENU = HANDLE67HMETAFILE = HANDLE68HMODULE = HANDLE69HMONITOR = HANDLE70HPALETTE = HANDLE71HPEN = HANDLE72HRGN = HANDLE73HRSRC = HANDLE74HSTR = HANDLE75HTASK = HANDLE76HWINSTA = HANDLE77HWND = HANDLE78SC_HANDLE = HANDLE79SERVICE_STATUS_HANDLE = HANDLE80################################################################81# Some important structure definitions82class RECT(Structure):83 _fields_ = [("left", c_long),84 ("top", c_long),85 ("right", c_long),86 ("bottom", c_long)]87tagRECT = _RECTL = RECTL = RECT88class _SMALL_RECT(Structure):89 _fields_ = [('Left', c_short),90 ('Top', c_short),91 ('Right', c_short),92 ('Bottom', c_short)]93SMALL_RECT = _SMALL_RECT94class _COORD(Structure):95 _fields_ = [('X', c_short),96 ('Y', c_short)]97class POINT(Structure):98 _fields_ = [("x", c_long),99 ("y", c_long)]100tagPOINT = _POINTL = POINTL = POINT101class SIZE(Structure):102 _fields_ = [("cx", c_long),103 ("cy", c_long)]104tagSIZE = SIZEL = SIZE105def RGB(red, green, blue):106 return red + (green << 8) + (blue << 16)107class FILETIME(Structure):108 _fields_ = [("dwLowDateTime", DWORD),109 ("dwHighDateTime", DWORD)]110_FILETIME = FILETIME111class MSG(Structure):112 _fields_ = [("hWnd", HWND),113 ("message", c_uint),114 ("wParam", WPARAM),115 ("lParam", LPARAM),116 ("time", DWORD),117 ("pt", POINT)]118tagMSG = MSG119MAX_PATH = 260120class WIN32_FIND_DATAA(Structure):121 _fields_ = [("dwFileAttributes", DWORD),122 ("ftCreationTime", FILETIME),123 ("ftLastAccessTime", FILETIME),124 ("ftLastWriteTime", FILETIME),125 ("nFileSizeHigh", DWORD),126 ("nFileSizeLow", DWORD),127 ("dwReserved0", DWORD),128 ("dwReserved1", DWORD),129 ("cFileName", c_char * MAX_PATH),130 ("cAlternateFileName", c_char * 14)]131class WIN32_FIND_DATAW(Structure):132 _fields_ = [("dwFileAttributes", DWORD),133 ("ftCreationTime", FILETIME),134 ("ftLastAccessTime", FILETIME),135 ("ftLastWriteTime", FILETIME),136 ("nFileSizeHigh", DWORD),137 ("nFileSizeLow", DWORD),138 ("dwReserved0", DWORD),139 ("dwReserved1", DWORD),140 ("cFileName", c_wchar * MAX_PATH),141 ("cAlternateFileName", c_wchar * 14)]142__all__ = ['ATOM', 'BOOL', 'BOOLEAN', 'BYTE', 'COLORREF', 'DOUBLE', 'DWORD',143 'FILETIME', 'FLOAT', 'HACCEL', 'HANDLE', 'HBITMAP', 'HBRUSH',144 'HCOLORSPACE', 'HDC', 'HDESK', 'HDWP', 'HENHMETAFILE', 'HFONT',145 'HGDIOBJ', 'HGLOBAL', 'HHOOK', 'HICON', 'HINSTANCE', 'HKEY',146 'HKL', 'HLOCAL', 'HMENU', 'HMETAFILE', 'HMODULE', 'HMONITOR',147 'HPALETTE', 'HPEN', 'HRGN', 'HRSRC', 'HSTR', 'HTASK', 'HWINSTA',148 'HWND', 'INT', 'LANGID', 'LARGE_INTEGER', 'LCID', 'LCTYPE',149 'LGRPID', 'LONG', 'LPARAM', 'LPCOLESTR', 'LPCSTR', 'LPCVOID',150 'LPCWSTR', 'LPOLESTR', 'LPSTR', 'LPVOID', 'LPWSTR', 'MAX_PATH',151 'MSG', 'OLESTR', 'POINT', 'POINTL', 'RECT', 'RECTL', 'RGB',152 'SC_HANDLE', 'SERVICE_STATUS_HANDLE', 'SHORT', 'SIZE', 'SIZEL',153 'SMALL_RECT', 'UINT', 'ULARGE_INTEGER', 'ULONG', 'USHORT',154 'VARIANT_BOOL', 'WCHAR', 'WIN32_FIND_DATAA', 'WIN32_FIND_DATAW',155 'WORD', 'WPARAM', '_COORD', '_FILETIME', '_LARGE_INTEGER',156 '_POINTL', '_RECTL', '_SMALL_RECT', '_ULARGE_INTEGER', 'tagMSG',...
Using AI Code Generation
1const fc = require('fast-check');2const { handle } = require('fast-check-monorepo');3const isEven = (n) => n % 2 === 0;4const isOdd = (n) => !isEven(n);5const isOddArb = fc.integer().filter(isOdd);6const isEvenArb = fc.integer().filter(isEven);7fc.assert(8 fc.property(isOddArb, (n) => {9 return isOdd(n);10 })11);12fc.assert(13 fc.property(isEvenArb, (n) => {14 return isEven(n);15 })16);17fc.assert(18 fc.property(isOddArb, isEvenArb, (n1, n2) => {19 return isOdd(n1) && isEven(n2);20 })21);22const fc = require('fast-check');23const { handle } = require('fast-check-monorepo');24const isEven = (n) => n % 2 === 0;25const isOdd = (n) => !isEven(n);26const isOddArb = fc.integer().filter(isOdd);27const isEvenArb = fc.integer().filter(isEven);28handle(29 fc.property(isOddArb, (n) => {30 return isOdd(n);31 })32);33handle(34 fc.property(isEvenArb, (n) => {35 return isEven(n);36 })37);38handle(39 fc.property(isOddArb, isEvenArb, (n1, n2) => {40 return isOdd(n1) && isEven(n2);41 })42);
Using AI Code Generation
1const fc = require("fast-check");2const lib = require("./lib");3fc.assert(4 fc.property(fc.integer(), fc.integer(), (a, b) => {5 const result = lib.add(a, b);6 return result === a + b;7 })8);9const fc = require("fast-check");10const lib = require("./lib");11test("addition is commutative", () => {12 fc.assert(13 fc.property(fc.integer(), fc.integer(), (a, b) => {14 const result = lib.add(a, b);15 return result === a + b;16 })17 );18});19const fc = require("fast-check");20const lib = require("./lib");21it("addition is commutative", () => {22 fc.assert(23 fc.property(fc.integer(), fc.integer(), (a, b) => {24 const result = lib.add(a, b);25 return result === a + b;26 })27 );28});29const fc = require("fast-check");30const lib = require("./lib");31it("addition is commutative", () => {32 fc.assert(33 fc.property(fc.integer(), fc.integer(), (a, b) => {34 const result = lib.add(a, b);35 return result === a + b;36 })37 );38});
Using AI Code Generation
1const fc = require('fast-check');2const { handle } = require('fast-check-monorepo');3const arb = fc.integer();4const arb2 = fc.integer();5const arb3 = fc.integer();6const arb4 = fc.integer();7const arb5 = fc.tuple(arb, arb2, arb3, arb4);8const arb6 = fc.tuple(fc.string(), fc.string(), fc.string(), fc.string());9const arb7 = fc.tuple(fc.boolean(), fc.boolean(), fc.boolean(), fc.boolean());10const arb8 = fc.tuple(fc.double(), fc.double(), fc.double(), fc.double());11const arb9 = fc.tuple(fc.float(), fc.float(), fc.float(), fc.float());12const arb10 = fc.tuple(fc.nat(), fc.nat(), fc.nat(), fc.nat());13const arb11 = fc.tuple(fc.char(), fc.char(), fc.char(), fc.char());14const arb12 = fc.tuple(fc.hexa(), fc.hexa(), fc.hexa(), fc.hexa());15const arb13 = fc.tuple(fc.ascii(), fc.ascii(), fc.ascii(), fc.ascii());16const arb14 = fc.tuple(fc.fullUnicode(), fc.fullUnicode(), fc.fullUnicode(), fc.fullUnicode());17const arb15 = fc.tuple(fc.unicode(), fc.unicode(), fc.unicode(), fc.unicode());18const arb16 = fc.tuple(fc.webUrl(), fc.webUrl(), fc.webUrl(), fc.webUrl());19const arb17 = fc.tuple(fc.date(), fc.date(), fc.date(), fc.date());20const arb18 = fc.tuple(fc.time(), fc.time(), fc.time(), fc.time());21const arb19 = fc.tuple(fc.timestamp(), fc.timestamp(), fc.timestamp(), fc.timestamp());22const arb20 = fc.tuple(fc.month(), fc.month(), fc.month(), fc.month());23const arb21 = fc.tuple(fc.day(), fc.day(), fc.day(), fc.day());24const arb22 = fc.tuple(fc.hour(), fc.hour(), fc.hour(), fc.hour());25const arb23 = fc.tuple(fc.minute(), fc.minute(), fc.minute(), fc.minute());26const arb24 = fc.tuple(fc.second(), fc.second(), fc.second(), fc.second());27const arb25 = fc.tuple(fc.datetime(), fc.datetime(), fc.datetime(), fc.datetime());28const arb26 = fc.tuple(fc.option(arb), fc.option(arb), fc.option(arb), fc.option(arb));
Using AI Code Generation
1const fc = require('fast-check');2const { handle } = require('fast-check-monorepo');3const add = (a, b) => a + b;4describe('add', () => {5 it('should be commutative', () => {6 fc.assert(7 fc.property(fc.integer(), fc.integer(), (a, b) => {8 handle(add(a, b)).should.be.equal(add(b, a));9 })10 );11 });12});
Using AI Code Generation
1var handle = require('fast-check-monorepo').handle;2var test3 = function (a, b) {3 handle(a, b);4 return a + b;5};6module.exports = test3;7var handle = require('fast-check-monorepo').handle;8var test4 = function (a, b) {9 handle(a, b);10 return a + b;11};12module.exports = test4;13var handle = require('fast-check-monorepo').handle;14var test5 = function (a, b) {15 handle(a, b);16 return a + b;17};18module.exports = test5;19var handle = require('fast-check-monorepo').handle;20var test6 = function (a, b) {21 handle(a, b);22 return a + b;23};24module.exports = test6;25var handle = require('fast-check-monorepo').handle;26var test7 = function (a, b) {27 handle(a, b);28 return a + b;29};30module.exports = test7;31var handle = require('fast-check-monorepo').handle;32var test8 = function (a, b) {33 handle(a, b);34 return a + b;35};36module.exports = test8;37var handle = require('fast-check-monorepo').handle;38var test9 = function (a, b) {39 handle(a, b);40 return a + b;41};42module.exports = test9;43var handle = require('fast-check-monorepo').handle;44var test10 = function (a, b) {45 handle(a, b);46 return a + b;47};48module.exports = test10;
Using AI Code Generation
1const handle = require('fast-check-monorepo')2const assert = require('assert')3handle('test3', (req, res) => {4 res.send('Hello World!')5})6const handle = require('fast-check-monorepo')7const assert = require('assert')8handle('test4', (req, res) => {9 res.send('Hello World!')10})11const handle = require('fast-check-monorepo')12const assert = require('assert')13handle('test5', (req, res) => {14 res.send('Hello World!')15})16const handle = require('fast-check-monorepo')17const assert = require('assert')18handle('test6', (req, res) => {19 res.send('Hello World!')20})21const handle = require('fast-check-monorepo')22const assert = require('assert')23handle('test7', (req, res) => {24 res.send('Hello World!')25})26const handle = require('fast-check-monorepo')27const assert = require('assert')28handle('test8', (req, res) => {29 res.send('Hello World!')30})31const handle = require('fast-check-monorepo')32const assert = require('assert')33handle('test9', (req, res) => {34 res.send('Hello World!')35})36const handle = require('fast-check-monorepo')37const assert = require('assert')38handle('test10', (req, res) => {39 res.send('Hello World!')40})41const handle = require('fast-check-monorepo')42const assert = require('assert')43handle('test11', (req, res) => {44 res.send('
Using AI Code Generation
1const fc = require('fast-check');2const handle = require('fast-check-monorepo/src/handle');3const { parse, print } = require('recast');4const { generate } = require('astring');5const { generate: generateEsprima } = require('escodegen');6const { parse: parseEsprima } = require('esprima');7function foo(x) {8 return x + 1;9}10`;11const ast = parse(code);12const astEsprima = parseEsprima(code);13console.log(generate(ast));14console.log(generateEsprima(astEsprima));15console.log(print(ast).code);16console.log(handle(ast));17 .oneof(18 .map((value) => {19 return {20 expression: {21 },22 };23 });24fc.assert(25 fc.property(arb, (ast) => {26 const code = generateEsprima(ast);27 const ast2 = parseEsprima(code);28 return JSON.stringify(ast) === JSON.stringify(ast2);29 })30);31Thanks to [Christophe Porteneuve](
Using AI Code Generation
1import { handle } from 'fast-check';2import { test } from './test2';3const test3 = handle(test, {4});5test3(1234);6import { testProp, fc } from 'fast-check';7testProp('should always pass', [fc.integer()], (a) => {8 return true;9});10import { testProp, fc } from 'fast-check';11testProp('should always pass', [fc.integer(), fc.integer()], (a, b) => {12 return true;13});14import { testProp, fc } from 'fast-check';15testProp('should always pass', [fc.integer(), fc.integer(), fc.integer()], (a, b, c) => {16 return true;17});18import { testProp, fc } from 'fast-check';19testProp('should always pass', [fc.integer(), fc.integer(), fc.integer(), fc.integer()], (a, b, c, d) => {20 return true;21});22import { testProp, fc } from 'fast-check';23testProp('should always pass', [fc.integer(), fc.integer(), fc.integer(), fc.integer(), fc.integer()], (a, b, c, d, e) => {24 return true;25});26import { testProp, fc } from 'fast-check';27testProp('should always pass', [fc.integer(), fc.integer(), fc.integer(), fc.integer(), fc.integer(), fc.integer()], (a, b, c, d, e, f) => {28 return true;29});30import { testProp, fc } from '
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!