code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def killCells(i, options, tm): """ Kill cells as appropriate """ # Kill cells if called for if options.simulation == "killer": if i == options.switchover: print "i=",i,"Killing cells for the first time!" tm.killCells(percent = options.noise) if i == options.secondKill: print "i=",...
Kill cells as appropriate
def query_by_account(self, account_id, end_time=None, start_time=None): """ Query by account. List authentication events for a given account. """ path = {} data = {} params = {} # REQUIRED - PATH - account_id """ID""" path["ac...
Query by account. List authentication events for a given account.
def psetex(self, key, milliseconds, value): """:meth:`~tredis.RedisClient.psetex` works exactly like :meth:`~tredis.RedisClient.psetex` with the sole difference that the expire time is specified in milliseconds instead of seconds. .. versionadded:: 0.2.0 .. note:: **Time comple...
:meth:`~tredis.RedisClient.psetex` works exactly like :meth:`~tredis.RedisClient.psetex` with the sole difference that the expire time is specified in milliseconds instead of seconds. .. versionadded:: 0.2.0 .. note:: **Time complexity**: ``O(1)`` :param key: The key to set ...
def bdecode(text): """Decodes a bencoded bytearray and returns it as a python object""" text = text.decode('utf-8') def bdecode_next(start): """bdecode helper function""" if text[start] == 'i': end = text.find('e', start) return int(text[start+1:end], 10), end + 1 ...
Decodes a bencoded bytearray and returns it as a python object
def published_tracks(self): """ Access the published_tracks :returns: twilio.rest.video.v1.room.room_participant.room_participant_published_track.PublishedTrackList :rtype: twilio.rest.video.v1.room.room_participant.room_participant_published_track.PublishedTrackList """ ...
Access the published_tracks :returns: twilio.rest.video.v1.room.room_participant.room_participant_published_track.PublishedTrackList :rtype: twilio.rest.video.v1.room.room_participant.room_participant_published_track.PublishedTrackList
def values(self, *fields): """ Ask the collection to return a list of dict of given fields for each instance found in the collection. If no fields are given, all "simple value" fields are used. """ if not fields: fields = self._get_simple_fields() fie...
Ask the collection to return a list of dict of given fields for each instance found in the collection. If no fields are given, all "simple value" fields are used.
def track(self, event_key, user_id, attributes=None, event_tags=None): """ Send conversion event to Optimizely. Args: event_key: Event key representing the event which needs to be recorded. user_id: ID for user. attributes: Dict representing visitor attributes and values which need to be reco...
Send conversion event to Optimizely. Args: event_key: Event key representing the event which needs to be recorded. user_id: ID for user. attributes: Dict representing visitor attributes and values which need to be recorded. event_tags: Dict representing metadata associated with the event.
def constraint_from_choices(cls, value_type: type, choices: collections.Sequence): """ Returns a constraint callable based on choices of a given type """ choices_str = ', '.join(map(str, choices)) def constraint(value): value = value_type(value) if value ...
Returns a constraint callable based on choices of a given type
def validate(self): """ Apply the `is_valid` methods to self and possibly raise a ValueError. """ # it is important to have the validator applied in a fixed order valids = [getattr(self, valid) for valid in sorted(dir(self.__class__)) if valid....
Apply the `is_valid` methods to self and possibly raise a ValueError.
def _set_random_detect(self, v, load=False): """ Setter method for random_detect, mapped from YANG variable /interface/ethernet/qos/random_detect (container) If this variable is read-only (config: false) in the source YANG file, then _set_random_detect is considered as a private method. Backends loo...
Setter method for random_detect, mapped from YANG variable /interface/ethernet/qos/random_detect (container) If this variable is read-only (config: false) in the source YANG file, then _set_random_detect is considered as a private method. Backends looking to populate this variable should do so via calli...
def _IncrementNestLevel(): """Increments the per thread nest level of imports.""" # This is the top call to import (no nesting), init the per-thread nest level # and names set. if getattr(_import_local, 'nest_level', None) is None: _import_local.nest_level = 0 if _import_local.nest_level == 0: # Re-i...
Increments the per thread nest level of imports.
def get_points(self, measurement=None, tags=None): """Return a generator for all the points that match the given filters. :param measurement: The measurement name :type measurement: str :param tags: Tags to look for :type tags: dict :return: Points generator ""...
Return a generator for all the points that match the given filters. :param measurement: The measurement name :type measurement: str :param tags: Tags to look for :type tags: dict :return: Points generator
def check_partition_column(partition_column, cols): """ Check partition_column existence and type Args: partition_column: partition_column name cols: dict with columns names and python types Returns: None """ for k, v in cols.items(): if k == partition_column: ...
Check partition_column existence and type Args: partition_column: partition_column name cols: dict with columns names and python types Returns: None
def add_domain_name(list_name, item_name): ''' Adds a domain name to a domain name list. list_name(str): The name of the specific policy domain name list to append to. item_name(str): The domain name to append. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_domain_name...
Adds a domain name to a domain name list. list_name(str): The name of the specific policy domain name list to append to. item_name(str): The domain name to append. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_domain_name MyDomainName foo.bar.com
def list_sebool(): ''' Return a structure listing all of the selinux booleans on the system and what state they are in CLI Example: .. code-block:: bash salt '*' selinux.list_sebool ''' bdata = __salt__['cmd.run']('semanage boolean -l').splitlines() ret = {} for line in bd...
Return a structure listing all of the selinux booleans on the system and what state they are in CLI Example: .. code-block:: bash salt '*' selinux.list_sebool
def set_ortho_choice(self, small_asset_data, large_asset_data, name='Choice'): """stub""" o3d_asset_id = self.create_o3d_asset(manip=None, small_ov_set=small_asset_data, large_ov_set=large_asset_data, ...
stub
def load(self, label): """ Load obj with give label from hidden state directory """ objloc = '{0}/{1}'.format(self.statedir, label) try: obj = pickle.load(open(objloc, 'r')) except (KeyError, IndexError, EOFError): obj = open(objloc, 'r').read() try...
Load obj with give label from hidden state directory
def get_unit_hostnames(self, units): """Return a dict of juju unit names to hostnames.""" host_names = {} for unit in units: host_names[unit.info['unit_name']] = \ str(unit.file_contents('/etc/hostname').strip()) self.log.debug('Unit host names: {}'.format(hos...
Return a dict of juju unit names to hostnames.
def direction(theta, phi): '''Return the direction vector of a cylinder defined by the spherical coordinates theta and phi. ''' return np.array([np.cos(phi) * np.sin(theta), np.sin(phi) * np.sin(theta), np.cos(theta)])
Return the direction vector of a cylinder defined by the spherical coordinates theta and phi.
def iterDiffs(self): """ Return all diffs used in optimal network. """ nodes = self.nodes.values() nodes.sort(key=lambda node: self._height(node)) for node in nodes: yield node.diff
Return all diffs used in optimal network.
def list_group_categories_for_context_courses(self, course_id): """ List group categories for a context. Returns a list of group categories in a context """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" ...
List group categories for a context. Returns a list of group categories in a context
def handle_request(self): """simply collect requests and put them on the queue for the workers.""" try: request, client_address = self.get_request() except socket.error: return if self.verify_request(request, client_address): self.requests.put((reques...
simply collect requests and put them on the queue for the workers.
def parent(self, parent): """ Sets the parent of the actor. :param parent: the parent :type parent: Actor """ self._name = self.unique_name(self._name) self._full_name = None self._logger = None self._parent = parent
Sets the parent of the actor. :param parent: the parent :type parent: Actor
def euclidean_distance_square(point1, point2): """! @brief Calculate square Euclidean distance between two vectors. \f[ dist(a, b) = \sum_{i=0}^{N}(a_{i} - b_{i})^{2}; \f] @param[in] point1 (array_like): The first vector. @param[in] point2 (array_like): The second vector. @...
! @brief Calculate square Euclidean distance between two vectors. \f[ dist(a, b) = \sum_{i=0}^{N}(a_{i} - b_{i})^{2}; \f] @param[in] point1 (array_like): The first vector. @param[in] point2 (array_like): The second vector. @return (double) Square Euclidean distance between two v...
def writeRaw8(self, value): """Write an 8-bit value on the bus (without register).""" value = value & 0xFF self._bus.write_byte(self._address, value) self._logger.debug("Wrote 0x%02X", value)
Write an 8-bit value on the bus (without register).
def movies_directed_by(self, director): """Return list of movies that were directed by certain person. :param director: Director's name :type director: str :rtype: list[movies.models.Movie] :return: List of movie instances. """ return [movie for movie in self._m...
Return list of movies that were directed by certain person. :param director: Director's name :type director: str :rtype: list[movies.models.Movie] :return: List of movie instances.
def cert_info(cert, digest='sha256'): ''' Return information for a particular certificate cert path to the certifiate PEM file or string .. versionchanged:: 2018.3.4 digest what digest to use for fingerprinting CLI Example: .. code-block:: bash salt '*' tls....
Return information for a particular certificate cert path to the certifiate PEM file or string .. versionchanged:: 2018.3.4 digest what digest to use for fingerprinting CLI Example: .. code-block:: bash salt '*' tls.cert_info /dir/for/certs/cert.pem
def _move_here(self): """Move the cursor to this item.""" cu = self.scraper.current_item # Already here? if self is cu: return # A child? if cu.items and self in cu.items: self.scraper.move_to(self) return # A parent? if...
Move the cursor to this item.
def get_ip_info(ip: str, exceptions: bool=False, timeout: int=10) -> tuple: """ Returns (ip, country_code, host) tuple of the IP address. :param ip: IP address :param exceptions: Raise Exception or not :param timeout: Timeout in seconds. Note that timeout only affects geo IP part, not getting host n...
Returns (ip, country_code, host) tuple of the IP address. :param ip: IP address :param exceptions: Raise Exception or not :param timeout: Timeout in seconds. Note that timeout only affects geo IP part, not getting host name. :return: (ip, country_code, host)
def moist_lapse(pressure, temperature, ref_pressure=None): r"""Calculate the temperature at a level assuming liquid saturation processes. This function lifts a parcel starting at `temperature`. The starting pressure can be given by `ref_pressure`. Essentially, this function is calculating moist pseudo-...
r"""Calculate the temperature at a level assuming liquid saturation processes. This function lifts a parcel starting at `temperature`. The starting pressure can be given by `ref_pressure`. Essentially, this function is calculating moist pseudo-adiabats. Parameters ---------- pressure : `pint.Q...
def text_search(self, text, sort=None, offset=100, page=1): """ Search in aquarius using text query. Given the string aquarius will do a full-text query to search in all documents. Currently implemented are the MongoDB and Elastic Search drivers. For a detailed guide on how to...
Search in aquarius using text query. Given the string aquarius will do a full-text query to search in all documents. Currently implemented are the MongoDB and Elastic Search drivers. For a detailed guide on how to search, see the MongoDB driver documentation: mongodb driverCurrently i...
def on_line(client, line): """Default handling for incoming lines. This handler will automatically manage the following IRC messages: PING: Responds with a PONG. PRIVMSG: Dispatches the PRIVMSG event. NOTICE: Dispatches the NOTICE event. MOTDSTART: Initi...
Default handling for incoming lines. This handler will automatically manage the following IRC messages: PING: Responds with a PONG. PRIVMSG: Dispatches the PRIVMSG event. NOTICE: Dispatches the NOTICE event. MOTDSTART: Initializes MOTD receive buffer. ...
def disconnect_channel(self, destination_id): """ Disconnect a channel with destination_id. """ if destination_id in self._open_channels: try: self.send_message( destination_id, NS_CONNECTION, {MESSAGE_TYPE: TYPE_CLOSE, 'origin': {}}, ...
Disconnect a channel with destination_id.
def GetRealPath(filename): """Given an executable filename, find in the PATH or find absolute path. Args: filename An executable filename (string) Returns: Absolute version of filename. None if filename could not be found locally, absolutely, or in PATH """ if os.path.isabs(filename): ...
Given an executable filename, find in the PATH or find absolute path. Args: filename An executable filename (string) Returns: Absolute version of filename. None if filename could not be found locally, absolutely, or in PATH
def forget_canvas(canvas): """ Forget about the given canvas. Used by the canvas when closed. """ cc = [c() for c in canvasses if c() is not None] while canvas in cc: cc.remove(canvas) canvasses[:] = [weakref.ref(c) for c in cc]
Forget about the given canvas. Used by the canvas when closed.
def save(self, filename, fformat=None, fill_value=None, compute=True, keep_palette=False, cmap=None, **format_kwargs): """Save the image to the given *filename*. Args: filename (str): Output filename fformat (str): File format of output file (optional). Can be ...
Save the image to the given *filename*. Args: filename (str): Output filename fformat (str): File format of output file (optional). Can be one of many image formats supported by the `rasterio` or `PIL` libraries ('jpg', 'png', ...
def _get_satisfiability_smt_script(self, constraints=(), variables=()): """ Returns a SMT script that declare all the symbols and constraint and checks their satisfiability (check-sat) :param extra-constraints: list of extra constraints that we want to evaluate only ...
Returns a SMT script that declare all the symbols and constraint and checks their satisfiability (check-sat) :param extra-constraints: list of extra constraints that we want to evaluate only in the scope of this call :return stri...
def expand_path(path): """Returns ``path`` as an absolute path with ~user and env var expansion applied. :API: public """ return os.path.abspath(os.path.expandvars(os.path.expanduser(path)))
Returns ``path`` as an absolute path with ~user and env var expansion applied. :API: public
def get_file(self, secure_data_path, version=None): """ Return a requests.structures.CaseInsensitiveDict object containing a file and the metadata/header information around it. The binary data of the file is under the key 'data' """ query = self._get_file(secure_data_pa...
Return a requests.structures.CaseInsensitiveDict object containing a file and the metadata/header information around it. The binary data of the file is under the key 'data'
def force_delete(self): """ Force a hard delete on a soft deleted model. """ self.__force_deleting__ = True self.delete() self.__force_deleting__ = False
Force a hard delete on a soft deleted model.
def add_caveats(self, cavs, key, loc): '''Add an array of caveats to the macaroon. This method does not mutate the current object. @param cavs arrary of caveats. @param key the PublicKey to encrypt third party caveat. @param loc locator to find the location object that has a met...
Add an array of caveats to the macaroon. This method does not mutate the current object. @param cavs arrary of caveats. @param key the PublicKey to encrypt third party caveat. @param loc locator to find the location object that has a method third_party_info.
def run(self, inputs, **kwargs): """Run model inference and return the result Parameters ---------- inputs : numpy array input to run a layer on Returns ------- params : numpy array result obtained after running the inference on mxnet ...
Run model inference and return the result Parameters ---------- inputs : numpy array input to run a layer on Returns ------- params : numpy array result obtained after running the inference on mxnet
def get_method_name(method): """ Returns given method name. :param method: Method to retrieve the name. :type method: object :return: Method name. :rtype: unicode """ name = get_object_name(method) if name.startswith("__") and not name.endswith("__"): name = "_{0}{1}".forma...
Returns given method name. :param method: Method to retrieve the name. :type method: object :return: Method name. :rtype: unicode
def setup_resource(self): """ Setting Up Resource """ template = self.template variables = self.get_variables() tclass = variables['Class'] tprops = variables['Properties'] output = variables['Output'] klass = load_object_from_string('troposphere.' + tclass) ...
Setting Up Resource
def is_readable(path): """ Returns if given path is readable. :param path: Path to check access. :type path: unicode :return: Is path writable. :rtype: bool """ if os.access(path, os.R_OK): LOGGER.debug("> '{0}' path is readable.".format(path)) return True else: ...
Returns if given path is readable. :param path: Path to check access. :type path: unicode :return: Is path writable. :rtype: bool
def list(self): """List versions under the current model in a table view. Raises: Exception if it is called in a non-IPython environment. """ import IPython # "self" is iterable (see __iter__() method). data = [{'name': version['name'].split()[-1], 'deploymentUri': version['...
List versions under the current model in a table view. Raises: Exception if it is called in a non-IPython environment.
def stat(self, follow_symlinks=True): """ Return a stat_result object for this entry. The result is cached on the os.DirEntry object. Args: follow_symlinks (bool): Follow symlinks. Not supported on cloud storage objects. Returns: os.stat...
Return a stat_result object for this entry. The result is cached on the os.DirEntry object. Args: follow_symlinks (bool): Follow symlinks. Not supported on cloud storage objects. Returns: os.stat_result: Stat result object
def xrefs_from(self): """Xrefs from the function. This includes the xrefs from every line in the function, as `Xref` objects. Xrefs are filtered to exclude code references that are internal to the function. This means that every xrefs to the function's code will NOT be returned (yet, re...
Xrefs from the function. This includes the xrefs from every line in the function, as `Xref` objects. Xrefs are filtered to exclude code references that are internal to the function. This means that every xrefs to the function's code will NOT be returned (yet, references to the function'...
def _computeStatus(self, dfile, service): """Computes status for file, basically this means if more than one service handles the file, it will place a 'C' (for complicated) otherwise if status matches between all services, will place that status""" # If only one service request...
Computes status for file, basically this means if more than one service handles the file, it will place a 'C' (for complicated) otherwise if status matches between all services, will place that status
def on_finished(self): """Finished signal handler""" self.controller.is_running = False error = self.controller.current_error if error is not None: self.info(self.tr("Stopped due to error(s), see Terminal.")) else: self.info(self.tr("Finished successfully...
Finished signal handler
def info(name): ''' Return information for the specified user This is just returns dummy data so that salt states can work. :param str name: The name of the user account to show. CLI Example: .. code-block:: bash salt '*' shadow.info root ''' info = __salt__['user.info'](name...
Return information for the specified user This is just returns dummy data so that salt states can work. :param str name: The name of the user account to show. CLI Example: .. code-block:: bash salt '*' shadow.info root
def _modify(self, **patch): '''Modify only draft or legacy policies Published policies cannot be modified :raises: OperationNotSupportedOnPublishedPolicy ''' legacy = patch.pop('legacy', False) tmos_ver = self._meta_data['bigip']._meta_data['tmos_version'] self....
Modify only draft or legacy policies Published policies cannot be modified :raises: OperationNotSupportedOnPublishedPolicy
def rejoin_lines(nb): """rejoin multiline text into strings For reversing effects of ``split_lines(nb)``. This only rejoins lines that have been split, so if text objects were not split they will pass through unchanged. Used when reading JSON files that may have been passed through sp...
rejoin multiline text into strings For reversing effects of ``split_lines(nb)``. This only rejoins lines that have been split, so if text objects were not split they will pass through unchanged. Used when reading JSON files that may have been passed through split_lines.
def _prepare_reserved_tokens(reserved_tokens): """Prepare reserved tokens and a regex for splitting them out of strings.""" reserved_tokens = [tf.compat.as_text(tok) for tok in reserved_tokens or []] dups = _find_duplicates(reserved_tokens) if dups: raise ValueError("Duplicates found in tokens: %s" % dups) ...
Prepare reserved tokens and a regex for splitting them out of strings.
def update(self, iterable): """ Return a new PSet with elements in iterable added >>> s1 = s(1, 2) >>> s1.update([3, 4, 4]) pset([1, 2, 3, 4]) """ e = self.evolver() for element in iterable: e.add(element) return e.persistent()
Return a new PSet with elements in iterable added >>> s1 = s(1, 2) >>> s1.update([3, 4, 4]) pset([1, 2, 3, 4])
def curve_reduce_approx(curve, reduced): """Image for :meth:`.curve.Curve.reduce` docstring.""" if NO_IMAGES: return ax = curve.plot(256) color = ax.lines[-1].get_color() add_patch(ax, curve._nodes, color, alpha=0.25, node_color=color) reduced.plot(256, ax=ax) color = ax.lines[-1].g...
Image for :meth:`.curve.Curve.reduce` docstring.
def create_summary_tear_sheet(factor_data, long_short=True, group_neutral=False): """ Creates a small summary tear sheet with returns, information, and turnover analysis. Parameters ---------- factor_data : pd.DataFrame - MultiIndex ...
Creates a small summary tear sheet with returns, information, and turnover analysis. Parameters ---------- factor_data : pd.DataFrame - MultiIndex A MultiIndex DataFrame indexed by date (level 0) and asset (level 1), containing the values for a single alpha factor, forward returns for ...
def add(self, name: str, pattern: str) -> None: """ add url pattern for name """ self.patterns[name] = URITemplate( pattern, converters=self.converters)
add url pattern for name
def process_iter(): """Return a generator yielding a Process class instance for all running processes on the local machine. Every new Process instance is only created once and then cached into an internal table which is updated every time this is used. The sorting order in which processes are yiel...
Return a generator yielding a Process class instance for all running processes on the local machine. Every new Process instance is only created once and then cached into an internal table which is updated every time this is used. The sorting order in which processes are yielded is based on their P...
def render_template(self): """Render and save API doc in openapi.yml.""" self._parse_paths() context = dict(napp=self._napp.__dict__, paths=self._paths) self._save(context)
Render and save API doc in openapi.yml.
def rpc_get_name_record(self, name, **con_info): """ Get the curernt state of a name or subdomain, excluding its history. Return {'status': True, 'record': rec} on success Return {'error': ...} on error """ res = None if check_name(name): res = self.ge...
Get the curernt state of a name or subdomain, excluding its history. Return {'status': True, 'record': rec} on success Return {'error': ...} on error
def dispatch(self, *args, **kwargs): """ Check that user signup is allowed before even bothering to dispatch or do other processing. """ if not self.registration_allowed(): return HttpResponseRedirect(force_text(self.disallowed_url)) return super(Registration...
Check that user signup is allowed before even bothering to dispatch or do other processing.
def supports_currency_type(self, currency_type): """Tests if the given currency type is supported. arg: currency_type (osid.type.Type): a currency Type return: (boolean) - ``true`` if the type is supported, ``false`` otherwise raise: IllegalState - syntax is not a ``...
Tests if the given currency type is supported. arg: currency_type (osid.type.Type): a currency Type return: (boolean) - ``true`` if the type is supported, ``false`` otherwise raise: IllegalState - syntax is not a ``CURRENCY`` raise: NullArgument - ``currency_type`` ...
def _apply(self, f, grouper=None, *args, **kwargs): """ Dispatch to _upsample; we are stripping all of the _upsample kwargs and performing the original function call on the grouped object. """ def func(x): x = self._shallow_copy(x, groupby=self.groupby) ...
Dispatch to _upsample; we are stripping all of the _upsample kwargs and performing the original function call on the grouped object.
def create_element(tag: str, name: str = None, base: type = None, attr: dict = None) -> Node: """Create element with a tag of ``name``. :arg str name: html tag. :arg type base: Base class of the created element (defatlt: ``WdomElement``) :arg dict attr: Attribu...
Create element with a tag of ``name``. :arg str name: html tag. :arg type base: Base class of the created element (defatlt: ``WdomElement``) :arg dict attr: Attributes (key-value pairs dict) of the new element.
def create(cls, name, certificate): """ Create a TLS CA. The certificate must be compatible with OpenSSL and be in PEM format. The certificate can be either a file with the Root CA, or a raw string starting with BEGIN CERTIFICATE, etc. When creating a TLS CA, you must also import...
Create a TLS CA. The certificate must be compatible with OpenSSL and be in PEM format. The certificate can be either a file with the Root CA, or a raw string starting with BEGIN CERTIFICATE, etc. When creating a TLS CA, you must also import the CA certificate. Once the CA is created, it ...
def add_files_to_git_repository(base_dir, files, description): """ Add and commit all files given in a list into a git repository in the base_dir directory. Nothing is done if the git repository has local changes. @param files: the files to commit @param description: the commit message """ ...
Add and commit all files given in a list into a git repository in the base_dir directory. Nothing is done if the git repository has local changes. @param files: the files to commit @param description: the commit message
def load_configuration(configuration): """Returns a dictionary, accepts a dictionary or a path to a JSON file.""" if isinstance(configuration, dict): return configuration else: with open(configuration) as configfile: return json.load(configfile)
Returns a dictionary, accepts a dictionary or a path to a JSON file.
def getElementsWithAttrValues(self, attrName, attrValues): ''' getElementsWithAttrValues - Search children of this tag for tags with an attribute name and one of several values @param attrName <lowercase str> - Attribute name (lowercase) @param attrValues set<str> - set of a...
getElementsWithAttrValues - Search children of this tag for tags with an attribute name and one of several values @param attrName <lowercase str> - Attribute name (lowercase) @param attrValues set<str> - set of acceptable attribute values @return - TagCollection of matching element...
def save_data(self, trigger_id, **data): """ let's save the data don't want to handle empty title nor content otherwise this will produce an Exception by the Evernote's API :param trigger_id: trigger ID from which to save data :param data:...
let's save the data don't want to handle empty title nor content otherwise this will produce an Exception by the Evernote's API :param trigger_id: trigger ID from which to save data :param data: the data to check to be used and save :type trigger_...
def is_instance_of(self, some_class): """Asserts that val is an instance of the given class.""" try: if not isinstance(self.val, some_class): if hasattr(self.val, '__name__'): t = self.val.__name__ elif hasattr(self.val, '__class__'): ...
Asserts that val is an instance of the given class.
def incrementing_sleep(self, previous_attempt_number, delay_since_first_attempt_ms): """ Sleep an incremental amount of time after each attempt, starting at wait_incrementing_start and incrementing by wait_incrementing_increment """ result = self._wait_incrementing_start + (self....
Sleep an incremental amount of time after each attempt, starting at wait_incrementing_start and incrementing by wait_incrementing_increment
def create_script_staging_table(self, output_table, col_list): """ appends the CREATE TABLE, index etc to another table """ self.ddl_text += '---------------------------------------------\n' self.ddl_text += '-- CREATE Staging Table - ' + output_table + '\n' self.ddl_text...
appends the CREATE TABLE, index etc to another table
def fix_paths(self, d, root=None, project=None): """ Fix the paths in the given dictionary to get absolute paths Parameters ---------- %(ExperimentsConfig.fix_paths.parameters)s Returns ------- %(ExperimentsConfig.fix_paths.returns)s Notes ...
Fix the paths in the given dictionary to get absolute paths Parameters ---------- %(ExperimentsConfig.fix_paths.parameters)s Returns ------- %(ExperimentsConfig.fix_paths.returns)s Notes ----- d is modified in place!
def create(self, name, network): """Create a new Account object and add it to this Accounts collection. Args: name (str): Account name network (str): Type of cryptocurrency. Can be one of, 'bitcoin', ' bitcoin_testnet', 'litecoin', 'dogecoin'. Returns: The new ...
Create a new Account object and add it to this Accounts collection. Args: name (str): Account name network (str): Type of cryptocurrency. Can be one of, 'bitcoin', ' bitcoin_testnet', 'litecoin', 'dogecoin'. Returns: The new round.Account
def iter_admin_log( self, entity, limit=None, *, max_id=0, min_id=0, search=None, admins=None, join=None, leave=None, invite=None, restrict=None, unrestrict=None, ban=None, unban=None, promote=None, demote=None, info=None, settings=None, pinned=None, edit=None, delete=Non...
Iterator over the admin log for the specified channel. Note that you must be an administrator of it to use this method. If none of the filters are present (i.e. they all are ``None``), *all* event types will be returned. If at least one of them is ``True``, only those that are true wil...
def phenotypes_actions(institute_id, case_name): """Perform actions on multiple phenotypes.""" institute_obj, case_obj = institute_and_case(store, institute_id, case_name) case_url = url_for('.case', institute_id=institute_id, case_name=case_name) action = request.form['action'] hpo_ids = request.fo...
Perform actions on multiple phenotypes.
def decide(self, accepts, context_aware=False): """ Returns what (mimetype,format) the client wants to receive Parses the given Accept header and picks the best one that we know how to output Returns (mimetype, format) An empty Accept will default to rdf+xml An Accept with */* use rdf+xm...
Returns what (mimetype,format) the client wants to receive Parses the given Accept header and picks the best one that we know how to output Returns (mimetype, format) An empty Accept will default to rdf+xml An Accept with */* use rdf+xml unless a better match is found An Accept that ...
def sample(polygon, count, factor=1.5, max_iter=10): """ Use rejection sampling to generate random points inside a polygon. Parameters ----------- polygon : shapely.geometry.Polygon Polygon that will contain points count : int Number of points to return ...
Use rejection sampling to generate random points inside a polygon. Parameters ----------- polygon : shapely.geometry.Polygon Polygon that will contain points count : int Number of points to return factor : float How many points to test per loop...
def load_experiment(folder, return_path=False): '''load_experiment: reads in the config.json for a folder, returns None if not found. :param folder: full path to experiment folder :param return_path: if True, don't load the config.json, but return it ''' fullpath = os.path.abspath(folder) co...
load_experiment: reads in the config.json for a folder, returns None if not found. :param folder: full path to experiment folder :param return_path: if True, don't load the config.json, but return it
def addDataset(self, dataset): """ Creates a new dataset instance for this scene. :param dataset | <XChartDataset> :return <XChartDatasetItem> """ item = XChartDatasetItem() self.addItem(item) item.setDataset(dataset) ...
Creates a new dataset instance for this scene. :param dataset | <XChartDataset> :return <XChartDatasetItem>
def resize(self, container, height, width): """ Resize the tty session. Args: container (str or dict): The container to resize height (int): Height of tty session width (int): Width of tty session Raises: :py:class:`docker.errors.APIError...
Resize the tty session. Args: container (str or dict): The container to resize height (int): Height of tty session width (int): Width of tty session Raises: :py:class:`docker.errors.APIError` If the server returns an error.
def cli(ctx, comment, metadata=""): """Add a canned comment Output: A dictionnary containing canned comment description """ return ctx.gi.cannedcomments.add_comment(comment, metadata=metadata)
Add a canned comment Output: A dictionnary containing canned comment description
def p_null_assignment(self, t): '''null_assignment : IDENT EQ NULL''' self.accu.add(Term('obs_vlabel', [self.name,"gen(\""+t[1]+"\")","0"]))
null_assignment : IDENT EQ NULL
def hex_color(self, safe: bool = False) -> str: """Generate a random hex color. :param safe: Get safe Flat UI hex color. :return: Hex color code. :Example: #d8346b """ if safe: return self.random.choice(SAFE_COLORS) return '#{:06x}'.form...
Generate a random hex color. :param safe: Get safe Flat UI hex color. :return: Hex color code. :Example: #d8346b
def _SetupBotoConfig(self): """Set the boto config so GSUtil works with provisioned service accounts.""" project_id = self._GetNumericProjectId() try: boto_config.BotoConfig(project_id, debug=self.debug) except (IOError, OSError) as e: self.logger.warning(str(e))
Set the boto config so GSUtil works with provisioned service accounts.
def _jaccard_similarity(f1, f2, weight_func): """Calculate generalized Jaccard similarity of formulas. Returns the weighted similarity value or None if there is no overlap at all. If the union of the formulas has a weight of zero (i.e. the denominator in the Jaccard similarity is zero), a value of zero...
Calculate generalized Jaccard similarity of formulas. Returns the weighted similarity value or None if there is no overlap at all. If the union of the formulas has a weight of zero (i.e. the denominator in the Jaccard similarity is zero), a value of zero is returned.
def choice(self, obj): """ Overloads the choice method to add the position of the object in the tree for future sorting. """ tree_id = getattr(obj, self.queryset.model._mptt_meta.tree_id_attr, 0) left = getattr(obj, self.queryset.model._mptt_meta.left_attr, 0) ret...
Overloads the choice method to add the position of the object in the tree for future sorting.
def pop_group(self): """Terminates the redirection begun by a call to :meth:`push_group` or :meth:`push_group_with_content` and returns a new pattern containing the results of all drawing operations performed to the group. The :meth:`pop_group` method calls :meth:`restore`, ...
Terminates the redirection begun by a call to :meth:`push_group` or :meth:`push_group_with_content` and returns a new pattern containing the results of all drawing operations performed to the group. The :meth:`pop_group` method calls :meth:`restore`, (balancing a call to :meth:`...
def _visual_bounds_at(self, pos, node=None): """Find a visual whose bounding rect encompasses *pos*. """ if node is None: node = self.scene for ch in node.children: hit = self._visual_bounds_at(pos, ch) if hit is not None: ...
Find a visual whose bounding rect encompasses *pos*.
def compile_into_spirv(raw, stage, filepath, language="glsl", optimization='size', suppress_warnings=False, warnings_as_errors=False): """Compile shader code into Spir-V binary. This function uses shaderc to compile your glsl or hlsl code into Spir-V code. You ...
Compile shader code into Spir-V binary. This function uses shaderc to compile your glsl or hlsl code into Spir-V code. You can refer to the shaderc documentation. Args: raw (bytes): glsl or hlsl code (bytes format, not str) stage (str): Pipeline stage in ['vert', 'tesc', 'tese', 'geom', ...
def fetch(self): ''' Gives all the data it has stored, and remembers what it has given. Later we need to call commit() to actually remove the data from the cache. ''' if self._fetched is not None: raise RuntimeError('fetch() was called but the previous one has...
Gives all the data it has stored, and remembers what it has given. Later we need to call commit() to actually remove the data from the cache.
def build_launcher(self, clsname, kind=None): """import and instantiate a Launcher based on importstring""" try: klass = find_launcher_class(clsname, kind) except (ImportError, KeyError): self.log.fatal("Could not import launcher class: %r"%clsname) self.exit(...
import and instantiate a Launcher based on importstring
def _process_macro_default_arg(self): """Handle the bit after an '=' in a macro default argument. This is probably the trickiest thing. The goal here is to accept all strings jinja would accept and always handle block start/end correctly: It's fine to have false positives, jinja can fail...
Handle the bit after an '=' in a macro default argument. This is probably the trickiest thing. The goal here is to accept all strings jinja would accept and always handle block start/end correctly: It's fine to have false positives, jinja can fail later. Return True if there are more ar...
def get_order_history(self, market=None): """ Used to retrieve order trade history of account Endpoint: 1.1 /account/getorderhistory 2.0 /key/orders/getorderhistory or /key/market/GetOrderHistory :param market: optional a string literal for the market (ie. BTC-LTC). ...
Used to retrieve order trade history of account Endpoint: 1.1 /account/getorderhistory 2.0 /key/orders/getorderhistory or /key/market/GetOrderHistory :param market: optional a string literal for the market (ie. BTC-LTC). If omitted, will return for all markets :type...
def update_instance( self, instance, field_mask, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Updates an instance, and begins allocating or releasing resources as requeste...
Updates an instance, and begins allocating or releasing resources as requested. The returned ``long-running operation`` can be used to track the progress of updating the instance. If the named instance does not exist, returns ``NOT_FOUND``. Immediately upon completion of this request: ...
def complete(self, text: str) -> Iterable[str]: """Return an iterable of possible completions for the given text in this namespace.""" assert not text.startswith(":") if "/" in text: prefix, suffix = text.split("/", maxsplit=1) results = itertools.chain( ...
Return an iterable of possible completions for the given text in this namespace.
def bulk_create(self, objs, *args, **kwargs): """Insert many object at once.""" if hasattr(self.model, 'save_prep'): # Method from AbstractBaseModel. If the model class doesn't # subclass AbstractBaseModel, then don't call this. self.model.save_prep(instance_or_instan...
Insert many object at once.
def configure_client( cls, address: Union[str, Tuple[str, int], Path] = 'localhost', port: int = 6379, db: int = 0, password: str = None, ssl: Union[bool, str, SSLContext] = False, **client_args) -> Dict[str, Any]: """ Configure a Redis client. :param address...
Configure a Redis client. :param address: IP address, host name or path to a UNIX socket :param port: port number to connect to (ignored for UNIX sockets) :param db: database number to connect to :param password: password used if the server requires authentication :param ssl: on...
def import_source(self, sheet, source, delimiter=","): """ Function: Save original data into specific sheet, and try to translate data to float type Input: sheet: Must be a non exists sheet source: File path of source """ # check input ...
Function: Save original data into specific sheet, and try to translate data to float type Input: sheet: Must be a non exists sheet source: File path of source