code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def del_repo(repo, **kwargs): ''' Remove an XBPS repository from the system. repo url of repo to remove (persistent). CLI Examples: .. code-block:: bash salt '*' pkg.del_repo <repo url> ''' try: _locate_repo_files(repo, rewrite=True) except IOError: r...
Remove an XBPS repository from the system. repo url of repo to remove (persistent). CLI Examples: .. code-block:: bash salt '*' pkg.del_repo <repo url>
def isoncurve(self, p): """ verifies if a point is on the curve """ return p.iszero() or p.y ** 2 == p.x ** 3 + self.a * p.x + self.b
verifies if a point is on the curve
def _addRawResult(self, resid, values={}, override=False): """ Structure of values dict (dict entry for each analysis/field): {'ALC': {'ALC': '13.55', 'DefaultResult': 'ALC', 'Remarks': ''}, 'CO2': {'CO2': '0.66', 'DefaultR...
Structure of values dict (dict entry for each analysis/field): {'ALC': {'ALC': '13.55', 'DefaultResult': 'ALC', 'Remarks': ''}, 'CO2': {'CO2': '0.66', 'DefaultResult': 'CO2', 'Remarks': ''}, 'Date'...
def delete_server(self, datacenter_id, server_id): """ Removes the server from your data center. :param datacenter_id: The unique ID of the data center. :type datacenter_id: ``str`` :param server_id: The unique ID of the server. :type server_id: ``...
Removes the server from your data center. :param datacenter_id: The unique ID of the data center. :type datacenter_id: ``str`` :param server_id: The unique ID of the server. :type server_id: ``str``
def add_to_dict_val_set(dict_obj, key, val): """Adds the given val to the set mapped by the given key. If the key is missing from the dict, the given mapping is added. Example ------- >>> dict_obj = {'a': set([1, 2])} >>> add_to_dict_val_set(dict_obj, 'a', 2) >>> print(dict_obj['a']) {1...
Adds the given val to the set mapped by the given key. If the key is missing from the dict, the given mapping is added. Example ------- >>> dict_obj = {'a': set([1, 2])} >>> add_to_dict_val_set(dict_obj, 'a', 2) >>> print(dict_obj['a']) {1, 2} >>> add_to_dict_val_set(dict_obj, 'a', 3) ...
def set_version(package_name, version_str): """ Set the version in _version.py to version_str """ current_version = get_version(package_name) version_file_path = helpers.package_file_path('_version.py', package_name) version_file_content = helpers.get_file_content(version_file_path) version_file_con...
Set the version in _version.py to version_str
def render_error(category, error_message, error_codes, exception=None): """ Render an error page. Arguments: category -- The category of the request error_message -- The message to provide to the error template error_codes -- The applicable HTTP error code(s). Will usually be an integer or...
Render an error page. Arguments: category -- The category of the request error_message -- The message to provide to the error template error_codes -- The applicable HTTP error code(s). Will usually be an integer or a list of integers; the HTTP error response will always be the first er...
def _get_url_datafiles(url_db_view, url_db_content, mrio_regex, access_cookie=None): """ Urls of mrio files by parsing url content for mrio_regex Parameters ---------- url_db_view: url str Url which shows the list of mrios in the db url_db_content: url str U...
Urls of mrio files by parsing url content for mrio_regex Parameters ---------- url_db_view: url str Url which shows the list of mrios in the db url_db_content: url str Url which needs to be appended before the url parsed from the url_db_view to get a valid download link m...
def get_next_types(self, n=None): """Gets the next set of ``Types`` in this list. The specified amount must be less than or equal to the return from ``available()``. arg: n (cardinal): the number of ``Type`` elements requested which must be less than or equal to ``av...
Gets the next set of ``Types`` in this list. The specified amount must be less than or equal to the return from ``available()``. arg: n (cardinal): the number of ``Type`` elements requested which must be less than or equal to ``available()`` return: (osid.type.Type) ...
def get_template_as_json(template_id, **kwargs): """ Get a template (including attribute and dataset definitions) as a JSON string. This is just a wrapper around the get_template_as_dict function. """ user_id = kwargs['user_id'] return json.dumps(get_template_as_dict(template_id, user_id...
Get a template (including attribute and dataset definitions) as a JSON string. This is just a wrapper around the get_template_as_dict function.
def add_cli_write_bel_namespace(main: click.Group) -> click.Group: # noqa: D202 """Add a ``write_bel_namespace`` command to main :mod:`click` function.""" @main.command() @click.option('-d', '--directory', type=click.Path(file_okay=False, dir_okay=True), default=os.getcwd(), help='output...
Add a ``write_bel_namespace`` command to main :mod:`click` function.
def module(self, value): """ Setter for **self.__module** attribute. :param value: Attribute value. :type value: ModuleType """ if value is not None: assert type(value) is type(sys), "'{0}' attribute: '{1}' type is not 'module'!".format("module", value) ...
Setter for **self.__module** attribute. :param value: Attribute value. :type value: ModuleType
def all(klass, client, **kwargs): """Returns a Cursor instance for a given resource.""" resource = klass.RESOURCE_COLLECTION request = Request(client, 'get', resource, params=kwargs) return Cursor(klass, request, init_with=[client])
Returns a Cursor instance for a given resource.
def get_hashed_rule_name(event, function, lambda_name): """ Returns an AWS-valid CloudWatch rule name using a digest of the event name, lambda name, and function. This allows support for rule names that may be longer than the 64 char limit. """ event_name = event.get('name', func...
Returns an AWS-valid CloudWatch rule name using a digest of the event name, lambda name, and function. This allows support for rule names that may be longer than the 64 char limit.
def doc_open(): """Build the HTML docs and open them in a web browser.""" doc_index = os.path.join(DOCS_DIRECTORY, 'build', 'html', 'index.html') if sys.platform == 'darwin': # Mac OS X subprocess.check_call(['open', doc_index]) elif sys.platform == 'win32': # Windows sub...
Build the HTML docs and open them in a web browser.
def fetch(self): """ Retrieves the content of the current security document from the remote database and populates the locally cached SecurityDocument object with that content. A call to fetch will overwrite any dictionary content currently in the locally cached SecurityDocument...
Retrieves the content of the current security document from the remote database and populates the locally cached SecurityDocument object with that content. A call to fetch will overwrite any dictionary content currently in the locally cached SecurityDocument object.
def version(self): """Return version of the TR DWE.""" res = self.client.service.Version() return '.'.join([ustr(x) for x in res[0]])
Return version of the TR DWE.
def sendall_stderr(self, s): """ Send data to the channel's "stderr" stream, without allowing partial results. Unlike L{send_stderr}, this method continues to send data from the given string until all data has been sent or an error occurs. Nothing is returned. @...
Send data to the channel's "stderr" stream, without allowing partial results. Unlike L{send_stderr}, this method continues to send data from the given string until all data has been sent or an error occurs. Nothing is returned. @param s: data to send to the client as "stderr" o...
def insert(self, dct, toa=None, comment=""): """Create a document :param dict dct: :param toa toa: Optional time of action, triggers this to be handled as a future insert action for a new document :param str comment: A comment :rtype str: :returns string bson id: ...
Create a document :param dict dct: :param toa toa: Optional time of action, triggers this to be handled as a future insert action for a new document :param str comment: A comment :rtype str: :returns string bson id:
def constraint_join(cfg_nodes): """Looks up all cfg_nodes and joins the bitvectors by using logical or.""" r = 0 for e in cfg_nodes: r = r | constraint_table[e] return r
Looks up all cfg_nodes and joins the bitvectors by using logical or.
def extract_async(self, destination, format='csv', csv_delimiter=None, csv_header=True, compress=False): """Starts a job to export the table to GCS. Args: destination: the destination URI(s). Can be a single URI or a list. format: the format to use for the exported data; one of ...
Starts a job to export the table to GCS. Args: destination: the destination URI(s). Can be a single URI or a list. format: the format to use for the exported data; one of 'csv', 'json', or 'avro' (default 'csv'). csv_delimiter: for CSV exports, the field delimiter to use. Defaults to ',...
def _convert_to_side(cls, side_spec): """ Convert ``side_spec`` to an openpyxl v2 Side object Parameters ---------- side_spec : str, dict A string specifying the border style, or a dict with zero or more of the following keys (or their synonyms). ...
Convert ``side_spec`` to an openpyxl v2 Side object Parameters ---------- side_spec : str, dict A string specifying the border style, or a dict with zero or more of the following keys (or their synonyms). 'style' ('border_style') 'color' ...
def search_for(self, query, include_draft=False): """ Search for a query text. :param query: keyword to query :param include_draft: return draft posts/pages or not :return: an iterable object of posts and pages (if allowed). """ query = query.lower() if n...
Search for a query text. :param query: keyword to query :param include_draft: return draft posts/pages or not :return: an iterable object of posts and pages (if allowed).
def handle_get(self): """Handle a single HTTP GET request. Default implementation indicates an error because XML-RPC uses the POST method. """ code = 400 message, explain = \ BaseHTTPServer.BaseHTTPRequestHandler.responses[code] response = Base...
Handle a single HTTP GET request. Default implementation indicates an error because XML-RPC uses the POST method.
def child(self, subkey): """ Retrieves a subkey for this Registry key, given its name. @type subkey: str @param subkey: Name of the subkey. @rtype: L{RegistryKey} @return: Subkey. """ path = self._path + '\\' + subkey handle = win32.RegOpenKey(...
Retrieves a subkey for this Registry key, given its name. @type subkey: str @param subkey: Name of the subkey. @rtype: L{RegistryKey} @return: Subkey.
def create_domainalias(self, domainid, data): """Create a domain alias""" return self.api_call( ENDPOINTS['domainaliases']['new'], dict(domainid=domainid), body=data)
Create a domain alias
def deploy(cls, remote_name, branch): """Deploy a PaaS instance.""" def get_remote_url(remote): return 'git config --local --get remote.%s.url' % (remote) remote_url = cls.exec_output(get_remote_url(remote_name)) \ .replace('\n', '') if not remote_url or not re....
Deploy a PaaS instance.
def pdf(self, d, n=None): r'''Computes the probability density function of a continuous particle size distribution at a specified particle diameter, an optionally in a specified basis. The evaluation function varies with the distribution chosen. The interconversion between distribution ...
r'''Computes the probability density function of a continuous particle size distribution at a specified particle diameter, an optionally in a specified basis. The evaluation function varies with the distribution chosen. The interconversion between distribution orders is performed using ...
def parse_char(self, c): '''input some data bytes, possibly returning a new message''' self.buf.extend(c) self.total_bytes_received += len(c) if self.native: if native_testing: self.test_buf.extend(c) m = self.__pa...
input some data bytes, possibly returning a new message
def _construct(self): """ Construct a control dependence graph. This implementation is based on figure 6 of paper An Efficient Method of Computing Static Single Assignment Form by Ron Cytron, etc. """ self._acyclic_cfg = self._cfg.copy() # TODO: Cycle-removing i...
Construct a control dependence graph. This implementation is based on figure 6 of paper An Efficient Method of Computing Static Single Assignment Form by Ron Cytron, etc.
def remove_all_servers(self): """ Remove all registered WBEM servers from the subscription manager. This also unregisters listeners from these servers and removes all owned indication subscriptions, owned indication filters, and owned listener destinations. Raises: ...
Remove all registered WBEM servers from the subscription manager. This also unregisters listeners from these servers and removes all owned indication subscriptions, owned indication filters, and owned listener destinations. Raises: Exceptions raised by :class:`~pywbem.WBEMC...
def _generate_create_callable(name, display_name, arguments, regex, doc, supported, post_arguments, is_action): """ Returns a callable which conjures the URL for the resource and POSTs data """ def f(self, *args, **kwargs): for key, value in args[-1].items(): if type(value) == file: ...
Returns a callable which conjures the URL for the resource and POSTs data
def _year_expand(s): """ Parses a year or dash-delimeted year range """ regex = r"^((?:19|20)\d{2})?(\s*-\s*)?((?:19|20)\d{2})?$" try: start, dash, end = match(regex, ustr(s)).groups() start = start or 1900 end = end or 2099 except AttributeErr...
Parses a year or dash-delimeted year range
def array_equiv(arr1, arr2): """Like np.array_equal, but also allows values to be NaN in both arrays """ arr1, arr2 = as_like_arrays(arr1, arr2) if arr1.shape != arr2.shape: return False with warnings.catch_warnings(): warnings.filterwarnings('ignore', "In the future, 'NAT == x'") ...
Like np.array_equal, but also allows values to be NaN in both arrays
def _reregister_tree_admin(): """Forces unregistration of tree admin class with following re-registration.""" try: admin.site.unregister(MODEL_TREE_CLASS) except NotRegistered: pass admin.site.register(MODEL_TREE_CLASS, _TREE_ADMIN())
Forces unregistration of tree admin class with following re-registration.
def electric_field_amplitude_intensity(s0, Isat=16.6889462814, Omega=1e6, units="ad-hoc"): """Return the amplitude of the electric field for saturation parameter. This is at a given saturation parameter s0=I/Isat, where I0 is by default \ Isat=16.6889462814 m/m^2 is ...
Return the amplitude of the electric field for saturation parameter. This is at a given saturation parameter s0=I/Isat, where I0 is by default \ Isat=16.6889462814 m/m^2 is the saturation intensity of the D2 line of \ rubidium for circularly polarized light. Optionally, a frequency scale \ `Omega` can be prov...
def _attrib_to_transform(attrib): """ Extract a homogenous transform from a dictionary. Parameters ------------ attrib: dict, optionally containing 'transform' Returns ------------ transform: (4, 4) float, homogeonous transformation """ transform = np.eye(4, dtype=np.float64) ...
Extract a homogenous transform from a dictionary. Parameters ------------ attrib: dict, optionally containing 'transform' Returns ------------ transform: (4, 4) float, homogeonous transformation
def expand_template(template, value): """ :param template: A UNICODE STRING WITH VARIABLE NAMES IN MOUSTACHES `{{.}}` :param value: Data HOLDING THE PARAMTER VALUES :return: UNICODE STRING WITH VARIABLES EXPANDED """ value = wrap(value) if is_text(template): return _simple_expand(tem...
:param template: A UNICODE STRING WITH VARIABLE NAMES IN MOUSTACHES `{{.}}` :param value: Data HOLDING THE PARAMTER VALUES :return: UNICODE STRING WITH VARIABLES EXPANDED
def show_doc(elt, doc_string:bool=True, full_name:str=None, arg_comments:dict=None, title_level=None, alt_doc_string:str='', ignore_warn:bool=False, markdown=True, show_tests=True): "Show documentation for element `elt`. Supported types: class, Callable, and enum." arg_comments = ifnone(arg_comment...
Show documentation for element `elt`. Supported types: class, Callable, and enum.
def observable( _method_or_viewset=None, poll_interval=None, primary_key=None, dependencies=None ): """Make ViewSet or ViewSet method observable. Decorating a ViewSet class is the same as decorating its `list` method. If decorated method returns a response containing a list of items, it must use t...
Make ViewSet or ViewSet method observable. Decorating a ViewSet class is the same as decorating its `list` method. If decorated method returns a response containing a list of items, it must use the provided `LimitOffsetPagination` for any pagination. In case a non-list response is returned, the result...
def create_ml_configuration_from_datasets(self, dataset_ids): """ Creates an ml configuration from dataset_ids and extract_as_keys :param dataset_ids: Array of dataset identifiers to make search template from :return: An identifier used to request the status of the builder job (get_ml_c...
Creates an ml configuration from dataset_ids and extract_as_keys :param dataset_ids: Array of dataset identifiers to make search template from :return: An identifier used to request the status of the builder job (get_ml_configuration_status)
def logout(): """ Remove the authenticated user's ID from the request. """ from uliweb import request delete_user_session() request.session.delete() request.user = None return True
Remove the authenticated user's ID from the request.
def do_class(self, element, decl, pseudo): """Implement class declaration - pre-match.""" step = self.state[self.state['current_step']] actions = step['actions'] strval = self.eval_string_value(element, decl.value) actions.append(('attrib', ('class', strval)))
Implement class declaration - pre-match.
def _purge_expired(self): """ Remove all expired entries from the cache. """ time_horizon = time.time() - self._keep_time new_cache = {} for (k, v) in self._cache.items(): if v.timestamp > time_horizon: new_cache[k] = v self._cache = ne...
Remove all expired entries from the cache.
def repeat(self, n=2, oscillate=False, callback=None): """ Returns a list that is a repetition of the given list. When oscillate is True, moves from the end back to the beginning, and then from the beginning to the end, and so on. """ colorlist = ColorList() ...
Returns a list that is a repetition of the given list. When oscillate is True, moves from the end back to the beginning, and then from the beginning to the end, and so on.
def tofile(self, f): """Serialize this ScalableBloomFilter into the file-object `f'.""" f.write(pack(self.FILE_FMT, self.scale, self.ratio, self.initial_capacity, self.error_rate)) # Write #-of-filters f.write(pack(b'<l', len(self.filters))) if len(...
Serialize this ScalableBloomFilter into the file-object `f'.
def fix_empty_methods(source): """ Appends 'pass' to empty methods/functions (i.e. where there was nothing but a docstring before we removed it =). Example:: # Note: This triple-single-quote inside a triple-double-quote is also a # pyminifier self-test def myfunc(): ...
Appends 'pass' to empty methods/functions (i.e. where there was nothing but a docstring before we removed it =). Example:: # Note: This triple-single-quote inside a triple-double-quote is also a # pyminifier self-test def myfunc(): '''This is just a placeholder function.'''...
def call(command, working_directory=config.BASE_DIR): """ Executes shell command in a given working_directory. Command is a list of strings to execute as a command line. Returns a tuple of two byte strings: (stdout, stderr) """ LOG.info(command) proc = sp.Popen(command, stdout=sp.PIPE, stde...
Executes shell command in a given working_directory. Command is a list of strings to execute as a command line. Returns a tuple of two byte strings: (stdout, stderr)
def new_cast_status(self, status): """ Called when a new status received from the Chromecast. """ self.status = status if status: self.status_event.set()
Called when a new status received from the Chromecast.
def get_all_children(self, include_self=False): """ Return all subsidiaries of this company. """ ownership = Ownership.objects.filter(parent=self) subsidiaries = Company.objects.filter(child__in=ownership) for sub in subsidiaries: subsidiaries = subsidiaries |...
Return all subsidiaries of this company.
def fetch_action_restriction(self, reftrack, action): """Return wheter the given action is restricted for the given reftrack available actions are: ``reference``, ``load``, ``unload``, ``replace``, ``import_reference``, ``import_taskfile``, ``delete`` If action is not available, Tr...
Return wheter the given action is restricted for the given reftrack available actions are: ``reference``, ``load``, ``unload``, ``replace``, ``import_reference``, ``import_taskfile``, ``delete`` If action is not available, True is returned. :param reftrack: the reftrack to query ...
def getSignature(self, signatureKey, serialized): """ :type signatureKey: ECPrivateKey :type serialized: bytearray """ try: return Curve.calculateSignature(signatureKey, serialized) except InvalidKeyException as e: raise AssertionError(e)
:type signatureKey: ECPrivateKey :type serialized: bytearray
def _constructClassificationRecord(self, inputs): """ Construct a _HTMClassificationRecord based on the state of the model passed in through the inputs. Types for self.classificationVectorType: 1 - TM active cells in learn state 2 - SP columns concatenated with error from TM column predicti...
Construct a _HTMClassificationRecord based on the state of the model passed in through the inputs. Types for self.classificationVectorType: 1 - TM active cells in learn state 2 - SP columns concatenated with error from TM column predictions and SP
def assert_condition_md5(self): """If the ``Content-MD5`` request header is present in the request it's verified against the MD5 hash of the request body. If they don't match, a 400 HTTP response is returned. :raises: :class:`webob.exceptions.ResponseException` of status 400 if ...
If the ``Content-MD5`` request header is present in the request it's verified against the MD5 hash of the request body. If they don't match, a 400 HTTP response is returned. :raises: :class:`webob.exceptions.ResponseException` of status 400 if the MD5 hash does not match the bo...
def predict_condition_models(self, model_names, input_columns, metadata_cols, data_mode="forecast", ): """ Apply condition modelsto forecast data. Args: ...
Apply condition modelsto forecast data. Args: model_names: List of names associated with each condition model used for prediction input_columns: List of columns in data used as input into the model metadata_cols: Columns from input data that should be included in the data fra...
def set_state(self, entity_id, new_state, **kwargs): "Updates or creates the current state of an entity." return remote.set_state(self.api, new_state, **kwargs)
Updates or creates the current state of an entity.
def database_remove_tags(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /database-xxxx/removeTags API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Tags#API-method%3A-%2Fclass-xxxx%2FremoveTags """ return DXHTTPRequest('/%s/removeTags' % o...
Invokes the /database-xxxx/removeTags API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Tags#API-method%3A-%2Fclass-xxxx%2FremoveTags
def refresh_db(**kwargs): ''' Update list of available packages from installed repos CLI Example: .. code-block:: bash salt '*' pkg.refresh_db ''' # Remove rtag file to keep multiple refreshes from happening in pkg states salt.utils.pkg.clear_rtag(__opts__) cmd = 'xbps-install...
Update list of available packages from installed repos CLI Example: .. code-block:: bash salt '*' pkg.refresh_db
def keygen(sk_file=None, pk_file=None, **kwargs): ''' Use libnacl to generate a keypair. If no `sk_file` is defined return a keypair. If only the `sk_file` is defined `pk_file` will use the same name with a postfix `.pub`. When the `sk_file` is already existing, but `pk_file` is not. The `pk_file...
Use libnacl to generate a keypair. If no `sk_file` is defined return a keypair. If only the `sk_file` is defined `pk_file` will use the same name with a postfix `.pub`. When the `sk_file` is already existing, but `pk_file` is not. The `pk_file` will be generated using the `sk_file`. CLI Examples...
def list_pkgs(versions_as_list=False, **kwargs): ''' List the packages currently installed as a dict:: {'<package_name>': '<version>'} CLI Example: .. code-block:: bash salt '*' pkg.list_pkgs ''' versions_as_list = salt.utils.data.is_true(versions_as_list) # not yet imple...
List the packages currently installed as a dict:: {'<package_name>': '<version>'} CLI Example: .. code-block:: bash salt '*' pkg.list_pkgs
def old_unpad(s): """ Removes padding from an input string based on a given block size. :param s: string :returns: The unpadded string. """ if not s: return s try: return Padding.removePadding(s, blocksize=OLD_BLOCK_SIZE) except AssertionError: # if there's an er...
Removes padding from an input string based on a given block size. :param s: string :returns: The unpadded string.
def monitor_deletion(): """ Function for checking for correct deletion of weakref-able objects. Example usage:: monitor, is_alive = monitor_deletion() obj = set() monitor(obj, "obj") assert is_alive("obj") # True because there is a ref to `obj` is_alive del obj ...
Function for checking for correct deletion of weakref-able objects. Example usage:: monitor, is_alive = monitor_deletion() obj = set() monitor(obj, "obj") assert is_alive("obj") # True because there is a ref to `obj` is_alive del obj assert not is_alive("obj") # Tru...
def remove_bad_sequence(codon_list, bad_seq, bad_seqs): """ Make a silent mutation to the given codon list to remove the first instance of the given bad sequence found in the gene sequence. If the bad sequence isn't found, nothing happens and the function returns false. Otherwise the function r...
Make a silent mutation to the given codon list to remove the first instance of the given bad sequence found in the gene sequence. If the bad sequence isn't found, nothing happens and the function returns false. Otherwise the function returns true. You can use these return values to easily write a ...
def create_border(self, border_style_type): """ Create a new MenuBorderStyle instance based on the given border style type. Args: border_style_type (int): an integer value from :obj:`MenuBorderStyleType`. Returns: :obj:`MenuBorderStyle`: a new MenuBorderStyle i...
Create a new MenuBorderStyle instance based on the given border style type. Args: border_style_type (int): an integer value from :obj:`MenuBorderStyleType`. Returns: :obj:`MenuBorderStyle`: a new MenuBorderStyle instance of the specified style.
def list_kubernetes_roles(self, mount_point='kubernetes'): """GET /auth/<mount_point>/role?list=true :param mount_point: The "path" the k8s auth backend was mounted on. Vault currently defaults to "kubernetes". :type mount_point: str. :return: Parsed JSON response from the list roles GE...
GET /auth/<mount_point>/role?list=true :param mount_point: The "path" the k8s auth backend was mounted on. Vault currently defaults to "kubernetes". :type mount_point: str. :return: Parsed JSON response from the list roles GET request. :rtype: dict.
def lookup( name, rdtype, method=None, servers=None, timeout=None, walk=False, walk_tld=False, secure=None ): ''' Lookup DNS records and return their data :param name: name to lookup :param rdtype: DNS record type :param method: gai (getaddrinfo()), dnspython, dig, d...
Lookup DNS records and return their data :param name: name to lookup :param rdtype: DNS record type :param method: gai (getaddrinfo()), dnspython, dig, drill, host, nslookup or auto (default) :param servers: (list of) server(s) to try in-order :param timeout: query timeout or a valiant approximatio...
def read_hier_references(jams_file, annotation_id=0, exclude_levels=[]): """Reads hierarchical references from a jams file. Parameters ---------- jams_file : str Path to the jams file. annotation_id : int > 0 Identifier of the annotator to read from. exclude_levels: list ...
Reads hierarchical references from a jams file. Parameters ---------- jams_file : str Path to the jams file. annotation_id : int > 0 Identifier of the annotator to read from. exclude_levels: list List of levels to exclude. Empty list to include all levels. Returns -...
def getWidget(self): """Some ideas for your widget: - Textual information (alert, license place number) - Check boxes : if checked, send e-mail to your mom when the analyzer spots something - .. or send an sms to yourself - You can include the cv2.imshow window to the widget to s...
Some ideas for your widget: - Textual information (alert, license place number) - Check boxes : if checked, send e-mail to your mom when the analyzer spots something - .. or send an sms to yourself - You can include the cv2.imshow window to the widget to see how the analyzer proceeds
def get_subfields(self, datafield, subfield, i1=None, i2=None, exception=False): """ Return content of given `subfield` in `datafield`. Args: datafield (str): Section name (for example "001", "100", "700"). subfield (str): Subfield name (for exampl...
Return content of given `subfield` in `datafield`. Args: datafield (str): Section name (for example "001", "100", "700"). subfield (str): Subfield name (for example "a", "1", etc..). i1 (str, default None): Optional i1/ind1 parameter value, which will be used...
def search(self, **kwargs): """ Method to search ipv6's based on extends search. :param search: Dict containing QuerySets to find ipv6's. :param include: Array containing fields to include on response. :param exclude: Array containing fields to exclude on response. :para...
Method to search ipv6's based on extends search. :param search: Dict containing QuerySets to find ipv6's. :param include: Array containing fields to include on response. :param exclude: Array containing fields to exclude on response. :param fields: Array containing fields to override d...
def receive_callback(request): """ Parses SSO callback, validates, retrieves :model:`esi.Token`, and internally redirects to the target url. """ logger.debug("Received callback for {0} session {1}".format(request.user, request.session.session_key[:5])) # make sure request has required parameters ...
Parses SSO callback, validates, retrieves :model:`esi.Token`, and internally redirects to the target url.
def read_gene2acc(file_path, logger): """Extracts Entrez ID -> gene symbol mapping from gene2accession.gz file. Parameters ---------- file_path: str The path of the gene2accession.gz file (or a filtered version thereof). The file may be gzip'ed. Returns ------- dict ...
Extracts Entrez ID -> gene symbol mapping from gene2accession.gz file. Parameters ---------- file_path: str The path of the gene2accession.gz file (or a filtered version thereof). The file may be gzip'ed. Returns ------- dict A mapping of Entrez IDs to gene symbols.
def merge_duplicates(self): """Merge and remove duplicate entries. Compares each entry ('name') in `stubs` to all later entries to check for duplicates in name or alias. If a duplicate is found, they are merged and written to file. """ if len(self.entries) == 0: ...
Merge and remove duplicate entries. Compares each entry ('name') in `stubs` to all later entries to check for duplicates in name or alias. If a duplicate is found, they are merged and written to file.
def vsan_add_disks(host, username, password, protocol=None, port=None, host_names=None): ''' Add any VSAN-eligible disks to the VSAN System for the given host or list of host_names. host The location of the host. username The username used to login to the host, such as ``root``. p...
Add any VSAN-eligible disks to the VSAN System for the given host or list of host_names. host The location of the host. username The username used to login to the host, such as ``root``. password The password used to login to the host. protocol Optionally set to alter...
def transform(self, data): """ Transform the SFrame `data` using a fitted model. Parameters ---------- data : SFrame The data to be transformed. Returns ------- A transformed SFrame. Returns ------- out: SFrame ...
Transform the SFrame `data` using a fitted model. Parameters ---------- data : SFrame The data to be transformed. Returns ------- A transformed SFrame. Returns ------- out: SFrame A transformed SFrame. See Also ...
def issubset(self, other): """Report whether another set contains this RangeSet.""" self._binary_sanity_check(other) return set.issubset(self, other)
Report whether another set contains this RangeSet.
def old_status(self, old_status): """ Sets the old_status of this BuildSetStatusChangedEvent. :param old_status: The old_status of this BuildSetStatusChangedEvent. :type: str """ allowed_values = ["NEW", "DONE", "REJECTED"] if old_status not in allowed_values: ...
Sets the old_status of this BuildSetStatusChangedEvent. :param old_status: The old_status of this BuildSetStatusChangedEvent. :type: str
def delete_service(self, name): """ Delete a service by name. @param name: Service name @return: The deleted ApiService object """ return services.delete_service(self._get_resource_root(), name, self.name)
Delete a service by name. @param name: Service name @return: The deleted ApiService object
def dirs(self, *args, **kwargs): """ D.dirs() -> List of this directory's subdirectories. The elements of the list are Path objects. This does not walk recursively into subdirectories (but see :meth:`walkdirs`). Accepts parameters to :meth:`listdir`. """ return ...
D.dirs() -> List of this directory's subdirectories. The elements of the list are Path objects. This does not walk recursively into subdirectories (but see :meth:`walkdirs`). Accepts parameters to :meth:`listdir`.
def _build_ip_constraints(roles, ips, constraints): """Generate the constraints at the ip/device level. Those constraints are those used by ansible to enforce tc/netem rules. """ local_ips = copy.deepcopy(ips) for constraint in constraints: gsrc = constraint['src'] gdst = constraint[...
Generate the constraints at the ip/device level. Those constraints are those used by ansible to enforce tc/netem rules.
def _node_add_with_peer_leaflist(self, child_self, child_other): '''_node_add_with_peer_leaflist Low-level api: Apply delta child_other to child_self when child_self is the peer of child_other. Element child_self and child_other are leaf-list nodes. Element child_self will be modified d...
_node_add_with_peer_leaflist Low-level api: Apply delta child_other to child_self when child_self is the peer of child_other. Element child_self and child_other are leaf-list nodes. Element child_self will be modified during the process. RFC6020 section 7.7.7 is a reference of this meth...
def all_tamil( word_in ): """ predicate checks if all letters of the input word are Tamil letters """ if isinstance(word_in,list): word = word_in else: word = get_letters( word_in ) return all( [(letter in tamil_letters) for letter in word] )
predicate checks if all letters of the input word are Tamil letters
def check_permissions(self, request): """Call the predicate(s) associated with the RPC method, to check if the current request can actually call the method. Return a boolean indicating if the method should be executed (True) or not (False)""" if not self.predicates: return T...
Call the predicate(s) associated with the RPC method, to check if the current request can actually call the method. Return a boolean indicating if the method should be executed (True) or not (False)
def size(self, t=None): """Return the number of edges at time t. Parameters ---------- t : snapshot id (default=None) If None will be returned the size of the flattened graph. Returns ------- nedges : int The number of edges See...
Return the number of edges at time t. Parameters ---------- t : snapshot id (default=None) If None will be returned the size of the flattened graph. Returns ------- nedges : int The number of edges See Also -------- numb...
def SegmentCollection(mode="agg-fast", *args, **kwargs): """ mode: string - "raw" (speed: fastest, size: small, output: ugly, no dash, no thickness) - "agg" (speed: slower, size: medium, output: perfect, no dash) """ if mode == "raw": return RawSegmentCollection(*args...
mode: string - "raw" (speed: fastest, size: small, output: ugly, no dash, no thickness) - "agg" (speed: slower, size: medium, output: perfect, no dash)
def build_accumulate(function: Callable[[Any, Any], Tuple[Any, Any]] = None, *, init: Any = NONE): """ Decorator to wrap a function to return an Accumulate operator. :param function: function to be wrapped :param init: optional initialization for state """ _init = init def...
Decorator to wrap a function to return an Accumulate operator. :param function: function to be wrapped :param init: optional initialization for state
def publish(self, value): """ Accepts: list of tuples in the format (ip, port) Returns: unicode """ if not isinstance(value, list): raise ValueError(value) slaves = ['%s:%d' % x for x in value] return unicode(", ".join(slaves))
Accepts: list of tuples in the format (ip, port) Returns: unicode
def nullify(function): "Decorator. If empty list, returns None, else list." def wrapper(*args, **kwargs): value = function(*args, **kwargs) if(type(value) == list and len(value) == 0): return None return value return wrapper
Decorator. If empty list, returns None, else list.
def visit_module(self, node): """ A interface will be called when visiting a module. @param node: node of current module """ if not node.file_stream: # failed to open the module return text = node.file_stream.read() self._checkCopyright(te...
A interface will be called when visiting a module. @param node: node of current module
def _compute_stacksize(self): ''' Given this object's code list, compute its maximal stack usage. This is done by scanning the code, and computing for each opcode the stack state at the opcode. ''' # get local access to code, save some attribute lookups later co...
Given this object's code list, compute its maximal stack usage. This is done by scanning the code, and computing for each opcode the stack state at the opcode.
def delete_script(delete=None): # noqa: E501 """Delete a script Delete a script # noqa: E501 :param delete: The data needed to delete this script :type delete: dict | bytes :rtype: Response """ if connexion.request.is_json: delete = Delete.from_dict(connexion.request.get_json()) ...
Delete a script Delete a script # noqa: E501 :param delete: The data needed to delete this script :type delete: dict | bytes :rtype: Response
def transform_velocity_array(array, pos_array, vel, euler, rotation_vel=(0,0,0)): """ Transform any Nx3 velocity vector array by adding the center-of-mass 'vel', accounting for solid-body rotation, and applying an euler transformation. :parameter array array: numpy array of Nx3 velocity vectors in the ...
Transform any Nx3 velocity vector array by adding the center-of-mass 'vel', accounting for solid-body rotation, and applying an euler transformation. :parameter array array: numpy array of Nx3 velocity vectors in the original (star) coordinate frame :parameter array pos_array: positions of the elem...
def get_market_last(symbols=None, **kwargs): """ MOVED to iexfinance.iexdata.get_last """ import warnings warnings.warn(WNG_MSG % ("get_market_last", "iexdata.get_last")) return Last(symbols, **kwargs).fetch()
MOVED to iexfinance.iexdata.get_last
def index_transcriptome(gtf_file, ref_file, data): """ use a GTF file and a reference FASTA file to index the transcriptome """ gtf_fasta = gtf.gtf_to_fasta(gtf_file, ref_file) bowtie2_index = os.path.splitext(gtf_fasta)[0] bowtie2_build = config_utils.get_program("bowtie2", data["config"]) + "-...
use a GTF file and a reference FASTA file to index the transcriptome
def do_read(self, args): """Receive from the resource in use.""" if not self.current: print('There are no resources in use. Use the command "open".') return try: print(self.current.read()) except Exception as e: print(e)
Receive from the resource in use.
def add_lambda_integration(self): """Attach lambda found to API.""" lambda_uri = self.generate_uris()['lambda_uri'] self.client.put_integration( restApiId=self.api_id, resourceId=self.resource_id, httpMethod=self.trigger_settings['method'], integra...
Attach lambda found to API.
def read_value(self, dtype='uint64', count=1, advance=True): """ Read one or more scalars of the indicated dtype. Count specifies the number of scalars to be read in. """ data = np.frombuffer(self._blob, dtype=dtype, count=count, offset=self.pos) if advance: #...
Read one or more scalars of the indicated dtype. Count specifies the number of scalars to be read in.
def from_body(self, param_name, schema): """ A decorator that converts the request body into a function parameter based on the specified schema. :param param_name: The parameter which receives the argument. :param schema: The schema class or instance used to deserialize the request body...
A decorator that converts the request body into a function parameter based on the specified schema. :param param_name: The parameter which receives the argument. :param schema: The schema class or instance used to deserialize the request body toa Python object. :return: A function
def _NDP_Attack_DAD_DoS(reply_callback, iface=None, mac_src_filter=None, tgt_filter=None, reply_mac=None): """ Internal generic helper accepting a specific callback as first argument, for NS or NA reply. See the two specific functions below. """ def is_request(req, mac_src_f...
Internal generic helper accepting a specific callback as first argument, for NS or NA reply. See the two specific functions below.
def add_filter_by_pattern(self, pattern, filter_type=DefaultFilterType): """ Add a files filter by linux-style pattern to this iterator. :param pattern: linux-style files pattern (or list of patterns) """ self.add_filter(FilterPattern(pattern), filter_type) return self
Add a files filter by linux-style pattern to this iterator. :param pattern: linux-style files pattern (or list of patterns)