code
stringlengths
51
2.34k
docstring
stringlengths
11
171
def reflect_left(self, value): if value > self: value = self.reflect(value) return value
Only reflects the value if is > self.
async def connect(self, timeout=None, ssl=None): await self._connect(timeout=timeout, ssl=ssl) self._connected = True self._send_task = self._loop.create_task(self._send_loop()) self._recv_task = self._loop.create_task(self._recv_loop())
Establishes a connection with the server.
def create_release_hook(name, source_path): from rez.plugin_managers import plugin_manager return plugin_manager.create_instance('release_hook', name, source_path=source_path)
Return a new release hook of the given type.
def pre_validate(self, form): for preprocessor in self._preprocessors: preprocessor(form, self) super(FieldHelper, self).pre_validate(form)
Calls preprocessors before pre_validation
def deletion_not_allowed(self, request, obj, language_code): opts = self.model._meta context = { 'object': obj.master, 'language_code': language_code, 'opts': opts, 'app_label': opts.app_label, 'language_name': get_language_title(language_code), 'object_name': force_text(opts.verbose_name) } return render(request, self.deletion_not_allowed_template, context)
Deletion-not-allowed view.
def group_dashboard(request, group_slug): groups = get_user_groups(request.user) group = get_object_or_404(groups, slug=group_slug) tenants = get_user_tenants(request.user, group) can_edit_group = request.user.has_perm('multitenancy.change_tenantgroup', group) count = len(tenants) if count == 1: return redirect(tenants[0]) context = { 'group': group, 'tenants': tenants, 'count': count, 'can_edit_group': can_edit_group, } return render(request, 'multitenancy/group-detail.html', context)
Dashboard for managing a TenantGroup.
def displayHelp(self): self.outputStream.write(self.linter.help()) sys.exit(32)
Output help message of twistedchecker.
def _get_fw(self, msg, updates, req_fw_type=None, req_fw_ver=None): fw_type = None fw_ver = None if not isinstance(updates, tuple): updates = (updates, ) for store in updates: fw_id = store.pop(msg.node_id, None) if fw_id is not None: fw_type, fw_ver = fw_id updates[-1][msg.node_id] = fw_id break if fw_type is None or fw_ver is None: _LOGGER.debug( 'Node %s is not set for firmware update', msg.node_id) return None, None, None if req_fw_type is not None and req_fw_ver is not None: fw_type, fw_ver = req_fw_type, req_fw_ver fware = self.firmware.get((fw_type, fw_ver)) if fware is None: _LOGGER.debug( 'No firmware of type %s and version %s found', fw_type, fw_ver) return None, None, None return fw_type, fw_ver, fware
Get firmware type, version and a dict holding binary data.
def to_linspace(self): if hasattr(self.shape, '__len__'): raise NotImplementedError("can only convert flat Full arrays to linspace") return Linspace(self.fill_value, self.fill_value, self.shape)
convert from full to linspace
def _pretty_access_flags_gen(self): if self.is_public(): yield "public" if self.is_final(): yield "final" if self.is_abstract(): yield "abstract" if self.is_interface(): if self.is_annotation(): yield "@interface" else: yield "interface" if self.is_enum(): yield "enum"
generator of the pretty access flags
def message_convert_rx(message_rx): is_extended_id = bool(message_rx.flags & IS_ID_TYPE) is_remote_frame = bool(message_rx.flags & IS_REMOTE_FRAME) is_error_frame = bool(message_rx.flags & IS_ERROR_FRAME) return Message(timestamp=message_rx.timestamp, is_remote_frame=is_remote_frame, is_extended_id=is_extended_id, is_error_frame=is_error_frame, arbitration_id=message_rx.id, dlc=message_rx.sizeData, data=message_rx.data[:message_rx.sizeData])
convert the message from the CANAL type to pythoncan type
def getitem(self, index): if index >= getattr(self.tree, self.size): raise IndexError(index) if self.__cache_objects and index in self.__cache: return self.__cache[index] obj = self.tree_object_cls(self.tree, self.name, self.prefix, index) if self.__cache_objects: self.__cache[index] = obj return obj
direct access without going through self.selection
def sensor(self, sensor_type): _LOGGER.debug("Reading %s sensor.", sensor_type) return self._session.read_sensor(self.device_id, sensor_type)
Update and return sensor value.
def visit_class(rec, cls, op): if isinstance(rec, MutableMapping): if "class" in rec and rec.get("class") in cls: op(rec) for d in rec: visit_class(rec[d], cls, op) if isinstance(rec, MutableSequence): for d in rec: visit_class(d, cls, op)
Apply a function to with "class" in cls.
def load_plan(self, fname): with open(fname, "r") as f: for line in f: if line != '': tpe, txt = self.parse_plan_from_string(line) if tpe == 'name': self.name = txt elif tpe == 'version': self.plan_version = txt elif tpe == 'belief': self.beliefs.add(txt) elif tpe == 'desire': self.desires.add(txt) elif tpe == 'intention': self.intentions.add(txt)
read the list of thoughts from a text file
def _initConstants(ptc): ptc.WeekdayOffsets = {} o = 0 for key in ptc.Weekdays: ptc.WeekdayOffsets[key] = o o += 1 o = 0 for key in ptc.shortWeekdays: ptc.WeekdayOffsets[key] = o o += 1 ptc.MonthOffsets = {} o = 1 for key in ptc.Months: ptc.MonthOffsets[key] = o o += 1 o = 1 for key in ptc.shortMonths: ptc.MonthOffsets[key] = o o += 1
Create localized versions of the units, week and month names
def MigrateArtifacts(): artifacts = data_store.REL_DB.ReadAllArtifacts() if artifacts: logging.info("Deleting %d artifacts from REL_DB.", len(artifacts)) for artifact in data_store.REL_DB.ReadAllArtifacts(): data_store.REL_DB.DeleteArtifact(Text(artifact.name)) else: logging.info("No artifacts found in REL_DB.") artifacts = artifact_registry.REGISTRY.GetArtifacts( reload_datastore_artifacts=True) logging.info("Found %d artifacts in AFF4.", len(artifacts)) artifacts = list(filter(_IsCustom, artifacts)) logging.info("Migrating %d user-created artifacts.", len(artifacts)) for artifact in artifacts: _MigrateArtifact(artifact)
Migrates Artifacts from AFF4 to REL_DB.
def maelstrom(args): infile = args.inputfile genome = args.genome outdir = args.outdir pwmfile = args.pwmfile methods = args.methods ncpus = args.ncpus if not os.path.exists(infile): raise ValueError("file {} does not exist".format(infile)) if methods: methods = [x.strip() for x in methods.split(",")] run_maelstrom(infile, genome, outdir, pwmfile, methods=methods, ncpus=ncpus)
Run the maelstrom method.
def show_active_only(self, state): query = self._copy() query.active_only = state return query
Set active only to true or false on a copy of this query
async def _async_ws_handler(self, data): sia_message = data['data']['sia'] spc_id = sia_message['sia_address'] sia_code = sia_message['sia_code'] _LOGGER.debug("SIA code is %s for ID %s", sia_code, spc_id) if sia_code in Area.SUPPORTED_SIA_CODES: entity = self._areas.get(spc_id, None) resource = 'area' elif sia_code in Zone.SUPPORTED_SIA_CODES: entity = self._zones.get(spc_id, None) resource = 'zone' else: _LOGGER.debug("Not interested in SIA code %s", sia_code) return if not entity: _LOGGER.error("Received message for unregistered ID %s", spc_id) return data = await self._async_get_data(resource, entity.id) entity.update(data, sia_code) if self._async_callback: ensure_future(self._async_callback(entity))
Process incoming websocket message.
def nb_to_python(nb_path): exporter = python.PythonExporter() output, resources = exporter.from_filename(nb_path) return output
convert notebook to python script
def _prep_cmd(cmd, tx_out_file): cmd = " ".join(cmd) if isinstance(cmd, (list, tuple)) else cmd return "export TMPDIR=%s && %s" % (os.path.dirname(tx_out_file), cmd)
Wrap CNVkit commands ensuring we use local temporary directories.
def write(self, fn=None): fn = fn or self.fn if not os.path.exists(os.path.dirname(fn)): os.makedirs(os.path.dirname(fn)) f = open(self.fn, 'rb') b = f.read() f.close() f = open(fn, 'wb') f.write(b) f.close()
copy the zip file from its filename to the given filename.
def timeit(threshold=0): def inner(func): @wraps(func) def wrapper(*args, **kwargs): start = time.time() return_value = func(*args, **kwargs) end = time.time() duration = float(end-start) if duration > threshold: logger.info("Execution of '{}{}' took {:2f}s".format( func.__name__, args, duration)) return return_value return wrapper return inner
Decorator to log the execution time of a function
def check_post_role(self): priv_dic = {'ADD': False, 'EDIT': False, 'DELETE': False, 'ADMIN': False} if self.userinfo: if self.userinfo.role[1] > '0': priv_dic['ADD'] = True if self.userinfo.role[1] >= '1': priv_dic['EDIT'] = True if self.userinfo.role[1] >= '3': priv_dic['DELETE'] = True if self.userinfo.role[1] >= '2': priv_dic['ADMIN'] = True return priv_dic
check the user role for docs.
def apply(self, f_del, h): fd_rule = self.rule ne = h.shape[0] nr = fd_rule.size - 1 _assert(nr < ne, 'num_steps ({0:d}) must be larger than ' '({1:d}) n + order - 1 = {2:d} + {3:d} -1' ' ({4:s})'.format(ne, nr+1, self.n, self.order, self.method)) f_diff = convolve(f_del, fd_rule[::-1], axis=0, origin=nr // 2) der_init = f_diff / (h ** self.n) ne = max(ne - nr, 1) return der_init[:ne], h[:ne]
Apply finite difference rule along the first axis.
def cull_to_timestep(self, timestep=1): valid_s = self.header.analysis_period.VALIDTIMESTEPS.keys() assert timestep in valid_s, \ 'timestep {} is not valid. Choose from: {}'.format(timestep, valid_s) new_ap, new_values, new_datetimes = self._timestep_cull(timestep) new_header = self.header.duplicate() new_header._analysis_period = new_ap new_coll = HourlyDiscontinuousCollection( new_header, new_values, new_datetimes) new_coll._validated_a_period = True return new_coll
Get a collection with only datetimes that fit a timestep.
def contracts_version_expects_deposit_limits(contracts_version: Optional[str]) -> bool: if contracts_version is None: return True if contracts_version == '0.3._': return False return compare(contracts_version, '0.9.0') > -1
Answers whether TokenNetworkRegistry of the contracts_vesion needs deposit limits
def enable_key(self): print("This command will enable a disabled key.") apiKeyID = input("API Key ID: ") try: key = self._curl_bitmex("/apiKey/enable", postdict={"apiKeyID": apiKeyID}) print("Key with ID %s enabled." % key["id"]) except: print("Unable to enable key, please try again.") self.enable_key()
Enable an existing API Key.
def _get_range(self, endpoint, *args, method='GET', **kwargs): if args: url = self.build_url(self._endpoints.get(endpoint).format(*args)) else: url = self.build_url(self._endpoints.get(endpoint)) if not kwargs: kwargs = None if method == 'GET': response = self.session.get(url, params=kwargs) elif method == 'POST': response = self.session.post(url, data=kwargs) if not response: return None return self.__class__(parent=self, **{self._cloud_data_key: response.json()})
Helper that returns another range
def create_md5(path): m = hashlib.md5() with open(path, "rb") as f: while True: data = f.read(8192) if not data: break m.update(data) return m.hexdigest()
Create the md5 hash of a file using the hashlib library.
def _connectToFB(self): if self.connected_to_fb: logger.debug("Already connected to fb") return True logger.debug("Connecting to fb") token = facebook_login.get_fb_token() try: self.fb = facebook.GraphAPI(token) except: print("Couldn't connect to fb") return False self.connected_to_fb=True return True
Establish the actual TCP connection to FB
def fetch_section_data(self, context, name): data = self.resolve_context(context, name) if not data: data = [] else: try: iter(data) except TypeError: data = [data] else: if is_string(data) or isinstance(data, dict): data = [data] return data
Fetch the value of a section as a list.
def unsure_pyname(pyname, unbound=True): if pyname is None: return True if unbound and not isinstance(pyname, pynames.UnboundName): return False if pyname.get_object() == pyobjects.get_unknown(): return True
Return `True` if we don't know what this name references
def include(self, pattern): found = [f for f in glob(pattern) if not os.path.isdir(f)] self.extend(found) return bool(found)
Include files that match 'pattern'.
def parse_json(text: str, encoding: str = "utf-8") -> HistogramBase: data = json.loads(text, encoding=encoding) return create_from_dict(data, format_name="JSON")
Create histogram from a JSON string.
def progress_status(self): if self.line % self.freq == 0: text = self.statustext.format(nele=self.line, totalele=self.total_lines) if self.main_window.grid.actions.pasting: try: post_command_event(self.main_window, self.main_window.StatusBarMsg, text=text) except TypeError: pass else: self.main_window.GetStatusBar().SetStatusText(text) if is_gtk(): try: wx.Yield() except: pass self.line += 1
Displays progress in statusbar
def geh(m, c): if m + c == 0: return 0 else: return math.sqrt(2 * (m - c) * (m - c) / (m + c))
Error function for hourly traffic flow measures after Geoffrey E. Havers
def getStartNodes(fdefs,calls): s=[] for source in fdefs: for fn in fdefs[source]: inboundEdges=False for call in calls: if call.target==fn: inboundEdges=True if not inboundEdges: s.append(fn) return s
Return a list of nodes in fdefs that have no inbound edges
def _update_Prxy_diag(self): for r in range(self.nsites): pr_half = self.prx[r]**0.5 pr_neghalf = self.prx[r]**-0.5 symm_pr = (pr_half * (self.Prxy[r] * pr_neghalf).transpose()).transpose() (evals, evecs) = scipy.linalg.eigh(symm_pr) self.D[r] = evals self.Ainv[r] = evecs.transpose() * pr_half self.A[r] = (pr_neghalf * evecs.transpose()).transpose()
Update `D`, `A`, `Ainv` from `Prxy`, `prx`.
def OnSelectCard(self, event): item = event.GetItem() if item: itemdata = self.readertreepanel.cardtreectrl.GetItemPyData(item) if isinstance(itemdata, smartcard.Card.Card): self.dialogpanel.OnSelectCard(itemdata) else: self.dialogpanel.OnDeselectCard(itemdata)
Called when the user selects a card in the tree.
def stamp(revision, sql, tag): alembic_command.stamp( config=get_config(), revision=revision, sql=sql, tag=tag )
Stamp db to given revision without migrating
def _get_file(src): try: if '://' in src or src[0:2] == '//': response = urllib2.urlopen(src) return response.read() else: with open(src, 'rb') as fh: return fh.read() except Exception as e: raise RuntimeError('Error generating base64image: {}'.format(e))
Return content from local or remote file.
def _getPastEvents(self, request): home = request.site.root_page return getAllPastEvents(request, home=home)
Return the past events in this site.
def public_timeline(self, delegate, params={}, extra_args=None): "Get the most recent public timeline." return self.__get('/statuses/public_timeline.atom', delegate, params, extra_args=extra_args)
Get the most recent public timeline.
def filter(select, iterable, namespaces=None, flags=0, **kwargs): return compile(select, namespaces, flags, **kwargs).filter(iterable)
Filter list of nodes.
def register_signals(self): for index in self.indexes: if index.object_type: self._connect_signal(index)
Register signals for all indexes.
def setWorkingStandingZeroPoseToRawTrackingPose(self): fn = self.function_table.setWorkingStandingZeroPoseToRawTrackingPose pMatStandingZeroPoseToRawTrackingPose = HmdMatrix34_t() fn(byref(pMatStandingZeroPoseToRawTrackingPose)) return pMatStandingZeroPoseToRawTrackingPose
Sets the preferred standing position in the working copy.
def getenv(option_name, default=None): env = "%s_%s" % (NAMESPACE.upper(), option_name.upper()) return os.environ.get(env, default)
Return the option from the environment in the FASTFOOD namespace.
def object(self, infotype, key): "Return the encoding, idletime, or refcount about the key" return self.execute_command('OBJECT', infotype, key, infotype=infotype)
Return the encoding, idletime, or refcount about the key
def execute_command(self): stderr = "" role_count = 0 for role in utils.roles_dict(self.roles_path): self.command = self.command.replace("%role_name", role) (_, err) = utils.capture_shell("cd {0} && {1}". format(os.path.join( self.roles_path, role), self.command)) stderr = err role_count += 1 utils.exit_if_no_roles(role_count, self.roles_path) if len(stderr) > 0: ui.error(c.MESSAGES["run_error"], stderr[:-1]) else: if not self.config["options_quiet"]: ui.ok(c.MESSAGES["run_success"].replace( "%role_count", str(role_count)), self.options.command)
Execute the shell command.
def run_all_evals(models, treebanks, out_file, check_parse, print_freq_tasks): print_header = True for tb_lang, treebank_list in treebanks.items(): print() print("Language", tb_lang) for text_path in treebank_list: print(" Evaluating on", text_path) gold_path = text_path.parent / (text_path.stem + '.conllu') print(" Gold data from ", gold_path) try: with gold_path.open(mode='r', encoding='utf-8') as gold_file: gold_ud = conll17_ud_eval.load_conllu(gold_file) for nlp, nlp_loading_time, nlp_name in models[tb_lang]: try: print(" Benchmarking", nlp_name) tmp_output_path = text_path.parent / str('tmp_' + nlp_name + '.conllu') run_single_eval(nlp, nlp_loading_time, nlp_name, text_path, gold_ud, tmp_output_path, out_file, print_header, check_parse, print_freq_tasks) print_header = False except Exception as e: print(" Ran into trouble: ", str(e)) except Exception as e: print(" Ran into trouble: ", str(e))
Run an evaluation for each language with its specified models and treebanks
def set(file_name, key, value, new): db = XonoticDB.load_path(file_name) if key not in db and not new: click.echo('Key %s is not found in the database' % key, file=sys.stderr) sys.exit(1) else: db[key] = value db.save(file_name)
Set a new value for the specified key.
def validate_config(data: dict) -> dict: errors = ConfigSchema().validate(data) if errors: for field, messages in errors.items(): if isinstance(messages, dict): for level, sample_errors in messages.items(): sample_id = data['samples'][level]['sample_id'] for sub_field, sub_messages in sample_errors.items(): LOG.error(f"{sample_id} -> {sub_field}: {', '.join(sub_messages)}") else: LOG.error(f"{field}: {', '.join(messages)}") raise ConfigError('invalid config input', errors=errors)
Convert to MIP config format.
def create_atomic_wrapper(cls, wrapped_func): def _create_atomic_wrapper(*args, **kwargs): with transaction.atomic(): return wrapped_func(*args, **kwargs) return _create_atomic_wrapper
Returns a wrapped function.
def stop(self): LOG.info("Shutting down server") self.server.shutdown() LOG.debug("ServerThread.stop: Stopping ServerThread") self.server.server_close() LOG.info("Server stopped")
Shut down our XML-RPC server.
def _get_variable_names(arr): if VARIABLELABEL in arr.dims: return arr.coords[VARIABLELABEL].tolist() else: return arr.name
Return the variable names of an array
def _use_vxrentry(self, f, VXRoffset, recStart, recEnd, offset): f.seek(VXRoffset+20) numEntries = int.from_bytes(f.read(4), 'big', signed=True) usedEntries = int.from_bytes(f.read(4), 'big', signed=True) self._update_offset_value(f, VXRoffset+28+4*usedEntries, 4, recStart) self._update_offset_value(f, VXRoffset+28+4*numEntries+4*usedEntries, 4, recEnd) self._update_offset_value(f, VXRoffset+28+2*4*numEntries+8*usedEntries, 8, offset) usedEntries += 1 self._update_offset_value(f, VXRoffset+24, 4, usedEntries) return usedEntries
Adds a VVR pointer to a VXR
def remote_call(request, cls, method, args, kw): actor = request.actor name = 'remote_%s' % cls.__name__ if not hasattr(actor, name): object = cls(actor) setattr(actor, name, object) else: object = getattr(actor, name) method_name = '%s%s' % (PREFIX, method) return getattr(object, method_name)(request, *args, **kw)
Command for executing remote calls on a remote object
def address_to_scripthash(address: str) -> UInt160: AddressVersion = 23 data = b58decode(address) if len(data) != 25: raise ValueError('Not correct Address, wrong length.') if data[0] != AddressVersion: raise ValueError('Not correct Coin Version') checksum_data = data[:21] checksum = hashlib.sha256(hashlib.sha256(checksum_data).digest()).digest()[:4] if checksum != data[21:]: raise Exception('Address format error') return UInt160(data=data[1:21])
Just a helper method
def mask_negative(self): self.mask = np.logical_and(self.mask, ~(self.intensity < 0))
Extend the mask with the image elements where the intensity is negative.
def req2frame(req, N: int=0): if req is None: frame = np.arange(N, dtype=np.int64) elif isinstance(req, int): frame = np.arange(0, N, req, dtype=np.int64) elif len(req) == 1: frame = np.arange(0, N, req[0], dtype=np.int64) elif len(req) == 2: frame = np.arange(req[0], req[1], dtype=np.int64) elif len(req) == 3: frame = np.arange(req[0], req[1], req[2], dtype=np.int64) - 1 else: frame = np.arange(N, dtype=np.int64) return frame
output has to be numpy.arange for > comparison
def plot_fit(self): self.plt.plot(*self.fit.fit, **self.options['fit'])
Add the fit to the plot.
def _handle_heading(self, token): level = token.level self._push() while self._tokens: token = self._tokens.pop() if isinstance(token, tokens.HeadingEnd): title = self._pop() return Heading(title, level) else: self._write(self._handle_token(token)) raise ParserError("_handle_heading() missed a close token")
Handle a case where a heading is at the head of the tokens.
def create(self, request, project): job_id = int(request.data['job_id']) bug_id = int(request.data['bug_id']) try: BugJobMap.create( job_id=job_id, bug_id=bug_id, user=request.user, ) message = "Bug job map saved" except IntegrityError: message = "Bug job map skipped: mapping already exists" return Response({"message": message})
Add a new relation between a job and a bug.
def soft_error(self, message): self.print_usage(sys.stderr) args = {'prog': self.prog, 'message': message} self._print_message( _('%(prog)s: error: %(message)s\n') % args, sys.stderr)
Same as error, without the dying in a fire part.
def _preprocess_edges_for_pydot(edges_with_data): for (source, target, attrs) in edges_with_data: if 'label' in attrs: yield (quote_for_pydot(source), quote_for_pydot(target), {'label': quote_for_pydot(attrs['label'])}) else: yield (quote_for_pydot(source), quote_for_pydot(target), {})
throw away all edge attributes, except for 'label
def parse_tags(self): tags = [] try: for tag in self._tag_group_dict["tags"]: tags.append(Tag(tag)) except: return tags return tags
Parses tags in tag group
def AddPassword(self, fileset): passwd = fileset.get("/etc/passwd") if passwd: self._ParseFile(passwd, self.ParsePasswdEntry) else: logging.debug("No /etc/passwd file.")
Add the passwd entries to the shadow store.
def release_lock(): get_lock.n_lock -= 1 assert get_lock.n_lock >= 0 if get_lock.lock_is_enabled and get_lock.n_lock == 0: get_lock.start_time = None get_lock.unlocker.unlock()
Release lock on compilation directory.
def search_list(kb, value=None, match_type=None, page=None, per_page=None, unique=False): page = page or 1 per_page = per_page or 10 if kb.kbtype == models.KnwKB.KNWKB_TYPES['written_as']: query = api.query_kb_mappings( kbid=kb.id, value=value or '', match_type=match_type or 's' ).with_entities(models.KnwKBRVAL.m_value) if unique: query = query.distinct() return [item.m_value for item in pagination.RestfulSQLAlchemyPagination( query, page=page or 1, per_page=per_page or 10 ).items] elif kb.kbtype == models.KnwKB.KNWKB_TYPES['dynamic']: items = api.get_kbd_values(kb.name, value) return pagination.RestfulPagination( page=page, per_page=per_page, total_count=len(items) ).slice(items) return []
Search "mappings to" for knowledge.
def _repr_mimebundle_(self, *args, **kwargs): try: if self.logo: p = pn.Row( self.logo_panel, self.panel, margin=0) return p._repr_mimebundle_(*args, **kwargs) else: return self.panel._repr_mimebundle_(*args, **kwargs) except: raise RuntimeError("Panel does not seem to be set up properly")
Display in a notebook or a server
def invert_differencing(self, initial_part, differenced_rest, order=None): if order is None: order = self.diff_order starting_points = [ self.apply_differencing(initial_part, order=order)[-1] for order in range(self.diff_order)] actual_predictions = differenced_rest import pdb pdb.set_trace() for s in starting_points[::-1]: actual_predictions = np.cumsum(np.hstack([s, actual_predictions]))[1:] return(actual_predictions)
function to invert the differencing
def main(): query = ' '.join(sys.stdin.readlines()) sys.stdout.write(pretty_print_graphql(query))
Read a GraphQL query from standard input, and output it pretty-printed to standard output.
def solve_minimize( self, func, weights, constraints, lower_bound=0.0, upper_bound=1.0, func_deriv=False ): bounds = ((lower_bound, upper_bound), ) * len(self.SUPPORTED_COINS) return minimize( fun=func, x0=weights, jac=func_deriv, bounds=bounds, constraints=constraints, method='SLSQP', options={'disp': False} )
Returns the solution to a minimization problem.
def _msg(self, label, *msg): if self.quiet is False: txt = self._unpack_msg(*msg) print("[" + label + "] " + txt)
Prints a message with a label
def to_dict(self): result = { 'type': get_qualified_name(self), 'fitted': self.fitted, 'constant_value': self.constant_value } if not self.fitted: return result result.update(self._fit_params()) return result
Returns parameters to replicate the distribution.
def assertEqual(cls, first, second, msg=None): asserter = None if type(first) is type(second): asserter = cls.equality_type_funcs.get(type(first)) try: basestring = basestring except NameError: basestring = str if asserter is not None: if isinstance(asserter, basestring): asserter = getattr(cls, asserter) if asserter is None: asserter = cls.simple_equality if msg is None: asserter(first, second) else: asserter(first, second, msg=msg)
Classmethod equivalent to unittest.TestCase method
def node_predictions(self): pred = np.zeros(self.data_size) for node in self: if node.is_terminal: pred[node.indices] = node.node_id return pred
Determines which rows fall into which node
def script_start_type(script): if script[0].type.text == 'when @greenFlag clicked': return HairballPlugin.HAT_GREEN_FLAG elif script[0].type.text == 'when I receive %s': return HairballPlugin.HAT_WHEN_I_RECEIVE elif script[0].type.text == 'when this sprite clicked': return HairballPlugin.HAT_MOUSE elif script[0].type.text == 'when %s key pressed': return HairballPlugin.HAT_KEY else: return HairballPlugin.NO_HAT
Return the type of block the script begins with.
def request_write(self, request: TBWriteRequest)->None: "Queues up an asynchronous write request to Tensorboard." if self.stop_request.isSet(): return self.queue.put(request)
Queues up an asynchronous write request to Tensorboard.
def _rebuild_key_ids(self): self._key_ids = collections.defaultdict(list) for i, x in enumerate(self._pairs): self._key_ids[x[0]].append(i)
Rebuild the internal key to index mapping.
def processes(self): if self._processes is None: self._processes = [] for p in range(self.workers): t = Task(self._target, self._args, self._kwargs) t.name = "%s-%d" % (self.target_name, p) self._processes.append(t) return self._processes
Initialise and return the list of processes associated with this pool
def draw_build_target(self, surf): round_half = lambda v, cond: round(v - 0.5) + 0.5 if cond else round(v) queued_action = self._queued_action if queued_action: radius = queued_action.footprint_radius if radius: pos = self.get_mouse_pos() if pos: pos = point.Point(round_half(pos.world_pos.x, (radius * 2) % 2), round_half(pos.world_pos.y, (radius * 2) % 2)) surf.draw_circle( colors.PLAYER_ABSOLUTE_PALETTE[ self._obs.observation.player_common.player_id], pos, radius)
Draw the build target.
def calculate(cls, byte_arr, crc=0): for byte in byte_iter(byte_arr): tmp = cls.CRC_TABLE[crc & 0xF] crc = (crc >> 4) & 0x0FFF crc = crc ^ tmp ^ cls.CRC_TABLE[byte & 0xF] tmp = cls.CRC_TABLE[crc & 0xF] crc = (crc >> 4) & 0x0FFF crc = crc ^ tmp ^ cls.CRC_TABLE[(byte >> 4) & 0xF] return crc
Compute CRC for input bytes.
def restore_original_method(self): if self._target.is_class_or_module(): setattr(self._target.obj, self._method_name, self._original_method) if self._method_name == '__new__' and sys.version_info >= (3, 0): _restore__new__(self._target.obj, self._original_method) else: setattr(self._target.obj, self._method_name, self._original_method) elif self._attr.kind == 'property': setattr(self._target.obj.__class__, self._method_name, self._original_method) del self._target.obj.__dict__[double_name(self._method_name)] elif self._attr.kind == 'attribute': self._target.obj.__dict__[self._method_name] = self._original_method else: del self._target.obj.__dict__[self._method_name] if self._method_name in ['__call__', '__enter__', '__exit__']: self._target.restore_attr(self._method_name)
Replaces the proxy method on the target object with its original value.
def measure_int_put(self, measure, value): if value < 0: logger.warning("Cannot record negative values") self._measurement_map[measure] = value
associates the measure of type Int with the given value
def tnet_to_nx(df, t=None): if t is not None: df = get_network_when(df, t=t) if 'weight' in df.columns: nxobj = nx.from_pandas_edgelist( df, source='i', target='j', edge_attr='weight') else: nxobj = nx.from_pandas_edgelist(df, source='i', target='j') return nxobj
Creates undirected networkx object
def _startDriver(self): framework = addict.Dict() framework.user = getpass.getuser() framework.name = "toil" framework.principal = framework.name self.driver = MesosSchedulerDriver(self, framework, self._resolveAddress(self.mesosMasterAddress), use_addict=True, implicit_acknowledgements=True) self.driver.start()
The Mesos driver thread which handles the scheduler's communication with the Mesos master
def birthday(self): if isfile(self.pid_file): tstamp = datetime.fromtimestamp(self.created()) tzone = tzname[0] weekday = WEEKDAY[tstamp.isoweekday()] age = self.age() age_str = '{}s ago'.format(age[0]) bday = '{} {} {}; {}'.format(weekday, tstamp, tzone, age_str) return (self.created(), bday) return (None, None)
Return a string representing the age of the process.
def main(data, utype, ctype): copula = CopulaModel(data, utype, ctype) print(copula.sampling(1, plot=True)) print(copula.model.vine_model[-1].tree_data)
Create a Vine from the data, utype and ctype
def patch_wda(self): import wda def _click(that): rawx, rawy = that.bounds.center x, y = self.d.scale*rawx, self.d.scale*rawy screen_before = self._save_screenshot() orig_click = pt.get_original(wda.Selector, 'click') screen_after = self._save_screenshot() self.add_step('click', screen_before=screen_before, screen_after=screen_after, position={'x': x, 'y': y}) return orig_click(that) pt.patch_item(wda.Selector, 'click', _click)
Record steps of WebDriverAgent
def cmd_center(self, args): if len(args) < 3: print("map center LAT LON") return lat = float(args[1]) lon = float(args[2]) self.map.set_center(lat, lon)
control center of view
def _perform_read(self, addr, size): return self._machine_controller.read(addr, size, self._x, self._y, 0)
Perform a read using the machine controller.
def _add_supplemental(data): if "supplemental" not in data["sv"]: data["sv"]["supplemental"] = [] if data["sv"].get("variantcaller"): cur_name = _useful_basename(data) for k in ["cns", "vrn_bed"]: if data["sv"].get(k) and os.path.exists(data["sv"][k]): dname, orig = os.path.split(data["sv"][k]) orig_base, orig_ext = utils.splitext_plus(orig) orig_base = _clean_name(orig_base, data) if orig_base: fname = "%s-%s%s" % (cur_name, orig_base, orig_ext) else: fname = "%s%s" % (cur_name, orig_ext) sup_out_file = os.path.join(dname, fname) utils.symlink_plus(data["sv"][k], sup_out_file) data["sv"]["supplemental"].append(sup_out_file) return data
Add additional supplemental files to CWL sv output, give useful names.
def register_eph_task(self, *args, **kwargs): kwargs["task_class"] = EphTask return self.register_task(*args, **kwargs)
Register an electron-phonon task.
def save_form(self, form, **kwargs): obj = form.save(commit=False) change = obj.pk is not None self.save_obj(obj, form, change) if hasattr(form, 'save_m2m'): form.save_m2m() return obj
Contains formset save, prepare obj for saving
def read_binary(self, num, item_type='B'): if 'B' in item_type: return self.read(num) if item_type[0] in ('@', '=', '<', '>', '!'): order = item_type[0] item_type = item_type[1:] else: order = '@' return list(self.read_struct(Struct(order + '{:d}'.format(int(num)) + item_type)))
Parse the current buffer offset as the specified code.
def autoLayout(self, size=None): if size is None: size = self._view.size() self.setSceneRect(0, 0, size.width(), size.height()) for item in self.items(): if isinstance(item, XWalkthroughGraphic): item.autoLayout(size)
Updates the layout for the graphics within this scene.
def update_product(product_id, **kwargs): content = update_product_raw(product_id, **kwargs) if content: return utils.format_json(content)
Update a Product with new information