code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def buildTreeFromAlignment(filename,WorkingDir=None,SuppressStderr=None): """Builds a new tree from an existing alignment filename: string, name of file containing the seqs or alignment """ app = Clustalw({'-tree':None,'-infile':filename},SuppressStderr=\ SuppressStderr,WorkingDir=WorkingDir) ...
Builds a new tree from an existing alignment filename: string, name of file containing the seqs or alignment
def simxGetIntegerParameter(clientID, paramIdentifier, operationMode): ''' Please have a look at the function description/documentation in the V-REP user manual ''' paramValue = ct.c_int() return c_GetIntegerParameter(clientID, paramIdentifier, ct.byref(paramValue), operationMode), paramValue.value
Please have a look at the function description/documentation in the V-REP user manual
def partial(__fn, *a, **kw): """Wrap a note for injection of a partially applied function. This allows for annotated functions to be injected for composition:: from jeni import annotate @annotate('foo', bar=annotate.maybe('bar')) def foobar(foo, bar=None): ...
Wrap a note for injection of a partially applied function. This allows for annotated functions to be injected for composition:: from jeni import annotate @annotate('foo', bar=annotate.maybe('bar')) def foobar(foo, bar=None): return @annotate('f...
def read(self, size): """ Read wrapper. Parameters ---------- size : int Number of bytes to read. """ try: return_val = self.handle.read(size) if return_val == '': print() print("Piksi disconnected...
Read wrapper. Parameters ---------- size : int Number of bytes to read.
def _start_app_and_connect(self): """Starts snippet apk on the device and connects to it. After prechecks, this launches the snippet apk with an adb cmd in a standing subprocess, checks the cmd response from the apk for protocol version, then sets up the socket connection over adb port-...
Starts snippet apk on the device and connects to it. After prechecks, this launches the snippet apk with an adb cmd in a standing subprocess, checks the cmd response from the apk for protocol version, then sets up the socket connection over adb port-forwarding. Args: Protoc...
def unregister(self, gadgets): """ Unregisters the specified gadget(s) if it/they has/have already been registered. "gadgets" can be a single class or a tuple/list of classes to unregister. """ gadgets = maintenance.ensure_list(gadgets) for gadget in gadgets: ...
Unregisters the specified gadget(s) if it/they has/have already been registered. "gadgets" can be a single class or a tuple/list of classes to unregister.
def output(self): """! @brief Returns output dynamic of the network. """ if (self.__ccore_legion_dynamic_pointer is not None): return wrapper.legion_dynamic_get_output(self.__ccore_legion_dynamic_pointer); return self.__output;
! @brief Returns output dynamic of the network.
def cors_wrapper(func): """ Decorator for CORS :param func: Flask method that handles requests and returns a response :return: Same, but with permissive CORS headers set """ def _setdefault(obj, key, value): if value == None: return obj.setdefault(key, value) de...
Decorator for CORS :param func: Flask method that handles requests and returns a response :return: Same, but with permissive CORS headers set
def rename(name, new_name): ''' Change the username for a named user Args: name (str): The user name to change new_name (str): The new name for the current user Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' use...
Change the username for a named user Args: name (str): The user name to change new_name (str): The new name for the current user Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' user.rename jsnuffy jshmoe
def conditions(self): """The if-else pairs.""" for idx in six.moves.range(1, len(self.children), 2): yield (self.children[idx - 1], self.children[idx])
The if-else pairs.
def matrix_mult_opt_order(M): """Matrix chain multiplication optimal order :param M: list of matrices :returns: matrices opt, arg, such that opt[i][j] is the optimal number of operations to compute M[i] * ... * M[j] when done in the order (M[i] * ... * M[k]) * (M[k + 1] * ... * ...
Matrix chain multiplication optimal order :param M: list of matrices :returns: matrices opt, arg, such that opt[i][j] is the optimal number of operations to compute M[i] * ... * M[j] when done in the order (M[i] * ... * M[k]) * (M[k + 1] * ... * M[j]) for k = arg[i][j] :complexi...
def push_zipkin_attrs(zipkin_attr): """Stores the zipkin attributes to thread local. .. deprecated:: Use the Tracer interface which offers better multi-threading support. push_zipkin_attrs will be removed in version 1.0. :param zipkin_attr: tuple containing zipkin related attrs :type zip...
Stores the zipkin attributes to thread local. .. deprecated:: Use the Tracer interface which offers better multi-threading support. push_zipkin_attrs will be removed in version 1.0. :param zipkin_attr: tuple containing zipkin related attrs :type zipkin_attr: :class:`zipkin.ZipkinAttrs`
def __Login(host, port, user, pwd, service, adapter, version, path, keyFile, certFile, thumbprint, sslContext, connectionPoolTimeout=CONNECTION_POOL_IDLE_TIMEOUT_SEC): """ Private method that performs the actual Connect and returns a connected service instance object. @param host: W...
Private method that performs the actual Connect and returns a connected service instance object. @param host: Which host to connect to. @type host: string @param port: Port @type port: int @param user: User @type user: string @param pwd: Password @type pwd: string @param service: Serv...
def read_parquet(cls, path, engine, columns, **kwargs): """Load a parquet object from the file path, returning a DataFrame. Ray DataFrame only supports pyarrow engine for now. Args: path: The filepath of the parquet file. We only support local files for now. ...
Load a parquet object from the file path, returning a DataFrame. Ray DataFrame only supports pyarrow engine for now. Args: path: The filepath of the parquet file. We only support local files for now. engine: Ray only support pyarrow reader. ...
def search_text(self, text_cursor, search_txt, search_flags): """ Searches a text in a text document. :param text_cursor: Current text cursor :param search_txt: Text to search :param search_flags: QTextDocument.FindFlags :returns: the list of occurrences, the current occ...
Searches a text in a text document. :param text_cursor: Current text cursor :param search_txt: Text to search :param search_flags: QTextDocument.FindFlags :returns: the list of occurrences, the current occurrence index :rtype: tuple([], int)
def disable_ipv6(): """ Disable ufw IPv6 support in /etc/default/ufw """ exit_code = subprocess.call(['sed', '-i', 's/IPV6=.*/IPV6=no/g', '/etc/default/ufw']) if exit_code == 0: hookenv.log('IPv6 support in ufw disabled', level='INFO') else: hooke...
Disable ufw IPv6 support in /etc/default/ufw
def result(self, state, row): "Place the next queen at the given row." col = state.index(None) new = state[:] new[col] = row return new
Place the next queen at the given row.
def get_attrs(self, *names): """Get multiple attributes from multiple objects.""" attrs = [getattr(self, name) for name in names] return attrs
Get multiple attributes from multiple objects.
def is_special_orthogonal( matrix: np.ndarray, *, rtol: float = 1e-5, atol: float = 1e-8) -> bool: """Determines if a matrix is approximately special orthogonal. A matrix is special orthogonal if it is square and real and its transpose is its inverse and its determinant is o...
Determines if a matrix is approximately special orthogonal. A matrix is special orthogonal if it is square and real and its transpose is its inverse and its determinant is one. Args: matrix: The matrix to check. rtol: The per-matrix-entry relative tolerance on equality. atol: The p...
def add_patches(self, patches, after=None): """ Add a list of patches to the patches list """ if after is None: self.insert_patches(patches) else: self._check_patch(after) patchlines = self._patchlines_before(after) patchlines.append(self.patch2lin...
Add a list of patches to the patches list
def quadrature_weights(Ntheta): """Fourier-space weights needed to evaluate I_{mm'} This is mostly an internal function, included here for backwards compatibility. See map2salm and salm2map for more useful functions. """ import numpy as np weights = np.empty(2*(Ntheta-1), dtype=np.complex128)...
Fourier-space weights needed to evaluate I_{mm'} This is mostly an internal function, included here for backwards compatibility. See map2salm and salm2map for more useful functions.
def prepare_service(data): """Prepare service for catalog endpoint Parameters: data (Union[str, dict]): Service ID or service definition Returns: Tuple[str, dict]: str is ID and dict is service Transform ``/v1/health/state/<state>``:: { "Node": "foobar", ...
Prepare service for catalog endpoint Parameters: data (Union[str, dict]): Service ID or service definition Returns: Tuple[str, dict]: str is ID and dict is service Transform ``/v1/health/state/<state>``:: { "Node": "foobar", "CheckID": "service:redis", ...
def extract_library_properties_from_selected_row(self): """ Extracts properties library_os_path, library_path, library_name and tree_item_key from tree store row """ (model, row) = self.view.get_selection().get_selected() tree_item_key = model[row][self.ID_STORAGE_ID] library_item = mode...
Extracts properties library_os_path, library_path, library_name and tree_item_key from tree store row
def custom_layouts_menu(self, value): """ Setter for **self.__custom_layouts_menu** attribute. :param value: Attribute value. :type value: QMenu """ if value is not None: assert type(value) is QMenu, "'{0}' attribute: '{1}' type is not 'QMenu'!".format( ...
Setter for **self.__custom_layouts_menu** attribute. :param value: Attribute value. :type value: QMenu
def _get_common_block_structure(lhs_bs, rhs_bs): """For two block structures ``aa = (a1, a2, ..., an)``, ``bb = (b1, b2, ..., bm)`` generate the maximal common block structure so that every block from aa and bb is contained in exactly one block of the resulting structure. This is useful for determining...
For two block structures ``aa = (a1, a2, ..., an)``, ``bb = (b1, b2, ..., bm)`` generate the maximal common block structure so that every block from aa and bb is contained in exactly one block of the resulting structure. This is useful for determining how to apply the distributive law when feeding two ...
def sanitize_http_request_cookies(client, event): """ Sanitizes http request cookies :param client: an ElasticAPM client :param event: a transaction or error event :return: The modified event """ # sanitize request.cookies dict try: cookies = event["context"]["request"]["cookie...
Sanitizes http request cookies :param client: an ElasticAPM client :param event: a transaction or error event :return: The modified event
def find_expected_error(self, delta_params='calc'): """ Returns the error expected after an update if the model were linear. Parameters ---------- delta_params : {numpy.ndarray, 'calc', or 'perfect'}, optional The relative change in parameters. If 'calc', use...
Returns the error expected after an update if the model were linear. Parameters ---------- delta_params : {numpy.ndarray, 'calc', or 'perfect'}, optional The relative change in parameters. If 'calc', uses update calculated from the current damping, J, etc; if...
def slugify(text, delim='-'): """Generate an ASCII-only slug.""" result = [] for word in _punct_re.split((text or '').lower()): result.extend(codecs.encode(word, 'ascii', 'replace').split()) return delim.join([str(r) for r in result])
Generate an ASCII-only slug.
def split_log(logf): """split concat log into individual samples""" flashpatt = re.compile( r'\[FLASH\] Fast Length Adjustment of SHort reads\n(.+?)\[FLASH\] FLASH', flags=re.DOTALL) return flashpatt.findall(logf)
split concat log into individual samples
def wavfile_to_examples(wav_file): """Convenience wrapper around waveform_to_examples() for a common WAV format. Args: wav_file: String path to a file, or a file-like object. The file is assumed to contain WAV audio data with signed 16-bit PCM samples. Returns: See waveform_to_examples. """ from...
Convenience wrapper around waveform_to_examples() for a common WAV format. Args: wav_file: String path to a file, or a file-like object. The file is assumed to contain WAV audio data with signed 16-bit PCM samples. Returns: See waveform_to_examples.
def get_files_by_layer(self, layer_name, file_pattern='*'): """ returns a list of all files with the given filename pattern in the given PCC annotation layer """ layer_path = os.path.join(self.path, layer_name) return list(dg.find_files(layer_path, file_pattern))
returns a list of all files with the given filename pattern in the given PCC annotation layer
def delete_network_resource_property_entry(resource, prop): """ Factory method for creating delete functions. """ def delete_func(cmd, resource_group_name, resource_name, item_name, no_wait=False): # pylint: disable=unused-argument client = getattr(network_client_factory(cmd.cli_ctx), resource) ...
Factory method for creating delete functions.
def relations(): """Get a nested dictionary of relation data for all related units""" rels = {} for reltype in relation_types(): relids = {} for relid in relation_ids(reltype): units = {local_unit(): relation_get(unit=local_unit(), rid=relid)} for unit in related_unit...
Get a nested dictionary of relation data for all related units
def iqi(ql, qs, ns=None, rc=None, ot=None, coe=None, moc=DEFAULT_ITER_MAXOBJECTCOUNT,): # pylint: disable=line-too-long """ *New in pywbem 0.10 as experimental and finalized in 0.12.* This function is a wrapper for :meth:`~pywbem.WBEMConnection.IterQueryInstances`. Execute a query in a...
*New in pywbem 0.10 as experimental and finalized in 0.12.* This function is a wrapper for :meth:`~pywbem.WBEMConnection.IterQueryInstances`. Execute a query in a namespace, using the corresponding pull operations if supported by the WBEM server or otherwise the corresponding traditional operation...
def username_role(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") username = ET.SubElement(config, "username", xmlns="urn:brocade.com:mgmt:brocade-aaa") name_key = ET.SubElement(username, "name") name_key.text = kwargs.pop('name') role = ...
Auto Generated Code
def update_sg(self, context, sg, rule_id, action): """Begins the async update process.""" db_sg = db_api.security_group_find(context, id=sg, scope=db_api.ONE) if not db_sg: return None with context.session.begin(): job_body = dict(action="%s sg rule %s" % (action,...
Begins the async update process.
def make_request(self, action, body='', object_hook=None): """ :raises: ``DynamoDBExpiredTokenError`` if the security token expires. """ headers = {'X-Amz-Target' : '%s_%s.%s' % (self.ServiceName, self.Version, action), ...
:raises: ``DynamoDBExpiredTokenError`` if the security token expires.
def copy(self, target=None, name=None): """ Asynchronously creates a copy of this DriveItem and all it's child elements. :param target: target location to move to. If it's a drive the item will be moved to the root folder. :type target: drive.Folder or Drive :param name...
Asynchronously creates a copy of this DriveItem and all it's child elements. :param target: target location to move to. If it's a drive the item will be moved to the root folder. :type target: drive.Folder or Drive :param name: a new name for the copy. :rtype: CopyOpera...
def _clear_zones(self, zone): """ Clear all expired zones from our status list. :param zone: current zone being processed :type zone: int """ cleared_zones = [] found_last_faulted = found_current = at_end = False # First pass: Find our start spot. ...
Clear all expired zones from our status list. :param zone: current zone being processed :type zone: int
def get_box_office_films(self): """uses a certain cinema (O2) and a certain day when non specialist films show (Wednesday) to get a list of the latest box office films""" today = datetime.date.today() next_wednesday = (today + datetime.timedelta((2 - today.weekday()) % 7)).strftime('%Y%m%d') ...
uses a certain cinema (O2) and a certain day when non specialist films show (Wednesday) to get a list of the latest box office films
def generate_encodeable_characters(characters: Iterable[str], encodings: Iterable[str]) -> Iterable[str]: """Generates the subset of 'characters' that can be encoded by 'encodings'. Args: characters: The characters to check for encodeability e.g. 'abcd'. encod...
Generates the subset of 'characters' that can be encoded by 'encodings'. Args: characters: The characters to check for encodeability e.g. 'abcd'. encodings: The encodings to check against e.g. ['cp1252', 'iso-8859-5']. Returns: The subset of 'characters' that can be encoded using one o...
def getTextualNode(self, textId, subreference=None, prevnext=False, metadata=False): """ Retrieve a text node from the API :param textId: PrototypeText Identifier :type textId: str :param subreference: Passage Reference :type subreference: str :param prevnext: Retrieve g...
Retrieve a text node from the API :param textId: PrototypeText Identifier :type textId: str :param subreference: Passage Reference :type subreference: str :param prevnext: Retrieve graph representing previous and next passage :type prevnext: boolean :param metada...
def _get_user_info(self, cmd, section, required=True, accept_just_who=False): """Parse a user section.""" line = self.next_line() if line.startswith(section + b' '): return self._who_when(line[len(section + b' '):], cmd, section, accept_just_who=accept_just_wh...
Parse a user section.
def milestones(self): '''Array of all milestones''' if self.cache['milestones']: return self.cache['milestones'] milestone_xml = self.bc.list_milestones(self.id) milestones = [] for node in ET.fromstring(milestone_xml).findall("milestone"): milestones.append(Milestone...
Array of all milestones
def sub_description(self): """Time and space dscription""" gd = self.geo_description td = self.time_description if gd and td: return '{}, {}. {} Rows.'.format(gd, td, self._p.count) elif gd: return '{}. {} Rows.'.format(gd, self._p.count) elif td:...
Time and space dscription
def refs_to(cls, sha1, repo): """Returns all refs pointing to the given SHA1.""" matching = [] for refname in repo.listall_references(): symref = repo.lookup_reference(refname) dref = symref.resolve() oid = dref.target commit = repo.get(oid) ...
Returns all refs pointing to the given SHA1.
def _symbol_bars( self, symbols, size, _from=None, to=None, limit=None): ''' Query historic_agg either minute or day in parallel for multiple symbols, and return in dict. symbols: list[str] size: str ('da...
Query historic_agg either minute or day in parallel for multiple symbols, and return in dict. symbols: list[str] size: str ('day', 'minute') _from: str or pd.Timestamp to: str or pd.Timestamp limit: str or int return: dict[str -> pd.DataFrame]
def to(location, code=falcon.HTTP_302): """Redirects to the specified location using the provided http_code (defaults to HTTP_302 FOUND)""" raise falcon.http_status.HTTPStatus(code, {'location': location})
Redirects to the specified location using the provided http_code (defaults to HTTP_302 FOUND)
def determine_elected_candidates_in_order(self, candidate_votes): """ determine all candidates with at least a quota of votes in `candidate_votes'. returns results in order of decreasing vote count. Any ties are resolved within this method. """ eligible_by_vote = defaultdict(list...
determine all candidates with at least a quota of votes in `candidate_votes'. returns results in order of decreasing vote count. Any ties are resolved within this method.
def _copy(query_dict): """ Return a mutable copy of `query_dict`. This is a workaround to Django bug #13572, which prevents QueryDict.copy from working. """ memo = { } result = query_dict.__class__('', encoding=query_dict.encoding, mutable=True) memo[id(query_dict)] = resu...
Return a mutable copy of `query_dict`. This is a workaround to Django bug #13572, which prevents QueryDict.copy from working.
def print_result(result): """Print the result, ascii encode if necessary""" try: print result except UnicodeEncodeError: if sys.stdout.encoding: print result.encode(sys.stdout.encoding, 'replace') else: print result.encode('utf8') except: print "Un...
Print the result, ascii encode if necessary
def open_file(filename, file_mode='w'): """ A static convenience function that performs the open of the recorder file correctly for different versions of Python. *New in pywbem 0.10.* This covers the issue where the file should be opened in text mode but that is done di...
A static convenience function that performs the open of the recorder file correctly for different versions of Python. *New in pywbem 0.10.* This covers the issue where the file should be opened in text mode but that is done differently in Python 2 and Python 3. The returned fi...
def named_side_effect(original, name): """Decorator for function or method that do not modify the recorder state but have some side effects that can't be replayed. What it does in recording mode is keep the function name, arguments, keyword and result as a side effect that will be recorded in the journa...
Decorator for function or method that do not modify the recorder state but have some side effects that can't be replayed. What it does in recording mode is keep the function name, arguments, keyword and result as a side effect that will be recorded in the journal. In replay mode, it will only pop the ne...
def vals(cls): """Return this class's attribute values (those not stating with '_'). Returns ------- _vals : list of objects List of values of internal attributes. Order is effectiely random. """ if cls._vals: return cls._vals # If `_val...
Return this class's attribute values (those not stating with '_'). Returns ------- _vals : list of objects List of values of internal attributes. Order is effectiely random.
def find_all_valid_decks(provider: Provider, deck_version: int, prod: bool=True) -> Generator: ''' Scan the blockchain for PeerAssets decks, returns list of deck objects. : provider - provider instance : version - deck protocol version (0, 1, 2, ...) : test True/False - test...
Scan the blockchain for PeerAssets decks, returns list of deck objects. : provider - provider instance : version - deck protocol version (0, 1, 2, ...) : test True/False - test or production P2TH
def user_parser(user): """ Parses a user object """ if __is_deleted(user): return deleted_parser(user) if user['id'] in item_types: raise Exception('Not a user name') if type(user['id']) == int: raise Exception('Not a user name') return User( user['id'], ...
Parses a user object
def wait_with_ioloop(self, ioloop, timeout=None): """Do blocking wait until condition is event is set. Parameters ---------- ioloop : tornadio.ioloop.IOLoop instance MUST be the same ioloop that set() / clear() is called from timeout : float, int or None ...
Do blocking wait until condition is event is set. Parameters ---------- ioloop : tornadio.ioloop.IOLoop instance MUST be the same ioloop that set() / clear() is called from timeout : float, int or None If not None, only wait up to `timeout` seconds for event to b...
def capabilities(self, width, height, rotate, mode="1"): """ Assigns attributes such as ``width``, ``height``, ``size`` and ``bounding_box`` correctly oriented from the supplied parameters. :param width: The device width. :type width: int :param height: The device height...
Assigns attributes such as ``width``, ``height``, ``size`` and ``bounding_box`` correctly oriented from the supplied parameters. :param width: The device width. :type width: int :param height: The device height. :type height: int :param rotate: An integer value of 0 (def...
def __generate_method(name): """ Wraps the DataFrame's original method by name to return the derived class instance. """ try: func = getattr(DataFrame, name) except AttributeError as e: # PySpark version is too old def func(self, *args, **kwarg...
Wraps the DataFrame's original method by name to return the derived class instance.
def serial_udb_extra_f8_encode(self, sue_HEIGHT_TARGET_MAX, sue_HEIGHT_TARGET_MIN, sue_ALT_HOLD_THROTTLE_MIN, sue_ALT_HOLD_THROTTLE_MAX, sue_ALT_HOLD_PITCH_MIN, sue_ALT_HOLD_PITCH_MAX, sue_ALT_HOLD_PITCH_HIGH): ''' Backwards compatible version of SERIAL_UDB_EXTRA F8: format ...
Backwards compatible version of SERIAL_UDB_EXTRA F8: format sue_HEIGHT_TARGET_MAX : Serial UDB Extra HEIGHT_TARGET_MAX (float) sue_HEIGHT_TARGET_MIN : Serial UDB Extra HEIGHT_TARGET_MIN (float) sue_ALT_HOLD_THROTTLE_MIN : Serial UDB Extra ALT_HOLD_TH...
def assemble_binary_rules(self, main, jar, custom_rules=None): """Creates an ordered list of rules suitable for fully shading the given binary. The default rules will ensure the `main` class name is un-changed along with a minimal set of support classes but that everything else will be shaded. Any `cu...
Creates an ordered list of rules suitable for fully shading the given binary. The default rules will ensure the `main` class name is un-changed along with a minimal set of support classes but that everything else will be shaded. Any `custom_rules` are given highest precedence and so they can interfere wit...
def intermediate_cpfs(self) -> List[CPF]: '''Returns list of intermediate-fluent CPFs in level order.''' _, cpfs = self.cpfs interm_cpfs = [cpf for cpf in cpfs if cpf.name in self.intermediate_fluents] interm_cpfs = sorted(interm_cpfs, key=lambda cpf: (self.intermediate_fluents[cpf.name]...
Returns list of intermediate-fluent CPFs in level order.
def getsuffix(subject): """ Returns the suffix of a filename. If the file has no suffix, returns None. Can return an empty string if the filenam ends with a period. """ index = subject.rfind('.') if index > subject.replace('\\', '/').rfind('/'): return subject[index+1:] return None
Returns the suffix of a filename. If the file has no suffix, returns None. Can return an empty string if the filenam ends with a period.
def _parse_type(self, element, types): """Parse a 'complexType' element. @param element: The top-level complexType element @param types: A map of the elements of all available complexType's. @return: The schema for the complexType. """ name = element.attrib["name"] ...
Parse a 'complexType' element. @param element: The top-level complexType element @param types: A map of the elements of all available complexType's. @return: The schema for the complexType.
def partial_distance_covariance(x, y, z): """ Partial distance covariance estimator. Compute the estimator for the partial distance covariance of the random vectors corresponding to :math:`x` and :math:`y` with respect to the random variable corresponding to :math:`z`. Parameters ---------...
Partial distance covariance estimator. Compute the estimator for the partial distance covariance of the random vectors corresponding to :math:`x` and :math:`y` with respect to the random variable corresponding to :math:`z`. Parameters ---------- x: array_like First random vector. The c...
def hash_file(path, block_size=65536): """Returns SHA256 checksum of a file Args: path (string): Absolute file path of file to hash block_size (int, optional): Number of bytes to read per block """ sha256 = hashlib.sha256() with open(path, 'rb') as f: for block in iter(lamb...
Returns SHA256 checksum of a file Args: path (string): Absolute file path of file to hash block_size (int, optional): Number of bytes to read per block
def get_delete_api(self, resource): """ Generates the meta descriptor for the resource item api. """ parameters = self.delete_item_parameters(resource) get_item_api = { 'path': '/%s/{id}/' % resource.get_api_name(), 'description': 'Operations on %s' % resource.model.__n...
Generates the meta descriptor for the resource item api.
def exec_command_on_nodes(nodes, cmd, label, conn_params=None): """Execute a command on a node (id or hostname) or on a set of nodes. :param nodes: list of targets of the command cmd. Each must be an execo.Host. :param cmd: string representing the command to run on the...
Execute a command on a node (id or hostname) or on a set of nodes. :param nodes: list of targets of the command cmd. Each must be an execo.Host. :param cmd: string representing the command to run on the remote nodes. :param label: string f...
def register_types(name, *types): """ Register a short name for one or more content types. """ type_names.setdefault(name, set()) for t in types: # Redirecting the type if t in media_types: type_names[media_types[t]].discard(t) # Save the mapping media_t...
Register a short name for one or more content types.
def _set_anycast_rp_ip(self, v, load=False): """ Setter method for anycast_rp_ip, mapped from YANG variable /routing_system/router/hide_pim_holder/pim/anycast_rp_ip (list) If this variable is read-only (config: false) in the source YANG file, then _set_anycast_rp_ip is considered as a private method...
Setter method for anycast_rp_ip, mapped from YANG variable /routing_system/router/hide_pim_holder/pim/anycast_rp_ip (list) If this variable is read-only (config: false) in the source YANG file, then _set_anycast_rp_ip is considered as a private method. Backends looking to populate this variable should d...
def register_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Add EC2 instance(s) to an Elastic Load Balancer. Removing an instance from the ``instances`` list does not remove it from the ELB. name The name of the Elastic Load Balancer to a...
Add EC2 instance(s) to an Elastic Load Balancer. Removing an instance from the ``instances`` list does not remove it from the ELB. name The name of the Elastic Load Balancer to add EC2 instances to. instances A list of EC2 instance IDs that this Elastic Load Balancer should distrib...
def await_any_transforms_exist(cli, transform_paths, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS): """ Waits for a transform to exist based on does_exist. :param cli: :param transform_paths: An array of transform paths [...] :param does_exist: Whether or not to await...
Waits for a transform to exist based on does_exist. :param cli: :param transform_paths: An array of transform paths [...] :param does_exist: Whether or not to await for exist state (True | False) :param timeout_seconds: How long until this returns with failure :return: bool
def set_cte(self, cte_id, sql): """This is the equivalent of what self.extra_ctes[cte_id] = sql would do if extra_ctes were an OrderedDict """ for cte in self.extra_ctes: if cte['id'] == cte_id: cte['sql'] = sql break else: ...
This is the equivalent of what self.extra_ctes[cte_id] = sql would do if extra_ctes were an OrderedDict
def _search(self, searchterm, pred, **args): """ Search for things using labels """ # TODO: DRY with sparql_ontol_utils searchterm = searchterm.replace('%','.*') namedGraph = get_named_graph(self.handle) query = """ prefix oboInOwl: <http://www.geneontolog...
Search for things using labels
def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: FieldTypeContext for this FieldTypeInstance :rtype: twilio.rest.autopilot.v1.assistant.field_type...
Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: FieldTypeContext for this FieldTypeInstance :rtype: twilio.rest.autopilot.v1.assistant.field_type.FieldTypeContext
def run(self, module, options): """ Run the operator. :param module: The target module path. :type module: ``str`` :param options: Any runtime options. :type options: ``dict`` :return: The operator results. :rtype: ``dict`` """ logger....
Run the operator. :param module: The target module path. :type module: ``str`` :param options: Any runtime options. :type options: ``dict`` :return: The operator results. :rtype: ``dict``
def create_osd( conn, cluster, data, journal, zap, fs_type, dmcrypt, dmcrypt_dir, storetype, block_wal, block_db, **kw): """ Run on osd node, creates an OSD from a data disk. """ ceph_volume_executable = syst...
Run on osd node, creates an OSD from a data disk.
def drop_namespaces(self): """Drop all namespaces.""" self.session.query(NamespaceEntry).delete() self.session.query(Namespace).delete() self.session.commit()
Drop all namespaces.
def likelihood(self, x, cl): """ X = numpy.random.random([2,3,4]) # we have data 2x3 with fature vector with 4 fatures Use likelihoodFromImage() function for 3d image input m.likelihood(X,0) """ # sha = x.shape # xr = x.reshape(-1, sha[-1]) # out...
X = numpy.random.random([2,3,4]) # we have data 2x3 with fature vector with 4 fatures Use likelihoodFromImage() function for 3d image input m.likelihood(X,0)
def get_context_data(self, **kwargs): """ Returns the context data to provide to the template. """ context = super(ForumView, self).get_context_data(**kwargs) # Insert the considered forum into the context context['forum'] = self.get_forum() # Get the list of forums that have t...
Returns the context data to provide to the template.
def start_plasma_store(stdout_file=None, stderr_file=None, object_store_memory=None, plasma_directory=None, huge_pages=False, plasma_store_socket_name=None): """This method starts an object store proce...
This method starts an object store process. Args: stdout_file: A file handle opened for writing to redirect stdout to. If no redirection should happen, then this should be None. stderr_file: A file handle opened for writing to redirect stderr to. If no redirection should hap...
def d2logpdf_dlink2(self, link_f, y, Y_metadata=None): """ Hessian at y, given link(f), w.r.t link(f) i.e. second derivative logpdf at y given link(f_i) and link(f_j) w.r.t link(f_i) and link(f_j) The hessian will be 0 unless i == j .. math:: \\frac{d^{2} \\ln p(y_{...
Hessian at y, given link(f), w.r.t link(f) i.e. second derivative logpdf at y given link(f_i) and link(f_j) w.r.t link(f_i) and link(f_j) The hessian will be 0 unless i == j .. math:: \\frac{d^{2} \\ln p(y_{i}|\lambda(f_{i}))}{d^{2}\\lambda(f)} = -\\beta^{2}\\frac{d\\Psi(\\alpha_{i...
def _box_click(self, event): """Check or uncheck box when clicked.""" x, y, widget = event.x, event.y, event.widget elem = widget.identify("element", x, y) if "image" in elem: # a box was clicked item = self.identify_row(y) if self.tag_has("unchecked",...
Check or uncheck box when clicked.
def calculate_size(name, permits, timeout): """ Calculates the request payload size""" data_size = 0 data_size += calculate_size_str(name) data_size += INT_SIZE_IN_BYTES data_size += LONG_SIZE_IN_BYTES return data_size
Calculates the request payload size
def new_context(self, vars=None, shared=False, locals=None): """Create a new :class:`Context` for this template. The vars provided will be passed to the template. Per default the globals are added to the context. If shared is set to `True` the data is passed as it to the context witho...
Create a new :class:`Context` for this template. The vars provided will be passed to the template. Per default the globals are added to the context. If shared is set to `True` the data is passed as it to the context without adding the globals. `locals` can be a dict of local variable...
def read_sample(filename): """! @brief Returns data sample from simple text file. @details This function should be used for text file with following format: @code point_1_coord_1 point_1_coord_2 ... point_1_coord_n point_2_coord_1 point_2_coord_2 ... point_2_coord_n ... ... @endc...
! @brief Returns data sample from simple text file. @details This function should be used for text file with following format: @code point_1_coord_1 point_1_coord_2 ... point_1_coord_n point_2_coord_1 point_2_coord_2 ... point_2_coord_n ... ... @endcode @param[in] filename ...
def has_scheduled_methods(cls): """Decorator; use this on a class for which some methods have been decorated with :func:`schedule` or :func:`schedule_hint`. Those methods are then tagged with the attribute `__member_of__`, so that we may serialise and retrieve the correct method. This should be consider...
Decorator; use this on a class for which some methods have been decorated with :func:`schedule` or :func:`schedule_hint`. Those methods are then tagged with the attribute `__member_of__`, so that we may serialise and retrieve the correct method. This should be considered a patch to a flaw in the Python ...
def tune(device, **kwargs): ''' Set attributes for the specified device CLI Example: .. code-block:: bash salt '*' disk.tune /dev/sda1 read-ahead=1024 read-write=True Valid options are: ``read-ahead``, ``filesystem-read-ahead``, ``read-only``, ``read-write``. See the ``blockdev(...
Set attributes for the specified device CLI Example: .. code-block:: bash salt '*' disk.tune /dev/sda1 read-ahead=1024 read-write=True Valid options are: ``read-ahead``, ``filesystem-read-ahead``, ``read-only``, ``read-write``. See the ``blockdev(8)`` manpage for a more complete descrip...
def to_aws_format(tags): """Convert the Ray node name tag to the AWS-specific 'Name' tag.""" if TAG_RAY_NODE_NAME in tags: tags["Name"] = tags[TAG_RAY_NODE_NAME] del tags[TAG_RAY_NODE_NAME] return tags
Convert the Ray node name tag to the AWS-specific 'Name' tag.
def connect(self): """ Sets up your Phabricator session, it's not necessary to call this directly """ if self.token: self.phab_session = {'token': self.token} return req = self.req_session.post('%s/api/conduit.connect' % self.host, data={ ...
Sets up your Phabricator session, it's not necessary to call this directly
def get_token(request): """ Returns the token model instance associated with the given request token key. If no user is retrieved AnonymousToken is returned. """ if (not request.META.get(header_name_to_django(auth_token_settings.HEADER_NAME)) and config.CHAMBER_MULTIDOMAINS_OVERTAKER_AUT...
Returns the token model instance associated with the given request token key. If no user is retrieved AnonymousToken is returned.
def size(self): """ Returns the number of connections cached by the pool. """ return sum(q.qsize() for q in self._connections.values()) + len(self._fairies)
Returns the number of connections cached by the pool.
def _parse_broadcast(self, msg): """ Given a broacast message, returns the message that was broadcast. """ # get message, remove surrounding quotes, and unescape return self._unescape(self._get_type(msg[self.broadcast_prefix_len:]))
Given a broacast message, returns the message that was broadcast.
def get_random_submission(self, subreddit='all'): """Return a random Submission object. :param subreddit: Limit the submission to the specified subreddit(s). Default: all """ url = self.config['subreddit_random'].format( subreddit=six.text_type(subreddit)) ...
Return a random Submission object. :param subreddit: Limit the submission to the specified subreddit(s). Default: all
def send_produce_request(self, payloads=None, acks=1, timeout=DEFAULT_REPLICAS_ACK_MSECS, fail_on_error=True, callback=None): """ Encode and send some ProduceRequests ProduceRequests will be grouped by (topic, partition) and then ...
Encode and send some ProduceRequests ProduceRequests will be grouped by (topic, partition) and then sent to a specific broker. Output is a list of responses in the same order as the list of payloads specified Parameters ---------- payloads: list of ProduceRe...
def str_repl(self, inputstring, **kwargs): """Add back strings.""" out = [] comment = None string = None for i, c in enumerate(append_it(inputstring, None)): try: if comment is not None: if c is not None and c in nums: ...
Add back strings.
def mklink(): """ Like cmd.exe's mklink except it will infer directory status of the target. """ from optparse import OptionParser parser = OptionParser(usage="usage: %prog [options] link target") parser.add_option( '-d', '--directory', help="Target is a directory (only necessary if not present)", action="...
Like cmd.exe's mklink except it will infer directory status of the target.
def _query_entities(self, table_name, filter=None, select=None, max_results=None, marker=None, accept=TablePayloadFormat.JSON_MINIMAL_METADATA, property_resolver=None, timeout=None): ''' Returns a list of entities under the specified table. Makes a single li...
Returns a list of entities under the specified table. Makes a single list request to the service. Used internally by the query_entities method. :param str table_name: The name of the table to query. :param str filter: Returns only entities that satisfy the specified fil...
def get_src_address_from_data(self, decoded=True): """ Return the SRC address of a message if SRC_ADDRESS label is present in message type of the message Return None otherwise :param decoded: :return: """ src_address_label = next((lbl for lbl in self.message_type...
Return the SRC address of a message if SRC_ADDRESS label is present in message type of the message Return None otherwise :param decoded: :return:
async def get_suggested_entities(self, get_suggested_entities_request): """Return suggested contacts.""" response = hangouts_pb2.GetSuggestedEntitiesResponse() await self._pb_request('contacts/getsuggestedentities', get_suggested_entities_request, response) ...
Return suggested contacts.