query
stringlengths
9
3.4k
document
stringlengths
9
87.4k
metadata
dict
negatives
listlengths
4
101
negative_scores
listlengths
4
101
document_score
stringlengths
3
10
document_rank
stringclasses
102 values
The selector function accepts a component instance and returns the appropriate key to index plot_classes dictionary.
def __init__(self, selector, plot_classes, allow_mismatch=False): self.selector = selector self.plot_classes = OrderedDict(plot_classes) interface = self._define_interface(self.plot_classes.values(), allow_mismatch) self.style_opts, self.plot_options = interface
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def node_selector(self) -> Dict[str, str]:\n return self._node_selector", "def lookup_class_idx(self,label):\r\n \r\n return self.class_labels[label]", "def getSelector(self, node):\n self.checkModelOpen()\n calcEngine = CalcEngine.factory(self.client_session)\n return...
[ "0.54593", "0.53855276", "0.5289531", "0.52059805", "0.51838773", "0.5170124", "0.51380694", "0.51380694", "0.51380694", "0.51380694", "0.51380694", "0.51380694", "0.51380694", "0.51380694", "0.51380694", "0.51380694", "0.51380694", "0.51380694", "0.51380694", "0.51380694", "...
0.4618312
68
Get the state of the Plot for a given frame number.
def __getitem__(self, frame): if not self.dynamic == 'open' and isinstance(frame, int) and frame > len(self): self.warning("Showing last frame available: %d" % len(self)) if not self.drawn: self.handles['fig'] = self.initialize_plot() if not self.dynamic == 'open' and not isinstance(frame, tuple): frame = self.keys[frame] self.update_frame(frame) return self.state
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def getFrame(self, num):\n\n return self.data[num]", "def get_plot_state(self_or_cls, obj, renderer=None, **kwargs):\n if not isinstance(obj, Plot):\n obj = self_or_cls.get_plot(obj=obj, renderer=renderer, **kwargs)\n return obj.state", "def get_frame(self, frame):\n retu...
[ "0.6576043", "0.64040893", "0.6168167", "0.61134017", "0.6076815", "0.6055128", "0.5951637", "0.5882845", "0.58641803", "0.5848422", "0.5799237", "0.5756058", "0.5718137", "0.5702686", "0.56998396", "0.56985414", "0.5595627", "0.5593545", "0.5543105", "0.5521952", "0.5484779"...
0.6989357
0
Required on each MPLPlot type to get the data corresponding just to the current frame out from the object.
def _get_frame(self, key): pass
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_data(self):\n return [self.axes]", "def plot_data(self):", "def _get_raw_data(self, idx=0):\n # Get the time step then make a data frame\n raise NotImplementedError('Code me up!')\n #data = self._data[???]\n return data", "def __data_frame(self):\n return sel...
[ "0.6572209", "0.6476473", "0.64533323", "0.6261248", "0.6070728", "0.59735954", "0.5929763", "0.5889976", "0.5844909", "0.5839488", "0.5793765", "0.5782455", "0.57820135", "0.5781594", "0.5757953", "0.5725428", "0.5717131", "0.5696034", "0.5693247", "0.56396365", "0.56344974"...
0.0
-1
Matches a specification against the current Plot.
def matches(self, spec): if callable(spec) and not isinstance(spec, type): return spec(self) elif isinstance(spec, type): return isinstance(self, spec) else: raise ValueError("Matching specs have to be either a type or a callable.")
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_match():\n fig, ax = plt.subplots()\n ax.plot([0, 1], [0, 2])\n slide = _get_empty_slide()\n text = ax.set_title(\"TITLE TEXT\")\n shape = figpptx.send(fig, slide=slide, match=text)\n assert get_typename(shape) == \"Shape\"\n shapes = _get_shapes(slide, individual=True)\n assert le...
[ "0.5498152", "0.54748654", "0.54442275", "0.51404667", "0.5081998", "0.5065666", "0.50126404", "0.50075436", "0.4972846", "0.49207228", "0.49176952", "0.4876025", "0.48672763", "0.48624754", "0.48509756", "0.48303744", "0.48123005", "0.4783596", "0.47810036", "0.47768372", "0...
0.51842225
3
Traverses any nested DimensionedPlot returning a list of all plots that match the specs. The specs should be supplied as a list of either Plot types or callables, which should return a boolean given the plot class.
def traverse(self, fn=None, specs=None, full_breadth=True): accumulator = [] matches = specs is None if not matches: for spec in specs: matches = self.matches(spec) if matches: break if matches: accumulator.append(fn(self) if fn else self) # Assumes composite objects are iterables if hasattr(self, 'subplots') and self.subplots: for el in self.subplots.values(): accumulator += el.traverse(fn, specs, full_breadth) if not full_breadth: break return accumulator
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_available_figures(self):\n return sorted((method[5:], func) \\\n for method, func in self.__class__.__dict__.iteritems() \\\n if method.startswith(\"plot_\") and callable(func))", "def get_plots(self):\n return list(self.plots.values())", "def _sp...
[ "0.52858", "0.52142483", "0.51448363", "0.50744987", "0.50589556", "0.48802635", "0.48739997", "0.48073155", "0.4798928", "0.4749356", "0.47428975", "0.47420156", "0.47197765", "0.46932372", "0.46918872", "0.4680866", "0.46731734", "0.46569225", "0.4638593", "0.46093962", "0....
0.56958634
0
Returns the formatted dimension group strings for a particular frame.
def _frame_title(self, key, group_size=2, separator='\n'): if self.dynamic == 'open' and self.current_key: key = self.current_key if self.layout_dimensions is not None: dimensions, key = zip(*self.layout_dimensions.items()) elif not self.dynamic and (not self.uniform or len(self) == 1) or self.subplot: return '' else: key = key if isinstance(key, tuple) else (key,) dimensions = self.dimensions dimension_labels = [dim.pprint_value_string(k) for dim, k in zip(dimensions, key)] groups = [', '.join(dimension_labels[i*group_size:(i+1)*group_size]) for i in range(len(dimension_labels))] return util.safe_unicode(separator.join(g for g in groups if g))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_grp_string(self):\n\n grp = self.get_grp()\n\n if grp == -1:\n\n return \"\"\n\n return \"grp \" + str(grp)", "def format_to_string(groups: List[List]) -> str:\n\tgroups_str = \"\"\n\tcount = 1\n\tfor group in groups:\n\t\tgroups_str += f\"Group {count}: {group} \\n\"\n\t\...
[ "0.64216906", "0.63535005", "0.6112604", "0.59159833", "0.58164614", "0.5747988", "0.5726756", "0.57234955", "0.56927526", "0.56833076", "0.565327", "0.5643954", "0.5607467", "0.55895174", "0.55715007", "0.5488538", "0.5466888", "0.5411597", "0.5394599", "0.53788805", "0.5364...
0.5254912
33
Given an object, a specific key and the normalization options this method will find the specified normalization options on the appropriate OptionTree, group the elements according to the selected normalization option (i.e. either per frame or over the whole animation) and finally compute the dimension ranges in each group. The new set of ranges is returned.
def compute_ranges(self, obj, key, ranges): all_table = all(isinstance(el, Table) for el in obj.traverse(lambda x: x, [Element])) if obj is None or not self.normalize or all_table: return OrderedDict() # Get inherited ranges ranges = self.ranges if ranges is None else dict(ranges) # Get element identifiers from current object and resolve # with selected normalization options norm_opts = self._get_norm_opts(obj) # Traverse displayed object if normalization applies # at this level, and ranges for the group have not # been supplied from a composite plot return_fn = lambda x: x if isinstance(x, Element) else None for group, (axiswise, framewise) in norm_opts.items(): elements = [] # Skip if ranges are cached or already computed by a # higher-level container object. framewise = framewise or self.dynamic if group in ranges and (not framewise or ranges is not self.ranges): continue elif not framewise: # Traverse to get all elements elements = obj.traverse(return_fn, [group]) elif key is not None: # Traverse to get elements for each frame frame = self._get_frame(key) elements = [] if frame is None else frame.traverse(return_fn, [group]) if not axiswise or ((not framewise or len(elements) == 1) and isinstance(obj, HoloMap)): # Compute new ranges self._compute_group_range(group, elements, ranges) self.ranges.update(ranges) return ranges
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _get_norm_opts(self, obj):\n norm_opts = {}\n\n # Get all elements' type.group.label specs and ids\n type_val_fn = lambda x: (x.id, (type(x).__name__, util.group_sanitizer(x.group, escape=False),\n util.label_sanitizer(x.label, escape=False))) \\\n ...
[ "0.6445774", "0.48843622", "0.4852263", "0.48259893", "0.4770748", "0.47455063", "0.4726611", "0.4720005", "0.4644569", "0.46267", "0.45563284", "0.4543702", "0.454177", "0.45273983", "0.4494524", "0.4494449", "0.44733185", "0.44697282", "0.44692782", "0.44428465", "0.4435969...
0.689226
0
Gets the normalization options for a LabelledData object by traversing the object for to find elements and their ids. The id is then used to select the appropriate OptionsTree, accumulating the normalization options into a dictionary. Returns a dictionary of normalization options for each element in the tree.
def _get_norm_opts(self, obj): norm_opts = {} # Get all elements' type.group.label specs and ids type_val_fn = lambda x: (x.id, (type(x).__name__, util.group_sanitizer(x.group, escape=False), util.label_sanitizer(x.label, escape=False))) \ if isinstance(x, Element) else None element_specs = {(idspec[0], idspec[1]) for idspec in obj.traverse(type_val_fn) if idspec is not None} # Group elements specs by ID and override normalization # options sequentially key_fn = lambda x: -1 if x[0] is None else x[0] id_groups = groupby(sorted(element_specs, key=key_fn), key_fn) for gid, element_spec_group in id_groups: gid = None if gid == -1 else gid group_specs = [el for _, el in element_spec_group] backend = self.renderer.backend optstree = Store.custom_options( backend=backend).get(gid, Store.options(backend=backend)) # Get the normalization options for the current id # and match against customizable elements for opts in optstree: path = tuple(opts.path.split('.')[1:]) applies = any(path == spec[:i] for spec in group_specs for i in range(1, 4)) if applies and 'norm' in opts.groups: nopts = opts['norm'].options if 'axiswise' in nopts or 'framewise' in nopts: norm_opts.update({path: (nopts.get('axiswise', False), nopts.get('framewise', False))}) element_specs = [spec for _, spec in element_specs] norm_opts.update({spec: (False, False) for spec in element_specs if not any(spec[:i] in norm_opts.keys() for i in range(1, 4))}) return norm_opts
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def dictize(self):\n dict = {}\n for node in self.sort():\n logger.debug(\"Dictize: id %s has name %s\" % (node._id, node.name))\n x = node._kwargs()\n dict[node._id]={\"klass\":node.__class__.__name__, \n \"kwargs\": x,\n ...
[ "0.4882127", "0.48138362", "0.46735653", "0.46150512", "0.45790586", "0.44817707", "0.44758487", "0.4465512", "0.442252", "0.44222006", "0.43991864", "0.43809223", "0.4366402", "0.43599775", "0.4356347", "0.43552524", "0.43511787", "0.42940468", "0.42261603", "0.42139208", "0...
0.6927882
0
Traverses the supplied object getting all options in opts for the specified opt_type and specs. Also takes into account the plotting class defaults for plot options. If a keyfn is supplied the returned options will be grouped by the returned keys.
def _traverse_options(cls, obj, opt_type, opts, specs=None, keyfn=None, defaults=True): def lookup(x): """ Looks up options for object, including plot defaults, keyfn determines returned key otherwise None key is used. """ options = cls.lookup_options(x, opt_type) selected = {o: options.options[o] for o in opts if o in options.options} if opt_type == 'plot' and defaults: plot = Store.registry[cls.backend].get(type(x)) selected['defaults'] = {o: getattr(plot, o) for o in opts if o not in selected and hasattr(plot, o)} key = keyfn(x) if keyfn else None return (key, selected) # Traverse object and accumulate options by key traversed = obj.traverse(lookup, specs) options = defaultdict(lambda: defaultdict(list)) default_opts = defaultdict(lambda: defaultdict(list)) for key, opts in traversed: defaults = opts.pop('defaults', {}) for opt, v in opts.items(): options[key][opt].append(v) for opt, v in defaults.items(): default_opts[key][opt].append(v) # Merge defaults into dictionary if not explicitly specified for key, opts in default_opts.items(): for opt, v in opts.items(): if opt not in options[key]: options[key][opt] = v return options if keyfn else options[None]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _all_opt_infos(self):\n for info in self._opts.values():\n yield info, None\n for group in self._groups.values():\n for info in group._opts.values():\n yield info, group", "def get_plot_kwargs(cfg, option, key=None):\n plot_kwargs = cfg.get(option, {}).ge...
[ "0.5892671", "0.5606828", "0.56063414", "0.550141", "0.54399914", "0.5378535", "0.5304472", "0.52757764", "0.52567726", "0.52553415", "0.52336997", "0.5221113", "0.5217911", "0.51816285", "0.5152726", "0.51514137", "0.5142801", "0.51401424", "0.5134124", "0.5131874", "0.51075...
0.86038965
0
Looks up options for object, including plot defaults, keyfn determines returned key otherwise None key is used.
def lookup(x): options = cls.lookup_options(x, opt_type) selected = {o: options.options[o] for o in opts if o in options.options} if opt_type == 'plot' and defaults: plot = Store.registry[cls.backend].get(type(x)) selected['defaults'] = {o: getattr(plot, o) for o in opts if o not in selected and hasattr(plot, o)} key = keyfn(x) if keyfn else None return (key, selected)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _traverse_options(cls, obj, opt_type, opts, specs=None, keyfn=None, defaults=True):\n def lookup(x):\n \"\"\"\n Looks up options for object, including plot defaults,\n keyfn determines returned key otherwise None key is used.\n \"\"\"\n options = cl...
[ "0.6476717", "0.6211503", "0.57079715", "0.5571008", "0.5534396", "0.547191", "0.54293185", "0.5385394", "0.53531367", "0.53213716", "0.5306876", "0.5284712", "0.5159889", "0.51395476", "0.5116941", "0.51114714", "0.50779635", "0.507736", "0.5073758", "0.5022548", "0.5020879"...
0.6997502
0
Uses traversal to find the appropriate projection for a nested object. Respects projections set on Overlays before considering Element based settings, before finally looking up the default projection on the plot type. If more than one nonNone projection type is found an exception is raised.
def _get_projection(cls, obj): isoverlay = lambda x: isinstance(x, CompositeOverlay) opts = cls._traverse_options(obj, 'plot', ['projection'], [CompositeOverlay, Element], keyfn=isoverlay) from_overlay = not all(p is None for p in opts[True]['projection']) projections = opts[from_overlay]['projection'] custom_projs = [p for p in projections if p is not None] if len(set(custom_projs)) > 1: raise Exception("An axis may only be assigned one projection type") return custom_projs[0] if custom_projs else None
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def projectionManip(*args, fitBBox: bool=True, projType: int=0, switchType: bool=True, q=True,\n query=True, **kwargs)->Union[None, Any]:\n pass", "def create_projection_from_projector_element(\n self, element, weight, type, projector_id\n ):\n projection = {\n \...
[ "0.61008054", "0.57861453", "0.541124", "0.5349921", "0.5343465", "0.5273637", "0.5211582", "0.51546365", "0.5075276", "0.504999", "0.49605206", "0.49293154", "0.48868015", "0.48221928", "0.48099476", "0.4738513", "0.47346017", "0.47128424", "0.47019666", "0.46675426", "0.459...
0.6758612
0
Refreshes the plot by rerendering it and then pushing the updated data if the plot has an associated Comm.
def refresh(self, **kwargs): traverse_setter(self, '_force', True) key = self.current_key if self.current_key else self.keys[0] stream_params = stream_parameters(self.streams) key = tuple(None if d in stream_params else k for d, k in zip(self.dimensions, key)) stream_key = util.wrap_tuple_streams(key, self.dimensions, self.streams) self.update(stream_key) if self.comm is not None: self.push()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def update_plot():\n pass", "def plot_refresh():\n figure.canvas.draw()", "def _UpdatePlot( self ):\n self._BusyDoOp( self._UpdatePlotImpl )", "def update_plot(self,ax):\n self.replot(ax)", "def updatePlot(self):\n self.axes.clear()\n self.axes.plot(self.data[0], self.data...
[ "0.7288777", "0.6962232", "0.6900487", "0.6737718", "0.6697221", "0.6682248", "0.6682248", "0.6682248", "0.6682248", "0.6682248", "0.66806316", "0.66681284", "0.6639615", "0.6597625", "0.6559798", "0.6359195", "0.63513744", "0.63109744", "0.6272057", "0.6253011", "0.62247986"...
0.0
-1
Pushes updated plot data via the Comm.
def push(self): if self.comm is None: raise Exception('Renderer does not have a comm.') diff = self.renderer.diff(self) self.comm.send(diff)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def update_plot():\n pass", "def on_new_data(self):\n\n if self.connected:\n tab_open = self.tab_open()\n\n # Update plot data\n for i, series in enumerate(self.measurements_list):\n if i == tab_open:\n self.plotted_data[i].setData(...
[ "0.6883734", "0.68772954", "0.6770715", "0.6723177", "0.6713831", "0.66170454", "0.6524996", "0.6524996", "0.6524996", "0.6524996", "0.6524996", "0.65054625", "0.6487483", "0.6401084", "0.6326303", "0.6279867", "0.622038", "0.60897267", "0.60824525", "0.6045853", "0.6021864",...
0.63146627
15
Initializes comm and attaches streams.
def init_comm(self, obj): comm = None if self.dynamic or self.renderer.widget_mode == 'live': comm = self.renderer.comms[self.renderer.mode][0](self) attach_streams(self, obj) return comm
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __init__(self):\n # Open stata as pipe; make a queue for non-blocking. Start the thread.\n self.proc = sp.Popen(['stata-mp'], stdin=sp.PIPE, stdout=sp.PIPE, bufsize=1)\n\n self.qu = Queue()\n\n self.thread = Thread(target = self.enqueue_output, args = (self.proc.stdout,\n ...
[ "0.62361443", "0.6131124", "0.6047162", "0.60436773", "0.59891397", "0.598821", "0.5979925", "0.59722435", "0.59679276", "0.59299994", "0.5921529", "0.5889616", "0.588344", "0.5872382", "0.58591175", "0.58533263", "0.5845079", "0.5841991", "0.582825", "0.57430446", "0.5731562...
0.5991638
4
Returns the total number of available frames.
def __len__(self): return len(self.keys)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_total_frames(self) -> int:\n return self.num_frames", "def size(self):\n if self.frames is None:\n return 0\n return self.frames.size", "def frames(self):\n frame_count = 0\n if self.is_video() or self.is_audio():\n if self.__dict__['nb_frames']:...
[ "0.8600426", "0.77835464", "0.7621566", "0.75558245", "0.7531837", "0.7526261", "0.7391324", "0.7189588", "0.71559983", "0.70775414", "0.70692587", "0.7036695", "0.7004031", "0.69709444", "0.6951622", "0.688492", "0.68131065", "0.6812733", "0.6789151", "0.66947013", "0.664887...
0.0
-1
Computes the zorder of element in the NdOverlay taking into account possible batching of elements.
def get_zorder(self, overlay, key, el): spec = util.get_overlay_spec(overlay, key, el) try: return self.ordering.index(spec) except ValueError: self.ordering = sorted(self.ordering+[spec]) return self.ordering.index(spec)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def getz_index(self):\n return self._getz_index", "def optimise_z(z, *args):\n x, y, elements, coordinates = args\n window_com = np.array([x, y, z])\n return pore_diameter(elements, coordinates, com=window_com)[0]", "def z(self):\r\n return self.position.z", "def _set_planar_pixel_order(im...
[ "0.57028675", "0.55984366", "0.5478423", "0.54625237", "0.5441317", "0.537248", "0.5289451", "0.52060914", "0.5195802", "0.51892036", "0.51678", "0.5121228", "0.51193726", "0.50830746", "0.507015", "0.5063056", "0.5060691", "0.5056381", "0.5056132", "0.50311744", "0.5008574",...
0.72016543
0
Gets the extents for the axes from the current View. The globally computed ranges can optionally override the extents.
def get_extents(self, view, ranges): ndims = len(view.dimensions()) num = 6 if self.projection == '3d' else 4 if self.apply_ranges: if ranges: dims = view.dimensions() x0, x1 = ranges[dims[0].name] if ndims > 1: y0, y1 = ranges[dims[1].name] else: y0, y1 = (np.NaN, np.NaN) if self.projection == '3d': if len(dims) > 2: z0, z1 = ranges[dims[2].name] else: z0, z1 = np.NaN, np.NaN else: x0, x1 = view.range(0) y0, y1 = view.range(1) if ndims > 1 else (np.NaN, np.NaN) if self.projection == '3d': z0, z1 = view.range(2) if self.projection == '3d': range_extents = (x0, y0, z0, x1, y1, z1) else: range_extents = (x0, y0, x1, y1) else: range_extents = (np.NaN,) * num if self.apply_extents: norm_opts = self.lookup_options(view, 'norm').options if norm_opts.get('framewise', False) or self.dynamic: extents = view.extents else: extent_list = self.hmap.traverse(lambda x: x.extents, [Element]) extents = util.max_extents(extent_list, self.projection == '3d') else: extents = (np.NaN,) * num return tuple(l1 if l2 is None or not np.isfinite(l2) else l2 for l1, l2 in zip(range_extents, extents))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def extents(self):\n self._updateExtents()\n return self.mExtents", "def extents(self):\n x0, y0, width, height = self._rect_bbox\n xmin, xmax = sorted([x0, x0 + width])\n ymin, ymax = sorted([y0, y0 + height])\n return xmin, xmax, ymin, ymax", "def extents(self):\n\n ...
[ "0.72161704", "0.6875994", "0.6859144", "0.67906785", "0.65129864", "0.63847166", "0.63576", "0.6300293", "0.6264915", "0.6224861", "0.61757976", "0.61531943", "0.61249256", "0.61061025", "0.60827875", "0.6021081", "0.5992878", "0.599001", "0.59846133", "0.5962699", "0.596207...
0.7218878
0
Set the plot(s) to the given frame number. Operates by manipulating the matplotlib objects held in the self._handles dictionary. If n is greater than the number of available frames, update using the last available frame.
def update_frame(self, key, ranges=None):
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __plot_n__(self, refresh=False, *args):\n # If plot is not requested, return:\n if not self.plotneVar.get() or not self.plotniVar.get():\n return\n\n # Check for a closed window:\n if 'n' in self.plots.keys() and not matplotlib.pyplot.fignum_exists(self.plots['n'].number)...
[ "0.62682223", "0.576072", "0.5558097", "0.55435854", "0.5533847", "0.55313236", "0.54860616", "0.54809326", "0.547151", "0.5446553", "0.54084885", "0.5352229", "0.53280175", "0.53238046", "0.5293158", "0.52775246", "0.5230508", "0.52274555", "0.5225835", "0.5224569", "0.52202...
0.0
-1
Given a HoloMap compute the appropriate (mapwise or framewise) ranges in order to apply the Compositor collapse operations in display mode (data collapse should already have happened).
def _apply_compositor(self, holomap, ranges=None, keys=None, dimensions=None): # Compute framewise normalization defaultdim = holomap.ndims == 1 and holomap.kdims[0].name != 'Frame' if keys and ranges and dimensions and not defaultdim: dim_inds = [dimensions.index(d) for d in holomap.kdims] sliced_keys = [tuple(k[i] for i in dim_inds) for k in keys] frame_ranges = OrderedDict([(slckey, self.compute_ranges(holomap, key, ranges[key])) for key, slckey in zip(keys, sliced_keys) if slckey in holomap.data.keys()]) else: mapwise_ranges = self.compute_ranges(holomap, None, None) frame_ranges = OrderedDict([(key, self.compute_ranges(holomap, key, mapwise_ranges)) for key in holomap.keys()]) ranges = frame_ranges.values() return Compositor.collapse(holomap, (ranges, frame_ranges.keys()), mode='display')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _modify_map_size(self, merged_map):\n pos_x_white, pos_y_white = np.where(merged_map == 255)\n pos_x_black, pos_y_black = np.where(merged_map == 0)\n\n pos_x_M = np.amax(np.hstack((pos_x_black, pos_x_white)))\n pos_x_m = np.amin(np.hstack((pos_x_black, pos_x_white)))\n pos_y_...
[ "0.53061557", "0.5123476", "0.50569475", "0.5041872", "0.4931829", "0.49258262", "0.4896154", "0.4868902", "0.4862584", "0.48051956", "0.48001003", "0.47694784", "0.47593305", "0.47555342", "0.4747587", "0.47454724", "0.47438157", "0.47292355", "0.47042343", "0.46995413", "0....
0.77395713
0
Creates a clone of the Layout with the nthframe for each Element.
def _get_frame(self, key): layout_frame = self.layout.clone(shared_data=False) keyisint = isinstance(key, int) if not isinstance(key, tuple): key = (key,) nthkey_fn = lambda x: zip(tuple(x.name for x in x.kdims), list(x.data.keys())[min([key[0], len(x)-1])]) if key == self.current_key: return self.current_frame else: self.current_key = key for path, item in self.layout.items(): if self.dynamic == 'open': if keyisint: counts = item.traverse(lambda x: x.counter, (DynamicMap,)) if key[0] >= counts[0]: item.traverse(lambda x: next(x), (DynamicMap,)) dim_keys = item.traverse(nthkey_fn, (DynamicMap,))[0] else: dim_keys = zip([d.name for d in self.dimensions if d in item.dimensions('key')], key) self.current_key = tuple(k[1] for k in dim_keys) elif item.traverse(lambda x: x, [DynamicMap]): with dimensionless_cache(item, not self._force or not self.drawn): key, frame = util.get_dynamic_item(item, self.dimensions, key) layout_frame[path] = frame continue elif self.uniform: dim_keys = zip([d.name for d in self.dimensions if d in item.dimensions('key')], key) else: dim_keys = item.traverse(nthkey_fn, (HoloMap,))[0] if dim_keys: obj = item.select((HoloMap,), **dict(dim_keys)) if isinstance(obj, HoloMap) and len(obj) == 0: continue else: layout_frame[path] = obj else: layout_frame[path] = item traverse_setter(self, '_force', False) self.current_frame = layout_frame return layout_frame
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def make_layout(self):\n\n for h in range(0, self.num_layout_heads):\n self.set_random_layout(h)\n self.set_sliding_window_layout(h)\n self.set_global_layout_itc(h)\n\n self.check_and_propagate_first_head_layout()\n return self.layout", "def clone(self):\n ...
[ "0.64056253", "0.64034027", "0.6147005", "0.6052775", "0.5999924", "0.59923536", "0.58694065", "0.5848677", "0.5804697", "0.58001226", "0.5778056", "0.5773629", "0.5630633", "0.55947256", "0.5549548", "0.54448736", "0.54406804", "0.54355043", "0.5418124", "0.5387226", "0.5353...
0.0
-1
Playing with spatial convs after transpose convolutions. Recent testing suggests this is the best setup so far. Revisit idea of interleaving spatial convolutions between transpose layers to achieve more cleanly defined shapes.
def decoder_setup_1(): decoder = RetinaDecoder( # pre-pooling {'op': 'avg', 'kernel': (1, 2, 2), 'causal': True}, # grouped temporal conv stacks: [ { 'in': 15, 'out': [45, 45, 15], 'kernel': (2, 1, 1), 'stride': 1, 'groups': 15, 'acivation': nn.ReLU, 'pool': {'op': 'avg', 'kernel': (2, 2, 2), 'causal': True} } ], # spatial conv layers: {in, out, kernel, stride} [ # {'in': 15, 'out': 64, 'kernel': (1, 3, 3), 'stride': 1} ], # for each ConvRNN cell: [ ], # temporal convolution stack(s) [ { 'in': 15, 'out': [128, 256, 128], 'kernel': (2, 3, 3), 'stride': 1, 'groups': 1, 'acivation': nn.ReLU } ], # ConvTranspose layers: {in, out, kernel, stride} [ {'in': 128, 'out': 64, 'kernel': (3, 3, 3), 'stride': (2, 2, 2)}, {'in': 64, 'out': 16, 'kernel': (3, 3, 3), 'stride': (1, 2, 2)}, ], # post conv layers [ {'in': 16, 'out': 8, 'kernel': (1, 3, 3), 'stride': 1}, {'in': 8, 'out': 1, 'kernel': (1, 1, 1), 'stride': 1} ], ) return decoder
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_transposed_conv2d_model(self):\n tf.compat.v1.reset_default_graph()\n\n _ = transposed_conv2d_model()\n\n conn_graph = ConnectedGraph(tf.compat.v1.get_default_graph(), ['input_1'], ['conv2d_transpose/BiasAdd'])\n self.assertEqual(conn_graph.get_all_ops()['conv2d_transpose/conv2...
[ "0.6420241", "0.63742214", "0.630493", "0.62457377", "0.6166526", "0.61490655", "0.60816073", "0.6013133", "0.59594655", "0.59204423", "0.5848845", "0.5842317", "0.58345294", "0.5829648", "0.58118945", "0.5805117", "0.57954824", "0.5793485", "0.5791456", "0.57831615", "0.5781...
0.0
-1
This setup was the first big success, solid base config to work from. Note the lack of causal pooling, I hadn't built that module yet.
def decoder_setup_2(): decoder = RetinaDecoder( # pre-pooling {'op': 'avg', 'kernel': (1, 2, 2), 'causal': False}, # grouped temporal conv stacks: [ { 'in': 15, 'out': [45, 45, 15], 'kernel': (2, 1, 1), 'stride': 1, 'groups': 15, 'acivation': nn.ReLU, 'pool': {'op': 'avg', 'kernel': (2, 2, 2), 'causal': False} } ], # spatial conv layers: {in, out, kernel, stride} [ ], # for each ConvRNN cell: [ ], # temporal convolution stack(s) [ { 'in': 15, 'out': [128, 256, 128], 'kernel': (2, 3, 3), 'stride': 1, 'groups': 1, 'acivation': nn.ReLU } ], # ConvTranspose layers: {in, out, kernel, stride} [ {'in': 128, 'out': 64, 'kernel': (3, 3, 3), 'stride': (2, 2, 2)}, {'in': 64, 'out': 1, 'kernel': (3, 3, 3), 'stride': (1, 2, 2)}, ], # post conv layers [ ], ) return decoder
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def build_configs():", "def config():", "def config():", "def _setup_pipeline_cfg(self):", "def init_config(self):\n pass", "def configure(self):", "def configure(self):", "def configure(self):", "def configure(self):", "def _configure(self):\n pass", "def get_base_config(self):\n...
[ "0.6253901", "0.62495774", "0.62495774", "0.61576325", "0.6040787", "0.60355586", "0.60355586", "0.60355586", "0.60355586", "0.59917283", "0.5979285", "0.59686154", "0.593352", "0.59138405", "0.5896729", "0.58624494", "0.58605725", "0.58148235", "0.5778351", "0.57762766", "0....
0.0
-1
This is the same as setup_2, which was the first breakthrough network, except here the pooling operations have been set to causal mode. On colab, 2x 20 epochs with lr=1e1 and batch_sz=8 has produced strong strong decoding results.
def decoder_setup_5(): decoder = RetinaDecoder( # pre-pooling {'op': 'avg', 'kernel': (1, 2, 2), 'causal': True}, # grouped temporal conv stacks: [ { 'in': 15, 'out': [45, 45, 15], 'kernel': (2, 1, 1), 'stride': 1, 'groups': 15, 'acivation': nn.ReLU, 'pool': {'op': 'avg', 'kernel': (2, 2, 2), 'causal': True} } ], # spatial conv layers: {in, out, kernel, stride} [ # {'in': 15, 'out': 64, 'kernel': (1, 3, 3), 'stride': 1} ], # for each ConvRNN cell: [ ], # temporal convolution stack(s) [ { 'in': 15, 'out': [128, 256, 128], 'kernel': (2, 3, 3), 'stride': 1, 'groups': 1, 'acivation': nn.ReLU } ], # ConvTranspose layers: {in, out, kernel, stride} [ {'in': 128, 'out': 64, 'kernel': (3, 3, 3), 'stride': (2, 2, 2)}, {'in': 64, 'out': 1, 'kernel': (3, 3, 3), 'stride': (1, 2, 2)}, ], # post conv layers [ ], ) return decoder
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def main_train(lr, bs, cuda_id, not_distrib, fp16, loss_scale):\r\n torch.backends.cudnn.benchmark = True\r\n if fp16: assert torch.backends.cudnn.enabled, \"missing cudnn\"\r\n stats = (np.array([ 0.4914 , 0.48216, 0.44653]), np.array([ 0.24703, 0.24349, 0.26159]))\r\n sz=32\r\n PATH = Path(\"....
[ "0.67401975", "0.6634952", "0.657736", "0.649362", "0.6486684", "0.64751244", "0.64618695", "0.64333904", "0.64330065", "0.6408339", "0.64069897", "0.6405594", "0.6391012", "0.63891834", "0.638887", "0.6384175", "0.6357176", "0.6355764", "0.63509816", "0.6346752", "0.6345361"...
0.0
-1
Create a onehot encoding of x of size k.
def one_hot(x, k, dtype=np.float32): return np.array(x[:, None] == np.arange(k), dtype)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _one_hot(z, K):\n z_one_hot = np.zeros((z.size, K))\n z_one_hot[np.arange(z.size), z] = 1\n return z_one_hot", "def one_hot(x, k, dtype=np.float32):\n return np.array(x[:, None] == np.arange(k), dtype)", "def _one_hot(x, k, dtype=np.float32):\n return np.array(x[:, None] == np.arange(k), dtype...
[ "0.804429", "0.801011", "0.78977334", "0.7889785", "0.7800311", "0.7714966", "0.75706875", "0.75658363", "0.7427502", "0.7418045", "0.73576915", "0.735553", "0.7347711", "0.7343637", "0.7291789", "0.7286171", "0.7206042", "0.72045", "0.7190287", "0.7164403", "0.71621656", "...
0.7974455
2
Returns a Bokeh glyph object.
def _init_glyph(self, plot, mapping, properties): level = properties.pop('level', 'underlay') renderer = plot.add_tile(mapping['tile_source'], level=level) renderer.alpha = properties.get('alpha', 1) return renderer, renderer
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def createReferenceGlyph(self):\n return _libsbml.GeneralGlyph_createReferenceGlyph(self)", "def createTextGlyph(self):\n return _libsbml.Layout_createTextGlyph(self)", "def _init_glyph(self, plot, mapping, properties):\n properties.pop('source')\n properties.pop('legend')\n ...
[ "0.64251554", "0.6417896", "0.6385368", "0.61207485", "0.6027903", "0.5853716", "0.5838887", "0.580616", "0.5715113", "0.5697527", "0.5558109", "0.55418766", "0.5470425", "0.54696107", "0.5457854", "0.5454618", "0.5413018", "0.5380582", "0.5379364", "0.5375702", "0.5330651", ...
0.5845592
6
This Method is used to display the snake on the screen
def draw_snake(self, dis, snake_Part, snake_Body): for x in snake_Body: if self.left: direction = pygame.transform.rotate(x[2], x[3]) dis.blit(direction, (x[0], x[1])) elif self.right: direction = pygame.transform.rotate(x[2], x[3]) dis.blit(direction, (x[0], x[1])) elif self.up: direction = pygame.transform.rotate(x[2], x[3]) dis.blit(direction, (x[0], x[1])) elif self.down: direction = pygame.transform.rotate(x[2], x[3]) dis.blit(direction, (x[0], x[1])) if self.left: x1 = self.x + self.x_change - 10 y1 = self.y + self.y_change - 10 hdir = pygame.transform.rotate(Head, -90) dis.blit(hdir, (x1,y1)) elif self.right: x1 = self.x + self.x_change - 10 y1 = self.y + self.y_change - 10 hdir = pygame.transform.rotate(Head, 90) dis.blit(hdir, (x1,y1)) elif self.up: x1 = self.x + self.x_change - 10 y1 = self.y + self.y_change - 10 hdir = pygame.transform.rotate(Head, 180) dis.blit(hdir, (x1,y1)) elif self.down: x1 = self.x + self.x_change - 10 y1 = self.y + self.y_change - 10 hdir = pygame.transform.rotate(Head, 0) dis.blit(hdir, (x1,y1)) pygame.display.update
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _draw_snake(self):\n if self._snake is not None:\n for pixel in self._snake.body:\n self._sensehat.set_pixel(pixel.x, pixel.y, self._snake.color)", "def snakePrint():\n for snake in snake_pos: \n pg.draw.rect(game_disp, white, snake)", "def draw(self):\n ...
[ "0.79485714", "0.7818384", "0.7750519", "0.76774824", "0.75454086", "0.75067466", "0.7198423", "0.7196283", "0.70794916", "0.7040218", "0.7037165", "0.69755983", "0.6951785", "0.6936071", "0.6926142", "0.69155216", "0.68954194", "0.6849644", "0.6842827", "0.6826483", "0.67571...
0.70201904
11
This Function Displays the Food
def fooddraw(foodx, foody): dis.blit(Food, (foodx, foody)) pygame.display.update()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def print_food(self):\n for dish in self.food:\n print(dish.get_name())", "def food_eaten(self):\r\n # get values from GUI\r\n\r\n foodList = \"\"\r\n foodCost=0\r\n if self.is_eggs.get():\r\n foodList += \"eggs $2.00\\n\"\r\n foodCost...
[ "0.77116036", "0.7256722", "0.68620783", "0.68321484", "0.6552086", "0.654516", "0.65346205", "0.6491626", "0.64828205", "0.64672315", "0.63990873", "0.63842154", "0.63528955", "0.6261036", "0.6243647", "0.62275267", "0.6203672", "0.61670315", "0.6158984", "0.60892135", "0.60...
0.5860002
39
This Function Shows a message on the screen
def message(msg ,font_size, color , pos): font_style = pygame.font.SysFont( "Times New Roman" , font_size) mesg = font_style.render(msg, True, color) dis.blit(mesg, pos) pygame.display.update()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def display_message():", "def showMessage(self):", "def showMessage(self, message):\r\n print message", "def display_message(self, message):\n\t\tself.render('message.html', {'message': message})", "def display(self,message):\r\n \r\n print(message)", "def showme(message):\n print...
[ "0.8671978", "0.8480241", "0.828352", "0.8071773", "0.80670726", "0.8040086", "0.78809476", "0.78725165", "0.77866286", "0.7779627", "0.77761686", "0.77727395", "0.7755101", "0.7697426", "0.7672498", "0.76241535", "0.75889695", "0.75355613", "0.7512984", "0.7485261", "0.74392...
0.70739853
42
This Function is used to control the Movement of the Snake
def Movement(): keys = pygame.key.get_pressed() if keys[pygame.K_LEFT] and not snake.ang==90: snake.x_change = -snake.vel snake.y_change = 0 snake.left = True snake.right = False snake.up = False snake.down = False snake.ang = -90 elif keys[pygame.K_RIGHT] and not snake.ang==-90: snake.x_change = snake.vel snake.y_change = 0 snake.left = False snake.right = True snake.up = False snake.down = False snake.ang = 90 elif keys[pygame.K_UP] and not snake.ang==0: snake.x_change = 0 snake.y_change = -snake.vel snake.left = False snake.right = False snake.up = True snake.down = False snake.ang = 180 elif keys[pygame.K_DOWN] and not snake.ang==180: snake.x_change = 0 snake.y_change = snake.vel snake.left = False snake.right = False snake.up = False snake.down = True snake.ang = 0
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def move(self):\r\n piece = []\r\n if self.direction == \"UP\":\r\n piece = [self.body[0][0], self.body[0][1] - self.POS_CHANGE] # create piece at new coordinates\r\n elif self.direction == \"DOWN\":\r\n piece = [self.body[0][0], self.body[0][1] + self.POS_CHANGE]\r\n ...
[ "0.7399674", "0.6836237", "0.6778097", "0.6765576", "0.67256254", "0.66972667", "0.65777445", "0.6498739", "0.6492528", "0.6492464", "0.64858997", "0.6451853", "0.64459854", "0.640347", "0.64023644", "0.6400139", "0.6397963", "0.6363882", "0.6341559", "0.63338673", "0.6333867...
0.78153515
0
This Function Shows the current Score of the Player
def scoredraw(score): msg = "SCORE : " + str(score - 4) font_style = pygame.font.SysFont( "Microsoft Sans Serif" , 30) mesg = font_style.render(msg, True, (255,255,255)) dis.blit(mesg, (10,10)) pygame.display.update()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def display_score(self, win, player, computer):\n font = pygame.font.SysFont('comicsans', 70)\n if player < 10 and computer < 10:\n pygame.draw.rect(win, black, (150, 30, 75, 50))\n pygame.draw.rect(win, black, (295, 30, 75, 50))\n text1 = font.render(str(player), 1, ...
[ "0.7532108", "0.7476087", "0.74749184", "0.74059784", "0.7357234", "0.73177207", "0.7274991", "0.71760094", "0.714652", "0.7103239", "0.7076728", "0.7065711", "0.7053772", "0.7051625", "0.70301944", "0.70110327", "0.6995284", "0.6994245", "0.6992214", "0.6988295", "0.6986813"...
0.0
-1
This Function draws The Background of the Game
def redraw(dis): dis.blit(Bg,(0,0))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def draw_bg(self):\n self.screen.fill(self.bg)", "def mainmenu_background():\n gameDisplay.fill((40, 0, 40))", "def mainmenu_background():\n gameDisplay.fill((40, 0, 40))", "def drawBackground(self,screen):\n pygame.draw.rect(screen,(240,240,240),(self.basepos[0],self.base...
[ "0.8316609", "0.82724404", "0.82724404", "0.8187887", "0.808807", "0.80437565", "0.8034377", "0.7890868", "0.7850961", "0.7809966", "0.7805984", "0.77891445", "0.7769102", "0.7744283", "0.76951754", "0.76865375", "0.75081706", "0.7474712", "0.74424314", "0.7403836", "0.738532...
0.7090386
34
This Function Calculates distance between Food and Snake
def Distance(foodx,foody): di = ((snake.x - foodx)**2) + ((snake.y - foody)**2) d = int(math.sqrt(di)) return d
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def measure_distance(self):\n # set Trigger to HIGH\n GPIO.output(self.GPIO_TRIGGER, True)\n\n # set Trigger after 0.01ms to LOW\n time.sleep(0.00001)\n GPIO.output(self.GPIO_TRIGGER, False)\n\n start_time = time.time()\n stop_time = time.time()\n\n # save St...
[ "0.6700603", "0.6521232", "0.6514296", "0.63147444", "0.62802625", "0.6160367", "0.61424226", "0.6136788", "0.61203325", "0.6113802", "0.6087659", "0.6070107", "0.6063656", "0.6058297", "0.60548335", "0.60548335", "0.60385036", "0.6023612", "0.60140026", "0.5991973", "0.59842...
0.8156581
0
This Function Shows the Start screen at the Start of the Game
def StartScreen(): dis.blit(Sl, (dis_width/2 - 200, 0)) message("Snake" , 90, (23, 252, 3), (dis_width/2 - 100, 400)) message("Press Enter To Start", 50, (143,250,3), (dis_width/2 - 190, 500)) pygame.display.update()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def gamemode_startscreen(self) -> None:\n self.__draw_startscreen()", "def displayStartScreen(self):\n self.model.buttons.draw(self.screen)\n Title=myfont.render(\"THE WORLD ENDS WITH COINS\", 1, random.choice(all_color))\n self.screen.blit(Title, (550, 300))\n pygame.display.u...
[ "0.8430267", "0.8425534", "0.8040839", "0.80370176", "0.7912492", "0.7737424", "0.76517355", "0.739627", "0.7327332", "0.7277575", "0.72326416", "0.7161845", "0.71366405", "0.7117598", "0.7070147", "0.70684344", "0.70596254", "0.70382", "0.70099735", "0.69944596", "0.69934815...
0.7316806
9
This function Show an End Screen If Player Losses the Game
def EndScreen(score): message("Game Over", 100, (255, 16, 16), (dis_width/2 - 210 , dis_height/2 -100) ) message(" Press Enter to Try Again and Esc to Exit", 30 , (50,255,100), (dis_width/2 - 250, dis_height/2 + 50)) last_score = "Your Score is : " +str(score - 4) message(last_score, 50, (255,255,255), (dis_width/2 - 170, dis_height/2))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def display_end_game(self):\n game_view = self.get_view.get_game_view\n character = self.model.get_character\n\n if character.alive:\n game_view.game_win()\n else:\n game_view.game_over()\n\n game_view.update_display()", "def end_game(self):\n pygam...
[ "0.79576516", "0.7893134", "0.7839257", "0.7556048", "0.7502281", "0.7455614", "0.74543214", "0.7444883", "0.7424693", "0.7401899", "0.7302308", "0.72807413", "0.72732544", "0.7265182", "0.7250664", "0.7242742", "0.72027653", "0.71485794", "0.714262", "0.7102258", "0.70943487...
0.70578074
22
If the user presses the close button in the Title Bar This Function Closes the Game
def Quit(): for event in pygame.event.get(): if event.type == pygame.QUIT: return True
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def OnClose(self, event):\r\n pos.app.main.Exit()", "def end_game():\n pygame.quit()\n exit()", "def __window_close(self):\n pass", "def onBtnCloseClicked(self):\n self.close()", "def exit_game(root):\n root.destroy()", "def end_pygame(self):\n pygame.quit()", "def ...
[ "0.78174365", "0.7448609", "0.73944855", "0.7382604", "0.7349683", "0.7257558", "0.7246158", "0.72404736", "0.72394633", "0.7183465", "0.71531284", "0.7136925", "0.7078766", "0.70734334", "0.70675", "0.7057641", "0.7057267", "0.70546734", "0.7045907", "0.7045907", "0.7045907"...
0.7133421
12
Main_Game function which includes all the functions and commands to run the game Returns None.
def main_game(): #All the initial perimeters required to Run the Game Game_quit = False Loss = False foodx = round(random.randrange(50, dis_width - 50)) foody = round(random.randrange(50, dis_height - 50)) snake_Body = [] score = 4 redraw(dis) while not Game_quit: keys = pygame.key.get_pressed() Game_quit = Quit() if not snake.Start: StartScreen() if keys[pygame.K_RETURN]: snake.Start = True if Loss: EndScreen(score) if keys[pygame.K_RETURN]: main_game() elif keys[pygame.K_ESCAPE]: Game_quit = True snake.x = dis_width/2 snake.y = dis_height/2 #Playing Game...... while snake.Start and not Loss and not Game_quit : Clock.tick(20) Game_quit = Quit() Movement() snake.x += snake.x_change snake.y += snake.y_change if snake.x < 0 or snake.x > dis_width - snake.width or snake.y < 0 or snake.y > dis_height - snake.height: Loss = True #For Drawing Snake Body having different x and y with each part of snake snake_Part = [] snake_Part.append(snake.x) snake_Part.append(snake.y) snake_Part.append(Mid) snake_Part.append(snake.ang) snake_Body.append(snake_Part) if len(snake_Body) > score: del snake_Body[0] #For Drawing the Head of the snake snake_x = snake.x snake_y = snake.y snake_x += snake.x_change snake_y += snake.y_change headposx = snake_x headposy = snake_y #Collision Detection between head and body for track in snake_Body[:-1]: if track[0] == headposx and track[1] == headposy: Loss = True snake.draw_snake(dis, snake_Part, snake_Body) fooddraw(foodx, foody) d = Distance(foodx,foody) #Collision Detection between Snake and the Food if d < 40: foodx = round(random.randrange(50, dis_width - 50)) foody = round(random.randrange(50, dis_height - 50)) score += 1 scoredraw(score) redraw(dis)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def main():\r\n gameclass = data.game.GameClass()\r\n gameclass.main_loop()", "def main():\n\n name, game = select_game(vgc.KNOWN_GAMES)\n print('---- Launching: %s -----'%name)\n game.game.main()\n sys.exit(0)", "def main():\n g = Game(800, 600)\n g.start()", "def main():\n if \"c...
[ "0.8002683", "0.7967029", "0.78307676", "0.7737318", "0.7592417", "0.7592117", "0.74496835", "0.74165875", "0.74120873", "0.7353868", "0.725643", "0.72122735", "0.72043264", "0.71520734", "0.71451414", "0.7072199", "0.70497036", "0.69795376", "0.69768864", "0.6971949", "0.697...
0.0
-1
Inserts the (priority, content) element and percolates it up in the binary heap.
def push(self, item: tuple): self.__heap.append(item) self.__sift_up(self.__len__() - 1)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def insert(self, data):\n # add data to list'end\n self.heap_list.append(data)\n # adjust max-heap from bottom to top\n self.sift_up(len(self.heap_list)-1)", "def insert(self, element):\n if self.size >= self.maxsize : \n return\n self.size+= 1\n self.H...
[ "0.7215978", "0.7176819", "0.7170936", "0.71155995", "0.7005643", "0.6955782", "0.6939675", "0.6876973", "0.6861779", "0.6800935", "0.67226076", "0.6711996", "0.669744", "0.6697037", "0.6668611", "0.66360056", "0.6631062", "0.66289246", "0.6607817", "0.6604025", "0.6573611", ...
0.6376806
35
Pops the item wih the largest priority and repairs the heap.
def pop(self) -> tuple: item = self.__heap.popleft() if len(self) > 1: self.__heap.appendleft(self.__heap.pop()) self.__sift_down(0) return item
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def push_pop(self, item, priority):\n if self.size() < 1:\n raise ValueError('Priority queue is empty and has no front item')\n else:\n # TODO: Replace and return min item from heap, if any\n ...", "def delete_max(self):\n retval = self.heap_list[1]\n ...
[ "0.77817386", "0.76223326", "0.7581046", "0.7518329", "0.74608326", "0.73750526", "0.72169954", "0.7203851", "0.7195688", "0.7184285", "0.7160784", "0.7153954", "0.71533555", "0.70930916", "0.70832413", "0.7074128", "0.7068215", "0.70491946", "0.70461", "0.7043287", "0.703058...
0.70076555
23
Updates the priority of an item.
def update(self, idx: int, new_priority: T.Union[int, float]): old_priority, item = self.__heap[idx] self.__heap[idx] = (new_priority, item) if new_priority < old_priority: self.__sift_up(idx) else: self.__sift_down(idx)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def setPriority(self, p):\n self.priority = p", "def increase_priority(self):\n if self._priority > 0:\n self._priority -= 1", "def schedule_update_priority(self, func, pri, *args, **kwargs):\n self.unschedule(func)\n new_item = _Item(func, pri, args, kwargs)\n for i,s...
[ "0.7033521", "0.70131207", "0.6888573", "0.68740356", "0.6721127", "0.6596157", "0.657843", "0.64021325", "0.6299", "0.6285044", "0.6251421", "0.624495", "0.6241001", "0.62359715", "0.6228096", "0.6220238", "0.6217791", "0.6217791", "0.6208242", "0.62000865", "0.61397344", ...
0.66484094
5
Percolates up the item if the first element in the item is smaller than the first element in the parent.
def __sift_up(self, i: int): while i > 0: parent = (i - 1) // 2 if self.__heap[i][0] < self.__heap[parent][0]: tmp = self.__heap[parent] self.__heap[parent] = self.__heap[i] self.__heap[i] = tmp i = parent
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def percolate_up(self, index):\n if self.min is True:\n parent = self._parent(index)\n if index > 0 and self._data[index] < self._data[parent]:\n self._swap(index, parent)\n self.percolate_up(parent)\n if self.min is False:\n parent = sel...
[ "0.73008174", "0.6977387", "0.69455796", "0.6931688", "0.6897218", "0.68804336", "0.6834447", "0.6793737", "0.67846876", "0.67604595", "0.672829", "0.6725234", "0.6719083", "0.66191155", "0.65959144", "0.6558018", "0.65543073", "0.6469654", "0.64037776", "0.63678527", "0.6363...
0.69485795
2
Percolates down the item if the first element in the item is larger than the first element in the child.
def __sift_down(self, i: int): while (2 * i + 1) <= self.__len__() - 1: child_idx = self.__get_smallest_child(i) if self.__heap[i][0] > self.__heap[child_idx][0]: tmp = self.__heap[i] self.__heap[i] = self.__heap[child_idx] self.__heap[child_idx] = tmp i = child_idx
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def perc_down(self, i): #\r\n while (i * 2) <= self.size:\r\n mc = self.max_child(i) ## find max child\r\n if self.items[i] < self.items[mc]:\r\n tmp = self.items[i]\r\n self.items[i] = self.items[mc]\r\n self.items[mc] = tmp\r\n ...
[ "0.7993369", "0.7516703", "0.7435907", "0.7400076", "0.7334863", "0.7306124", "0.719238", "0.71682036", "0.710217", "0.70360464", "0.68641955", "0.6791557", "0.6775774", "0.66466707", "0.65461844", "0.653898", "0.64824", "0.64718825", "0.64513063", "0.6429633", "0.6399211", ...
0.71848524
7
Push item to its leaf in the tree and update sums.
def push(self, value): idx = self.__capacity - 1 + self.__size self.__tree[idx] = value self.__update(idx) self.__size += 1
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def add(self, item):\r\n self.root = self.recurse_add(self.root, item)", "def push(self, item): # 05:27 Lecture Week 2 \"Stacks\" (16:24)\n oldfirst = self.first # Save a link to the list\n self.first = self._Node(item, oldfirst) # first points to most recent Node\n self.N += 1", "def add(t...
[ "0.73173857", "0.66109264", "0.6454965", "0.6436707", "0.6278545", "0.6239465", "0.6177632", "0.6154286", "0.6113809", "0.6101891", "0.6088831", "0.60733277", "0.60294855", "0.59839755", "0.59787667", "0.597623", "0.59745806", "0.5972004", "0.596576", "0.5932941", "0.5916967"...
0.6273207
5
Updates the value of a leaf node and all the sums above it. Idx expected in the [0, capacity] range.
def update(self, idx, value): idx = self.__capacity - 1 + idx self.__tree[idx] = value self.__update(idx)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def update(\n self, index: Union[int, np.ndarray], value: Union[float, np.ndarray]\n ):\n\n tree_index = self.capacity + index\n self._tree[tree_index] = value\n\n # Propagate up the tree.\n parent = tree_index // 2\n while np.any(parent > 0):\n left = self._...
[ "0.74209356", "0.6767374", "0.6753369", "0.6640915", "0.62751794", "0.6238642", "0.61967045", "0.61868465", "0.618199", "0.6152516", "0.6152516", "0.6152516", "0.6084542", "0.5986752", "0.5953413", "0.5944968", "0.58795923", "0.581223", "0.5790687", "0.57693315", "0.57603663"...
0.74235
0
Returns the leaf in a given interval.
def get(self, subtree_sum): idx = 0 while True: # if idx is a leaf node return the idx and the value if idx >= self.__capacity - 1: return (idx - self.__capacity + 1, self.__tree[idx]) # else continue down left = 2 * idx + 1 right = 2 * idx + 2 left_sum = self.__tree[left] if left_sum >= subtree_sum: idx = left else: idx = right subtree_sum -= left_sum
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def interval(self):\n return Interval(self._ll_tree.get_left(), self._ll_tree.get_right())", "def get_leaves(self):\n raise NotImplementedError()", "def get_leaf(self, leaf_index):\n return self.__leaves_db.get(encode_int(leaf_index))", "def insert(self, interval):\n if self.root ...
[ "0.6567261", "0.6479266", "0.64509547", "0.64048004", "0.6272358", "0.59726596", "0.58964354", "0.58870226", "0.5835878", "0.58030605", "0.578581", "0.5713284", "0.5709979", "0.5675937", "0.56747264", "0.56653345", "0.5579153", "0.5558996", "0.54881215", "0.5477241", "0.54582...
0.0
-1
Return the sum of all elements in the tree.
def get_sum(self): return self.__tree[0]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def sum(self) -> int:\n return self.root.sum", "def sum_tree(t):\n \"*** YOUR CODE HERE ***\"\n if is_leaf(t):\n return entry(t)\n total = entry(t)\n for subtree in subtrees(t):\n total += sum_tree(subtree)\n return total", "def sum_of_tree(root_elem):\r\n\tif root_elem is N...
[ "0.8006212", "0.7781466", "0.77158576", "0.7709356", "0.7609589", "0.71323264", "0.7114631", "0.70373267", "0.7006873", "0.7004098", "0.68861806", "0.68853563", "0.68853563", "0.68846256", "0.688014", "0.6859513", "0.68298334", "0.6807194", "0.68041164", "0.6771166", "0.67473...
0.755793
5
Receives the idx of a leaf node and updates the sums on all the nodes above it based on its current value.
def __update(self, idx): parent = (idx - 1) // 2 while parent >= 0: left, right = 2 * parent + 1, 2 * parent + 2 self.__tree[parent] = self.__tree[left] + self.__tree[right] parent = (parent - 1) // 2
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def update(\n self, index: Union[int, np.ndarray], value: Union[float, np.ndarray]\n ):\n\n tree_index = self.capacity + index\n self._tree[tree_index] = value\n\n # Propagate up the tree.\n parent = tree_index // 2\n while np.any(parent > 0):\n left = self._...
[ "0.70218706", "0.6763772", "0.65720445", "0.6464258", "0.634624", "0.62440336", "0.62352777", "0.6203399", "0.6152715", "0.61511225", "0.61511225", "0.61511225", "0.61307853", "0.6130343", "0.6128592", "0.61171615", "0.6116346", "0.60709554", "0.60432565", "0.60112834", "0.59...
0.75952435
0
Given an arbitrary number of functions we create a pipeline where the output is piped between functions. you can also specify a tuple of arguments that should be passed to functions in the pipeline. The first arg is always the output of the previous function.
def PipeLine(*funcs, **kwargs): def wrapper(*data): if len(funcs) == 1: combinedArgs = data + kwargs.get(funcs[-1].__name__, tuple()) return funcs[-1](combinedArgs) else: combinedArgs = kwargs.get(funcs[-1].__name__, tuple()) if combinedArgs != (): del kwargs[funcs[-1].__name__] return funcs[-1](PipeLine(*funcs[:-1], **kwargs)(*data), *combinedArgs) return wrapper
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def pipe(*functions):\n\n return reduce(compose, functions, identity)", "def make_pipeline(steps):\n def compose2(f, g):\n return lambda x: g(f(x))\n return functools.reduce(compose2, steps)", "def tee_pipe(*funcs: Tuple[Callable[[GT], GS], ...]) -> Callable[[GT], GT]:\n\n piped = compose(*f...
[ "0.8024059", "0.7620117", "0.74363697", "0.7264736", "0.71780145", "0.6964314", "0.68261856", "0.67939293", "0.6666394", "0.6643853", "0.66330147", "0.66295445", "0.6628641", "0.6607316", "0.6598455", "0.6594299", "0.6561477", "0.6514276", "0.6458189", "0.64448345", "0.644368...
0.74768734
2
Given an arbitrary number of functions we create a pipeline where the output is piped between functions. You can also specify a tuple of arguments that should be passed to the functions in the pipeline. The first argument is always the output of the previous function. This version uses the reduce builtin instead of using recursion.
def ReducePipeline(*funcs, **kwargs): def accum(val, func): funcArgs = kwargs.get(func.__name__, tuple()) if hasattr(val, "__call__"): return func(val(), *funcArgs) else: return func(val, *funcArgs) def wrapper(*data): newFuncs = (partial(funcs[0], *data),) + funcs[1:] return reduce(accum, newFuncs) return wrapper
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def pipe(*functions):\n\n return reduce(compose, functions, identity)", "def make_pipeline(steps):\n def compose2(f, g):\n return lambda x: g(f(x))\n return functools.reduce(compose2, steps)", "def compose(*fns):\n return functools.reduce(lambda f,g: lambda x: f(g(x)), fns)", "def compose(...
[ "0.85493785", "0.79058933", "0.7589019", "0.75349104", "0.7516276", "0.7404753", "0.7371548", "0.7317679", "0.7314664", "0.7298046", "0.7296629", "0.7294338", "0.7245193", "0.719107", "0.71188146", "0.7108474", "0.710505", "0.7088272", "0.69122714", "0.6900706", "0.68673223",...
0.8107064
1
Calculates new observation vector for GridWorld.
def calculate_next_vector(vector, displacement, max_length): # recover vector to goal alpha = vector[0] * pi d = tan(alpha) col = max_length * vector[1] / sqrt(d ** 2 + 1) row = d * col if abs(alpha) > pi / 2: col = -col new_row = row - displacement[0] new_col = col - displacement[1] # get vector back again new_vec = np.zeros(2) new_vec[0] = atan(new_row / (new_col + 1e-12)) if new_col < 0 < new_row: new_vec[0] += pi elif (new_col < 0) and (new_row <= 0): new_vec[0] -= pi new_vec[0] /= pi new_vec[1] = sqrt(new_col ** 2 + new_row ** 2) / max_length return new_vec
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _update_loc(self) -> None:\n self.state[:, :, Boids.Attr.LOC] += self.state[:, :, Boids.Attr.VEL]\n # wrap-around the simulated environment\n self.state[:, :, Boids.Attr.LOC] %= np.expand_dims(self.env_bounds, axis=1)", "def compute_observation(self):\n robotPos, robotOrn = p.getB...
[ "0.6230598", "0.6210779", "0.6134541", "0.6021939", "0.5974683", "0.5839655", "0.58316547", "0.58069307", "0.57648754", "0.56969017", "0.56762373", "0.56254745", "0.5595447", "0.5594612", "0.55772495", "0.55599743", "0.5549346", "0.5541184", "0.5500111", "0.54753816", "0.5457...
0.0
-1
Check move possibility using observation window
def is_move_possible(obs_window, displacement): pos_row = obs_window.shape[0] // 2 pos_col = obs_window.shape[1] // 2 new_pos_row = pos_row + displacement[0] new_pos_col = pos_col + displacement[1] is_traversable = obs_window[new_pos_row, new_pos_col] == 0 is_shortcut = obs_window[new_pos_row, pos_col] or obs_window[pos_row, new_pos_col] return is_traversable and (not is_shortcut)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _ismoving(self):\n return self.dp.state()==PyTango.DevState.MOVING", "def move_window():\n\tif SLIDING_WINDOW:\n\t\t# get the chosen predicates\n\t\tpred = Predicate.objects.filter(pk__in=[p+1 for p in toggles.CHOSEN_PREDS])\n\n\t\t# handle window properties\n\t\tfor p in pred:\n\t\t\tp.move_window()"...
[ "0.6529597", "0.6286072", "0.6259327", "0.6203149", "0.6197683", "0.6197294", "0.6170365", "0.601616", "0.5998505", "0.5931079", "0.5923095", "0.5921639", "0.5878888", "0.5877249", "0.58698124", "0.585277", "0.5812267", "0.5797952", "0.5775176", "0.57483536", "0.5737459", "...
0.7049266
0
Returns the CPModule from within the loaded Python module m an imported module returns the CPModule class
def find_cpmodule(m): for v, val in list(m.__dict__.items()): if isinstance(val, type) and issubclass(val, cellprofiler_core.module.Module): return val raise ValueError( "Could not find cellprofiler_core.module.Module class in %s" % m.__file__ )
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _module(self):\n if self._module_cache is None:\n self._module_cache = load_module(self._name, self._path)\n return self._module_cache", "def base_module(self) -> nn.Module:\n return getattr(__import__(\"src.modules\", fromlist=[\"\"]), self.name)", "def get_module(self):\n ...
[ "0.6648748", "0.64653724", "0.64607435", "0.6405533", "0.63600814", "0.6347188", "0.63392264", "0.63091576", "0.625608", "0.6237327", "0.61681557", "0.6154078", "0.6154078", "0.6154078", "0.6154078", "0.6154078", "0.6122566", "0.6057319", "0.6050425", "0.6026159", "0.6026159"...
0.7351052
0
Encrypts data based on what the TPLink smartplug is expecting
def __encrypt(string: str) -> str: key = 171 result = b"\0\0\0" + chr(len(string)).encode('latin-1') for i in string.encode('latin-1'): a = key ^ i key = a result += chr(a).encode('latin-1') return result
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def encrypt_data(self, params):\n raise NotImplementedError", "def encrypt(data, key):\n data = six.ensure_binary(data)\n data = privy.hide(secret=data, password=key)\n data = six.ensure_text(data)\n return data", "def Encrypt(self, data):\n\n if len(data) % 16 != 0:\n data...
[ "0.7355738", "0.72868085", "0.7221197", "0.719316", "0.71014744", "0.70030105", "0.69509864", "0.69267815", "0.68219936", "0.6818995", "0.6817378", "0.67560524", "0.67371756", "0.6733585", "0.6675217", "0.6667538", "0.654713", "0.65417606", "0.65303856", "0.65274465", "0.6526...
0.0
-1
Decrypts data based on what the TPLink smartplug is using
def __decrypt(string: str) -> str: key = 171 result = "" i: int for i in string: a = key ^ i key = i result += chr(a) return result
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def decrypt(self, data):", "def decrypt_data(self, encrypted_data):\n raise NotImplementedError", "def decrypt_data ( aes_key, data ) :\n decoded_data = decode_data( data )\n salt = decoded_data[ 0 : Crypto.Cipher.AES.block_size ]\n encrypted_data = decoded_data[ Crypto.Cipher.AES.block_size : ]\n...
[ "0.8398597", "0.7666521", "0.76633376", "0.7455099", "0.74344987", "0.73562866", "0.73562866", "0.73559135", "0.7330574", "0.7323575", "0.7264788", "0.7229528", "0.7145882", "0.71009696", "0.6988444", "0.69679904", "0.6960979", "0.6948455", "0.6828047", "0.6825578", "0.682328...
0.0
-1
Performs any TPLink smartplug supported command. See the commands dictionary
def perform_command(self, cmd: str) -> dict: sock_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock_tcp.connect((self.ip, self.port)) sock_tcp.send(self.__encrypt(cmd)) data = sock_tcp.recv(2048) sock_tcp.close() data = self.__decrypt(data[4:]) if not data: raise ConnectionError("Error: Could not communicate to the smart plug") return json.loads(data)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def commands():", "def commands():\n pass", "def commands():\n pass", "def commands():\n pass", "def commands():\n pass", "def silkscreen_commands(self, commands):\n self.pcb_layers[\"silkscreen\"].commands = commands", "def execCommand(self, command, opts):\n if command == \"atta...
[ "0.62071913", "0.6122376", "0.6122376", "0.6122376", "0.6122376", "0.6035483", "0.59634626", "0.5925076", "0.59209687", "0.58657867", "0.57914144", "0.57778853", "0.5737286", "0.5727475", "0.5710332", "0.5668034", "0.5654879", "0.56148833", "0.55979323", "0.55908215", "0.5581...
0.0
-1
Turns the TPLink smartplug on or off depending on the state
def set_state(self, is_on: bool) -> None: json_data = self.perform_command(self.commands["on"] if is_on else self.commands["off"]) if json_data["system"]["set_relay_state"]["err_code"] != 0: raise Exception("Error: Error from the smartplug: " + json.dumps(json_data))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def turn_on(self, **kwargs):\n self.smartplug.turn_on()", "def turn_on(self, **kwargs):\n self._state = True\n if(self._device['type'] == '_DT-PLUG' or self._device['type'] == '_THIMR'):\n self._send_cmd(self._device,'cmd=ctrl&devices={[' + self._device[\"sid\"] + ']}&op={\"cmd\":...
[ "0.7354772", "0.6991087", "0.68995047", "0.6771655", "0.645624", "0.639057", "0.6386869", "0.63163376", "0.6220862", "0.6093367", "0.60827076", "0.5999483", "0.5967314", "0.5949829", "0.59453136", "0.593405", "0.59292585", "0.5903088", "0.5894138", "0.58599454", "0.583519", ...
0.58260435
21
default values of parameters from Ciresan et al.
def rotate_scale(X, min_angle=-15, max_angle=15, min_scale=0.85, max_scale=1.15, random_state=None, n_jobs=1): if random_state is None: rng = np.random else: rng = np.random.RandomState(random_state) angles = rng.uniform(min_angle, max_angle, size=X.shape[0]) scales = rng.uniform(min_scale, max_scale, size=X.shape[0]) X_rot = Parallel(n_jobs=n_jobs)(delayed(rotate_scale_one)(X[i], angles[i], scales[i]) for i in range(X.shape[0])) return np.array(X_rot, dtype='float32')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def set_default_parameters(self):\n super().set_default_parameters()", "def default_params():\n params = {}\n params['dataset'] = 'adult'\n params['engines'] = ['MD','RDA']\n params['iters'] = 10000\n params['epsilon'] = 1.0\n params['delta'] = 0.0\n params['bounded'] = True\n para...
[ "0.77844316", "0.74832076", "0.7425697", "0.74207234", "0.7282676", "0.72558606", "0.7254189", "0.72380584", "0.72216916", "0.7146505", "0.71138066", "0.7112786", "0.70974725", "0.7068888", "0.70080286", "0.70061696", "0.69936126", "0.698711", "0.69810283", "0.6930297", "0.69...
0.0
-1
default values of parameters from Ciresan et al.
def elastic_transform(X, min_alpha=36, max_alpha=38, min_sigma=5, max_sigma=6, random_state=None, n_jobs=1): if random_state is None: rng = np.random else: rng = np.random.RandomState(random_state) alphas = rng.uniform(min_alpha, max_alpha, size=X.shape[0]) sigmas = rng.uniform(min_sigma, max_sigma, size=X.shape[0]) X_elas = Parallel(n_jobs=n_jobs)(delayed(elastic_transform_one)(X[i], alphas[i], sigmas[i]) for i in range(X.shape[0])) return np.array(X_elas, dtype='float32')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def set_default_parameters(self):\n super().set_default_parameters()", "def default_params():\n params = {}\n params['dataset'] = 'adult'\n params['engines'] = ['MD','RDA']\n params['iters'] = 10000\n params['epsilon'] = 1.0\n params['delta'] = 0.0\n params['bounded'] = True\n para...
[ "0.77844316", "0.74832076", "0.7425697", "0.74207234", "0.7282676", "0.72558606", "0.7254189", "0.72380584", "0.72216916", "0.7146505", "0.71138066", "0.7112786", "0.70974725", "0.7068888", "0.70080286", "0.70061696", "0.69936126", "0.698711", "0.69810283", "0.6930297", "0.69...
0.0
-1
Elastic deformation of images as described in [Simard2003]_. .. [Simard2003] Simard, Steinkraus and Platt, "Best Practices for Convolutional Neural Networks applied to Visual Document Analysis", in Proc. of the International Conference on Document Analysis and Recognition, 2003.
def elastic_transform_one(image, alpha, sigma, random_state=None): if random_state is None: random_state = np.random.randint(0, 999999) rng = np.random.RandomState(random_state) shape = image.shape dx = gaussian_filter((rng.rand(*shape) * 2 - 1), sigma, mode="constant", cval=0) * alpha dy = gaussian_filter((rng.rand(*shape) * 2 - 1), sigma, mode="constant", cval=0) * alpha x, y = np.meshgrid(np.arange(shape[0]), np.arange(shape[1])) indices = np.reshape(y+dy, (-1, 1)), np.reshape(x+dx, (-1, 1)) return map_coordinates(image, indices, order=1).reshape(shape)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_random_elastic_deformation(dummy_input):\n # Test the 2D image: H, W, C\n image, label = dummy_input(image_size=(512, 512, 3),\n label_size=(512, 512, 1))\n transform = RandomElasticDeformation()\n _image, _label = transform(image, label, elastic_deformation_order...
[ "0.68137693", "0.6105213", "0.58586067", "0.5774048", "0.5770297", "0.57465637", "0.5704582", "0.5688945", "0.56770426", "0.5661012", "0.5661012", "0.56132793", "0.5603475", "0.5600591", "0.55894667", "0.5575768", "0.5571582", "0.5547392", "0.55281556", "0.5469116", "0.545669...
0.5255144
43
CPU mnist test for TF Training Instance Type c5.4xlarge Given above parameters, registers a task with family named after this test, runs the task, and waits for the task to be stopped before doing teardown operations of instance and cluster.
def test_ecs_tensorflow_training_mnist_cpu(cpu_only, ecs_container_instance, tensorflow_training, training_cmd, ecs_cluster_name): instance_id, cluster_arn = ecs_container_instance ecs_utils.ecs_training_test_executor(ecs_cluster_name, cluster_arn, training_cmd, tensorflow_training, instance_id)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_mnist():\n env = os.environ.copy()\n if not \"CUDA_VISIBLE_DEVICES\" in env:\n env[\"CUDA_VISIBLE_DEVICES\"] = \"\"\n subprocess.run(\n \"edflow -b template_tfe/config.yaml -t --max_batcher_per_epoch --num_epochs 1\",\n shell=True,\n check=True,\n env=env,\n ...
[ "0.67484915", "0.63618076", "0.60620654", "0.5980725", "0.5914939", "0.59113973", "0.59051156", "0.58966136", "0.5866718", "0.58654135", "0.5864061", "0.58606243", "0.5860597", "0.58368456", "0.58136004", "0.5806316", "0.57960474", "0.5792729", "0.57621115", "0.5742489", "0.5...
0.6672013
1
GPU mnist test for TF Training Instance Type p3.2xlarge Given above parameters, registers a task with family named after this test, runs the task, and waits for the task to be stopped before doing teardown operations of instance and cluster.
def test_ecs_tensorflow_training_mnist_gpu(gpu_only, ecs_container_instance, tensorflow_training, training_cmd, ecs_cluster_name): instance_id, cluster_arn = ecs_container_instance num_gpus = ec2_utils.get_instance_num_gpus(instance_id) ecs_utils.ecs_training_test_executor(ecs_cluster_name, cluster_arn, training_cmd, tensorflow_training, instance_id, num_gpus=num_gpus)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_mnist():\n env = os.environ.copy()\n if not \"CUDA_VISIBLE_DEVICES\" in env:\n env[\"CUDA_VISIBLE_DEVICES\"] = \"\"\n subprocess.run(\n \"edflow -b template_tfe/config.yaml -t --max_batcher_per_epoch --num_epochs 1\",\n shell=True,\n check=True,\n env=env,\n ...
[ "0.6628726", "0.6221861", "0.6108858", "0.6095782", "0.60324526", "0.60173756", "0.6013705", "0.60083187", "0.59039736", "0.58947945", "0.58934516", "0.5819561", "0.5818858", "0.5764458", "0.5733247", "0.5716348", "0.57152057", "0.5713483", "0.5712434", "0.569594", "0.5687781...
0.6573886
1
GPU Faster RCNN test for TF Training Instance Type g3.8xlarge Given above parameters, registers a task with family named after this test, runs the task, and waits for the task to be stopped before doing teardown operations of instance and cluster.
def test_ecs_tensorflow_training_fasterrcnn_gpu(gpu_only, ecs_container_instance, tensorflow_training, training_cmd, ecs_cluster_name): instance_id, cluster_arn = ecs_container_instance num_gpus = ec2_utils.get_instance_num_gpus(instance_id) ecs_utils.ecs_training_test_executor(ecs_cluster_name, cluster_arn, training_cmd, tensorflow_training, instance_id, num_gpus=num_gpus)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def do_testing(gpu=0):\n # expected environment variables\n os.environ[\"BERT_BASE_DIR\"] = \"pretrained/cased_L-12_H-768_A-12\"\n os.environ[\"DATA_DIR\"] = \"dataset\"\n os.environ[\"OUTPUT_DIR\"] = \"output\"\n assert os.environ.get(\"BERT_BASE_DIR\") is not None\n assert os.environ.get(\"DATA...
[ "0.63982433", "0.63317746", "0.6286564", "0.62145746", "0.6099212", "0.6017336", "0.59935385", "0.5987405", "0.59732693", "0.5968696", "0.59411806", "0.58942217", "0.58580977", "0.58526134", "0.5831714", "0.58247334", "0.5802177", "0.57978106", "0.5790498", "0.5788643", "0.57...
0.6722839
0
Takes a results list and puts it in a pandas dataframe together with other relevant variables (runs, generations, and language class)
def language_stats_to_dataframe(results, n_runs, n_gens, possible_form_lengths): if len(possible_form_lengths) == 1: n_language_classes = 4 else: n_language_classes = 7 #TODO: or should this be 6 (i.e. collapsing the two different reduplication strategies?) column_proportion = np.array(results) if n_language_classes == 4 and column_proportion.shape[2] > n_language_classes: column_proportion_compositional_summed = np.zeros((n_runs, n_gens, n_language_classes)) for r in range(len(column_proportion_compositional_summed)): for g in range(len(column_proportion_compositional_summed[0])): column_proportion_compositional_summed[r][g] = np.array([column_proportion[r][g][0], column_proportion[r][g][1], column_proportion[r][g][2]+column_proportion[r][g][3], column_proportion[r][g][4]]) column_proportion = column_proportion_compositional_summed.flatten() else: column_proportion = column_proportion.flatten() column_runs = [] for i in range(n_runs): for j in range(n_gens): for k in range(n_language_classes): column_runs.append(i) column_runs = np.array(column_runs) column_generation = [] for i in range(n_runs): for j in range(n_gens): for k in range(n_language_classes): column_generation.append(j) column_generation = np.array(column_generation) column_type = [] for i in range(n_runs): for j in range(n_gens): if len(possible_form_lengths) == 1: column_type.append('degenerate') column_type.append('holistic') column_type.append('compositional') column_type.append('other') else: column_type.append('degenerate') column_type.append('holistic') column_type.append('holistic_diversify_signal') column_type.append('compositional') column_type.append('compositional_reduplicate_segments') column_type.append('compositional_reduplicate_whole_signal') column_type.append('other') data = {'run': column_runs, 'generation': column_generation, 'proportion': column_proportion, 'class': column_type} lang_class_prop_over_gen_df = pd.DataFrame(data) return lang_class_prop_over_gen_df
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def create_dataframe(result):\n # List of elements in the search result\n names = []\n snippet = []\n url = []\n \n # Append search results to list\n for j,item in enumerate(result):\n for i,element in enumerate(result[j]['items']):\n names.append(result[j]['items'][i]['title...
[ "0.72283614", "0.71309644", "0.6913391", "0.6884854", "0.6688005", "0.65761745", "0.6487272", "0.6475751", "0.6433946", "0.632648", "0.6261752", "0.6226283", "0.6154", "0.6113945", "0.610395", "0.6074205", "0.6056309", "0.60420865", "0.6016165", "0.5957813", "0.59397256", "...
0.73413634
0
Takes a pandas dataframe of results and turns it back into a simple results array, which only contains the populations' posterior probability distributions over generations.
def dataframe_to_language_stats(dataframe, n_runs, n_batches, n_gens, possible_form_lengths): if len(possible_form_lengths) == 1: n_language_classes = 4 else: n_language_classes = 7 #TODO: or should this be 6 (i.e. collapsing the two different reduplication strategies?) proportion_column = np.array(dataframe['proportion']) proportion_column_as_results = proportion_column.reshape((n_runs*n_batches, n_gens, n_language_classes)) return proportion_column_as_results
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def pandas(self):\n names,prior,posterior = [],[],[]\n for iname,name in enumerate(self.posterior_parameter.row_names):\n names.append(name)\n posterior.append(np.sqrt(float(\n self.posterior_parameter[iname, iname]. x)))\n iprior = self.parcov.row_name...
[ "0.6117095", "0.58314747", "0.58246684", "0.5775569", "0.5740103", "0.562746", "0.5493443", "0.5482421", "0.5470787", "0.5464433", "0.54462564", "0.5428806", "0.54074293", "0.5386283", "0.5379246", "0.5360976", "0.53533596", "0.53266215", "0.5307653", "0.5297774", "0.5293929"...
0.51801986
34
Takes a pandas dataframe which contains the proportions of language classes over generations and plots timecourses
def plot_timecourse_language_types(lang_class_prop_over_gen_df, title, file_path, file_name): sns.set_style("darkgrid") sns.set_context("talk") fig, ax = plt.subplots() if len(possible_form_lengths) == 1: palette = sns.color_palette(["black", "red", "green", "grey"]) else: palette = sns.color_palette(["black", sns.color_palette("colorblind")[3], sns.color_palette("colorblind")[1], sns.color_palette("colorblind")[2], sns.color_palette("colorblind")[9], sns.color_palette("colorblind")[0], sns.color_palette("colorblind")[7]]) sns.lineplot(x="generation", y="proportion", hue="class", data=lang_class_prop_over_gen_df, palette=palette) # sns.lineplot(x="generation", y="proportion", hue="class", data=lang_class_prop_over_gen_df, palette=palette, ci=95, err_style="bars") plt.tick_params(axis='both', which='major', labelsize=18) plt.tick_params(axis='both', which='minor', labelsize=18) plt.ylim(-0.05, 1.05) plt.title(title, fontsize=22) plt.xlabel('Generation', fontsize=20) plt.ylabel('Mean proportion', fontsize=20) handles, labels = ax.get_legend_handles_labels() labels = ['D', 'H', 'H+Div.', 'C', 'C+Red.-part', 'C+Red.-whole', 'O'] # ax.legend(handles=handles[1:], labels=labels[1:]) ax.legend(handles=handles, labels=labels) plt.tight_layout() plt.savefig(file_path + "Timecourse_plot_lang_types_" + file_name + ".png") plt.show()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def plot_word_class_pr_genre(df):\n df['nouns'] = df['nouns'] * 100\n df['verbs'] = df['verbs'] * 100\n df['adverbs'] = df['adverbs'] * 100\n # plotting nouns\n plotting_helper_method('nouns', 'genre', df)\n plt.title('Amount of nouns pr song pr. genre')\n plt.xlabel(\"Amount of nouns in each ...
[ "0.6448972", "0.6392558", "0.6383187", "0.6325968", "0.58468354", "0.5693776", "0.5645798", "0.5629048", "0.5622483", "0.5611402", "0.55704165", "0.5545969", "0.54707754", "0.5421868", "0.541172", "0.5408939", "0.53972", "0.5382327", "0.5376701", "0.5373505", "0.5348653", "...
0.66838074
0
Takes a pandas dataframe which contains the proportions of language classes over generations and generates a barplot (excluding the burnin period)
def plot_barplot_language_types(lang_class_prop_over_gen_df, title, file_path, file_name, n_runs, n_batches, n_gens, gen_start, lang_class_baselines_all, lang_class_baselines_fully_expressive, possible_form_lengths): sns.set_style("darkgrid") sns.set_context("talk") if len(possible_form_lengths) == 1: n_language_classes = 4 else: n_language_classes = 7 #TODO: or should this be 6 (i.e. collapsing the two different reduplication strategies?) proportion_column_as_results = dataframe_to_language_stats(lang_class_prop_over_gen_df, n_runs, n_batches, n_gens, possible_form_lengths) proportion_column_from_start_gen = proportion_column_as_results[:, gen_start:] proportion_column_from_start_gen = proportion_column_from_start_gen.flatten() runs_column_from_start_gen = [] for i in range(n_runs*n_batches): for j in range(gen_start, n_gens): for k in range(n_language_classes): runs_column_from_start_gen.append(i) runs_column_from_start_gen = np.array(runs_column_from_start_gen) generation_column_from_start_gen = [] for i in range(n_runs*n_batches): for j in range(gen_start, n_gens): for k in range(n_language_classes): generation_column_from_start_gen.append(j) generation_column_from_start_gen = np.array(generation_column_from_start_gen) class_column_from_start_gen = [] for i in range(n_runs*n_batches): for j in range(gen_start, n_gens): if n_language_classes == 4: class_column_from_start_gen.append('degenerate') class_column_from_start_gen.append('holistic') class_column_from_start_gen.append('compositional') class_column_from_start_gen.append('other') elif n_language_classes == 7: class_column_from_start_gen.append('D') class_column_from_start_gen.append('H') class_column_from_start_gen.append('H+Div.') class_column_from_start_gen.append('C') class_column_from_start_gen.append('C+Red.-part') class_column_from_start_gen.append('C+Red.-whole') class_column_from_start_gen.append('O') new_data_dict = {'run': runs_column_from_start_gen, 'generation': generation_column_from_start_gen, 'proportion': proportion_column_from_start_gen, 'class': class_column_from_start_gen} lang_class_prop_over_gen_df_from_starting_gen = pd.DataFrame(new_data_dict) if len(possible_form_lengths) == 1: palette = sns.color_palette(["black", "red", "green", "grey"]) else: palette = sns.color_palette(["black", sns.color_palette("colorblind")[3], sns.color_palette("colorblind")[1], sns.color_palette("colorblind")[2], sns.color_palette("colorblind")[9], sns.color_palette("colorblind")[0], sns.color_palette("colorblind")[7]]) sns.barplot(x="class", y="proportion", data=lang_class_prop_over_gen_df_from_starting_gen, palette=palette) # plt.axhline(y=lang_class_baselines_all[0], xmin=0.0, xmax=0.25, color='k', linestyle='--', linewidth=2) # plt.axhline(y=lang_class_baselines_all[1], xmin=0.25, xmax=0.5, color='k', linestyle='--', linewidth=2) # plt.axhline(y=lang_class_baselines_all[2], xmin=0.5, xmax=0.75, color='k', linestyle='--', linewidth=2) # plt.axhline(y=lang_class_baselines_all[3], xmin=0.75, xmax=1.0, color='k', linestyle='--', linewidth=2) # # if title == 'Mutual Understanding Only' or title == 'Minimal Effort & Mutual Understanding': # plt.axhline(y=lang_class_baselines_fully_expressive[0], xmin=0.25, xmax=0.5, color='0.6', linestyle='--', linewidth=2) # plt.axhline(y=lang_class_baselines_fully_expressive[1], xmin=0.5, xmax=0.75, color='0.6', linestyle='--', linewidth=2) plt.tick_params(axis='both', which='major', labelsize=18) plt.tick_params(axis='both', which='minor', labelsize=18) plt.ylim(-0.05, 1.05) plt.title(title, fontsize=22) # plt.xlabel('Language class') plt.xlabel('', fontsize=20) plt.ylabel('Mean proportion', fontsize=20) plt.tight_layout() if holistic_without_partial_meaning is True: plt.savefig(file_path + "Barplot_lang_types_" + file_name + "_burn_in_" + str(gen_start) + ".png") else: plt.savefig(file_path + "Barplot_lang_types_" + file_name + "_burn_in_" + str(gen_start) + "_NEW.png") plt.show()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def bar_plot(df_NP):\n cnt = Counter()\n for tax_list in df_NP.taxonomy:\n for tax in list(tax_list):\n if tax != 'no':\n cnt[tax] += 1\n plt.bar(cnt.keys(),cnt.values())\n plt.xlabel('taxonomic provenance')\n plt.ylabel('number of molecules')\n plt.title('number ...
[ "0.6668762", "0.6598685", "0.6580668", "0.65461254", "0.6532494", "0.6513617", "0.6504175", "0.6385042", "0.63797927", "0.63521934", "0.6340164", "0.63299674", "0.619069", "0.61589485", "0.6137865", "0.6120342", "0.607238", "0.6047123", "0.60318536", "0.59974545", "0.5966363"...
0.6864728
0
Takes a pandas dataframe which contains the proportions of language classes over generations and plots timecourses
def plot_timecourse_repair_counts(repair_counts_over_gen_df, title, file_path, file_name): sns.set_style("darkgrid") sns.set_context("talk") fig, ax = plt.subplots() palette = sns.color_palette("colorblind") sns.lineplot(x="generation", y="independent_repair_proportion", data=repair_counts_over_gen_df, palette=palette) # sns.lineplot(x="generation", y="proportion", hue="class", data=lang_class_prop_over_gen_df, palette=palette, ci=95, err_style="bars") plt.tick_params(axis='both', which='major', labelsize=18) plt.tick_params(axis='both', which='minor', labelsize=18) plt.ylim(-0.05, 1.05) plt.title(title, fontsize=22) plt.xlabel('Generation', fontsize=20) plt.ylabel('Mean proportion', fontsize=20) # handles, labels = ax.get_legend_handles_labels() # # labels = ['D', 'H', 'H+Div.', 'C', 'C+Red.-part', 'C+Red.-whole', 'O'] # # ax.legend(handles=handles[1:], labels=labels[1:]) # ax.legend(handles=handles, labels=labels) plt.tight_layout() plt.savefig(file_path + "Timecourse_plot_repairs_" + file_name + ".png") plt.show()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def plot_timecourse_language_types(lang_class_prop_over_gen_df, title, file_path, file_name):\n sns.set_style(\"darkgrid\")\n sns.set_context(\"talk\")\n\n fig, ax = plt.subplots()\n\n if len(possible_form_lengths) == 1:\n palette = sns.color_palette([\"black\", \"red\", \"green\", \"grey\"])\n ...
[ "0.66838074", "0.6448972", "0.6392558", "0.6383187", "0.6325968", "0.58468354", "0.5693776", "0.5645798", "0.5629048", "0.5611402", "0.55704165", "0.5545969", "0.54707754", "0.5421868", "0.541172", "0.5408939", "0.53972", "0.5382327", "0.5376701", "0.5373505", "0.5348653", ...
0.5622483
9
Initialize a new HTTP client event router object uri is a URI for this event router. A new URI derived from this is created for the HTTP client event relay. host is the IP address of host name to which the HTTP connection is made. port is the TCP port number to which the HTTP connection is made.
def __init__(self, uri=None, host='', port=8082, simplex=False): super(EventRouterHTTPC, self).__init__(uri) relayuri = self.getUri()+"/HTTPC" self._relay = EventRelayHTTPC(self, relayuri, host, port, simplex) return
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __init__(self, router, uri=None, host='', port=8082, simplex=False):\n super(EventRelayHTTPC, self).__init__(uri)\n self._router = router\n self._queue = Queue()\n self._event = threading.Event()\n self._closing = False\n self._queueEvent = threading.Event()\n ...
[ "0.74562943", "0.6506829", "0.63234913", "0.63234913", "0.63085514", "0.621488", "0.60746145", "0.6005634", "0.59841245", "0.5979701", "0.5968453", "0.5921957", "0.5919456", "0.58944875", "0.58941567", "0.5850365", "0.58042604", "0.5793125", "0.5780519", "0.5780519", "0.57790...
0.7386842
1
Function called to close down event router.
def close(self): self._relay.close() super(EventRouterHTTPC, self).close() return
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def closeEvent(self, event):\n\n sys.exit()", "def on_closing_event(self):\n self.exit_event(None)", "def closeEvent(self, event):\n sys.exit(0)", "def close(self) -> None:\n self.relay(\"close\")()", "def closeEvent(self, event):\n self.exit()\n event.accept()", ...
[ "0.71471226", "0.71452016", "0.70188725", "0.7006168", "0.6977439", "0.6927479", "0.68837065", "0.6871763", "0.68616617", "0.68096364", "0.6793978", "0.6784437", "0.67712516", "0.6754609", "0.6701007", "0.6697934", "0.6681519", "0.6672537", "0.6667044", "0.66509724", "0.66509...
0.73405606
0
Initialize a new HTTP client event passing object An HTTP client is associated with an existing event router, and sends all messages received from that router to the HTTP connection, and forwards all messages received from the HTTP connection to the router. Interaction with the indicated EventRouter object takes place primarily through the 'receive' methods of this class and the supplied router. Because messages received from HTTP are sent onwards using the normal forwarding mechanisms, this class must perform loopdetection to stop events being bounced back to the HTTP connection.
def __init__(self, router, uri=None, host='', port=8082, simplex=False): super(EventRelayHTTPC, self).__init__(uri) self._router = router self._queue = Queue() self._event = threading.Event() self._closing = False self._queueEvent = threading.Event() self._simplex = simplex # Have 'router' send all subscriptions events to this object router.routeEventFrom(None, None, self) router.doSubscribeRequest(self, -1, None, None) # Create HTTP "connection", and start thread to respond to new events from it. self._httpcon = httplib.HTTPConnection(host=host, port=port) self._thread = threading.Thread(name=uri, target=self.processEvent) self._thread.start() return
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __init__(self, uri=None, host='', port=8082, simplex=False):\n super(EventRouterHTTPC, self).__init__(uri)\n relayuri = self.getUri()+\"/HTTPC\"\n self._relay = EventRelayHTTPC(self, relayuri, host, port, simplex)\n return", "def __init__(self, router):\n self._router = ro...
[ "0.61509657", "0.5864122", "0.57680523", "0.5765937", "0.5636957", "0.542871", "0.53911084", "0.5345458", "0.52738434", "0.52246845", "0.517456", "0.51684", "0.51025426", "0.5091683", "0.50771654", "0.5053803", "0.50480044", "0.50263023", "0.501474", "0.49918574", "0.49689016...
0.74102676
0
This function receives messages from the associated router and queues them for transmission on the HTTP interface.
def receive(self, fromrouter, envelope): event = envelope.unWrap(self.getUri()) if event: Trace("%s receive %s from %s"%(self.getUri(),event,fromrouter), "EventLib.EventRelayHTTPC") return self.queueItem(["forward",envelope]) return makeDeferred(StatusVal.OK)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def recv_messages(self):\n while True:\n b = unwrap_read(self.sock.recv(4096))\n msgs = self.parser.feed(b)\n if msgs:\n for msg in msgs:\n self.router.incoming(msg)\n return", "def __process_requests(self):\n\t\tfor receive...
[ "0.69763803", "0.63376343", "0.6313037", "0.62614304", "0.62203604", "0.6201189", "0.6163866", "0.61292046", "0.6127975", "0.60782707", "0.60757583", "0.6066614", "0.6057568", "0.6052637", "0.6049549", "0.6036926", "0.60339874", "0.60330033", "0.60038686", "0.5997388", "0.597...
0.55585676
92
Shut down the event router thread
def close(self): Trace("%s close"%(self.getUri()), "EventLib.EventRelayHTTPC") self._httpcon.close() self._closing = True self._event.set() self._queueEvent.set() self._queue.put(["closedown",[]]) self._thread.join() Trace("%s closed"%(self.getUri()), "EventLib.EventRelayHTTPC") return
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def shutdown(self):\n self.socket_thread.stop()", "def shutdown(self):\n if not self.stop_event.is_set():\n self.stop_event.set()\n\n if self.pusher_thread:\n self.pusher_thread.join()", "def __del__(self):\n AppHelper.stopEventLoop()", "def __del__(self)...
[ "0.73733056", "0.7205434", "0.7066241", "0.7066241", "0.68949795", "0.6849437", "0.6786754", "0.6766629", "0.67512125", "0.6745822", "0.6738774", "0.67175186", "0.6715772", "0.6702667", "0.669924", "0.66910434", "0.6680487", "0.66720706", "0.66561806", "0.66561806", "0.664059...
0.0
-1
Add item to the queue, and return a deferred object that fires when an item is removed (or the queue is empty).
def queueItem(self, item): Trace("%s queueItem (%s)"%(self.getUri(),item), "EventLib.EventRelayHTTPC") if not self._closing: self._queue.put(item) self._queueEvent.set() return makeQueueDeferred(StatusVal.OK, self._queue, self._event) return makeDeferred(StatusVal.OK)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def add(self, item):\n completeDeferred = defer.Deferred()\n self.queue.append((item, completeDeferred))", "def add(self, item: T) -> None:\n self._queue.append(item)\n if not self.is_empty():\n self._queue.sort(reverse=True)", "def enqueue(self, item):\n self.queu...
[ "0.809805", "0.66659725", "0.6658853", "0.6658853", "0.649351", "0.6432891", "0.6412939", "0.6350026", "0.6251586", "0.623737", "0.6233821", "0.6162664", "0.6149751", "0.6137725", "0.6091136", "0.60882497", "0.60764444", "0.6054781", "0.5985582", "0.5985582", "0.598518", "0...
0.6929844
1
Wait for an item to be queued, then return it.
def getQueuedItem(self): Trace("%s getQueuedItem ..."%(self.getUri()), context="EventLib.EventRelayHTTPC") item = self._queue.get() Trace("%s getQueuedItem (%s)"%(self.getUri(),item), context="EventLib.EventRelayHTTPC") self._event.set() return item
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_item_from_queue(Q, timeout=0.01):\n try:\n item = Q.get(True, 0.01)\n except queue.Empty:\n return None\n return item", "def get_item_from_queue(Q, timeout=0.01):\n try:\n item = Q.get(True, 0.01)\n except Queue.Empty:\n return None\n return item", "def wor...
[ "0.69198966", "0.69057333", "0.6884813", "0.6864645", "0.68376034", "0.6821141", "0.6660425", "0.6638609", "0.65500504", "0.6460967", "0.6446401", "0.63761413", "0.63736504", "0.6362188", "0.6324351", "0.62841207", "0.6243727", "0.61811554", "0.6120136", "0.61119175", "0.6085...
0.734153
0
This function is the HTTP client worker thread.
def processEvent(self): # Note: break out of event dispatch loop when closedown event is received # and closing flag is set. This is to prevent DoS attack by faked closedown # event type, and to ensure that prior events received are all processed. delay_on_error_min = 0.125 # Back off retry interval on error.. delay_on_error_max = 20.0 # .. delay_on_error = delay_on_error_min # .. while True: if delay_on_error < delay_on_error_max: delay_on_error *= 2 try: # PLEASE NOTE: In the event that the HTTPC is run as duplex, not simplex # then the post methods will be delayed if nothing is sent down to the client # from the server. This timeout is controlled by QUEUE_WAIT_TIMEOUT in EventRouterHTTPS.py if self._simplex == True: self._queueEvent.wait() self._queueEvent.clear() if not self._queue.empty(): Trace("%s queue.get ..."%(self.getUri()), "EventLib.EventRelayHTTPC") ###msgbody = self._queue.get() ###Trace("%s get msgbody: %s"%(self.getUri(),msgbody), "EventLib.EventRelayHTTPC") ###self._event.set() msgbody = self.getQueuedItem() [typ,env] = msgbody if typ == "closedown": if self._closing: break else: # process request as an HTTP POST request data = makeEnvelopeData(env) headers = { "Content-type": "text/plain", "Accept": "text/plain", "Content-length": str(len(data)) } self._httpcon.request("POST", "/request_path_ignored", data, headers) response = self._httpcon.getresponse() delay_on_error = delay_on_error_min elif self._simplex == False: # Nothing in queue: # issue a GET for incoming events _log.info("%s HTTP get ..."%(self.getUri())) headers = { "Accept": "text/plain" } self._httpcon.request("GET", "/request_path_ignored", None, headers) response = self._httpcon.getresponse() if response.status == 200: delay_on_error = delay_on_error_min msgbody = response.read() Trace("%s get msgbody: %s"%(self.getUri(),msgbody), "EventLib.EventRelayHTTPC") # Parse message and act accordingly msgdata = parseMessageData(msgbody) Trace("%s get msgdata: %s"%(self.getUri(),str(msgdata)), "EventLib.EventRelayHTTPC") if msgdata == None: #TODO: Log "Request body malformed" pass elif msgdata[0] == "forward": # msgdata = ["forward", [['R1', 'R2', 'R3'], 'ev:typ', 'ev:src', 'payload']] event = makeEvent(evtype=msgdata[1][1],source=msgdata[1][2],payload=msgdata[1][3]) env = constructEnvelope(msgdata[1][0], event) self.forward(event, env) elif msgdata[0] == "idle": # Idle response gives client a chance to send if anything is queued pass else: #TODO: handle closedown message? Warn( "%s Request body unrecognized option: %s"%(self.getUri(),msgdata[0]), "EventRelayHTTPC") pass elif response.status == 503: Trace( "%s processEvent error response: %u, %s"%(self.getUri(),response.status,response.reason), "EventLib.EventRelayHTTPC") # Remote end closed down break else: # TODO: (log error response) Warn( "%s processEvent error response: %u, %s"%(self.getUri(),response.status,response.reason), "EventLib.EventRelayHTTPC") time.sleep(delay_on_error) except httplib.BadStatusLine, e: # This can happen at closedown Info( "%s processEvent bad response: %s"%(self.getUri(), str(e)), "EventLib.EventRelayHTTPC") time.sleep(delay_on_error) except httplib.CannotSendRequest, e: # This can happen at closedown Info( "%s Cannot send request: %s"%(self.getUri(), str(e)), "EventLib.EventRelayHTTPC") time.sleep(delay_on_error) except httplib.ResponseNotReady, e: # This can happen at startup and sometimes other times: # maybe multiple requests on a single HTTP connection object? Info( "%s Response not ready: (%s)"%(self.getUri(), str(e)), "EventLib.EventRelayHTTPC") time.sleep(delay_on_error) except socket.error, e: Warn( "%s Socket error: %s"%(self.getUri(), str(e)), "EventLib.EventRelayHTTPC") time.sleep(delay_on_error) return
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __manage_client_thread(self, conn_socket: socket.socket, address: tuple):\n print(\"[THREAD] new thread started for client\")\n connected = True\n\n while connected:\n request_header = HttpServer.get_request_header(conn_socket)\n split_request_header = request_header....
[ "0.6994863", "0.68837047", "0.6724171", "0.65650207", "0.6561778", "0.64669704", "0.63919336", "0.63876474", "0.63811946", "0.63524044", "0.6348768", "0.63193417", "0.6318059", "0.62665766", "0.6266232", "0.6265155", "0.6248112", "0.6233416", "0.6225023", "0.61834395", "0.618...
0.0
-1
Performs a single iteration of the algorithm. This includes collecting the data, updating the parameters, and adding the metrics of interest to the logger. Does not update the `curr_iter` attribute.
def step(self, snapshot_mode: str, meta_info: dict = None): # Save snapshot to save the correct iteration count self.save_snapshot() if self.curr_checkpoint == -1: self.train_teachers(snapshot_mode, None) self.reached_checkpoint() # setting counter to 0 if self.curr_checkpoint == 0: # Sample observations ros, rets, all_lengths = self.sample() # Log current progress self.logger.add_value("max return", np.max(rets), 4) self.logger.add_value("median return", np.median(rets), 4) self.logger.add_value("avg return", np.mean(rets), 4) self.logger.add_value("min return", np.min(rets), 4) self.logger.add_value("std return", np.std(rets), 4) self.logger.add_value("std var", self.expl_strat.std.item(), 4) self.logger.add_value("avg rollout len", np.mean(all_lengths), 4) self.logger.add_value("num total samples", np.sum(all_lengths)) # Save snapshot data self.make_snapshot(snapshot_mode, np.mean(rets), meta_info) # Update policy and value function self.update(rollouts=ros)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def iterate(self, data):\n \n # Append data to self.data\n self.data = np.append(self.data, data)\n \n for i, d in enumerate(data):\n update = self.current*self.likelihood(d)\n self.current = self._normalize(update)\n self.posterior = np.concatena...
[ "0.67205477", "0.6347677", "0.634362", "0.61698365", "0.61429197", "0.6141512", "0.60966563", "0.599339", "0.5989898", "0.59228843", "0.59223664", "0.5900693", "0.5892551", "0.58662176", "0.58467567", "0.584372", "0.582183", "0.58217317", "0.58217317", "0.5800747", "0.5751619...
0.0
-1
Samples observations from several samplers.
def sample(self) -> Tuple[List[List[StepSequence]], np.array, np.array]: ros = [] rets = [] all_lengths = [] for sampler in self.samplers: samples = sampler.sample() ros.append(samples) rets.extend([sample.undiscounted_return() for sample in samples]) all_lengths.extend([sample.length for sample in samples]) return ros, np.array(rets), np.array(all_lengths)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def samples(self):\n pass", "def load_samplers(self):\n for sampler in self.gltf.samplers:\n # Use a sane default sampler if the sampler data is empty\n # Samplers can simply just be json data: \"{}\"\n if sampler.minFilter is sampler.magFilter is None:\n ...
[ "0.67290366", "0.66936", "0.66508645", "0.6528074", "0.6460033", "0.6458007", "0.63837016", "0.6380185", "0.6372922", "0.63533103", "0.63098216", "0.6204721", "0.6148462", "0.6148462", "0.6144332", "0.61341447", "0.6125732", "0.61021185", "0.60895056", "0.6007772", "0.5969845...
0.0
-1
Update the policy's (and value functions') parameters based on the collected rollout data.
def update(self, *args: Any, **kwargs: Any): obss = [] losses = [] for t in range(self.num_teachers): concat_ros = StepSequence.concat(kwargs["rollouts"][t]) concat_ros.torch(data_type=to.get_default_dtype()) obss.append(concat_ros.get_data_values("observations")[: self.min_steps]) # Train student for epoch in range(self.num_epochs): self.optimizer.zero_grad() loss = 0 for t_idx, teacher in enumerate(self.teacher_policies): s_dist = self.expl_strat.action_dist_at(self.policy(obss[t_idx])) s_act = s_dist.sample() t_dist = self.teacher_expl_strats[t_idx].action_dist_at(teacher(obss[t_idx])) l = self.teacher_weights[t_idx] * self.criterion(t_dist.log_prob(s_act), s_dist.log_prob(s_act)) loss += l losses.append([t_idx, l.item()]) print(f"Epoch {epoch} Loss: {loss.item()}") loss.backward() self.optimizer.step()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def policy_update_fn(self, data: Dict[str, Any], result: Dict[str, Any]) -> None:", "def update_policy(self, *args, **kwargs):\r\n pass", "def update_policy(self):\n pass", "def update_Policy(self,inputpolicy):\n \n policyob = self.SD_Map.retrieve_ob(inputpolicy)\n policyob...
[ "0.73782724", "0.7067951", "0.66169596", "0.63102925", "0.60266966", "0.5975819", "0.595031", "0.5920189", "0.5888775", "0.58857965", "0.5820289", "0.5794157", "0.57780397", "0.5770066", "0.5761156", "0.57414526", "0.5721823", "0.5698898", "0.56790006", "0.56590545", "0.56160...
0.5152639
71
Creates random environments of the given type.
def set_random_envs(self): self.randomizer.randomize(num_samples=self.num_teachers) params = self.randomizer.get_params(fmt="dict", dtype="numpy") for e in range(self.num_teachers): self.teacher_envs.append(deepcopy(self.env_real)) print({key: value[e] for key, value in params.items()}) self.teacher_envs[e].domain_param = {key: value[e] for key, value in params.items()}
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def make_environment(seed, task_horizon):\n # Load the gym environment.\n environment = CartPoleEnv()\n environment = gym_wrappers.TimeLimit(environment, task_horizon)\n environment.seed(seed)\n environment = wrappers.GymWrapper(environment)\n environment = wrappers.SinglePrecisionWrapper(environ...
[ "0.639185", "0.61963034", "0.6018439", "0.5951477", "0.58627504", "0.5845492", "0.57870317", "0.57843524", "0.5763606", "0.56360656", "0.56098664", "0.5605386", "0.55746096", "0.55565745", "0.55424", "0.5505138", "0.5489955", "0.5485594", "0.5475609", "0.54569376", "0.5443105...
0.5628647
10
Recursively load all teachers that can be found in the current experiment's directory.
def load_teachers(self): # Get the experiment's directory to load from ex_dir = ask_for_experiment(max_display=10, env_name=self.env_real.name, perma=False) self.load_teacher_experiment(ex_dir) if len(self.teacher_policies) < self.num_teachers: print( f"You have loaded {len(self.teacher_policies)} teachers - load at least {self.num_teachers - len(self.teacher_policies)} more!" ) self.load_teachers()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def load_teacher_experiment(self, exp: Experiment):\n _, _, extra = load_experiment(exp)\n self.unpack_teachers(extra)", "def preload_all_problems(self):\n for _, _, filenames in os.walk(self.problemDir):\n for filename in filenames:\n if filename[-3:] == \".py\" an...
[ "0.66310847", "0.59174895", "0.5706464", "0.56006503", "0.5449008", "0.5424291", "0.54034406", "0.53829217", "0.5337041", "0.53273314", "0.53095233", "0.5307464", "0.52964854", "0.5285679", "0.52551943", "0.5226202", "0.5178625", "0.5178625", "0.51691693", "0.5146963", "0.514...
0.7492254
0
Load teachers from PDDRTeachers experiment.
def load_teacher_experiment(self, exp: Experiment): _, _, extra = load_experiment(exp) self.unpack_teachers(extra)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def load_teachers(self):\n # Get the experiment's directory to load from\n ex_dir = ask_for_experiment(max_display=10, env_name=self.env_real.name, perma=False)\n self.load_teacher_experiment(ex_dir)\n if len(self.teacher_policies) < self.num_teachers:\n print(\n ...
[ "0.7358244", "0.5859265", "0.5856855", "0.5826998", "0.5742936", "0.552974", "0.5405307", "0.5320931", "0.5187403", "0.5179637", "0.5173516", "0.5170551", "0.51504564", "0.51137877", "0.50919735", "0.5080042", "0.5077611", "0.50590116", "0.5048102", "0.5040496", "0.50286186",...
0.7384021
0
Unpack teachers from PDDRTeachers experiment.
def unpack_teachers(self, extra: dict): self.teacher_policies.extend(extra["teacher_policies"]) self.teacher_envs.extend(extra["teacher_envs"]) self.teacher_expl_strats.extend(extra["teacher_expl_strats"]) self.teacher_critics.extend(extra["teacher_critics"]) self.teacher_ex_dirs.extend(extra["teacher_ex_dirs"])
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def load_teacher_experiment(self, exp: Experiment):\n _, _, extra = load_experiment(exp)\n self.unpack_teachers(extra)", "def prune_teachers(self):\n self.teacher_policies = self.teacher_policies[: self.num_teachers]\n self.teacher_envs = self.teacher_envs[: self.num_teachers]\n ...
[ "0.6385784", "0.5618853", "0.54759747", "0.54556435", "0.5198481", "0.5048664", "0.49990323", "0.4985974", "0.49433678", "0.4874634", "0.47989118", "0.47896883", "0.4787353", "0.47753018", "0.4730215", "0.46576267", "0.46548298", "0.46495625", "0.4646888", "0.46451658", "0.46...
0.67790115
0
Prune teachers to only use the first num_teachers of them.
def prune_teachers(self): self.teacher_policies = self.teacher_policies[: self.num_teachers] self.teacher_envs = self.teacher_envs[: self.num_teachers] self.teacher_expl_strats = self.teacher_expl_strats[: self.num_teachers] self.teacher_critics = self.teacher_critics[: self.num_teachers] self.teacher_ex_dirs = self.teacher_ex_dirs[: self.num_teachers]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def cleanOrphanedLearners(self):\n\n # Before deleting Learners, ensure that if any Learners that are about to be\n # deleted point to a Team as their action, then that Team's count of\n # referincing Learners is decremented.\n for learner in self.learner_pop:\n if learner.ge...
[ "0.5696694", "0.545549", "0.54449904", "0.5432693", "0.52488464", "0.5203805", "0.5048298", "0.50102764", "0.493123", "0.49195728", "0.48889333", "0.48790887", "0.4860135", "0.48572624", "0.48336893", "0.48332903", "0.4776946", "0.47586012", "0.47427273", "0.47353852", "0.473...
0.7730154
0
Mirror a point over the diagonal of the map
def __mirror(self, x, y): return (self.width - x - 1, self.height - y - 1)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def mirror_point_point(point, mirror):\n return add_vectors(mirror, subtract_vectors(mirror, point))", "def mirror(self, p1=(0, 1), p2=(0, 0)):\n self.position = _reflect_points(self.position, p1, p2)\n return self", "def op_mirror():\n mir = np.array([[1, 0, 0, 0],\n [0,...
[ "0.71411884", "0.640484", "0.6257936", "0.59739065", "0.59739065", "0.58550274", "0.5843202", "0.5798668", "0.5773249", "0.57277185", "0.57091093", "0.57091093", "0.5707049", "0.56990564", "0.5662024", "0.5583394", "0.55673605", "0.55462587", "0.5533044", "0.54987687", "0.547...
0.6138612
3
Compute several gaussians and build the payout map
def __generate_payouts(self, num_hills, hill_size): hills = [] for i in range(num_hills): cx = random.randint(0, self.width - 1) cy = random.randint(0, self.height - 1) sx = random.random() * hill_size + 1 sy = random.random() * hill_size + 1 theta = random.random() * math.pi hills.append(Gaussian2D((cx, cy), (sx, sy), theta)) # Add a mirror image one too to make the map fair hills.append(Gaussian2D(self.__mirror(cx, cy), (sx, sy), theta + math.pi)) # Sum all the hills money_payout_rates = [[0.0] * self.height for x in range(self.width)] for y in range(self.height): for x in range(self.width): money_payout_rates[x][y] = sum([h.value((x,y)) for h in hills]) # Normalize the rates from 0->1 max_payout = max([max(row) for row in money_payout_rates]) min_payout = min([min(row) for row in money_payout_rates]) for y in range(self.height): for x in range(self.width): offset = money_payout_rates[x][y] - min_payout money_payout_rates[x][y] = offset / (max_payout - min_payout) money_payout_rates[x][y] = int(1000 * money_payout_rates[x][y]) / 1000.0 return money_payout_rates
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def Generate_BG_Template(outputSize=300, angularSize = 10, fileOut = 'BGRateMap.pickle' ):\r\n template = np.zeros((outputSize,outputSize))\r\n ppd=float(outputSize)/float(angularSize) # pixels per deg\r\n \r\n events110 = ParseFermi.Import_File('photons.txt', energyRange = (120000,140000),lonRange=(-...
[ "0.5963468", "0.59558034", "0.5918713", "0.589341", "0.5847284", "0.58300716", "0.5703463", "0.5690351", "0.5650076", "0.5646748", "0.56256956", "0.55975646", "0.5596329", "0.5573423", "0.55663466", "0.55646265", "0.5511411", "0.55077195", "0.5489869", "0.54598117", "0.545031...
0.0
-1
Keep trying random points until it's mirror is far enough away
def __generate_spawn_points(self): while True: p1x = random.randint(0, self.width - 1) p1y = random.randint(0, self.height - 1) p2x, p2y = self.__mirror(p1x, p1y) d_sq = (p1x - p2x)**2 + (p1y - p2y)**2 if d_sq >= (self.width / 2)**2: break return (p1x, p1y), (p2x, p2y)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def random(self):\n adj = self.adjacent()\n self.switch(random.choice([pos for pos in adj if self.in_grid(pos) and pos != self.prev]))", "def bc19_4_radius(randomize=False):\n moves = [\n Point(0, 1),\n Point(1, 0),\n Point(0, -1),\n Point(-1, 0),\n Point(1, 1)...
[ "0.65802413", "0.6314837", "0.62275654", "0.61400115", "0.61373764", "0.61373764", "0.6013303", "0.6008652", "0.59597766", "0.59432083", "0.5940083", "0.5926595", "0.59224373", "0.5892852", "0.58895075", "0.5842744", "0.58392626", "0.5830656", "0.58206266", "0.58205765", "0.5...
0.62696826
2
return orthanc object of study
def get(self): return orthanc.study(self.orthanc_id)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def orthanc_studies(self):\n return [orthanc.study(x.orthanc_id) for x in self.studies]", "def salome_study_init(theStudyId=0):\n\n global salome_study_initial\n global myStudyManager, myStudyId, myStudy, myStudyName\n global orb, lcc, naming_service, cm\n\n if salome_study_initial:\n s...
[ "0.6370708", "0.5323299", "0.51920646", "0.5153776", "0.5107432", "0.5070821", "0.5055284", "0.49911162", "0.49496976", "0.49446896", "0.49231794", "0.49001023", "0.4827991", "0.48052597", "0.4804953", "0.47864586", "0.4774238", "0.47692737", "0.4762107", "0.4743235", "0.4733...
0.7259197
0
return orthanc objects of studies
def orthanc_studies(self): return [orthanc.study(x.orthanc_id) for x in self.studies]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get(self):\n return orthanc.study(self.orthanc_id)", "def studies(self):\n return self._study_queryset", "def DumpStudies():\n for name in myStudyManager.GetOpenStudies():\n s=myStudyManager.GetStudyByName(name)\n print \"study:\",name, s._get_StudyId()\n DumpStudy(s)", "def searc...
[ "0.6256025", "0.5748354", "0.5600851", "0.5587314", "0.5289076", "0.52684903", "0.52684903", "0.5218291", "0.50912505", "0.509042", "0.50746655", "0.50711817", "0.50640666", "0.5047204", "0.49905527", "0.49653897", "0.49444157", "0.49329725", "0.49328998", "0.4929676", "0.492...
0.7746891
0
Returns all numbers below N, that is a multiple of M.
def findMultiples(M, N): numbers = [] for i in range(N): if(i + 1 == N): break if(((i + 1) % M) == 0): numbers.append(i+1) return numbers
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def sixn(m):\n if m <= 2:\n return ()\n if m > 2:\n yield 2\n if m > 3:\n yield 3\n for n in count(1):\n x = 6 * n - 1\n y = x + 2\n if x < m:\n yield x\n else:\n break\n if y < m:\n yield y\n else:\n ...
[ "0.67994684", "0.67914283", "0.6521023", "0.64013743", "0.632049", "0.62614083", "0.6100065", "0.6055581", "0.6036513", "0.6017747", "0.60122454", "0.60112625", "0.59835833", "0.59610224", "0.59551555", "0.59433913", "0.5900685", "0.587324", "0.5860821", "0.5820013", "0.58147...
0.7943605
0
Check if object is exactly an instance of specified class
def is_same_class(obj, a_class): return type(obj) == a_class
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __instancecheck__(self, instance):\n\n if isinstance(instance, ObjCInstance):\n return bool(instance.isKindOfClass(self))\n else:\n return False", "def is_same_class(obj, a_class):\n return isinstance(obj, a_class)", "def is_same_class(obj, a_class):\n if type(obj)...
[ "0.7938733", "0.7921352", "0.7915792", "0.79037", "0.79037", "0.7898302", "0.7889888", "0.7864915", "0.7833402", "0.78156614", "0.778558", "0.77762145", "0.77750516", "0.77750516", "0.77750516", "0.77750516", "0.77750516", "0.77750516", "0.777345", "0.7769582", "0.7744331", ...
0.7816911
10
setup any state tied to the execution of the given method in a class. setup_method is invoked for every test method of a class.
def setup_method(self, objectCreation):
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def setup_method(self, method):\n pass", "def setup_method(self, method):\n pass", "def _decorate_setup(self, setup_method):\n @wraps(setup_method)\n def setup_method_wrapper(*args, **kwargs):\n \"\"\"setup method wrapper.\n\n * Locks the required resources for...
[ "0.75784695", "0.75784695", "0.74024475", "0.7322949", "0.72970635", "0.72218513", "0.70287365", "0.6968257", "0.6819937", "0.67959106", "0.6794511", "0.6696449", "0.66864085", "0.6648191", "0.6600183", "0.659615", "0.6559962", "0.65412855", "0.65281886", "0.6489964", "0.6485...
0.61271554
48
teardown any state that was previously setup with a setup_method call.
def teardown_method(self, objectCreation):
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def teardown_method(self, method) -> None:", "def teardown_method(self, method):\n pass", "def teardown_method(self, method):\n pass", "def teardown_method(self, test_method):\n self.wo_obj = None\n self.config_data = None", "def teardown_method(self):", "def teardown_method(s...
[ "0.79968005", "0.78846675", "0.78846675", "0.7871643", "0.7792453", "0.7720631", "0.7659778", "0.7625319", "0.757913", "0.757913", "0.75738186", "0.75738186", "0.7567817", "0.7567817", "0.7567817", "0.7565642", "0.7565642", "0.7565642", "0.7450825", "0.7437996", "0.7437996", ...
0.71103287
40
Stop the simulator thread.
def stop(self): self._stop_event.set() super().stop()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def stop(self):\n self._Thread__stop()", "def stop(self):\n\n self.stop_thread = True", "def stop(self):\n self._state.transit(sitcpy.THREAD_STOPPING)", "def stop(self):\n self._state.transit(sitcpy.THREAD_STOPPING)", "def stop(self) -> None:\n # set the stop event, then ca...
[ "0.81179816", "0.796208", "0.7771914", "0.7771914", "0.76687425", "0.76618785", "0.76455426", "0.76039106", "0.75676537", "0.75364685", "0.7525308", "0.7504455", "0.7481357", "0.7431703", "0.7421729", "0.7421202", "0.7421202", "0.7421202", "0.7421202", "0.7421202", "0.7421202...
0.0
-1
Returns true if the logged in user is active
def is_active(self): return True
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def is_active(self):\n return self.status == ACTIVE_USER", "def is_active(self):\n return self.user.is_active", "def is_active_user(self):\n\n return self.is_active", "def check_active(self, user):\r\n if not self.require_active:\r\n # Ignore & move on.\r\n r...
[ "0.88505435", "0.8798741", "0.8700004", "0.854557", "0.78350693", "0.7738377", "0.7705481", "0.76957625", "0.76723784", "0.7669489", "0.7668266", "0.76530737", "0.7633366", "0.76033133", "0.75975317", "0.7560072", "0.7550248", "0.7520325", "0.75200886", "0.75200886", "0.75200...
0.775682
21
Returns false if the user is not logged in
def is_anonymous(self): return False
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def logged_in(self):\n return self.auth.get_user_by_session() is not None", "def isLoggedIn(self):\n session = self.getSession()\n if session is not None:\n return True\n return False", "def is_logged_in(self) -> bool:\n return self.id is not None and self.username is ...
[ "0.85514784", "0.8487751", "0.8463887", "0.84311163", "0.83854413", "0.83422846", "0.8227351", "0.81986076", "0.8189232", "0.81029665", "0.80995315", "0.8037724", "0.79774845", "0.7907793", "0.78765494", "0.7856657", "0.7833945", "0.7820103", "0.7789442", "0.77781737", "0.771...
0.0
-1
Returns true if the user is logged in
def is_authenticated(self): return True
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def logged_in():\n\n if current_user.is_authenticated:\n return True\n\n return False", "def is_logged_in():\n return 'user' in session", "def logged_in(self):\n return self.auth.get_user_by_session() is not None", "def isLoggedIn(self):\n session = self.getSession()\n if ses...
[ "0.88950294", "0.8790608", "0.8753903", "0.8581064", "0.8567044", "0.84687513", "0.84203804", "0.8413966", "0.8383255", "0.8209496", "0.82089865", "0.8092678", "0.80382335", "0.8021618", "0.79841244", "0.7928396", "0.7890733", "0.78188694", "0.77794355", "0.7776155", "0.77729...
0.7648227
30
Returns true if the logged in user is an admin
def is_admin(self): if self.type == 1: return True else: return False
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def is_admin(user):\n return user.is_authenticated and user.id == app.config.get('ADMIN')", "def is_admin_user(self):\n if \"is_admin\" in self._properties and self.is_admin == 'YES':\n return True\n return False", "def isAdmin():\n\tif 'username' in session and session['usernam...
[ "0.88923126", "0.8880638", "0.8843605", "0.87530965", "0.87412965", "0.86163646", "0.8612412", "0.85848016", "0.84613305", "0.8420776", "0.84073126", "0.840208", "0.8374834", "0.83690375", "0.835545", "0.8350487", "0.8346385", "0.8346304", "0.83000356", "0.8297389", "0.828466...
0.7866901
36
Returns the id of the user
def get_id(self): return self.id
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_user_id(self):\n return self.id_user", "def get_id(self):\n return self.user_id", "def get_id(self) -> int:\n return self.user_id", "def id(self) -> int:\n return self.user.id", "def user_id(self):\n return self.status.user[\"id\"]", "def get_user_id(self):\n ...
[ "0.87912023", "0.8627861", "0.8567077", "0.8435428", "0.8355682", "0.82900876", "0.8260854", "0.8231441", "0.8231441", "0.82138103", "0.82138103", "0.82138103", "0.82138103", "0.82138103", "0.82041234", "0.8196352", "0.8126279", "0.8126279", "0.8086236", "0.8086236", "0.80807...
0.0
-1
Returns the logged in user after adding the wanted user to his followers list
def follow(self, user): if not self.is_following(user): self.followed.append(user) return self
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def follow_user(cls, user, following):\r\n pass", "def follow(request, usertofollow):\n to_follow = Member.objects.get(user__username=usertofollow)\n user = Member.objects.get(user=request.user)\n user.following.add(to_follow)\n user.save()\n return redirect(request.META['HTTP_REFERER'])", ...
[ "0.7044998", "0.69360614", "0.6906444", "0.6870493", "0.67471176", "0.66945994", "0.66936237", "0.668267", "0.6638689", "0.65982777", "0.6567574", "0.65394175", "0.6528088", "0.6518445", "0.64401454", "0.6416909", "0.6398086", "0.6381833", "0.63553584", "0.63553584", "0.63504...
0.6222603
29
Returns the logged in user after removing the wanted user from his followers list
def unfollow(self, user): if self.is_following(user): self.followed.remove(user) return self
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def unfollowUser(following):\n \n cur, user_id, con = initialise(3, True)\n cur.execute(\"DELETE FROM followers WHERE user = (SELECT username FROM users WHERE id = ?) AND following = ?\", (user_id, following))\n finish(con)", "def unfollow(self, user):\n f = self.followed.filter_by(followed_id...
[ "0.7169295", "0.70720047", "0.70225513", "0.699361", "0.6943185", "0.682216", "0.6751137", "0.67458344", "0.6741086", "0.6738047", "0.6737277", "0.6707055", "0.66615844", "0.6618556", "0.6605784", "0.6594128", "0.65536183", "0.6531541", "0.6502671", "0.6478856", "0.64270645",...
0.65360326
17
Returns true if the current user is following the desired user
def is_following(self, user): return self.followed.filter(followers.c.followed_id == user.id).count() > 0
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def is_user_following(self, user_id):\n return user_id in self.following", "def is_following(self, you, them):\n if self.filter(from_user=you, to_user=them).count() > 0:\n return True\n return False", "def is_following(self, user):\n return self.followed.filter_by(\n ...
[ "0.7629527", "0.7531042", "0.7460013", "0.73141354", "0.72661006", "0.70735085", "0.70591176", "0.7049096", "0.6914572", "0.69122463", "0.68232995", "0.6788982", "0.67763567", "0.6769098", "0.6714947", "0.65794", "0.6538119", "0.652213", "0.6521558", "0.64769983", "0.64418167...
0.7424364
4