code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def delPlayer(name): """forget about a previously defined PlayerRecord setting by deleting its disk file""" player = getPlayer(name) try: os.remove(player.filename) # delete from disk except IOError: pass # shouldn't happen, but don't crash if the disk data doesn't exist try: del getKnownPlaye...
forget about a previously defined PlayerRecord setting by deleting its disk file
def remove_users_from_user_group(self, id, **kwargs): # noqa: E501 """Remove multiple users from a specific user group # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thre...
Remove multiple users from a specific user group # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.remove_users_from_user_group(id, async_req=True) >>> result = ...
def _delay_call(self): """ Makes sure that web service calls are at least 0.2 seconds apart. """ now = time.time() time_since_last = now - self.last_call_time if time_since_last < DELAY_TIME: time.sleep(DELAY_TIME - time_since_last) self.last_ca...
Makes sure that web service calls are at least 0.2 seconds apart.
def reraise(tpe, value, tb=None): " Reraise an exception from an exception info tuple. " Py3 = (sys.version_info[0] == 3) if value is None: value = tpe() if Py3: if value.__traceback__ is not tb: raise value.with_traceback(tb) raise value else: exec('raise tpe, value, tb')
Reraise an exception from an exception info tuple.
def mark_running(self): """Moves the service to the Running state. Raises if the service is not currently in the Paused state. """ with self._lock: self._set_state(self._RUNNING, self._PAUSED)
Moves the service to the Running state. Raises if the service is not currently in the Paused state.
def start_timer(self, duration, func, *args): """ Schedules a function to be called after some period of time. * duration - time in seconds to wait before firing * func - function to be called * args - arguments to pass to the function """ t = threading.Timer(dur...
Schedules a function to be called after some period of time. * duration - time in seconds to wait before firing * func - function to be called * args - arguments to pass to the function
def reset(name): ''' Force power down and restart an existing VM ''' ret = {} client = salt.client.get_local_client(__opts__['conf_file']) data = vm_info(name, quiet=True) if not data: __jid_event__.fire_event({'message': 'Failed to find VM {0} to reset'.format(name)}, 'progress') ...
Force power down and restart an existing VM
def hardware_info(self, mask=0xFFFFFFFF): """Returns a list of 32 integer values corresponding to the bitfields specifying the power consumption of the target. The values returned by this function only have significance if the J-Link is powering the target. The words, indexed, ...
Returns a list of 32 integer values corresponding to the bitfields specifying the power consumption of the target. The values returned by this function only have significance if the J-Link is powering the target. The words, indexed, have the following significance: 0. If ``1`...
def check_initial_subdomain(cls, subdomain_rec): """ Verify that a first-ever subdomain record is well-formed. * n must be 0 * the subdomain must not be independent of its domain """ if subdomain_rec.n != 0: return False if subdomain_rec.indepe...
Verify that a first-ever subdomain record is well-formed. * n must be 0 * the subdomain must not be independent of its domain
def post_grade(self, grade): """ Post grade to LTI consumer using XML :param: grade: 0 <= grade <= 1 :return: True if post successful and grade valid :exception: LTIPostMessageException if call failed """ message_identifier_id = self.message_identifier_id() ...
Post grade to LTI consumer using XML :param: grade: 0 <= grade <= 1 :return: True if post successful and grade valid :exception: LTIPostMessageException if call failed
def do_clearrep(self, line): """clearrep Set the replication policy to default. The default replication policy has no preferred or blocked member nodes, allows replication and sets the preferred number of replicas to 3. """ self._split_args(line, 0, 0) self._command_pro...
clearrep Set the replication policy to default. The default replication policy has no preferred or blocked member nodes, allows replication and sets the preferred number of replicas to 3.
def notify_init(self): ''' run the queed callback for just the first session only ''' _session_count = len(self._sessions) self._update_session_count(1, _session_count) if _session_count == 1: self._run_queued_callbacks()
run the queed callback for just the first session only
def stat(self, path): """ Retrieve information about a file on the remote system. The return value is an object whose attributes correspond to the attributes of python's C{stat} structure as returned by C{os.stat}, except that it contains fewer fields. An SFTP server may return...
Retrieve information about a file on the remote system. The return value is an object whose attributes correspond to the attributes of python's C{stat} structure as returned by C{os.stat}, except that it contains fewer fields. An SFTP server may return as much or as little info as it w...
def find(wave, dep_var, der=None, inst=1, indep_min=None, indep_max=None): r""" Return the independent variable point associated with a dependent variable point. If the dependent variable point is not in the dependent variable vector the independent variable vector point is obtained by linear interpola...
r""" Return the independent variable point associated with a dependent variable point. If the dependent variable point is not in the dependent variable vector the independent variable vector point is obtained by linear interpolation :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` ...
def index_relations(sender, pid_type, json=None, record=None, index=None, **kwargs): """Add relations to the indexed record.""" if not json: json = {} pid = PersistentIdentifier.query.filter( PersistentIdentifier.object_uuid == record.id, PersistentIdentifier.pid_...
Add relations to the indexed record.
def imap_unordered(requests, stream=True, pool=None, size=2, exception_handler=None): """Concurrently converts a generator object of Requests to a generator of Responses. :param requests: a generator of Request objects. :param stream: If False, the content will not be downloaded immediately. :param...
Concurrently converts a generator object of Requests to a generator of Responses. :param requests: a generator of Request objects. :param stream: If False, the content will not be downloaded immediately. :param size: Specifies the number of requests to make at a time. default is 2 :param exception_...
def get_uids_from_record(self, record, key): """Returns a list of parsed UIDs from a single form field identified by the given key. A form field ending with `_uid` can contain an empty value, a single UID or multiple UIDs separated by a comma. This method parses the UID value a...
Returns a list of parsed UIDs from a single form field identified by the given key. A form field ending with `_uid` can contain an empty value, a single UID or multiple UIDs separated by a comma. This method parses the UID value and returns a list of non-empty UIDs.
def is_ready_update(self): """ Returns whether or not the trainer has enough elements to run update model :return: A boolean corresponding to whether or not update_model() can be run """ size_of_buffer = len(self.training_buffer.update_buffer['actions']) return size_of_bu...
Returns whether or not the trainer has enough elements to run update model :return: A boolean corresponding to whether or not update_model() can be run
def get_nodes(self, coord, coords): """Get the variables containing the definition of the nodes Parameters ---------- coord: xarray.Coordinate The mesh variable coords: dict The coordinates to use to get node coordinates""" def get_coord(coord): ...
Get the variables containing the definition of the nodes Parameters ---------- coord: xarray.Coordinate The mesh variable coords: dict The coordinates to use to get node coordinates
def self_consistent_update(u_kn, N_k, f_k): """Return an improved guess for the dimensionless free energies Parameters ---------- u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float' The reduced potential energies, i.e. -log unnormalized probabilities N_k : np.ndarray, shape=(n_sta...
Return an improved guess for the dimensionless free energies Parameters ---------- u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float' The reduced potential energies, i.e. -log unnormalized probabilities N_k : np.ndarray, shape=(n_states), dtype='int' The number of samples in ...
def upsert(self, doc, namespace, timestamp, update_spec=None): """Insert a document into Elasticsearch.""" index, doc_type = self._index_and_mapping(namespace) # No need to duplicate '_id' in source document doc_id = u(doc.pop("_id")) metadata = { 'ns': namespace, ...
Insert a document into Elasticsearch.
def main(args): """ main entry point for the GenomicIntIntersection script. :param args: the arguments for this script, as a list of string. Should already have had things like the script name stripped. That is, if there are no args provided, this should be an empty l...
main entry point for the GenomicIntIntersection script. :param args: the arguments for this script, as a list of string. Should already have had things like the script name stripped. That is, if there are no args provided, this should be an empty list.
def record_magic(dct, magic_kind, magic_name, func): """Utility function to store a function as a magic of a specific kind. Parameters ---------- dct : dict A dictionary with 'line' and 'cell' subdicts. magic_kind : str Kind of magic to be stored. magic_name : str Key to sto...
Utility function to store a function as a magic of a specific kind. Parameters ---------- dct : dict A dictionary with 'line' and 'cell' subdicts. magic_kind : str Kind of magic to be stored. magic_name : str Key to store the magic as. func : function Callable object ...
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status if hasattr(self, 'message') and self.message is not None: _dict['message'] = self.message ...
Return a json dictionary representing this model.
def bonds(self): """ iterate other all bonds """ seen = set() for n, m_bond in self._adj.items(): seen.add(n) for m, bond in m_bond.items(): if m not in seen: yield n, m, bond
iterate other all bonds
def token_of_request( self, method, host, url, qheaders, content_type=None, body=None): """ <Method> <PathWithRawQuery> Host: <Host> Content-Type: <ContentType> [<X-Qiniu-*> Headers] [<Bo...
<Method> <PathWithRawQuery> Host: <Host> Content-Type: <ContentType> [<X-Qiniu-*> Headers] [<Body>] #这里的 <Body> 只有在 <ContentType> 存在且不为 application/octet-stream 时才签进去。
def _do_multivalued_field_facets(self, results, field_facets): """ Implements a multivalued field facet on the results. This is implemented using brute force - O(N^2) - because Xapian does not have it implemented yet (see http://trac.xapian.org/ticket/199) """ fa...
Implements a multivalued field facet on the results. This is implemented using brute force - O(N^2) - because Xapian does not have it implemented yet (see http://trac.xapian.org/ticket/199)
def maybe_replace_any_if_equal(name, expected, actual): """Return the type given in `expected`. Raise ValueError if `expected` isn't equal to `actual`. If --replace-any is used, the Any type in `actual` is considered equal. The implementation is naively checking if the string representation of `a...
Return the type given in `expected`. Raise ValueError if `expected` isn't equal to `actual`. If --replace-any is used, the Any type in `actual` is considered equal. The implementation is naively checking if the string representation of `actual` is one of "Any", "typing.Any", or "t.Any". This is done...
def information_content(values): "Number of bits to represent the probability distribution in values." probabilities = normalize(removeall(0, values)) return sum(-p * log2(p) for p in probabilities)
Number of bits to represent the probability distribution in values.
def repr(self, changed_widgets=None): """It is used to automatically represent the object to HTML format packs all the attributes, children and so on. Args: changed_widgets (dict): A dictionary containing a collection of tags that have to be updated. The tag that hav...
It is used to automatically represent the object to HTML format packs all the attributes, children and so on. Args: changed_widgets (dict): A dictionary containing a collection of tags that have to be updated. The tag that have to be updated is the key, and the value is its ...
def _identify(self, dataframe): """ Returns a list of indexes containing only the points that pass the filter. Parameters ---------- dataframe : DataFrame """ ## # TODO Fix this implementation. (i.e., why not support just 'left') # At the moment t...
Returns a list of indexes containing only the points that pass the filter. Parameters ---------- dataframe : DataFrame
def _make_request(self, opener, request, timeout=None): """Make the API call and return the response. This is separated into it's own function, so we can mock it easily for testing. :param opener: :type opener: :param request: url payload to request :type request: url...
Make the API call and return the response. This is separated into it's own function, so we can mock it easily for testing. :param opener: :type opener: :param request: url payload to request :type request: urllib.Request object :param timeout: timeout value or None ...
def verify_checksum(*lines): """Verify the checksum of one or more TLE lines. Raises `ValueError` if any of the lines fails its checksum, and includes the failing line in the error message. """ for line in lines: checksum = line[68:69] if not checksum.isdigit(): continu...
Verify the checksum of one or more TLE lines. Raises `ValueError` if any of the lines fails its checksum, and includes the failing line in the error message.
def processRequest(self, request: Request, frm: str): """ Handle a REQUEST from the client. If the request has already been executed, the node re-sends the reply to the client. Otherwise, the node acknowledges the client request, adds it to its list of client requests, and sends ...
Handle a REQUEST from the client. If the request has already been executed, the node re-sends the reply to the client. Otherwise, the node acknowledges the client request, adds it to its list of client requests, and sends a PROPAGATE to the remaining nodes. :param request: the R...
def bytes_to_ustr(self, b): "convert bytes array to unicode string" return b.decode(charset_map.get(self.charset, self.charset))
convert bytes array to unicode string
def get_base_url(self, force_http=False): """ Creates base URL path :param force_http: `True` if HTTP base URL should be used and `False` otherwise :type force_http: str :return: base url string :rtype: str """ base_url = SHConfig().aws_metadata_url.rstrip('/') i...
Creates base URL path :param force_http: `True` if HTTP base URL should be used and `False` otherwise :type force_http: str :return: base url string :rtype: str
def search(self, start_ts, end_ts): """Called to query Mongo for documents in a time range. """ for meta_collection_name in self._meta_collections(): meta_coll = self.meta_database[meta_collection_name] for ts_ns_doc in meta_coll.find( {"_ts": {"$lte": end...
Called to query Mongo for documents in a time range.
def postprocess_result(morphresult, trim_phonetic, trim_compound): """Postprocess vabamorf wrapper output.""" word, analysis = morphresult return { 'text': deconvert(word), 'analysis': [postprocess_analysis(a, trim_phonetic, trim_compound) for a in analysis] }
Postprocess vabamorf wrapper output.
def __create(self, account_id, name, short_description, amount, period, **kwargs): """Call documentation: `/subscription_plan/create <https://www.wepay.com/developer/reference/subscription_plan#create>`_, plus extra keyword parameters: :keyword str access_token:...
Call documentation: `/subscription_plan/create <https://www.wepay.com/developer/reference/subscription_plan#create>`_, plus extra keyword parameters: :keyword str access_token: will be used instead of instance's ``access_token``, with ``batch_mode=True`` will set `authorizati...
def _init_multi_count_metrics(self, pplan_helper): """Initializes the default values for a necessary set of MultiCountMetrics""" # inputs to_in_init = [self.metrics[i] for i in self.inputs_init if i in self.metrics and isinstance(self.metrics[i], MultiCountMetric)] for in_stream in ppl...
Initializes the default values for a necessary set of MultiCountMetrics
def to_java_doubles(m): ''' to_java_doubles(m) yields a java array object for the vector or matrix m. ''' global _java if _java is None: _init_registration() m = np.asarray(m) dims = len(m.shape) if dims > 2: raise ValueError('1D and 2D arrays supported only') bindat = serialize_nump...
to_java_doubles(m) yields a java array object for the vector or matrix m.
def unset(entity, *types): """Unset the TypedFields on the input `entity`. Args: entity: A mixbox.Entity object. *types: A variable-length list of TypedField subclasses. If not provided, defaults to TypedField. """ if not types: types = (TypedField,) fields = li...
Unset the TypedFields on the input `entity`. Args: entity: A mixbox.Entity object. *types: A variable-length list of TypedField subclasses. If not provided, defaults to TypedField.
def monitor_session_span_command_direction(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") monitor = ET.SubElement(config, "monitor", xmlns="urn:brocade.com:mgmt:brocade-span") session = ET.SubElement(monitor, "session") session_number_key = ET.S...
Auto Generated Code
def cube(width, height, depth, center=(0.0, 0.0, 0.0), normals=True, uvs=True) -> VAO: """ Creates a cube VAO with normals and texture coordinates Args: width (float): Width of the cube height (float): Height of the cube depth (float): Depth of the cube Keyword Args: ce...
Creates a cube VAO with normals and texture coordinates Args: width (float): Width of the cube height (float): Height of the cube depth (float): Depth of the cube Keyword Args: center: center of the cube as a 3-component tuple normals: (bool) Include normals uvs...
def nps_survey_response_show(self, survey_id, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/nps-api/responses#show-response" api_path = "/api/v2/nps/surveys/{survey_id}/responses/{id}.json" api_path = api_path.format(survey_id=survey_id, id=id) return self.call(api_path, **...
https://developer.zendesk.com/rest_api/docs/nps-api/responses#show-response
def _get_transitions(self, expression: Any, expected_type: PredicateType) -> Tuple[List[str], PredicateType]: """ This is used when converting a logical form into an action sequence. This piece recursively translates a lisp expression into an action sequence, making sure we match the ex...
This is used when converting a logical form into an action sequence. This piece recursively translates a lisp expression into an action sequence, making sure we match the expected type (or using the expected type to get the right type for constant expressions).
def draw_data_value_rect(cairo_context, color, value_size, name_size, pos, port_side): """This method draws the containing rect for the data port value, depending on the side and size of the label. :param cairo_context: Draw Context :param color: Background color of value part :param value_size: Size (...
This method draws the containing rect for the data port value, depending on the side and size of the label. :param cairo_context: Draw Context :param color: Background color of value part :param value_size: Size (width, height) of label holding the value :param name_size: Size (width, height) of label ...
def from_pb(cls, app_profile_pb, instance): """Creates an instance app_profile from a protobuf. :type app_profile_pb: :class:`instance_pb2.app_profile_pb` :param app_profile_pb: An instance protobuf object. :type instance: :class:`google.cloud.bigtable.instance.Instance` :param...
Creates an instance app_profile from a protobuf. :type app_profile_pb: :class:`instance_pb2.app_profile_pb` :param app_profile_pb: An instance protobuf object. :type instance: :class:`google.cloud.bigtable.instance.Instance` :param instance: The instance that owns the cluster. ...
def search(self, terms): """ returns a dict {"name": "image_dict"} """ images = {} response = self._request_builder('GET', 'search', params={'q': terms}) if self._validate_response(response): body = json.loads(response.content.decode('utf-8'))['results'] ...
returns a dict {"name": "image_dict"}
def cash_table(self): '现金的table' _cash = pd.DataFrame( data=[self.cash[1::], self.time_index_max], index=['cash', 'datetime'] ).T _cash = _cash.assign( date=_cash.datetime.apply(lambda x: pd.to_datetime(str(x)[0:10]...
现金的table
def drop_curie(self, name): """Removes a CURIE. The CURIE link with the given name is removed from the document. """ curies = self.o[LINKS_KEY][self.draft.curies_rel] if isinstance(curies, dict) and curies['name'] == name: del self.o[LINKS_KEY][self.draft.curies_rel...
Removes a CURIE. The CURIE link with the given name is removed from the document.
def reconstruct_emds(edm, Om, all_points, method=None, **kwargs): """ Reconstruct point set using E(dge)-MDS. """ from .point_set import dm_from_edm N = all_points.shape[0] d = all_points.shape[1] dm = dm_from_edm(edm) if method is None: from .mds import superMDS Xhat, __ = s...
Reconstruct point set using E(dge)-MDS.
def get_asn_verbose_dns(self, asn=None): """ The function for retrieving the information for an ASN from Cymru via port 53 (DNS). This is needed since IP to ASN mapping via Cymru DNS does not return the ASN Description like Cymru Whois does. Args: asn (:obj:`str`): T...
The function for retrieving the information for an ASN from Cymru via port 53 (DNS). This is needed since IP to ASN mapping via Cymru DNS does not return the ASN Description like Cymru Whois does. Args: asn (:obj:`str`): The AS number (required). Returns: str: T...
def update_domain(self, domain, emailAddress=None, ttl=None, comment=None): """ Provides a way to modify the following attributes of a domain record: - email address - ttl setting - comment """ if not any((emailAddress, ttl, comment)): ...
Provides a way to modify the following attributes of a domain record: - email address - ttl setting - comment
def to_triangulation(self): """ Returns the mesh as a matplotlib.tri.Triangulation instance. (2D only) """ from matplotlib.tri import Triangulation conn = self.split("simplices").unstack() coords = self.nodes.coords.copy() node_map = pd.Series(data = np.arange(len(coords)), index = coords.i...
Returns the mesh as a matplotlib.tri.Triangulation instance. (2D only)
def maybe_cythonize_extensions(top_path, config): """Tweaks for building extensions between release and development mode.""" is_release = os.path.exists(os.path.join(top_path, 'PKG-INFO')) if is_release: build_from_c_and_cpp_files(config.ext_modules) else: message = ('Please install cyt...
Tweaks for building extensions between release and development mode.
def get_target_extraction_context(self, build_file_path: str) -> dict: """Return a build file parser target extraction context. The target extraction context is a build-file-specific mapping from builder-name to target extraction function, for every registered builder. """ ...
Return a build file parser target extraction context. The target extraction context is a build-file-specific mapping from builder-name to target extraction function, for every registered builder.
def getAdaptedTraveltime(self, edgeID, time): """getAdaptedTraveltime(string, double) -> double Returns the travel time value (in s) used for (re-)routing which is valid on the edge at the given time. """ self._connection._beginMessage(tc.CMD_GET_EDGE_VARIABLE, tc.VAR_EDGE_TRAVE...
getAdaptedTraveltime(string, double) -> double Returns the travel time value (in s) used for (re-)routing which is valid on the edge at the given time.
def setup_logging(verbosity, filename=None): """Configure logging for this tool.""" levels = [logging.WARNING, logging.INFO, logging.DEBUG] level = levels[min(verbosity, len(levels) - 1)] logging.root.setLevel(level) fmt = logging.Formatter('%(asctime)s %(levelname)-12s %(message)-100s ' ...
Configure logging for this tool.
def register_intent_parser(self, intent_parser, domain=0): """ Register a intent parser with a domain. Args: intent_parser(intent): The intent parser you wish to register. domain(str): a string representing the domain you wish register the intent parser t...
Register a intent parser with a domain. Args: intent_parser(intent): The intent parser you wish to register. domain(str): a string representing the domain you wish register the intent parser to.
def device_destroy(self, id, **kwargs): # noqa: E501 """Delete a device. # noqa: E501 Delete device. Only available for devices with a developer certificate. Attempts to delete a device with a production certicate will return a 400 response. # noqa: E501 This method makes a synchronous HTTP ...
Delete a device. # noqa: E501 Delete device. Only available for devices with a developer certificate. Attempts to delete a device with a production certicate will return a 400 response. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request,...
def get(self, wheel=False): """Downloads the package from PyPI. Returns: Full path of the downloaded file. Raises: PermissionError if the save_dir is not writable. """ try: url = get_url(self.client, self.name, self.version, ...
Downloads the package from PyPI. Returns: Full path of the downloaded file. Raises: PermissionError if the save_dir is not writable.
def precompute_begin_state(self): """ Caches the summation calculation and available choices for BEGIN * state_size. Significantly speeds up chain generation on large corpuses. Thanks, @schollz! """ begin_state = tuple([ BEGIN ] * self.state_size) choices, weights = zip(*...
Caches the summation calculation and available choices for BEGIN * state_size. Significantly speeds up chain generation on large corpuses. Thanks, @schollz!
def ndim(self): """If given FeatureType stores a dictionary of numpy.ndarrays it returns dimensions of such arrays.""" if self.is_raster(): return { FeatureType.DATA: 4, FeatureType.MASK: 4, FeatureType.SCALAR: 2, FeatureType.LA...
If given FeatureType stores a dictionary of numpy.ndarrays it returns dimensions of such arrays.
def get_victoria_day(self, year): """ Return Victoria Day for Edinburgh. Set to the Monday strictly before May 24th. It means that if May 24th is a Monday, it's shifted to the week before. """ may_24th = date(year, 5, 24) # Since "MON(day) == 0", it's either the ...
Return Victoria Day for Edinburgh. Set to the Monday strictly before May 24th. It means that if May 24th is a Monday, it's shifted to the week before.
def _event_duration(vevent): """unify dtend and duration to the duration of the given vevent""" if hasattr(vevent, 'dtend'): return vevent.dtend.value - vevent.dtstart.value elif hasattr(vevent, 'duration') and vevent.duration.value: return vevent.duration.value r...
unify dtend and duration to the duration of the given vevent
def initialize(self, store): """Common initialization of handlers happens here. If additional initialization is required, this method must either be called with ``super`` or the child class must assign the ``store`` attribute and register itself with the store. """ ...
Common initialization of handlers happens here. If additional initialization is required, this method must either be called with ``super`` or the child class must assign the ``store`` attribute and register itself with the store.
def flatten(suitable_for_isinstance): """ isinstance() can accept a bunch of really annoying different types: * a single type * a tuple of types * an arbitrary nested tree of tuples Return a flattened tuple of the given argument. """ types = set() if not isinstance(su...
isinstance() can accept a bunch of really annoying different types: * a single type * a tuple of types * an arbitrary nested tree of tuples Return a flattened tuple of the given argument.
def DbPutClassAttributeProperty2(self, argin): """ This command adds support for array properties compared to the previous one called DbPutClassAttributeProperty. The old comman is still there for compatibility reason :param argin: Str[0] = Tango class name Str[1] = Attribute number ...
This command adds support for array properties compared to the previous one called DbPutClassAttributeProperty. The old comman is still there for compatibility reason :param argin: Str[0] = Tango class name Str[1] = Attribute number Str[2] = Attribute name Str[3] = Property numb...
def creds_display(creds: dict, filt: dict = None, filt_dflt_incl: bool = False) -> dict: """ Find indy-sdk creds matching input filter from within input creds structure, json-loaded as returned via HolderProver.get_creds(), and return human-legible summary. :param creds: creds structure returned by Hol...
Find indy-sdk creds matching input filter from within input creds structure, json-loaded as returned via HolderProver.get_creds(), and return human-legible summary. :param creds: creds structure returned by HolderProver.get_creds(); e.g., :: { "attrs": { "attr0_uuid": ...
def get_averaged_bias_matrix(bias_sequences, dtrajs, nstates=None): r""" Computes a bias matrix via an exponential average of the observed frame wise bias energies. Parameters ---------- bias_sequences : list of numpy.ndarray(T_i, num_therm_states) A single reduced bias energy trajectory or...
r""" Computes a bias matrix via an exponential average of the observed frame wise bias energies. Parameters ---------- bias_sequences : list of numpy.ndarray(T_i, num_therm_states) A single reduced bias energy trajectory or a list of reduced bias energy trajectories. For every simulatio...
def download_apcor(self, uri): """ Downloads apcor data. Args: uri: The URI of the apcor data file. Returns: apcor: ossos.downloads.core.ApcorData """ local_file = os.path.basename(uri) if os.access(local_file, os.F_OK): fobj = o...
Downloads apcor data. Args: uri: The URI of the apcor data file. Returns: apcor: ossos.downloads.core.ApcorData
def iterate_analogy_datasets(args): """Generator over all analogy evaluation datasets. Iterates over dataset names, keyword arguments for their creation and the created dataset. """ for dataset_name in args.analogy_datasets: parameters = nlp.data.list_datasets(dataset_name) for key...
Generator over all analogy evaluation datasets. Iterates over dataset names, keyword arguments for their creation and the created dataset.
def _get_role(rolename): """Reads and parses a file containing a role""" path = os.path.join('roles', rolename + '.json') if not os.path.exists(path): abort("Couldn't read role file {0}".format(path)) with open(path, 'r') as f: try: role = json.loads(f.read()) except ...
Reads and parses a file containing a role
def _symmetrize_correlograms(correlograms): """Return the symmetrized version of the CCG arrays.""" n_clusters, _, n_bins = correlograms.shape assert n_clusters == _ # We symmetrize c[i, j, 0]. # This is necessary because the algorithm in correlograms() # is sensitive to the order of identical...
Return the symmetrized version of the CCG arrays.
def get_status_badge(self, project, definition, branch_name=None, stage_name=None, job_name=None, configuration=None, label=None): """GetStatusBadge. [Preview API] <p>Gets the build status for a definition, optionally scoped to a specific branch, stage, job, and configuration.</p> <p>If there are more t...
GetStatusBadge. [Preview API] <p>Gets the build status for a definition, optionally scoped to a specific branch, stage, job, and configuration.</p> <p>If there are more than one, then it is required to pass in a stageName value when specifying a jobName, and the same rule then applies for both if passing a conf...
def enable_service_freshness_checks(self): """Enable service freshness checks (globally) Format of the line that triggers function call:: ENABLE_SERVICE_FRESHNESS_CHECKS :return: None """ if not self.my_conf.check_service_freshness: self.my_conf.modified_att...
Enable service freshness checks (globally) Format of the line that triggers function call:: ENABLE_SERVICE_FRESHNESS_CHECKS :return: None
def detect_with_url( self, url, return_face_id=True, return_face_landmarks=False, return_face_attributes=None, recognition_model="recognition_01", return_recognition_model=False, custom_headers=None, raw=False, **operation_config): """Detect human faces in an image, return face rectangles, and optio...
Detect human faces in an image, return face rectangles, and optionally with faceIds, landmarks, and attributes.<br /> * Optional parameters including faceId, landmarks, and attributes. Attributes include age, gender, headPose, smile, facialHair, glasses, emotion, hair, makeup, occlusion,...
def fnmatch_multiple(candidates, pattern): ''' Convenience function which runs fnmatch.fnmatch() on each element of passed iterable. The first matching candidate is returned, or None if there is no matching candidate. ''' # Make sure that candidates is iterable to avoid a TypeError when we try t...
Convenience function which runs fnmatch.fnmatch() on each element of passed iterable. The first matching candidate is returned, or None if there is no matching candidate.
def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error): """Checks for additional blank line issues related to sections. Currently the only thing checked here is blank line before protected/private. Args: filename: The name of the current file. clean_lines: A CleansedLines instance co...
Checks for additional blank line issues related to sections. Currently the only thing checked here is blank line before protected/private. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. class_info: A _ClassInfo objects. linenum: The number ...
def visit_and_update_expressions(self, visitor_fn): """Create an updated version (if needed) of the ConstructResult via the visitor pattern.""" new_fields = {} for key, value in six.iteritems(self.fields): new_value = value.visit_and_update(visitor_fn) if new_value is no...
Create an updated version (if needed) of the ConstructResult via the visitor pattern.
def count_emails(self, conditions={}): """ Count all certified emails """ url = self.EMAILS_COUNT_URL + "?" for key, value in conditions.items(): if key is 'ids': value = ",".join(value) url += '&%s=%s' % (key, value) connection ...
Count all certified emails
def autofix_codeblock(codeblock, max_line_len=80, aggressive=False, very_aggressive=False, experimental=False): r""" Uses autopep8 to format a block of code Example: >>> # DISABLE_DOCTEST >>> import utool as ut >>> co...
r""" Uses autopep8 to format a block of code Example: >>> # DISABLE_DOCTEST >>> import utool as ut >>> codeblock = ut.codeblock( ''' def func( with , some = 'Problems' ): syntax ='Ok' but = 'Its very messy' if None: ...
def samples(dataset='imagenet', index=0, batchsize=1, shape=(224, 224), data_format='channels_last'): ''' Returns a batch of example images and the corresponding labels Parameters ---------- dataset : string The data set to load (options: imagenet, mnist, cifar10, cifar100, ...
Returns a batch of example images and the corresponding labels Parameters ---------- dataset : string The data set to load (options: imagenet, mnist, cifar10, cifar100, fashionMNIST) index : int For each data set 20 example images exist. The returned batch contains the i...
def _routes_updated(self, ri): """Update the state of routes in the router. Compares the current routes with the (configured) existing routes and detect what was removed or added. Then configure the logical router in the hosting device accordingly. :param ri: RouterInfo correspo...
Update the state of routes in the router. Compares the current routes with the (configured) existing routes and detect what was removed or added. Then configure the logical router in the hosting device accordingly. :param ri: RouterInfo corresponding to the router. :return: None...
def check_len_in(self, min_len, max_len, item): """Checks that the length of item is in range(min_len, max_len+1).""" if max_len is None: if min_len: self.add_check("_coconut.len(" + item + ") >= " + str(min_len)) elif min_len == max_len: self.add_check("_...
Checks that the length of item is in range(min_len, max_len+1).
def __densify_border(self): """ Densify the border of a polygon. The border is densified by a given factor (by default: 0.5). The complexity of the polygon's geometry is evaluated in order to densify the borders of its interior rings as well. Returns: list:...
Densify the border of a polygon. The border is densified by a given factor (by default: 0.5). The complexity of the polygon's geometry is evaluated in order to densify the borders of its interior rings as well. Returns: list: a list of points where each point is represente...
def as_float_array(a): """View the quaternion array as an array of floats This function is fast (of order 1 microsecond) because no data is copied; the returned quantity is just a "view" of the original. The output view has one more dimension (of size 4) than the input array, but is otherwise the ...
View the quaternion array as an array of floats This function is fast (of order 1 microsecond) because no data is copied; the returned quantity is just a "view" of the original. The output view has one more dimension (of size 4) than the input array, but is otherwise the same shape.
def update(self, name=None, description=None, privacy_policy=None, subscription_policy=None, is_managed=None): """Update group. :param name: Name of group. :param description: Description of group. :param privacy_policy: PrivacyPolicy :param subscription_policy: S...
Update group. :param name: Name of group. :param description: Description of group. :param privacy_policy: PrivacyPolicy :param subscription_policy: SubscriptionPolicy :returns: Updated group
def record_to_fs(self): """Create a filesystem file from a File""" fr = self.record fn_path = self.file_name if fr.contents: if six.PY2: with self._fs.open(fn_path, 'wb') as f: self.record_to_fh(f) else: # py3...
Create a filesystem file from a File
def get_alpha_value(self): ''' getter Learning rate. ''' if isinstance(self.__alpha_value, float) is False: raise TypeError("The type of __alpha_value must be float.") return self.__alpha_value
getter Learning rate.
def IsDesktopLocked() -> bool: """ Check if desktop is locked. Return bool. Desktop is locked if press Win+L, Ctrl+Alt+Del or in remote desktop mode. """ isLocked = False desk = ctypes.windll.user32.OpenDesktopW(ctypes.c_wchar_p('Default'), 0, 0, 0x0100) # DESKTOP_SWITCHDESKTOP = 0x0100 ...
Check if desktop is locked. Return bool. Desktop is locked if press Win+L, Ctrl+Alt+Del or in remote desktop mode.
def post(self): """ Makes the HTTP POST to the url sending post_data. """ self._construct_post_data() post_args = {"json": self.post_data} self.http_method_args.update(post_args) return self.http_method("POST")
Makes the HTTP POST to the url sending post_data.
def zone_compare(timezone): ''' Compares the given timezone name with the system timezone name. Checks the hash sum between the given timezone, and the one set in /etc/localtime. Returns True if names and hash sums match, and False if not. Mostly useful for running state checks. .. versionchang...
Compares the given timezone name with the system timezone name. Checks the hash sum between the given timezone, and the one set in /etc/localtime. Returns True if names and hash sums match, and False if not. Mostly useful for running state checks. .. versionchanged:: 2016.3.0 .. note:: On...
def job_exists(name=None): ''' Check whether the job exists in configured Jenkins jobs. :param name: The name of the job is check if it exists. :return: True if job exists, False if job does not exist. CLI Example: .. code-block:: bash salt '*' jenkins.job_exists jobname ''' ...
Check whether the job exists in configured Jenkins jobs. :param name: The name of the job is check if it exists. :return: True if job exists, False if job does not exist. CLI Example: .. code-block:: bash salt '*' jenkins.job_exists jobname
def record_schemas( fn, wrapper, location, request_schema=None, response_schema=None): """Support extracting the schema from the decorated function.""" # have we already been decorated by an acceptable api call? has_acceptable = hasattr(fn, '_acceptable_metadata') if request_schema is not None:...
Support extracting the schema from the decorated function.
def get(self, request, format=None): """ Get list of bots --- serializer: BotSerializer responseMessages: - code: 401 message: Not authenticated """ bots = Bot.objects.filter(owner=request.user) serializer = BotSerializer(bots, ma...
Get list of bots --- serializer: BotSerializer responseMessages: - code: 401 message: Not authenticated
def patch_conf(settings_patch=None, settings_file=None): """ Reload the configuration form scratch. Only the default config is loaded, not the environment-specified config. Then the specified patch is applied. This is for unit tests only! :param settings_patch: Custom configuration values to ...
Reload the configuration form scratch. Only the default config is loaded, not the environment-specified config. Then the specified patch is applied. This is for unit tests only! :param settings_patch: Custom configuration values to insert :param settings_file: Custom settings file to read
def param_title(param_values, slug): """ Отображает наименование параметра товара Пример использования:: {% param_title item.paramvalue_set.all "producer" %} :param param_values: список значений параметров :param slug: символьный код параметра :return: """ for val in param_val...
Отображает наименование параметра товара Пример использования:: {% param_title item.paramvalue_set.all "producer" %} :param param_values: список значений параметров :param slug: символьный код параметра :return:
def cluster_elongate(): "Not so applicable for this sample" start_centers = [[1.0, 4.5], [3.1, 2.7]] template_clustering(start_centers, SIMPLE_SAMPLES.SAMPLE_ELONGATE, criterion = splitting_type.BAYESIAN_INFORMATION_CRITERION) template_clustering(start_centers, SIMPLE_SAMPLES.SAMPLE_ELONGATE, criter...
Not so applicable for this sample