code
stringlengths
51
2.34k
docstring
stringlengths
11
171
def init_database(self): with contextlib.closing(self.database.cursor()) as cursor: cursor.execute( )
Initialize database, if it has not been initialized yet.
def templatesCollector(text, open, close): others = [] spans = [i for i in findBalanced(text, open, close)] spanscopy = copy(spans) for i in range(len(spans)): start, end = spans[i] o = text[start:end] ol = o.lower() if 'vaata|' in ol or 'wikitable' in ol: spa...
leaves related articles and wikitables in place
def _get_child_mock(mock, **kw): attribute = "." + kw["name"] if "name" in kw else "()" mock_name = _extract_mock_name(mock) + attribute raise AttributeError(mock_name)
Intercepts call to generate new mocks and raises instead
def magnitude(a): "calculates the magnitude of a vecor" from math import sqrt sum = 0 for coord in a: sum += coord ** 2 return sqrt(sum)
calculates the magnitude of a vecor
def RecordHelloWorld(handler, t): url = "%s/receive_recording.py" % THIS_URL t.startRecording(url) t.say ("Hello, World.") t.stopRecording() json = t.RenderJson() logging.info ("RecordHelloWorld json: %s" % json) handler.response.out.write(json)
Demonstration of recording a message.
def restart(uuid, **kwargs): from .worker_engine import restart_worker return text_type(restart_worker(uuid, **kwargs).uuid)
Restart the workflow from a given workflow engine UUID.
def _init_norm(self, weights): with tf.variable_scope("init_norm"): flat = tf.reshape(weights, [-1, self.layer_depth]) return tf.reshape(tf.norm(flat, axis=0), (self.layer_depth,))
Set the norm of the weight vector.
def make_result(self): result = {} if self._base_image_build: result[BASE_IMAGE_KOJI_BUILD] = self._base_image_build if self._parent_builds: result[PARENT_IMAGES_KOJI_BUILDS] = self._parent_builds return result if result else None
Construct the result dict to be preserved in the build metadata.
def _proc_cyclic(self): main_axis, rot = max(self.rot_sym, key=lambda v: v[1]) self.sch_symbol = "C{}".format(rot) mirror_type = self._find_mirror(main_axis) if mirror_type == "h": self.sch_symbol += "h" elif mirror_type == "v": self.sch_symbol += "v" ...
Handles cyclic group molecules.
def do_expire(self): _timeouts = deepcopy(self.timeouts) for key, value in _timeouts.items(): if value - self.clock.now() < timedelta(0): del self.timeouts[key] if key in self.redis: self.redis.pop(key, None)
Expire objects assuming now == time
def send(session_id, message): try: socket = CLIENTS[session_id][1] except KeyError: raise NoSocket("There is no socket with the session ID: " + session_id) socket.send(message)
Send a message to the socket for the given session ID.
def prep(config=None, path=None): if config is None: config = parse() if path is None: path = os.getcwd() root = config.get('root', 'path') root = os.path.join(path, root) root = os.path.realpath(root) os.environ['SCIDASH_HOME'] = root if sys.path[0] != root: sys.path...
Prepare to read the configuration information.
async def get_volume_information(self) -> List[Volume]: res = await self.services["audio"]["getVolumeInformation"]({}) volume_info = [Volume.make(services=self.services, **x) for x in res] if len(volume_info) < 1: logging.warning("Unable to get volume information") elif len(v...
Get the volume information.
def reissue(self, order_id, csr, software_id, organization_handle, approver_email=None, signature_hash_algorithm=None, domain_validation_methods=None, hostnames=None, technical_handle=None): response = self.request(E.reissueSslCertRequest( E.id(order_id), ...
Reissue an SSL certificate order
def update_rule_entry(self, rule_info): if rule_info.get('status') == 'up': self.add_rule_entry(rule_info) if rule_info.get('status') == 'down': self.remove_rule_entry(rule_info)
Update the rule_info list.
def format(self, record): if record.levelno == logging.DEBUG: record.msg = ' {}'.format(record.msg) return super(AuditLogFormatter, self).format(record)
Space debug messages for more legibility.
def extract_library_properties_from_selected_row(self): (model, row) = self.view.get_selection().get_selected() tree_item_key = model[row][self.ID_STORAGE_ID] library_item = model[row][self.ITEM_STORAGE_ID] library_path = model[row][self.LIB_PATH_STORAGE_ID] if isinstance(library...
Extracts properties library_os_path, library_path, library_name and tree_item_key from tree store row
def makecsvdiffs(thediffs, dtls, n1, n2): def ishere(val): if val == None: return "not here" else: return "is here" rows = [] rows.append(['file1 = %s' % (n1, )]) rows.append(['file2 = %s' % (n2, )]) rows.append('') rows.append(theheader(n1, n2)) keys ...
return the csv to be displayed
def unescape(s, unicode_action="replace"): import HTMLParser hp = HTMLParser.HTMLParser() s = hp.unescape(s) s = s.encode('ascii', unicode_action) s = s.replace("\n", "").strip() return s
Unescape HTML strings, and convert &amp; etc.
def call_git_branch(): try: with open(devnull, "w") as fnull: arguments = [GIT_COMMAND, 'rev-parse', '--abbrev-ref', 'HEAD'] return check_output(arguments, cwd=CURRENT_DIRECTORY, stderr=fnull).decode("ascii").strip() except (OSError, CalledProcessE...
return the string output of git desribe
def show_std_icons(): app = qapplication() dialog = ShowStdIcons(None) dialog.show() sys.exit(app.exec_())
Show all standard Icons
def parse_player_info(self, player): if not player.ishltv: self.player_info[player.name] = { "user_id": player.userID, "guid": player.guid, "bot": player.fakeplayer, }
Parse a PlayerInfo struct. This arrives before a FileInfo message
def _write_items(self, row_lookup, col_lookup, item): self.qc.write_items(row_lookup, col_lookup, item)
Perform remote write and replace blocks.
def unauthorized_callback(self): return redirect(self.login_url(params=dict(next=request.url)))
Redirect to login url with next param set as request.url
def parse_plain_scalar_indent(TokenClass): def callback(lexer, match, context): text = match.group() if len(text) <= context.indent: context.stack.pop() context.stack.pop() return if text: yield match.start(), TokenClass, text conte...
Process indentation spaces in a plain scalar.
def _tensors(cls, fluents: Sequence[FluentPair]) -> Iterable[tf.Tensor]: for _, fluent in fluents: tensor = cls._output_size(fluent.tensor) yield tensor
Yields the `fluents`' tensors.
def vtableEqual(a, objectStart, b): N.enforce_number(objectStart, N.UOffsetTFlags) if len(a) * N.VOffsetTFlags.bytewidth != len(b): return False for i, elem in enumerate(a): x = encode.Get(packer.voffset, b, i * N.VOffsetTFlags.bytewidth) if x == 0 and elem == 0: pass ...
vtableEqual compares an unwritten vtable to a written vtable.
def setup_signing(self, secret_key, sign_outgoing=True, allow_unsigned_callback=None, initial_timestamp=None, link_id=None): self.mav.signing.secret_key = secret_key self.mav.signing.sign_outgoing = sign_outgoing self.mav.signing.allow_unsigned_callback = allow_unsigned_callback if link_...
setup for MAVLink2 signing
def clearOldCalibrations(self, date=None): self.coeffs['dark current'] = [self.coeffs['dark current'][-1]] self.coeffs['noise'] = [self.coeffs['noise'][-1]] for light in self.coeffs['flat field']: self.coeffs['flat field'][light] = [ self.coeffs['flat field'][lig...
if not only a specific date than remove all except of the youngest calibration
def query(cls, name, type_=Type.String, description=None, required=None, default=None, minimum=None, maximum=None, enum=None, **options): if minimum is not None and maximum is not None and minimum > maximum: raise ValueError("Minimum must be less than or equal to the maximum.") ...
Define a query parameter
def cc(filename: 'input source file', output: 'output file name. default to be replacing input file\'s suffix with ".py"' = None, name: 'name of language' = 'unname'): lang = Language(name) with Path(filename).open('r') as fr: build_language(fr.read(), lang, filename) if not out...
rbnf source code compiler.
def initialize_env_specs(hparams, env_problem_name): if env_problem_name: env = registry.env_problem(env_problem_name, batch_size=hparams.batch_size) else: env = rl_utils.setup_env(hparams, hparams.batch_size, hparams.eval_max_num_noops, hparams.rl_e...
Initializes env_specs using the appropriate env.
def _resolve_path(self, path): filepath = None mimetype = None for root, dirs, files in self.filter_files(self.path): error_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'error_templates', path) try: with open(error_path): ...
Resolve static file paths
def update(self, *args): "Appends any passed in byte arrays to the digest object." for string in args: self._hobj.update(string) self._fobj = None
Appends any passed in byte arrays to the digest object.
def update(self, **kwargs): url_str = self.base_url + '/%s' % kwargs['alarm_id'] del kwargs['alarm_id'] resp = self.client.create(url=url_str, method='PUT', json=kwargs) return resp
Update a specific alarm definition.
def show_all(imgs:Collection[Image], r:int=1, c:Optional[int]=None, figsize=(12,6)): "Show all `imgs` using `r` rows" imgs = listify(imgs) if c is None: c = len(imgs)//r for i,ax in plot_flat(r,c,figsize): imgs[i].show(ax)
Show all `imgs` using `r` rows
def linter_functions_from_filters(whitelist=None, blacklist=None): def _keyvalue_pair_if(dictionary, condition): return { k: v for (k, v) in dictionary.items() if condition(k) } def _check_list(check_list, cond): def _check_against_list(key):...
Yield tuples of _LinterFunction matching whitelist but not blacklist.
def current_user_was_last_verifier(analysis): verifiers = analysis.getVerificators() return verifiers and verifiers[:-1] == api.get_current_user().getId()
Returns whether the current user was the last verifier or not
def handler(ca_file=None): def request(url, message, **kwargs): scheme, host, port, path = spliturl(url) if scheme != "https": ValueError("unsupported scheme: %s" % scheme) connection = HTTPSConnection(host, port, ca_file) try: body = message.get('body', "") ...
Returns an HTTP request handler configured with the given ca_file.
def _put_obj(irods_path, obj): text = json.dumps(obj, indent=2) _put_text(irods_path, text)
Put python object into iRODS as JSON text.
def _write_header(self): 'Writes the header to the underlying file object.' header = b'scrypt' + CHR0 + struct.pack('>BII', int(math.log(self.N, 2)), self.r, self.p) + self.salt checksum = hashlib.sha256(header).digest()[:16] header += checksum self._checksumer = hmac.new(self.ke...
Writes the header to the underlying file object.
def _get_string_type_from_token(token_type): return_value = None if token_type in [TokenType.BeginSingleQuotedLiteral, TokenType.EndSingleQuotedLiteral]: return_value = "Single" elif token_type in [TokenType.BeginDoubleQuotedLiteral, TokenType.EndDoubleQ...
Return 'Single' or 'Double' depending on what kind of string this is.
def repack_all(self): non_na_sequences = [s for s in self.sequences if ' ' not in s] self.pack_new_sequences(non_na_sequences) return
Repacks the side chains of all Polymers in the Assembly.
def CleanName(name): name = re.sub('[^_A-Za-z0-9]', '_', name) if name[0].isdigit(): name = '_%s' % name while keyword.iskeyword(name): name = '%s_' % name if name.startswith('__'): name = 'f%s' % name return name
Perform generic name cleaning.
def _get_data_versions(data): genome_dir = install.get_genome_dir(data["genome_build"], data["dirs"].get("galaxy"), data) if genome_dir: version_file = os.path.join(genome_dir, "versions.csv") if version_file and os.path.exists(version_file): return version_file return None
Retrieve CSV file with version information for reference data.
def _validate(cls, kind): if kind not in cls._valid_kinds: mesg = "'kind' must be one of {}, {}, {}, or {}." raise ValueError(mesg.format(*cls._valid_kinds)) else: return kind
Validate the kind argument.
def __GetChunk(self, start, end, additional_headers=None): self.EnsureInitialized() request = http_wrapper.Request(url=self.url) self.__SetRangeHeader(request, start, end=end) if additional_headers is not None: request.headers.update(additional_headers) return http_wr...
Retrieve a chunk, and return the full response.
def revoke_token(access_token): response = requests.post( get_revoke_token_url(), data={ 'token': access_token, 'client_id': settings.API_CLIENT_ID, 'client_secret': settings.API_CLIENT_SECRET, }, timeout=15 ) return response.status_code ==...
Instructs the API to delete this access token and associated refresh token
def list_managers_view(request): managerset = Manager.objects.filter(active=True) return render_to_response('list_managers.html', { 'page_name': "Managers", 'managerset': managerset, }, context_instance=RequestContext(request))
Show a list of manager positions with links to view in detail.
def _get_names(dirs): alphabets = set() label_names = {} for d in dirs: for example in _walk_omniglot_dir(d): alphabet, alphabet_char_id, label, _ = example alphabets.add(alphabet) label_name = "%s_%d" % (alphabet, alphabet_char_id) if label in label_names: assert label_names[l...
Get alphabet and label names, union across all dirs.
def morph_cost(self) -> Optional["Cost"]: if self.tech_alias is None or self.tech_alias[0] in {UnitTypeId.TECHLAB, UnitTypeId.REACTOR}: return None tech_alias_cost_minerals = max([self._game_data.units[tech_alias.value].cost.minerals for tech_alias in self.tech_alias]) tech_alias_cos...
This returns 150 minerals for OrbitalCommand instead of 550
def collection(path, *stats): def initMethod(self): init(self, path) attributes = {'__init__': initMethod} for stat in stats: attributes[stat.getName()] = stat newClass = type('Stats:%s' % path, (object,), attributes) instance = newClass() for stat in stats: default = stat._getInit() if defa...
Creates a named stats collection object.
def generate_static(self, path): if not path: return "" if path[0] == '/': return "%s?v=%s" % (path, self.version) return "%s/%s?v=%s" % (self.static, path, self.version)
This method generates a valid path to the public folder of the running project
def add_group(self, group_attribs=None, parent=None): if parent is None: parent = self.tree.getroot() elif not self.contains_group(parent): warnings.warn('The requested group {0} does not belong to ' 'this Document'.format(parent)) if group_attri...
Add an empty group element to the SVG.
def recover_and_supervise(recovery_file): try: logging.info("Attempting to recover Supervisor data from " + recovery_file) with open(recovery_file) as rf: recovery_data = json.load(rf) monitor_data = recovery_data['monitor_data'] dependencies = recovery_data['depe...
Retrieve monitor data from recovery_file and resume monitoring
def clean_by_request(self, request): if request not in self.request_map: return for tag, matcher, future in self.request_map[request]: self._timeout_future(tag, matcher, future) if future in self.timeout_map: tornado.ioloop.IOLoop.current().remove_time...
Remove all futures that were waiting for request `request` since it is done waiting
def PortPathMatcher(cls, port_path): if isinstance(port_path, str): port_path = [int(part) for part in SYSFS_PORT_SPLIT_RE.split(port_path)] return lambda device: device.port_path == port_path
Returns a device matcher for the given port path.
def on_created(self, event): if self.trigger != "create": return action_input = ActionInput(event, "", self.name) flows.Global.MESSAGE_DISPATCHER.send_message(action_input)
Fired when something's been created
def mask_average(dset,mask): o = nl.run(['3dmaskave','-q','-mask',mask,dset]) if o: return float(o.output.split()[-1])
Returns average of voxels in ``dset`` within non-zero voxels of ``mask``
def _prt_line_detail(self, prt, line, lnum=""): data = zip(self.flds, line.split('\t')) txt = ["{:2}) {:13} {}".format(i, hdr, val) for i, (hdr, val) in enumerate(data)] prt.write("{LNUM}\n{TXT}\n".format(LNUM=lnum, TXT='\n'.join(txt)))
Print each field and its value.
def _new_song(self): s = self.song if self.shuffle: self.song = self.shuffles[random.randrange(len(self.shuffles))] else: self.song += 1 if self.song >= len(self.loop): self.song = 0 self.dif_song = s != self.song self.pos = 0
Used internally to get a metasong index.
def _send(self, msg, buffers=None): if self.comm is not None and self.comm.kernel is not None: self.comm.send(data=msg, buffers=buffers)
Sends a message to the model in the front-end.
def _parse_date_hungarian(dateString): m = _hungarian_date_format_re.match(dateString) if not m or m.group(2) not in _hungarian_months: return None month = _hungarian_months[m.group(2)] day = m.group(3) if len(day) == 1: day = '0' + day hour = m.group(4) if len(hour) == 1: ...
Parse a string according to a Hungarian 8-bit date format.
def _idToStr(self, x): if x < 0: sign = -1 elif x == 0: return self._idChars[0] else: sign = 1 x *= sign digits = [] while x: digits.append(self._idChars[x % self._idCharsCnt]) x //= self._idCharsCnt if s...
Convert VCD id in int to string
def who_am_i(): me = url['me'].format(token) r = requests.get(me, params={'client_id': CLIENT_ID}) r.raise_for_status() current_user = r.json() logger.debug(me) logger.info('Hello {0}!'.format(current_user['username'])) return current_user
Display username from current token and check for validity
def in_file(self, fn: str) -> Iterator[Statement]: yield from self.__file_to_statements.get(fn, [])
Returns an iterator over all of the statements belonging to a file.
def recent(self, include=None): return self._query_zendesk(self.endpoint.recent, 'ticket', id=None, include=include)
Retrieve the most recent tickets
def list(): running_list = [] parser = argparse.ArgumentParser() parser.add_argument('--logdir') parser.add_argument('--port') for p in psutil.process_iter(): if p.name() != 'tensorboard' or p.status() == psutil.STATUS_ZOMBIE: continue cmd_args = p.cmdline() del cmd_args[0:...
List running TensorBoard instances.
def from_filename(cls, path_string, origin=MISSING, **kwargs): path = Path(path_string) return cls.from_path(path, origin, **kwargs)
Read Sass source from a String specifying the path
def _add_access_token_to_response(self, response, access_token): response['access_token'] = access_token.value response['token_type'] = access_token.type response['expires_in'] = access_token.expires_in
Adds the Access Token and the associated parameters to the Token Response.
def _merge_dicts(first, second): new = deepcopy(first) for k, v in second.items(): if isinstance(v, dict) and v: ret = _merge_dicts(new.get(k, dict()), v) new[k] = ret else: new[k] = second[k] return new
Merge the 'second' multiple-dictionary into the 'first' one.
def _set_data(self, data, offset=None, copy=False): data = np.array(data, copy=copy) data = self._normalize_shape(data) if offset is None: self._resize(data.shape) elif all([i == 0 for i in offset]) and data.shape == self._shape: self._resize(data.shape) o...
Internal method for set_data.
def _init_hdrgo_sortby(self, hdrgo_sortby, sortby): if hdrgo_sortby is not None: return hdrgo_sortby if sortby is not None: return sortby return self.sortby
Initialize header sort function.
def unregister_callback(callback_id): global _callbacks obj = _callbacks.pop(callback_id, None) threads = [] if obj is not None: t, quit = obj quit.set() threads.append(t) for t in threads: t.join()
unregister a callback registration
def encode_hdr(self, boundary): boundary = encode_and_quote(boundary) headers = ["--%s" % boundary] if self.filename: disposition = 'form-data; name="%s"; filename="%s"' % (self.name, self.filename) else: ...
Returns the header of the encoding of this parameter
def _preallocate_samples(self): self.prealloc_samples_ = [] for i in range(self.num_prealloc_samples_): self.prealloc_samples_.append(self.sample())
Preallocate samples for faster adaptive sampling.
def native_string_to_unicode(s, encoding="ascii", errors="strict"): if not isinstance(s, str): raise TypeError("{} must be type str, not {}".format(s, type(s))) if str is unicode: return s else: return s.decode(encoding=encoding, errors=errors)
Ensure that the native string ``s`` is converted to ``unicode``.
def most_seen_works_card(kind=None, num=10): object_list = most_seen_works(kind=kind, num=num) object_list = chartify(object_list, 'num_views', cutoff=1) if kind: card_title = 'Most seen {}'.format( Work.get_kind_name_plural(kind).lower()) else: card_t...
Displays a card showing the Works that are associated with the most Events.
def detect_sv(align_bam, genome_build, dirs, config): work_dir = utils.safe_makedir(os.path.join(dirs["work"], "structural")) pair_stats = shared.calc_paired_insert_stats(align_bam) fix_bam = remove_nopairs(align_bam, work_dir, config) tier2_align = tiered_alignment(fix_bam, "2", True, [], ...
Detect structural variation from discordant aligned pairs.
def storage_list(storage_name=None): _args = ['storage-list', '--format=json'] if storage_name: _args.append(storage_name) try: return json.loads(subprocess.check_output(_args).decode('UTF-8')) except ValueError: return None except OSError as e: import errno i...
List the storage IDs for the unit
def next_frame_sv2p_atari(): hparams = next_frame_sv2p() hparams.video_num_input_frames = 4 hparams.video_num_target_frames = 4 hparams.action_injection = "multiplicative" hparams.num_iterations_1st_stage = 12000 hparams.num_iterations_2nd_stage = 12000 hparams.anneal_end = 40000 hparams.latent_loss_mul...
SV2P model for atari.
def _parse_invite(client, command, actor, args): target, _, channel = args.rpartition(" ") client.dispatch_event("INVITE", actor, target, channel.lower())
Parse an INVITE and dispatch an event.
def select_and_start_cluster(self, platform): clusters = self.reactor_config.get_enabled_clusters_for_platform(platform) if not clusters: raise UnknownPlatformException('No clusters found for platform {}!' .format(platform)) retry_contexts =...
Choose a cluster and start a build on it
def _from_dict(cls, _dict): args = {} if 'input' in _dict: args['input'] = MessageInput._from_dict(_dict.get('input')) if 'intents' in _dict: args['intents'] = [ RuntimeIntent._from_dict(x) for x in (_dict.get('intents')) ] if 'entities...
Initialize a MessageRequest object from a json dictionary.
def _compute_dynamic_properties(self, builder): splits = self.splits for split_info in utils.tqdm( splits.values(), desc="Computing statistics...", unit=" split"): try: split_name = split_info.name dataset_feature_statistics, schema = get_dataset_feature_statistics( bui...
Update from the DatasetBuilder.
def sense(self): cmd_name = random.choice(self.senses) param = '' if cmd_name == 'ls': if random.randint(0, 1): param = '-l' elif cmd_name == 'uname': opts = 'asnrvmpio' start = random.randint(0, len(opts) - 2) end = random....
Launch a command in the 'senses' List, and update the current state.
def clear_to_reset(self, config_vars): super(RemoteBridgeState, self).clear_to_reset(config_vars) self.status = BRIDGE_STATUS.IDLE self.error = 0
Clear the RemoteBridge subsystem to its reset state.
def unfreeze(self): g = get_root(self).globals self.filter.configure(state='normal') dtype = g.observe.rtype() if dtype == 'data caution' or dtype == 'data' or dtype == 'technical': self.prog_ob.configure(state='normal') self.pi.configure(state='normal') ...
Unfreeze all settings so that they can be altered
def to_matrix(np_array): if len(np_array.shape) == 2: return Matrices.dense(np_array.shape[0], np_array.shape[1], np_array.ravel()) else: raise Exception("An MLLib Matrix can only be created from a two-dimensional " + ...
Convert numpy array to MLlib Matrix
def delete_vnic_template_for_vlan(self, vlan_id): with self.session.begin(subtransactions=True): try: self.session.query(ucsm_model.VnicTemplate).filter_by( vlan_id=vlan_id).delete() except orm.exc.NoResultFound: return
Deletes VNIC Template for a vlan_id and physnet if it exists.
def handle_source_positions(self, call_id, payload): self.log.debug('handle_source_positions: in %s', Pretty(payload)) call_options = self.call_options[call_id] word_under_cursor = call_options.get("word_under_cursor") positions = payload["positions"] if not positions: ...
Handler for source positions
def disconnect(self): old_api = object.__getattribute__(self, '_api') new_api = API.build_hardware_simulator( loop=old_api._loop, config=copy.copy(old_api.config)) setattr(self, '_api', new_api)
Disconnect from connected hardware.
def _add_cmd_output(self, cmd, suggest_filename=None, root_symlink=None, timeout=300, stderr=True, chroot=True, runat=None, env=None, binary=False, sizelimit=None, pred=None): cmdt = ( cmd, suggest_filename, root_sym...
Internal helper to add a single command to the collection list.
def delete_port_binding(self, port, host): if not self.get_instance_type(port): return for pb_key in self._get_binding_keys(port, host): pb_res = MechResource(pb_key, a_const.PORT_BINDING_RESOURCE, a_const.DELETE) self.provision_queue...
Enqueue port binding delete
def _next_sample_index(self): return self.rng.choice(self.n_active, p=(self.stream_weights_ / self.weight_norm_))
StochasticMux chooses its next sample stream randomly
def write(self): with open(self.log_path, "w") as f: json.dump(self.log_dict, f, indent=1)
Dump JSON to file
def check_network_id(network_id, web3: Web3): while True: current_id = int(web3.version.network) if network_id != current_id: raise RuntimeError( f'Raiden was running on network with id {network_id} and it detected ' f'that the underlying ethereum client n...
Check periodically if the underlying ethereum client's network id has changed
def _run_sync(self, method: Callable, *args, **kwargs) -> Any: if self.loop.is_running(): raise RuntimeError("Event loop is already running.") if not self.is_connected: self.loop.run_until_complete(self.connect()) task = asyncio.Task(method(*args, **kwargs), loop=self.loo...
Utility method to run commands synchronously for testing.
def _get_deps(deps, tree_base, saltenv='base'): deps_list = '' if deps is None: return deps_list if not isinstance(deps, list): raise SaltInvocationError( '\'deps\' must be a Python list or comma-separated string' ) for deprpm in deps: parsed = _urlparse(deprp...
Get include string for list of dependent rpms to build package
def delete_node(self, key_chain): node = self._data for key in key_chain[:-1]: node = node[key] del node[key_chain[-1]]
key_chain is an array of keys giving the path to the node that should be deleted.