code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def obj_res(data, fail_on=['type', 'obj', 'res']): """ Given some CLI input data, Returns the following and their types: obj - the role grantee res - the resource that the role applies to """ errors = [] if not data.get('type', None) and 'type' in fail_on:...
Given some CLI input data, Returns the following and their types: obj - the role grantee res - the resource that the role applies to
def _sentence_context(match, language='latin', case_insensitive=True): """Take one incoming regex match object and return the sentence in which the match occurs. :rtype : str :param match: regex.match :param language: str """ language_punct = {'greek': r'\.|;', 'lati...
Take one incoming regex match object and return the sentence in which the match occurs. :rtype : str :param match: regex.match :param language: str
def _graphite_url(self, query, raw_data=False, graphite_url=None): """Build Graphite URL.""" query = escape.url_escape(query) graphite_url = graphite_url or self.reactor.options.get('public_graphite_url') url = "{base}/render/?target={query}&from=-{from_time}&until=-{until}".format( ...
Build Graphite URL.
def create_graph_rules(address_mapper): """Creates tasks used to parse Structs from BUILD files. :param address_mapper_key: The subject key for an AddressMapper instance. :param symbol_table: A SymbolTable instance to provide symbols for Address lookups. """ @rule(AddressMapper, []) def address_mapper_sin...
Creates tasks used to parse Structs from BUILD files. :param address_mapper_key: The subject key for an AddressMapper instance. :param symbol_table: A SymbolTable instance to provide symbols for Address lookups.
def _repack_options(options): ''' Repack the options data ''' return dict( [ (six.text_type(x), _normalize(y)) for x, y in six.iteritems(salt.utils.data.repack_dictlist(options)) ] )
Repack the options data
def calculate_leapdays(init_date, final_date): """Currently unsupported, it only works for differences in years.""" leap_days = (final_date.year - 1) // 4 - (init_date.year - 1) // 4 leap_days -= (final_date.year - 1) // 100 - (init_date.year - 1) // 100 leap_days += (final_date.year - 1) // 400 - (ini...
Currently unsupported, it only works for differences in years.
def get_auth_header(self, user_payload): """ Returns the value for authorization header Args: user_payload(dict, required): A `dict` containing required information to create authentication token """ auth_token = self.get_auth_token(user_payload) ...
Returns the value for authorization header Args: user_payload(dict, required): A `dict` containing required information to create authentication token
def to_cloudformation(self): """Generates CloudFormation resources from a SAM API resource :returns: a tuple containing the RestApi, Deployment, and Stage for an empty Api. :rtype: tuple """ rest_api = self._construct_rest_api() deployment = self._construct_deployment(r...
Generates CloudFormation resources from a SAM API resource :returns: a tuple containing the RestApi, Deployment, and Stage for an empty Api. :rtype: tuple
def filterMapNames(regexText, records=getIndex(), excludeRegex=False, closestMatch=True): """matches each record against regexText according to parameters NOTE: the code could be written more simply, but this is loop-optimized to scale better with a large number of map records""" bestScr = 99999 ...
matches each record against regexText according to parameters NOTE: the code could be written more simply, but this is loop-optimized to scale better with a large number of map records
def parse(cls, fptr, offset, length): """Parse JPX free box. Parameters ---------- f : file Open file object. offset : int Start position of box in bytes. length : int Length of the box in bytes. Returns ------- ...
Parse JPX free box. Parameters ---------- f : file Open file object. offset : int Start position of box in bytes. length : int Length of the box in bytes. Returns ------- FreeBox Instance of the current fre...
def config(config, fork_name="", origin_name=""): """Setting various configuration options""" state = read(config.configfile) any_set = False if fork_name: update(config.configfile, {"FORK_NAME": fork_name}) success_out("fork-name set to: {}".format(fork_name)) any_set = True ...
Setting various configuration options
def cmd(command, *args, **kwargs): ''' run commands from __proxy__ :mod:`salt.proxy.onyx<salt.proxy.onyx>` command function from `salt.proxy.onyx` to run args positional args to pass to `command` function kwargs key word arguments to pass to `command` function .. ...
run commands from __proxy__ :mod:`salt.proxy.onyx<salt.proxy.onyx>` command function from `salt.proxy.onyx` to run args positional args to pass to `command` function kwargs key word arguments to pass to `command` function .. code-block:: bash salt '*' onyx.cmd se...
def _read_set(ctx: ReaderContext) -> lset.Set: """Return a set from the input stream.""" start = ctx.reader.advance() assert start == "{" def set_if_valid(s: Collection) -> lset.Set: if len(s) != len(set(s)): raise SyntaxError("Duplicated values in set") return lset.set(s) ...
Return a set from the input stream.
def mkstemp(suffix="", prefix=template, dir=None, text=False): """User-callable function to create and return a unique temporary file. The return value is a pair (fd, name) where fd is the file descriptor returned by os.open, and name is the filename. If 'suffix' is specified, the file name will end w...
User-callable function to create and return a unique temporary file. The return value is a pair (fd, name) where fd is the file descriptor returned by os.open, and name is the filename. If 'suffix' is specified, the file name will end with that suffix, otherwise there will be no suffix. If 'prefi...
def username_user_password(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") username = ET.SubElement(config, "username", xmlns="urn:brocade.com:mgmt:brocade-aaa") name_key = ET.SubElement(username, "name") name_key.text = kwargs.pop('name') ...
Auto Generated Code
def get_properties(self, feature): """Returns all contained properties associated with 'feature'""" if not isinstance(feature, b2.build.feature.Feature): feature = b2.build.feature.get(feature) assert isinstance(feature, b2.build.feature.Feature) result = [] for p in...
Returns all contained properties associated with 'feature
def hflip(img): """Horizontally flip the given PIL Image. Args: img (PIL Image): Image to be flipped. Returns: PIL Image: Horizontall flipped image. """ if not _is_pil_image(img): raise TypeError('img should be PIL Image. Got {}'.format(type(img))) return img.transpos...
Horizontally flip the given PIL Image. Args: img (PIL Image): Image to be flipped. Returns: PIL Image: Horizontall flipped image.
def table_add(tab, data, col): """ Function to parse dictionary list **data** and add the data to table **tab** for column **col** Parameters ---------- tab: Table class Table to store values data: list Dictionary list from the SQL query col: str Column name (ie, dictionar...
Function to parse dictionary list **data** and add the data to table **tab** for column **col** Parameters ---------- tab: Table class Table to store values data: list Dictionary list from the SQL query col: str Column name (ie, dictionary key) for the column to add
def lintersects(self, span): """ If this span intersects the left (starting) side of the given span. """ if isinstance(span, list): return [sp for sp in span if self._lintersects(sp)] return self._lintersects(span)
If this span intersects the left (starting) side of the given span.
def reordi(iorder, ndim, array): """ Re-order the elements of an integer array according to a given order vector. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/reordi_c.html :param iorder: Order vector to be used to re-order array. :type iorder: Array of ints :param ndim: Dimensi...
Re-order the elements of an integer array according to a given order vector. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/reordi_c.html :param iorder: Order vector to be used to re-order array. :type iorder: Array of ints :param ndim: Dimension of array. :type ndim: int :param a...
def unpublish(scm, published_branch, verbose, fake): """Removes a published branch from the remote repository.""" scm.fake = fake scm.verbose = fake or verbose scm.repo_check(require_remote=True) branch = scm.fuzzy_match_branch(published_branch) if not branch: scm.display_available_bra...
Removes a published branch from the remote repository.
def share(track_id=None, url=None, users=None): """ Returns list of users track has been shared with. Either track or url need to be provided. """ client = get_client() if url: track_id = client.get('/resolve', url=url).id if not users: return client.get('/tracks/%d/permis...
Returns list of users track has been shared with. Either track or url need to be provided.
def delete_host(zone, name, nameserver='127.0.0.1', timeout=5, port=53, **kwargs): ''' Delete the forward and reverse records for a host. Returns true if any records are deleted. CLI Example: .. code-block:: bash salt ns1 ddns.delete_host example.com host1 ''' fqd...
Delete the forward and reverse records for a host. Returns true if any records are deleted. CLI Example: .. code-block:: bash salt ns1 ddns.delete_host example.com host1
def add_multiifo_input_list_opt(self, opt, inputs): """ Add an option that determines a list of inputs from multiple detectors. Files will be supplied as --opt ifo1:input1 ifo2:input2 ..... """ # NOTE: Here we have to use the raw arguments functionality as the # ...
Add an option that determines a list of inputs from multiple detectors. Files will be supplied as --opt ifo1:input1 ifo2:input2 .....
def watch_from_file(connection, file_name): """ Start watching a new volume :type connection: boto.ec2.connection.EC2Connection :param connection: EC2 connection object :type file_name: str :param file_name: path to config file :returns: None """ with open(file_name, 'r') as filehandle:...
Start watching a new volume :type connection: boto.ec2.connection.EC2Connection :param connection: EC2 connection object :type file_name: str :param file_name: path to config file :returns: None
def plot_precision_recall_curve(y_true, y_probas, title='Precision-Recall Curve', curves=('micro', 'each_class'), ax=None, figsize=None, cmap='nipy_spectral', title_fontsize="large", ...
Generates the Precision Recall Curve from labels and probabilities Args: y_true (array-like, shape (n_samples)): Ground truth (correct) target values. y_probas (array-like, shape (n_samples, n_classes)): Prediction probabilities for each class returned by a classifier. ...
def assign(self, value, termenc): """ >>> scanner = DefaultScanner() >>> scanner.assign("01234", "ascii") >>> scanner._data u'01234' """ if self._termenc != termenc: self._decoder = codecs.getincrementaldecoder(termenc)(errors='replace') se...
>>> scanner = DefaultScanner() >>> scanner.assign("01234", "ascii") >>> scanner._data u'01234'
def active_tcp(): ''' Return a dict containing information on all of the running TCP connections (currently linux and solaris only) .. versionchanged:: 2015.8.4 Added support for SunOS CLI Example: .. code-block:: bash salt '*' network.active_tcp ''' if __grains__['kerne...
Return a dict containing information on all of the running TCP connections (currently linux and solaris only) .. versionchanged:: 2015.8.4 Added support for SunOS CLI Example: .. code-block:: bash salt '*' network.active_tcp
def to_bool(s): """ Convert string `s` into a boolean. `s` can be 'true', 'True', 1, 'false', 'False', 0. Examples: >>> to_bool("true") True >>> to_bool("0") False >>> to_bool(True) True """ if isinstance(s, bool): return s elif s.lower() in ['true', '1']: ...
Convert string `s` into a boolean. `s` can be 'true', 'True', 1, 'false', 'False', 0. Examples: >>> to_bool("true") True >>> to_bool("0") False >>> to_bool(True) True
def _update(self, layer=None): """ Update layers in model. """ meta = getattr(self, ModelBase._meta_attr) if not layer: layers = self.layers else: # convert non-sequence to tuple layers = _listify(layer) for layer in layers: ...
Update layers in model.
def cmd_set(context): """ Set the new "current" value for a key. If the existing current version and the new version have identical /value/ and /status, then nothing is written, to avoid stacking up redundant entreis in the version table. Args: context: a populated EFVersionContext object """ # If ke...
Set the new "current" value for a key. If the existing current version and the new version have identical /value/ and /status, then nothing is written, to avoid stacking up redundant entreis in the version table. Args: context: a populated EFVersionContext object
def get_offset_range(self, row_offset, column_offset): """ Gets an object which represents a range that's offset from the specified range. The dimension of the returned range will match this range. If the resulting range is forced outside the bounds of the worksheet grid, an ...
Gets an object which represents a range that's offset from the specified range. The dimension of the returned range will match this range. If the resulting range is forced outside the bounds of the worksheet grid, an exception will be thrown. :param int row_offset: The number of rows...
def Async(f, n=None, timeout=None): """Concise usage for pool.submit. Basic Usage Asnyc & threads :: from torequests.main import Async, threads import time def use_submit(i): time.sleep(i) result = 'use_submit: %s' % i print(result) ret...
Concise usage for pool.submit. Basic Usage Asnyc & threads :: from torequests.main import Async, threads import time def use_submit(i): time.sleep(i) result = 'use_submit: %s' % i print(result) return result @threads() def...
def bus_inspector(self, bus, message): """ Inspect the bus for screensaver messages of interest """ # We only care about stuff on this interface. We did filter # for it above, but even so we still hear from ourselves # (hamster messages). if message.get_interfac...
Inspect the bus for screensaver messages of interest
def _session(self): """The current session used by the client. The Session object allows you to persist certain parameters across requests. It also persists cookies across all requests made from the Session instance, and will use urllib3's connection pooling. So if you're making...
The current session used by the client. The Session object allows you to persist certain parameters across requests. It also persists cookies across all requests made from the Session instance, and will use urllib3's connection pooling. So if you're making several requests to the same h...
def tag_remove(self, *tags): """ Return a view with the specified tags removed """ return View({**self.spec, 'tag': list(set(self.tags) - set(tags))})
Return a view with the specified tags removed
def google_poem(self, message, topic): """make a poem about __: show a google poem about __""" r = requests.get("http://www.google.com/complete/search?output=toolbar&q=" + topic + "%20") xmldoc = minidom.parseString(r.text) item_list = xmldoc.getElementsByTagName("suggestion") co...
make a poem about __: show a google poem about __
def find_module(self, fullname, path=None): """ Tell if the module to load can be loaded by the load_module function, ie: if it is a ``pygal.maps.*`` module. """ if fullname.startswith('pygal.maps.') and hasattr( maps, fullname.split('.')[2]): ...
Tell if the module to load can be loaded by the load_module function, ie: if it is a ``pygal.maps.*`` module.
def savefig(writekey, dpi=None, ext=None): """Save current figure to file. The `filename` is generated as follows: filename = settings.figdir + writekey + settings.plot_suffix + '.' + settings.file_format_figs """ if dpi is None: # we need this as in notebooks, the internal figures are...
Save current figure to file. The `filename` is generated as follows: filename = settings.figdir + writekey + settings.plot_suffix + '.' + settings.file_format_figs
def set_mode(self, mode): """ Set *Vim* mode to ``mode``. Supported modes: * ``normal`` * ``insert`` * ``command`` * ``visual`` * ``visual-block`` This method behave as setter-only property. Example: >>> import headlessvim ...
Set *Vim* mode to ``mode``. Supported modes: * ``normal`` * ``insert`` * ``command`` * ``visual`` * ``visual-block`` This method behave as setter-only property. Example: >>> import headlessvim >>> with headlessvim.open() as vim: ...
def insert(self, tag, identifier, parent, data): """ Insert the given meta data into the database :param tag: The tag (equates to meta_data_id) :param identifier: The identifier (a combination of the meta_data_id and the plate value) :param parent: The parent plate identifier ...
Insert the given meta data into the database :param tag: The tag (equates to meta_data_id) :param identifier: The identifier (a combination of the meta_data_id and the plate value) :param parent: The parent plate identifier :param data: The data (plate value) :return: None
def _get_args_for_reloading(): """Returns the executable. This contains a workaround for windows if the executable is incorrectly reported to not have the .exe extension which can cause bugs on reloading. """ rv = [sys.executable] py_script = sys.argv[0] if os.name == 'nt' and not os.path.ex...
Returns the executable. This contains a workaround for windows if the executable is incorrectly reported to not have the .exe extension which can cause bugs on reloading.
def _validate_row_label(dataset, label=None, default_label='__id'): """ Validate a row label column. If the row label is not specified, a column is created with row numbers, named with the string in the `default_label` parameter. Parameters ---------- dataset : SFrame Input dataset....
Validate a row label column. If the row label is not specified, a column is created with row numbers, named with the string in the `default_label` parameter. Parameters ---------- dataset : SFrame Input dataset. label : str, optional Name of the column containing row labels. ...
def get_view_attr(view, key, default=None, cls_name=None): """ Get the attributes that was saved for the view :param view: object (class or instance method) :param key: string - the key :param default: mixed - the default value :param cls_name: str - To pass the class name associated to the view...
Get the attributes that was saved for the view :param view: object (class or instance method) :param key: string - the key :param default: mixed - the default value :param cls_name: str - To pass the class name associated to the view in the case of decorators that may not give the real class...
def add_columns(self, layers: Union[np.ndarray, Dict[str, np.ndarray], loompy.LayerManager], col_attrs: Dict[str, np.ndarray], *, row_attrs: Dict[str, np.ndarray] = None, fill_values: Dict[str, np.ndarray] = None) -> None: """ Add columns of data and attribute values to the dataset. Args: layers (dict or nump...
Add columns of data and attribute values to the dataset. Args: layers (dict or numpy.ndarray or LayerManager): Either: 1) A N-by-M matrix of float32s (N rows, M columns) in this case columns are added at the default layer 2) A dict {layer_name : matrix} specified so that the matrix (N, M) will be adde...
def unload(module): ''' Unload specified fault manager module module: string module to unload CLI Example: .. code-block:: bash salt '*' fmadm.unload software-response ''' ret = {} fmadm = _check_fmadm() cmd = '{cmd} unload {module}'.format( cmd=fmadm, ...
Unload specified fault manager module module: string module to unload CLI Example: .. code-block:: bash salt '*' fmadm.unload software-response
def _already_resized_on_flickr(self,fn,pid,_megapixels): """Checks if image file (fn) with photo_id (pid) has already been resized on flickr. If so, returns True""" logger.debug("%s - resize requested"%(fn)) # Get width/height from flickr width_flickr,height_flickr=self._getphoto...
Checks if image file (fn) with photo_id (pid) has already been resized on flickr. If so, returns True
def from_pubsec_file(cls: Type[SigningKeyType], path: str) -> SigningKeyType: """ Return SigningKey instance from Duniter WIF file :param path: Path to WIF file """ with open(path, 'r') as fh: pubsec_content = fh.read() # line patterns regex_pubkey =...
Return SigningKey instance from Duniter WIF file :param path: Path to WIF file
def lml(self): """ Log of the marginal likelihood. Returns ------- lml : float Log of the marginal likelihood. Notes ----- The log of the marginal likelihood is given by :: 2⋅log(p(𝐲)) = -n⋅log(2π) - n⋅log(s) - log|D| - (Qᵀ𝐲)ᵀs...
Log of the marginal likelihood. Returns ------- lml : float Log of the marginal likelihood. Notes ----- The log of the marginal likelihood is given by :: 2⋅log(p(𝐲)) = -n⋅log(2π) - n⋅log(s) - log|D| - (Qᵀ𝐲)ᵀs⁻¹D⁻¹(Qᵀ𝐲) ...
def _send_request(self, enforce_json, method, raise_for_status, url, **kwargs): """Send HTTP request. Args: enforce_json (bool): Require properly-formatted JSON or raise :exc:`~pancloud.exceptions.PanCloudError`. Defaults to ``False``. method (str): HTTP ...
Send HTTP request. Args: enforce_json (bool): Require properly-formatted JSON or raise :exc:`~pancloud.exceptions.PanCloudError`. Defaults to ``False``. method (str): HTTP method. raise_for_status (bool): If ``True``, raises :exc:`~pancloud.exceptions.HTTPError` if status...
def __set_private_key(self, pk): """ Internal method that sets the specified private key :param pk: private key to set :return: None """ self.__private_key = pk self.__public_key = pk.public_key()
Internal method that sets the specified private key :param pk: private key to set :return: None
def setActiveState(self, active): """ Use this to enable or disable (grey out) a parameter. """ st = DISABLED if active: st = NORMAL self.entry.configure(state=st) self.inputLabel.configure(state=st) self.promptLabel.configure(state=st)
Use this to enable or disable (grey out) a parameter.
def read_local_conf(local_conf): """Search for conf.py in any rel_source directory in CWD and if found read it and return. :param str local_conf: Path to conf.py to read. :return: Loaded conf.py. :rtype: dict """ log = logging.getLogger(__name__) # Attempt to read. log.info('Reading c...
Search for conf.py in any rel_source directory in CWD and if found read it and return. :param str local_conf: Path to conf.py to read. :return: Loaded conf.py. :rtype: dict
def get_element_types(obj, **kwargs): """Get element types as a set.""" max_iterable_length = kwargs.get('max_iterable_length', 10000) consume_generator = kwargs.get('consume_generator', False) if not isiterable(obj): return None if isgenerator(obj) and not consume_generator: retu...
Get element types as a set.
def disconnect(self, forced=False): """ Given the pipeline topology disconnects ``Pipers`` in the order output -> input. This also disconnects inputs. See ``Dagger.connect``, ``Piper.connect`` and ``Piper.disconnect``. If "forced" is ``True`` ``NuMap`` instances will be emptied....
Given the pipeline topology disconnects ``Pipers`` in the order output -> input. This also disconnects inputs. See ``Dagger.connect``, ``Piper.connect`` and ``Piper.disconnect``. If "forced" is ``True`` ``NuMap`` instances will be emptied. Arguments: - forced...
def data(self, **query): """Query for Data object annotation.""" objects = self.cache['objects'] data = self.api.data.get(**query)['objects'] data_objects = [] for d in data: _id = d['id'] if _id in objects: # Update existing object ...
Query for Data object annotation.
def sshpull(host, maildir, localmaildir, noop=False, verbose=False, filterfile=None): """Pull a remote maildir to the local one. """ store = _SSHStore(host, maildir) _pull(store, localmaildir, noop, verbose, filterfile)
Pull a remote maildir to the local one.
def add_zoom_buttons(viewer, canvas=None, color='black'): """Add zoom buttons to a canvas. Parameters ---------- viewer : an ImageView subclass instance If True, show the color bar; else remove it if present. canvas : a DrawingCanvas instance The canvas to which the buttons should ...
Add zoom buttons to a canvas. Parameters ---------- viewer : an ImageView subclass instance If True, show the color bar; else remove it if present. canvas : a DrawingCanvas instance The canvas to which the buttons should be added. If not supplied defaults to the private canvas...
def to_json(obj): """ Convert obj to json. Used mostly to convert the classes in json_span.py until we switch to nested dicts (or something better) :param obj: the object to serialize to json :return: json string """ try: return json.dumps(obj, default=lambda obj: {k.lower(): v fo...
Convert obj to json. Used mostly to convert the classes in json_span.py until we switch to nested dicts (or something better) :param obj: the object to serialize to json :return: json string
def simple_attention(memory, att_size, mask, keep_prob=1.0, scope="simple_attention"): """Simple attention without any conditions. Computes weighted sum of memory elements. """ with tf.variable_scope(scope): BS, ML, MH = tf.unstack(tf.shape(memory)) memory_do = tf.nn.dropout(memory, ...
Simple attention without any conditions. Computes weighted sum of memory elements.
def default_styles(): """Generate default ODF styles.""" styles = {} def _add_style(name, **kwargs): styles[name] = _create_style(name, **kwargs) _add_style('heading-1', family='paragraph', fontsize='24pt', fontweight='bold', ) _...
Generate default ODF styles.
def build_parser(self, context): """ Create the final argument parser. This method creates the non-early (full) argparse argument parser. Unlike the early counterpart it is expected to have knowledge of the full command tree. This method relies on ``context.cmd_tree`` a...
Create the final argument parser. This method creates the non-early (full) argparse argument parser. Unlike the early counterpart it is expected to have knowledge of the full command tree. This method relies on ``context.cmd_tree`` and produces ``context.parser``. Other ingredi...
def resolve_response_data(head_key, data_key, data): """ Resolves the responses you get from billomat If you have done a get_one_element request then you will get a dictionary If you have done a get_all_elements request then you will get a list with all elements in it :param hea...
Resolves the responses you get from billomat If you have done a get_one_element request then you will get a dictionary If you have done a get_all_elements request then you will get a list with all elements in it :param head_key: the head key e.g: CLIENTS :param data_key: the data key e....
def uncomment_or_update_or_append_line(filename, prefix, new_line, comment='#', keep_backup=True, update_or_append_line=update_or_append_line): '''Remove the comment of an commented out line and make the line "active". If such an com...
Remove the comment of an commented out line and make the line "active". If such an commented out line not exists it would be appended.
def autocorrect(query, possibilities, delta=0.75): """Attempts to figure out what possibility the query is This autocorrect function is rather simple right now with plans for later improvement. Right now, it just attempts to finish spelling a word as much as possible, and then determines which possibil...
Attempts to figure out what possibility the query is This autocorrect function is rather simple right now with plans for later improvement. Right now, it just attempts to finish spelling a word as much as possible, and then determines which possibility is closest to said word. Args: query (un...
def _filter_by_moys_slow(self, moys): """Filter the Data Collection with a slow method that always works.""" _filt_values = [] _filt_datetimes = [] for i, d in enumerate(self.datetimes): if d.moy in moys: _filt_datetimes.append(d) _filt_values....
Filter the Data Collection with a slow method that always works.
def run_linters(files): """ Run through file list, and try to find a linter that matches the given file type. If it finds a linter, it will run it, and store the resulting data in a dictionary (keyed to file_type). :param files: :return: {file_extension: lint_data} """ data = {} ...
Run through file list, and try to find a linter that matches the given file type. If it finds a linter, it will run it, and store the resulting data in a dictionary (keyed to file_type). :param files: :return: {file_extension: lint_data}
def query_relations(self, environment_id, collection_id, entities=None, context=None, sort=None, filter=None, count=None, eviden...
Knowledge Graph relationship query. See the [Knowledge Graph documentation](https://cloud.ibm.com/docs/services/discovery?topic=discovery-kg#kg) for more details. :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. :...
def patch(self, *args, **kwargs): """Patch only drafts. Status required: ``'draft'``. Meta information inside `_deposit` are preserved. """ return super(Deposit, self).patch(*args, **kwargs)
Patch only drafts. Status required: ``'draft'``. Meta information inside `_deposit` are preserved.
def _CheckCollation(cursor): """Checks MySQL collation and warns if misconfigured.""" # Do not fail for wrong collation, because changing it is harder than changing # the character set. Some providers only allow changing character set and then # use the default collation. Also, misconfigured collation is not e...
Checks MySQL collation and warns if misconfigured.
def built_datetime(self): """Return the built time as a datetime object""" from datetime import datetime try: return datetime.fromtimestamp(self.state.build_done) except TypeError: # build_done is null return None
Return the built time as a datetime object
def add_minutes(self, datetimestr, n): """Returns a time that n minutes after a time. :param datetimestr: a datetime object or a datetime str :param n: number of minutes, value can be negative **中文文档** 返回给定日期N分钟之后的时间。 """ a_datetime = self.parse_datetime(dateti...
Returns a time that n minutes after a time. :param datetimestr: a datetime object or a datetime str :param n: number of minutes, value can be negative **中文文档** 返回给定日期N分钟之后的时间。
def merge_ids(self, token, channel, ids, delete=False): """ Call the restful endpoint to merge two RAMON objects into one. Arguments: token (str): The token to inspect channel (str): The channel to inspect ids (int[]): the list of the IDs to merge ...
Call the restful endpoint to merge two RAMON objects into one. Arguments: token (str): The token to inspect channel (str): The channel to inspect ids (int[]): the list of the IDs to merge delete (bool : False): Whether to delete after merging. Returns: ...
def get_ttext(value): """ttext = <matches _ttext_matcher> We allow any non-TOKEN_ENDS in ttext, but add defects to the token's defects list if we find non-ttext characters. We also register defects for *any* non-printables even though the RFC doesn't exclude all of them, because we follow the spir...
ttext = <matches _ttext_matcher> We allow any non-TOKEN_ENDS in ttext, but add defects to the token's defects list if we find non-ttext characters. We also register defects for *any* non-printables even though the RFC doesn't exclude all of them, because we follow the spirit of RFC 5322.
def _add_secondary_if_exists(secondary, out, get_retriever): """Add secondary files only if present locally or remotely. """ secondary = [_file_local_or_remote(y, get_retriever) for y in secondary] secondary = [z for z in secondary if z] if secondary: out["secondaryFiles"] = [{"class": "File...
Add secondary files only if present locally or remotely.
def Chen_Friedel(m, x, rhol, rhog, mul, mug, sigma, D, roughness=0, L=1): r'''Calculates two-phase pressure drop with the Chen modification of the Friedel correlation, as given in [1]_ and also shown in [2]_ and [3]_. .. math:: \Delta P = \Delta P_{Friedel}\Omega For Bo < 2.5: .. math:: ...
r'''Calculates two-phase pressure drop with the Chen modification of the Friedel correlation, as given in [1]_ and also shown in [2]_ and [3]_. .. math:: \Delta P = \Delta P_{Friedel}\Omega For Bo < 2.5: .. math:: \Omega = \frac{0.0333Re_{lo}^{0.45}}{Re_g^{0.09}(1 + 0.4\exp(-Bo))} ...
def verify_files(files, user): ''' Verify that the named files exist and are owned by the named user ''' if salt.utils.platform.is_windows(): return True import pwd # after confirming not running Windows try: pwnam = pwd.getpwnam(user) uid = pwnam[2] except KeyError:...
Verify that the named files exist and are owned by the named user
def session(self): """ Returns the current db session """ if not self.__session: self.__session = dal.get_default_session() return self.__session
Returns the current db session
def contains_remove(self, item): # type (Any, Any) -> Any '''Takes a collection and an item and returns a new collection of the same type with that item removed. The notion of "contains" is defined by the object itself; the following must be ``True``: .. code-block:: python item not in con...
Takes a collection and an item and returns a new collection of the same type with that item removed. The notion of "contains" is defined by the object itself; the following must be ``True``: .. code-block:: python item not in contains_remove(obj, item) This function is used by some lenses (pa...
def load_instackenv(self): """Load the instackenv.json file and wait till the ironic nodes are ready. TODO(Gonéri): should be splitted, write_instackenv() to generate the instackenv.json and instackenv_import() for the rest. """ self.add_environment_file(user='stack', filename='s...
Load the instackenv.json file and wait till the ironic nodes are ready. TODO(Gonéri): should be splitted, write_instackenv() to generate the instackenv.json and instackenv_import() for the rest.
def get_dataset(self, key, info): """Load a dataset.""" if self._polarization != key.polarization: return logger.debug('Reading %s.', key.name) if key.name in ['longitude', 'latitude']: logger.debug('Constructing coordinate arrays.') if self.lons is...
Load a dataset.
def get_summary(self): """ Return the function summary Returns: (str, str, str, list(str), list(str), listr(str), list(str), list(str); contract_name, name, visibility, modifiers, vars read, vars written, internal_calls, external_calls_as_expressions """ ...
Return the function summary Returns: (str, str, str, list(str), list(str), listr(str), list(str), list(str); contract_name, name, visibility, modifiers, vars read, vars written, internal_calls, external_calls_as_expressions
def branches(self): """ Returns a data frame of all branches in origin. The DataFrame will have the columns: * repository * branch * local :returns: DataFrame """ # first pull the local branches local_branches = self.repo.branches da...
Returns a data frame of all branches in origin. The DataFrame will have the columns: * repository * branch * local :returns: DataFrame
def return_values_ssa(self): """ list(Return Values in SSA form): List of the return values in ssa form """ from slither.core.cfg.node import NodeType from slither.slithir.operations import Return from slither.slithir.variables import Constant if self._return...
list(Return Values in SSA form): List of the return values in ssa form
def compute_geometric_median(X, eps=1e-5): """ Estimate the geometric median of points in 2D. Code from https://stackoverflow.com/a/30305181 Parameters ---------- X : (N,2) ndarray Points in 2D. Second axis must be given in xy-form. eps : float, optional Distance threshold...
Estimate the geometric median of points in 2D. Code from https://stackoverflow.com/a/30305181 Parameters ---------- X : (N,2) ndarray Points in 2D. Second axis must be given in xy-form. eps : float, optional Distance threshold when to return the median. Returns ------- ...
def normalizeGroupValue(value): """ Normalizes group value. * **value** must be a ``list``. * **value** items must normalize as glyph names with :func:`normalizeGlyphName`. * Returned value will be a ``tuple`` of unencoded ``unicode`` strings. """ if not isinstance(value, (tuple, list...
Normalizes group value. * **value** must be a ``list``. * **value** items must normalize as glyph names with :func:`normalizeGlyphName`. * Returned value will be a ``tuple`` of unencoded ``unicode`` strings.
def recommendations(self, **kwargs): """ Get a list of recommended movies for a movie. Args: language: (optional) ISO 639-1 code. page: (optional) Minimum value of 1. Expected value is an integer. Returns: A dict representation of the JSON returned ...
Get a list of recommended movies for a movie. Args: language: (optional) ISO 639-1 code. page: (optional) Minimum value of 1. Expected value is an integer. Returns: A dict representation of the JSON returned from the API.
def emit(self, record): """ Override emit() method in handler parent for sending log to RESTful API """ # avoid infinite recursion if record.name.startswith('requests'): return data, header = self._prepPayload(record) try: self.session.po...
Override emit() method in handler parent for sending log to RESTful API
def _nested_cwl_record(xs, want_attrs, input_files): """Convert arbitrarily nested samples into a nested list of dictionaries. nests only at the record level, rather than within records. For batching a top level list is all of the batches and sub-lists are samples within the batch. """ if isins...
Convert arbitrarily nested samples into a nested list of dictionaries. nests only at the record level, rather than within records. For batching a top level list is all of the batches and sub-lists are samples within the batch.
def parse(self, response): ''' 根据对 ``start_urls`` 中提供链接的请求响应包内容,解析生成具体文章链接请求 :param Response response: 由 ``Scrapy`` 调用并传入的请求响应对象 ''' content_raw = response.body.decode() self.logger.debug('响应body原始数据:{}'.format(content_raw)) content = json.loads(content_raw, enco...
根据对 ``start_urls`` 中提供链接的请求响应包内容,解析生成具体文章链接请求 :param Response response: 由 ``Scrapy`` 调用并传入的请求响应对象
def __set_window_title(self): """ Sets the Component window title. """ if self.has_editor_tab(): windowTitle = "{0} - {1}".format(self.__default_window_title, self.get_current_editor().file) else: windowTitle = "{0}".format(self.__default_window_title) ...
Sets the Component window title.
def from_scf_task(cls, scf_task, ddk_tolerance=None, ph_tolerance=None, manager=None): """ Build tasks for the computation of Born effective charges from a ground-state task. Args: scf_task: ScfTask object. ddk_tolerance: tolerance used in the DDK run if with_becs. None ...
Build tasks for the computation of Born effective charges from a ground-state task. Args: scf_task: ScfTask object. ddk_tolerance: tolerance used in the DDK run if with_becs. None to use AbiPy default. ph_tolerance: dict {"varname": value} with the tolerance used in the phon...
def estimate_clock_model(params): """ implementing treetime clock """ if assure_tree(params, tmp_dir='clock_model_tmp'): return 1 dates = utils.parse_dates(params.dates) if len(dates)==0: return 1 outdir = get_outdir(params, '_clock') ##################################...
implementing treetime clock
def approx(x, y, xout, method='linear', rule=1, f=0, yleft=None, yright=None, ties='mean'): """Linearly interpolate points. Return a list of points which (linearly) interpolate given data points, or a function performing the linear (or constant) interpolation. Parameters ---------- ...
Linearly interpolate points. Return a list of points which (linearly) interpolate given data points, or a function performing the linear (or constant) interpolation. Parameters ---------- x : array-like, shape=(n_samples,) Numeric vector giving the coordinates of the points to be i...
def add_peer(self, peer_addr): "Build a connection to the Hub at a given ``(host, port)`` address" peer = connection.Peer( self._ident, self._dispatcher, peer_addr, backend.Socket()) peer.start() self._started_peers[peer_addr] = peer
Build a connection to the Hub at a given ``(host, port)`` address
def main(): """Create an organization, print out its attributes and delete it.""" org = Organization(name='junk org').create() pprint(org.get_values()) # e.g. {'name': 'junk org', …} org.delete()
Create an organization, print out its attributes and delete it.
def subscribe_to_address_webhook(callback_url, subscription_address, event='tx-confirmation', confirmations=0, confidence=0.00, coin_symbol='btc', api_key=None): ''' Subscribe to transaction webhooks on a given address. Webhooks for transaction broadcast and each confirmation (up to 6). Returns the blo...
Subscribe to transaction webhooks on a given address. Webhooks for transaction broadcast and each confirmation (up to 6). Returns the blockcypher ID of the subscription
def logs(ctx, services, num, follow): """Show logs of daemonized service.""" logger.debug("running command %s (%s)", ctx.command.name, ctx.params, extra={"command": ctx.command.name, "params": ctx.params}) home = ctx.obj["HOME"] services_path = os.path.join(home, SERVICES) tail_th...
Show logs of daemonized service.
def purge(self): """ Purges read/write buffers. """ try: self._device.setblocking(0) while(self._device.recv(1)): pass except socket.error as err: pass finally: self._device.setblocking(1)
Purges read/write buffers.
def update_type_lookups(self): """ Update type and typestring lookup dicts. Must be called once the ``types`` and ``python_type_strings`` attributes are set so that ``type_to_typestring`` and ``typestring_to_type`` are constructed. .. versionadded:: 0.2 Notes -...
Update type and typestring lookup dicts. Must be called once the ``types`` and ``python_type_strings`` attributes are set so that ``type_to_typestring`` and ``typestring_to_type`` are constructed. .. versionadded:: 0.2 Notes ----- Subclasses need to call this f...