Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
348,500
async def get_creds(self) -> dict: if not hasattr(DisclosedProof.get_creds, "cb"): self.logger.debug("vcx_disclosed_proof_retrieve_credentials: Creating callback") DisclosedProof.get_creds.cb = create_cb(CFUNCTYPE(None, c_uint32, c_uint32, c_char_p)) c_disclosed_proof_h...
Gets the credentials from a disclosed proof Example: msg_id = '1' phone_number = '8019119191' connection = await Connection.create(source_id) await connection.connect(phone_number) disclosed_proof = await DisclosedProof.create_with_msgid(source_id, connection, msg_id) ...
348,501
def pop_front(self): backend = self.backend return backend.execute(backend.structure(self).pop_front(), self.value_pickler.loads)
Remove the first element from of the list.
348,502
def forwardCheck(self, variables, domains, assignments, _unassigned=Unassigned): unassignedvariable = _unassigned for variable in variables: if variable not in assignments: if unassignedvariable is _unassigned: unassignedvariable = variable ...
Helper method for generic forward checking Currently, this method acts only when there's a single unassigned variable. @param variables: Variables affected by that constraint, in the same order provided by the user @type variables: sequence @param dom...
348,503
def _lincomb_impl(a, x1, b, x2, out): import scipy.linalg size = native(x1.size) if size < THRESHOLD_SMALL: out.data[:] = a * x1.data + b * x2.data return elif (size < THRESHOLD_MEDIUM or not _blas_is_applicable(x1.data, x2.data, out.data)): def f...
Optimized implementation of ``out[:] = a * x1 + b * x2``.
348,504
def getEmpTraitCovar(self): if self.P==1: out=self.Y[self.Iok].var() else: out=SP.cov(self.Y[self.Iok].T) return out
Returns the empirical trait covariance matrix
348,505
def to_geopoint(self): if self._lon is None or self._lat is None: return None return geo.Point(self._lon, self._lat)
Returns the geoJSON compliant representation of this location :returns: a ``pyowm.utils.geo.Point`` instance
348,506
def out_of_date(original, derived): return (not os.path.exists(derived) or os.stat(derived).st_mtime < os.stat(original).st_mtime)
Returns True if derivative is out-of-date wrt original, both of which are full file paths.
348,507
def move_folder(self, to_folder): if self.root: return False if not to_folder: return False url = self.build_url( self._endpoints.get().format(id=self.folder_id)) if isinstance(to_folder, ContactFolder): folder_id = to_folder.fol...
Change this folder name :param to_folder: folder_id/ContactFolder to move into :type to_folder: str or ContactFolder :return: Moved or Not :rtype: bool
348,508
def wait_for_jobs(self, job_ids, timeout, delay): if self.skip: return logger.debug("Waiting up to %d sec for completion of the job IDs %s", timeout, job_ids) remaining_job_ids = set(job_ids) found_jobs = [] countdown = timeout while countdown > 0:...
Waits until the jobs appears in the completed job queue.
348,509
def import_sanitizer(sanitizer): directory = os.path.dirname(sanitizer) not directory in sys.path and sys.path.append(directory) namespace = __import__(foundations.strings.get_splitext_basename(sanitizer)) if hasattr(namespace, "bleach"): return namespace else: raise foundatio...
Imports the sanitizer python module. :param sanitizer: Sanitizer python module file. :type sanitizer: unicode :return: Module. :rtype: object
348,510
def getlogger(pkg=, handler=None): from .caller import caller if not pkg: m = caller.modulename() s = m.split(, 1) if len(s) > 1: pkg = s[0] if haslogger(pkg): return logging.getLogger(pkg) else: logger = logging.getLogger(pkg) ...
패키지 혹은 채널 로거 logging.getLogger(package_name) or logg.getLogger() :param pkg: str
348,511
def slug_sub(match): level = match.group(1) title = match.group(2) slug = title.lower() slug = re.sub(r, , slug) slug = re.sub(r, , slug).strip() slug = slug.replace(, ) if slug: return .format(level, slug, title) return match.group(0)
Assigns id-less headers a slug that is derived from their titles. Slugs are generated by lower-casing the titles, stripping all punctuation, and converting spaces to hyphens (-).
348,512
def get_user_details(self, response): result = { : response[self.ENV_USERNAME], : response.get(self.ENV_EMAIL, None), : response.get(self.ENV_FIRST_NAME, None), : response.get(self.ENV_LAST_NAME, None) } if result[] and result[]: ...
Complete with additional information from environment, as available.
348,513
def index_exists(engine: Engine, tablename: str, indexname: str) -> bool: insp = Inspector.from_engine(engine) return any(i[] == indexname for i in insp.get_indexes(tablename))
Does the specified index exist for the specified table?
348,514
def __recognize_union(self, node: yaml.Node, expected_type: Type) -> RecResult: logger.debug() recognized_types = [] message = union_types = generic_type_args(expected_type) logger.debug(.format(union_types)) for possible_type in union_...
Recognize a node that we expect to be one of a union of types. Args: node: The node to recognize. expected_type: Union[...something...] Returns: The specific type that was recognized, multiple, or none.
348,515
def handle(send, msg, args): worker = args["handler"].workers result = worker.run_pool(get_urls, [msg]) try: urls = result.get(5) except multiprocessing.TimeoutError: worker.restart_pool() send("Url regex timed out.", target=args["config"]["core"]["ctrlchan"]) return...
Get titles for urls. Generate a short url. Get the page title.
348,516
def get_functionalHome(self, functionalHomeType: type) -> FunctionalHome: for x in self.functionalHomes: if isinstance(x, functionalHomeType): return x return None
gets the specified functionalHome Args: functionalHome(type): the type of the functionalHome which should be returned Returns: the FunctionalHome or None if it couldn't be found
348,517
def sequence_molar_extinction_280(seq): if in seq: warnings.warn(_nc_warning_str, NoncanonicalWarning) return sum([residue_ext_280[aa] * n for aa, n in Counter(seq).items()])
Returns the molar extinction coefficient of the sequence at 280 nm. Notes ----- Units = M/cm Parameters ---------- seq : str Sequence of amino acids.
348,518
def is_presence_handler(type_, from_, cb): try: handlers = aioxmpp.service.get_magic_attr(cb) except AttributeError: return False return aioxmpp.service.HandlerSpec( (_apply_presence_handler, (type_, from_)), require_deps=( SimplePresenceDispatcher, ...
Return true if `cb` has been decorated with :func:`presence_handler` for the given `type_` and `from_`.
348,519
def plot_pointings(self,pointings=None): if pointings is None: pointings=self.pointings i=0 for pointing in pointings: items=[] i=i+1 label={} label[]=pointing[][] for ccd in pointing["camera"].getGeometry(): (x1,y1)=self.p2c...
Plot pointings on canavs
348,520
def interactive_update_profile_vars(self): profile = self._parent_class.get.profile() if profile.cgx_status: self._parent_class.tenant_id = profile.cgx_content.get() self._parent_class.email = profile.cgx_content.get() self._parent_class._user...
Function to update the `cloudgenix.API` object with profile info. Run after login or client login. **Returns:** Boolean on success/failure,
348,521
def get_double(self, group: str) -> pointerutils.Double: if group in (, ): if self.deploymode != : return self.sequences.fastaccess.sim return self.sequences.fastaccess.obs if group in (, ): if self.deploymode != : return self....
Return the |Double| object appropriate for the given |Element| input or output group and the actual |Node.deploymode|. Method |Node.get_double| should be of interest for framework developers only (and eventually for model developers). Let |Node| object `node1` handle different simulati...
348,522
def has_privileges(name, object_name, object_type, privileges=None, grant_option=None, prepend=, maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): * object_type, privileges, _privs = _mod_priv...
.. versionadded:: 2016.3.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked ...
348,523
def _cell_attribute_append(self, selection, tab, attributes): cell_attributes = self.code_array.cell_attributes thick_bottom_cells = [] thick_right_cells = [] if "borderwidth_bottom" in attributes: bwidth = attributes["borderwidth_bottom"] fo...
Appends to cell_attributes with checks
348,524
def register(self, _type, _format, creater, _2nd_pass=None): if _type not in self._map: self._map[_type] = {} self._map[_type][_format] = (creater, _2nd_pass)
register a type/format handler when producing primitives example function to create a byte primitive: ```python def create_byte(obj, val, ctx): # val is the value used to create this primitive, for example, a # dict would be used to create a Model and list would be used ...
348,525
def structureLink(lines): KEYWORDS = (, , , ) WEIR_KEYWORDS = (, , , , , , , ) CULVERT_KEYWORDS = (, ...
Parse STRUCTURE LINK Method
348,526
def write(self, val, sig: SimSignal)-> None: try: simSensProcs = sig.simSensProcs except AttributeError: sig = sig._sigInside simSensProcs = sig.simSensProcs t = sig._dtype if isinstance(val, Value): v = val.clo...
Write value to signal or interface.
348,527
def format_cell(val, round_floats = False, decimal_places = 2, format_links = False, hlx = , hxl = , xhl = ): if round_floats: val = smart_round(val, decimal_places = decimal_places) if format_links: val = format_hyperlink(val, hlx, hxl, xhl) return val
Applys smart_round and format_hyperlink to values in a cell if desired.
348,528
def stitch(self, folder=None): debug( + self.__str__()) if not folder: folder = self.path macros = [] files = [] for well in self.wells: f,m = stitch_macro(well, folder) macros.extend(m) files.extend(f) c...
Stitches all wells in experiment with ImageJ. Stitched images are saved in experiment root. Images which already exists are omitted stitching. Parameters ---------- folder : string Where to store stitched images. Defaults to experiment path. Returns ...
348,529
def _decrypt(ascii_armor_message: str, signing_key: SigningKey) -> str: data = signing_key.decrypt_seal(base64.b64decode(ascii_armor_message)) return data.decode()
Decrypt a message from ascii armor format :param ascii_armor_message: Utf-8 message :param signing_key: SigningKey instance created from credentials :return:
348,530
def validate(self): self._populate_domain() missing = [] for domain_device in self.domain: for truster, trustees in iteritems(self.domain): if domain_device not in trustees: missing.append((domain_device, truster, trustees)) if m...
Validate that devices are each trusted by one another :param kwargs: dict -- keyword args for devices and partition :raises: DeviceNotTrusted
348,531
def remover_provisionamento(self, equipamentos, vips): code, map = self.submit({: {: equipamentos}, : { : vips}}, , ) return self.response(code, map)
Remove o provisionamento de um grupo virtual para o sistema de Orquestração VM. :param equipamentos: Lista de equipamentos gerada pelo método "add_equipamento_remove" da classe "EspecificacaoGrupoVirtual". :param vips: Lista de VIPs gerada pelo método "add_vip_remove" da classe "Especificacao...
348,532
def create(cls, name, connection_profile_ref=None, md5_password=None, local_as_option=, max_prefix_option=, send_community=, connected_check=, orf_option=, next_hop_self=True, override_capability=False, dont_capability_negotiate=False, remote_pr...
Create a new BGPPeering configuration. :param str name: name of peering :param str,BGPConnectionProfile connection_profile_ref: required BGP connection profile. System default used if not provided. :param str md5_password: optional md5_password :param str local_as_option: th...
348,533
def plot_average(sdat, lovs): steps_iter = iter(sdat.walk.filter(rprof=True)) try: step = next(steps_iter) except StopIteration: return sovs = misc.set_of_vars(lovs) istart = step.istep nprofs = 1 rprof_averaged = {} rads = {} metas = {} for rvar in s...
Plot time averaged profiles. Args: sdat (:class:`~stagpy.stagyydata.StagyyData`): a StagyyData instance. lovs (nested list of str): nested list of profile names such as the one produced by :func:`stagpy.misc.list_of_vars`. Other Parameters: conf.core.snapshots: the slice of...
348,534
def _ConvertValueForCsv(self, pql_value): if in pql_value: field = pql_value[] elif in pql_value: field = pql_value[] else: field = None if field: if isinstance(field, list): if all(AdManagerClassType(single_field) == AdManagerClassType(field[0]) fo...
Sanitizes a field value from a Value object to a CSV suitable format. Args: pql_value: dict a dictionary containing the data for a single field of an entity. Returns: str a CSV writer friendly value formatted by Value.Type.
348,535
def bind(end_point, socket_type): sock = context.socket(socket_type) try: sock.bind(end_point) except zmq.error.ZMQError as exc: sock.close() raise exc.__class__( % (exc, end_point)) return sock
Bind to a zmq URL; raise a proper error if the URL is invalid; return a zmq socket.
348,536
def get_what_txt(self): return .format(var=self.get_variable_str(), func=self.validator.get_validated_func_display_name())
Overrides the base behaviour defined in ValidationError in order to add details about the function. :return:
348,537
def voltage(self): raw = self.value volts = raw * (_ADS1X15_PGA_RANGE[self._ads.gain] / (2**(self._ads.bits-1) - 1)) return volts
Returns the voltage from the ADC pin as a floating point value.
348,538
def discharge(ctx, id, caveat, key, checker, locator): caveat_id_prefix = [] if caveat is None: caveat = id else: cav_info.version, cav_info.namespace, ) m._caveat_id_prefix = caveat_id_prefix if caveats is not None: for cav in caveats:...
Creates a macaroon to discharge a third party caveat. The given parameters specify the caveat and how it should be checked. The condition implicit in the caveat is checked for validity using checker. If it is valid, a new macaroon is returned which discharges the caveat. The macaroon is created with a ...
348,539
def marketplace(self): if self._marketplace is None: self._marketplace = Marketplace(self) return self._marketplace
:returns: Version marketplace of preview :rtype: twilio.rest.preview.marketplace.Marketplace
348,540
def _recurse(coreml_tree, scikit_tree, tree_id, node_id, scaling = 1.0, mode = , n_classes = 2, tree_index = 0): if not(HAS_SKLEARN): raise RuntimeError() if node_id == _tree.TREE_LEAF: raise ValueError("Invalid node_id %s" % _tree.TREE_LEAF) if scikit_tree.chil...
Traverse through the tree and append to the tree spec.
348,541
def _get_calling_module(self): for frame in inspect.stack(): mod = inspect.getmodule(frame[0]) logger.debug(f) if mod is not None: mod_name = mod.__name__ if mod_name != __name__: return mod
Get the last module in the call stack that is not this module or ``None`` if the call originated from this module.
348,542
def proxy_manager_for(self, proxy, **proxy_kwargs): context = create_urllib3_context(ciphers=self.CIPHERS, ssl_version=ssl.PROTOCOL_TLSv1) proxy_kwargs[] = context return super(TLSv1Adapter, self).proxy_manager_for(proxy, ...
Ensure cipher and Tlsv1
348,543
def dict_param(obj, param_name, key_type=None, value_type=None): if not isinstance(obj, dict): raise_with_traceback(_param_type_mismatch_exception(obj, dict, param_name)) if not (key_type or value_type): return obj return _check_key_value_types(obj, key_type, value_type)
Ensures argument obj is a native Python dictionary, raises an exception if not, and otherwise returns obj.
348,544
def update_color(string, name, style=, when=): clear() write_color(string, name, style, when)
Replace the existing line with the given colored string.
348,545
def get_chunk(self, bucket_name, key_path): bucket = get_bucket(self.config, bucket_name=bucket_name) key = bucket.get_key(key_path) if key is None: raise FailedExtraction( % key_path) fh = StringIO() key.get_contents_to_file(fh) data = fh.getvalue()...
return Chunk object full of records bucket_name may be None
348,546
def AjustarLiquidacionUnificado(self): "Ajustar Liquidación Primaria de Granos" for k in (, ): if not any(self.ajuste[k].values()): del self.ajuste[k] else: if not self.ajuste[k][]: del self.ajuste[k][] ...
Ajustar Liquidación Primaria de Granos
348,547
def loads(s, check_version=True): v = objectify.fromstring(s) _remove_root_tag_prefix(v) if check_version: version = v.attrib[] if not version == : raise ValueError( + version) return v
Load VOEvent from bytes. This parses a VOEvent XML packet string, taking care of some subtleties. For Python 3 users, ``s`` should be a bytes object - see also http://lxml.de/FAQ.html, "Why can't lxml parse my XML from unicode strings?" (Python 2 users can stick with old-school ``str`` type if pref...
348,548
def leaky_relu(x, name=None): with tf.name_scope(name, , [x]) as scope: x = tf.convert_to_tensor(x, name=) return tf.where(tf.less(x, 0.0), 0.01 * x, x, name=scope)
Creates a leaky_relu. This is an alternate non-linearity to relu. The leaky part of the relu may prevent dead Neurons in a model since the gradient doesn't go completely to 0. Args: x: The input tensor. name: Optional name for this op. Returns: x if x > 0 otherwise 0.01 * x.
348,549
def interrupt(self, address): if(self.push_pc): self.memory_bus.write_word(self.sp, self.pc) self._set_sp(self.sp - 1) self._set_pc(address)
Interrupts the Processor and forces him to jump to ``address``. If ``push_pc`` is enabled this will push the PC to the stack.
348,550
def remove(self, item): check_not_none(item, "item can't be none") return self._encode_invoke(transactional_list_remove_codec, item=self._to_data(item))
Transactional implementation of :func:`List.remove(item) <hazelcast.proxy.list.List.remove>` :param item: (object), the specified item to be removed. :return: (bool), ``true`` if the item is removed successfully, ``false`` otherwise.
348,551
def _next_timestamp(self, now, last): if now > last: self.last = now return now else: self._maybe_warn(now=now) self.last = last + 1 return self.last
Returns the timestamp that should be used if ``now`` is the current time and ``last`` is the last timestamp returned by this object. Intended for internal and testing use only; to generate timestamps, call an instantiated ``MonotonicTimestampGenerator`` object. :param int now: an intege...
348,552
def setProfiles(self, profiles): self.blockSignals(True) self._profileCombo.blockSignals(True) self._profiles = profiles[:] self._profileCombo.clear() self._profileCombo.addItems(map(lambda x: x.name(), profiles)) self._profileCombo.blockSignals...
Sets a list of profiles to be the options for the manager. :param profiles | [<XViewProfile>, ..]
348,553
def serialize_instance(obj): obj_dict = {: type(obj).__name__} obj_dict.update(obj.__dict__) for key, value in obj_dict.items(): if not isinstance(value, commonDataType): sub_dict = serialize_instance(value) obj_dict.update({key: sub_dict}) else: cont...
对象序列化 :param: * obj: (object) 对象实例 :return: * obj_dict: (dict) 对象序列化字典 举例如下:: print('--- serialize_instance demo ---') # 定义两个对象 class Obj(object): def __init__(self, a, b): self.a = a self.b = b class ObjB(objec...
348,554
def paint(self, painter, option, widget): scene = self.scene() if not scene: return scene.chart().renderer().drawItem(self, painter, option)
Draws this item with the inputed painter. This will call the scene's renderer to draw this item.
348,555
def position(self): if self.end != self.start + 1: raise ValueError("Not a single base: %s" % str(self)) return self.start
If this locus spans a single base, this property gives that position. Otherwise, raises a ValueError.
348,556
def rec_load_all(self, zone): has_more = True current_count = 0 while has_more: records = self._request({ : , : current_count, : zone }) try: has_more = records[][][] curr...
Lists all DNS records for the given domain :param zone: the domain for which records are being retrieved :type zone: str :return: :rtype: generator
348,557
def delete(all=False, *databases): if not all and not databases: raise CommandExecutionError() try: ret = dict() inspector = _("collector").Inspector(cachedir=__opts__[], piddir=os.path.dirname(__opts__[])) for dbid in all and in...
Remove description snapshots from the system. ::parameter: all. Default: False. Remove all snapshots, if set to True. CLI example: .. code-block:: bash salt myminion inspector.delete <ID> <ID1> <ID2>.. salt myminion inspector.delete all=True
348,558
def get_key_delivery_url(access_token, ck_id, key_type): path = full_path = .join([path, "()", "/GetKeyDeliveryUrl"]) endpoint = .join([ams_rest_endpoint, full_path]) body = + key_type + return do_ams_post(endpoint, full_path, body, access_token)
Get Media Services Key Delivery URL. Args: access_token (str): A valid Azure authentication token. ck_id (str): A Media Service Content Key ID. key_type (str): A Media Service key Type. Returns: HTTP response. JSON body.
348,559
def get_gicon(self, icon_id: str) -> "Gio.Icon": return Gio.ThemedIcon.new_from_names(self._icon_names[icon_id])
Lookup Gio.Icon from udiskie-internal id.
348,560
def safe_service(attr, default_value=None): def _(fun): @functools.wraps(fun) def run(self): try: return fun(self) except: logger.error(traceback.format_exc()) setattr(self, attr, default_value) return run retur...
A **method** decorator for creating safe services. Given an attribute name, this returns a decorator for creating safe services. Namely, if a service that is not yet available is requested (like a database connection), then ``safe_service`` will log any errors and set the given attribute to ``default_v...
348,561
def request_password_reset(email): s Password Process. Return True/False indicate success/failure on the request/requestPasswordReset']) try: User.POST(url, email=email) return True except ParseError: return False
Trigger Parse\'s Password Process. Return True/False indicate success/failure on the request
348,562
def _dfs(self, visited): if self not in visited: visited.add(self) for successor in self._children + self._followOns: successor._dfs(visited)
Adds the job and all jobs reachable on a directed path from current node to the given set.
348,563
def get_links(rlinks): if rlinks is None: return links = [] for item in rlinks: if in item: links.append(item[]) if in item and in item: if item[] == 0: links.append(item[]) return sorted(links) if links else None
returns list of titles/urls from query/parse links response
348,564
def set_contents(self, stream, chunk_size=None, size=None, size_limit=None, progress_callback=None, **kwargs): self.set_uri( *self.storage(**kwargs).save( stream, chunk_size=chunk_size, size=size, size_limit=size_limit, progress_callback=...
Save contents of stream to this file. :param obj: ObjectVersion instance from where this file is accessed from. :param stream: File-like stream.
348,565
def process_raw_data(cls, raw_data): properties = raw_data.get("properties", {}) raw_ip_configuration = properties.get("backendIPConfiguration", []) if isinstance(raw_ip_configuration, dict): raw_ip_configuration = [raw_ip_configuration] for raw_content in raw_ip_c...
Create a new model using raw API response.
348,566
def message_interactions(self): if self._message_interactions is None: self._message_interactions = MessageInteractionList( self._version, service_sid=self._solution[], session_sid=self._solution[], participant_sid=self._soluti...
Access the message_interactions :returns: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionList :rtype: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionList
348,567
def tsp_linearize(data, niter=1000, metric=, **kwargs): N = data.shape[0] D = scipy.spatial.distance.pdist(data, metric=metric, **kwargs) dist = np.zeros((N+1, N+1)) dist[:N, :N] = scipy.spatial.distance.squareform(D) perm, cost_hist = _solve_tsp(dist) ...
Sorts a matrix dataset to (approximately) solve the traveling salesperson problem. The matrix can be re-sorted so that sequential rows represent datapoints that are close to each other based on some user-defined distance metric. Uses 2-opt local search algorithm. Args ---- data : ndarray, N x R...
348,568
def parse_messages_by_stream(messages_by_stream): if messages_by_stream is None: return [] parsed = [] for stream, messages in messages_by_stream: for message_id, fields in parse_messages(messages): parsed.append((stream, message_id, fields)) return parsed
Parse messages returned by stream Messages returned by XREAD arrive in the form: [stream_name, [ [message_id, [key1, value1, key2, value2, ...]], ... ], ... ] Here we parse this into (with the help of the above parse_messages(...
348,569
def set_rate(self, param): rate = int(param) if 1 <= rate <= 15000: self.device.temperature_rate = rate / 100.0 return ""
Models "Rate Command" functionality of device. Sets the target rate of temperature change. :param param: Rate of temperature change in C/min, multiplied by 100, as a string. Must be positive. :return: Empty string.
348,570
def _to_zip_product(sweep: Sweep) -> Product: if not isinstance(sweep, Product): sweep = Product(sweep) if not all(isinstance(f, Zip) for f in sweep.factors): factors = [f if isinstance(f, Zip) else Zip(f) for f in sweep.factors] sweep = Product(*factors) for factor in sweep.fac...
Converts sweep to a product of zips of single sweeps, if possible.
348,571
def merged(self, timeslots: ) -> : slots = [Timeslot(slot.interval, slot.channel) for slot in self.timeslots] slots.extend([Timeslot(slot.interval, slot.channel) for slot in timeslots.timeslots]) return TimeslotCollection(*slots)
Return a new TimeslotCollection merged with a specified `timeslots` Args: timeslots: TimeslotCollection to be merged
348,572
def superimposition_matrix(v0, v1, scaling=False, usesvd=True): v0 = numpy.array(v0, dtype=numpy.float64, copy=False)[:3] v1 = numpy.array(v1, dtype=numpy.float64, copy=False)[:3] if v0.shape != v1.shape or v0.shape[1] < 3: raise ValueError("Vector sets are of wrong shape or type.") ...
Return matrix to transform given vector set into second vector set. v0 and v1 are shape (3, \*) or (4, \*) arrays of at least 3 vectors. If usesvd is True, the weighted sum of squared deviations (RMSD) is minimized according to the algorithm by W. Kabsch [8]. Otherwise the quaternion based algorithm b...
348,573
def preview(src_path): preview = embedded_preview(src_path) if not is_valid_preview(preview): preview = generator_preview(src_path) if not is_valid_preview(preview): preview = thumbnail_preview(src_path) if is_valid_preview(preview): if mimetype(preview) in [ExportMimeType.PNG]: retur...
Generates a preview of src_path in the requested format. :returns: A list of preview paths, one for each page. Blank list if unsupported.
348,574
def lsm_data_to_subset_netcdf(self, netcdf_file_path, data_var_map_array, resample_method=None): self._check_lsm_input(data_var_map_array) output_datasets = [] for gssha_var, lsm_var in data_var_ma...
Writes extracted data to the NetCDF file format .. todo:: NetCDF output data time is always in UTC time. Need to convert to local timezone for GSSHA. .. warning:: The NetCDF GSSHA file is only supported in GSSHA 7 or greater. .. note:: GSSHA CARDS: * HMET_NETCDF po...
348,575
def move(self, external_index, new_priority): index = external_index + (self._capacity - 1) return self._move(index, new_priority)
Change the priority of a leaf node
348,576
def tween(self, t): if t is None: return None if self.method in self.method_to_tween: return self.method_to_tween[self.method](t) elif self.method in self.method_1param: return self.method_1param[self.method](t, self.param1) elif self.method ...
t is number between 0 and 1 to indicate how far the tween has progressed
348,577
def first_cyclic_node(head): runner = walker = head while runner and runner.next: runner = runner.next.next walker = walker.next if runner is walker: break if runner is None or runner.next is None: return None walker = head while runner is not walke...
:type head: Node :rtype: Node
348,578
def items(self): "Returns all elements as a list in (key,value) format." return list(zip(list(self.keys()), list(self.values())))
Returns all elements as a list in (key,value) format.
348,579
def remove_blacklisted_filepaths(self, filepaths): filepaths = util.to_absolute_paths(filepaths) black_paths = self.blacklisted_filepaths black_paths = util.remove_from_set(black_paths, filepaths)
Removes `filepaths` from blacklisted filepaths Recommend passing in absolute filepaths but method will attempt to convert to absolute filepaths based on current working directory.
348,580
def libvlc_media_list_player_set_media_list(p_mlp, p_mlist): f = _Cfunctions.get(, None) or \ _Cfunction(, ((1,), (1,),), None, None, MediaListPlayer, MediaList) return f(p_mlp, p_mlist)
Set the media list associated with the player. @param p_mlp: media list player instance. @param p_mlist: list of media.
348,581
def get_diskinfo(opts, show_all=False, debug=False, local_only=False): outunit = opts.outunit disks = [] try: label_map = get_label_map(opts) lines = run(diskcmd).splitlines()[1:] for line in lines: tokens = line.split() mntp = b.join(tokens[8:]) ...
Returns a list holding the current disk info, stats divided by the ouptut unit.
348,582
def parse(self, expr, simplify=False): precedence = {self.NOT: 5, self.AND: 10, self.OR: 15, TOKEN_LPAR: 20} if isinstance(expr, basestring): tokenized = self.tokenize(expr) else: tokenized = iter(expr) if TRACE_PARSE: tokenized = list(toke...
Return a boolean expression parsed from `expr` either a unicode string or tokens iterable. Optionally simplify the expression if `simplify` is True. Raise ParseError on errors. If `expr` is a string, the standard `tokenizer` is used for tokenization and the algebra configured ...
348,583
def get_port_bindings(container_config, client_config): port_bindings = {} if_ipv4 = client_config.interfaces if_ipv6 = client_config.interfaces_ipv6 for exposed_port, ex_port_bindings in itertools.groupby( sorted(container_config.exposes, key=_get_ex_port), _get_ex_port): bind_...
Generates the input dictionary contents for the ``port_bindings`` argument. :param container_config: Container configuration. :type container_config: dockermap.map.config.container.ContainerConfiguration :param client_config: Client configuration. :type client_config: dockermap.map.config.client.Client...
348,584
def parse(cls, detail_string): split = detail_string.split() if len(split) != 4: raise Exception() ltpk = binascii.unhexlify(split[0]) ltsk = binascii.unhexlify(split[1]) atv_id = binascii.unhexlify(split[2]) client_id = binascii.unhexlify(split[3]...
Parse a string represention of Credentials.
348,585
def move_tab(self, index_from, index_to): filename = self.filenames.pop(index_from) client = self.clients.pop(index_from) self.filenames.insert(index_to, filename) self.clients.insert(index_to, client) self.update_tabs_text() self.sig_update_plugin_title.e...
Move tab (tabs themselves have already been moved by the tabwidget)
348,586
def update_config(self, config): newconfig = deepcopy(self.config) newconfig._merge(config) self.config = newconfig
Fire the traits events when the config is updated.
348,587
def get(self, timeout=None): if not self.wait(timeout): raise TimeoutError("Result not available within %fs" % timeout) if self._success: return self._data raise self._data[0]
Returns the result when it arrives. If timeout is not None and the result does not arrive within timeout seconds then TimeoutError is raised. If the remote call raised an exception then that exception will be reraised by get().
348,588
def run(self, args): self.args = self.parse_and_process_args(args) if self.args.version: print(__version__) return 0 if self.args.rulefile: for filename in self.args.rulefile: self._load_rule_file(filename) if s...
Parse command line arguments, and run rflint
348,589
def hessian_tensor_product(fun, argnum=0): fun_grad = grad(fun, argnum) def vector_dot_grad(*args, **kwargs): args, vector = args[:-1], args[-1] return np.tensordot(fun_grad(*args, **kwargs), vector, np.ndim(vector)) return grad(vector_dot_grad, argnum)
Builds a function that returns the exact Hessian-tensor product. The returned function has arguments (*args, tensor, **kwargs), and for vectors takes roughly 4x as long to evaluate as the original function.
348,590
def list_keys(hive, key=None, use_32bit_registry=False): HKLMSOFTWARE\\Microsoft local_hive = _to_unicode(hive) local_key = _to_unicode(key) registry = Registry() try: hkey = registry.hkeys[local_hive] except KeyError: raise CommandExecutionError(.format(local_hive)) access...
Enumerates the subkeys in a registry key or hive. Args: hive (str): The name of the hive. Can be one of the following: - HKEY_LOCAL_MACHINE or HKLM - HKEY_CURRENT_USER or HKCU - HKEY_USERS or HKU - HKEY_CLASSES_ROOT or HKCR ...
348,591
def encrypt(self, plaintext): msg_key = random_letters(3) while msg_key == self.grundstellung: msg_key = random_letters(3) self.machine.set_display(self.grundstellung) enc_key = self.machine.process_text(msg_key) self.machine.set_display(m...
Have the operator encrypt a message.
348,592
def calc_fwhm(img, region, fexpand=3, axis=0): xpregion = expand_region(region, fexpand, fexpand) cslit = img[xpregion] pslit = cslit.mean(axis=axis) x2 = len(pslit) y1, y2 = pslit[0], pslit[-1] mslope = (y2-y1) / x2 backstim = mslope*numpy.ar...
Compute the FWHM in the direction given by axis
348,593
def match(tgt, opts=None): if not opts: opts = __opts__ try: tgt = ipaddress.ip_address(tgt) except: try: tgt = ipaddress.ip_network(tgt) except: log.error(, tgt) return [] proto = .format(tgt.version) ...
Matches based on IP address or CIDR notation
348,594
def num_trees(n): dp = [0] * (n+1) dp[0] = 1 dp[1] = 1 for i in range(2, n+1): for j in range(i+1): dp[i] += dp[i-j] * dp[j-1] return dp[-1]
:type n: int :rtype: int
348,595
def run(self): self.thread = Thread(target=self.__processQueue) self.thread.start()
Creates the actor thread wich will process the channel queue while the actor :meth:`is_alive`, making it able to receive queries.
348,596
def with_context(cls, *args, **kwargs): context = dict(args[0] if args else cls.env.context, **kwargs) return cls.with_env(cls.env(context=context))
Return a model (or recordset) equivalent to the current model (or recordset) attached to an environment with another context. The context is taken from the current environment or from the positional arguments `args` if given, and modified by `kwargs`. Thus, the following two examples ar...
348,597
def UpdateValues(self, grid): "Update all displayed values" msg = gridlib.GridTableMessage(self, gridlib.GRIDTABLE_REQUEST_VIEW_GET_VALUES) grid.ProcessTableMessage(msg)
Update all displayed values
348,598
def add_link_type_vlan(enode, portlbl, name, vlan_id, shell=None): assert name if name in enode.ports: raise ValueError(.format(name=name)) assert portlbl assert vlan_id port = enode.ports[portlbl] cmd = .format( dev=port, name=name, vlan_id=vlan_id) response = enode(...
Add a new virtual link with the type set to VLAN. Creates a new vlan device {name} on device {port}. Will raise an exception if value is already assigned. :param enode: Engine node to communicate with. :type enode: topology.platforms.base.BaseNode :param str portlbl: Port label to configure. Port ...
348,599
def pause(self, signum, seconds=0, callback_function=None): if callback_function is None: callback_function = self.default_handler if seconds > 0: self.log.info("Signal handler pausing for {0} seconds or until it receives SIGALRM or SIGCONT".format(seconds)) ...
Pause execution, execution will resume in X seconds or when the appropriate resume signal is received. Execution will jump to the callback_function, the default callback function is the handler method which will run all tasks registered with the reg_on_resume methodi. Returns Tru...