positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def console_set_char( con: tcod.console.Console, x: int, y: int, c: Union[int, str] ) -> None: """Change the character at x,y to c, keeping the current colors. Args: con (Console): Any Console instance. x (int): Character x position from the left. y (int): Character y position from ...
Change the character at x,y to c, keeping the current colors. Args: con (Console): Any Console instance. x (int): Character x position from the left. y (int): Character y position from the top. c (Union[int, AnyStr]): Character to draw, can be an integer or string. .. deprecate...
def get_sentences(self, root_element, block_tags): """Returns a list of plain-text sentences by iterating through XML tags except for those listed in block_tags.""" sentences = [] for element in root_element: if not self.any_ends_with(block_tags, element.tag): ...
Returns a list of plain-text sentences by iterating through XML tags except for those listed in block_tags.
def full(self): """Return True if there are maxsize items in the queue. Note: if the Queue was initialized with maxsize=0 (the default), then full() is never True. """ if self._parent._maxsize <= 0: return False else: return self.qsize() >= self._...
Return True if there are maxsize items in the queue. Note: if the Queue was initialized with maxsize=0 (the default), then full() is never True.
def partial_trace(self, qubits: Qubits) -> 'QubitVector': """ Return the partial trace over some subset of qubits""" N = self.qubit_nb R = self.rank if R == 1: raise ValueError('Cannot take trace of vector') new_qubits: List[Qubit] = list(self.qubits) ...
Return the partial trace over some subset of qubits
def message(self, executor_id, slave_id, message): """Sends a message from the framework to one of its executors. These messages are best effort; do not expect a framework message to be retransmitted in any reliable fashion. """ logging.info('Sends message `{}` to executor `{}` ...
Sends a message from the framework to one of its executors. These messages are best effort; do not expect a framework message to be retransmitted in any reliable fashion.
def get_range_around(range_value, current_item, padding): """ Returns a range of numbers around the given number. This is useful for pagination, where you might want to show something like this:: << < ... 4 5 (6) 7 8 .. > >> In this example `6` would be the current page and we show 2 item...
Returns a range of numbers around the given number. This is useful for pagination, where you might want to show something like this:: << < ... 4 5 (6) 7 8 .. > >> In this example `6` would be the current page and we show 2 items around that page (including the page itself). Usage:: ...
def stream_json_file(local_file): """Stream a JSON file (in JSON-per-line format) Args: local_file (file-like object) an open file-handle that contains a JSON string on each line Yields: (dict) JSON objects """ for i, line in enumerate(local_file): try: ...
Stream a JSON file (in JSON-per-line format) Args: local_file (file-like object) an open file-handle that contains a JSON string on each line Yields: (dict) JSON objects
def get(self, *args, **kwargs): """Perform a get request.""" if 'convert' in kwargs: conversion = kwargs.pop('convert') else: conversion = True kwargs = self._get_keywords(**kwargs) url = self._create_path(*args) request = self.session.get(url, par...
Perform a get request.
def make_session(username=None, password=None, bearer_token=None, extra_headers_dict=None): """Creates a Requests Session for use. Accepts a bearer token for premiums users and will override username and password information if present. Args: username (str): username for the session pa...
Creates a Requests Session for use. Accepts a bearer token for premiums users and will override username and password information if present. Args: username (str): username for the session password (str): password for the user bearer_token (str): token for a premium API user.
def search_series(self, name=None, imdb_id=None, zap2it_id=None): """ Searchs for a series in TheTVDB by either its name, imdb_id or zap2it_id. :param name: the name of the series to look for :param imdb_id: the IMDB id of the series to look for :param zap2it_id: the zap2it id o...
Searchs for a series in TheTVDB by either its name, imdb_id or zap2it_id. :param name: the name of the series to look for :param imdb_id: the IMDB id of the series to look for :param zap2it_id: the zap2it id of the series to look for. :return: a python dictionary with either the result ...
def frames(self, flush=True): """ Returns the latest color image from the stream Raises: Exception if opencv sensor gives ret_val of 0 """ self.flush() ret_val, frame = self._sensor.read() if not ret_val: raise Exception("Unable to retrieve frame f...
Returns the latest color image from the stream Raises: Exception if opencv sensor gives ret_val of 0
def unbind(self): """ Unbinds this connection from queue and topic managers (freeing up resources) and resets state. """ self.connected = False self.queue_manager.disconnect(self.connection) self.topic_manager.disconnect(self.connection)
Unbinds this connection from queue and topic managers (freeing up resources) and resets state.
def get_fipscode(self, obj): """County FIPS code""" if obj.division.level.name == DivisionLevel.COUNTY: return obj.division.code return None
County FIPS code
def drop_vocab(self, vocab_name, **kwargs): """ Removes the vocab from the definiton triplestore args: vocab_name: the name or uri of the vocab to return """ vocab_dict = self.__get_vocab_dict__(vocab_name, **kwargs) return self.drop_file(vocab_dict['filename'], **k...
Removes the vocab from the definiton triplestore args: vocab_name: the name or uri of the vocab to return
def delete_external_feed_courses(self, course_id, external_feed_id): """ Delete an external feed. Deletes the external feed. """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course...
Delete an external feed. Deletes the external feed.
def find(self, id): """Get a resource by its id Args: id (string): Resource id Returns: object: Instance of the resource type """ url = "{}/{}/{}".format(__endpoint__, self.type.RESOURCE, id) response = RestClient.get(url)[self.type.RESOURCE[:-1]]...
Get a resource by its id Args: id (string): Resource id Returns: object: Instance of the resource type
def scan(self, stop_on_first=True, base_ip=0): """Scans the local network for TVs.""" tvs = [] # Check if base_ip has been passed if base_ip == 0: # Find IP address of computer pymitv is running on sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) ...
Scans the local network for TVs.
def get_neuroglancer_link(self, resource, resolution, x_range, y_range, z_range, url_prefix, **kwargs): """ Get a neuroglancer link of the cutout specified from the host specified in the remote configuration step. Args: resource (intern.resource.Resource): Resource compatible with c...
Get a neuroglancer link of the cutout specified from the host specified in the remote configuration step. Args: resource (intern.resource.Resource): Resource compatible with cutout operations. resolution (int): 0 indicates native resolution. x_range (list[int]): x range such...
def objectives(self, rank): """Returns objective values of models with specified rank. """ self._check_rank(rank) return [result.obj for result in self.results[rank]]
Returns objective values of models with specified rank.
def list_models(self, macaroons): """ Get the logged in user's models from the JIMM controller. @param macaroons The discharged JIMM macaroons. @return The json decoded list of environments. """ return make_request("{}model".format(self.url), timeout=self.timeout, ...
Get the logged in user's models from the JIMM controller. @param macaroons The discharged JIMM macaroons. @return The json decoded list of environments.
def getDXGIOutputInfo(self): """ [D3D10/11 Only] Returns the adapter index and output index that the user should pass into EnumAdapters and EnumOutputs to create the device and swap chain in DX10 and DX11. If an error occurs both indices will be set to -1. """ fn = self....
[D3D10/11 Only] Returns the adapter index and output index that the user should pass into EnumAdapters and EnumOutputs to create the device and swap chain in DX10 and DX11. If an error occurs both indices will be set to -1.
def fullname(self): """Returns the name of the ``Record`` class this ``Property`` is attached to, and attribute name it is attached as.""" if not self.bound: if self.name is not None: return "(unbound).%s" % self.name else: return "(unbound...
Returns the name of the ``Record`` class this ``Property`` is attached to, and attribute name it is attached as.
def write(self, pkt): """ Writes a Packet or bytes to a pcap file. :param pkt: Packet(s) to write (one record for each Packet), or raw bytes to write (as one record). :type pkt: iterable[Packet], Packet or bytes """ if isinstance(pkt, bytes): ...
Writes a Packet or bytes to a pcap file. :param pkt: Packet(s) to write (one record for each Packet), or raw bytes to write (as one record). :type pkt: iterable[Packet], Packet or bytes
def _single_qubit_accumulate_into_scratch(args: Dict[str, Any]): """Accumulates single qubit phase gates into the scratch shards.""" index = args['indices'][0] shard_num = args['shard_num'] half_turns = args['half_turns'] num_shard_qubits = args['num_shard_qubits'] scratch = _scratch_shard(args)...
Accumulates single qubit phase gates into the scratch shards.
def bool(cls, must=None, should=None, must_not=None, minimum_number_should_match=None, boost=None): ''' http://www.elasticsearch.org/guide/reference/query-dsl/bool-query.html A query that matches documents matching boolean combinations of other queris. The bool query maps to Lucene BooleanQuery....
http://www.elasticsearch.org/guide/reference/query-dsl/bool-query.html A query that matches documents matching boolean combinations of other queris. The bool query maps to Lucene BooleanQuery. It is built using one of more boolean clauses, each clause with a typed occurrence. The occurrence types are: '...
def _queue(self, kwargs): """The hard resource_list comes like this: '<qname>=TRUE,mem=128M'. To process it we have to split it twice (',' and then on '='), create a dictionary and extract just the qname""" if not 'hard resource_list' in kwargs: return 'all.q' d = dict([k.split('=') for k in kwargs[...
The hard resource_list comes like this: '<qname>=TRUE,mem=128M'. To process it we have to split it twice (',' and then on '='), create a dictionary and extract just the qname
def add_method(function, klass, name=None): '''Add an existing function to a class as a method. Note: Consider using the extend decorator as a more readable alternative to using this function directly. Args: function: The function to be added to the class klass. klass: Th...
Add an existing function to a class as a method. Note: Consider using the extend decorator as a more readable alternative to using this function directly. Args: function: The function to be added to the class klass. klass: The class to which the new method will be added. ...
def _get_analysis_period_subset(self, a_per): """Return an analysis_period is always a subset of the Data Collection""" if self.header.analysis_period.is_annual: return a_per new_needed = False n_ap = [a_per.st_month, a_per.st_day, a_per.st_hour, a_per.end_mo...
Return an analysis_period is always a subset of the Data Collection
def _apply_scope(self, scope, builder): """ Apply a single scope on the given builder instance. :param scope: The scope to apply :type scope: callable or Scope :param builder: The builder to apply the scope to :type builder: Builder """ if callable(scope...
Apply a single scope on the given builder instance. :param scope: The scope to apply :type scope: callable or Scope :param builder: The builder to apply the scope to :type builder: Builder
def zoneheight(idf, zonename, debug=False): """zone height""" zone = idf.getobject('ZONE', zonename) surfs = idf.idfobjects['BuildingSurface:Detailed'.upper()] zone_surfs = [s for s in surfs if s.Zone_Name == zone.Name] floors = [s for s in zone_surfs if s.Surface_Type.upper() == 'FLOOR'] roofs ...
zone height
def expand_paths(paths, marker='*'): """ :param paths: A glob path pattern string or pathlib.Path object holding such path, or a list consists of path strings or glob path pattern strings or pathlib.Path object holding such ones, or file objects :param marker: Glob marker character o...
:param paths: A glob path pattern string or pathlib.Path object holding such path, or a list consists of path strings or glob path pattern strings or pathlib.Path object holding such ones, or file objects :param marker: Glob marker character or string, e.g. '*' :return: List of path str...
def set_fluxinfo(self): """ Uses list of known flux calibrators (with models in CASA) to find full name given in scan. """ knowncals = ['3C286', '3C48', '3C147', '3C138'] # find scans with knowncals in the name sourcenames = [self.sources[source]['source'] for source in self.so...
Uses list of known flux calibrators (with models in CASA) to find full name given in scan.
async def build_attrib_request(submitter_did: str, target_did: str, xhash: Optional[str], raw: Optional[str], enc: Optional[str]) -> str: """ Builds an ATTRIB request. Request to add attri...
Builds an ATTRIB request. Request to add attribute to a NYM record. :param submitter_did: DID of the submitter stored in secured Wallet. :param target_did: Target DID as base58-encoded string for 16 or 32 bit DID value. :param xhash: (Optional) Hash of attribute data. :param raw: (Optional) Json, where...
def getData(self, *statements): """ Get the data corresponding to the display statements. The statements can be AMPL expressions, or entities. It captures the equivalent of the command: .. code-block:: ampl display ds1, ..., dsn; where ds1, ..., dsn are the...
Get the data corresponding to the display statements. The statements can be AMPL expressions, or entities. It captures the equivalent of the command: .. code-block:: ampl display ds1, ..., dsn; where ds1, ..., dsn are the ``displayStatements`` with which the functi...
def delete(ctx, family_id, individual_id, root): """ Delete a case or individual from the database. If no database was found run puzzle init first. """ root = root or ctx.obj.get('root') or os.path.expanduser("~/.puzzle") if os.path.isfile(root): logger.error("'root' can't be a file") ...
Delete a case or individual from the database. If no database was found run puzzle init first.
def set_plugin_filepaths(self, filepaths, except_blacklisted=True): """ Sets `filepaths` to the `self.plugin_filepaths`. Recommend passing in absolute filepaths. Method will attempt to convert to absolute paths if they are not already. `filepaths` can be a single object or an it...
Sets `filepaths` to the `self.plugin_filepaths`. Recommend passing in absolute filepaths. Method will attempt to convert to absolute paths if they are not already. `filepaths` can be a single object or an iterable. If `except_blacklisted` is `True`, all `filepaths` that have be...
def find(self, resource_id, query=None, **kwargs): """Gets a single resource.""" if query is None: query = {} return self.client._get( self._url(resource_id), query, **kwargs )
Gets a single resource.
def counter_style(self, val, style): """Return counter value in given style.""" if style == 'decimal-leading-zero': if val < 10: valstr = "0{}".format(val) else: valstr = str(val) elif style == 'lower-roman': valstr = _to_roman(...
Return counter value in given style.
def unload_module(self, path): '''Unload a loaded shared library. Call this function to remove a shared library (e.g. a component) that was previously loaded. @param path The path to the shared library. @raises FailedToUnloadModuleError ''' with self._mutex: ...
Unload a loaded shared library. Call this function to remove a shared library (e.g. a component) that was previously loaded. @param path The path to the shared library. @raises FailedToUnloadModuleError
def create(args): """ cdstarcat create PATH Create objects in CDSTAR specified by PATH. When PATH is a file, a single object (possibly with multiple bitstreams) is created; When PATH is a directory, an object will be created for each file in the directory (recursing into subdirectories). ""...
cdstarcat create PATH Create objects in CDSTAR specified by PATH. When PATH is a file, a single object (possibly with multiple bitstreams) is created; When PATH is a directory, an object will be created for each file in the directory (recursing into subdirectories).
def feed_parser(self, data): """Parse received message.""" assert isinstance(data, bytes) self.controller.feed_parser(data)
Parse received message.
def get_gallery_album(self, id): """ Return the gallery album matching the id. Note that an album's id is different from it's id as a gallery album. This makes it possible to remove an album from the gallery and setting it's privacy setting as secret, without compromising it's s...
Return the gallery album matching the id. Note that an album's id is different from it's id as a gallery album. This makes it possible to remove an album from the gallery and setting it's privacy setting as secret, without compromising it's secrecy.
def create(self, throw_on_exists=False): """ Creates a database defined by the current database object, if it does not already exist and raises a CloudantException if the operation fails. If the database already exists then this method call is a no-op. :param bool throw_on_exis...
Creates a database defined by the current database object, if it does not already exist and raises a CloudantException if the operation fails. If the database already exists then this method call is a no-op. :param bool throw_on_exists: Boolean flag dictating whether or not to thro...
def get_bits( self, count ): """Get an integer containing the next [count] bits from the source.""" result = 0 for i in range( count ): if self.bits_remaining <= 0: self._fill_buffer() if self.bits_reverse: bit = (1 if (self.current_bits & ...
Get an integer containing the next [count] bits from the source.
def update_group(self, group_name, new_group_name=None, new_path=None): """ Updates name and/or path of the specified group. :type group_name: string :param group_name: The name of the new group :type new_group_name: string :param new_group_name: If provided, the name o...
Updates name and/or path of the specified group. :type group_name: string :param group_name: The name of the new group :type new_group_name: string :param new_group_name: If provided, the name of the group will be changed to this name. :type new_...
def replace_header(self, header_text): """Replace pip-compile header with custom text""" with open(self.outfile, 'rt') as fp: _, body = self.split_header(fp) with open(self.outfile, 'wt') as fp: fp.write(header_text) fp.writelines(body)
Replace pip-compile header with custom text
def repeat_masker_alignment_iterator(fn, index_friendly=True, verbose=False): """ Iterator for repeat masker alignment files; yields multiple alignment objects. Iterate over a file/stream of full repeat alignments in the repeatmasker format. Briefly, this format is as follows: each record (alignment) begins ...
Iterator for repeat masker alignment files; yields multiple alignment objects. Iterate over a file/stream of full repeat alignments in the repeatmasker format. Briefly, this format is as follows: each record (alignment) begins with a header line (see _rm_parse_header_line documentation for details of header fo...
def cli(env): """List Reserved Capacity groups.""" manager = CapacityManager(env.client) result = manager.list() table = formatting.Table( ["ID", "Name", "Capacity", "Flavor", "Location", "Created"], title="Reserved Capacity" ) for r_c in result: occupied_string = "#" * i...
List Reserved Capacity groups.
def _get_object_class(cls, class_name): """ :type class_name: str :rtype: core.BunqModel """ class_name = class_name.lstrip(cls.__STRING_FORMAT_UNDERSCORE) if class_name in cls._override_field_map: class_name = cls._override_field_map[class_name] tr...
:type class_name: str :rtype: core.BunqModel
def get_available_ip6_for_vip(self, id_evip, name): """ Get and save a available IP in the network ipv6 for vip request :param id_evip: Vip environment identifier. Integer value and greater than zero. :param name: Ip description :return: Dictionary with the following structure:...
Get and save a available IP in the network ipv6 for vip request :param id_evip: Vip environment identifier. Integer value and greater than zero. :param name: Ip description :return: Dictionary with the following structure: :: {'ip': {'bloco1':<bloco1>, 'bloco2...
def data(request): """Return server side data.""" columns = [ ColumnDT(User.id), ColumnDT(User.name), ColumnDT(Address.description), ColumnDT(func.strftime("%d-%m-%Y", User.birthday)), ColumnDT(User.age) ] query = DBSession.query().select_from(User).join(Address)...
Return server side data.
def water_bridges(bs_hba, lig_hba, bs_hbd, lig_hbd, water): """Find water-bridged hydrogen bonds between ligand and protein. For now only considers bridged of first degree.""" data = namedtuple('waterbridge', 'a a_orig_idx atype d d_orig_idx dtype h water water_orig_idx distance_aw ' ...
Find water-bridged hydrogen bonds between ligand and protein. For now only considers bridged of first degree.
def merge(a_intervals, b_intervals, op): """ Merge two lists of intervals according to the boolean function op ``a_intervals`` and ``b_intervals`` need to be sorted and consistent (no overlapping intervals). This operation keeps the resulting interval set consistent. Parameters...
Merge two lists of intervals according to the boolean function op ``a_intervals`` and ``b_intervals`` need to be sorted and consistent (no overlapping intervals). This operation keeps the resulting interval set consistent. Parameters ---------- a_intervals : `~numpy.ndarray` ...
def buffer_list(editor): """ List all buffers. """ def handler(): wa = editor.window_arrangement for info in wa.list_open_buffers(): char = '%' if info.is_active else '' eb = info.editor_buffer print(' %3i %-2s %-20s line %i' % ( inf...
List all buffers.
def fromString(strdata): """ Generates profile data from the inputed string data. :param strdata | <str> :return <XViewProfile> """ if strdata: try: xprofile = ElementTree.fromstring(nativestring(strdata)) ...
Generates profile data from the inputed string data. :param strdata | <str> :return <XViewProfile>
def create(model, count, *args, **kwargs): ''' Create *count* instances of *model* using the either an appropiate autofixture that was :ref:`registry <registry>` or fall back to the default:class:`AutoFixture` class. *model* can be a model class or its string representation (e.g. ``"app.ModelClass"`...
Create *count* instances of *model* using the either an appropiate autofixture that was :ref:`registry <registry>` or fall back to the default:class:`AutoFixture` class. *model* can be a model class or its string representation (e.g. ``"app.ModelClass"``). All positional and keyword arguments are passe...
def get_fmri(name, **kwargs): ''' Returns FMRI from partial name. Returns empty string ('') if not found. In case of multiple match, the function returns list of all matched packages. CLI Example: .. code-block:: bash salt '*' pkg.get_fmri bash ''' if name.startswith('pkg://'): ...
Returns FMRI from partial name. Returns empty string ('') if not found. In case of multiple match, the function returns list of all matched packages. CLI Example: .. code-block:: bash salt '*' pkg.get_fmri bash
def interpret(code, in_vars): """Try to evaluate the given code, otherwise execute it.""" try: result = eval(code, in_vars) except SyntaxError: pass # exec code outside of exception context else: if result is not None: print(ascii(result)) return # don't als...
Try to evaluate the given code, otherwise execute it.
def brightness_to_hex(self, level): """Convert numeric brightness percentage into hex for insteon""" level_int = int(level) new_int = int((level_int * 255)/100) new_level = format(new_int, '02X') self.logger.debug("brightness_to_hex: %s to %s", level, str(new_level)) retu...
Convert numeric brightness percentage into hex for insteon
def to_array(self): """Return a 1-dimensional |numpy| |numpy.ndarray| with six entries defining the actual date (year, month, day, hour, minute, second). >>> from hydpy import Date >>> Date('1992-10-8 15:15:42').to_array() array([ 1992., 10., 8., 15., 15., 42.])...
Return a 1-dimensional |numpy| |numpy.ndarray| with six entries defining the actual date (year, month, day, hour, minute, second). >>> from hydpy import Date >>> Date('1992-10-8 15:15:42').to_array() array([ 1992., 10., 8., 15., 15., 42.]) .. note:: ...
def group_content(content, namespace, grpname, grpnodetype): """Group the given content in the given namespace under a node of type grpnodetype with the name grpname :param content: the nodes to group :type content: :class:`list` :param namespace: the namespace to use :type namespace: str | Non...
Group the given content in the given namespace under a node of type grpnodetype with the name grpname :param content: the nodes to group :type content: :class:`list` :param namespace: the namespace to use :type namespace: str | None :param grpname: the name of the new grpnode :type grpname:...
def to_dict(self, properties=None): """Return a dictionary containing Compound data. Optionally specify a list of the desired properties. synonyms, aids and sids are not included unless explicitly specified using the properties parameter. This is because they each require an extra request. ...
Return a dictionary containing Compound data. Optionally specify a list of the desired properties. synonyms, aids and sids are not included unless explicitly specified using the properties parameter. This is because they each require an extra request.
def shell_out_ignore_exitcode(cmd, stderr=STDOUT, cwd=None): """Same as shell_out but doesn't raise if the cmd exits badly.""" try: return shell_out(cmd, stderr=stderr, cwd=cwd) except CalledProcessError as c: return _clean_output(c.output)
Same as shell_out but doesn't raise if the cmd exits badly.
def find_loader(fullname): """Find a PEP 302 "loader" object for fullname If fullname contains dots, path must be the containing package's __path__. Returns None if the module cannot be found or imported. This function uses iter_importers(), and is thus subject to the same limitations regarding pla...
Find a PEP 302 "loader" object for fullname If fullname contains dots, path must be the containing package's __path__. Returns None if the module cannot be found or imported. This function uses iter_importers(), and is thus subject to the same limitations regarding platform-specific special import loca...
def sighash_all(self, index=0, script=None, prevout_value=None, anyone_can_pay=False): ''' SproutTx, int, byte-like, byte-like, bool -> bytearray Sighashes suck Generates the hash to be signed with SIGHASH_ALL https://en.bitcoin.it/wiki/OP_CHECKSIG#Hashtype_SI...
SproutTx, int, byte-like, byte-like, bool -> bytearray Sighashes suck Generates the hash to be signed with SIGHASH_ALL https://en.bitcoin.it/wiki/OP_CHECKSIG#Hashtype_SIGHASH_ALL_.28default.29
def get_homology_models(self): """DictList: Return a DictList of all homology models in self.structures""" # TODO: change to a property? if self.representative_structure: return DictList(x for x in self.structures if not x.is_experimental and x.id != self.representative_structure.id)...
DictList: Return a DictList of all homology models in self.structures
def from_cap(cls, theta, lwin, clat=None, clon=None, nwin=None, theta_degrees=True, coord_degrees=True, dj_matrix=None, weights=None): """ Construct spherical cap localization windows. Usage ----- x = SHWindow.from_cap(theta, lwin, [clat, clon, ...
Construct spherical cap localization windows. Usage ----- x = SHWindow.from_cap(theta, lwin, [clat, clon, nwin, theta_degrees, coord_degrees, dj_matrix, weights]) Returns ------- x : SHWindow class instance Parameters...
def clean_output_files(self, follow_parents=True): """ This method is called when the task reaches S_OK. It removes all the output files produced by the task that are not needed by its children as well as the output files produced by its parents if no other node needs them. Args...
This method is called when the task reaches S_OK. It removes all the output files produced by the task that are not needed by its children as well as the output files produced by its parents if no other node needs them. Args: follow_parents: If true, the output files of the parents ...
def plot_pca_component_variance(clf, title='PCA Component Explained Variances', target_explained_variance=0.75, ax=None, figsize=None, title_fontsize="large", text_fontsize="medium"): """Plots PCA components' explained v...
Plots PCA components' explained variance ratios. (new in v0.2.2) Args: clf: PCA instance that has the ``explained_variance_ratio_`` attribute. title (string, optional): Title of the generated plot. Defaults to "PCA Component Explained Variances" target_explained_variance (floa...
def _get_account(self, address): """Get account by address. :param address: :return: """ state = self._get_head_state() account_address = binascii.a2b_hex(utils.remove_0x_head(address)) return state.get_and_cache_account(account_address)
Get account by address. :param address: :return:
def _handle_port_request(self, client_data, writer): """Given a port request body, parse it and respond appropriately. Args: client_data: The request bytes from the client. writer: The asyncio Writer for the response to be written to. """ try: pid = int(c...
Given a port request body, parse it and respond appropriately. Args: client_data: The request bytes from the client. writer: The asyncio Writer for the response to be written to.
def __ConstructQueryParams(self, query_params, request, global_params): """Construct a dictionary of query parameters for this request.""" # First, handle the global params. global_params = self.__CombineGlobalParams( global_params, self.__client.global_params) global_param_n...
Construct a dictionary of query parameters for this request.
def dfs_tree(graph, start=0): """DFS, build DFS tree in unweighted graph :param graph: directed graph in listlist or listdict format :param int start: source vertex :returns: precedence table :complexity: `O(|V|+|E|)` """ to_visit = [start] prec = [None] * len(graph) ...
DFS, build DFS tree in unweighted graph :param graph: directed graph in listlist or listdict format :param int start: source vertex :returns: precedence table :complexity: `O(|V|+|E|)`
def generate_new_id(self): """ generate new id and event hook for new Individual """ self.events.append(Event()) indiv_id = self.indiv_counter self.indiv_counter += 1 return indiv_id
generate new id and event hook for new Individual
def import_schema_to_json(name, store_it=False): """ loads the given schema name from the local filesystem and puts it into a store if it is not in there yet :param name: :param store_it: if set to True, stores the contents :return: """ schema_file = u"%s.json" % name file_p...
loads the given schema name from the local filesystem and puts it into a store if it is not in there yet :param name: :param store_it: if set to True, stores the contents :return:
def end_output (self, **kwargs): """Write end of checking info as HTML.""" if self.has_part("stats"): self.write_stats() if self.has_part("outro"): self.write_outro() self.close_fileoutput()
Write end of checking info as HTML.
def next(self): """Returns the next input from this input reader as (ZipInfo, opener) tuple. Returns: The next input from this input reader, in the form of a 2-tuple. The first element of the tuple is a zipfile.ZipInfo object. The second element of the tuple is a zero-argument function that, ...
Returns the next input from this input reader as (ZipInfo, opener) tuple. Returns: The next input from this input reader, in the form of a 2-tuple. The first element of the tuple is a zipfile.ZipInfo object. The second element of the tuple is a zero-argument function that, when called, retu...
def simxGetInMessageInfo(clientID, infoType): ''' Please have a look at the function description/documentation in the V-REP user manual ''' info = ct.c_int() return c_GetInMessageInfo(clientID, infoType, ct.byref(info)), info.value
Please have a look at the function description/documentation in the V-REP user manual
def _compute_type_url(klass, prefix=_GOOGLE_APIS_PREFIX): """Compute a type URL for a klass. :type klass: type :param klass: class to be used as a factory for the given type :type prefix: str :param prefix: URL prefix for the type :rtype: str :returns: the URL, prefixed as appropriate ...
Compute a type URL for a klass. :type klass: type :param klass: class to be used as a factory for the given type :type prefix: str :param prefix: URL prefix for the type :rtype: str :returns: the URL, prefixed as appropriate
def _update_zone_bypass_status(self, message=None, status=None, zone=None): """ Uses the provided message to update the zone bypass state. :param message: message to use to update :type message: :py:class:`~alarmdecoder.messages.Message` :param status: bypass status, overrides m...
Uses the provided message to update the zone bypass state. :param message: message to use to update :type message: :py:class:`~alarmdecoder.messages.Message` :param status: bypass status, overrides message bits. :type status: bool :param zone: zone associated with bypass event ...
def append_to_arg_count(self, data): """ Add digit to the input argument. :param data: the typed digit as string """ assert data in '-0123456789' current = self._arg if data == '-': assert current is None or current == '-' result = data ...
Add digit to the input argument. :param data: the typed digit as string
def create_salt(length: int=128) -> bytes: """ Create a new salt :param int length: How many bytes should the salt be long? :return: The salt :rtype: bytes """ return b''.join(bytes([SystemRandom().randint(0, 255)]) for _ in range(length))
Create a new salt :param int length: How many bytes should the salt be long? :return: The salt :rtype: bytes
def get_tx_power(self, tx_power): """Validates tx_power against self.tx_power_table @param tx_power: index into the self.tx_power_table list; if tx_power is 0 then the max power from self.tx_power_table @return: a dict {antenna: (tx_power_index, power_dbm)} from self.tx_...
Validates tx_power against self.tx_power_table @param tx_power: index into the self.tx_power_table list; if tx_power is 0 then the max power from self.tx_power_table @return: a dict {antenna: (tx_power_index, power_dbm)} from self.tx_power_table @raise: LLRPError if the ...
def send(self, message): """Send our message Args: message (str): The message to be sent. Returns: requests.models.Response: The response from the request. """ body = { 'notificationType': self._notification_type, 'priority': sel...
Send our message Args: message (str): The message to be sent. Returns: requests.models.Response: The response from the request.
def Push(self, source_file, device_filename, mtime='0', timeout_ms=None, progress_callback=None, st_mode=None): """Push a file or directory to the device. Args: source_file: Either a filename, a directory or file-like object to push to the device. device_filen...
Push a file or directory to the device. Args: source_file: Either a filename, a directory or file-like object to push to the device. device_filename: Destination on the device to write to. mtime: Optional, modification time to set on the file. time...
def on_press(self, window, key, scancode, action, mods): """ Key handler for key presses. """ # controls for moving position if key == glfw.KEY_W: self.pos[0] -= self._pos_step # dec x elif key == glfw.KEY_S: self.pos[0] += self._pos_step # inc ...
Key handler for key presses.
def get_registered_configs(self, instances=None): """ Return the persisted values of all config files registered with the config manager. """ configs = self.state.get('config_files', {}) if instances is not None: for config_file, config in configs.items(): if ...
Return the persisted values of all config files registered with the config manager.
def handle_exception(self, exc): """ Handle any exception that occurs, by returning an appropriate response, or re-raising the error. """ if isinstance(exc, (exceptions.NotAuthenticated, exceptions.AuthenticationFailed)): # WWW-Authenticate...
Handle any exception that occurs, by returning an appropriate response, or re-raising the error.
def list_networks(full_ids=False): """ Lists networks on the Docker remote host, similar to ``docker network ls``. :param full_ids: Shows the full network ids. When ``False`` (default) only shows the first 12 characters. :type full_ids: bool """ networks = docker_fabric().networks() _format...
Lists networks on the Docker remote host, similar to ``docker network ls``. :param full_ids: Shows the full network ids. When ``False`` (default) only shows the first 12 characters. :type full_ids: bool
def update_resource(self, path, data, if_match=None): """Update the required resource.""" response = self._http_request(resource=path, method="PUT", body=data, if_match=if_match) try: return response.json() except ValueError: ...
Update the required resource.
def inject(fun: Callable) -> Callable: """ A decorator for injection dependencies into functions/methods, based on their type annotations. .. code-block:: python class SomeClass: @inject def __init__(self, my_dep: DepType) -> None: self.my_dep = my_dep ...
A decorator for injection dependencies into functions/methods, based on their type annotations. .. code-block:: python class SomeClass: @inject def __init__(self, my_dep: DepType) -> None: self.my_dep = my_dep .. important:: On the opposite to :cla...
def _load_with_overrides(base) -> Dict[str, str]: """ Load an config or write its defaults """ should_write = False overrides = _get_environ_overrides() try: index = json.load((base/_CONFIG_FILENAME).open()) except (OSError, json.JSONDecodeError) as e: sys.stderr.write("Error loading...
Load an config or write its defaults
def set_encoding (parsobj, attrs): """ Set document encoding for the HTML parser according to the <meta> tag attribute information. @param attrs: attributes of a <meta> HTML tag @type attrs: dict @return: None """ charset = attrs.get_true('charset', u'') if charset: # <meta ...
Set document encoding for the HTML parser according to the <meta> tag attribute information. @param attrs: attributes of a <meta> HTML tag @type attrs: dict @return: None
def corr(self, method='pearson', min_periods=1): """ Compute pairwise correlation of columns, excluding NA/null values. Parameters ---------- method : {'pearson', 'kendall', 'spearman'} or callable * pearson : standard correlation coefficient * kendall : ...
Compute pairwise correlation of columns, excluding NA/null values. Parameters ---------- method : {'pearson', 'kendall', 'spearman'} or callable * pearson : standard correlation coefficient * kendall : Kendall Tau correlation coefficient * spearman : Spearman...
def format_summary(self): """Generate a summary string for the progress bar.""" chunks = [chunk.format_chunk_summary() for chunk in self._progress_chunks] return "/".join(chunks)
Generate a summary string for the progress bar.
def get_queryset(self): ''' Recent events are listed in link form. ''' return Event.objects.filter( Q(startTime__gte=timezone.now() - timedelta(days=90)) & ( Q(series__isnull=False) | Q(publicevent__isnull=False) ) ).annotate(count=Count('eventregistratio...
Recent events are listed in link form.
def check_and_set_unreachability(self, hosts, services): """ Check if all dependencies are down, if yes set this object as unreachable. todo: this function do not care about execution_failure_criteria! :param hosts: hosts objects, used to get object in act_depend_of :ty...
Check if all dependencies are down, if yes set this object as unreachable. todo: this function do not care about execution_failure_criteria! :param hosts: hosts objects, used to get object in act_depend_of :type hosts: alignak.objects.host.Hosts :param services: services object...
def convert_to_decimal(string): """ Decode the exif-gps format into a decimal point. '[51, 4, 1234/34]' -> 51.074948366 """ number_or_fraction = '(?:\d{1,2}) | (?:\d{1,10} \\ \d{1,10})' m = re.compile('''\[?\s? # opening bracket \d{{1,2}}\s?,\s? # first...
Decode the exif-gps format into a decimal point. '[51, 4, 1234/34]' -> 51.074948366
def _find_cf_standard_name_table(self, ds): ''' Parse out the `standard_name_vocabulary` attribute and download that version of the cf standard name table. If the standard name table has already been downloaded, use the cached version. Modifies `_std_names` attribute to store s...
Parse out the `standard_name_vocabulary` attribute and download that version of the cf standard name table. If the standard name table has already been downloaded, use the cached version. Modifies `_std_names` attribute to store standard names. Returns True if the file exists and Fals...
def compute_verify_data(self, con_end, read_or_write, handshake_msg, master_secret): """ Return verify_data based on handshake messages, connection end, master secret, and read_or_write position. See RFC 5246, section 7.4.9. Every TLS 1.2 cipher suite has a v...
Return verify_data based on handshake messages, connection end, master secret, and read_or_write position. See RFC 5246, section 7.4.9. Every TLS 1.2 cipher suite has a verify_data of length 12. Note also: "This PRF with the SHA-256 hash function is used for all cipher suites defined i...