code
stringlengths
51
2.38k
docstring
stringlengths
4
15.2k
def _load_matcher(self) -> None: for id_key in self._rule_lst: if self._rule_lst[id_key].active: pattern_lst = [a_pattern.spacy_token_lst for a_pattern in self._rule_lst[id_key].patterns] for spacy_rule_id, spacy_rule in enumerate(itertools.product(*pattern_lst)): ...
Add constructed spacy rule to Matcher
def reject_recursive_repeats(to_wrap): to_wrap.__already_called = {} @functools.wraps(to_wrap) def wrapped(*args): arg_instances = tuple(map(id, args)) thread_id = threading.get_ident() thread_local_args = (thread_id,) + arg_instances if thread_local_args in to_wrap.__already...
Prevent simple cycles by returning None when called recursively with same instance
def __is_subgraph_planar(graph): num_nodes = graph.num_nodes() num_edges = graph.num_edges() if num_nodes < 5: return True if num_edges > 3*(num_nodes - 2): return False return kocay_planarity_test(graph)
Internal function to determine if a subgraph is planar.
def merge_element_data(dest, sources, use_copy=True): if dest is not None: ret = dest.copy() else: ret = {} if use_copy: sources = copy.deepcopy(sources) for s in sources: if 'electron_shells' in s: if 'electron_shells' not in ret: ret['electro...
Merges the basis set data for an element from multiple sources into dest. The destination is not modified, and a (shallow) copy of dest is returned with the data from sources added. If use_copy is True, then the data merged into dest will be a (deep) copy of that found in sources. Otherwise, data ...
def _intersection(A,B): intersection = [] for i in A: if i in B: intersection.append(i) return intersection
A simple function to find an intersection between two arrays. @type A: List @param A: First List @type B: List @param B: Second List @rtype: List @return: List of Intersections
def format_info(raw): logging.debug(_('raw[0]: %s'), raw[0]) results, sense = raw new = '\n'.join( '{} {} {} {}'.format( i[0], sense.kind_id_to_name(i[1]), sense.file_id_to_name(i[2]).lower(), i[3] + ' ' if i[3] else '').strip() for i in results) retur...
Format a string representing the information concerning the name.
def external(func): def f(*args, **kwargs): return func(*args, **kwargs) f.external = True f.__doc__ = func.__doc__ return f
Mark function as external. :param func: :return:
def _iupac_ambiguous_equal(ambig_base, unambig_base): iupac_translation = { 'A': 'A', 'C': 'C', 'G': 'G', 'T': 'T', 'U': 'U', 'R': 'AG', 'Y': 'CT', 'S': 'GC', 'W': 'AT', 'K': 'GT', 'M': 'AC', 'B': 'CGT', 'D': 'AG...
Tests two bases for equality, accounting for IUPAC ambiguous DNA ambiguous base may be IUPAC ambiguous, unambiguous must be one of ACGT
def _dict_key_priority(s): if isinstance(s, Hook): return _priority(s._schema) - 0.5 if isinstance(s, Optional): return _priority(s._schema) + 0.5 return _priority(s)
Return priority for a given key object.
def publish(self, topic, data, defer=None, block=True, timeout=None, raise_error=True): result = AsyncResult() conn = self._get_connection(block=block, timeout=timeout) try: self._response_queues[conn].append(result) conn.publish(topic, data, defer=defer) ...
Publish a message to the given topic. :param topic: the topic to publish to :param data: bytestring data to publish :param defer: duration in milliseconds to defer before publishing (requires nsq 0.3.6) :param block: wait for a connection to become available before ...
def dict_from_node(node, recursive=False): dict = {} for snode in node: if len(snode) > 0: if recursive: value = dict_from_node(snode, True) else: value = len(snode) elif snode.text is not None: value = snode.text else: ...
Converts ElementTree node to a dictionary. Parameters ---------- node : ElementTree node recursive : boolean If recursive=False, the value of any field with children will be the number of children. Returns ------- dict : nested dictionary. Tags as keys and values as...
def confirmation_pdf(self, confirmation_id): return self._create_get_request(resource=CONFIRMATIONS, billomat_id=confirmation_id, command=PDF)
Opens a pdf of a confirmation :param confirmation_id: the confirmation id :return: dict
def last_executed_query(self, cursor, sql, params): return super(DatabaseOperations, self).last_executed_query(cursor, cursor.last_sql, cursor.last_params)
Returns a string of the query last executed by the given cursor, with placeholders replaced with actual values. `sql` is the raw query containing placeholders, and `params` is the sequence of parameters. These are used by default, but this method exists for database backends to provide ...
def engine(self): pid = os.getpid() conn = SQLAlchemyTarget._engine_dict.get(self.connection_string) if not conn or conn.pid != pid: engine = sqlalchemy.create_engine( self.connection_string, connect_args=self.connect_args, echo=self.ec...
Return an engine instance, creating it if it doesn't exist. Recreate the engine connection if it wasn't originally created by the current process.
def write_sample_sheet(path, accessions, names, celfile_urls, sel=None): with open(path, 'wb') as ofh: writer = csv.writer(ofh, dialect='excel-tab', lineterminator=os.linesep, quoting=csv.QUOTE_NONE) writer.writerow(['Accession', 'Name', 'CEL f...
Write the sample sheet.
def catalog_split_yaml(self, **kwargs): kwargs_copy = self.base_dict.copy() kwargs_copy.update(**kwargs) self._replace_none(kwargs_copy) localpath = NameFactory.catalog_split_yaml_format.format(**kwargs_copy) if kwargs.get('fullpath', False): return self.fullp...
return the name of a catalog split yaml file
def train(self, content_objs, idx_labels): if len(set([lab[0] for lab in idx_labels])) <= 1: return None fcs = [fc for _, fc in content_objs] feature_names = vectorizable_features(fcs) dis = dissimilarities(feature_names, fcs) phi_dicts, labels = [], [] for co...
Trains and returns a model using sklearn. If there are new labels to add, they can be added, returns an sklearn model which can be used for prediction and getting features. This method may return ``None`` if there is insufficient training data to produce a model. :para...
def draw_address(canvas): business_details = ( u'COMPANY NAME LTD', u'STREET', u'TOWN', U'COUNTY', U'POSTCODE', U'COUNTRY', u'', u'', u'Phone: +00 (0) 000 000 000', u'Email: example@example.com', u'Website: www.example.com', ...
Draws the business address
def on_output_path_textChanged(self): output_path = self.output_path.text() output_not_xml_msg = tr('output file is not .tif') if output_path and not output_path.endswith('.tif'): self.warning_text.add(output_not_xml_msg) elif output_path and output_not_xml_msg in self.warnin...
Action when output file name is changed.
def _log_function(self, handler): if handler.get_status() < 400: log_method = request_log.info elif handler.get_status() < 500: log_method = request_log.warning else: log_method = request_log.error for i in settings['LOGGING_IGNORE_URLS']: ...
Override Application.log_function so that what to log can be controlled.
def loadSettings(self, groupName=None): groupName = groupName if groupName else self.settingsGroupName settings = QtCore.QSettings() logger.info("Reading {!r} from: {}".format(groupName, settings.fileName())) settings.beginGroup(groupName) self.clear() try: fo...
Reads the registry items from the persistent settings store.
def _signal_handler(self, signum, frame): if self._options.config: with open(self._options.config, "w") as cfg: yaml.dump(self._home_assistant_config(), cfg) print( "Dumped home assistant configuration at", self._options.config)...
Method called when handling signals
def permitted_actions(self, user, obj=None): try: if not self._obj_ok(obj): raise InvalidPermissionObjectException return user.permset_tree.permitted_actions(obj) except ObjectDoesNotExist: return []
Determine list of permitted actions for an object or object pattern. :param user: The user to test. :type user: ``User`` :param obj: A function mapping from action names to object paths to test. :type obj: callable :returns: ``list(tutelary.engine.Act...
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 info(gandi, resource): output_keys = ['name', 'state', 'size', 'type', 'id', 'dc', 'vm', 'profile', 'kernel', 'cmdline'] resource = sorted(tuple(set(resource))) vms = dict([(vm['id'], vm) for vm in gandi.iaas.list()]) datacenters = gandi.datacenter.list() result = [] for n...
Display information about a disk. Resource can be a disk name or ID
def readFile(self, pathToFile): fd = open(pathToFile, "rb") data = fd.read() fd.close() return data
Returns data from a file. @type pathToFile: str @param pathToFile: Path to the file. @rtype: str @return: The data from file.
def glyphs2ufo(options): if options.output_dir is None: options.output_dir = os.path.dirname(options.glyphs_file) or "." if options.designspace_path is None: options.designspace_path = os.path.join( options.output_dir, os.path.basename(os.path.splitext(options.glyphs_file...
Converts a Glyphs.app source file into UFO masters and a designspace file.
def iter_tours(tourfile, frames=1): fp = open(tourfile) i = 0 for row in fp: if row[0] == '>': label = row[1:].strip() if label.startswith("GA"): pf, j, score = label.split("-", 2) j = int(j) else: j = 0 ...
Extract tours from tourfile. Tourfile contains a set of contig configurations, generated at each iteration of the genetic algorithm. Each configuration has two rows, first row contains iteration id and score, second row contains list of contigs, separated by comma.
def diff(self, mail_a, mail_b): return len(''.join(unified_diff( mail_a.body_lines, mail_b.body_lines, fromfile='a', tofile='b', fromfiledate='', tofiledate='', n=0, lineterm='\n')))
Return difference in bytes between two mails' normalized body. TODO: rewrite the diff algorithm to not rely on naive unified diff result parsing.
def commit(self, id, impreq): schema = RequestSchema() json = self.service.encode(schema, impreq) schema = RequestSchema() resp = self.service.post(self.base+str(id)+'/', json=json) return self.service.decode(schema, resp)
Commit a staged import. :param id: Staged import ID as an int. :param impreq: :class:`imports.Request <imports.Request>` object :return: :class:`imports.Request <imports.Request>` object :rtype: imports.Request
def deploy_from_template(self, context, deploy_action, cancellation_context): deploy_from_template_model = self.resource_model_parser.convert_to_resource_model( attributes=deploy_action.actionParams.deployment.attributes, resource_model_type=vCenterVMFromTemplateResourceModel) da...
Deploy From Template Command, will deploy vm from template :param CancellationContext cancellation_context: :param ResourceCommandContext context: the context of the command :param DeployApp deploy_action: :return DeployAppResult deploy results
def authenticate_with_serviceaccount(reactor, **kw): config = KubeConfig.from_service_account(**kw) policy = https_policy_from_config(config) token = config.user["token"] agent = HeaderInjectingAgent( _to_inject=Headers({u"authorization": [u"Bearer {}".format(token)]}), _agent=Agent(reac...
Create an ``IAgent`` which can issue authenticated requests to a particular Kubernetes server using a service account token. :param reactor: The reactor with which to configure the resulting agent. :param bytes path: The location of the service account directory. The default should work fine for ...
def get_region(self, x,z): if (x,z) not in self.regions: if (x,z) in self.regionfiles: self.regions[(x,z)] = region.RegionFile(self.regionfiles[(x,z)]) else: self.regions[(x,z)] = region.RegionFile() self.regions[(x,z)].loc = Location(x=x,z=z) ...
Get a region using x,z coordinates of a region. Cache results.
def fields(self): if self._fields is None: self._fields = FieldList( self._version, assistant_sid=self._solution['assistant_sid'], task_sid=self._solution['sid'], ) return self._fields
Access the fields :returns: twilio.rest.autopilot.v1.assistant.task.field.FieldList :rtype: twilio.rest.autopilot.v1.assistant.task.field.FieldList
def get_allowed_domain(url, allow_subdomains=True): if allow_subdomains: return re.sub(re_www, '', re.search(r'[^/]+\.[^/]+', url).group(0)) else: return re.search(re_domain, UrlExtractor.get_allowed_domain(url)).group(0)
Determines the url's domain. :param str url: the url to extract the allowed domain from :param bool allow_subdomains: determines wether to include subdomains :return str: subdomains.domain.topleveldomain or domain.topleveldomain
def unpack_struct(self, struct): size = struct.size offset = self.offset if self.data: avail = len(self.data) - offset else: avail = 0 if avail < size: raise UnpackException(struct.format, size, avail) self.offset = offset + size ...
unpacks the given struct from the underlying buffer and returns the results. Will raise an UnpackException if there is not enough data to satisfy the format of the structure
def _init_file(self): self.keyring_key = self._get_new_password() self.set_password('keyring-setting', 'password reference', 'password reference value') self._write_config_value('keyring-setting', 'scheme', ...
Initialize a new password file and set the reference password.
def _cfg(key, default=None): root_cfg = __salt__.get('config.get', __opts__.get) kms_cfg = root_cfg('aws_kms', {}) return kms_cfg.get(key, default)
Return the requested value from the aws_kms key in salt configuration. If it's not set, return the default.
def setScales(self,scales=None,term_num=None): if scales==None: for term_i in range(self.n_terms): n_scales = self.vd.getTerm(term_i).getNumberScales() self.vd.getTerm(term_i).setScales(SP.array(SP.randn(n_scales))) elif term_num==None: assert scal...
get random initialization of variances based on the empirical trait variance Args: scales: if scales==None: set them randomly, else: set scales to term_num (if term_num==None: set to all terms) term_num: set scales to term_num
def _get_hanging_wall_coeffs_rrup(self, dists): fhngrrup = np.ones(len(dists.rrup)) idx = dists.rrup > 0.0 fhngrrup[idx] = (dists.rrup[idx] - dists.rjb[idx]) / dists.rrup[idx] return fhngrrup
Returns the hanging wall rrup term defined in equation 13
def get_phase(n_samples, des_mask, asc_mask): import numpy phase = numpy.zeros(n_samples, dtype=int) phase[asc_mask] = 1 phase[des_mask] = -1 return phase
Get the directional phase sign for each sample in depths Args ---- n_samples: int Length of output phase array des_mask: numpy.ndarray, shape (n,) Boolean mask of values where animal is descending asc_mask: numpy.ndarray, shape(n,) Boolean mask of values where animal is asce...
def _get_api_id(self, event_properties): api_id = event_properties.get("RestApiId") if isinstance(api_id, dict) and "Ref" in api_id: api_id = api_id["Ref"] return api_id
Get API logical id from API event properties. Handles case where API id is not specified or is a reference to a logical id.
def setup_dir(self): cd = self.opts.cd or self.config['crony'].get('directory') if cd: self.logger.debug(f'Adding cd to {cd}') self.cmd = f'cd {cd} && {self.cmd}'
Change directory for script if necessary.
def add(self, key): encodedKey = json.dumps(key) with self.connect() as conn: with doTransaction(conn): sql = 'INSERT IGNORE INTO ' + self.table + ' (name) VALUES (%s)' return insertSQL(conn, sql, args=[encodedKey])
add key to the namespace. it is fine to add a key multiple times.
def __start_connection(self, context, node, ccallbacks=None): _logger.debug("Creating connection object: CONTEXT=[%s] NODE=[%s]", context, node) c = nsq.connection.Connection( context, node, self.__identify, self.__...
Start a new connection, and manage it from a new greenlet.
def getYadisXRD(xrd_tree): xrd = None for xrd in xrd_tree.findall(xrd_tag): pass if xrd is None: raise XRDSError('No XRD present in tree') return xrd
Return the XRD element that should contain the Yadis services
def _exponential_timeout_generator(initial, maximum, multiplier, deadline): if deadline is not None: deadline_datetime = datetime_helpers.utcnow() + datetime.timedelta( seconds=deadline ) else: deadline_datetime = datetime.datetime.max timeout = initial while True: ...
A generator that yields exponential timeout values. Args: initial (float): The initial timeout. maximum (float): The maximum timeout. multiplier (float): The multiplier applied to the timeout. deadline (float): The overall deadline across all invocations. Yields: float:...
def raise_error(error_type: str) -> None: try: error = next((v for k, v in ERROR_CODES.items() if k in error_type)) except StopIteration: error = AirVisualError raise error(error_type)
Raise the appropriate error based on error message.
def _button_plus_clicked(self, n): self._button_save.setEnabled(True) self.insert_colorpoint(self._colorpoint_list[n][0], self._colorpoint_list[n][1], self._colorpoint_list[n][2]) self._build_gui()
Create a new colorpoint.
def section(self, section): if not isinstance(self._container, ConfigUpdater): raise ValueError("Sections can only be added at section level!") if isinstance(section, str): section = Section(section, container=self._container) elif not isinstance(section, Section): ...
Creates a section block Args: section (str or :class:`Section`): name of section or object Returns: self for chaining
def normalized_start(self): namespaces_after_key = list(self.make_datastore_query().Run(limit=1)) if not namespaces_after_key: return None namespace_after_key = namespaces_after_key[0].name() or '' return NamespaceRange(namespace_after_key, self.namespace_end, ...
Returns a NamespaceRange with leading non-existant namespaces removed. Returns: A copy of this NamespaceRange whose namespace_start is adjusted to exclude the portion of the range that contains no actual namespaces in the datastore. None is returned if the NamespaceRange contains no actual ...
def __locate_scubainit(self): pkg_path = os.path.dirname(__file__) self.scubainit_path = os.path.join(pkg_path, 'scubainit') if not os.path.isfile(self.scubainit_path): raise ScubaError('scubainit not found at "{}"'.format(self.scubainit_path))
Determine path to scubainit binary
def open_http(self, url, data=None): return self._open_generic_http(http_client.HTTPConnection, url, data)
Use HTTP protocol.
def find_packages(): packages = ['pyctools'] for root, dirs, files in os.walk(os.path.join('src', 'pyctools')): package = '.'.join(root.split(os.sep)[1:]) for name in dirs: packages.append(package + '.' + name) return packages
Walk source directory tree and convert each sub directory to a package name.
def capacityForRole(self,role): if isinstance(role, DanceRole): role_id = role.id else: role_id = role eventRoles = self.eventrole_set.filter(capacity__gt=0) if eventRoles.count() > 0 and role_id not in [x.role.id for x in eventRoles]: return 0 ...
Accepts a DanceRole object and determines the capacity for that role at this event.this Since roles are not always custom specified for events, this looks for the set of available roles in multiple places, and only returns the overall capacity of the event if roles are not found elsewhere.
def create_and_run_collector(document, options): collector = None if not options.report == 'off': collector = Collector() collector.store.configure(document) Event.configure(collector_queue=collector.queue) collector.start() return collector
Create and run collector process for report data.
def time_until_expiration(self): if self.password_expires_at is not None: expiration_date = datetime.datetime.strptime( self.password_expires_at, "%Y-%m-%dT%H:%M:%S.%f") return expiration_date - datetime.datetime.now()
Returns the number of remaining days until user's password expires. Calculates the number days until the user must change their password, once the password expires the user will not able to log in until an admin changes its password.
def validate_port(port): if not isinstance(port, (str, int)): raise TypeError(f'port must be an integer or string: {port}') if isinstance(port, str) and port.isdigit(): port = int(port) if isinstance(port, int) and 0 < port <= 65535: return port raise ValueError(f'invalid port: {...
Validate port and return it as an integer. A string, or its representation as an integer, is accepted.
def default_token_implementation(self, user_id): user = self.get(user_id) if not user: msg = 'No user with such id [{}]' raise x.JwtNoUser(msg.format(user_id)) if user._token: try: self.decode_token(user._token) return user._tok...
Default JWT token implementation This is used by default for generating user tokens if custom implementation was not configured. The token will contain user_id and expiration date. If you need more information added to the token, register your custom implementation. It will load...
def get_all_tags_of_offer(self, offer_id): return self._iterate_through_pages( get_function=self.get_tags_of_offer_per_page, resource=OFFER_TAGS, **{'offer_id': offer_id} )
Get all tags of offer This will iterate over all pages until it gets all elements. So if the rate limit exceeded it will throw an Exception and you will get nothing :param offer_id: the offer id :return: list
def get_state_map(meta_graph, state_ops, unsupported_state_ops, get_tensor_by_name): state_map = {} for node in meta_graph.graph_def.node: if node.op in state_ops: tensor_name = node.name + ":0" tensor = get_tensor_by_name(tensor_name) num_outputs = len(tensor.op.outputs) ...
Returns a map from tensor names to tensors that hold the state.
def _void_array_to_list(restuple, _func, _args): shape = (restuple.e.len, 1) array_size = np.prod(shape) mem_size = 8 * array_size array_str_e = string_at(restuple.e.data, mem_size) array_str_n = string_at(restuple.n.data, mem_size) ls_e = np.frombuffer(array_str_e, float, array_size).tolist() ...
Convert the FFI result to Python data structures
def register(self, event, fn): self._callbacks.setdefault(event, []).append(fn) return fn
Tell the object to run `fn` whenever a message of type `event` is received.
def safe_stat(path, timeout=1, cmd=None): "Use threads and a subproc to bodge a timeout on top of filesystem access" global safe_stat_process if cmd is None: cmd = ['/usr/bin/stat'] cmd.append(path) def target(): global safe_stat_process logger.debug('Stat thread started') ...
Use threads and a subproc to bodge a timeout on top of filesystem access
def rotateX(self, angle): rad = angle * math.pi / 180 cosa = math.cos(rad) sina = math.sin(rad) y = self.y * cosa - self.z * sina z = self.y * sina + self.z * cosa return Point3D(self.x, y, z)
Rotates the point around the X axis by the given angle in degrees.
def missing(self, dst): for inst in six.itervalues(dst): if inst.status != REMOVED: inst.status = REMOVED inst.save()
Mark all missing plugins, that exists in database, but are not registered.
def open(self): if self.handle is None: self.handle = fits.open(self.fname, mode='readonly') if self.extn: if len(self.extn) == 1: hdu = self.handle[self.extn[0]] else: hdu = self.handle[self.extn[0],self.extn[1]] else: ...
Opens the file for subsequent access.
def setup_locale(lc_all: str, first_weekday: int = None, *, lc_collate: str = None, lc_ctype: str = None, lc_messages: str = None, lc_monetary: str = None, lc_numeric: str = None, lc_t...
Shortcut helper to setup locale for backend application. :param lc_all: Locale to use. :param first_weekday: Weekday for start week. 0 for Monday, 6 for Sunday. By default: None :param lc_collate: Collate locale to use. By default: ``<lc_all>`` :param lc_ctype: Ctype locale to use. By default: ...
def delete(self): try: self.revert() except errors.ChangelistError: pass self._connection.run(['change', '-d', str(self._change)])
Reverts all files in this changelist then deletes the changelist from perforce
def remove_mapping(agent, prefix, ip): return _broadcast(agent, RemoveMappingManager, RecordType.record_A, prefix, ip)
Removes a mapping with a contract. It has high latency but gives some kind of guarantee.
def register_directory(self, directory, parent, ensure_uniqueness=False): if ensure_uniqueness: if self.get_directory_nodes(directory): raise foundations.exceptions.ProgrammingError("{0} | '{1}' directory is already registered!".format( self.__class__.__name__, di...
Registers given directory in the Model. :param directory: Directory to register. :type directory: unicode :param parent: DirectoryNode parent. :type parent: GraphModelNode :param ensure_uniqueness: Ensure registrar uniqueness. :type ensure_uniqueness: bool :retur...
def logout(self): from flask_login import logout_user, current_user if not current_user.is_authenticated: return True user = current_user events.logout_event.send(user) logout_user() app = current_app._get_current_object() identity_changed.send(app, id...
Logout user and emit event.
def _build(self, inputs, prev_state): next_state = self._model(prev_state) return next_state, next_state
Connects the ModelRNN module into the graph. If this is not the first time the module has been connected to the graph, the Tensors provided as input_ and state must have the same final dimension, in order for the existing variables to be the correct size for their corresponding multiplications. The bat...
def clear(self): for key in self.conn.keys(): self.conn.delete(key)
Helper for clearing all the keys in a database. Use with caution!
def push(self, read_time, next_resume_token): deletes, adds, updates = Watch._extract_changes( self.doc_map, self.change_map, read_time ) updated_tree, updated_map, appliedChanges = self._compute_snapshot( self.doc_tree, self.doc_map, deletes, adds, updates ) ...
Assembles a new snapshot from the current set of changes and invokes the user's callback. Clears the current changes on completion.
def node_label_absent(name, node, **kwargs): ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} labels = __salt__['kubernetes.node_labels'](node, **kwargs) if name not in labels: ret['result'] = True if not __opts__['test'] else None ret['com...
Ensures that the named label is absent from the node. name The name of the label node The name of the node
def show_wbridges(self): grp = self.getPseudoBondGroup("Water Bridges-%i" % self.tid, associateWith=[self.model]) grp.lineWidth = 3 for i, wbridge in enumerate(self.plcomplex.waterbridges): c = grp.newPseudoBond(self.atoms[wbridge.water_id], self.atoms[wbridge.acc_id]) c....
Visualizes water bridges
def get_snapshots_filename(impl, working_dir): snapshots_filename = impl.get_virtual_chain_name() + ".snapshots" return os.path.join(working_dir, snapshots_filename)
Get the absolute path to the chain's consensus snapshots file.
def name_to_system_object(self, name): if isinstance(name, str): if self.allow_name_referencing: name = name else: raise NameError('System.allow_name_referencing is set to False, cannot convert string to name') elif isinstance(name, Object): ...
Give SystemObject instance corresponding to the name
def write(self, data): self._check_can_write() compressed = self._compressor.compress(data) self._fp.write(compressed) self._pos += len(data) return len(data)
Write a bytes object to the file. Returns the number of uncompressed bytes written, which is always len(data). Note that due to buffering, the file on disk may not reflect the data written until close() is called.
def get_all_subnets(self, subnet_ids=None, filters=None): params = {} if subnet_ids: self.build_list_params(params, subnet_ids, 'SubnetId') if filters: i = 1 for filter in filters: params[('Filter.%d.Name' % i)] = filter[0] para...
Retrieve information about your Subnets. You can filter results to return information only about those Subnets that match your search parameters. Otherwise, all Subnets associated with your account are returned. :type subnet_ids: list :param subnet_ids: A list of strings with ...
def post(self, request, uri): uri = self.decode_uri(uri) data, meta = self.get_post_data(request) meta['author'] = auth.get_username(request) node = cio.set(uri, data, publish=False, **meta) return self.render_to_json(node)
Set node data for uri, return rendered content. JSON Response: {uri: x, content: y}
def copy(self): if self.object_getattr is Query.object_getattr: other = Query(self.key) else: other = Query(self.key, object_getattr=self.object_getattr) other.limit = self.limit other.offset = self.offset other.offset_key = self.offset_key other.filters = self.filters other.orde...
Returns a copy of this query.
def create(self): api = self._instance._client.database_admin_api metadata = _metadata_with_prefix(self.name) db_name = self.database_id if "-" in db_name: db_name = "`%s`" % (db_name,) future = api.create_database( parent=self._instance.name, ...
Create this database within its instance Inclues any configured schema assigned to :attr:`ddl_statements`. See https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.CreateDatabase :rtype: :class:`~google.api_core...
def isPeregrine(self): return isPeregrine(self.obj.id, self.obj.sign, self.obj.signlon)
Returns if this object is peregrine.
def _management_form(self): if self.is_bound: form = ConcurrentManagementForm(self.data, auto_id=self.auto_id, prefix=self.prefix) if not form.is_valid(): raise ValidationError('ManagementForm data is missing or has been tampere...
Returns the ManagementForm instance for this FormSet.
def _match_depth(self, sect, depth): while depth < sect.depth: if sect is sect.parent: raise SyntaxError() sect = sect.parent if sect.depth == depth: return sect raise SyntaxError()
Given a section and a depth level, walk back through the sections parents to see if the depth level matches a previous section. Return a reference to the right section, or raise a SyntaxError.
def list_firmware_manifests(self, **kwargs): kwargs = self._verify_sort_options(kwargs) kwargs = self._verify_filters(kwargs, FirmwareManifest, True) api = self._get_api(update_service.DefaultApi) return PaginatedResponse(api.firmware_manifest_list, lwrap_type=FirmwareManifest, **kwargs)
List all manifests. :param int limit: number of manifests to retrieve :param str order: sort direction of manifests when ordered by time. 'desc' or 'asc' :param str after: get manifests after given `image_id` :param dict filters: Dictionary of filters to apply :return: list of :...
def _consent_registration(self, consent_args): jws = JWS(json.dumps(consent_args), alg=self.signing_key.alg).sign_compact([self.signing_key]) request = "{}/creq/{}".format(self.api_url, jws) res = requests.get(request) if res.status_code != 200: raise UnexpectedResponseError(...
Register a request at the consent service :type consent_args: dict :rtype: str :param consent_args: All necessary parameters for the consent request :return: Ticket received from the consent service
def container_exists(self, id=None, name=None): exists = False if id and self.container_by_id(id): exists = True elif name and self.container_by_name(name): exists = True return exists
Checks if container exists already
def _load_dataframe(self, resource_name): try: import pandas except ImportError: raise RuntimeError('To enable dataframe support, ' 'run \'pip install datadotworld[pandas]\'') tabular_resource = self.__tabular_resources[resource_name] ...
Build pandas.DataFrame from resource data Lazy load any optional dependencies in order to allow users to use package without installing pandas if so they wish. :param resource_name:
def _build_query_string(q, default_field=None, default_operator='AND'): def _is_phrase_search(query_string): clean_query = query_string.strip() return clean_query and clean_query.startswith('"') and clean_query.endswith('"') def _get_phrase(query_string): return query_string.strip().stri...
Build ``query_string`` object from ``q``. :param q: q of type String :param default_field: default_field :return: dictionary object.
def _comic_archive_write_zipfile(new_filename, tmp_dir): if Settings.verbose: print('Rezipping archive', end='') with zipfile.ZipFile(new_filename, 'w', compression=zipfile.ZIP_DEFLATED) as new_zf: root_len = len(os.path.abspath(tmp_dir)) for r_d_f in os.walk(tmp...
Zip up the files in the tempdir into the new filename.
def read_transport(self): if ('r' not in self.access_type): raise BTIncompatibleTransportAccessType return self.codec.decode(self.fd, self.read_mtu)
Read data from media transport. The returned data payload is SBC decoded and has all RTP encapsulation removed. :return data: Payload data that has been decoded, with RTP encapsulation removed. :rtype: array{byte}
def add_options(self, path: str, handler: _WebHandler, **kwargs: Any) -> AbstractRoute: return self.add_route(hdrs.METH_OPTIONS, path, handler, **kwargs)
Shortcut for add_route with method OPTIONS
def build_model_input(cls, name='input'): return cls(name, PortDirection.INPUT, type=PortType.MODEL)
Build a model input port. :param name: port name :type name: str :return: port object :rtype: PortDef
def format_hsl(hsl_color): hue, saturation, lightness = hsl_color return 'hsl({}, {:.2%}, {:.2%})'.format(hue, saturation, lightness)
Format hsl color as css color string.
def results(self, Pc): r Psatn = self['pore.invasion_pressure'] <= Pc Tsatn = self['throat.invasion_pressure'] <= Pc inv_phase = {} inv_phase['pore.occupancy'] = sp.array(Psatn, dtype=float) inv_phase['throat.occupancy'] = sp.array(Tsatn, dtype=float) return inv_p...
r""" This method determines which pores and throats are filled with invading phase at the specified capillary pressure, and creates several arrays indicating the occupancy status of each pore and throat for the given pressure. Parameters ---------- Pc : scalar ...
def downloads_per_day(self): count, num_days = self._downloads_for_num_days(7) res = ceil(count / num_days) logger.debug("Downloads per day = (%d / %d) = %d", count, num_days, res) return res
Return the number of downloads per day, averaged over the past 7 days of data. :return: average number of downloads per day :rtype: int
def _calculate_weights(self, this_samples, N): this_weights = self.weights.append(N)[:,0] if self.target_values is None: for i in range(N): tmp = self.target(this_samples[i]) - self.proposal.evaluate(this_samples[i]) this_weights[i] = _exp(tmp) else: ...
Calculate and save the weights of a run.