code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def toggle_object_status(self, objname): """ Toggle boolean-valued sensor status between ``True`` and ``False``. """ o = getattr(self.system, objname) o.status = not o.status self.system.flush() return o.status
Toggle boolean-valued sensor status between ``True`` and ``False``.
def _find_nn_pos_before_site(self, siteindex): """ Returns index of nearest neighbor atoms. """ alldist = [(self._mol.get_distance(siteindex, i), i) for i in range(siteindex)] alldist = sorted(alldist, key=lambda x: x[0]) return [d[1] for d in alldist]
Returns index of nearest neighbor atoms.
def iter_nearest_neighbours(umis, substr_idx): ''' Added by Matt 06/05/17 use substring dict to get (approximately) all the nearest neighbours to each in a set of umis. ''' for i, u in enumerate(umis, 1): neighbours = set() for idx, substr_map in substr_idx.items(): u...
Added by Matt 06/05/17 use substring dict to get (approximately) all the nearest neighbours to each in a set of umis.
def create_api_interface_request(self): """Get an instance of Api Vip Requests services facade.""" return ApiInterfaceRequest( self.networkapi_url, self.user, self.password, self.user_ldap)
Get an instance of Api Vip Requests services facade.
def score(self, X, y, sample_weight=None): """Returns the mean accuracy on the given test data and labels. NOTE: In the condition of sklearn.svm.SVC with precomputed kernel when the kernel matrix is computed portion by portion, the function will ignore the first input argument X. ...
Returns the mean accuracy on the given test data and labels. NOTE: In the condition of sklearn.svm.SVC with precomputed kernel when the kernel matrix is computed portion by portion, the function will ignore the first input argument X. Parameters ---------- X: list of tu...
def cross_chan_coherence(st1, st2, allow_shift=False, shift_len=0.2, i=0, xcorr_func='time_domain'): """ Calculate cross-channel coherency. Determine the cross-channel coherency between two streams of multichannel seismic data. :type st1: obspy.core.stream.Stream :para...
Calculate cross-channel coherency. Determine the cross-channel coherency between two streams of multichannel seismic data. :type st1: obspy.core.stream.Stream :param st1: Stream one :type st2: obspy.core.stream.Stream :param st2: Stream two :type allow_shift: bool :param allow_shift: ...
def parse_import_directory(self, rva, size, dllnames_only=False): """Walk and parse the import directory.""" import_descs = [] error_count = 0 while True: try: # If the RVA is invalid all would blow up. Some EXEs seem to be # specially nasty ...
Walk and parse the import directory.
def can_modify_objective_hierarchy(self): """Tests if this user can change the hierarchy. A return of true does not guarantee successful authorization. A return of false indicates that it is known performing any update will result in a PermissionDenied. This is intended as a hint to ...
Tests if this user can change the hierarchy. A return of true does not guarantee successful authorization. A return of false indicates that it is known performing any update will result in a PermissionDenied. This is intended as a hint to an application that may opt not to offer these o...
def _check_action(action): """check for invalid actions""" if isinstance(action, types.StringTypes): action = action.lower() if action not in ['learn', 'forget', 'report', 'revoke']: raise SpamCError('The action option is invalid') return action
check for invalid actions
def closeTab(self, item): """ Requests a close for the inputed tab item. :param item | <XViewPanelItem> """ index = self.indexOf(item) if index != -1: self.tabCloseRequested.emit(index)
Requests a close for the inputed tab item. :param item | <XViewPanelItem>
def filter_validate_response(get_response, params): """ This filter process the returned response. It does 2 things: - If the response is a ``sanic.response.HTTPResponse`` and not a :class:`rafter.http.Response`, return it immediately. - It processes, validates and serializes this response when a...
This filter process the returned response. It does 2 things: - If the response is a ``sanic.response.HTTPResponse`` and not a :class:`rafter.http.Response`, return it immediately. - It processes, validates and serializes this response when a schema is provided. That means that you can always r...
def tagBlocks(self): ''' tagBlocks - Property. Returns all the blocks which are direct children of this node, where that block is a tag (not text) NOTE: This is similar to .children , and you should probably use .children instead except within this class its...
tagBlocks - Property. Returns all the blocks which are direct children of this node, where that block is a tag (not text) NOTE: This is similar to .children , and you should probably use .children instead except within this class itself @return list<AdvancedTag...
def salt_ssh_create_dirs(self): """ Creates the `salt-ssh` required directory structure """ logger.debug('Creating salt-ssh dirs into: %s', self.settings_dir) utils.create_dir(os.path.join(self.settings_dir, 'salt')) utils.create_dir(os.path.join(self.settings_dir, 'pilla...
Creates the `salt-ssh` required directory structure
def key_validation_check(tweet_keys_list, superset_keys, minset_keys): """ Validates the keys present in a Tweet. Args: tweet_keys_list (list): the keys present in a tweet superset_keys (set): the set of all possible keys for a tweet minset_keys (set): the set of minimal keys expect...
Validates the keys present in a Tweet. Args: tweet_keys_list (list): the keys present in a tweet superset_keys (set): the set of all possible keys for a tweet minset_keys (set): the set of minimal keys expected in a tweet. Returns: 0 if no errors Raises: Unexpected...
def set_node_attributes(self): """ Replicates molecule site properties (specie, coords, etc.) in the MoleculeGraph. :return: """ species = {} coords = {} properties = {} for node in self.graph.nodes(): species[node] = self.molecule[no...
Replicates molecule site properties (specie, coords, etc.) in the MoleculeGraph. :return:
def query_single(self, object_type, url_params, query_params=None): # type: (str, list, dict) -> dict """ Query for a single object. :param object_type: string query type (e.g., "users" or "groups") :param url_params: required list of strings to provide as additional URL componen...
Query for a single object. :param object_type: string query type (e.g., "users" or "groups") :param url_params: required list of strings to provide as additional URL components :param query_params: optional dictionary of query options :return: the found object (a dictionary), which is em...
def is_serializable_type(type_): """Return `True` if the given type's instances conform to the Serializable protocol. :rtype: bool """ if not inspect.isclass(type_): return Serializable.is_serializable(type_) return issubclass(type_, Serializable) or hasattr(type_, '_asdict')
Return `True` if the given type's instances conform to the Serializable protocol. :rtype: bool
def _display_stream(normalized_data, stream): """ print stream message from docker-py stream. """ try: stream.write(normalized_data['stream']) except UnicodeEncodeError: stream.write(normalized_data['stream'].encode("utf-8"))
print stream message from docker-py stream.
def get_annotated_data_x_y(timestamps, data, lbls): """ DOESN'T work with OVERLAPPING labels :param timestamps: :param data: :param lbls: :return: """ timestamps = np.array(timestamps) timestamp_step = timestamps[3]-timestamps[2] current...
DOESN'T work with OVERLAPPING labels :param timestamps: :param data: :param lbls: :return:
def post(self, request, *args, **kwargs): """ Handles POST requests. """ return self.approve(request, *args, **kwargs)
Handles POST requests.
def ip_address(): """Get the IP address used for public connections.""" s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # 8.8.8.8 is the google public DNS s.connect(("8.8.8.8", 53)) ip = s.getsockname()[0] s.close() return ip
Get the IP address used for public connections.
def get_temporary_filename(extension="", use_program_temp_dir=True): """Return the string for a temporary file with the given extension or suffix. For a file extension like .pdf the dot should also be in the passed string. Caller is expected to open and close it as necessary and call os.remove on it after...
Return the string for a temporary file with the given extension or suffix. For a file extension like .pdf the dot should also be in the passed string. Caller is expected to open and close it as necessary and call os.remove on it after finishing with it. (Note the entire programTempDir will be deleted on ...
def random(cls, L=1, avg_mu=1.0, alphabet='nuc', pi_dirichlet_alpha=1, W_dirichlet_alpha=3.0, mu_gamma_alpha=3.0): """ Creates a random GTR model Parameters ---------- mu : float Substitution rate alphabet : str Alphabet name (s...
Creates a random GTR model Parameters ---------- mu : float Substitution rate alphabet : str Alphabet name (should be standard: 'nuc', 'nuc_gap', 'aa', 'aa_gap')
def _maxlength(X): """ Returns the maximum length of signal trajectories X """ N = 0 for x in X: if len(x) > N: N = len(x) return N
Returns the maximum length of signal trajectories X
def dictToH5(h5, d, link_copy=False): """ Save a dictionary into an hdf5 file h5py is not capable of handling dictionaries natively""" global _array_cache _array_cache = dict() h5 = h5py.File(h5, mode="w") dictToH5Group(d, h5["/"], link_copy=link_copy) h5.close() _array_cache = dict(...
Save a dictionary into an hdf5 file h5py is not capable of handling dictionaries natively
def short_repr(obj, noneAsNA=False): '''Return a short representation of obj for clarity.''' if obj is None: return 'unspecified' if noneAsNA else 'None' elif isinstance(obj, str) and len(obj) > 80: return '{}...{}'.format(obj[:60].replace('\n', '\\n'), obj[-2...
Return a short representation of obj for clarity.
def Expand(instring, noerror=0): """ Expand a string with embedded IRAF variables (IRAF virtual filename). Allows comma-separated lists. Also uses os.path.expanduser to replace '~' symbols. Set the noerror flag to silently replace undefined variables with just the variable name or null (so Ex...
Expand a string with embedded IRAF variables (IRAF virtual filename). Allows comma-separated lists. Also uses os.path.expanduser to replace '~' symbols. Set the noerror flag to silently replace undefined variables with just the variable name or null (so Expand('abc$def') = 'abcdef' and Expand('(a...
def unread_all(self, user=None): """ Marks all notifications as unread for a user (if supplied) :param user: Notification recipient. :return: Updates QuerySet as unread. """ qs = self.read() if user: qs = qs.filter(recipient=user) qs.update(r...
Marks all notifications as unread for a user (if supplied) :param user: Notification recipient. :return: Updates QuerySet as unread.
def clean(context, days_ago, yes): """Clean up files from "old" analyses runs.""" number_of_days_ago = dt.datetime.now() - dt.timedelta(days=days_ago) analyses = context.obj['store'].analyses( status='completed', before=number_of_days_ago, deleted=False, ) for analysis_obj in...
Clean up files from "old" analyses runs.
def _calculate_rotation_angle(reg_coordinate_frame, header): """Calculates the rotation angle from the region to the header's frame This attempts to be compatible with the implementation used by SAOImage DS9. In particular, this measures the rotation of the north axis as measured at the center of the i...
Calculates the rotation angle from the region to the header's frame This attempts to be compatible with the implementation used by SAOImage DS9. In particular, this measures the rotation of the north axis as measured at the center of the image, and therefore requires a `~astropy.io.fits.Header` object ...
def remove(self, spam=False): """Remove object. This is the moderator version of delete. The object is removed from the subreddit listings and placed into the spam listing. If spam is set to True, then the automatic spam filter will try to remove objects with similar attributes in the f...
Remove object. This is the moderator version of delete. The object is removed from the subreddit listings and placed into the spam listing. If spam is set to True, then the automatic spam filter will try to remove objects with similar attributes in the future. :returns: The json respon...
def write_string_on_file_between_markers(filename: str, string: str, marker: str): r"""Write the table of contents on a single file. :parameter filename: the file that needs to be read or modified. :parameter string: the string that will be written on the file. ...
r"""Write the table of contents on a single file. :parameter filename: the file that needs to be read or modified. :parameter string: the string that will be written on the file. :parameter marker: a marker that will identify the start and the end of the string. :type filenames: str :type ...
def build_result_metadata(self, data=None, args=None): """ collect metadata into this object :param data: dict :param args: build from args instead of data """ data = data if data else self._build_result_metainfo(args) if data.get("build_branch"): sel...
collect metadata into this object :param data: dict :param args: build from args instead of data
def matches(self, object): """ <Purpose> Return True if 'object' matches this schema, False if it doesn't. If the caller wishes to signal an error on a failed match, check_match() should be called, which will raise a 'exceptions.FormatError' exception. """ try: self.check_match(...
<Purpose> Return True if 'object' matches this schema, False if it doesn't. If the caller wishes to signal an error on a failed match, check_match() should be called, which will raise a 'exceptions.FormatError' exception.
def from_rfc(datestring, use_dateutil=True): """Parse a RFC822-formatted datetime string and return a datetime object. Use dateutil's parser if possible. https://stackoverflow.com/questions/885015/how-to-parse-a-rfc-2822-date-time-into-a-python-datetime """ # Use dateutil's parser if possible ...
Parse a RFC822-formatted datetime string and return a datetime object. Use dateutil's parser if possible. https://stackoverflow.com/questions/885015/how-to-parse-a-rfc-2822-date-time-into-a-python-datetime
def iterator_zip(variables: VarType, parent: str = None) -> Iterable[VarMatrix]: """Apply the zip operator to a set of variables. This uses the python zip iterator to combine multiple lists of variables such that the nth variable in each list is aligned. Args: variables: The variables object ...
Apply the zip operator to a set of variables. This uses the python zip iterator to combine multiple lists of variables such that the nth variable in each list is aligned. Args: variables: The variables object parent: Unused
def from_shapely(sgeom, srid=None): """ Create a Geometry from a Shapely geometry and the specified SRID. The Shapely geometry will not be modified. """ if SHAPELY: WKBWriter.defaults["include_srid"] = True if srid: lgeos.GEOSSetSRID(sgeom...
Create a Geometry from a Shapely geometry and the specified SRID. The Shapely geometry will not be modified.
def load_roster(self, source): """Load roster from an XML file. Can be used before the connection is started to load saved roster copy, for efficient retrieval of versioned roster. :Parameters: - `source`: file name or a file object :Types: - `source`: `...
Load roster from an XML file. Can be used before the connection is started to load saved roster copy, for efficient retrieval of versioned roster. :Parameters: - `source`: file name or a file object :Types: - `source`: `str` or file-like object
def collate_tensors(batch, stack_tensors=torch.stack): """ Collate a list of type ``k`` (dict, namedtuple, list, etc.) with tensors. Inspired by: https://github.com/pytorch/pytorch/blob/master/torch/utils/data/_utils/collate.py#L31 Args: batch (list of k): List of rows of type ``k``. s...
Collate a list of type ``k`` (dict, namedtuple, list, etc.) with tensors. Inspired by: https://github.com/pytorch/pytorch/blob/master/torch/utils/data/_utils/collate.py#L31 Args: batch (list of k): List of rows of type ``k``. stack_tensors (callable): Function to stack tensors into a batch...
def assemble_buffer(self, buf_header, buf_payload): ''' Add a buffer header and payload that we read from the socket. This differs from add_buffer() because we're validating vs. the header's num_buffers, instead of filling in the header. Args: buf_header (``JSON``) : a buff...
Add a buffer header and payload that we read from the socket. This differs from add_buffer() because we're validating vs. the header's num_buffers, instead of filling in the header. Args: buf_header (``JSON``) : a buffer header buf_payload (``JSON`` or bytes) : a buffer...
def addNodeToGraph(nodeName, graphFileHandle, label, width=0.3, height=0.3, shape="circle", colour="black", fontsize=14): """Adds a node to the graph. """ graphFileHandle.write("node[width=%s,height=%s,shape=%s,colour=%s,fontsize=%s];\n" % (width, height, shape, colour, fontsize)) graphFileHandle.write(...
Adds a node to the graph.
def etag(self): """ Get the ETag option of the message. :rtype: list :return: the ETag values or [] if not specified by the request """ value = [] for option in self.options: if option.number == defines.OptionRegistry.ETAG.number: valu...
Get the ETag option of the message. :rtype: list :return: the ETag values or [] if not specified by the request
def DeserializeFromDB(buffer): """ Deserialize full object. Args: buffer (bytes, bytearray, BytesIO): (Optional) data to create the stream from. Returns: StorageItem: """ m = StreamManager.GetStream(buffer) reader = BinaryReader(m) ...
Deserialize full object. Args: buffer (bytes, bytearray, BytesIO): (Optional) data to create the stream from. Returns: StorageItem:
def calculate_item_depth(self, tree_alias, item_id, depth=0): """Calculates depth of the item in the tree. :param str|unicode tree_alias: :param int item_id: :param int depth: :rtype: int """ item = self.get_item_by_id(tree_alias, item_id) if hasattr(ite...
Calculates depth of the item in the tree. :param str|unicode tree_alias: :param int item_id: :param int depth: :rtype: int
def delete_transfer_job(self, job_name, project_id): """ Deletes a transfer job. This is a soft delete. After a transfer job is deleted, the job and all the transfer executions are subject to garbage collection. Transfer jobs become eligible for garbage collection 30 days after s...
Deletes a transfer job. This is a soft delete. After a transfer job is deleted, the job and all the transfer executions are subject to garbage collection. Transfer jobs become eligible for garbage collection 30 days after soft delete. :param job_name: (Required) Name of the job to be de...
def get_sources_by_position(self, skydir, dist, min_dist=None, square=False, coordsys='CEL'): """Retrieve sources within a certain angular distance of a sky coordinate. This function supports two types of geometric selections: circular (square=False) and square (...
Retrieve sources within a certain angular distance of a sky coordinate. This function supports two types of geometric selections: circular (square=False) and square (square=True). The circular selection finds all sources with a given angular distance of the target position. The square ...
def parse_command_line(self) -> Tuple[List[ServerConnectivityTester], List[ServerStringParsingError], Any]: """Parses the command line used to launch SSLyze. """ (args_command_list, args_target_list) = self._parser.parse_args() if args_command_list.update_trust_stores: # Jus...
Parses the command line used to launch SSLyze.
def _get_properties(self, logical_id): """ Returns the properties of resource with given logical ID. If a resource is not found, then it returns an empty data. Parameters ---------- logical_id : str Logical ID of the resource Returns ------- ...
Returns the properties of resource with given logical ID. If a resource is not found, then it returns an empty data. Parameters ---------- logical_id : str Logical ID of the resource Returns ------- samcli.commands.local.lib.sam_api_provider.ApiColle...
def _set_microcode(self, v, load=False): """ Setter method for microcode, mapped from YANG variable /firmware/peripheral_update/microcode (container) If this variable is read-only (config: false) in the source YANG file, then _set_microcode is considered as a private method. Backends looking to popu...
Setter method for microcode, mapped from YANG variable /firmware/peripheral_update/microcode (container) If this variable is read-only (config: false) in the source YANG file, then _set_microcode is considered as a private method. Backends looking to populate this variable should do so via calling thisO...
def specwindow_lsp_value(times, mags, errs, omega): '''This calculates the peak associated with the spectral window function for times and at the specified omega. NOTE: this is classical Lomb-Scargle, not the Generalized Lomb-Scargle. `mags` and `errs` are silently ignored since we're calculating t...
This calculates the peak associated with the spectral window function for times and at the specified omega. NOTE: this is classical Lomb-Scargle, not the Generalized Lomb-Scargle. `mags` and `errs` are silently ignored since we're calculating the periodogram of the observing window function. These are ...
def send_key(self, key, repeat=1): """ Send a keyboard event Usage: C{keyboard.send_key(key, repeat=1)} @param key: they key to be sent (e.g. "s" or "<enter>") @param repeat: number of times to repeat the key event """ for _ in range(repe...
Send a keyboard event Usage: C{keyboard.send_key(key, repeat=1)} @param key: they key to be sent (e.g. "s" or "<enter>") @param repeat: number of times to repeat the key event
def ytdl_progress_hook(self, d): """Called when youtube-dl updates progress""" if d['status'] == 'downloading': self.play_empty() if "elapsed" in d: if d["elapsed"] > self.current_download_elapsed + 4: self.current_download_elapsed = d["elapse...
Called when youtube-dl updates progress
def symmetry_normalised_reflections(self, hkl): """Returns an array of same size as *hkl*, containing the corresponding symmetry-equivalent reflections of lowest indices. Example: >>> from ase.lattice.spacegroup import Spacegroup >>> sg = Spacegroup(225) # fcc ...
Returns an array of same size as *hkl*, containing the corresponding symmetry-equivalent reflections of lowest indices. Example: >>> from ase.lattice.spacegroup import Spacegroup >>> sg = Spacegroup(225) # fcc >>> sg.symmetry_normalised_reflections([[2, 0, 0], [0, 2, 0...
def keep_screen(self): """ Freese screenshot, so all image functions will not take images, until call free_screen() """ self.__last_screen = self.screenshot() self.__keep_screen = True inner_self = self class _C(object): def __enter__(self): ...
Freese screenshot, so all image functions will not take images, until call free_screen()
def tripleexprlabel_to_iriref(self, tripleExprLabel: ShExDocParser.TripleExprLabelContext) \ -> Union[ShExJ.BNODE, ShExJ.IRIREF]: """ tripleExprLabel: iri | blankNode """ if tripleExprLabel.iri(): return self.iri_to_iriref(tripleExprLabel.iri()) else: return S...
tripleExprLabel: iri | blankNode
def index_to_time_seg(time_seg_idx, slide_step): """ 将时间片索引值转换为时间片字符串 :param time_seg_idx: :param slide_step: :return: """ assert (time_seg_idx * slide_step < const.MINUTES_IN_A_DAY) return time_util.minutes_to_time_str(time_seg_idx * slide_step)
将时间片索引值转换为时间片字符串 :param time_seg_idx: :param slide_step: :return:
def SetCredentials(api_key,api_passwd): """Establish API key and password associated with APIv1 commands.""" global V1_API_KEY global V1_API_PASSWD global _V1_ENABLED _V1_ENABLED = True V1_API_KEY = api_key V1_API_PASSWD = api_passwd
Establish API key and password associated with APIv1 commands.
def write_snapshots(G, path, delimiter=' ', encoding='utf-8'): """Write a DyNetx graph in snapshot graph list format. Parameters ---------- G : graph A DyNetx graph. path : basestring The desired output filename delimiter : character C...
Write a DyNetx graph in snapshot graph list format. Parameters ---------- G : graph A DyNetx graph. path : basestring The desired output filename delimiter : character Column delimiter
def find_task_descriptor(self, task_id): """Returns the task_descriptor corresponding to task_id.""" # It is not guaranteed that the index will be task_id - 1 when --tasks is # used with a min/max range. for task_descriptor in self.task_descriptors: if task_descriptor.task_metadata.get('task-id')...
Returns the task_descriptor corresponding to task_id.
def relocate(self, lon): """ Relocates this object to a new longitude. """ self.lon = angle.norm(lon) self.signlon = self.lon % 30 self.sign = const.LIST_SIGNS[int(self.lon / 30.0)]
Relocates this object to a new longitude.
def print_status(self, repo_name, repo_path): """Print repository status.""" color = Color() self.logger.info(color.colored( "=> [%s] %s" % (repo_name, repo_path), "green")) try: repo = Repository(repo_path) repo.status() except RepositoryError...
Print repository status.
def show_print_dialog(self): """Open the print dialog""" if not self.impact_function: # Now try to read the keywords and show them in the dock try: active_layer = self.iface.activeLayer() keywords = self.keyword_io.read_keywords(active_layer) ...
Open the print dialog
def all_as_dict(): ''' returns a dict {'Running': ['cont1', 'cont2'], 'Stopped': ['cont3', 'cont4'] } ''' cmd = ['lxc-list'] out = subprocess.check_output(cmd).splitlines() stopped = [] running = [] frozen = [] ...
returns a dict {'Running': ['cont1', 'cont2'], 'Stopped': ['cont3', 'cont4'] }
def relative_path(cls, git_diff_path): """ Returns git_diff_path relative to cwd. """ # Remove git_root from src_path for searching the correct filename # If cwd is `/home/user/work/diff-cover/diff_cover` # and src_path is `diff_cover/violations_reporter.py` # sea...
Returns git_diff_path relative to cwd.
def jinja_env(self): """Create a sandboxed Jinja environment.""" if self._jinja_env is None: self._jinja_env = SandboxedEnvironment( extensions=[ 'jinja2.ext.autoescape', 'jinja2.ext.with_', ], autoescape=True, ) sel...
Create a sandboxed Jinja environment.
def get_astheader(expnum, ccd, version='p', prefix=None): """ Retrieve the header for a given dbimages file. @param expnum: CFHT odometer number @param ccd: which ccd based extension (0..35) @param version: 'o','p', or 's' @param prefix: @return: """ logger.debug("Getting ast heade...
Retrieve the header for a given dbimages file. @param expnum: CFHT odometer number @param ccd: which ccd based extension (0..35) @param version: 'o','p', or 's' @param prefix: @return:
def parse_host(self, tup_tree): """ Parse a HOST element and return its text content as a unicode string. :: <!ELEMENT HOST (#PCDATA)> """ self.check_node(tup_tree, 'HOST', (), (), (), allow_pcdata=True) return self.pcdata(tup_tree)
Parse a HOST element and return its text content as a unicode string. :: <!ELEMENT HOST (#PCDATA)>
def active(self): """ Returns the count of non-skipped actors. :return: the count :rtype: int """ result = 0 for actor in self.actors: if not actor.skip: result += 1 return result
Returns the count of non-skipped actors. :return: the count :rtype: int
def cmd_ok(cmd): """Returns True if cmd can be run. """ try: sp.check_call(cmd, stderr=sp.PIPE, stdout=sp.PIPE) except sp.CalledProcessError: # bwa gives return code of 1 with no argument pass except: sys.stderr.write("{} not found, skipping\n".format(cmd)) r...
Returns True if cmd can be run.
def _batch_report(cls, request): """ Report the collected custom metrics to New Relic. """ if not newrelic: return metrics_cache = cls._get_metrics_cache() try: newrelic.agent.add_custom_parameter('user_id', request.user.id) except Attribut...
Report the collected custom metrics to New Relic.
def is_background_knowledge(stmt): '''Return True if Statement is only supported by background knowledge.''' any_background = False # Iterate over all evidence for the statement for ev in stmt.evidence: epi = ev.epistemics if epi is not None: sec = epi.get('section_type') ...
Return True if Statement is only supported by background knowledge.
def close(self): """Close method. Closes the underlying comm. When the comm is closed, all of the widget views are automatically removed from the front-end.""" if self.comm is not None: Widget.widgets.pop(self.model_id, None) self.comm.close() ...
Close method. Closes the underlying comm. When the comm is closed, all of the widget views are automatically removed from the front-end.
def ensure_size( self, size = None ): """ This function removes the least frequent elements until the size constraint is met. """ if size is None: size = self.size_constraint while sys.getsizeof(self) > size: element_frequen...
This function removes the least frequent elements until the size constraint is met.
def _set_cfunctions(self): # type: () -> None """ Set all ctypes functions and attach them to attributes. """ def cfactory(func, argtypes, restype): # type: (str, List[Any], Any) -> None """ Factorize ctypes creations. """ self._cfactory( attr...
Set all ctypes functions and attach them to attributes.
def _ostaunicode_zero_pad(src, fulllen): # type: (str, int) -> bytes ''' Internal function to create a zero-padded Identifier byte string from a source string. Parameters: src - The src string to start from. fulllen - The padded out length of the result. Returns: A full identifie...
Internal function to create a zero-padded Identifier byte string from a source string. Parameters: src - The src string to start from. fulllen - The padded out length of the result. Returns: A full identifier byte string containing the source string.
def refresh_access_token(self, refresh_token): """刷新 access token :param refresh_token: OAuth2 refresh token :return: JSON 数据包 """ res = self._get( 'sns/oauth2/refresh_token', params={ 'appid': self.app_id, 'grant_type': 'r...
刷新 access token :param refresh_token: OAuth2 refresh token :return: JSON 数据包
def list_distribute_contents_simple(input_list, function=lambda x: x): # type: (List, Callable[[Any], Any]) -> List """Distribute the contents of a list eg. [1, 1, 1, 2, 2, 3] -> [1, 2, 3, 1, 2, 1]. List can contain complex types like dictionaries in which case the function can return the appropriate value ...
Distribute the contents of a list eg. [1, 1, 1, 2, 2, 3] -> [1, 2, 3, 1, 2, 1]. List can contain complex types like dictionaries in which case the function can return the appropriate value eg. lambda x: x[KEY] Args: input_list (List): List to distribute values function (Callable[[Any], Any]): ...
def add_book_series(self, title, volume=None): """ :param volume: the volume of the book :type volume: string :param title: the title of the book :type title: string """ book_series = {} if title is not None: book_series['title'] = title ...
:param volume: the volume of the book :type volume: string :param title: the title of the book :type title: string
def cancel(self, consumer_tag): """Cancel a channel by consumer tag.""" if not self.channel.conn: return self.channel.basic_cancel(consumer_tag)
Cancel a channel by consumer tag.
def _maybe_set_current_user_vars(method, api_info=None, request=None): """Get user information from the id_token or oauth token in the request. Used internally by Endpoints to set up environment variables for user authentication. Args: method: The class method that's handling this request. This method ...
Get user information from the id_token or oauth token in the request. Used internally by Endpoints to set up environment variables for user authentication. Args: method: The class method that's handling this request. This method should be annotated with @endpoints.method. api_info: An api_config....
def conversation(self, name=None, **kwargs): """Make a new conversation. Arguments: name: The key for the dictionary the conversation will be stored as in conversations. If None the conversation will be stored as a list instead. Mixing both types results in a...
Make a new conversation. Arguments: name: The key for the dictionary the conversation will be stored as in conversations. If None the conversation will be stored as a list instead. Mixing both types results in an error. **kwargs: Keyword arguments to pass...
def __search_book_html(self, anywords, page): """ 检索图书列表页面 :param anywords: 关键字 :param page: 页码 :return: html code """ _params = { 'dt': 'ALL', 'cl': 'ALL', 'dp': '20', 'sf': 'M_PUB_YEAR', 'ob': 'DESC', ...
检索图书列表页面 :param anywords: 关键字 :param page: 页码 :return: html code
def _get_snapshot(vm, snapshot_name): """ Returns snapshot object by its name :param vm: :param snapshot_name: :type snapshot_name: str :return: Snapshot by its name :rtype vim.vm.Snapshot """ snapshots = SnapshotRetriever.get_vm_snapshots(vm) ...
Returns snapshot object by its name :param vm: :param snapshot_name: :type snapshot_name: str :return: Snapshot by its name :rtype vim.vm.Snapshot
def _adjust_inserted_indices(inserted_indices_list, prune_indices_list): """Adjust inserted indices, if there are pruned elements.""" # Created a copy, to preserve cached property updated_inserted = [[i for i in dim_inds] for dim_inds in inserted_indices_list] pruned_and_inserted = zip(p...
Adjust inserted indices, if there are pruned elements.
def defaults_docstring(cls, header=None, indent=None, footer=None): """Add the default values to the class docstring""" return defaults_docstring(cls.defaults, header=header, indent=indent, footer=footer)
Add the default values to the class docstring
def get_t_conjunction(self, params): """ Return the time of primary transit center (calculated using `params.t_secondary`). """ phase = self._get_phase(params, "primary") phase2 = self._get_phase(params, "secondary") return params.t_secondary + params.per*(phase-phase2)
Return the time of primary transit center (calculated using `params.t_secondary`).
def lockout_response(request): """ if we are locked out, here is the response """ if config.LOCKOUT_TEMPLATE: context = { 'cooloff_time_seconds': config.COOLOFF_TIME, 'cooloff_time_minutes': config.COOLOFF_TIME / 60, 'failure_limit': config.FAILURE_LIMIT, } ...
if we are locked out, here is the response
def register_app(self, name, redirect_uri, callback): ''' register_app takes an application name and redirect_uri It generates client_id (client_key) and client_secret, then stores all of the above in the data_store, and returns a dictionary containing the client_id and client_se...
register_app takes an application name and redirect_uri It generates client_id (client_key) and client_secret, then stores all of the above in the data_store, and returns a dictionary containing the client_id and client_secret.
def register_macro(name: str, func: Callable, allow_overwrite: bool = False) -> None: """Register new macro to Circuit. Args: name (str): The name of macro. func (callable): The function to be called. allow_overwrite (bool, optional): If True, allow to overwrite the ...
Register new macro to Circuit. Args: name (str): The name of macro. func (callable): The function to be called. allow_overwrite (bool, optional): If True, allow to overwrite the existing macro. Otherwise, raise the ValueError. Raises: Val...
def taper(path, length, final_width, final_distance, direction=None, layer=0, datatype=0): ''' Linear tapers for the lazy. path : `gdspy.Path` to append the taper length : total length final_width : final width of th taper ...
Linear tapers for the lazy. path : `gdspy.Path` to append the taper length : total length final_width : final width of th taper direction : taper direction layer : GDSII layer number (int or list) datatype : GDSII datatype number (int or list) Parameters `layer` and ...
def readspecscan(f, number=None): """Read the next spec scan in the file, which starts at the current position.""" scan = None scannumber = None while True: l = f.readline() if l.startswith('#S'): scannumber = int(l[2:].split()[0]) if not ((number is None) or (num...
Read the next spec scan in the file, which starts at the current position.
def _var_uint_field_handler(handler, ctx): """Handler co-routine for variable unsigned integer fields that. Invokes the given ``handler`` function with the read field and context, then immediately yields to the resulting co-routine. """ _, self = yield queue = ctx.queue value = 0 while ...
Handler co-routine for variable unsigned integer fields that. Invokes the given ``handler`` function with the read field and context, then immediately yields to the resulting co-routine.
def until_state_in(self, *states, **kwargs): """Return a tornado Future, resolves when any of the requested states is set""" timeout = kwargs.get('timeout', None) state_futures = (self.until_state(s, timeout=timeout) for s in states) return until_any(*state_futures)
Return a tornado Future, resolves when any of the requested states is set
def rollback_group(self, group_id, version, force=False): """Roll a group back to a previous version. :param str group_id: group ID :param str version: group version :param bool force: apply even if a deployment is in progress :returns: a dict containing the deployment id and v...
Roll a group back to a previous version. :param str group_id: group ID :param str version: group version :param bool force: apply even if a deployment is in progress :returns: a dict containing the deployment id and version :rtype: dict
def _get_resources(self, args, params): """ Finds the list of resources from the keyword parameters and pops them out of the params dictionary. """ resources = [] disabled = [] for resource in ['holoviews'] + list(Store.renderers.keys()): if resource i...
Finds the list of resources from the keyword parameters and pops them out of the params dictionary.
def add_dependency(self, address): """Add a dependency to this target. This will deduplicate existing dependencies.""" if address in self._dependencies_by_address: if self._dependencies_by_address[address].has_comment(): logger.warn('BuildFileManipulator would have added {address} as a dependency...
Add a dependency to this target. This will deduplicate existing dependencies.
def _selectFromList(self, _list, using_pattern=True, objtype=None): """ Generic method that lets users pick an item from a list via input *using_pattern* flag to know if we're showing all choices or not Note: the list items need to be Ontospy entities. <objtype>: if specified, it...
Generic method that lets users pick an item from a list via input *using_pattern* flag to know if we're showing all choices or not Note: the list items need to be Ontospy entities. <objtype>: if specified, it allows incremental search by keeping specifying a different pattern.
def register(self,obj,cls=type(None),hist={}): """ Takes a FortranObject and adds it to the appropriate list, if not already present. """ #~ ident = getattr(obj,'ident',obj) if is_submodule(obj,cls): if obj not in self.submodules: self.submodules[obj] = Submod...
Takes a FortranObject and adds it to the appropriate list, if not already present.
def OnHelpMove(self, event): """Help window move event handler stores position in config""" position = event.GetPosition() config["help_window_position"] = repr((position.x, position.y)) event.Skip()
Help window move event handler stores position in config
def isFlexible(self): """ Returns true if any one of the channel, height, or width ranges of this shape allow more than one input value. """ for key, value in self.arrayShapeRange.items(): if key in _CONSTRAINED_KEYS: if value.isFlexible: r...
Returns true if any one of the channel, height, or width ranges of this shape allow more than one input value.