code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def enable_backups(self, table_name, model): """Calls UpdateContinuousBackups on the table according to model.Meta["continuous_backups"] :param table_name: The name of the table to enable Continuous Backups on :param model: The model to get Continuous Backups settings from """ s...
Calls UpdateContinuousBackups on the table according to model.Meta["continuous_backups"] :param table_name: The name of the table to enable Continuous Backups on :param model: The model to get Continuous Backups settings from
def _producer_wrapper(f, port, addr='tcp://127.0.0.1'): """A shim that sets up a socket and starts the producer callable. Parameters ---------- f : callable Callable that takes a single argument, a handle for a ZeroMQ PUSH socket. Must be picklable. port : int The port on wh...
A shim that sets up a socket and starts the producer callable. Parameters ---------- f : callable Callable that takes a single argument, a handle for a ZeroMQ PUSH socket. Must be picklable. port : int The port on which the socket should connect. addr : str, optional ...
def rigid_transform_from_ros(from_frame, to_frame, service_name='rigid_transforms/rigid_transform_listener', namespace=None): """Gets transform from ROS as a rigid transform Requires ROS rigid_transform_publisher service to be running. Assuming autolab_core is installed as a catkin package, ...
Gets transform from ROS as a rigid transform Requires ROS rigid_transform_publisher service to be running. Assuming autolab_core is installed as a catkin package, this can be done with: roslaunch autolab_core rigid_transforms.launch Parameters ---------- from_fr...
def copy(self, **replacements): """Returns a clone of this M2Coordinate with the given replacements kwargs overlaid.""" cls = type(self) kwargs = {'org': self.org, 'name': self.name, 'ext': self.ext, 'classifier': self.classifier, 'rev': self.rev} for key, val in replacements.items(): kwargs[key] ...
Returns a clone of this M2Coordinate with the given replacements kwargs overlaid.
def _SignedVarintEncoder(): """Return an encoder for a basic signed varint value (does not include tag).""" def EncodeSignedVarint(write, value): if value < 0: value += (1 << 64) bits = value & 0x7f value >>= 7 while value: write(six.int2byte(0x80|bits)) bits = value & 0x7f ...
Return an encoder for a basic signed varint value (does not include tag).
def generate_graphs(result, topic, aspect, for_doc=False): """ genrate graphs from result file Parameters ---------- result : str path to result file topic : str benchmark topic; for example "Open file" or "Save file" aspect : str performance indiitemsor; can be "ram" (R...
genrate graphs from result file Parameters ---------- result : str path to result file topic : str benchmark topic; for example "Open file" or "Save file" aspect : str performance indiitemsor; can be "ram" (RAM memory usage) or "time" (elapsed time) for_doc : bool ...
def parse_item(self, response): """ Get basic information about a page, so that it can be passed to the `pa11y` tool for further testing. @url https://www.google.com/ @returns items 1 1 @returns requests 0 0 @scrapes url request_headers accessed_at page_title ...
Get basic information about a page, so that it can be passed to the `pa11y` tool for further testing. @url https://www.google.com/ @returns items 1 1 @returns requests 0 0 @scrapes url request_headers accessed_at page_title
def draw_interface(objects, callback, callback_text): """ Draws a ncurses interface. Based on the given object list, every object should have a "string" key, this is whats displayed on the screen, callback is called with the selected object. Rest of the code is modified from: https://stackov...
Draws a ncurses interface. Based on the given object list, every object should have a "string" key, this is whats displayed on the screen, callback is called with the selected object. Rest of the code is modified from: https://stackoverflow.com/a/30834868
def _ensure_batch_is_sufficiently_small( self, batch_instances: Iterable[Instance], excess: Deque[Instance]) -> List[List[Instance]]: """ If self._maximum_samples_per_batch is specified, then split the batch into smaller sub-batches if it exceeds the maximum s...
If self._maximum_samples_per_batch is specified, then split the batch into smaller sub-batches if it exceeds the maximum size. Parameters ---------- batch_instances : ``Iterable[Instance]`` A candidate batch. excess : ``Deque[Instance]`` Instances that we...
def runlist_list(**kwargs): """ Show uploaded runlists. """ ctx = Context(**kwargs) ctx.execute_action('runlist:list', **{ 'storage': ctx.repo.create_secure_service('storage'), })
Show uploaded runlists.
def CheckVersion(problems, latest_version=None): """ Check if there is a newer version of transitfeed available. Args: problems: if a new version is available, a NewVersionAvailable problem will be added latest_version: if specified, override the latest version read from the project page ""...
Check if there is a newer version of transitfeed available. Args: problems: if a new version is available, a NewVersionAvailable problem will be added latest_version: if specified, override the latest version read from the project page
def normalize_extension(extension): """Normalise a file name extension.""" extension = decode_path(extension) if extension is None: return if extension.startswith('.'): extension = extension[1:] if '.' in extension: _, extension = os.path.splitext(extension) extension = s...
Normalise a file name extension.
def ok(self, text=u"OK", err=False): """Set Ok (success) finalizer to a spinner.""" # Do not display spin text for ok state self._text = None _text = to_text(text) if text else u"OK" err = err or not self.write_to_stdout self._freeze(_text, err=err)
Set Ok (success) finalizer to a spinner.
def proxy_alias(alias_name, node_type): """Get a Proxy from the given name to the given node type.""" proxy = type( alias_name, (lazy_object_proxy.Proxy,), { "__class__": object.__dict__["__class__"], "__instancecheck__": _instancecheck, }, ) retur...
Get a Proxy from the given name to the given node type.
def is_vert_aligned(c): """Return true if all the components of c are vertically aligned. Vertical alignment means that the bounding boxes of each Mention of c shares a similar x-axis value in the visual rendering of the document. :param c: The candidate to evaluate :rtype: boolean """ ret...
Return true if all the components of c are vertically aligned. Vertical alignment means that the bounding boxes of each Mention of c shares a similar x-axis value in the visual rendering of the document. :param c: The candidate to evaluate :rtype: boolean
def get_distance( self, l_motor: float, r_motor: float, tm_diff: float ) -> typing.Tuple[float, float]: """ Given motor values and the amount of time elapsed since this was last called, retrieves the x,y,angle that the robot has moved. Pass these values to :meth:`...
Given motor values and the amount of time elapsed since this was last called, retrieves the x,y,angle that the robot has moved. Pass these values to :meth:`PhysicsInterface.distance_drive`. To update your encoders, use the ``l_position`` and ``r_position`` at...
def transfer(self, receiver_address, amount, from_account): """ Transfer tokens from one account to the receiver address. :param receiver_address: Address of the transfer receiver, str :param amount: Amount of tokens, int :param from_account: Sender account, Account :ret...
Transfer tokens from one account to the receiver address. :param receiver_address: Address of the transfer receiver, str :param amount: Amount of tokens, int :param from_account: Sender account, Account :return: bool
def load_core_file(core_fp): """ For core OTU data file, returns Genus-species identifier for each data entry. :type core_fp: str :param core_fp: A file containing core OTU data. :rtype: str :return: Returns genus-species identifier based on identified taxonomical level. """...
For core OTU data file, returns Genus-species identifier for each data entry. :type core_fp: str :param core_fp: A file containing core OTU data. :rtype: str :return: Returns genus-species identifier based on identified taxonomical level.
def get_random_proxy(self): """Return random proxy""" idx = randint(0, len(self._list) - 1) return self._list[idx]
Return random proxy
def close(self): """ Close the internal epoll file descriptor if it isn't closed :raises OSError: If the underlying ``close(2)`` fails. The error message matches those found in the manual page. """ with self._close_lock: epfd = self._epfd ...
Close the internal epoll file descriptor if it isn't closed :raises OSError: If the underlying ``close(2)`` fails. The error message matches those found in the manual page.
def write_bus_data(self, file): """ Writes bus data as CSV. """ writer = self._get_writer(file) writer.writerow(BUS_ATTRS) for bus in self.case.buses: writer.writerow([getattr(bus, attr) for attr in BUS_ATTRS])
Writes bus data as CSV.
def register_blueprint(self, blueprint): ''' Register given blueprint on curren app. This method is provided for using inside plugin's module-level :func:`register_plugin` functions. :param blueprint: blueprint object with plugin endpoints :type blueprint: flask.Bluepri...
Register given blueprint on curren app. This method is provided for using inside plugin's module-level :func:`register_plugin` functions. :param blueprint: blueprint object with plugin endpoints :type blueprint: flask.Blueprint
def register(self, app, options): """Register the blueprint to the mach9 app.""" url_prefix = options.get('url_prefix', self.url_prefix) # Routes for future in self.routes: # attach the blueprint name to the handler so that it can be # prefixed properly in the r...
Register the blueprint to the mach9 app.
def update_identity(self, identity, identity_id): """UpdateIdentity. :param :class:`<Identity> <azure.devops.v5_0.identity.models.Identity>` identity: :param str identity_id: """ route_values = {} if identity_id is not None: route_values['identityId'] = self._...
UpdateIdentity. :param :class:`<Identity> <azure.devops.v5_0.identity.models.Identity>` identity: :param str identity_id:
def formatdate(timeval=None, localtime=False, usegmt=False): """Returns a date string as specified by RFC 2822, e.g.: Fri, 09 Nov 2001 01:08:47 -0000 Optional timeval if given is a floating point time value as accepted by gmtime() and localtime(), otherwise the current time is used. Optional loca...
Returns a date string as specified by RFC 2822, e.g.: Fri, 09 Nov 2001 01:08:47 -0000 Optional timeval if given is a floating point time value as accepted by gmtime() and localtime(), otherwise the current time is used. Optional localtime is a flag that when True, interprets timeval, and returns ...
def p_DefaultValue_string(p): """DefaultValue : STRING""" p[0] = model.Value(type=model.Value.STRING, value=p[1])
DefaultValue : STRING
def get_error(self, block=False, timeout=None): """Removes and returns an error from self._errors Args: block(bool): if True block until a RTMMessage is available, else it will return None when self._inbox is empty timeout(int): it blocks at most timeout...
Removes and returns an error from self._errors Args: block(bool): if True block until a RTMMessage is available, else it will return None when self._inbox is empty timeout(int): it blocks at most timeout seconds Returns: error if inbox is no...
def _find_set_members(set): ''' Return list of members for a set ''' cmd = '{0} list {1}'.format(_ipset_cmd(), set) out = __salt__['cmd.run_all'](cmd, python_shell=False) if out['retcode'] > 0: # Set doesn't exist return false return False _tmp = out['stdout'].split('\n') ...
Return list of members for a set
def rps_at(self, t): '''Return rps for second t''' if 0 <= t <= self.duration: return self.minrps + \ float(self.maxrps - self.minrps) * t / self.duration else: return 0
Return rps for second t
def put_archive(self, path, data): """ Insert a file or folder in this container using a tar archive as source. Args: path (str): Path inside the container where the file(s) will be extracted. Must exist. data (bytes): tar data to be extracted ...
Insert a file or folder in this container using a tar archive as source. Args: path (str): Path inside the container where the file(s) will be extracted. Must exist. data (bytes): tar data to be extracted Returns: (bool): True if the call suc...
def nvrtcGetPTX(self, prog): """ Returns the compiled PTX for the NVRTC program object. """ size = c_size_t() code = self._lib.nvrtcGetPTXSize(prog, byref(size)) self._throw_on_error(code) buf = create_string_buffer(size.value) code = self._lib.nvrtcGetPT...
Returns the compiled PTX for the NVRTC program object.
def outdict(self, ndigits=3): """Return dictionary structure rounded to a given precision.""" output = self.__dict__.copy() for item in output: output[item] = round(output[item], ndigits) return output
Return dictionary structure rounded to a given precision.
def AutorizarAnticipo(self): "Autorizar Anticipo de una Liquidación Primaria Electrónica de Granos" # extraer y adaptar los campos para el anticipo anticipo = {"liquidacion": self.liquidacion} liq = anticipo["liquidacion"] liq["campaniaPpal"] = self.liquidacion["campaniaPPal"] ...
Autorizar Anticipo de una Liquidación Primaria Electrónica de Granos
def logtrace(logger, msg, *args, **kwargs): ''' If esgfpid.defaults.LOG_TRACE_TO_DEBUG, messages are treated like debug messages (with an added [trace]). Otherwise, they are ignored. ''' if esgfpid.defaults.LOG_TRACE_TO_DEBUG: logdebug(logger, '[trace] %s' % msg, *args, **kwargs) els...
If esgfpid.defaults.LOG_TRACE_TO_DEBUG, messages are treated like debug messages (with an added [trace]). Otherwise, they are ignored.
def _sendDDEcommand(self, cmd, timeout=None): """Send command to DDE client""" reply = self.conversation.Request(cmd, timeout) if self.pyver > 2: reply = reply.decode('ascii').rstrip() return reply
Send command to DDE client
def listIterators(self, login, tableName): """ Parameters: - login - tableName """ self.send_listIterators(login, tableName) return self.recv_listIterators()
Parameters: - login - tableName
def write(self, nb, fp, **kwargs): """Write a notebook to a file like object""" return fp.write(self.writes(nb,**kwargs))
Write a notebook to a file like object
def unpack_fixed8(src): """Get a FIXED8 value.""" dec_part = unpack_ui8(src) int_part = unpack_ui8(src) return int_part + dec_part / 256
Get a FIXED8 value.
def _start_of_century(self): """ Reset the date to the first day of the century. :rtype: Date """ year = self.year - 1 - (self.year - 1) % YEARS_PER_CENTURY + 1 return self.set(year, 1, 1)
Reset the date to the first day of the century. :rtype: Date
def just(*args): ''' this works as an infinite loop that yields the given argument(s) over and over ''' assert len(args) >= 1, 'generators.just needs at least one arg' if len(args) == 1: # if only one arg is given try: # try to cycle in a set for iteration speedup ...
this works as an infinite loop that yields the given argument(s) over and over
def create_key(file_): """ Create a key and save it into ``file_``. Note that ``file`` must be opened in binary mode. """ pkey = crypto.PKey() pkey.generate_key(crypto.TYPE_RSA, 2048) file_.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey)) file_.flush()
Create a key and save it into ``file_``. Note that ``file`` must be opened in binary mode.
def decode_source(source_bytes): """Decode bytes representing source code and return the string. Universal newline support is used in the decoding. """ # source_bytes_readline = io.BytesIO(source_bytes).readline # encoding, _ = detect_encoding(source_bytes_readline) newline_decoder = io.Incremen...
Decode bytes representing source code and return the string. Universal newline support is used in the decoding.
def unhook_wnd_proc(self): """Restore previous Window message handler""" if not self.__local_wnd_proc_wrapped: return SetWindowLong(self.__local_win_handle, GWL_WNDPROC, self.__old_wnd_proc) ## Allow the ctypes wrapper ...
Restore previous Window message handler
def percentile(self, p): """ Computes the percentile of a specific value in [0,100]. """ if not (0 <= p <= 100): raise ValueError("p must be between 0 and 100, inclusive.") p = float(p)/100. p *= self.n c_i = None t = 0 if p == 0: ...
Computes the percentile of a specific value in [0,100].
def _unpack(c, tmp, package, version, git_url=None): """ Download + unpack given package into temp dir ``tmp``. Return ``(real_version, source)`` where ``real_version`` is the "actual" version downloaded (e.g. if a Git master was indicated, it will be the SHA of master HEAD) and ``source`` is the s...
Download + unpack given package into temp dir ``tmp``. Return ``(real_version, source)`` where ``real_version`` is the "actual" version downloaded (e.g. if a Git master was indicated, it will be the SHA of master HEAD) and ``source`` is the source directory (relative to unpacked source) to import into ...
def get_dataframe_from_variable(nc, data_var): """ Returns a Pandas DataFrame of the data. This always returns positive down depths """ time_var = nc.get_variables_by_attributes(standard_name='time')[0] depth_vars = nc.get_variables_by_attributes(axis=lambda v: v is not None and v.lower() == 'z...
Returns a Pandas DataFrame of the data. This always returns positive down depths
def copy(self): """ Make a copy of the SegmentList. :return: A copy of the SegmentList instance. :rtype: angr.analyses.cfg_fast.SegmentList """ n = SegmentList() n._list = [ a.copy() for a in self._list ] n._bytes_occupied = self._bytes_occupied ...
Make a copy of the SegmentList. :return: A copy of the SegmentList instance. :rtype: angr.analyses.cfg_fast.SegmentList
def update(self, slug): ''' Update the page. ''' post_data = self.get_post_data() post_data['user_name'] = self.userinfo.user_name pageinfo = MWiki.get_by_uid(slug) cnt_old = tornado.escape.xhtml_unescape(pageinfo.cnt_md).strip() cnt_new = post_data['c...
Update the page.
def handle_response (response): """ Handle a response from the newton API """ response = json.loads(response.read()) # Was the expression valid? if 'error' in response: raise ValueError(response['error']) else: # Some of the strings returned can be parsed to integer...
Handle a response from the newton API
def enable_directory_service(self, check_peer=False): """Enable the directory service. :param check_peer: If True, enables server authenticity enforcement. If False, enables directory service integration. :type check_peer: bool, optional ...
Enable the directory service. :param check_peer: If True, enables server authenticity enforcement. If False, enables directory service integration. :type check_peer: bool, optional :returns: A dictionary describing the status of the directo...
def _get_on_name(self, func): """Return `eventname` when the function name is `on_<eventname>()`.""" r = re.match("^on_(.+)$", func.__name__) if r: event = r.group(1) else: raise ValueError("The function name should be " "`on_<eventnam...
Return `eventname` when the function name is `on_<eventname>()`.
def update_thesis_information(self): """501 degree info - move subfields.""" fields_501 = record_get_field_instances(self.record, '502') for field in fields_501: new_subs = [] for key, value in field[0]: if key == 'b': new_subs.append((...
501 degree info - move subfields.
def get(self, name): """Returns a Notification by name. """ if not self.loaded: raise RegistryNotLoaded(self) if not self._registry.get(name): raise NotificationNotRegistered( f"Notification not registered. Got '{name}'." ) retu...
Returns a Notification by name.
def ungrist (value): """ Returns the value without grist. If value is a sequence, does it for every value and returns the result as a sequence. """ assert is_iterable_typed(value, basestring) or isinstance(value, basestring) def ungrist_one (value): stripped = __re_grist_content.match (v...
Returns the value without grist. If value is a sequence, does it for every value and returns the result as a sequence.
def _relative_attention_inner(x, y, z, transpose): """Relative position-aware dot-product attention inner calculation. This batches matrix multiply calculations to avoid unnecessary broadcasting. Args: x: Tensor with shape [batch_size, heads, length or 1, length or depth]. y: Tensor with shape [batch_si...
Relative position-aware dot-product attention inner calculation. This batches matrix multiply calculations to avoid unnecessary broadcasting. Args: x: Tensor with shape [batch_size, heads, length or 1, length or depth]. y: Tensor with shape [batch_size, heads, length or 1, depth]. z: Tensor with shape...
def _download_initial_config(self): """Loads the initial config.""" _initial_config = self._download_running_config() # this is a bit slow! self._last_working_config = _initial_config self._config_history.append(_initial_config) self._config_history.append(_initial_config)
Loads the initial config.
def receive_request(self, transaction): """ Handle requests coming from the udp socket. :param transaction: the transaction created to manage the request """ with transaction: transaction.separate_timer = self._start_separate_timer(transaction) self._b...
Handle requests coming from the udp socket. :param transaction: the transaction created to manage the request
def get_or_create_namespace(self, url: str) -> Union[Namespace, Dict]: """Insert the namespace file at the given location to the cache. If not cachable, returns the dict of the values of this namespace. :raises: pybel.resources.exc.ResourceError """ result = self.get_namespace_...
Insert the namespace file at the given location to the cache. If not cachable, returns the dict of the values of this namespace. :raises: pybel.resources.exc.ResourceError
def quotation_markers(self, value): """ Setter for **self.__quotation_markers** attribute. :param value: Attribute value. :type value: tuple or list """ if value is not None: assert type(value) in (tuple, list), "'{0}' attribute: '{1}' type is not 'tuple' or...
Setter for **self.__quotation_markers** attribute. :param value: Attribute value. :type value: tuple or list
def set_meta_rdf(self, rdf, fmt='n3'): """Set the metadata for this Thing in RDF fmt Advanced users who want to manipulate the RDF for this Thing directly without the [ThingMeta](ThingMeta.m.html#IoticAgent.IOT.ThingMeta.ThingMeta) helper object Raises [IOTException](./Exceptions.m.htm...
Set the metadata for this Thing in RDF fmt Advanced users who want to manipulate the RDF for this Thing directly without the [ThingMeta](ThingMeta.m.html#IoticAgent.IOT.ThingMeta.ThingMeta) helper object Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) ...
def object_ref(self): """Return the reference of the changed object.""" return ImmutableDict(type=self.type, category_id=self.category_id, event_id=self.event_id, session_id=self.session_id, contrib_id=self.contrib_id, subcontrib_id=self.subcontrib_id)
Return the reference of the changed object.
def indices2one_hot(indices, nb_classes): """ Convert an iterable of indices to one-hot encoded list. You might also be interested in sklearn.preprocessing.OneHotEncoder Parameters ---------- indices : iterable iterable of indices nb_classes : int Number of classes dtyp...
Convert an iterable of indices to one-hot encoded list. You might also be interested in sklearn.preprocessing.OneHotEncoder Parameters ---------- indices : iterable iterable of indices nb_classes : int Number of classes dtype : type Returns ------- one_hot : list ...
def _on_apply_button_clicked(self, *args): """Apply button clicked: Apply the configuration """ refresh_required = self.core_config_model.apply_preliminary_config() refresh_required |= self.gui_config_model.apply_preliminary_config() if not self.gui_config_model.config.get_confi...
Apply button clicked: Apply the configuration
def d3logpdf_dlink3(self, link_f, y, Y_metadata=None): """ Third order derivative log-likelihood function at y given link(f) w.r.t link(f) .. math:: \\frac{d^{3} \\ln p(y_{i}|\lambda(f_{i}))}{d^{3}\\lambda(f)} = -\\beta^{3}\\frac{d^{2}\\Psi(\\alpha_{i})}{d\\alpha_{i}}\\\\ ...
Third order derivative log-likelihood function at y given link(f) w.r.t link(f) .. math:: \\frac{d^{3} \\ln p(y_{i}|\lambda(f_{i}))}{d^{3}\\lambda(f)} = -\\beta^{3}\\frac{d^{2}\\Psi(\\alpha_{i})}{d\\alpha_{i}}\\\\ \\alpha_{i} = \\beta y_{i} :param link_f: latent variables link(...
def fit(self, choosers, alternatives, current_choice): """ Fit and save model parameters based on given data. Parameters ---------- choosers : pandas.DataFrame Table describing the agents making choices, e.g. households. alternatives : pandas.DataFrame ...
Fit and save model parameters based on given data. Parameters ---------- choosers : pandas.DataFrame Table describing the agents making choices, e.g. households. alternatives : pandas.DataFrame Table describing the things from which agents are choosing, ...
def validate_json(data, validator): """Validate data against a given JSON schema (see https://json-schema.org). data: JSON-serializable data to validate. validator (jsonschema.DraftXValidator): The validator. RETURNS (list): A list of error messages, if available. """ errors = [] for err in...
Validate data against a given JSON schema (see https://json-schema.org). data: JSON-serializable data to validate. validator (jsonschema.DraftXValidator): The validator. RETURNS (list): A list of error messages, if available.
def match(self, s): """ Matching the pattern to the input string, returns True/False and saves the matched string in the internal list """ if self.re.match(s): self.list.append(s) return True else: return False
Matching the pattern to the input string, returns True/False and saves the matched string in the internal list
def minimize(bed_file): """ strip a BED file down to its three necessary columns: chrom start end """ if not bed_file: return bed_file else: sorted_bed = bt.BedTool(bed_file).cut(range(3)).sort() if not sorted_bed.fn.endswith(".bed"): return sorted_bed.moveto(sort...
strip a BED file down to its three necessary columns: chrom start end
def _GetAccessToken(self): """Gets oauth2 access token for Gitkit API using service account. Returns: string, oauth2 access token. """ d = { 'assertion': self._GenerateAssertion(), 'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer', } try: body = parse.url...
Gets oauth2 access token for Gitkit API using service account. Returns: string, oauth2 access token.
def available_state(self, state: State) -> Tuple[State, ...]: """ Return the state reachable from a given state. """ result = [] for gene in self.genes: result.extend(self.available_state_for_gene(gene, state)) if len(result) > 1 and state in result: result.remove...
Return the state reachable from a given state.
def validate(self, document, schema=None, update=False, normalize=True): """ Normalizes and validates a mapping against a validation-schema of defined rules. :param document: The document to normalize. :type document: any :term:`mapping` :param schema: The validation schema. Def...
Normalizes and validates a mapping against a validation-schema of defined rules. :param document: The document to normalize. :type document: any :term:`mapping` :param schema: The validation schema. Defaults to :obj:`None`. If not provided here, the schema must ha...
def transition_matrix_reversible_pisym(C, return_statdist=False, **kwargs): r""" Estimates reversible transition matrix as follows: ..:math: p_{ij} = c_{ij} / c_i where c_i = sum_j c_{ij} \pi_j = \sum_j \pi_i p_{ij} x_{ij} = \pi_i p_{ij} + \pi_j p_{ji} p^{rev}_{ij} = x_{ij} ...
r""" Estimates reversible transition matrix as follows: ..:math: p_{ij} = c_{ij} / c_i where c_i = sum_j c_{ij} \pi_j = \sum_j \pi_i p_{ij} x_{ij} = \pi_i p_{ij} + \pi_j p_{ji} p^{rev}_{ij} = x_{ij} / x_i where x_i = sum_j x_{ij} In words: takes the nonreversible transition...
def slice_begin(self, tensor_shape, pnum): """Begin position for the tensor slice for the given processor. Args: tensor_shape: Shape. pnum: int <= self.size. Returns: list of integers with length tensor_shape.ndims. """ tensor_layout = self.tensor_layout(tensor_shape) coordin...
Begin position for the tensor slice for the given processor. Args: tensor_shape: Shape. pnum: int <= self.size. Returns: list of integers with length tensor_shape.ndims.
def get_sorted_hdrgo2usrgos(self, hdrgos, flat_list=None, hdrgo_prt=True, hdrgo_sort=True): """Return GO IDs sorting using go2nt's namedtuple.""" # Return user-specfied sort or default sort of header and user GO IDs sorted_hdrgos_usrgos = [] h2u_get = self.grprobj.hdrgo2usrgos.get ...
Return GO IDs sorting using go2nt's namedtuple.
def cmd_ping(ip, interface, count, timeout, wait, verbose): """The classic ping tool that send ICMP echo requests. \b # habu.ping 8.8.8.8 IP / ICMP 8.8.8.8 > 192.168.0.5 echo-reply 0 / Padding IP / ICMP 8.8.8.8 > 192.168.0.5 echo-reply 0 / Padding IP / ICMP 8.8.8.8 > 192.168.0.5 echo-reply 0 / ...
The classic ping tool that send ICMP echo requests. \b # habu.ping 8.8.8.8 IP / ICMP 8.8.8.8 > 192.168.0.5 echo-reply 0 / Padding IP / ICMP 8.8.8.8 > 192.168.0.5 echo-reply 0 / Padding IP / ICMP 8.8.8.8 > 192.168.0.5 echo-reply 0 / Padding IP / ICMP 8.8.8.8 > 192.168.0.5 echo-reply 0 / Padding
def _add_explicit_includes(lines, dependencies=None, extralinks=None): """Adds any relevant libraries that need to be explicitly included according to the fortpy configuration file. Libraries are appended to the specified collection of lines. Returns true if relevant libraries were added. """ from f...
Adds any relevant libraries that need to be explicitly included according to the fortpy configuration file. Libraries are appended to the specified collection of lines. Returns true if relevant libraries were added.
def parse_error(self, tup_tree): """ Parse the tuple for an ERROR element: :: <!ELEMENT ERROR (INSTANCE*)> <!ATTLIST ERROR CODE CDATA #REQUIRED DESCRIPTION CDATA #IMPLIED> """ self.check_node(tup_tree, 'ERROR', ('CODE',...
Parse the tuple for an ERROR element: :: <!ELEMENT ERROR (INSTANCE*)> <!ATTLIST ERROR CODE CDATA #REQUIRED DESCRIPTION CDATA #IMPLIED>
def extrude( self, input_entity, translation_axis=None, rotation_axis=None, point_on_axis=None, angle=None, num_layers=None, recombine=False, ): """Extrusion (translation + rotation) of any entity along a given translation_axis, around ...
Extrusion (translation + rotation) of any entity along a given translation_axis, around a given rotation_axis, about a given angle. If one of the entities is not provided, this method will produce only translation or rotation.
def setup_address(self, name, address=default, transact={}): """ Set up the name to point to the supplied address. The sender of the transaction must own the name, or its parent name. Example: If the caller owns ``parentname.eth`` with no subdomains and calls this method...
Set up the name to point to the supplied address. The sender of the transaction must own the name, or its parent name. Example: If the caller owns ``parentname.eth`` with no subdomains and calls this method with ``sub.parentname.eth``, then ``sub`` will be created as part of thi...
def create_model( # noqa: C901 (ignore complexity) model_name: str, *, __config__: Type[BaseConfig] = None, __base__: Type[BaseModel] = None, __module__: Optional[str] = None, __validators__: Dict[str, classmethod] = None, **field_definitions: Any, ) -> BaseModel: """ Dynamically cr...
Dynamically create a model. :param model_name: name of the created model :param __config__: config class to use for the new model :param __base__: base class for the new model to inherit from :param __validators__: a dict of method names and @validator class methods :param **field_definitions: field...
def send_response(self, transaction): """ Finalize to add the client to the list of observer. :type transaction: Transaction :param transaction: the transaction that owns the response :return: the transaction unmodified """ host, port = transaction.request.source...
Finalize to add the client to the list of observer. :type transaction: Transaction :param transaction: the transaction that owns the response :return: the transaction unmodified
def get(self, alias: str): """ Retrieve cache identified by alias. Will return always the same instance If the cache was not instantiated yet, it will do it lazily the first time this is called. :param alias: str cache alias :return: cache instance """ t...
Retrieve cache identified by alias. Will return always the same instance If the cache was not instantiated yet, it will do it lazily the first time this is called. :param alias: str cache alias :return: cache instance
def get_field_def( schema: GraphQLSchema, parent_type: GraphQLObjectType, field_name: str ) -> GraphQLField: """Get field definition. This method looks up the field on the given type definition. It has special casing for the two introspection fields, `__schema` and `__typename`. `__typename` is spe...
Get field definition. This method looks up the field on the given type definition. It has special casing for the two introspection fields, `__schema` and `__typename`. `__typename` is special because it can always be queried as a field, even in situations where no other fields are allowed, like on a Un...
def intersect_3d(p1, p2): """Find the closes point for a given set of lines in 3D. Parameters ---------- p1 : (M, N) array_like Starting points p2 : (M, N) array_like End points. Returns ------- x : (N,) ndarray Least-squares solution - the closest point of the ...
Find the closes point for a given set of lines in 3D. Parameters ---------- p1 : (M, N) array_like Starting points p2 : (M, N) array_like End points. Returns ------- x : (N,) ndarray Least-squares solution - the closest point of the intersections. Raises --...
def pred_eq(self, n, val): """ Test if a node set with setint or setstr equal a certain value example:: R = [ __scope__:n ['a' #setint(n, 12) | 'b' #setint(n, 14)] C [#eq(n, 12) D] ] """ v1 = n.value v2 = val if hasattr(val, ...
Test if a node set with setint or setstr equal a certain value example:: R = [ __scope__:n ['a' #setint(n, 12) | 'b' #setint(n, 14)] C [#eq(n, 12) D] ]
def from_body(cls, body): """Create a tunnelling request from a given body of a KNX/IP frame.""" # TODO: Check length request = cls() request.channel = body[1] request.seq = body[2] request.cemi = body[4:] return request
Create a tunnelling request from a given body of a KNX/IP frame.
def insert_code(filename, code, save=True, marker='# ATX CODE END'): """ Auto append code """ content = '' found = False for line in open(filename, 'rb'): if not found and line.strip() == marker: found = True cnt = line.find(marker) content += line[:cnt] + cod...
Auto append code
def validate(identifier): '''Validate a source given its identifier''' source = actions.validate_source(identifier) log.info('Source %s (%s) has been validated', source.slug, str(source.id))
Validate a source given its identifier
def get_repo(self, repo: str, branch: str, *, depth: Optional[int]=1, reference: Optional[Path]=None ) -> Repo: """ Returns a :class:`Repo <git.repo.base.Repo>` instance for the branch. See :meth:`run` for arguments descriptions. """ gi...
Returns a :class:`Repo <git.repo.base.Repo>` instance for the branch. See :meth:`run` for arguments descriptions.
def sleep(seconds=0): """Yield control to another eligible coroutine until at least *seconds* have elapsed. *seconds* may be specified as an integer, or a float if fractional seconds are desired. """ loop = evergreen.current.loop current = Fiber.current() assert loop.task is not current...
Yield control to another eligible coroutine until at least *seconds* have elapsed. *seconds* may be specified as an integer, or a float if fractional seconds are desired.
def stopped(name=None, containers=None, shutdown_timeout=None, unpause=False, error_on_absent=True, **kwargs): ''' Ensure that a container (or containers) is stopped name Name or ID of the container containers Run this state o...
Ensure that a container (or containers) is stopped name Name or ID of the container containers Run this state on more than one container at a time. The following two examples accomplish the same thing: .. code-block:: yaml stopped_containers: docker_...
def from_start_and_end(cls, start, end, sequence, phos_3_prime=False): """Creates a DNA duplex from a start and end point. Parameters ---------- start: [float, float, float] Start of the build axis. end: [float, float, float] End o...
Creates a DNA duplex from a start and end point. Parameters ---------- start: [float, float, float] Start of the build axis. end: [float, float, float] End of build axis. sequence: str Nucleotide sequence. ...
def deserialize(self, buffer=bytes(), index=Index(), **options): """ De-serializes the `Field` from the byte *buffer* starting at the begin of the *buffer* or with the given *index* by unpacking the bytes to the :attr:`value` of the `Field` in accordance with the decoding *byte order* fo...
De-serializes the `Field` from the byte *buffer* starting at the begin of the *buffer* or with the given *index* by unpacking the bytes to the :attr:`value` of the `Field` in accordance with the decoding *byte order* for the de-serialization and the decoding :attr:`byte_order` of the `Fi...
def get_encoded_word(value): """ encoded-word = "=?" charset "?" encoding "?" encoded-text "?=" """ ew = EncodedWord() if not value.startswith('=?'): raise errors.HeaderParseError( "expected encoded word but found {}".format(value)) _3to2list1 = list(value[2:].split('?=', 1)) ...
encoded-word = "=?" charset "?" encoding "?" encoded-text "?="
def _find_errors_param(self): """ Searches for the parameter on the estimator that contains the array of errors that was used to determine the optimal alpha. If it cannot find the parameter then a YellowbrickValueError is raised. """ # NOTE: The order of the search is ve...
Searches for the parameter on the estimator that contains the array of errors that was used to determine the optimal alpha. If it cannot find the parameter then a YellowbrickValueError is raised.
def filter_on_wire_representation(ava, acs, required=None, optional=None): """ :param ava: A dictionary with attributes and values :param acs: List of tuples (Attribute Converter name, Attribute Converter instance) :param required: A list of saml.Attributes :param optional: A list of saml.At...
:param ava: A dictionary with attributes and values :param acs: List of tuples (Attribute Converter name, Attribute Converter instance) :param required: A list of saml.Attributes :param optional: A list of saml.Attributes :return: Dictionary of expected/wanted attributes and values
def load_backend(build_configuration, backend_package): """Installs the given backend package into the build configuration. :param build_configuration the :class:``pants.build_graph.build_configuration.BuildConfiguration`` to install the backend plugin into. :param string backend_package: the package name co...
Installs the given backend package into the build configuration. :param build_configuration the :class:``pants.build_graph.build_configuration.BuildConfiguration`` to install the backend plugin into. :param string backend_package: the package name containing the backend plugin register module that provides...
def _new_convolution(self, use_bias): """Returns new convolution. Args: use_bias: Use bias in convolutions. If False, clean_dict removes bias entries from initializers, partitioners and regularizers passed to the constructor of the convolution. """ def clean_dict(input_dict): ...
Returns new convolution. Args: use_bias: Use bias in convolutions. If False, clean_dict removes bias entries from initializers, partitioners and regularizers passed to the constructor of the convolution.
def _generate_union_tag_vars_funcs(self, union): """Emits the getter methods for retrieving tag-specific state. Setters throw an error in the event an associated tag state variable is accessed without the correct tag state.""" for field in union.all_fields: if not is_void_typ...
Emits the getter methods for retrieving tag-specific state. Setters throw an error in the event an associated tag state variable is accessed without the correct tag state.
def get_url(request, application, roles, label=None): """ Retrieve a link that will work for the current user. """ args = [] if label is not None: args.append(label) # don't use secret_token unless we have to if 'is_admin' in roles: # Administrators can access anything without secre...
Retrieve a link that will work for the current user.