code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def update(self): """Updates an instance within a project. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_update_instance] :end-before: [END bigtable_update_instance] .. note:: Updates any or all of the following values:...
Updates an instance within a project. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_update_instance] :end-before: [END bigtable_update_instance] .. note:: Updates any or all of the following values: ``display_name``...
def times(self, func, *args): """ Run a function **n** times. """ n = self.obj i = 0 while n is not 0: n -= 1 func(i) i += 1 return self._wrap(func)
Run a function **n** times.
def getConfig(self): """Return the configuration of the city. :return: configuration of the city. :rtype: dict. """ config = {} config["name"] = self.city config["intervals"] = self.__intervals config["last_date"] = self.__lastDay config["excluded...
Return the configuration of the city. :return: configuration of the city. :rtype: dict.
def getParameter(self, name, index=-1): """ Overrides :meth:`nupic.bindings.regions.PyRegion.PyRegion.getParameter`. """ if name == "patternCount": return self._knn._numPatterns elif name == "patternMatrix": return self._getPatternMatrix() elif name == "k": return self._knn.k ...
Overrides :meth:`nupic.bindings.regions.PyRegion.PyRegion.getParameter`.
def locate_key(self, key): """Get index location for the requested key. Parameters ---------- key : object Value to locate. Returns ------- loc : int or slice Location of `key` (will be slice if there are duplicate entries). Exam...
Get index location for the requested key. Parameters ---------- key : object Value to locate. Returns ------- loc : int or slice Location of `key` (will be slice if there are duplicate entries). Examples -------- >>> imp...
def check_status(status, expected, path, headers=None, resp_headers=None, body=None, extras=None): """Check HTTP response status is expected. Args: status: HTTP response status. int. expected: a list of expected statuses. A list of ints. path: filename or a path prefix. headers: HT...
Check HTTP response status is expected. Args: status: HTTP response status. int. expected: a list of expected statuses. A list of ints. path: filename or a path prefix. headers: HTTP request headers. resp_headers: HTTP response headers. body: HTTP response body. extras: extra info to be l...
def compat_serializer_attr(serializer, obj): """ Required only for DRF 3.1, which does not make dynamically added attribute available in obj in serializer. This is a quick solution but works without breajing anything. """ if DRFVLIST[0] == 3 and DRFVLIST[1] == 1: for i in serializer.instance...
Required only for DRF 3.1, which does not make dynamically added attribute available in obj in serializer. This is a quick solution but works without breajing anything.
def ensure_one_opt_multi_ifo(opt, parser, ifo, opt_list): """ Check that one and only one in the opt_list is defined in opt Parameters ---------- opt : object Result of option parsing parser : object OptionParser instance. opt_list : list of strings """ the_one = None ...
Check that one and only one in the opt_list is defined in opt Parameters ---------- opt : object Result of option parsing parser : object OptionParser instance. opt_list : list of strings
def sumvalues(self, q=0): """Sum of top q passowrd frequencies """ if q == 0: return self._totalf else: return -np.partition(-self._freq_list, q)[:q].sum()
Sum of top q passowrd frequencies
def restart(self, wait=True, timeout=None, wait_polling_interval=None): """Restart b2g, waiting for the adb connection to become stable. :param timeout: Maximum time to wait for restart. :param wait_polling_interval: Interval at which to poll for device readiness. """ self.stop(...
Restart b2g, waiting for the adb connection to become stable. :param timeout: Maximum time to wait for restart. :param wait_polling_interval: Interval at which to poll for device readiness.
def update_frequency(shell_ctx): """ updates the frequency from files """ frequency_path = os.path.join(shell_ctx.config.get_config_dir(), shell_ctx.config.get_frequency()) if os.path.exists(frequency_path): with open(frequency_path, 'r') as freq: try: frequency = json.lo...
updates the frequency from files
def get_translated_file(fapi, file_uri, locale, retrieval_type, include_original_strings, use_cache, cache_dir=None): """ Returns a translated file from smartling """ file_data = None cache_name = str(file_uri)+"."+str(locale)+"."+str(retrieval_type)+"."+str(include_original_strings) cache_file = os...
Returns a translated file from smartling
def second_order_score(y, mean, scale, shape, skewness): """ GAS Laplace Update term potentially using second-order information - native Python function Parameters ---------- y : float datapoint for the time series mean : float location parameter for the...
GAS Laplace Update term potentially using second-order information - native Python function Parameters ---------- y : float datapoint for the time series mean : float location parameter for the Laplace distribution scale : float scale parame...
def _nextOn(self, request): """ Formatted date/time of when this event (including any postponements) will next be on """ retval = None nextDt, event = self.__localAfterOrPostponedTo(timezone.localtime(), dt.time.min) ...
Formatted date/time of when this event (including any postponements) will next be on
def AND(cpu, dest, src): """ Logical AND. Performs a bitwise AND operation on the destination (first) and source (second) operands and stores the result in the destination operand location. Each bit of the result is set to 1 if both corresponding bits of the first and se...
Logical AND. Performs a bitwise AND operation on the destination (first) and source (second) operands and stores the result in the destination operand location. Each bit of the result is set to 1 if both corresponding bits of the first and second operands are 1; otherwise, it is set to ...
def save(self, directory, parameters='all'): """ Saves results to disk. Depending on which results are selected and if they exist, the following directories and files are created: * `powerflow_results` directory * `voltages_pu.csv` See :py:attr:`~pfa_v_m...
Saves results to disk. Depending on which results are selected and if they exist, the following directories and files are created: * `powerflow_results` directory * `voltages_pu.csv` See :py:attr:`~pfa_v_mag_pu` for more information. * `currents.csv` ...
def find_resources(self, rsrc_type, sort=None, yield_pages=False, **kwargs): """Find instances of `rsrc_type` that match the filter in `**kwargs`""" return rsrc_type.find(self, sort=sort, yield_pages=yield_pages, **kwargs)
Find instances of `rsrc_type` that match the filter in `**kwargs`
def discriminator(self, imgs, y): """ return a (b, 1) logits""" yv = y y = tf.reshape(y, [-1, 1, 1, 10]) with argscope(Conv2D, kernel_size=5, strides=1): l = (LinearWrap(imgs) .ConcatWith(tf.tile(y, [1, 28, 28, 1]), 3) .Conv2D('conv0', 11) ...
return a (b, 1) logits
def get_agent_data(self, queues=None, edge=None, edge_type=None, return_header=False): """Gets data from queues and organizes it by agent. If none of the parameters are given then data from every :class:`.QueueServer` is retrieved. Parameters ---------- queues : int or ...
Gets data from queues and organizes it by agent. If none of the parameters are given then data from every :class:`.QueueServer` is retrieved. Parameters ---------- queues : int or *array_like* (optional) The edge index (or an iterable of edge indices) identifying ...
def set_icon(self, icon_url): """Sets the icon_url for the message :param icon_url: (str) Icon URL :return: None """ log = logging.getLogger(self.cls_logger + '.set_icon') if not isinstance(icon_url, basestring): msg = 'icon_url arg must be a string' ...
Sets the icon_url for the message :param icon_url: (str) Icon URL :return: None
def detach_securitygroup_components(self, group_id, component_ids): """Detaches network components from a security group. :param int group_id: The ID of the security group :param list component_ids: The IDs of the network components to detach """ return self.security_group.detac...
Detaches network components from a security group. :param int group_id: The ID of the security group :param list component_ids: The IDs of the network components to detach
def path(): """ Detect config file path """ # Detect config directory try: directory = os.environ["DID_DIR"] except KeyError: directory = CONFIG # Detect config file (even before options are parsed) filename = "config" matched = re.search("...
Detect config file path
def exp(x, context=None): """ Return the exponential of x. """ return _apply_function_in_current_context( BigFloat, mpfr.mpfr_exp, (BigFloat._implicit_convert(x),), context, )
Return the exponential of x.
def _normalized_mutual_info_score(reference_indices, estimated_indices): """Compute the mutual information between two sequence labelings, adjusted for chance. Parameters ---------- reference_indices : np.ndarray Array of reference indices estimated_indices : np.ndarray Array o...
Compute the mutual information between two sequence labelings, adjusted for chance. Parameters ---------- reference_indices : np.ndarray Array of reference indices estimated_indices : np.ndarray Array of estimated indices Returns ------- nmi : float <= 1.0 Norm...
def _get_ipv4_from_binary(self, bin_addr): """Converts binary address to Ipv4 format.""" return socket.inet_ntop(socket.AF_INET, struct.pack("!L", bin_addr))
Converts binary address to Ipv4 format.
def encrypt(cls, private_key, password, kdf=None, iterations=None): ''' Creates a dictionary with an encrypted version of your private key. To import this keyfile into Ethereum clients like geth and parity: encode this dictionary with :func:`json.dumps` and save it to disk where your ...
Creates a dictionary with an encrypted version of your private key. To import this keyfile into Ethereum clients like geth and parity: encode this dictionary with :func:`json.dumps` and save it to disk where your client keeps key files. :param private_key: The raw private key :t...
def _log_task(self, task): """ Logs task record to file. `task` ``Task`` instance. """ if not task.duration: return self._setup_dir(task.base_dir) stats_dir = self._sdir(task.base_dir) duration = task.duration while d...
Logs task record to file. `task` ``Task`` instance.
def Update(self, filename, clean_lines, linenum, error): """Update nesting state with current line. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any err...
Update nesting state with current line. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
def _read_ancestry(file): """ Read and parse Ancestry.com file. http://www.ancestry.com Parameters ---------- file : str path to file Returns ------- pandas.DataFrame individual's genetic data normalized for use with `lineage` ...
Read and parse Ancestry.com file. http://www.ancestry.com Parameters ---------- file : str path to file Returns ------- pandas.DataFrame individual's genetic data normalized for use with `lineage` str name of data sou...
def add_node(self, node): """ Add a node to this network, let the node know which network it's on. """ if _debug: Network._debug("add_node %r", node) self.nodes.append(node) node.lan = self # update the node name if not node.name: node.name = '%s:%s' % (self...
Add a node to this network, let the node know which network it's on.
def _apply_default_values(catalog, default_values): """Aplica valores default a los campos de un catálogo. Si el campo está vacío, aplica el default. Si tiene un valor, deja el valor que estaba. Sólo soporta defaults para las siguientes clases: catalog dataset distribution f...
Aplica valores default a los campos de un catálogo. Si el campo está vacío, aplica el default. Si tiene un valor, deja el valor que estaba. Sólo soporta defaults para las siguientes clases: catalog dataset distribution field Args: catalog (dict): Un catálogo. ...
def _osx_skype_status(status, message): """ Updates status and message for Skype IM application on Mac OSX. `status` Status type. `message` Status message. """ # XXX: Skype has a bug with it's applescript support on Snow Leopard # where it will ignore the "n...
Updates status and message for Skype IM application on Mac OSX. `status` Status type. `message` Status message.
def full(self, filetype, **kwargs): """Return the full name of a given type of file. Parameters ---------- filetype : str File type parameter. Returns ------- full : str The full path to the file. """ # check if full alre...
Return the full name of a given type of file. Parameters ---------- filetype : str File type parameter. Returns ------- full : str The full path to the file.
def member_del(self, member_id, reconfig=True): """remove member from replica set Args: member_id - member index reconfig - is need reconfig replica return True if operation success otherwise False """ server_id = self._servers.host_to_server_id( ...
remove member from replica set Args: member_id - member index reconfig - is need reconfig replica return True if operation success otherwise False
def get_src_builders(self, env): """ Returns the list of source Builders for this Builder. This exists mainly to look up Builders referenced as strings in the 'BUILDER' variable of the construction environment and cache the result. """ memo_key = id(env) ...
Returns the list of source Builders for this Builder. This exists mainly to look up Builders referenced as strings in the 'BUILDER' variable of the construction environment and cache the result.
def compose(self, mapping): """Apply the ``compose`` method to all functions. Returns a new farray. """ items = [f.compose(mapping) for f in self._items] return self.__class__(items, self.shape, self.ftype)
Apply the ``compose`` method to all functions. Returns a new farray.
def _canceller_for(self, elts, event): """Obtains a cancellation function that removes elts. The returned cancellation function returns ``True`` if all elements was removed successfully from the _in_deque, and false if it was not. """ def canceller(): """Cancels subm...
Obtains a cancellation function that removes elts. The returned cancellation function returns ``True`` if all elements was removed successfully from the _in_deque, and false if it was not.
def handle_eclipses(self, expose_horizon=False, **kwargs): """ Detect the triangles at the horizon and the eclipsed triangles, handling any necessary subdivision. :parameter str eclipse_method: name of the algorithm to use to detect the horizon or eclipses (defaults to the v...
Detect the triangles at the horizon and the eclipsed triangles, handling any necessary subdivision. :parameter str eclipse_method: name of the algorithm to use to detect the horizon or eclipses (defaults to the value set by computeoptions) :parameter str subdiv_alg: name of the algo...
def srp1(*args, **kargs): """Send and receive packets at layer 2 and return only the first answer""" ans, _ = srp(*args, **kargs) if len(ans) > 0: return ans[0][1] else: return None
Send and receive packets at layer 2 and return only the first answer
def sample_zip(items_list, num_samples, allow_overflow=False, per_bin=1): """ Helper for sampling Given a list of lists, samples one item for each list and bins them into num_samples bins. If all sublists are of equal size this is equivilent to a zip, but otherewise consecutive bins will have monotonic...
Helper for sampling Given a list of lists, samples one item for each list and bins them into num_samples bins. If all sublists are of equal size this is equivilent to a zip, but otherewise consecutive bins will have monotonically less elemements # Doctest doesn't work with assertionerror #util...
def parse_client_table(redis_client): """Read the client table. Args: redis_client: A client to the primary Redis shard. Returns: A list of information about the nodes in the cluster. """ NIL_CLIENT_ID = ray.ObjectID.nil().binary() message = redis_client.execute_command("RAY.TA...
Read the client table. Args: redis_client: A client to the primary Redis shard. Returns: A list of information about the nodes in the cluster.
def split_words(sentence, modify=True, keep_shorts=False): """ Extract and yield the keywords from the sentence: - Drop keywords that are too short (keep_shorts=False) - Drop the accents (modify=True) - Make everything lower case (modify=True) - Try to separate the words as much as possible (usi...
Extract and yield the keywords from the sentence: - Drop keywords that are too short (keep_shorts=False) - Drop the accents (modify=True) - Make everything lower case (modify=True) - Try to separate the words as much as possible (using 2 list of separators, one being more complete than the others)
def infiles(fnames, progress, leave=True): """Get input file paths. Parameters ---------- fnames : `list` of `str` File paths. progress : `bool` Show progress bar. leave : `bool`, optional Leave progress bar (default: True). Returns ------- `generator` of `s...
Get input file paths. Parameters ---------- fnames : `list` of `str` File paths. progress : `bool` Show progress bar. leave : `bool`, optional Leave progress bar (default: True). Returns ------- `generator` of `str` Input file paths.
def delete(self): """ Remove the document and all of its bundles from ProvStore. .. warning:: Cannot be undone. """ if self.abstract: raise AbstractDocumentException() self._api.delete_document(self.id) self._id = None return True
Remove the document and all of its bundles from ProvStore. .. warning:: Cannot be undone.
def make_rundir(path): """When a path has not been specified, make the run directory. Creates a rundir with the following hierarchy: ./runinfo <- Home of all run directories |----000 |----001 <- Directories for each run | .... |----NNN Kwargs: - path...
When a path has not been specified, make the run directory. Creates a rundir with the following hierarchy: ./runinfo <- Home of all run directories |----000 |----001 <- Directories for each run | .... |----NNN Kwargs: - path (str): String path to a speci...
def create_shared_noise(count): """Create a large array of noise to be shared by all workers.""" seed = 123 noise = np.random.RandomState(seed).randn(count).astype(np.float32) return noise
Create a large array of noise to be shared by all workers.
def get_note_names(self): """Return a list with all the note names in the current container. Every name will only be mentioned once. """ res = [] for n in self.notes: if n.name not in res: res.append(n.name) return res
Return a list with all the note names in the current container. Every name will only be mentioned once.
def regionprops_3D(im): r""" Calculates various metrics for each labeled region in a 3D image. The ``regionsprops`` method in **skimage** is very thorough for 2D images, but is a bit limited when it comes to 3D images, so this function aims to fill this gap. Parameters ---------- im : ...
r""" Calculates various metrics for each labeled region in a 3D image. The ``regionsprops`` method in **skimage** is very thorough for 2D images, but is a bit limited when it comes to 3D images, so this function aims to fill this gap. Parameters ---------- im : array_like An imagin...
def load(self, response): '''Load the response and increment the counter. Args: response (:class:`.http.request.Response`): The response from a previous request. ''' self._response = response if self.next_location(raw=True): self._num_red...
Load the response and increment the counter. Args: response (:class:`.http.request.Response`): The response from a previous request.
def find_biomass_precursors(model, reaction): """ Return a list of all biomass precursors excluding ATP and H2O. Parameters ---------- reaction : cobra.core.reaction.Reaction The biomass reaction of the model under investigation. model : cobra.Model The metabolic model under inv...
Return a list of all biomass precursors excluding ATP and H2O. Parameters ---------- reaction : cobra.core.reaction.Reaction The biomass reaction of the model under investigation. model : cobra.Model The metabolic model under investigation. Returns ------- list Meta...
def _build_search(structured_query): """Construct search statment for db execution. Produces the search statement and argument dictionary to be executed by the DBAPI v2 execute method. For example, ``cursor.execute(*_build_search(query, weights))`` :param query: containing terms, filters, and sort...
Construct search statment for db execution. Produces the search statement and argument dictionary to be executed by the DBAPI v2 execute method. For example, ``cursor.execute(*_build_search(query, weights))`` :param query: containing terms, filters, and sorts. :type query: Query :param weights...
def make_tmp_dir(suffix="", prefix="tmp", dir=None): # pylint: disable=redefined-builtin """Make a temporary directory.""" if dir is None: return tempfile.mkdtemp(suffix, prefix, dir) else: while True: rand_term = random.randint(1, 9999) tmp_dir = os.path.join(dir, "%s%d%s" % (prefix, rand_te...
Make a temporary directory.
def forwards(self, orm): "Write your forwards methods here." for category in orm['document_library.DocumentCategory'].objects.all(): category.is_published = True category.save()
Write your forwards methods here.
def syllabify(self): """ Syllabifier module for Middle High German The algorithm works by applying the MOP(Maximal Onset Principle) on open syllables. For closed syllables, the legal partitions are checked and applied. The word is always returned in lowercase. Examples:...
Syllabifier module for Middle High German The algorithm works by applying the MOP(Maximal Onset Principle) on open syllables. For closed syllables, the legal partitions are checked and applied. The word is always returned in lowercase. Examples: >>> Word('entslâfen').syllab...
def create(self, name, cidr, **kwargs): """This function will create a user network. Within OpenStack, it will create a network and a subnet Within AWS, it will create a VPC and a subnet :param name: string :param cidr: string E.x: "10.0.0.0/24" :param kwargs: dict ...
This function will create a user network. Within OpenStack, it will create a network and a subnet Within AWS, it will create a VPC and a subnet :param name: string :param cidr: string E.x: "10.0.0.0/24" :param kwargs: dict :return: dict
def create_minimal_scaleio_cluster(self, mdmPassword, liaPassword): """ Using IM this method create a 3-node ScaleIO cluster with 2xMDM, 1xTB, 3x SDS (using /dev/sdb), 3x SDC """ """ self.read_cluster_config_from_disk("minimal-cluster.json") #self._cluster_config_cached.s...
Using IM this method create a 3-node ScaleIO cluster with 2xMDM, 1xTB, 3x SDS (using /dev/sdb), 3x SDC
def hittime(cls, timestamp=None, age=None, milliseconds=None): """ Returns an integer represeting the milliseconds offset for a given hit (relative to now) """ if isinstance(timestamp, (int, float)): return int(Time.milliseconds_offset(Time.from_unix(timestamp, milliseconds=milliseconds))) ...
Returns an integer represeting the milliseconds offset for a given hit (relative to now)
def encrypt(text, _key, salt=None): """ RETURN {"salt":s, "length":l, "data":d} -> JSON -> UTF8 """ if is_text(text): encoding = 'utf8' data = bytearray(text.encode("utf8")) elif is_binary(text): encoding = None if PY2: data = bytearray(text) else...
RETURN {"salt":s, "length":l, "data":d} -> JSON -> UTF8
def cycle_data(self, verbose=False, result_cycle=None, result_size=None, result_edges=None,changelog=True): """Get data from JIRA for cycle/flow times and story points size change. Build a numerically indexed data frame with the following 'fixed' columns: `key`, 'url', 'issue_type', `summary`, ...
Get data from JIRA for cycle/flow times and story points size change. Build a numerically indexed data frame with the following 'fixed' columns: `key`, 'url', 'issue_type', `summary`, `status`, and `resolution` from JIRA, as well as the value of any fields set in the `fields` dict in `s...
def _GetConfigValue(self, config_parser, section_name, value_name): """Retrieves a value from the config parser. Args: config_parser (ConfigParser): configuration parser. section_name (str): name of the section that contains the value. value_name (str): name of the value. Returns: ...
Retrieves a value from the config parser. Args: config_parser (ConfigParser): configuration parser. section_name (str): name of the section that contains the value. value_name (str): name of the value. Returns: object: configuration value or None if the value does not exists.
def wins(self, year): """Returns the # of regular season wins a team in a year. :year: The year for the season in question. :returns: The number of regular season wins. """ schedule = self.schedule(year) if schedule.empty: return np.nan return schedul...
Returns the # of regular season wins a team in a year. :year: The year for the season in question. :returns: The number of regular season wins.
def get_profile_data(self, raw_token): """Fetch user profile information.""" try: response = self.request('get', self.profile_url, token=raw_token) response.raise_for_status() except RequestException as e: logger.error('Unable to fetch user profile: {0}'.forma...
Fetch user profile information.
def encode(raw): """Encode SLIP message.""" return raw \ .replace(bytes([SLIP_ESC]), bytes([SLIP_ESC, SLIP_ESC_ESC])) \ .replace(bytes([SLIP_END]), bytes([SLIP_ESC, SLIP_ESC_END]))
Encode SLIP message.
def _push_writer(self): """push a capturing buffer onto this Context and return the new writer function.""" buf = util.FastEncodingBuffer() self._buffer_stack.append(buf) return buf.write
push a capturing buffer onto this Context and return the new writer function.
def from_dict(cls, tx, skip_schema_validation=True): """Transforms a Python dictionary to a Transaction object. Args: tx_body (dict): The Transaction to be transformed. Returns: :class:`~bigchaindb.common.transaction.Transaction` """ oper...
Transforms a Python dictionary to a Transaction object. Args: tx_body (dict): The Transaction to be transformed. Returns: :class:`~bigchaindb.common.transaction.Transaction`
def feature_info(self): """Retrieve dict<feature name, FeatureInfo>. Must first call Problem.get_hparams or Problem.dataset to have the problem's internal hparams already constructed. Returns: dict<feature name, FeatureInfo> """ if self._feature_info is not None: return self._featu...
Retrieve dict<feature name, FeatureInfo>. Must first call Problem.get_hparams or Problem.dataset to have the problem's internal hparams already constructed. Returns: dict<feature name, FeatureInfo>
def incremental_value(self, slip_moment, mmax, mag_value, bbar, dbar): """ Returns the incremental rate with Mmax = Mag_value """ delta_m = mmax - mag_value a_3 = self._get_a3(bbar, dbar, slip_moment, mmax) return a_3 * bbar * (np.exp(bbar * delta_m) - 1.0) * (delta_m > 0...
Returns the incremental rate with Mmax = Mag_value
def CountHuntFlows(self, hunt_id, filter_condition=db.HuntFlowsCondition.UNSET, cursor=None): """Counts hunt flows matching given conditions.""" hunt_id_int = db_utils.HuntIDToInt(hunt_id) query = ("SELECT COUNT(*) FROM flows " "FO...
Counts hunt flows matching given conditions.
def generate_pipeline_code(pipeline_tree, operators): """Generate code specific to the construction of the sklearn Pipeline. Parameters ---------- pipeline_tree: list List of operators in the current optimized pipeline Returns ------- Source code for the sklearn pipeline """ ...
Generate code specific to the construction of the sklearn Pipeline. Parameters ---------- pipeline_tree: list List of operators in the current optimized pipeline Returns ------- Source code for the sklearn pipeline
def _get_delay(self, userdelay, frameslist): """ Get the appropriate delay value to use, trying in this order: userdelay frameslist.delay default_delay The user can override the frameslist's delay by specifiying a value, and if neither are...
Get the appropriate delay value to use, trying in this order: userdelay frameslist.delay default_delay The user can override the frameslist's delay by specifiying a value, and if neither are given the default is used.
def execute(self): """ Execute the search and return the response. """ r = self._s.execute() r._faceted_search = self return r
Execute the search and return the response.
def wheelEvent(self, ev, axis=None): """Reacts to mouse wheel movement, custom behaviour switches zoom axis when ctrl is pressed, and sets the locus of zoom, if zeroWheel is set.""" state = None # ctrl reverses mouse operation axis if ev.modifiers() == QtCore.Qt.ControlMo...
Reacts to mouse wheel movement, custom behaviour switches zoom axis when ctrl is pressed, and sets the locus of zoom, if zeroWheel is set.
def apply_motion_tracks(self, tracks, accuracy=0.004): """ Similar to click but press the screen for the given time interval and then release Args: tracks (:py:obj:`list`): list of :py:class:`poco.utils.track.MotionTrack` object accuracy (:py:obj:`float`): motion accuracy ...
Similar to click but press the screen for the given time interval and then release Args: tracks (:py:obj:`list`): list of :py:class:`poco.utils.track.MotionTrack` object accuracy (:py:obj:`float`): motion accuracy for each motion steps in normalized coordinate metrics.
def has_axis(self, axis): """Check if the event has a valid value for the given axis. If this method returns True for an axis and :meth:`get_axis_value` returns a value of 0, the event is a scroll stop event. For pointer events that are not of type :attr:`~libinput.constant.EventType.POINTER_AXIS`, this met...
Check if the event has a valid value for the given axis. If this method returns True for an axis and :meth:`get_axis_value` returns a value of 0, the event is a scroll stop event. For pointer events that are not of type :attr:`~libinput.constant.EventType.POINTER_AXIS`, this method raises :exc:`AttributeErr...
def GetValueByName(self, name): """Retrieves a value by name. Value names are not unique and pyregf provides first match for the value. Args: name (str): name of the value or an empty string for the default value. Returns: WinRegistryValue: Windows Registry value if a corresponding value ...
Retrieves a value by name. Value names are not unique and pyregf provides first match for the value. Args: name (str): name of the value or an empty string for the default value. Returns: WinRegistryValue: Windows Registry value if a corresponding value was found or None if not.
def visit_slice(self, node): """return an astroid.Slice node as string""" lower = node.lower.accept(self) if node.lower else "" upper = node.upper.accept(self) if node.upper else "" step = node.step.accept(self) if node.step else "" if step: return "%s:%s:%s" % (lower...
return an astroid.Slice node as string
def is_invalid_params_py3(func, *args, **kwargs): """ Use inspect.signature instead of inspect.getargspec or inspect.getfullargspec (based on inspect.signature itself) as it provides more information about function parameters. .. versionadded: 1.11.2 """ signature = inspect.signature(func)...
Use inspect.signature instead of inspect.getargspec or inspect.getfullargspec (based on inspect.signature itself) as it provides more information about function parameters. .. versionadded: 1.11.2
def calculate_concordance(graph: BELGraph, key: str, cutoff: Optional[float] = None, use_ambiguous: bool = False) -> float: """Calculates network-wide concordance. Assumes data already annotated with given key :param graph: A BEL graph :param key: The node data dictionary key...
Calculates network-wide concordance. Assumes data already annotated with given key :param graph: A BEL graph :param key: The node data dictionary key storing the logFC :param cutoff: The optional logFC cutoff for significance :param use_ambiguous: Compare to ambiguous edges as well
def get_instance(self, payload): """ Build an instance of VariableInstance :param dict payload: Payload response from the API :returns: twilio.rest.serverless.v1.service.environment.variable.VariableInstance :rtype: twilio.rest.serverless.v1.service.environment.variable.Variabl...
Build an instance of VariableInstance :param dict payload: Payload response from the API :returns: twilio.rest.serverless.v1.service.environment.variable.VariableInstance :rtype: twilio.rest.serverless.v1.service.environment.variable.VariableInstance
def _create_authority_file(self, file_path): """ Create a new LSID authority file at the indicated location :param file_path: location of LSID authority file """ parent_dir = os.path.dirname(os.path.realpath(file_path)) # Create the parent directory if it does not exist ...
Create a new LSID authority file at the indicated location :param file_path: location of LSID authority file
def image_information_response(self): """Parse image information request and create response.""" dr = degraded_request(self.identifier) if (dr): self.logger.info("image_information: degraded %s -> %s" % (self.identifier, dr)) self.degraded = s...
Parse image information request and create response.
def wait_for_service_endpoint(service_name, timeout_sec=120): """Checks the service url if available it returns true, on expiration it returns false""" master_count = len(get_all_masters()) return time_wait(lambda: service_available_predicate(service_name), timeout_seconds=timeout_...
Checks the service url if available it returns true, on expiration it returns false
def get_config_directory(override_files=False): """ Looks for the most specific configuration directory possible, in order to load individual configuration files. """ if override_files: possible_dirs = [override_files] else: xdg_config_home = os.environ.get('XDG_CONFIG_HOME') or...
Looks for the most specific configuration directory possible, in order to load individual configuration files.
def page_not_found(request, template_name='404.html'): """ Default 404 handler. Templates: :template:`404.html` Context: request_path The path of the requested URL (e.g., '/app/pages/bad_page/') """ response = render_in_page(request, template_name) if response: ...
Default 404 handler. Templates: :template:`404.html` Context: request_path The path of the requested URL (e.g., '/app/pages/bad_page/')
def status(self): """See :py:meth:`~stash.repository.Repository.status`.""" result = set() for line in self._execute('svn stat')[1].splitlines(): if line[0] == '?': result.add((FileStatus.Added, line[2:].strip())) elif line[0] == '!': resul...
See :py:meth:`~stash.repository.Repository.status`.
def wait_for_fresh_games(self, poll_interval=15.0): """Block caller until required new games have been played. Args: poll_interval: number of seconds to wait between checks If the cell `table_state=metadata:wait_for_game_number` exists, then block the caller, checking every ...
Block caller until required new games have been played. Args: poll_interval: number of seconds to wait between checks If the cell `table_state=metadata:wait_for_game_number` exists, then block the caller, checking every `poll_interval` seconds, until `table_state=metadata:ga...
def extract(self, obj, bypass_ref=False): """ Extract subelement from obj, according to pointer. It assums that document is the object. :param obj: the object source :param bypass_ref: disable JSON Reference errors """ return self.pointer.extract(obj, bypass_ref)
Extract subelement from obj, according to pointer. It assums that document is the object. :param obj: the object source :param bypass_ref: disable JSON Reference errors
def read_until(self, s, echo=None): """ Read until a certain string is encountered.. Args: s(bytes): The string to wait for. echo(bool): Whether to write the read data to stdout. Returns: bytes: The data up to and including *s*. Raises: ...
Read until a certain string is encountered.. Args: s(bytes): The string to wait for. echo(bool): Whether to write the read data to stdout. Returns: bytes: The data up to and including *s*. Raises: EOFError: If the channel was closed.
def get_appliance_by_name(self, appliance_name): """ Gets the particular Image Streamer resource based on its name. Args: appliance_name: The Image Streamer resource name. Returns: dict: Image Streamer resource. """ appliances = ...
Gets the particular Image Streamer resource based on its name. Args: appliance_name: The Image Streamer resource name. Returns: dict: Image Streamer resource.
def parse_create(prs, conn): """Create record. Arguments: prs: parser object of argparse conn: dictionary of connection information """ prs_create = prs.add_parser( 'create', help='create record of specific zone') set_option(prs_create, 'domain') conn_options(prs_creat...
Create record. Arguments: prs: parser object of argparse conn: dictionary of connection information
def req_string(self, model): """ Return string describing model and version requirement. """ if model not in self.models: model = self.models if self.min_ykver and self.max_ykver: return "%s %d.%d..%d.%d" % (model, \ self.min_ykv...
Return string describing model and version requirement.
def geotiff_tags(self): """Return consolidated metadata from GeoTIFF tags as dict.""" if not self.is_geotiff: return None tags = self.tags gkd = tags['GeoKeyDirectoryTag'].value if gkd[0] != 1: log.warning('GeoTIFF tags: invalid GeoKeyDirectoryTag') ...
Return consolidated metadata from GeoTIFF tags as dict.
def hash_vector(self, v, querying=False): """ Hashes the vector and returns the bucket key as string. """ bucket_keys = [] if querying: # If we are querying, use the bucket key map for lshash in self.child_hashes: # Get regular bucket key...
Hashes the vector and returns the bucket key as string.
def plot(self, **plot_kwargs: Any) -> None: """Plots excited state probability vs the Rabi angle (angle of rotation around the x-axis). Args: **plot_kwargs: Arguments to be passed to matplotlib.pyplot.plot. """ fig = plt.figure() plt.plot(self._rabi_angles, s...
Plots excited state probability vs the Rabi angle (angle of rotation around the x-axis). Args: **plot_kwargs: Arguments to be passed to matplotlib.pyplot.plot.
def intersection(self): """Compute the intersection with the given MOC. This command takes the name of a MOC file and forms the intersection of the running MOC with that file. :: pymoctool a.fits --intersection b.fits --output intersection.fits """ if self...
Compute the intersection with the given MOC. This command takes the name of a MOC file and forms the intersection of the running MOC with that file. :: pymoctool a.fits --intersection b.fits --output intersection.fits
def mock_import(do_not_mock=None, **mock_kwargs): """ Mocks import statements by ignoring ImportErrors and replacing the missing module with a Mock. :param str|unicode|list[str|unicode] do_not_mock: names of modules that should exists, and an ImportError could be raised for. :param mock_kwa...
Mocks import statements by ignoring ImportErrors and replacing the missing module with a Mock. :param str|unicode|list[str|unicode] do_not_mock: names of modules that should exists, and an ImportError could be raised for. :param mock_kwargs: kwargs for MagicMock object. :return: patch object
def s3_upload(self, keyname, absolute_path): """ Upload a file to s3 """ mimetype = mimetypes.guess_type(absolute_path) options = {'Content-Type': mimetype[0]} if mimetype[0] is not None and mimetype[0].startswith('text/'): upload = open(absolute_path, 'rb') ...
Upload a file to s3
def cleanup_codra_edus(self): """Remove leading/trailing '_!' from CODRA EDUs and unescape its double quotes.""" for leafpos in self.tree.treepositions('leaves'): edu_str = self.tree[leafpos] edu_str = EDU_START_RE.sub("", edu_str) edu_str = TRIPLE_ESCAPE_RE.sub('"',...
Remove leading/trailing '_!' from CODRA EDUs and unescape its double quotes.
def render_text(self, request, instance, context): """ Custom rendering function for HTML output """ render_template = self.get_render_template(request, instance, email_format='text') if not render_template: # If there is no TEXT variation, create it by removing the H...
Custom rendering function for HTML output
def get_profile(self, img_type, coordinate, num_points): ''' Extract a profile from (lat1,lon1) to (lat2,lon2) Args: img_type (str): Either lola or wac. coordinate (float,float,float,flaot): A tupple ``(lon0,lon1,lat0,lat1)`` with: - lon0: First ...
Extract a profile from (lat1,lon1) to (lat2,lon2) Args: img_type (str): Either lola or wac. coordinate (float,float,float,flaot): A tupple ``(lon0,lon1,lat0,lat1)`` with: - lon0: First point longitude - lat0: First point latitude ...