code
stringlengths
51
2.38k
docstring
stringlengths
4
15.2k
def sync_objects_in(self): self.dstate = self.STATES.BUILDING self.build_source_files.record_to_objects()
Synchronize from records to objects
def serve(application, host='127.0.0.1', port=8080): WSGIServer((host, int(port)), application).serve_forever()
Gevent-based WSGI-HTTP server.
def subtype(self, **kwargs): initializers = self.readOnly.copy() cloneValueFlag = kwargs.pop('cloneValueFlag', False) implicitTag = kwargs.pop('implicitTag', None) if implicitTag is not None: initializers['tagSet'] = self.tagSet.tagImplicitly(implicitTag) explicitTag ...
Create a specialization of |ASN.1| schema object. The `subtype()` method accepts the same set arguments as |ASN.1| class takes on instantiation except that all parameters of the `subtype()` method are optional. With the exception of the arguments described below, the rest of su...
def write_configs(self): utils.banner("Generating Configs") if not self.runway_dir: app_configs = configs.process_git_configs(git_short=self.git_short) else: app_configs = configs.process_runway_configs(runway_dir=self.runway_dir) self.configs = configs.write_vari...
Generate the configurations needed for pipes.
def pesn(number, separator=u''): number = re.sub(r'[\s-]', '', meid(number)) serial = hashlib.sha1(unhexlify(number[:14])) return separator.join(['80', serial.hexdigest()[-6:].upper()])
Printable Pseudo Electronic Serial Number. :param number: hexadecimal string >>> print(pesn('1B69B4BA630F34E')) 805F9EF7
def post_url(self, url, form): _r = self.br.open(url, form.click_request_data()[1]) if self.br.geturl().startswith(self.AUTH_URL): raise AuthRequiredException elif self.br.geturl().startswith(self.ERROR_URL): raise RequestErrorException else: return _r...
Internally used to retrieve the contents of a URL using the POST request method. The `form` parameter is a mechanize.HTMLForm object This method will use a POST request type regardless of the method used in the `form`.
def set_register(self, register, value): context = self.get_context() context[register] = value self.set_context(context)
Sets the value of a specific register. @type register: str @param register: Register name. @rtype: int @return: Register value.
def validate_custom_interpreters_list(self): custom_list = self.get_option('custom_interpreters_list') valid_custom_list = [] for value in custom_list: if (osp.isfile(value) and programs.is_python_interpreter(value) and value != get_python_executable()): ...
Check that the used custom interpreters are still valid.
def validate_version(self, service_id, version_number): content = self._fetch("/service/%s/version/%d/validate" % (service_id, version_number)) return self._status(content)
Validate the version for a particular service and version.
def meta_manager_view(request): managers = Manager.objects.all() return render_to_response('meta_manager.html', { 'page_name': "Admin - Meta-Manager", 'managerset': managers, }, context_instance=RequestContext(request))
A manager of managers. Display a list of current managers, with links to modify them. Also display a link to add a new manager. Restricted to presidents and superadmins.
def percent_of_the_time(p): def decorator(fn): def wrapped(*args, **kwargs): if in_percentage(p): fn(*args, **kwargs) return wrapped return decorator
Function has a X percentage chance of running
async def cancel(self, task: asyncio.Task, wait_for: bool = True) -> Any: if task is None: return task.cancel() with suppress(KeyError): self._tasks.remove(task) with suppress(Exception): return (await task) if wait_for else None
Cancels and waits for an `asyncio.Task` to finish. Removes it from the collection of managed tasks. Args: task (asyncio.Task): The to be cancelled task. It is not required that the task was was created with `TaskScheduler.create_task()`. wait_for...
def used_by(self, bundle): if bundle is None or bundle is self.__bundle: return with self.__usage_lock: self.__using_bundles.setdefault(bundle, _UsageCounter()).inc()
Indicates that this reference is being used by the given bundle. This method should only be used by the framework. :param bundle: A bundle using this reference
def limit_spec(self, spec): if list(spec.keys()) == ['name']: return ((Q(name=spec['name']) | Q(other_names__name=spec['name'])) & Q(memberships__organization__jurisdiction_id=self.jurisdiction_id)) spec['memberships__organization__jurisdiction_id'] = self.jurisdiction_id...
Whenever we do a Pseudo ID lookup from the database, we need to limit based on the memberships -> organization -> jurisdiction, so we scope the resolution.
def node_slider(self, seed=None): prop = 0.999 assert isinstance(prop, float), "prop must be a float" assert prop < 1, "prop must be a proportion >0 and < 1." random.seed(seed) ctree = self._ttree.copy() for node in ctree.treenode.traverse(): if node.up and no...
Returns a toytree copy with node heights modified while retaining the same topology but not necessarily node branching order. Node heights are moved up or down uniformly between their parent and highest child node heights in 'levelorder' from root to tips. The total tree height is ret...
def get_file(self, file, **kwargs): file_id = obj_or_id(file, "file", (File,)) response = self.__requester.request( 'GET', 'files/{}'.format(file_id), _kwargs=combine_kwargs(**kwargs) ) return File(self.__requester, response.json())
Return the standard attachment json object for a file. :calls: `GET /api/v1/files/:id \ <https://canvas.instructure.com/doc/api/files.html#method.files.api_show>`_ :param file: The object or ID of the file to retrieve. :type file: :class:`canvasapi.file.File` or int :rtype: :c...
def _analyse(self, table=''): self._logger.info('Starting analysis of database') self._conn.execute(constants.ANALYSE_SQL.format(table)) self._logger.info('Analysis of database complete')
Analyses the database, or `table` if it is supplied. :param table: optional name of table to analyse :type table: `str`
def dms_to_decimal(degrees, minutes, seconds, hemisphere): dms = float(degrees) + float(minutes) / 60 + float(seconds) / 3600 if hemisphere in "WwSs": dms = -1 * dms return dms
Convert from degrees, minutes, seconds to decimal degrees. @author: mprins
def endswith(self, suffix): return ArrayPredicate( term=self, op=LabelArray.endswith, opargs=(suffix,), )
Construct a Filter matching values ending with ``suffix``. Parameters ---------- suffix : str String suffix against which to compare values produced by ``self``. Returns ------- matches : Filter Filter returning True for all sid/date pairs for wh...
def mxvg(m1, v2, nrow1, nc1r2): m1 = stypes.toDoubleMatrix(m1) v2 = stypes.toDoubleVector(v2) nrow1 = ctypes.c_int(nrow1) nc1r2 = ctypes.c_int(nc1r2) vout = stypes.emptyDoubleVector(nrow1.value) libspice.mxvg_c(m1, v2, nrow1, nc1r2, vout) return stypes.cVectorToPython(vout)
Multiply a matrix and a vector of arbitrary size. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/mxvg_c.html :param m1: Left-hand matrix to be multiplied. :type m1: NxM-Element Array of floats :param v2: Right-hand vector to be multiplied. :type v2: Array of floats :param nrow1: Row d...
def configure_logger(self, name, config, incremental=False): logger = logging.getLogger(name) self.common_logger_config(logger, config, incremental) propagate = config.get('propagate', None) if propagate is not None: logger.propagate = propagate
Configure a non-root logger from a dictionary.
def get_assessment_taken_admin_session(self, proxy): if not self.supports_assessment_taken_admin(): raise errors.Unimplemented() return sessions.AssessmentTakenAdminSession(proxy=proxy, runtime=self._runtime)
Gets the ``OsidSession`` associated with the assessment taken administration service. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.assessment.AssessmentTakenAdminSession) - an ``AssessmentTakenAdminSession`` raise: NullArgument - ``proxy`` is ``null`` raise: ...
def locate_file(start_path, file_name): if os.path.isfile(start_path): start_dir_path = os.path.dirname(start_path) elif os.path.isdir(start_path): start_dir_path = start_path else: raise exceptions.FileNotFound("invalid path: {}".format(start_path)) file_path = os.path.join(star...
locate filename and return absolute file path. searching will be recursive upward until current working directory. Args: start_path (str): start locating path, maybe file path or directory path Returns: str: located file path. None if file not found. Raises: exceptions.Fil...
def autocrop(im, bgcolor): "Crop away a border of the given background color." if im.mode != "RGB": im = im.convert("RGB") bg = Image.new("RGB", im.size, bgcolor) diff = ImageChops.difference(im, bg) bbox = diff.getbbox() if bbox: return im.crop(bbox) return im
Crop away a border of the given background color.
def _readline_echo(self, char, echo): if self._readline_do_echo(echo): self.write(char)
Echo a recieved character, move cursor etc...
def as_block_string(txt): import json lines = [] for line in txt.split('\n'): line_ = json.dumps(line) line_ = line_[1:-1].rstrip() lines.append(line_) return '' % '\n'.join(lines)
Return a string formatted as a python block comment string, like the one you're currently reading. Special characters are escaped if necessary.
def adev(self, tau0, tau): prefactor = self.adev_from_qd(tau0=tau0, tau=tau) c = self.c_avar() avar = pow(prefactor, 2)*pow(tau, c) return np.sqrt(avar)
return predicted ADEV of noise-type at given tau
def remove_grad_hooks(module, input): for hook in list(module.param_hooks.keys()): module.param_hooks[hook].remove() module.param_hooks.pop(hook) for hook in list(module.var_hooks.keys()): module.var_hooks[hook].remove() module.var_hooks.pop(hook)
Remove gradient hooks to all of the parameters and monitored vars
def subset(self, used_indices, params=None): if params is None: params = self.params ret = Dataset(None, reference=self, feature_name=self.feature_name, categorical_feature=self.categorical_feature, params=params, free_raw_data=self.free_raw_data) ...
Get subset of current Dataset. Parameters ---------- used_indices : list of int Indices used to create the subset. params : dict or None, optional (default=None) These parameters will be passed to Dataset constructor. Returns ------- subs...
def has(self, block, name): try: self.get(block, name) return True except KeyError: return False
Return whether or not the field named `name` has a non-default value for the XBlock `block`. :param block: block to check :type block: :class:`~xblock.core.XBlock` :param name: field name :type name: str
def set_password(url, ownerToken, password): service, fileId, key = sendclient.common.splitkeyurl(url) rawKey = sendclient.common.unpadded_urlsafe_b64decode(key) keys = sendclient.common.secretKeys(rawKey, password, url) return api_password(service, fileId, ownerToken, keys.newAuthKey)
set or change the password required to download a file hosted on a send server.
def stats_tube(self, tube_name): with self._sock_ctx() as socket: self._send_message('stats-tube {0}'.format(tube_name), socket) body = self._receive_data_with_prefix(b'OK', socket) return yaml_load(body)
Fetch statistics about a single tube :param tube_name: Tube to fetch stats about :rtype: dict
def rev(self, i): on = copy(self) on.revision = i return on
Return a clone with a different revision.
def _dump_multilinestring(obj, big_endian, meta): coords = obj['coordinates'] vertex = coords[0][0] num_dims = len(vertex) wkb_string, byte_fmt, byte_order = _header_bytefmt_byteorder( 'MultiLineString', num_dims, big_endian, meta ) ls_type = _WKB[_INT_TO_DIM_LABEL.get(num_dims)]['LineSt...
Dump a GeoJSON-like `dict` to a multilinestring WKB string. Input parameters and output are similar to :funct:`_dump_point`.
def delete_object(self, container, obj, **kwargs): try: LOG.debug('delete_object() with %s is success.', self.driver) return self.driver.delete_object(container, obj, **kwargs) except DriverException as e: LOG.exception('download_object() with %s raised\ ...
Delete object in container :param container: container name (Container is equivalent to Bucket term in Amazon). :param obj: object name (Object is equivalent to Key term in Amazon).
def validate (self): if not os.path.isfile(self.pathname): self.message.append('Filename "%s" does not exist.') else: try: with open(self.pathname, 'r') as stream: pass except IOError: self.messages.append('Could not open "%s" for reading.' % self.pathname) for li...
Returns True if this Sequence is valid, False otherwise. Validation error messages are stored in self.messages.
def get_standard_package(self, server_id, is_virt=True): firewall_port_speed = self._get_fwl_port_speed(server_id, is_virt) _value = "%s%s" % (firewall_port_speed, "Mbps Hardware Firewall") _filter = {'items': {'description': utils.query_filter(_value)}} return self.prod_pkg.getItems(id=...
Retrieves the standard firewall package for the virtual server. :param int server_id: The ID of the server to create the firewall for :param bool is_virt: True if the ID provided is for a virtual server, False for a server :returns: A dictionary containing the stand...
def str_brief(obj, lim=20, dots='...', use_repr=True): if isinstance(obj, basestring) or not use_repr: full = str(obj) else: full = repr(obj) postfix = [] CLOSERS = {'(': ')', '{': '}', '[': ']', '"': '"', "'": "'", '<': '>'} for i, c in enumerate(full): if i >= lim + len(pos...
Truncates a string, starting from 'lim' chars. The given object can be a string, or something that can be casted to a string. >>> import string >>> str_brief(string.uppercase) 'ABCDEFGHIJKLMNOPQRST...' >>> str_brief(2 ** 50, lim=10, dots='0') '11258999060'
def load_csv(filename, dialect='excel', encoding='utf-8'): return Context.fromfile(filename, 'csv', encoding, dialect=dialect)
Load and return formal context from CSV file. Args: filename: Path to the CSV file to load the context from. dialect: Syntax variant of the CSV file (``'excel'``, ``'excel-tab'``). encoding (str): Encoding of the file (``'utf-8'``, ``'latin1'``, ``'ascii'``, ...). Example: >>> ...
def RGB_to_HSL(cobj, *args, **kwargs): var_R = cobj.rgb_r var_G = cobj.rgb_g var_B = cobj.rgb_b var_max = max(var_R, var_G, var_B) var_min = min(var_R, var_G, var_B) var_H = __RGB_to_Hue(var_R, var_G, var_B, var_min, var_max) var_L = 0.5 * (var_max + var_min) if var_max == var_min: ...
Converts from RGB to HSL. H values are in degrees and are 0 to 360. S values are a percentage, 0.0 to 1.0. L values are a percentage, 0.0 to 1.0.
def clean(self, force: bool=False): assert not self._closed with (yield from self._host_pools_lock): for key, pool in tuple(self._host_pools.items()): yield from pool.clean(force=force) if not self._host_pool_waiters[key] and pool.empty(): ...
Clean all closed connections. Args: force: Clean connected and idle connections too. Coroutine.
async def send_files_preconf(filepaths, config_path=CONFIG_PATH): config = read_config(config_path) subject = "PDF files from pdfebc" message = "" await send_with_attachments(subject, message, filepaths, config)
Send files using the config.ini settings. Args: filepaths (list(str)): A list of filepaths.
def get_n_header(f, header_char='"'): n_header = 0 reading_headers = True while reading_headers: line = f.readline() if line.startswith(header_char): n_header += 1 else: reading_headers = False return n_header
Get the nummber of header rows in a Little Leonardo data file Args ---- f : file stream File handle for the file from which header rows will be read header_char: str Character array at beginning of each header line Returns ------- n_header: int Number of header rows...
def cms_identify(self, url, timeout=15, headers={}): self.out.debug("cms_identify") if isinstance(self.regular_file_url, str): rfu = [self.regular_file_url] else: rfu = self.regular_file_url is_cms = False for regular_file_url in rfu: try: ...
Function called when attempting to determine if a URL is identified as being this particular CMS. @param url: the URL to attempt to identify. @param timeout: number of seconds before a timeout occurs on a http connection. @param headers: custom HTTP headers as expected by req...
def _index_classes(self) -> Dict[Text, Type[Platform]]: out = {} for p in get_platform_settings(): cls: Type[Platform] = import_class(p['class']) if 'name' in p: out[p['name']] = cls else: out[cls.NAME] = cls return out
Build a name index for all platform classes
def to_index(self, index_type, index_name, includes=None): return IndexField(self.name, self.data_type, index_type, index_name, includes)
Create an index field from this field
def is_encrypted_account(self, id): for key in self.secured_field_names: if not self.parser.is_secure_option(id, key): return False return True
Are all fields for the account id encrypted?
def invite_others_to_group(self, group_id, invitees): path = {} data = {} params = {} path["group_id"] = group_id data["invitees"] = invitees self.logger.debug("POST /api/v1/groups/{group_id}/invite with query params: {params} and form data: {data}".format(params=pa...
Invite others to a group. Sends an invitation to all supplied email addresses which will allow the receivers to join the group.
def factory(self, request, parent=None, name=None): traverse = request.matchdict['traverse'] if not traverse: return {} else: service = {} name = name or traverse[0] traversed = '/' + '/'.join(traverse) service_type = None s...
Returns a new service for the given request. :param request | <pyramid.request.Request> :return <pyramid_restful.services.AbstractService>
def get_string_plus_property_value(value): if value: if isinstance(value, str): return [value] if isinstance(value, list): return value if isinstance(value, tuple): return list(value) return None
Converts a string or list of string into a list of strings :param value: A string or a list of strings :return: A list of strings or None
def _pnorm_diagweight(x, p, w): order = 'F' if all(a.flags.f_contiguous for a in (x.data, w)) else 'C' xp = np.abs(x.data.ravel(order)) if p == float('inf'): xp *= w.ravel(order) return np.max(xp) else: xp = np.power(xp, p, out=xp) xp *= w.ravel(order) return np.s...
Diagonally weighted p-norm implementation.
def compute_hash(attributes, ignored_attributes=None): ignored_attributes = list(ignored_attributes) if ignored_attributes else [] tuple_attributes = _convert(attributes.copy(), ignored_attributes) hasher = hashlib.sha256(str(tuple_attributes).encode('utf-8', errors='ignore')) return hasher.hexdigest()
Computes a hash code for the given dictionary that is safe for persistence round trips
def uninstall_handler(self, event_type, handler, user_handle=None): self.visalib.uninstall_visa_handler(self.session, event_type, handler, user_handle)
Uninstalls handlers for events in this resource. :param event_type: Logical event identifier. :param handler: Interpreted as a valid reference to a handler to be uninstalled by a client application. :param user_handle: The user handle (ctypes object or None) returned by install_handler.
def create_team(self, name, repo_names=[], permission=''): data = {'name': name, 'repo_names': repo_names, 'permission': permission} url = self._build_url('teams', base_url=self._api) json = self._json(self._post(url, data), 201) return Team(json, self._session) if json e...
Assuming the authenticated user owns this organization, create and return a new team. :param str name: (required), name to be given to the team :param list repo_names: (optional) repositories, e.g. ['github/dotfiles'] :param str permission: (optional), options: ...
def angles(triangles): u = triangles[:, 1] - triangles[:, 0] v = triangles[:, 2] - triangles[:, 0] w = triangles[:, 2] - triangles[:, 1] u /= np.linalg.norm(u, axis=1, keepdims=True) v /= np.linalg.norm(v, axis=1, keepdims=True) w /= np.linalg.norm(w, axis=1, keepdims=True) a = np.arccos(np....
Calculates the angles of input triangles. Parameters ------------ triangles : (n, 3, 3) float Vertex positions Returns ------------ angles : (n, 3) float Angles at vertex positions, in radians
def hexbin(x, y, size, orientation="pointytop", aspect_scale=1): pd = import_required('pandas','hexbin requires pandas to be installed') q, r = cartesian_to_axial(x, y, size, orientation, aspect_scale=aspect_scale) df = pd.DataFrame(dict(r=r, q=q)) return df.groupby(['q', 'r']).size().reset_index(name='...
Perform an equal-weight binning of data points into hexagonal tiles. For more sophisticated use cases, e.g. weighted binning or scaling individual tiles proportional to some other quantity, consider using HoloViews. Args: x (array[float]) : A NumPy array of x-coordinates for binnin...
def flipGenotype(genotype): newGenotype = set() for allele in genotype: if allele == "A": newGenotype.add("T") elif allele == "C": newGenotype.add("G") elif allele == "T": newGenotype.add("A") elif allele == "G": newGenotype.add("C"...
Flips a genotype. :param genotype: the genotype to flip. :type genotype: set :returns: the new flipped genotype (as a :py:class:`set`) .. testsetup:: from pyGenClean.DupSNPs.duplicated_snps import flipGenotype .. doctest:: >>> flipGenotype({"A", "T"}) set(['A', 'T']) ...
def clean(self, force: bool=False): with (yield from self._lock): for connection in tuple(self.ready): if force or connection.closed(): connection.close() self.ready.remove(connection)
Clean closed connections. Args: force: Clean connected and idle connections too. Coroutine.
def coerce(val: t.Any, coerce_type: t.Optional[t.Type] = None, coercer: t.Optional[t.Callable] = None) -> t.Any: if not coerce_type and not coercer: return val if coerce_type and type(val) is coerce_type: return val if coerce_type and coerce_...
Casts a type of ``val`` to ``coerce_type`` with ``coercer``. If ``coerce_type`` is bool and no ``coercer`` specified it uses :func:`~django_docker_helpers.utils.coerce_str_to_bool` by default. :param val: a value of any type :param coerce_type: any type :param coercer: provide ...
def force_string(val=None): if val is None: return '' if isinstance(val, list): newval = [str(x) for x in val] return ';'.join(newval) if isinstance(val, str): return val else: return str(val)
Force a string representation of an object Args: val: object to parse into a string Returns: str: String representation
def remove_from_queue(self, series): result = self._android_api.remove_from_queue(series_id=series.series_id) return result
Remove a series from the queue @param crunchyroll.models.Series series @return bool
def unarmor(pem_bytes, multiple=False): generator = _unarmor(pem_bytes) if not multiple: return next(generator) return generator
Convert a PEM-encoded byte string into a DER-encoded byte string :param pem_bytes: A byte string of the PEM-encoded data :param multiple: If True, function will return a generator :raises: ValueError - when the pem_bytes do not appear to be PEM-encoded bytes :return: ...
def _thread_worker(self): while self._running: packet = self._queue.get(True) if isinstance(packet, dict) and QS_CMD in packet: try: self._callback_listen(packet) except Exception as err: _LOGGER.error("Exception in ...
Process callbacks from the queue populated by &listen.
def exchange_reference(root_url, service, version): root_url = root_url.rstrip('/') if root_url == OLD_ROOT_URL: return 'https://references.taskcluster.net/{}/{}/exchanges.json'.format(service, version) else: return '{}/references/{}/{}/exchanges.json'.format(root_url, service, version)
Generate URL for a Taskcluster exchange reference.
def main(): try: pkg_version = Update() if pkg_version.updatable(): pkg_version.show_message() metadata = control.retreive_metadata() parser = parse_options(metadata) argvs = sys.argv if len(argvs) <= 1: parser.print_help() sys.exit...
Execute main processes.
def get_token(self): if self.__token is not None: return self.__token url = "https://api.neur.io/v1/oauth2/token" creds = b64encode(":".join([self.__key,self.__secret]).encode()).decode() headers = { "Authorization": " ".join(["Basic", creds]), } payload = { "grant_type": "clie...
Performs Neurio API token authentication using provided key and secret. Note: This method is generally not called by hand; rather it is usually called as-needed by a Neurio Client object. Returns: string: the access token
def _add_task(self, task): if hasattr(task, '_task_group'): raise RuntimeError('task is already part of a group') if self._closed: raise RuntimeError('task group is closed') task._task_group = self if task.done(): self._done.append(task) else: ...
Add an already existing task to the task group.
def _write(self, session, openFile, replaceParamFile): openFile.write(text(self.projection))
Projection File Write to File Method
def _is_valid_netmask(self, netmask): mask = netmask.split('.') if len(mask) == 4: try: for x in mask: if int(x) not in self._valid_mask_octets: return False except ValueError: return False fo...
Verify that the netmask is valid. Args: netmask: A string, either a prefix or dotted decimal netmask. Returns: A boolean, True if the prefix represents a valid IPv4 netmask.
def _load_single_patient_cufflinks(self, patient, filter_ok): data = pd.read_csv(patient.tumor_sample.cufflinks_path, sep="\t") data["patient_id"] = patient.id if filter_ok: data = data[data["FPKM_status"] == "OK"] return data
Load Cufflinks gene quantification given a patient Parameters ---------- patient : Patient filter_ok : bool, optional If true, filter Cufflinks data to row with FPKM_status == "OK" Returns ------- data: Pandas dataframe Pandas dataframe o...
def _action_get(self, ids): if not ids: ids = self.jobs result = [] ids = set(ids) while ids: id_ = ids.pop() if id_ is None: continue try: payload = r_client.get(id_) except ResponseError: ...
Get the details for ids Parameters ---------- ids : {list, set, tuple, generator} of str The IDs to get Notes ----- If ids is empty, then all IDs are returned. Returns ------- list of dict The details of the jobs
def parse_document(xmlcontent): document = etree.fromstring(xmlcontent) body = document.xpath('.//w:body', namespaces=NAMESPACES)[0] document = doc.Document() for elem in body: if elem.tag == _name('{{{w}}}p'): document.elements.append(parse_paragraph(document, elem)) if elem...
Parse document with content. Content is placed in file 'document.xml'.
def populateFromRow(self, ontologyRecord): self._id = ontologyRecord.id self._dataUrl = ontologyRecord.dataurl self._readFile()
Populates this Ontology using values in the specified DB row.
def lambert_xticks(ax, ticks): te = lambda xy: xy[0] lc = lambda t, n, b: np.vstack((np.zeros(n) + t, np.linspace(b[2], b[3], n))).T xticks, xticklabels = _lambert_ticks(ax, ticks, 'bottom', lc, te) ax.xaxis.tick_bottom() ax.set_xticks(xticks) ax.set_xticklabels([ax.xaxis.get_major_formatter()(x...
Draw ticks on the bottom x-axis of a Lambert Conformal projection.
def get_label(self, code): for style in self.styles: if style[1] == code: return style[0] msg = _("Code {code} is invalid.").format(code=code) raise ValueError(msg)
Returns string label for given code string Inverse of get_code Parameters ---------- code: String \tCode string, field 1 of style tuple
def images(self): for ds_id, projectable in self.datasets.items(): if ds_id in self.wishlist: yield projectable.to_image()
Generate images for all the datasets from the scene.
def walknset_vars(self, task_class=None, *args, **kwargs): def change_task(task): if task_class is not None and task.__class__ is not task_class: return False return True if self.is_work: for task in self: if not change_task(task): continue ...
Set the values of the ABINIT variables in the input files of the nodes Args: task_class: If not None, only the input files of the tasks belonging to class `task_class` are modified. Example: flow.walknset_vars(ecut=10, kptopt=4)
def CallApiHandler(handler, args, token=None): result = handler.Handle(args, token=token) expected_type = handler.result_type if expected_type is None: expected_type = None.__class__ if result.__class__ != expected_type: raise UnexpectedResultTypeError( "Expected %s, but got %s." %...
Handles API call to a given handler with given args and token.
def assert_is_not_substring(substring, subject, message=None, extra=None): assert ( (subject is not None) and (substring is not None) and (subject.find(substring) == -1) ), _assert_fail_message(message, substring, subject, "is in", extra)
Raises an AssertionError if substring is a substring of subject.
def getChildrenInfo(self): print '%s call getChildrenInfo' % self.port try: childrenInfoAll = [] childrenInfo = {'EUI': 0, 'Rloc16': 0, 'MLEID': ''} childrenList = self.__sendCommand('child list')[0].split() print childrenList if 'Done' in chil...
get all children information Returns: children's extended address
def validateaddress(self, address: str) -> bool: "Returns True if the passed address is valid, False otherwise." try: Address.from_string(address, self.network_properties) except InvalidAddress: return False return True
Returns True if the passed address is valid, False otherwise.
def cfgGetBool(theObj, name, dflt): strval = theObj.get(name, None) if strval is None: return dflt return strval.lower().strip() == 'true'
Get a stringified val from a ConfigObj obj and return it as bool
def from_google(cls, google_x, google_y, zoom): max_tile = (2 ** zoom) - 1 assert 0 <= google_x <= max_tile, 'Google X needs to be a value between 0 and (2^zoom) -1.' assert 0 <= google_y <= max_tile, 'Google Y needs to be a value between 0 and (2^zoom) -1.' return cls(tms_x=google_x, tm...
Creates a tile from Google format X Y and zoom
def submit_by_selector(self, selector): elem = find_element_by_jquery(world.browser, selector) elem.submit()
Submit the form matching the CSS selector.
def _nodedev_event_update_cb(conn, dev, opaque): _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': opaque['event'] })
Node device update events handler
def make_reader_task(self, stream, callback): return self.loop.create_task(self.executor_wrapper(background_reader, stream, self.loop, callback))
Create a reader executor task for a stream.
def grant_user_access(self, user, db_names, strict=True): user = utils.get_name(user) uri = "/%s/%s/databases" % (self.uri_base, user) db_names = self._get_db_names(db_names, strict=strict) dbs = [{"name": db_name} for db_name in db_names] body = {"databases": dbs} try: ...
Gives access to the databases listed in `db_names` to the user. You may pass in either a single db or a list of dbs. If any of the databases do not exist, a NoSuchDatabase exception will be raised, unless you specify `strict=False` in the call.
def add_redistribution(self, protocol, route_map_name=None): protocols = ['bgp', 'rip', 'static', 'connected'] if protocol not in protocols: raise ValueError('redistributed protocol must be' 'bgp, connected, rip or static') if route_map_name is None: ...
Adds a protocol redistribution to OSPF Args: protocol (str): protocol to redistribute route_map_name (str): route-map to be used to filter the protocols Returns: bool: True if the command completes successfully ...
def evaluate(self, dataset): if dataset is None: values = [self.f_eval()] else: values = [self.f_eval(*x) for x in dataset] monitors = zip(self._monitor_names, np.mean(values, axis=0)) return collections.OrderedDict(monitors)
Evaluate the current model parameters on a dataset. Parameters ---------- dataset : :class:`Dataset <downhill.dataset.Dataset>` A set of data to use for evaluating the model. Returns ------- monitors : OrderedDict A dictionary mapping monitor nam...
def find(cls, dtype): try: return cls._member_map_[dtype] except KeyError: try: dtype = numpy.dtype(dtype).type except TypeError: for ndstype in cls._member_map_.values(): if ndstype.value is dtype: ...
Returns the NDS2 type corresponding to the given python type
def _process_info(self): if not self._process: return [] output, error = self._process.communicate(timeout=5) if error is None: error = b"" output = output.decode("utf-8").strip() error = error.decode("utf-8").strip() info = (u"returncode: %r\n" ...
Return details about the fake process.
def loadACatalog(filename): ret = libxml2mod.xmlLoadACatalog(filename) if ret is None:raise treeError('xmlLoadACatalog() failed') return catalog(_obj=ret)
Load the catalog and build the associated data structures. This can be either an XML Catalog or an SGML Catalog It will recurse in SGML CATALOG entries. On the other hand XML Catalogs are not handled recursively.
def highlightBlock(self, text): if self._allow_highlight: start = self.previousBlockState() + 1 end = start + len(text) for i, (fmt, letter) in enumerate(self._charlist[start:end]): self.setFormat(i, 1, fmt) self.setCurrentBlockState(end) ...
Actually highlight the block
def login(self, email, password): response = FlightData.session.post( url=LOGIN_URL, data={ 'email': email, 'password': password, 'remember': 'true', 'type': 'web' }, headers={ 'Origin...
Login to the flightradar24 session The API currently uses flightradar24 as the primary data source. The site provides different levels of data based on user plans. For users who have signed up for a plan, this method allows to login with the credentials from flightradar24. The API obtains a tok...
def terminate(self, instances, count=0): if not instances: return if count > 0: instances = self._scale_down(instances, count) self.ec2.terminate_instances([i.id for i in instances])
Terminate each provided running or stopped instance. :param count: :param instances: A list of instances. :type instances: list
def check(self, targets, topological_order=False): all_vts = self.wrap_targets(targets, topological_order=topological_order) invalid_vts = [vt for vt in all_vts if not vt.valid] return InvalidationCheck(all_vts, invalid_vts)
Checks whether each of the targets has changed and invalidates it if so. Returns a list of VersionedTargetSet objects (either valid or invalid). The returned sets 'cover' the input targets, with one caveat: if the FingerprintStrategy opted out of fingerprinting a target because it doesn't contribute to inv...
def most_frequent_terms(self, depth): counts = self.term_counts() top_terms = set(list(counts.keys())[:depth]) end_count = list(counts.values())[:depth][-1] bucket = self.term_count_buckets()[end_count] return top_terms.union(set(bucket))
Get the X most frequent terms in the text, and then probe down to get any other terms that have the same count as the last term. Args: depth (int): The number of terms. Returns: set: The set of frequent terms.
def to_char(token): if ord(token) in _range(9216, 9229 + 1): token = _unichr(ord(token) - 9216) return token
Transforms the ASCII control character symbols to their real char. Note: If the token is not an ASCII control character symbol, just return the token. Keyword arguments: token -- the token to transform
def fast_exit(code): sys.stdout.flush() sys.stderr.flush() os._exit(code)
Exit without garbage collection, this speeds up exit by about 10ms for things like bash completion.
def link_text(cls): link = cls.__name__ if link.endswith('View'): link = link[:-4] return link
Return link text for this view.