positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def read_key_value_lines(path, separator=' ', default_value=''): """ Reads lines of a text file with two columns as key/value dictionary. Parameters: path (str): Path to the file. separator (str): Separator that is used to split key and value. default_value (str): If no value is giv...
Reads lines of a text file with two columns as key/value dictionary. Parameters: path (str): Path to the file. separator (str): Separator that is used to split key and value. default_value (str): If no value is given this value is used. Returns: dict: A dictionary with first co...
def get_object(self, queryset=None): """ Returns the object the view is displaying. Copied from SingleObjectMixin except that this allows us to lookup preview objects. """ schema = manager.get_schema() vid = None if self.request.GET.get('vid') and self.r...
Returns the object the view is displaying. Copied from SingleObjectMixin except that this allows us to lookup preview objects.
def present(self, path, timeout=0): """returns True if there is an entity at path""" ret, data = self.sendmess(MSG_PRESENCE, str2bytez(path), timeout=timeout) assert ret <= 0 and not data, (ret, data) if ret < 0: return False else: ...
returns True if there is an entity at path
def is_Type(tp): """Python version independent check if an object is a type. For Python 3.7 onwards(?) this is not equivalent to ``isinstance(tp, type)`` any more, as that call would return ``False`` for PEP 484 types. Tested with CPython 2.7, 3.5, 3.6, 3.7 and Jython 2.7.1. """ if isinstanc...
Python version independent check if an object is a type. For Python 3.7 onwards(?) this is not equivalent to ``isinstance(tp, type)`` any more, as that call would return ``False`` for PEP 484 types. Tested with CPython 2.7, 3.5, 3.6, 3.7 and Jython 2.7.1.
def _analyze_function(self): """ Go over the variable information in variable manager for this function, and return all uninitialized register/stack variables. :return: """ if not self._function.is_simprocedure \ and not self._function.is_plt \ ...
Go over the variable information in variable manager for this function, and return all uninitialized register/stack variables. :return:
def entities(self, name_id): """ Returns all the entities of assertions for a subject, disregarding whether the assertion still is valid or not. :param name_id: The subject identifier, a NameID instance :return: A possibly empty list of entity identifiers """ cni = code(...
Returns all the entities of assertions for a subject, disregarding whether the assertion still is valid or not. :param name_id: The subject identifier, a NameID instance :return: A possibly empty list of entity identifiers
def index_at_event(self, event): """Get the index under the position of the given MouseEvent This implementation takes the indentation into account. :param event: the mouse event :type event: :class:`QtGui.QMouseEvent` :returns: the index :rtype: :class:`QtCore.QModelIn...
Get the index under the position of the given MouseEvent This implementation takes the indentation into account. :param event: the mouse event :type event: :class:`QtGui.QMouseEvent` :returns: the index :rtype: :class:`QtCore.QModelIndex` :raises: None
def explain_prediction_sklearn(estimator, doc, vec=None, top=None, top_targets=None, target_names=None, targets=None, feature_names=No...
Return an explanation of a scikit-learn estimator
def _is_really_comment(tokens, index): """Return true if the token at index is really a comment.""" if tokens[index].type == TokenType.Comment: return True # Really a comment in disguise! try: if tokens[index].content.lstrip()[0] == "#": return True except IndexError: ...
Return true if the token at index is really a comment.
def variance_K(K, verbose=False): """estimate the variance explained by K""" c = SP.sum((SP.eye(len(K)) - (1.0 / len(K)) * SP.ones(K.shape)) * SP.array(K)) scalar = (len(K) - 1) / c return 1.0/scalar
estimate the variance explained by K
def set_image(self, user, image_path): """Sets a custom image for the game. `image_path` should refer to an image file on disk""" _, ext = os.path.splitext(image_path) shutil.copy(image_path, self._custom_image_path(user, ext))
Sets a custom image for the game. `image_path` should refer to an image file on disk
def _aggregate_config_values(config_values: typing.List[ConfigValue]) -> dict: """ Returns a (sorted) :param config_values: :type config_values: :return: :rtype: """ _keys: defaultdict = _nested_default_dict() _sorted_values = sorted(config_values, key=lambda x: x.name) for valu...
Returns a (sorted) :param config_values: :type config_values: :return: :rtype:
def match_filter(template_names, template_list, st, threshold, threshold_type, trig_int, plotvar, plotdir='.', xcorr_func=None, concurrency=None, cores=None, debug=0, plot_format='png', output_cat=False, output_event=True, extract_detections=False, ...
Main matched-filter detection function. Over-arching code to run the correlations of given templates with a day of seismic data and output the detections based on a given threshold. For a functional example see the tutorials. :type template_names: list :param template_names: List of templa...
def is_valid_coll(self, coll): """Determines if the collection name for a request is valid (exists) :param str coll: The name of the collection to check :return: True if the collection is valid, false otherwise :rtype: bool """ #if coll == self.all_coll: # ret...
Determines if the collection name for a request is valid (exists) :param str coll: The name of the collection to check :return: True if the collection is valid, false otherwise :rtype: bool
def extract_single_dist_for_current_platform(self, reqs, dist_key): """Resolve a specific distribution from a set of requirements matching the current platform. :param list reqs: A list of :class:`PythonRequirement` to resolve. :param str dist_key: The value of `distribution.key` to match for a `distributi...
Resolve a specific distribution from a set of requirements matching the current platform. :param list reqs: A list of :class:`PythonRequirement` to resolve. :param str dist_key: The value of `distribution.key` to match for a `distribution` from the resolved requirements. :return: T...
def bind(self, source=None, destination=None, node=None, edge_title=None, edge_label=None, edge_color=None, edge_weight=None, point_title=None, point_label=None, point_color=None, point_size=None): """Relate data attributes to graph structure and visual representation. To faci...
Relate data attributes to graph structure and visual representation. To facilitate reuse and replayable notebooks, the binding call is chainable. Invocation does not effect the old binding: it instead returns a new Plotter instance with the new bindings added to the existing ones. Both the old and new bindings...
def _qrd_solve_full(a, b, ddiag, dtype=np.float): """Solve the equation A^T x = B, D x = 0. Parameters: a - an n-by-m array, m >= n b - an m-vector ddiag - an n-vector giving the diagonal of D. (The rest of D is 0.) Returns: x - n-vector solving the equation. s - the n-by-n supplementary matrix s. p...
Solve the equation A^T x = B, D x = 0. Parameters: a - an n-by-m array, m >= n b - an m-vector ddiag - an n-vector giving the diagonal of D. (The rest of D is 0.) Returns: x - n-vector solving the equation. s - the n-by-n supplementary matrix s. pmut - n-element permutation vector defining the permutati...
def do_unique(environment, value, case_sensitive=False, attribute=None): """Returns a list of unique items from the the given iterable. .. sourcecode:: jinja {{ ['foo', 'bar', 'foobar', 'FooBar']|unique }} -> ['foo', 'bar', 'foobar'] The unique items are yielded in the same order as t...
Returns a list of unique items from the the given iterable. .. sourcecode:: jinja {{ ['foo', 'bar', 'foobar', 'FooBar']|unique }} -> ['foo', 'bar', 'foobar'] The unique items are yielded in the same order as their first occurrence in the iterable passed to the filter. :param case...
def _resolve_sources(self, sources, tables, stage=None, predicate=None): """ Determine what sources to run from an input of sources and tables :param sources: A collection of source objects, source names, or source vids :param tables: A collection of table names :param stage: I...
Determine what sources to run from an input of sources and tables :param sources: A collection of source objects, source names, or source vids :param tables: A collection of table names :param stage: If not None, select only sources from this stage :param predicate: If not none, a call...
def system_listMethods(self): """system.listMethods() => ['add', 'subtract', 'multiple'] Returns a list of the methods supported by the server.""" methods = self.funcs.keys() if self.instance is not None: # Instance can implement _listMethod to return a list of ...
system.listMethods() => ['add', 'subtract', 'multiple'] Returns a list of the methods supported by the server.
def get_family_admin_session(self): """Gets the ``OsidSession`` associated with the family administrative service. return: (osid.relationship.FamilyAdminSession) - a ``FamilyAdminSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``sup...
Gets the ``OsidSession`` associated with the family administrative service. return: (osid.relationship.FamilyAdminSession) - a ``FamilyAdminSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_family_admin()`` is ``false`` *co...
def table(contents, heading=True, colw=None, cwunit='dxa', tblw=0, twunit='auto', borders={}, celstyle=None): """ Return a table element based on specified parameters @param list contents: A list of lists describing contents. Every item in the list can be a string or a v...
Return a table element based on specified parameters @param list contents: A list of lists describing contents. Every item in the list can be a string or a valid XML element itself. It can also be a list. In that case all the listed elem...
def cookiejar(name='session'): """ Ready the CookieJar, loading a saved session if available @rtype: cookielib.LWPCookieJar """ log = logging.getLogger('ipsv.common.cookiejar') spath = os.path.join(config().get('Paths', 'Data'), '{n}.txt'.format(n=name)) cj = cookielib.LWPCookieJar(spath) ...
Ready the CookieJar, loading a saved session if available @rtype: cookielib.LWPCookieJar
def recv(files, dest): ''' Used with salt-cp, pass the files dict, and the destination. This function receives small fast copy files from the master via salt-cp. It does not work via the CLI. ''' ret = {} for path, data in six.iteritems(files): if os.path.basename(path) == os.path.b...
Used with salt-cp, pass the files dict, and the destination. This function receives small fast copy files from the master via salt-cp. It does not work via the CLI.
def default_format(self): """ Returns full name (first and last) if name is available. If not, returns username if available. If not available too, returns the user id as a string. """ user = self.user if user.first_name is not None: return self.full_n...
Returns full name (first and last) if name is available. If not, returns username if available. If not available too, returns the user id as a string.
def cons(f, mindepth): """ Makes a list of lists of reads at each site """ C = ClustFile(f) for data in C: names, seqs, nreps = zip(*data) total_nreps = sum(nreps) # Depth filter if total_nreps < mindepth: continue S = [] for name, seq, nr...
Makes a list of lists of reads at each site
def camelResource(obj): """Some sources from apis return lowerCased where as describe calls always return TitleCase, this function turns the former to the later """ if not isinstance(obj, dict): return obj for k in list(obj.keys()): v = obj.pop(k) obj["%s%s" % (k[0].upper(),...
Some sources from apis return lowerCased where as describe calls always return TitleCase, this function turns the former to the later
def explode_map(self, map_): """ Much faster version of ``pyny.Space.explode()`` method for previously locked ``pyny.Space``. :param map_: the points, and the same order, that appear at ``pyny.Space.get_map()``. There is no need for the index if ...
Much faster version of ``pyny.Space.explode()`` method for previously locked ``pyny.Space``. :param map_: the points, and the same order, that appear at ``pyny.Space.get_map()``. There is no need for the index if locked. :type map_: ndarray (shape=(N, 3)...
def to_cloudformation(self, **kwargs): """Returns the Lambda Permission resource allowing S3 to invoke the function this event source triggers. :param dict kwargs: S3 bucket resource :returns: a list of vanilla CloudFormation Resources, to which this S3 event expands :rtype: list ...
Returns the Lambda Permission resource allowing S3 to invoke the function this event source triggers. :param dict kwargs: S3 bucket resource :returns: a list of vanilla CloudFormation Resources, to which this S3 event expands :rtype: list
def clark(self, databasepath): """ Download and set-up the CLARK database using the set_targets.sh script. Use defaults of bacteria for database type, and species for taxonomic level :param databasepath: path to use to save the database """ if self.clarkpath: ...
Download and set-up the CLARK database using the set_targets.sh script. Use defaults of bacteria for database type, and species for taxonomic level :param databasepath: path to use to save the database
def get_serializer(self, *args, **kwargs): """Get an instance of the child serializer.""" init_args = { k: v for k, v in six.iteritems(self.kwargs) if k in self.SERIALIZER_KWARGS } kwargs = self._inherit_parent_kwargs(kwargs) init_args.update(kwargs) ...
Get an instance of the child serializer.
def print_meter_record(file_path, rows=5): """ Output readings for specified number of rows to console """ m = nr.read_nem_file(file_path) print('Header:', m.header) print('Transactions:', m.transactions) for nmi in m.readings: for channel in m.readings[nmi]: print(nmi, 'Channel'...
Output readings for specified number of rows to console
def taskRunning(self, *args, **kwargs): """ Task Running Messages Whenever a task is claimed by a worker, a run is started on the worker, and a message is posted on this exchange. This exchange outputs: ``v1/task-running-message.json#``This exchange takes the following keys: ...
Task Running Messages Whenever a task is claimed by a worker, a run is started on the worker, and a message is posted on this exchange. This exchange outputs: ``v1/task-running-message.json#``This exchange takes the following keys: * routingKeyKind: Identifier for the routing-key kin...
def Presentation(pptx=None): """ Return a |Presentation| object loaded from *pptx*, where *pptx* can be either a path to a ``.pptx`` file (a string) or a file-like object. If *pptx* is missing or ``None``, the built-in default presentation "template" is loaded. """ if pptx is None: p...
Return a |Presentation| object loaded from *pptx*, where *pptx* can be either a path to a ``.pptx`` file (a string) or a file-like object. If *pptx* is missing or ``None``, the built-in default presentation "template" is loaded.
def generate(oracle, seq_len, p=0.5, k=1, LRS=0, weight=None): """ Generate a sequence based on traversing an oracle. :param oracle: a indexed vmo object :param seq_len: the length of the returned improvisation sequence :param p: a float between (0,1) representing the probability using the forward link...
Generate a sequence based on traversing an oracle. :param oracle: a indexed vmo object :param seq_len: the length of the returned improvisation sequence :param p: a float between (0,1) representing the probability using the forward links. :param k: the starting improvisation time step in oracle :pa...
def remove_builder(cls, builder_name: str): """Remove a registered builder `builder_name`. No reason to use this except for tests. """ cls.builders.pop(builder_name, None) for hook_spec in cls.hooks.values(): hook_spec.pop(builder_name, None)
Remove a registered builder `builder_name`. No reason to use this except for tests.
def validlines(self): """Return all lines within which Prosodic understood all words.""" return [ln for ln in self.lines() if (not ln.isBroken() and not ln.ignoreMe)]
Return all lines within which Prosodic understood all words.
def _check_file_is_under_workingdir(filename, wdir): """ Raise error if input is being staged to a location not underneath the working dir """ p = filename if not os.path.isabs(p): p = os.path.join(wdir, p) targetpath = os.path.realpath(p) wdir = os.path.realp...
Raise error if input is being staged to a location not underneath the working dir
def print_duplicate_anchor_information(duplicate_tags): """ Prints information about duplicate AnchorHub tags found during collection. :param duplicate_tags: Dictionary mapping string file path keys to a list of tuples. The tuples contain the following information, in order: 1. The string ...
Prints information about duplicate AnchorHub tags found during collection. :param duplicate_tags: Dictionary mapping string file path keys to a list of tuples. The tuples contain the following information, in order: 1. The string AnchorHub tag that was repeated 2. The line in the file that...
def remove_tx_rich(self): """ Remove any `c:tx[c:rich]` child, or do nothing if not present. """ matches = self.xpath('c:tx[c:rich]') if not matches: return tx = matches[0] self.remove(tx)
Remove any `c:tx[c:rich]` child, or do nothing if not present.
def create_bag(dir_bag): """ Create a Bag out of given files. :param str dir_bag: Directory that contains csv, jsonld, and changelog files. :return obj: Bag """ logger_bagit.info("enter create_bag") # if not dir_bag: # dir_bag = os.getcwd() try: bag = bagit.make_bag(dir_b...
Create a Bag out of given files. :param str dir_bag: Directory that contains csv, jsonld, and changelog files. :return obj: Bag
def clone(self, **kwargs): """ Clone Task instance. Reset network_try_count, increase task_try_count. Reset priority attribute if it was not set explicitly. """ # First, create exact copy of the current Task object attr_copy = self.__dict__.copy() if att...
Clone Task instance. Reset network_try_count, increase task_try_count. Reset priority attribute if it was not set explicitly.
def write_frames(self, frames_out): """Write multiple pamqp frames from the current channel. :param list frames_out: A list of pamqp frames. :return: """ self.check_for_errors() self._connection.write_frames(self.channel_id, frames_out)
Write multiple pamqp frames from the current channel. :param list frames_out: A list of pamqp frames. :return:
def get_urls(htmlDoc, limit=200): '''takes in html document as string, returns links to dots''' soup = BeautifulSoup( htmlDoc ) anchors = soup.findAll( 'a' ) urls = {} counter = 0 for i,v in enumerate( anchors ): href = anchors[i].get( 'href' ) if ('dots' in href and counter <...
takes in html document as string, returns links to dots
def exponential_moving_average(data, period): """ Exponential Moving Average. Formula: p0 + (1 - w) * p1 + (1 - w)^2 * p2 + (1 + w)^3 * p3 +... / 1 + (1 - w) + (1 - w)^2 + (1 - w)^3 +... where: w = 2 / (N + 1) """ catch_errors.check_for_period_error(data, period) emas...
Exponential Moving Average. Formula: p0 + (1 - w) * p1 + (1 - w)^2 * p2 + (1 + w)^3 * p3 +... / 1 + (1 - w) + (1 - w)^2 + (1 - w)^3 +... where: w = 2 / (N + 1)
def sendSync(self, query, *parameters, **options): '''Performs a synchronous query against a q service and returns parsed data. In typical use case, `query` is the name of the function to call and `parameters` are its parameters. When `parameters` list is empty, the q...
Performs a synchronous query against a q service and returns parsed data. In typical use case, `query` is the name of the function to call and `parameters` are its parameters. When `parameters` list is empty, the query can be an arbitrary q expression (e.g. ``0 +/ til 100``)....
def construct(self, max_message_size, remote_name=None, python_path=None, debug=False, connect_timeout=None, profiling=False, unidirectional=False, old_router=None, **kwargs): """Get the named context running on the local machine, creating it if it does not exist.""" ...
Get the named context running on the local machine, creating it if it does not exist.
def fade_out(self, duration=3): """Turns off the light by gradually fading it out. The optional `duration` parameter allows for control of the fade out duration (in seconds)""" super(RgbLight, self).fade_out(duration) self.off()
Turns off the light by gradually fading it out. The optional `duration` parameter allows for control of the fade out duration (in seconds)
async def make_default_options_response(self) -> Response: """This is the default route function for OPTIONS requests.""" methods = _request_ctx_stack.top.url_adapter.allowed_methods() return self.response_class('', headers={'Allow': ', '.join(methods)})
This is the default route function for OPTIONS requests.
def launch(self, timeout=2): """ Hierapp instance, with environment dependencies: - can be launched within short timeout - auto-destroys shortly """ self.start_time = time.time() self.end_time = time.time() instance = self.app.launch(environment=self.env) ...
Hierapp instance, with environment dependencies: - can be launched within short timeout - auto-destroys shortly
def find_value_type(global_ns, value_type_str): """implementation details""" if not value_type_str.startswith('::'): value_type_str = '::' + value_type_str found = global_ns.decls( name=value_type_str, function=lambda decl: not isinstance(decl, calldef.calldef...
implementation details
def unsubscribe(self, topic): """Unsubscribe to some topic.""" if self.sock == NC.INVALID_SOCKET: return NC.ERR_NO_CONN self.logger.info("UNSUBSCRIBE: %s", topic) return self.send_unsubscribe(False, [utf8encode(topic)])
Unsubscribe to some topic.
def set(self, key, samples, sampling_rate): """ Set the samples and sampling-rate for the given key. Existing data will be overwritten. The samples have to have ``np.float32`` datatype and values in the range of -1.0 and 1.0. Args: key (str): A key to store t...
Set the samples and sampling-rate for the given key. Existing data will be overwritten. The samples have to have ``np.float32`` datatype and values in the range of -1.0 and 1.0. Args: key (str): A key to store the data for. samples (numpy.ndarray): 1-D array of a...
def set_chime_volume(self, volume): """ :param volume: one of [low, medium, high] """ values = { "desired_state": { "chime_volume": volume } } response = self.api_interface.set_device_state(self, values) self._upda...
:param volume: one of [low, medium, high]
def merge_vertices(self, digits=None): """ Merges vertices which are identical and replace references. Parameters -------------- digits : None, or int How many digits to consider when merging vertices Alters ----------- self.entities : entity.p...
Merges vertices which are identical and replace references. Parameters -------------- digits : None, or int How many digits to consider when merging vertices Alters ----------- self.entities : entity.points re- referenced self.vertices : duplicates rem...
def windowed_statistic(pos, values, statistic, size=None, start=None, stop=None, step=None, windows=None, fill=np.nan): """Calculate a statistic from items in windows over a single chromosome/contig. Parameters ---------- pos : array_like, int, shape (n_items,) The i...
Calculate a statistic from items in windows over a single chromosome/contig. Parameters ---------- pos : array_like, int, shape (n_items,) The item positions in ascending order, using 1-based coordinates.. values : array_like, int, shape (n_items,) The values to summarise. May also...
def iter(self, **kwargs): """see :py:meth:`Propagator.iter() <beyond.propagators.base.Propagator.iter>` """ if self.propagator.orbit is not self: self.propagator.orbit = self return self.propagator.iter(**kwargs)
see :py:meth:`Propagator.iter() <beyond.propagators.base.Propagator.iter>`
def query_str_2_dict(query_str): """ 将查询字符串,转换成字典 a=123&b=456 {'a': '123', 'b': '456'} :param query_str: :return: """ if query_str: query_list = query_str.split('&') query_dict = {} for t in query_list: x = t.split('=') query_dict[x[0]] = x...
将查询字符串,转换成字典 a=123&b=456 {'a': '123', 'b': '456'} :param query_str: :return:
def resolve_asset_dependency(self): """ Converts every file dependency into absolute path so when we merge we don't break things. """ for node in self.asset.findall("./*[@file]"): file = node.get("file") abs_path = os.path.abspath(self.folder) abs_pat...
Converts every file dependency into absolute path so when we merge we don't break things.
def setup(self): """Continue the run process blocking on MasterControlProgram.run""" # If the app was invoked to specified to prepend the path, do so now if self.args.prepend_path: self._prepend_python_path(self.args.prepend_path)
Continue the run process blocking on MasterControlProgram.run
def output_key_name(self, input_key: str, output_hist: Hist, projection_name: str, **kwargs) -> str: """ Returns the key under which the output object should be stored. Note: This function is just a basic placeholder which returns the projection name and likely should be overrid...
Returns the key under which the output object should be stored. Note: This function is just a basic placeholder which returns the projection name and likely should be overridden. Args: input_key: Key of the input hist in the input dict output_hist: The o...
def validate(self, data=None, only=None, exclude=None): """ Validate the data for all fields and return whether the validation was successful. This method also retains the validated data in ``self.data`` so that it can be accessed later. This is usually the method you want to call after...
Validate the data for all fields and return whether the validation was successful. This method also retains the validated data in ``self.data`` so that it can be accessed later. This is usually the method you want to call after creating the validator instance. :param data: Dictionary of data t...
def spawn_container(addr, env_cls=Environment, mgr_cls=EnvManager, set_seed=True, *args, **kwargs): """Spawn a new environment in a given address as a coroutine. Arguments and keyword arguments are passed down to the created environment at initialization time. If `setproctitle <htt...
Spawn a new environment in a given address as a coroutine. Arguments and keyword arguments are passed down to the created environment at initialization time. If `setproctitle <https://pypi.python.org/pypi/setproctitle>`_ is installed, this function renames the title of the process to start with 'c...
async def create_link_secret(self, label: str) -> None: """ Create link secret (a.k.a. master secret) used in proofs by HolderProver, if the current link secret does not already correspond to the input link secret label. Raise WalletState if wallet is closed, or any other IndyError caus...
Create link secret (a.k.a. master secret) used in proofs by HolderProver, if the current link secret does not already correspond to the input link secret label. Raise WalletState if wallet is closed, or any other IndyError causing failure to set link secret in wallet. :param label: lab...
def export_agg_losses(ekey, dstore): """ :param ekey: export key, i.e. a pair (datastore key, fmt) :param dstore: datastore object """ dskey = ekey[0] oq = dstore['oqparam'] dt = oq.loss_dt() name, value, tags = _get_data(dstore, dskey, oq.hazard_stats().items()) writer = writers.Csv...
:param ekey: export key, i.e. a pair (datastore key, fmt) :param dstore: datastore object
def _run_command(command, targets, options): # type: (str, List[str], List[str]) -> bool """Runs `command` + `targets` + `options` in a subprocess and returns a boolean determined by the process return code. >>> result = run_command('pylint', ['foo.py', 'some_module'], ['-E']) >>> result Tr...
Runs `command` + `targets` + `options` in a subprocess and returns a boolean determined by the process return code. >>> result = run_command('pylint', ['foo.py', 'some_module'], ['-E']) >>> result True :param command: str :param targets: List[str] :param options: List[str] :return:...
def validate_attr(resource_attr_id, scenario_id, template_id=None): """ Check that a resource attribute satisfies the requirements of all the types of the resource. """ rs = db.DBSession.query(ResourceScenario).\ filter(ResourceScenario.resource_attr_id==resource_attr...
Check that a resource attribute satisfies the requirements of all the types of the resource.
def stop_watch(self): """ Stops the periodic watch greenlet, thus the pool itself """ if self.greenlet_watch: self.greenlet_watch.kill(block=False) self.greenlet_watch = None
Stops the periodic watch greenlet, thus the pool itself
def partition_all(n, iterable): """Partition a list into equally sized pieces, including last smaller parts http://stackoverflow.com/questions/5129102/python-equivalent-to-clojures-partition-all """ it = iter(iterable) while True: chunk = list(itertools.islice(it, n)) if not chunk: ...
Partition a list into equally sized pieces, including last smaller parts http://stackoverflow.com/questions/5129102/python-equivalent-to-clojures-partition-all
def updateModel(self, X_all, Y_all, X_new, Y_new): """ Updates the model with new observations. """ if self.model is None: self._create_model(X_all, Y_all) else: self.model.set_XY(X_all, Y_all) # WARNING: Even if self.max_iters=0, the hyperparamet...
Updates the model with new observations.
def triangle(self, params=None, **kwargs): """ Makes a nifty corner plot. """ if params is None: params = ['mass_A', 'mass_B', 'mass_C', 'age', 'feh', 'distance', 'AV'] super(TripleStarModel, self).triangle(params=params, **kwargs)
Makes a nifty corner plot.
def spectral_clustering(geom, K, eigen_solver = 'dense', random_state = None, solver_kwds = None, renormalize = True, stabalize = True, additional_vectors = 0): """ Spectral clustering for find K clusters by using the eigenvectors of a matrix which is derived from a set of similari...
Spectral clustering for find K clusters by using the eigenvectors of a matrix which is derived from a set of similarities S. Parameters ----------- S: array-like,shape(n_sample,n_sample) similarity matrix K: integer number of K clusters eigen_solver : {'auto', 'dense', 'arpack...
def parse_html_list(dictionary, prefix=''): """ Used to suport list values in HTML forms. Supports lists of primitives and/or dictionaries. * List of primitives. { '[0]': 'abc', '[1]': 'def', '[2]': 'hij' } --> [ 'abc', 'def', 'hij' ...
Used to suport list values in HTML forms. Supports lists of primitives and/or dictionaries. * List of primitives. { '[0]': 'abc', '[1]': 'def', '[2]': 'hij' } --> [ 'abc', 'def', 'hij' ] * List of dictionaries. { '[0]foo...
def set_distance_units(value=np.NaN, from_units='mm', to_units='cm'): """convert distance into new units Parameters: =========== value: float. value to convert from_units: string. Must be 'mm', 'cm' or 'm' to_units: string. must be 'mm','cm' or 'm' Returns: ======== convert...
convert distance into new units Parameters: =========== value: float. value to convert from_units: string. Must be 'mm', 'cm' or 'm' to_units: string. must be 'mm','cm' or 'm' Returns: ======== converted value Raises: ======= ValueError if from_units is not a v...
def get_email_receivers_of_recurring_per_page(self, recurring_id, per_page=1000, page=1): """ Get email receivers of recurring per page :param recurring_id: the recurring id :param per_page: How many objects per page. Default: 1000 :param page: Which page. Default: 1 :re...
Get email receivers of recurring per page :param recurring_id: the recurring id :param per_page: How many objects per page. Default: 1000 :param page: Which page. Default: 1 :return: list
async def viewreaction(self, ctx, *, reactor : str): """Views a specific reaction""" data = self.config.get(ctx.message.server.id, {}) keyword = data.get(reactor, {}) if not keyword: await self.bot.responses.failure(message="Reaction '{}' was not found.".format(reactor)) ...
Views a specific reaction
def _process_disease_models(self, limit): """ Here we make associations between a disease and the supplied "model". In this case it's an allele. FIXME consider changing this... are alleles really models? Perhaps map these alleles into actual animals/strains or genotypes? ...
Here we make associations between a disease and the supplied "model". In this case it's an allele. FIXME consider changing this... are alleles really models? Perhaps map these alleles into actual animals/strains or genotypes? :param limit: :return:
def is_writable(path): """Check if path has write access""" try: testfile = tempfile.TemporaryFile(dir=path) testfile.close() except OSError as e: if e.errno == errno.EACCES: # 13 return False return True
Check if path has write access
def is_name_owner( self, name, sender_script_pubkey ): """ Given the fully-qualified name and a sender's script pubkey, determine if the sender owns the name. The name must exist and not be revoked or expired at the current block. """ if not self.is_name_register...
Given the fully-qualified name and a sender's script pubkey, determine if the sender owns the name. The name must exist and not be revoked or expired at the current block.
def predict(self, u=0): """ Predict next position. Parameters ---------- u : ndarray Optional control vector. If non-zero, it is multiplied by `B` to create the control input into the system. """ # x = Fx + Bu self.x = dot(self.F,...
Predict next position. Parameters ---------- u : ndarray Optional control vector. If non-zero, it is multiplied by `B` to create the control input into the system.
def check_bam(bam, o): """ Check reads in BAM file for read type and lengths. :param str bam: BAM file path. :param int o: Number of reads to look at for estimation. """ try: p = sp.Popen(['samtools', 'view', bam], stdout=sp.PIPE) # Count paired alignments paired = 0 ...
Check reads in BAM file for read type and lengths. :param str bam: BAM file path. :param int o: Number of reads to look at for estimation.
def offset(self): """int: offset of the key within the Windows Registry file or None.""" if not self._registry_key and self._registry: self._GetKeyFromRegistry() if not self._registry_key: return None return self._registry_key.offset
int: offset of the key within the Windows Registry file or None.
def drop(self): """Drop the table from the database. Deletes both the schema and all the contents within it. """ with self.db.lock: if self.exists: self._threading_warn() self.table.drop(self.db.executable, checkfirst=True) sel...
Drop the table from the database. Deletes both the schema and all the contents within it.
def on(self, left_speed, right_speed): """ Start rotating the motors according to ``left_speed`` and ``right_speed`` forever. Speeds can be percentages or any SpeedValue implementation. """ (left_speed_native_units, right_speed_native_units) = self._unpack_speeds_to_native_units(...
Start rotating the motors according to ``left_speed`` and ``right_speed`` forever. Speeds can be percentages or any SpeedValue implementation.
def _make_intersection(edge_info, all_edge_nodes): """Convert a description of edges into a curved polygon. .. note:: This is a helper used only by :meth:`.Surface.intersect`. Args: edge_info (Tuple[Tuple[int, float, float], ...]): Information describing each edge in the curved...
Convert a description of edges into a curved polygon. .. note:: This is a helper used only by :meth:`.Surface.intersect`. Args: edge_info (Tuple[Tuple[int, float, float], ...]): Information describing each edge in the curved polygon by indicating which surface / edge on...
def install_package(self, path, recursive=False): # type: (str, bool) -> tuple """ Installs all the modules found in the given package (directory). It is a utility method working like :meth:`~pelix.framework.BundleContext.install_visiting`, with a visitor accepting every ...
Installs all the modules found in the given package (directory). It is a utility method working like :meth:`~pelix.framework.BundleContext.install_visiting`, with a visitor accepting every module found. :param path: Path of the package (folder) :param recursive: If True, install...
def value(self): """Returns the positive value to subtract from the total.""" originalPrice = self.lineItem.totalPrice if self.flatRate == 0: return originalPrice * self.percent return self.flatRate
Returns the positive value to subtract from the total.
def parse_url(self): """ Parses a URL of the form: - ws://host[:port][path] - wss://host[:port][path] - ws+unix:///path/to/my.socket """ self.scheme = None self.resource = None self.host = None self.port = None if self.url is None: ...
Parses a URL of the form: - ws://host[:port][path] - wss://host[:port][path] - ws+unix:///path/to/my.socket
def _get_length_sequences_where(x): """ This method calculates the length of all sub-sequences where the array x is either True or 1. Examples -------- >>> x = [0,1,0,0,1,1,1,0,0,1,0,1,1] >>> _get_length_sequences_where(x) >>> [1, 3, 1, 2] >>> x = [0,True,0,0,True,True,True,0,0,True,0,...
This method calculates the length of all sub-sequences where the array x is either True or 1. Examples -------- >>> x = [0,1,0,0,1,1,1,0,0,1,0,1,1] >>> _get_length_sequences_where(x) >>> [1, 3, 1, 2] >>> x = [0,True,0,0,True,True,True,0,0,True,0,True,True] >>> _get_length_sequences_where(x...
def _teardown_redundancy_router_gw_connectivity(self, context, router, router_db, plugging_driver): """To be called in update_router() if the router gateway is to change BEFORE router has been updated...
To be called in update_router() if the router gateway is to change BEFORE router has been updated in DB .
def cred_def_id(issuer_did: str, schema_seq_no: int, protocol: Protocol = None) -> str: """ Return credential definition identifier for input issuer DID and schema sequence number. Implementation passes to NodePool Protocol. :param issuer_did: DID of credential definition issuer :param schema_seq_...
Return credential definition identifier for input issuer DID and schema sequence number. Implementation passes to NodePool Protocol. :param issuer_did: DID of credential definition issuer :param schema_seq_no: schema sequence number :param protocol: indy protocol version :return: credential defini...
def install_os(name, **kwargs): ''' Installs the given image on the device. After the installation is complete the device is rebooted, if reboot=True is given as a keyworded argument. .. code-block:: yaml salt://images/junos_image.tgz: junos: - install_os ...
Installs the given image on the device. After the installation is complete the device is rebooted, if reboot=True is given as a keyworded argument. .. code-block:: yaml salt://images/junos_image.tgz: junos: - install_os - timeout: 100 -...
def metadata_and_language_from_option_line(self, line): """Parse code options on the given line. When a start of a code cell is found, self.metadata is set to a dictionary.""" if self.start_code_re.match(line): self.language, self.metadata = self.options_to_metadata(line[line.find('%...
Parse code options on the given line. When a start of a code cell is found, self.metadata is set to a dictionary.
def get_onsets(text, vowels="aeiou", threshold=0.0002): """ Source: Resonances in Middle High German: New Methodologies in Prosody, 2017, C. L. Hench :param text: str list: text to be analysed :param vowels: str: valid vowels constituting the syllable :param threshold: minimum frequency count...
Source: Resonances in Middle High German: New Methodologies in Prosody, 2017, C. L. Hench :param text: str list: text to be analysed :param vowels: str: valid vowels constituting the syllable :param threshold: minimum frequency count for valid onset, C. Hench noted that the algorithm produces the...
def concordance_index(event_times, predicted_scores, event_observed=None): """ Calculates the concordance index (C-index) between two series of event times. The first is the real survival times from the experimental data, and the other is the predicted survival times from a model of some kind. ...
Calculates the concordance index (C-index) between two series of event times. The first is the real survival times from the experimental data, and the other is the predicted survival times from a model of some kind. The c-index is the average of how often a model says X is greater than Y when, in the o...
def _merge_out_from_infiles(in_files): """Generate output merged file name from set of input files. Handles non-shared filesystems where we don't know output path when setting up split parts. """ fname = os.path.commonprefix([os.path.basename(f) for f in in_files]) while fname.endswith(("-", "_...
Generate output merged file name from set of input files. Handles non-shared filesystems where we don't know output path when setting up split parts.
def complete(self, default_output=None): """Marks this asynchronous Pipeline as complete. Args: default_output: What value the 'default' output slot should be assigned. Raises: UnexpectedPipelineError if the slot no longer exists or this method was called for a pipeline that is not async...
Marks this asynchronous Pipeline as complete. Args: default_output: What value the 'default' output slot should be assigned. Raises: UnexpectedPipelineError if the slot no longer exists or this method was called for a pipeline that is not async.
def from_csv(cls, path:PathOrStr, folder:PathOrStr=None, label_delim:str=None, csv_labels:PathOrStr='labels.csv', valid_pct:float=0.2, fn_col:int=0, label_col:int=1, suffix:str='', delimiter:str=None, header:Optional[Union[int,str]]='infer', **kwargs:Any)->'ImageDataBunch': "Cr...
Create from a csv file in `path/csv_labels`.
def _get_proxy_info(self, _=None): """Generate a ProxyInfo class from a connected SSH transport Args: _ (None): Ignored. This is just here as the ProxyInfo spec requires it. Returns: SSHTunnelProxyInfo: A ProxyInfo with an active socket tunneled through SSH "...
Generate a ProxyInfo class from a connected SSH transport Args: _ (None): Ignored. This is just here as the ProxyInfo spec requires it. Returns: SSHTunnelProxyInfo: A ProxyInfo with an active socket tunneled through SSH
def run_cell(self, cell, cell_index=0): """ Run cell with caching :param cell: cell to run :param cell_index: cell index (optional) :return: """ hash = self.cell_hash(cell, cell_index) fname_session = '/tmp/pynb-cache-{}-session.dill'.format(hash) ...
Run cell with caching :param cell: cell to run :param cell_index: cell index (optional) :return: