code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def _travis_job_state(state): """ Converts a Travis state into a state character, color, and whether it's still running or a stopped state. """ if state in [None, 'queued', 'created', 'received']: return colorama.Fore.YELLOW, '*', True elif state in ['started', 'running']: return coloram...
Converts a Travis state into a state character, color, and whether it's still running or a stopped state.
def _get_principal(self, principal_arn): """ raise ResourceNotFoundException """ if ':cert/' in principal_arn: certs = [_ for _ in self.certificates.values() if _.arn == principal_arn] if len(certs) == 0: raise ResourceNotFoundException() ...
raise ResourceNotFoundException
def match_grade_system_id(self, grade_system_id, match): """Sets the grade system ``Id`` for this query. arg: grade_system_id (osid.id.Id): a grade system ``Id`` arg: match (boolean): ``true`` for a positive match, ``false`` for a negative match raise: NullArgumen...
Sets the grade system ``Id`` for this query. arg: grade_system_id (osid.id.Id): a grade system ``Id`` arg: match (boolean): ``true`` for a positive match, ``false`` for a negative match raise: NullArgument - ``grade_system_id`` is ``null`` *compliance: mandatory -...
def decode(in_bytes): """Decode a string using Consistent Overhead Byte Stuffing (COBS). Input should be a byte string that has been COBS encoded. Output is also a byte string. A cobs.DecodeError exception will be raised if the encoded data is invalid.""" if isinstance(in_bytes, str): ...
Decode a string using Consistent Overhead Byte Stuffing (COBS). Input should be a byte string that has been COBS encoded. Output is also a byte string. A cobs.DecodeError exception will be raised if the encoded data is invalid.
def covariance_eigvals(self): """ The two eigenvalues of the `covariance` matrix in decreasing order. """ if not np.isnan(np.sum(self.covariance)): eigvals = np.linalg.eigvals(self.covariance) if np.any(eigvals < 0): # negative variance ...
The two eigenvalues of the `covariance` matrix in decreasing order.
def set_auth_key( user, key, enc='ssh-rsa', comment='', options=None, config='.ssh/authorized_keys', cache_keys=None, fingerprint_hash_type=None): ''' Add a key to the authorized_keys file. The "key" parameter must only be the string of text th...
Add a key to the authorized_keys file. The "key" parameter must only be the string of text that is the encoded key. If the key begins with "ssh-rsa" or ends with user@host, remove those from the key before passing it to this function. CLI Example: .. code-block:: bash salt '*' ssh.set_aut...
def update_role_config_group(resource_root, service_name, name, apigroup, cluster_name="default"): """ Update a role config group by name. @param resource_root: The root Resource object. @param service_name: Service name. @param name: Role config group name. @param apigroup: The updated role config grou...
Update a role config group by name. @param resource_root: The root Resource object. @param service_name: Service name. @param name: Role config group name. @param apigroup: The updated role config group. @param cluster_name: Cluster name. @return: The updated ApiRoleConfigGroup object. @since: API v3
def hicup_stats_table(self): """ Add core HiCUP stats to the general stats table """ headers = OrderedDict() headers['Percentage_Ditags_Passed_Through_HiCUP'] = { 'title': '% Passed', 'description': 'Percentage Di-Tags Passed Through HiCUP', 'max': 100, ...
Add core HiCUP stats to the general stats table
def lrelu_sq(x): """ Concatenates lrelu and square """ dim = len(x.get_shape()) - 1 return tf.concat(dim, [lrelu(x), tf.minimum(tf.abs(x), tf.square(x))])
Concatenates lrelu and square
def sum_transactions(transactions): """ Sums transactions into a total of remaining vacation days. """ workdays_per_year = 250 previous_date = None rate = 0 day_sum = 0 for transaction in transactions: date, action, value = _parse_transaction_entry(transaction) if previous_date i...
Sums transactions into a total of remaining vacation days.
def GET(self): """ Handles GET request """ if self.user_manager.session_logged_in() or not self.app.allow_registration: raise web.notfound() error = False reset = None msg = "" data = web.input() if "activate" in data: msg, error = self.a...
Handles GET request
def _bind_ith_exec(self, i, data_shapes, label_shapes, shared_group): """Internal utility function to bind the i-th executor. This function utilizes simple_bind python interface. """ shared_exec = None if shared_group is None else shared_group.execs[i] context = self.contexts[i] ...
Internal utility function to bind the i-th executor. This function utilizes simple_bind python interface.
def default_get_arg_names_from_class_name(class_name): """Converts normal class names into normal arg names. Normal class names are assumed to be CamelCase with an optional leading underscore. Normal arg names are assumed to be lower_with_underscores. Args: class_name: a class name, e.g., "FooB...
Converts normal class names into normal arg names. Normal class names are assumed to be CamelCase with an optional leading underscore. Normal arg names are assumed to be lower_with_underscores. Args: class_name: a class name, e.g., "FooBar" or "_FooBar" Returns: all likely corresponding a...
def clean(ctx): """Clean previously built package artifacts. """ ctx.run(f'python setup.py clean') dist = ROOT.joinpath('dist') print(f'[clean] Removing {dist}') if dist.exists(): shutil.rmtree(str(dist))
Clean previously built package artifacts.
def copy_folder(self, dest_folder_id, source_folder_id): """ Copy a folder. Copy a folder (and its contents) from elsewhere in Canvas into a folder. Copying a folder across contexts (between courses and users) is permitted, but the source and destination must bel...
Copy a folder. Copy a folder (and its contents) from elsewhere in Canvas into a folder. Copying a folder across contexts (between courses and users) is permitted, but the source and destination must belong to the same institution. If the source and destination folders are...
def get_name_str(self, element): '''get_name_str High-level api: Produce a string that represents the name of a node. Parameters ---------- element : `Element` A node in model tree. Returns ------- str A string that represents ...
get_name_str High-level api: Produce a string that represents the name of a node. Parameters ---------- element : `Element` A node in model tree. Returns ------- str A string that represents the name of a node.
def get_files_types(self): """ Return the files inside the APK with their associated types (by using python-magic) :rtype: a dictionnary """ if self._files == {}: # Generate File Types / CRC List for i in self.get_files(): buffer = self.zi...
Return the files inside the APK with their associated types (by using python-magic) :rtype: a dictionnary
def ascii2h5(bh_dir=None): """ Convert the Burstein & Heiles (1982) dust map from ASCII to HDF5. """ if bh_dir is None: bh_dir = os.path.join(data_dir_default, 'bh') fname = os.path.join(bh_dir, '{}.ascii') f = h5py.File('bh.h5', 'w') for region in ('hinorth', 'hisouth'): ...
Convert the Burstein & Heiles (1982) dust map from ASCII to HDF5.
def enable(self, cmd="sudo su", pattern="ssword", re_flags=re.IGNORECASE): """Attempt to become root.""" delay_factor = self.select_delay_factor(delay_factor=0) output = "" if not self.check_enable_mode(): self.write_channel(self.normalize_cmd(cmd)) time.sleep(0.3...
Attempt to become root.
def get_revocation_time(self): """Get the revocation time as naive datetime. Note that this method is only used by cryptography>=2.4. """ if self.revoked is False: return if timezone.is_aware(self.revoked_date): # convert datetime object to UTC and make ...
Get the revocation time as naive datetime. Note that this method is only used by cryptography>=2.4.
def invertible_total_flatten(unflat_list): r""" Args: unflat_list (list): Returns: tuple: (flat_list, invert_levels) CommandLine: python -m utool.util_list --exec-invertible_total_flatten --show Example: >>> # DISABLE_DOCTEST >>> from utool.util_list import...
r""" Args: unflat_list (list): Returns: tuple: (flat_list, invert_levels) CommandLine: python -m utool.util_list --exec-invertible_total_flatten --show Example: >>> # DISABLE_DOCTEST >>> from utool.util_list import * # NOQA >>> import utool as ut ...
def _ParseFileData(self, knowledge_base, file_object): """Parses file content (data) for system product preprocessing attribute. Args: knowledge_base (KnowledgeBase): to fill with preprocessing information. file_object (dfvfs.FileIO): file-like object that contains the artifact value data...
Parses file content (data) for system product preprocessing attribute. Args: knowledge_base (KnowledgeBase): to fill with preprocessing information. file_object (dfvfs.FileIO): file-like object that contains the artifact value data. Raises: errors.PreProcessFail: if the preprocessi...
def apt_add_repository_from_apt_string(apt_string, apt_file): """ adds a new repository file for apt """ apt_file_path = '/etc/apt/sources.list.d/%s' % apt_file if not file_contains(apt_file_path, apt_string.lower(), use_sudo=True): file_append(apt_file_path, apt_string.lower(), use_sudo=True) ...
adds a new repository file for apt
def write_cookies_to_cache(cj, username): """ Save RequestsCookieJar to disk in Mozilla's cookies.txt file format. This prevents us from repeated authentications on the accounts.coursera.org and class.coursera.org/class_name sites. """ mkdir_p(PATH_COOKIES, 0o700) path = get_cookies_cache_p...
Save RequestsCookieJar to disk in Mozilla's cookies.txt file format. This prevents us from repeated authentications on the accounts.coursera.org and class.coursera.org/class_name sites.
def load_inhibit(self, train=True, test=True) -> tuple: """Generate data with inhibitory inputs created from wake word samples""" def loader(kws: list, nkws: list): from precise.params import pr inputs = np.empty((0, pr.n_features, pr.feature_size)) outputs = np.zero...
Generate data with inhibitory inputs created from wake word samples
async def send_request(self): """Coroutine to send request headers with metadata to the server. New HTTP/2 stream will be created during this coroutine call. .. note:: This coroutine will be called implicitly during first :py:meth:`send_message` coroutine call, if not called before...
Coroutine to send request headers with metadata to the server. New HTTP/2 stream will be created during this coroutine call. .. note:: This coroutine will be called implicitly during first :py:meth:`send_message` coroutine call, if not called before explicitly.
def _cast_expected_to_returned_type(expected, returned): ''' Determine the type of variable returned Cast the expected to the type of variable returned ''' ret_type = type(returned) new_expected = expected if expected == "False" and ret_type == bool: e...
Determine the type of variable returned Cast the expected to the type of variable returned
def append(self, cls, infer_hidden: bool = False, **kwargs) -> Encoder: """ Extends sequence with new Encoder. 'dtype' gets passed into Encoder instance if not present in parameters and supported by specific Encoder type. :param cls: Encoder type. :param infer_hidden: If number ...
Extends sequence with new Encoder. 'dtype' gets passed into Encoder instance if not present in parameters and supported by specific Encoder type. :param cls: Encoder type. :param infer_hidden: If number of hidden should be inferred from previous encoder. :param kwargs: Named arbitrary p...
def _save_npz(self): ''' Saves all of the de-trending information to disk in an `npz` file ''' # Save the data d = dict(self.__dict__) d.pop('_weights', None) d.pop('_A', None) d.pop('_B', None) d.pop('_f', None) d.pop('_mK', None) ...
Saves all of the de-trending information to disk in an `npz` file
def processDefines(defs): """process defines, resolving strings, lists, dictionaries, into a list of strings """ if SCons.Util.is_List(defs): l = [] for d in defs: if d is None: continue elif SCons.Util.is_List(d) or isinstance(d, tuple): ...
process defines, resolving strings, lists, dictionaries, into a list of strings
def from_csv(cls, path:PathOrStr, csv_name, valid_pct:float=0.2, test:Optional[str]=None, tokenizer:Tokenizer=None, vocab:Vocab=None, classes:Collection[str]=None, delimiter:str=None, header='infer', text_cols:IntsOrStrs=1, label_cols:IntsOrStrs=0, label_delim:str=None, ...
Create a `TextDataBunch` from texts in csv files. `kwargs` are passed to the dataloader creation.
def search_responsify(serializer, mimetype): """Create a Records-REST search result response serializer. :param serializer: Serializer instance. :param mimetype: MIME type of response. :returns: Function that generates a record HTTP response. """ def view(pid_fetcher, search_result, code=200, h...
Create a Records-REST search result response serializer. :param serializer: Serializer instance. :param mimetype: MIME type of response. :returns: Function that generates a record HTTP response.
def emulate_mouse(self, key_code, x_val, y_val, data): """Emulate the ev codes using the data Windows has given us. Note that by default in Windows, to recognise a double click, you just notice two clicks in a row within a reasonablely short time period. However, if the applica...
Emulate the ev codes using the data Windows has given us. Note that by default in Windows, to recognise a double click, you just notice two clicks in a row within a reasonablely short time period. However, if the application developer sets the application window's class style t...
def _runcmd(progargs, stdinput=None): ''' Run the command progargs with optional input to be fed in to stdin. ''' stdin = None if stdinput is not None: assert(isinstance(stdinput, list)) stdin=PIPE err = 0 output = b'' log_debug("Calling {} with input {}".format(' '.join...
Run the command progargs with optional input to be fed in to stdin.
def get_schema_descendant( self, route: SchemaRoute) -> Optional[SchemaNode]: """Return descendant schema node or ``None`` if not found. Args: route: Schema route to the descendant node (relative to the receiver). """ node = self for p ...
Return descendant schema node or ``None`` if not found. Args: route: Schema route to the descendant node (relative to the receiver).
def transformer_ada_lmpackedbase_dialog(): """Set of hyperparameters.""" hparams = transformer_base_vq_ada_32ex_packed() hparams.max_length = 1024 hparams.ffn_layer = "dense_relu_dense" hparams.batch_size = 4096 return hparams
Set of hyperparameters.
def get_start_time(self): """ Return the start time of the entry as a :class:`datetime.time` object. If the start time is `None`, the end time of the previous entry will be returned instead. If the current entry doesn't have a duration in the form of a tuple, if there's no previo...
Return the start time of the entry as a :class:`datetime.time` object. If the start time is `None`, the end time of the previous entry will be returned instead. If the current entry doesn't have a duration in the form of a tuple, if there's no previous entry or if the previous entry has ...
def delete_message_from_handle(self, queue, receipt_handle): """ Delete a message from a queue, given a receipt handle. :type queue: A :class:`boto.sqs.queue.Queue` object :param queue: The Queue from which messages are read. :type receipt_handle: str :param rec...
Delete a message from a queue, given a receipt handle. :type queue: A :class:`boto.sqs.queue.Queue` object :param queue: The Queue from which messages are read. :type receipt_handle: str :param receipt_handle: The receipt handle for the message :rtype: bool ...
def save_figure_raw_data(figure="gcf", **kwargs): """ This will just output an ascii file for each of the traces in the shown figure. **kwargs are sent to dialogs.Save() """ # choose a path to save to path = _s.dialogs.Save(**kwargs) if path=="": return "aborted." # if no argument was...
This will just output an ascii file for each of the traces in the shown figure. **kwargs are sent to dialogs.Save()
def snapshot (self): """Take a snapshot of the experiment. Returns `self`.""" nextSnapshotNum = self.nextSnapshotNum nextSnapshotPath = self.getFullPathToSnapshot(nextSnapshotNum) if os.path.lexists(nextSnapshotPath): self.rmR(nextSnapshotPath) self.mkdirp(os.path.join(nextSnapshotPath...
Take a snapshot of the experiment. Returns `self`.
def camera_info(self, camera_ids, **kwargs): """Return a list of cameras matching camera_ids.""" api = self._api_info['camera'] payload = dict({ '_sid': self._sid, 'api': api['name'], 'method': 'GetInfo', 'version': api['version'], 'cam...
Return a list of cameras matching camera_ids.
def add(self, chassis): """ add chassis. :param chassis: chassis IP address. """ self.chassis_chain[chassis] = IxeChassis(self.session, chassis, len(self.chassis_chain) + 1) self.chassis_chain[chassis].connect()
add chassis. :param chassis: chassis IP address.
def _set_up_schema_elements_of_kind(self, class_name_to_definition, kind, class_names): """Load all schema classes of the given kind. Used as part of __init__.""" allowed_duplicated_edge_property_names = frozenset({ EDGE_DESTINATION_PROPERTY_NAME, EDGE_SOURCE_PROPERTY_NAME }) ...
Load all schema classes of the given kind. Used as part of __init__.
def respond_unauthorized(self, request_authentication=False): """ Respond to the client that the request is unauthorized. :param bool request_authentication: Whether to request basic authentication information by sending a WWW-Authenticate header. """ headers = {} if request_authentication: headers['WWW...
Respond to the client that the request is unauthorized. :param bool request_authentication: Whether to request basic authentication information by sending a WWW-Authenticate header.
def nonzero(self): """ property decorated method to get a new ObservationEnsemble of only non-zero weighted observations Returns ------- ObservationEnsemble : ObservationEnsemble """ df = self.loc[:,self.pst.nnz_obs_names] return ObservationEnsemble.from...
property decorated method to get a new ObservationEnsemble of only non-zero weighted observations Returns ------- ObservationEnsemble : ObservationEnsemble
def list_hosting_device_handled_by_config_agent( self, client, cfg_agent_id, **_params): """Fetches a list of hosting devices handled by a config agent.""" return client.get((ConfigAgentHandlingHostingDevice.resource_path + CFG_AGENT_HOSTING_DEVICES) % cfg_agent_id...
Fetches a list of hosting devices handled by a config agent.
def set_request(self, method=None, sub_url="", data=None, params=None, proxies=None): """ :param method: str of the method of the api_call :param sub_url: str of the url after the uri :param data: dict of form data to be sent with the request :param params: di...
:param method: str of the method of the api_call :param sub_url: str of the url after the uri :param data: dict of form data to be sent with the request :param params: dict of additional data to be sent as the request args :param proxies: str of the proxie to use :return: None
def write(self, outfile): """Write the livetime cube to a FITS file.""" hdu_pri = fits.PrimaryHDU() hdu_exp = self._create_exp_hdu(self.data) hdu_exp.name = 'EXPOSURE' hdu_exp_wt = self._create_exp_hdu(self._data_wt) hdu_exp_wt.name = 'WEIGHTED_EXPOSURE' cols =...
Write the livetime cube to a FITS file.
def _compute_B_statistics(self, K, W, log_concave, *args, **kwargs): """ Rasmussen suggests the use of a numerically stable positive definite matrix B Which has a positive diagonal elements and can be easily inverted :param K: Prior Covariance matrix evaluated at locations X :ty...
Rasmussen suggests the use of a numerically stable positive definite matrix B Which has a positive diagonal elements and can be easily inverted :param K: Prior Covariance matrix evaluated at locations X :type K: NxN matrix :param W: Negative hessian at a point (diagonal matrix) ...
def _RunActions(self, rule, client_id): """Run all the actions specified in the rule. Args: rule: Rule which actions are to be executed. client_id: Id of a client where rule's actions are to be executed. Returns: Number of actions started. """ actions_count = 0 for action in...
Run all the actions specified in the rule. Args: rule: Rule which actions are to be executed. client_id: Id of a client where rule's actions are to be executed. Returns: Number of actions started.
def GetNextWrittenEventSource(self): """Retrieves the next event source that was written after open. Returns: EventSource: event source or None if there are no newly written ones. Raises: IOError: when the storage writer is closed. OSError: when the storage writer is closed. """ ...
Retrieves the next event source that was written after open. Returns: EventSource: event source or None if there are no newly written ones. Raises: IOError: when the storage writer is closed. OSError: when the storage writer is closed.
def copy_to(self, destination): """ Copies the file to the given destination. Returns a File object that represents the target file. `destination` must be a File or Folder object. """ target = self.__get_destination__(destination) logger.info("Copying %s to %s" % ...
Copies the file to the given destination. Returns a File object that represents the target file. `destination` must be a File or Folder object.
def factory(cls, note, fn=None): """Register a function as a provider. Function (name support is optional):: from jeni import Injector as BaseInjector from jeni import Provider class Injector(BaseInjector): pass @Injector.factory('echo'...
Register a function as a provider. Function (name support is optional):: from jeni import Injector as BaseInjector from jeni import Provider class Injector(BaseInjector): pass @Injector.factory('echo') def echo(name=None): ...
def HashIt(self): """Finalizing function for the Fingerprint class. This method applies all the different hash functions over the previously specified different ranges of the input file, and computes the resulting hashes. After calling HashIt, the state of the object is reset to its initial st...
Finalizing function for the Fingerprint class. This method applies all the different hash functions over the previously specified different ranges of the input file, and computes the resulting hashes. After calling HashIt, the state of the object is reset to its initial state, with no fingers defi...
def short_title(self, key, value): """Populate the ``short_title`` key. Also populates the ``title_variants`` key through side effects. """ short_title = value.get('a') title_variants = self.get('title_variants', []) if value.get('u'): short_title = value.get('u') title_variant...
Populate the ``short_title`` key. Also populates the ``title_variants`` key through side effects.
def install(name=None, refresh=False, pkgs=None, version=None, test=False, **kwargs): ''' Install the named fileset(s)/rpm package(s). name The name of the fileset or rpm package to be installed. refresh Whether or not to update the yum database before executing. Multiple Package...
Install the named fileset(s)/rpm package(s). name The name of the fileset or rpm package to be installed. refresh Whether or not to update the yum database before executing. Multiple Package Installation Options: pkgs A list of filesets and/or rpm packages to install. ...
def _create_parsing_plan(self, desired_type: Type[T], filesystem_object: PersistedObject, logger: Logger, log_only_last: bool = False): """ Adds a log message and creates a recursive parsing plan. :param desired_type: :param filesystem_object: :param...
Adds a log message and creates a recursive parsing plan. :param desired_type: :param filesystem_object: :param logger: :param log_only_last: a flag to only log the last part of the file path (default False) :return:
def CheckApproversForLabel(self, token, client_urn, requester, approvers, label): """Checks if requester and approvers have approval privileges for labels. Checks against list of approvers for each label defined in approvers.yaml to determine if the list of approvers is suffici...
Checks if requester and approvers have approval privileges for labels. Checks against list of approvers for each label defined in approvers.yaml to determine if the list of approvers is sufficient. Args: token: user token client_urn: ClientURN object of the client requester: username str...
def deleteGenome(species, name) : """Removes a genome from the database""" printf('deleting genome (%s, %s)...' % (species, name)) conf.db.beginTransaction() objs = [] allGood = True try : genome = Genome_Raba(name = name, species = species.lower()) objs.append(genome) ...
Removes a genome from the database
def street_address(self): """ :example '791 Crist Parks' """ pattern = self.random_element(self.street_address_formats) return self.generator.parse(pattern)
:example '791 Crist Parks'
def _get_audio_sample_rate(self, audio_abs_path): """ Parameters ---------- audio_abs_path : str Returns ------- sample_rate : int """ sample_rate = int( subprocess.check_output( ("""sox --i {} | grep "{}" | awk -F " : " ...
Parameters ---------- audio_abs_path : str Returns ------- sample_rate : int
def verify_oauth2_token(id_token, request, audience=None): """Verifies an ID Token issued by Google's OAuth 2.0 authorization server. Args: id_token (Union[str, bytes]): The encoded token. request (google.auth.transport.Request): The object used to make HTTP requests. audien...
Verifies an ID Token issued by Google's OAuth 2.0 authorization server. Args: id_token (Union[str, bytes]): The encoded token. request (google.auth.transport.Request): The object used to make HTTP requests. audience (str): The audience that this token is intended for. This is ...
def _add_conversation(self, conversation): """ Add the conversation and fire the :meth:`on_conversation_added` event. :param conversation: The conversation object to add. :type conversation: :class:`~.AbstractConversation` The conversation is added to the internal list of conve...
Add the conversation and fire the :meth:`on_conversation_added` event. :param conversation: The conversation object to add. :type conversation: :class:`~.AbstractConversation` The conversation is added to the internal list of conversations which can be queried at :attr:`conversations`....
def is_ge(dicom_input): """ Use this function to detect if a dicom series is a GE dataset :param dicom_input: list with dicom objects """ # read dicom header header = dicom_input[0] if 'Manufacturer' not in header or 'Modality' not in header: return False # we try generic conversi...
Use this function to detect if a dicom series is a GE dataset :param dicom_input: list with dicom objects
def add_filter(self, property_name, operator, value): """Filter the query based on a property name, operator and a value. Expressions take the form of:: .add_filter('<property>', '<operator>', <value>) where property is a property stored on the entity in the datastore and op...
Filter the query based on a property name, operator and a value. Expressions take the form of:: .add_filter('<property>', '<operator>', <value>) where property is a property stored on the entity in the datastore and operator is one of ``OPERATORS`` (ie, ``=``, ``<``, ``<=``,...
def get_highest_build_tool(sdk_version=None): """ Gets the highest build tool version based on major version sdk version. :param sdk_version(int) - sdk version to be used as the marjor build tool version context. Returns: A string containg the build tool version (default is 23.0.2 if none is found) """ ...
Gets the highest build tool version based on major version sdk version. :param sdk_version(int) - sdk version to be used as the marjor build tool version context. Returns: A string containg the build tool version (default is 23.0.2 if none is found)
def get_login_info(): """ Give back an array of dicts with the connection information for all the environments. """ connections = {} _defaults = {} _defaults['start_in'] = '' _defaults['rpm_sign_plugin'] = '' config = _config_file() _config_test(config) juicer.utils.Log.lo...
Give back an array of dicts with the connection information for all the environments.
def migrate_window(bg): "Take a pythoncard background resource and convert to a gui2py window" ret = {} for k, v in bg.items(): if k == 'type': v = WIN_MAP[v]._meta.name elif k == 'menubar': menus = v['menus'] v = [migrate_control(menu) for menu in menus] ...
Take a pythoncard background resource and convert to a gui2py window
def get_tissue_specificities(cls, entry): """ get list of :class:`pyuniprot.manager.models.TissueSpecificity` object from XML node entry :param entry: XML node entry :return: models.TissueSpecificity object """ tissue_specificities = [] query = "./comment[@type=...
get list of :class:`pyuniprot.manager.models.TissueSpecificity` object from XML node entry :param entry: XML node entry :return: models.TissueSpecificity object
def get_meta(self): """Get the metadata object for this Point Returns a [PointMeta](PointMeta.m.html#IoticAgent.IOT.PointMeta.PointMeta) object - OR - Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a ...
Get the metadata object for this Point Returns a [PointMeta](PointMeta.m.html#IoticAgent.IOT.PointMeta.PointMeta) object - OR - Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkEx...
def logs(self): """returns an object to work with the site logs""" if self._resources is None: self.__init() if "logs" in self._resources: url = self._url + "/logs" return _logs.Log(url=url, securityHandler=self._securityHandler, ...
returns an object to work with the site logs
def __send_log_set_exc_and_wait(self, msg, level=None, wait_seconds=CONN_RETRY_DELAY_SECONDS): """To be called in exception context only. msg - message to log level - logging level. If not specified, ERROR unless it is a repeated failure in which case DEBUG. If specified, the given leve...
To be called in exception context only. msg - message to log level - logging level. If not specified, ERROR unless it is a repeated failure in which case DEBUG. If specified, the given level will always be used. wait_seconds - how long to pause for (so retry is not triggered immediately...
def fence_status_encode(self, breach_status, breach_count, breach_type, breach_time): ''' Status of geo-fencing. Sent in extended status stream when fencing enabled breach_status : 0 if currently inside fence, 1 if outside (uint8_t) ...
Status of geo-fencing. Sent in extended status stream when fencing enabled breach_status : 0 if currently inside fence, 1 if outside (uint8_t) breach_count : number of fence breaches (uint16_t) breach_type : last bre...
def add(self, *l): '''add inner to outer Args: *l: element that is passed into Inner init ''' for a in flatten(l): self._add([self.Inner(a)], self.l)
add inner to outer Args: *l: element that is passed into Inner init
def save(self,callit="misc",closeToo=True,fullpath=False): """save the existing figure. does not close it.""" if fullpath is False: fname=self.abf.outPre+"plot_"+callit+".jpg" else: fname=callit if not os.path.exists(os.path.dirname(fname)): os.mkdir(o...
save the existing figure. does not close it.
def run_plugins(context_obj, boto3_clients): """ Executes all loaded plugins designated for the service calling the function. Args: context_obj (obj:EFContext): The EFContext object created by the service. boto3_clients (dict): Dictionary of boto3 clients created by ef_utils.create_aws_clients() """ ...
Executes all loaded plugins designated for the service calling the function. Args: context_obj (obj:EFContext): The EFContext object created by the service. boto3_clients (dict): Dictionary of boto3 clients created by ef_utils.create_aws_clients()
def delete_userpass(self, username, mount_point='userpass'): """DELETE /auth/<mount point>/users/<username> :param username: :type username: :param mount_point: :type mount_point: :return: :rtype: """ return self._adapter.delete('/v1/auth/{}/users...
DELETE /auth/<mount point>/users/<username> :param username: :type username: :param mount_point: :type mount_point: :return: :rtype:
def setup_tree(ctx, verbose=None, root=None, tree_dir=None, modules_dir=None): ''' Sets up the SDSS tree enviroment ''' print('Setting up the tree') ctx.run('python bin/setup_tree.py -t {0} -r {1} -m {2}'.format(tree_dir, root, modules_dir))
Sets up the SDSS tree enviroment
def GetFieldValuesTuple(self, trip_id): """Return a tuple that outputs a row of _FIELD_NAMES to be written to a GTFS file. Arguments: trip_id: The trip_id of the trip to which this StopTime corresponds. It must be provided, as it is not stored in StopTime. """ result = [...
Return a tuple that outputs a row of _FIELD_NAMES to be written to a GTFS file. Arguments: trip_id: The trip_id of the trip to which this StopTime corresponds. It must be provided, as it is not stored in StopTime.
def FrameworkDir32(self): """ Microsoft .NET Framework 32bit directory. """ # Default path guess_fw = os.path.join(self.WinDir, r'Microsoft.NET\Framework') # Try to get path from registry, if fail use default path return self.ri.lookup(self.ri.vc, 'frameworkdir32...
Microsoft .NET Framework 32bit directory.
def getTypeWidth(self, dtype: HdlType, do_eval=False) -> Tuple[int, Union[int, RtlSignal], bool]: """ :see: doc of method on parent class """ width = dtype.width if isinstance(width, int): widthStr = str(width) else: widthStr = self.getExprVal(widt...
:see: doc of method on parent class
def get_source_lane(fork_process, pipeline_list): """Returns the lane of the last process that matches fork_process Parameters ---------- fork_process : list List of processes before the fork. pipeline_list : list List with the pipeline connection dictionaries. Returns ----...
Returns the lane of the last process that matches fork_process Parameters ---------- fork_process : list List of processes before the fork. pipeline_list : list List with the pipeline connection dictionaries. Returns ------- int Lane of the last process that matches...
def _nick(self, nick): """ Sets your nick. Required arguments: * nick - New nick. """ with self.lock: self.send('NICK :%s' % nick) if self.readable(): msg = self._recv(expected_replies='NICK') if msg[0] == 'NICK': ...
Sets your nick. Required arguments: * nick - New nick.
def list_lbaas_loadbalancers(self, retrieve_all=True, **_params): """Fetches a list of all lbaas_loadbalancers for a project.""" return self.list('loadbalancers', self.lbaas_loadbalancers_path, retrieve_all, **_params)
Fetches a list of all lbaas_loadbalancers for a project.
def get_nameserver_detail_output_show_nameserver_nameserver_cascaded(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_nameserver_detail = ET.Element("get_nameserver_detail") config = get_nameserver_detail output = ET.SubElement(get_nameserver_...
Auto Generated Code
def greenhall_sz(t, F, alpha, d): """ Eqn (9) from Greenhall2004 """ if d == 1: a = 2*greenhall_sx(t, F, alpha) b = greenhall_sx(t-1.0, F, alpha) c = greenhall_sx(t+1.0, F, alpha) return a-b-c elif d == 2: a = 6*greenhall_sx(t, F, alpha) b = 4*greenhall_sx(t-1...
Eqn (9) from Greenhall2004
def validate(method): """ Config option name value validator decorator. """ # Name error template name_error = 'configuration option "{}" is not supported' @functools.wraps(method) def validator(self, name, *args): if name not in self.allowed_opts: raise ValueError(name_...
Config option name value validator decorator.
def main(): """Run playbook""" for flag in ('--check',): if flag not in sys.argv: sys.argv.append(flag) obj = PlaybookCLI(sys.argv) obj.parse() obj.run()
Run playbook
def codestr2rst(codestr, lang='python'): """Return reStructuredText code block from code string""" code_directive = "\n.. code-block:: {0}\n\n".format(lang) indented_block = indent(codestr, ' ' * 4) return code_directive + indented_block
Return reStructuredText code block from code string
def p_statement_border(p): """ statement : BORDER expr """ p[0] = make_sentence('BORDER', make_typecast(TYPE.ubyte, p[2], p.lineno(1)))
statement : BORDER expr
def auth(self, username, password): """Authentication of a user""" binddn = self._get_user(self._byte_p2(username), NO_ATTR) if binddn is not None: ldap_client = self._connect() try: ldap_client.simple_bind_s( self._byte_p2(binddn)...
Authentication of a user
def _currentLineExtraSelections(self): """QTextEdit.ExtraSelection, which highlightes current line """ if self._currentLineColor is None: return [] def makeSelection(cursor): selection = QTextEdit.ExtraSelection() selection.format.setBackground(self._...
QTextEdit.ExtraSelection, which highlightes current line
def starlike(x): "weird things happen to cardinality when working with * in comma-lists. this detects when to do that." # todo: is '* as name' a thing? return isinstance(x,sqparse2.AsterX) or isinstance(x,sqparse2.AttrX) and isinstance(x.attr,sqparse2.AsterX)
weird things happen to cardinality when working with * in comma-lists. this detects when to do that.
def map_list(key_map, *inputs, copy=False, base=None): """ Returns a new dict. :param key_map: A list that maps the dict keys ({old key: new key} :type key_map: list[str | dict | list] :param inputs: A sequence of data. :type inputs: iterable | dict | int | float | list | tuple...
Returns a new dict. :param key_map: A list that maps the dict keys ({old key: new key} :type key_map: list[str | dict | list] :param inputs: A sequence of data. :type inputs: iterable | dict | int | float | list | tuple :param copy: If True, it returns a deepcopy of input ...
def partsphere(self, x): """Sphere (squared norm) test objective function""" self.counter += 1 # return np.random.rand(1)[0]**0 * sum(x**2) + 1 * np.random.rand(1)[0] dim = len(x) x = array([x[i % dim] for i in xrange(2 * dim)]) N = 8 i = self.counter % dim ...
Sphere (squared norm) test objective function
def create(self, **kwargs): """ returns the JSON object {'embedded': { 'sign_url': 'https://www.hellosign.com/editor/embeddedSign?signature_id={signature_id}&token={token}', 'expires_at': {timestamp} }} """ auth = None if 'auth' in kwar...
returns the JSON object {'embedded': { 'sign_url': 'https://www.hellosign.com/editor/embeddedSign?signature_id={signature_id}&token={token}', 'expires_at': {timestamp} }}
def safe_dump_pk(obj, abspath, pk_protocol=pk_protocol, compress=False, enable_verbose=True): """A stable version of dump_pk, silently overwrite existing file. When your program been interrupted, you lose nothing. Typically if your program is interrupted by any reason, it only leaves a inc...
A stable version of dump_pk, silently overwrite existing file. When your program been interrupted, you lose nothing. Typically if your program is interrupted by any reason, it only leaves a incomplete file. If you use replace=True, then you also lose your old file. So a bettr way is to: 1. dump p...
def get_firewall_rule(self, datacenter_id, server_id, nic_id, firewall_rule_id): """ Retrieves a single firewall rule by ID. :param datacenter_id: The unique ID of the data center. :type datacenter_id: ``str`` :param server_id: The uniq...
Retrieves a single firewall rule by ID. :param datacenter_id: The unique ID of the data center. :type datacenter_id: ``str`` :param server_id: The unique ID of the server. :type server_id: ``str`` :param nic_id: The unique ID of the NIC. :typ...
def dug(obj, key, value): """ Inverse of dig: recursively set a value in a dictionary, using dot notation. >>> test = {"a":{"b":{"c":1}}} >>> dug(test, "a.b.c", 10) >>> test {'a': {'b': {'c': 10}}} """ array = key.split(".") return _dug(obj, value, *array)
Inverse of dig: recursively set a value in a dictionary, using dot notation. >>> test = {"a":{"b":{"c":1}}} >>> dug(test, "a.b.c", 10) >>> test {'a': {'b': {'c': 10}}}
def enable_argscope_for_module(module, log_shape=True): """ Overwrite all functions of a given module to support argscope. Note that this function monkey-patches the module and therefore could have unexpected consequences. It has been only tested to work well with ``tf.layers`` module. Example:...
Overwrite all functions of a given module to support argscope. Note that this function monkey-patches the module and therefore could have unexpected consequences. It has been only tested to work well with ``tf.layers`` module. Example: .. code-block:: python import tensorflow as t...