code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def configure(host=DEFAULT_HOST, port=DEFAULT_PORT, prefix=''): """ >>> configure() >>> configure('localhost', 8125, 'mymetrics') """ global _client logging.info("Reconfiguring metrics: {}:{}/{}".format(host, port, prefix)) _client = statsdclient.StatsdClient(host, port, prefix)
>>> configure() >>> configure('localhost', 8125, 'mymetrics')
def shrunk_covariance(self, delta=0.2): """ Shrink a sample covariance matrix to the identity matrix (scaled by the average sample variance). This method does not estimate an optimal shrinkage parameter, it requires manual input. :param delta: shrinkage parameter, defaults to 0....
Shrink a sample covariance matrix to the identity matrix (scaled by the average sample variance). This method does not estimate an optimal shrinkage parameter, it requires manual input. :param delta: shrinkage parameter, defaults to 0.2. :type delta: float, optional :return: shr...
def main(): """ Launches data-parallel multi-gpu training. """ mlperf_log.ROOT_DIR_GNMT = os.path.dirname(os.path.abspath(__file__)) mlperf_log.LOGGER.propagate = False args = parse_args() device = utils.set_device(args.cuda, args.local_rank) distributed = utils.init_distributed(args.cu...
Launches data-parallel multi-gpu training.
def minimize_memory(self): """ Reduce the allocated memory to the minimum required to store the current audio samples. This function is meant to be called when building a wave incrementally, after the last append operation. .. versionadded:: 1.5.0 """ ...
Reduce the allocated memory to the minimum required to store the current audio samples. This function is meant to be called when building a wave incrementally, after the last append operation. .. versionadded:: 1.5.0
def _slice_take_blocks_ax0(self, slice_or_indexer, fill_tuple=None): """ Slice/take blocks along axis=0. Overloaded for SingleBlock Returns ------- new_blocks : list of Block """ allow_fill = fill_tuple is not None sl_type, slobj, sllen = _pre...
Slice/take blocks along axis=0. Overloaded for SingleBlock Returns ------- new_blocks : list of Block
def serialize(self, value, greedy=True): """ Greedy serialization requires the value to either be a column or convertible to a column, whereas non-greedy serialization will pass through any string as-is and will only serialize Column objects. Non-greedy serialization is ...
Greedy serialization requires the value to either be a column or convertible to a column, whereas non-greedy serialization will pass through any string as-is and will only serialize Column objects. Non-greedy serialization is useful when preparing queries with custom filters or ...
async def verifier_verify_proof(proof_request_json: str, proof_json: str, schemas_json: str, credential_defs_json: str, rev_reg_defs_json: str, rev_regs_json: s...
Verifies a proof (of multiple credential). All required schemas, public keys and revocation registries must be provided. :param proof_request_json: { "name": string, "version": string, "nonce": string, "requested_attributes": { // set of requested a...
def _gen_from_dircmp(dc, lpath, rpath): """ do the work of comparing the dircmp """ left_only = dc.left_only left_only.sort() for f in left_only: fp = join(dc.left, f) if isdir(fp): for r, _ds, fs in walk(fp): r = relpath(r, lpath) fo...
do the work of comparing the dircmp
def snake2ucamel(value): """Casts a snake_case string to an UpperCamelCase string.""" UNDER, LETTER, OTHER = object(), object(), object() def group_key_function(char): if char == "_": return UNDER if char in string.ascii_letters: return LETTER return OTHER ...
Casts a snake_case string to an UpperCamelCase string.
def in_base(self, unit_system=None): """ Creates a copy of this array with the data in the specified unit system, and returns it in that system's base units. Parameters ---------- unit_system : string, optional The unit system to be used in the conversion. If...
Creates a copy of this array with the data in the specified unit system, and returns it in that system's base units. Parameters ---------- unit_system : string, optional The unit system to be used in the conversion. If not specified, the configured default base u...
def list_container_processes(container): """ List the processes running inside a container. We use an exec rather than `container.top()` because we want to run 'ps' inside the container. This is because we want to get PIDs and usernames in the container's namespaces. `container.top()` uses 'ps' from...
List the processes running inside a container. We use an exec rather than `container.top()` because we want to run 'ps' inside the container. This is because we want to get PIDs and usernames in the container's namespaces. `container.top()` uses 'ps' from outside the container in the host's namespaces. ...
def output_extras(self, output_file): """ Returns dict mapping local path to remote name. """ output_directory = dirname(output_file) def local_path(name): return join(output_directory, self.path_helper.local_name(name)) files_directory = "%s_files%s" % (bas...
Returns dict mapping local path to remote name.
def parse_value(parser, event, node): # pylint: disable=unused-argument """ Parse CIM/XML VALUE element and return the value""" value = '' (next_event, next_node) = six.next(parser) if next_event == pulldom.CHARACTERS: value = next_node.nodeValue (next_event, next_node) = six.next(pa...
Parse CIM/XML VALUE element and return the value
def _apply_backwards_compatibility(df): """ Attach properties to the Dataframe to make it backwards compatible with older versions of this library :param df: The dataframe to be modified """ df.row_count = types.MethodType(lambda self: len(self.index), df) df.col_count = types.MethodType(lambda...
Attach properties to the Dataframe to make it backwards compatible with older versions of this library :param df: The dataframe to be modified
def selectrangeopenleft(table, field, minv, maxv, complement=False): """Select rows where the given field is greater than or equal to `minv` and less than `maxv`.""" minv = Comparable(minv) maxv = Comparable(maxv) return select(table, field, lambda v: minv <= v < maxv, complement=...
Select rows where the given field is greater than or equal to `minv` and less than `maxv`.
def pull_screenrecord(self, bit_rate: int = 5000000, time_limit: int = 180, remote: _PATH = '/sdcard/demo.mp4', local: _PATH = 'demo.mp4') -> None: '''Recording the display of devices running Android 4.4 (API level 19) and higher. Then copy it to your computer. Args: bit_rate:You can increa...
Recording the display of devices running Android 4.4 (API level 19) and higher. Then copy it to your computer. Args: bit_rate:You can increase the bit rate to improve video quality, but doing so results in larger movie files. time_limit: Sets the maximum recording time, in seconds, and ...
def from_dict(data, ctx): """ Instantiate a new Candlestick from a dict (generally from loading a JSON response). The data used to instantiate the Candlestick is a shallow copy of the dict passed in, with any complex child types instantiated appropriately. """ da...
Instantiate a new Candlestick from a dict (generally from loading a JSON response). The data used to instantiate the Candlestick is a shallow copy of the dict passed in, with any complex child types instantiated appropriately.
def connect(self, db_uri, debug=False): """Configure connection to a SQL database. Args: db_uri (str): path/URI to the database to connect to debug (Optional[bool]): whether to output logging information """ kwargs = {'echo': debug, 'convert_unicode': True} ...
Configure connection to a SQL database. Args: db_uri (str): path/URI to the database to connect to debug (Optional[bool]): whether to output logging information
def add(self, schema, data): """ Stage ``data`` as a set of statements, based on the given ``schema`` definition. """ binding = self.get_binding(schema, data) uri, triples = triplify(binding) for triple in triples: self.graph.add(triple) return uri
Stage ``data`` as a set of statements, based on the given ``schema`` definition.
def _AddVariable(self, variable): """ Add a variable to the model. Should not be used by end-user """ if isinstance(variable, Signal): if not variable in self.signals: self.signals.append(variable) elif isinstance(variable, Variable): if no...
Add a variable to the model. Should not be used by end-user
def set_position(self, decl_pos): """Set editor position from ENSIME declPos data.""" if decl_pos["typehint"] == "LineSourcePosition": self.editor.set_cursor(decl_pos['line'], 0) else: # OffsetSourcePosition point = decl_pos["offset"] row, col = self.editor.p...
Set editor position from ENSIME declPos data.
def add(self, item_numid, collect_type, shared, session): '''taobao.favorite.add 添加收藏夹 根据用户昵称和收藏目标的数字id以及收藏目标的类型,实现收藏行为''' request = TOPRequest('taobao.favorite.add') request['item_numid'] = item_numid request['collect_type'] = collect_type request['shared'] = sh...
taobao.favorite.add 添加收藏夹 根据用户昵称和收藏目标的数字id以及收藏目标的类型,实现收藏行为
def iter_create_panes(self, w, wconf): """ Return :class:`libtmux.Pane` iterating through window config dict. Run ``shell_command`` with ``$ tmux send-keys``. Parameters ---------- w : :class:`libtmux.Window` window to create panes for wconf : dict ...
Return :class:`libtmux.Pane` iterating through window config dict. Run ``shell_command`` with ``$ tmux send-keys``. Parameters ---------- w : :class:`libtmux.Window` window to create panes for wconf : dict config section for window Returns ...
def _set_ldp_fec_vcs(self, v, load=False): """ Setter method for ldp_fec_vcs, mapped from YANG variable /mpls_state/ldp/fec/ldp_fec_vcs (container) If this variable is read-only (config: false) in the source YANG file, then _set_ldp_fec_vcs is considered as a private method. Backends looking to popu...
Setter method for ldp_fec_vcs, mapped from YANG variable /mpls_state/ldp/fec/ldp_fec_vcs (container) If this variable is read-only (config: false) in the source YANG file, then _set_ldp_fec_vcs is considered as a private method. Backends looking to populate this variable should do so via calling thisObj...
def get_unused_port(port=None): """Checks if port is already in use.""" if port is None or port < 1024 or port > 65535: port = random.randint(1024, 65535) assert(1024 <= port <= 65535) while True: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.bind(('', ...
Checks if port is already in use.
async def process_graph_input(graph, stream, value, rpc_executor): """Process an input through this sensor graph. The tick information in value should be correct and is transfered to all results produced by nodes acting on this tick. This coroutine is an asyncio compatible version of SensorGraph.proce...
Process an input through this sensor graph. The tick information in value should be correct and is transfered to all results produced by nodes acting on this tick. This coroutine is an asyncio compatible version of SensorGraph.process_input() Args: stream (DataStream): The stream the input is...
def get_value(self, name): """ Get return value of a dependency factory or a live singleton instance. """ factory = self._registered.get(name) if not factory: raise KeyError('Name not registered') if factory._giveme_singleton: if name in se...
Get return value of a dependency factory or a live singleton instance.
def is_date(self): """Determine if a data record is of type DATE.""" dt = DATA_TYPES['date'] if type(self.data) is dt['type'] and '-' in str(self.data) and str(self.data).count('-') == 2: # Separate year, month and day date_split = str(self.data).split('-') y,...
Determine if a data record is of type DATE.
def get_environments(): '''Returns a list of all known virtual environments as :class:`VirtualEnvironment` instances. This includes those in CPENV_HOME and any others that are cached(created by the current user or activated once by full path.) ''' environments = set() cwd = os.getcwd() ...
Returns a list of all known virtual environments as :class:`VirtualEnvironment` instances. This includes those in CPENV_HOME and any others that are cached(created by the current user or activated once by full path.)
def add_nodes_to_axes(self): """ Creates a new marker for every node from idx indexes and lists of node_values, node_colors, node_sizes, node_style, node_labels_style. Pulls from node_color and adds to a copy of the style dict for each node to create marker. Node_color...
Creates a new marker for every node from idx indexes and lists of node_values, node_colors, node_sizes, node_style, node_labels_style. Pulls from node_color and adds to a copy of the style dict for each node to create marker. Node_colors has priority to overwrite node_style['fill']
def majmin(reference_labels, estimated_labels): """Compare chords along major-minor rules. Chords with qualities outside Major/minor/no-chord are ignored. Examples -------- >>> (ref_intervals, ... ref_labels) = mir_eval.io.load_labeled_intervals('ref.lab') >>> (est_intervals, ... est_...
Compare chords along major-minor rules. Chords with qualities outside Major/minor/no-chord are ignored. Examples -------- >>> (ref_intervals, ... ref_labels) = mir_eval.io.load_labeled_intervals('ref.lab') >>> (est_intervals, ... est_labels) = mir_eval.io.load_labeled_intervals('est.lab')...
def paddingsize(self, namedstruct): ''' Return the size of the padded struct (including the "real" size and the padding bytes) :param namedstruct: a NamedStruct object of this type. :returns: size including both data and padding. ''' if self.base is not ...
Return the size of the padded struct (including the "real" size and the padding bytes) :param namedstruct: a NamedStruct object of this type. :returns: size including both data and padding.
def read(self, sync_map_format, input_file_path, parameters=None): """ Read sync map fragments from the given file in the specified format, and add them the current (this) sync map. Return ``True`` if the call succeeded, ``False`` if an error occurred. :param sync_map_f...
Read sync map fragments from the given file in the specified format, and add them the current (this) sync map. Return ``True`` if the call succeeded, ``False`` if an error occurred. :param sync_map_format: the format of the sync map :type sync_map_format: :class:`~aeneas.syncm...
def is_unicode_string(string): """ Return ``True`` if the given string is a Unicode string, that is, of type ``unicode`` in Python 2 or ``str`` in Python 3. Return ``None`` if ``string`` is ``None``. :param str string: the string to be checked :rtype: bool """ if string is None: ...
Return ``True`` if the given string is a Unicode string, that is, of type ``unicode`` in Python 2 or ``str`` in Python 3. Return ``None`` if ``string`` is ``None``. :param str string: the string to be checked :rtype: bool
def graph(self): """ A conjunctive graph of all statements in the current instance. """ if not hasattr(self, '_graph') or self._graph is None: self._graph = ConjunctiveGraph(store=self.store, identifier=self.base_uri) return self._graph
A conjunctive graph of all statements in the current instance.
def stream_download(url, target_path, verbose=False): """ Download a large file without loading it into memory. """ response = requests.get(url, stream=True) handle = open(target_path, "wb") if verbose: print("Beginning streaming download of %s" % url) start = datetime.now() try:...
Download a large file without loading it into memory.
def gevent_worker(self): """ Process one task after another by calling the handler (`copy_file` or `copy_link`) method of the super class. """ while not self.task_queue.empty(): task_kwargs = self.task_queue.get() handler_type = task_kwargs.pop('handler_type') ...
Process one task after another by calling the handler (`copy_file` or `copy_link`) method of the super class.
def _set_attributes(self): """Traverse the internal dictionary and set the getters""" for parameter, data in self._data.items(): if isinstance(data, dict) or isinstance(data, OrderedDict): field_names, field_values = zip(*data.items()) sorted_indices = np.args...
Traverse the internal dictionary and set the getters
def register_plugin(self): """Register plugin in Spyder's main window""" self.focus_changed.connect(self.main.plugin_focus_changed) self.main.add_dockwidget(self) self.main.console.set_help(self) self.internal_shell = self.main.console.shell self.console = self.ma...
Register plugin in Spyder's main window
def est_entropy(self): r""" Estimates the entropy of the current particle distribution as :math:`-\sum_i w_i \log w_i` where :math:`\{w_i\}` is the set of particles with nonzero weight. """ nz_weights = self.particle_weights[self.particle_weights > 0] return -np.s...
r""" Estimates the entropy of the current particle distribution as :math:`-\sum_i w_i \log w_i` where :math:`\{w_i\}` is the set of particles with nonzero weight.
def load_x509_certificates(buf): """Load one or multiple X.509 certificates from a buffer. :param str buf: A buffer is an instance of `basestring` and can contain multiple certificates. :return: An iterator that iterates over certificates in a buffer. :rtype: list[:class:`OpenSSL.crypto.X509`] """ if ...
Load one or multiple X.509 certificates from a buffer. :param str buf: A buffer is an instance of `basestring` and can contain multiple certificates. :return: An iterator that iterates over certificates in a buffer. :rtype: list[:class:`OpenSSL.crypto.X509`]
def prompt_gui(path): """Prompt for a new filename via GUI.""" import subprocess filepath, extension = os.path.splitext(path) basename = os.path.basename(filepath) dirname = os.path.dirname(filepath) retry_text = 'Sorry, please try again...' icon = 'video-x-generic' # detect and conf...
Prompt for a new filename via GUI.
def strtimezone (): """Return timezone info, %z on some platforms, but not supported on all. """ if time.daylight: zone = time.altzone else: zone = time.timezone return "%+04d" % (-zone//SECONDS_PER_HOUR)
Return timezone info, %z on some platforms, but not supported on all.
def routingAreaUpdateComplete(ReceiveNpduNumbersList_presence=0): """ROUTING AREA UPDATE COMPLETE Section 9.4.16""" a = TpPd(pd=0x3) b = MessageType(mesType=0xa) # 00001010 packet = a / b if ReceiveNpduNumbersList_presence is 1: c = ReceiveNpduNumbersList(ieiRNNL=0x26) packet = pack...
ROUTING AREA UPDATE COMPLETE Section 9.4.16
def __writeDocstring(self): """ Runs eternally, dumping out docstring line batches as they get fed in. Replaces original batches of docstring lines with modified versions fed in via send. """ while True: firstLineNum, lastLineNum, lines = (yield) ...
Runs eternally, dumping out docstring line batches as they get fed in. Replaces original batches of docstring lines with modified versions fed in via send.
def version(ctx, version=None, force=False): """ Specify a new version for the package. .. important:: If no version is specified, will take the most recent parsable git tag and bump the patch number. :param str version: The new version of the package. :param bool force: If True, skips version...
Specify a new version for the package. .. important:: If no version is specified, will take the most recent parsable git tag and bump the patch number. :param str version: The new version of the package. :param bool force: If True, skips version check
def resp_set_lightpower(self, resp, power_level=None): """Default callback for set_power """ if power_level is not None: self.power_level=power_level elif resp: self.power_level=resp.power_level
Default callback for set_power
def edge(self, from_node, to_node, edge_type="", **args): """draw an edge from a node to another. """ self._stream.write( '%s%sedge: {sourcename:"%s" targetname:"%s"' % (self._indent, edge_type, from_node, to_node) ) self._write_attributes(EDGE_ATTRS, **ar...
draw an edge from a node to another.
def get_acronyms(fulltext): """Find acronyms and expansions from the fulltext. If needed, acronyms can already contain a dictionary of previously found acronyms that will be merged with the current results. """ acronyms = {} for m in ACRONYM_BRACKETS_REGEX.finditer(fulltext): acronym ...
Find acronyms and expansions from the fulltext. If needed, acronyms can already contain a dictionary of previously found acronyms that will be merged with the current results.
def find(objs, selector, context=None): ''' Query a collection of Bokeh models and yield any that match the a selector. Args: obj (Model) : object to test selector (JSON-like) : query selector context (dict) : kwargs to supply callable query attributes Yields: Model : o...
Query a collection of Bokeh models and yield any that match the a selector. Args: obj (Model) : object to test selector (JSON-like) : query selector context (dict) : kwargs to supply callable query attributes Yields: Model : objects that match the query Queries are spe...
def get_counter(self, name, start=0): ''' Gets the DynamoDB item behind a counter and ties it to a Counter instace. ''' item = self.get_item(hash_key=name, start=start) counter = Counter(dynamo_item=item, pool=self) return counter
Gets the DynamoDB item behind a counter and ties it to a Counter instace.
def rnn(name, input, state, kernel, bias, new_state, number_of_gates = 2): ''' - Ht = f(Xt*Wi + Ht_1*Ri + Wbi + Rbi) ''' nn = Build(name) nn.tanh( nn.mad(kernel=kernel, bias=bias, x=nn.concat(input, state)), out=new_state); return nn.layers;
- Ht = f(Xt*Wi + Ht_1*Ri + Wbi + Rbi)
def upload_directory_contents(input_dict, environment_dict): """This function serves to upload every file in a user-supplied source directory to all of the vessels in the current target group. It essentially calls seash's `upload` function repeatedly, each time with a file name taken from the source directory...
This function serves to upload every file in a user-supplied source directory to all of the vessels in the current target group. It essentially calls seash's `upload` function repeatedly, each time with a file name taken from the source directory. A note on the input_dict argument: `input_dict` contains ou...
def V_vertical_torispherical_concave(D, f, k, h): r'''Calculates volume of a vertical tank with a concave torispherical bottom, according to [1]_. No provision for the top of the tank is made here. .. math:: V = \frac{\pi D^2 h}{4} - v_1(h=a_1+a_2) + v_1(h=a_1 + a_2 -h),\; 0 \le h < a_2 .. mat...
r'''Calculates volume of a vertical tank with a concave torispherical bottom, according to [1]_. No provision for the top of the tank is made here. .. math:: V = \frac{\pi D^2 h}{4} - v_1(h=a_1+a_2) + v_1(h=a_1 + a_2 -h),\; 0 \le h < a_2 .. math:: V = \frac{\pi D^2 h}{4} - v_1(h=a_1+a_2) +...
def _get_isolated(self, hostport): """Get a Peer for the given destination for a request. A new Peer is added and returned if one does not already exist for the given host-port. Otherwise, the existing Peer is returned. **NOTE** new peers will not be added to the peer heap. """...
Get a Peer for the given destination for a request. A new Peer is added and returned if one does not already exist for the given host-port. Otherwise, the existing Peer is returned. **NOTE** new peers will not be added to the peer heap.
def get_processing_block_ids(self): """Get list of processing block ids using the processing block id""" # Initialise empty list _processing_block_ids = [] # Pattern used to search processing block ids pattern = '*:processing_block:*' block_ids = self._db.get_ids(patter...
Get list of processing block ids using the processing block id
def MultiOpenOrdered(self, urns, **kwargs): """Opens many URNs and returns handles in the same order. `MultiOpen` can return file handles in arbitrary order. This makes it more efficient and in most cases the order does not matter. However, there are cases where order is important and this function sho...
Opens many URNs and returns handles in the same order. `MultiOpen` can return file handles in arbitrary order. This makes it more efficient and in most cases the order does not matter. However, there are cases where order is important and this function should be used instead. Args: urns: A list ...
def load(self): '''获取当前的离线任务列表''' def on_list_task(info, error=None): self.loading_spin.stop() self.loading_spin.hide() if not info: self.app.toast(_('Network error, info is empty')) if error or not info: logger.error('Cloud...
获取当前的离线任务列表
def make_job_graph(infiles, fragfiles, blastcmds): """Return a job dependency graph, based on the passed input sequence files. - infiles - a list of paths to input FASTA files - fragfiles - a list of paths to fragmented input FASTA files By default, will run ANIb - it *is* possible to make a mess of p...
Return a job dependency graph, based on the passed input sequence files. - infiles - a list of paths to input FASTA files - fragfiles - a list of paths to fragmented input FASTA files By default, will run ANIb - it *is* possible to make a mess of passing the wrong executable for the mode you're using....
def _run_in_reactor(self, function, _, args, kwargs): """ Implementation: A decorator that ensures the wrapped function runs in the reactor thread. When the wrapped function is called, an EventualResult is returned. """ def runs_in_reactor(result, args, kwargs): ...
Implementation: A decorator that ensures the wrapped function runs in the reactor thread. When the wrapped function is called, an EventualResult is returned.
def uninstall(self, name: str, force: bool = False, noprune: bool = False ) -> None: """ Attempts to uninstall a given Docker image. Parameters: name: the name of the Docker image. force: a flag indi...
Attempts to uninstall a given Docker image. Parameters: name: the name of the Docker image. force: a flag indicating whether or not an exception should be thrown if the image associated with the given build instructions is not installed. If `True`, no exc...
def fractal_dimension(image): '''Estimates the fractal dimension of an image with box counting. Counts pixels with value 0 as empty and everything else as non-empty. Input image has to be grayscale. See, e.g `Wikipedia <https://en.wikipedia.org/wiki/Fractal_dimension>`_. :param image: numpy.ndarra...
Estimates the fractal dimension of an image with box counting. Counts pixels with value 0 as empty and everything else as non-empty. Input image has to be grayscale. See, e.g `Wikipedia <https://en.wikipedia.org/wiki/Fractal_dimension>`_. :param image: numpy.ndarray :returns: estimation of fractal...
async def jsk_load(self, ctx: commands.Context, *extensions: ExtensionConverter): """ Loads or reloads the given extension names. Reports any extensions that failed to load. """ paginator = commands.Paginator(prefix='', suffix='') for extension in itertools.chain(*exte...
Loads or reloads the given extension names. Reports any extensions that failed to load.
def is_free(self): """ Returns a concrete determination as to whether the chunk is free. """ raise NotImplementedError("%s not implemented for %s" % (self.is_free.__func__.__name__, self.__class__.__name__))
Returns a concrete determination as to whether the chunk is free.
def pad_line_to_ontonotes(line, domain) -> List[str]: """ Pad line to conform to ontonotes representation. """ word_ind, word = line[ : 2] pos = 'XX' oie_tags = line[2 : ] line_num = 0 parse = "-" lemma = "-" return [domain, line_num, word_ind, word, pos, parse, lemma, '-',\ ...
Pad line to conform to ontonotes representation.
def get_fs(path): """Find the file system implementation for this path.""" scheme = '' if '://' in path: scheme = path.partition('://')[0] for schemes, fs_class in FILE_EXTENSIONS: if scheme in schemes: return fs_class return FileSystem
Find the file system implementation for this path.
def method(value, arg): """Method attempts to see if the value has a specified method. Usage: {% load custom_filters %} {% if foo|method:"has_access" %} """ if hasattr(value, str(arg)): return getattr(value, str(arg)) return "[%s has no method %s]" % (value, arg)
Method attempts to see if the value has a specified method. Usage: {% load custom_filters %} {% if foo|method:"has_access" %}
def threshold_monitor_hidden_threshold_monitor_sfp_policy_area_alert_above_above_highthresh_action(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") threshold_monitor_hidden = ET.SubElement(config, "threshold-monitor-hidden", xmlns="urn:brocade.com:mgmt:brocade-th...
Auto Generated Code
def set_instances(name, instances, test=False, region=None, key=None, keyid=None, profile=None): ''' Set the instances assigned to an ELB to exactly the list given CLI example: .. code-block:: bash salt myminion boto_elb.set_instances myelb region=us-east-1 instances=...
Set the instances assigned to an ELB to exactly the list given CLI example: .. code-block:: bash salt myminion boto_elb.set_instances myelb region=us-east-1 instances="[instance_id,instance_id]"
def _combine_season_stats(self, table_rows, career_stats, all_stats_dict): """ Combine all stats for each season. Since all of the stats are spread across multiple tables, they should be combined into a single field which can be used to easily query stats at once. Param...
Combine all stats for each season. Since all of the stats are spread across multiple tables, they should be combined into a single field which can be used to easily query stats at once. Parameters ---------- table_rows : generator A generator where each elem...
def copy_pkg(self, filename, id_=-1): """Copy a pkg, dmg, or zip to all repositories. Args: filename: String path to the local file to copy. id_: Integer ID you wish to associate package with for a JDS or CDP only. Default is -1, which is used for creating ...
Copy a pkg, dmg, or zip to all repositories. Args: filename: String path to the local file to copy. id_: Integer ID you wish to associate package with for a JDS or CDP only. Default is -1, which is used for creating a new package object in the database.
def get_hosted_zone_by_name(client, zone_name): """Get the zone id of an existing zone by name. Args: client (:class:`botocore.client.Route53`): The connection used to interact with Route53's API. zone_name (string): The name of the DNS hosted zone to create. Returns: s...
Get the zone id of an existing zone by name. Args: client (:class:`botocore.client.Route53`): The connection used to interact with Route53's API. zone_name (string): The name of the DNS hosted zone to create. Returns: string: The Id of the Hosted Zone.
def prune_missing(table): """ Prune any files which are missing from the specified table """ try: for item in table.select(): if not os.path.isfile(item.file_path): logger.info("File disappeared: %s", item.file_path) item.delete() except: # pylint:disable...
Prune any files which are missing from the specified table
def predict(self,param_dict): """ predict new waveforms using multivar fit """ encoder_dict = self._designmatrix_object.encoder X, col_names = self._designmatrix_object.run_encoder(param_dict, encoder_dict) # compute predictions Y_pred = self._compute_prediction(X) return...
predict new waveforms using multivar fit
def _xml_namespace_strip(root): # type: (ET.Element) -> None """Strip the XML namespace prefix from all element tags under the given root Element.""" if '}' not in root.tag: return # Nothing to do, no namespace present for element in root.iter(): if '}' in element.tag: elem...
Strip the XML namespace prefix from all element tags under the given root Element.
def desc(self): """return the description of this endpoint""" doc = inspect.getdoc(self.controller_class) if not doc: doc = '' return doc
return the description of this endpoint
def errint(marker, number): """ Substitute an integer for the first occurrence of a marker found in the current long error message. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/errint_c.html :param marker: A substring of the error message to be replaced. :type marker: str :param...
Substitute an integer for the first occurrence of a marker found in the current long error message. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/errint_c.html :param marker: A substring of the error message to be replaced. :type marker: str :param number: The integer to substitute for m...
def list_settings(self): """ Get list of all appropriate settings and their default values. """ result = super().list_settings() result.append((self.SETTING_FLAG_HEADER, True)) result.append((self.SETTING_HEADER_CONTENT, 'Notice')) result.append((self.SETTING_HEAD...
Get list of all appropriate settings and their default values.
def load_creditscoring1(cost_mat_parameters=None): """Load and return the credit scoring Kaggle Credit competition dataset (classification). The credit scoring is a easily transformable example-dependent cost-sensitive classification dataset. Parameters ---------- cost_mat_parameters : Dictionary-...
Load and return the credit scoring Kaggle Credit competition dataset (classification). The credit scoring is a easily transformable example-dependent cost-sensitive classification dataset. Parameters ---------- cost_mat_parameters : Dictionary-like object, optional (default=None) If not None, ...
def _parse_node(graph, text): """parse dumped node""" match = _NODEPAT.match(text) if match is not None: node = match.group(1) graph.node(node, label=match.group(2), shape='circle') return node match = _LEAFPAT.match(text) if match is not None: node = match.group(1) ...
parse dumped node
def arch_prefixes(self): """Return the initial 1, 2, ..., N architectures as a prefix list For arch1/arch2/arch3, this returns [arch1],[arch1/arch2],[arch1/arch2/arch3] """ archs = self.archs(as_list=True) prefixes = [] for i in range(1, len(archs)+1): ...
Return the initial 1, 2, ..., N architectures as a prefix list For arch1/arch2/arch3, this returns [arch1],[arch1/arch2],[arch1/arch2/arch3]
def get_innerclasses(self): """ sequence of JavaInnerClassInfo instances describing the inner classes of this class definition reference: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.6 """ # noqa buff = self.get_attribute("InnerClasses") ...
sequence of JavaInnerClassInfo instances describing the inner classes of this class definition reference: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.6
def save_intermediate_array(self, array, name): """Save intermediate array object as FITS.""" if self.intermediate_results: fits.writeto(name, array, overwrite=True)
Save intermediate array object as FITS.
def export_path(self, relname, export_dir=None): """ Return the path of the exported file by adding the export_dir in front, the calculation ID at the end. :param relname: relative file name :param export_dir: export directory (if None use .export_dir) """ # remo...
Return the path of the exported file by adding the export_dir in front, the calculation ID at the end. :param relname: relative file name :param export_dir: export directory (if None use .export_dir)
def replacebranch1(idf, loop, branchname, listofcomponents_tuples, fluid=None, debugsave=False): """do I even use this ? .... yup! I do""" if fluid is None: fluid = '' listofcomponents_tuples = _clean_listofcomponents_tuples(listofcomponents_tuples) branch = idf.getobject('BRA...
do I even use this ? .... yup! I do
def get_backup_end_segment_and_time(self, db_conn, backup_mode): """Grab a timestamp and WAL segment name after the end of the backup: this is a point in time to which we must be able to recover to, and the last WAL segment that is required for the backup to be consistent. Note that pg_...
Grab a timestamp and WAL segment name after the end of the backup: this is a point in time to which we must be able to recover to, and the last WAL segment that is required for the backup to be consistent. Note that pg_switch_xlog()/pg_switch_wal() is a superuser-only function, but since pg_sta...
def _sliced_list(self, selector): """For slice selectors operating on lists, we need to handle them differently, depending on ``skipmissing``. In explicit mode, we may have to expand the list with ``default`` values. """ if self.skipmissing: return self.obj[selector] ...
For slice selectors operating on lists, we need to handle them differently, depending on ``skipmissing``. In explicit mode, we may have to expand the list with ``default`` values.
def jieba_tokenize(text, external_wordlist=False): """ Tokenize the given text into tokens whose word frequencies can probably be looked up. This uses Jieba, a word-frequency-based tokenizer. If `external_wordlist` is False, we tell Jieba to default to using wordfreq's own Chinese wordlist, and not...
Tokenize the given text into tokens whose word frequencies can probably be looked up. This uses Jieba, a word-frequency-based tokenizer. If `external_wordlist` is False, we tell Jieba to default to using wordfreq's own Chinese wordlist, and not to infer unknown words using a hidden Markov model. This e...
def get_relationship(self, relationship_id=None): """Gets the ``Relationship`` specified by its ``Id``. arg: relationship_id (osid.id.Id): the ``Id`` of the ``Relationship`` to retrieve return: (osid.relationship.Relationship) - the returned ``Relationship`` ...
Gets the ``Relationship`` specified by its ``Id``. arg: relationship_id (osid.id.Id): the ``Id`` of the ``Relationship`` to retrieve return: (osid.relationship.Relationship) - the returned ``Relationship`` raise: NotFound - no ``Relationship`` found with the ...
def data(self): """return all of colData as a 2D numpy array.""" data=np.empty((self.nRows,self.nCols),dtype=np.float) data[:]=np.nan # make everything nan by default for colNum,colData in enumerate(self.colData): validIs=np.where([np.isreal(v) for v in colData])[0] ...
return all of colData as a 2D numpy array.
def _UpdateAuthorizedKeys(self, user, ssh_keys): """Update the authorized keys file for a Linux user with a list of SSH keys. Args: user: string, the name of the Linux user account. ssh_keys: list, the SSH key strings associated with the user. Raises: IOError, raised when there is an exc...
Update the authorized keys file for a Linux user with a list of SSH keys. Args: user: string, the name of the Linux user account. ssh_keys: list, the SSH key strings associated with the user. Raises: IOError, raised when there is an exception updating a file. OSError, raised when setti...
def connect(self, server, port=6667): """Connects to a given IRC server. After the connection is established, it calls the on_connect event handler. """ self.socket.connect((server, port)) self.lines = self._read_lines() for event_handler in list(self.on_connect): ...
Connects to a given IRC server. After the connection is established, it calls the on_connect event handler.
def serialize(self, data, fmt='%10.7E'): """ Serialize a collection of ground motion fields to XML. :param data: An iterable of "GMF set" objects. Each "GMF set" object should: * have an `investigation_time` attribute * have an `stochastic_event_...
Serialize a collection of ground motion fields to XML. :param data: An iterable of "GMF set" objects. Each "GMF set" object should: * have an `investigation_time` attribute * have an `stochastic_event_set_id` attribute * be iterable, yielding a seque...
def _read(cls, filepath_or_buffer, **kwargs): """Read csv file from local disk. Args: filepath_or_buffer: The filepath of the csv file. We only support local files for now. kwargs: Keyword arguments in pandas.read_csv """ # The ...
Read csv file from local disk. Args: filepath_or_buffer: The filepath of the csv file. We only support local files for now. kwargs: Keyword arguments in pandas.read_csv
def cross(environment, book, row, sheet_source, column_source, column_key): """ Returns a single value from a column from a different dataset, matching by the key. """ a = book.sheets[sheet_source] return environment.copy(a.get(**{column_key: row[column_key]})[column_source])
Returns a single value from a column from a different dataset, matching by the key.
def _read_columns_file(f): """Return the list of column queries read from the given JSON file. :param f: path to the file to read :type f: string :rtype: list of dicts """ try: columns = json.loads(open(f, 'r').read(), object_pairs_hook=collections.Ordered...
Return the list of column queries read from the given JSON file. :param f: path to the file to read :type f: string :rtype: list of dicts
def flatten_(structure): """Combine all leaves of a nested structure into a tuple. The nested structure can consist of any combination of tuples, lists, and dicts. Dictionary keys will be discarded but values will ordered by the sorting of the keys. Args: structure: Nested structure. Returns: Fla...
Combine all leaves of a nested structure into a tuple. The nested structure can consist of any combination of tuples, lists, and dicts. Dictionary keys will be discarded but values will ordered by the sorting of the keys. Args: structure: Nested structure. Returns: Flat tuple.
def is_os(name, version_id=None): '''Return True if OS name in /etc/lsb-release of host given by fabric param `-H` is the same as given by argument, False else. If arg version_id is not None only return True if it is the same as in /etc/lsb-release, too. Args: name: 'Debian GNU/Linux', 'Ub...
Return True if OS name in /etc/lsb-release of host given by fabric param `-H` is the same as given by argument, False else. If arg version_id is not None only return True if it is the same as in /etc/lsb-release, too. Args: name: 'Debian GNU/Linux', 'Ubuntu' version_id(None or str): No...
def set_chebyshev_approximators(self, deg_forward=50, deg_backwards=200): r'''Method to derive and set coefficients for chebyshev polynomial function approximation of the height-volume and volume-height relationship. A single set of chebyshev coefficients is used for t...
r'''Method to derive and set coefficients for chebyshev polynomial function approximation of the height-volume and volume-height relationship. A single set of chebyshev coefficients is used for the entire height- volume and volume-height relationships respectively. ...
def _connected(self, link_uri): """ This callback is called form the Crazyflie API when a Crazyflie has been connected and the TOCs have been downloaded.""" print('Connected to %s' % link_uri) # Print the param TOC p_toc = self._cf.param.toc.toc for group in sorted(p_toc...
This callback is called form the Crazyflie API when a Crazyflie has been connected and the TOCs have been downloaded.