code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def update_compaction(model): """Updates the compaction options for the given model if necessary. :param model: The model to update. :return: `True`, if the compaction options were modified in Cassandra, `False` otherwise. :rtype: bool """ logger.debug("Checking %s for compaction diffe...
Updates the compaction options for the given model if necessary. :param model: The model to update. :return: `True`, if the compaction options were modified in Cassandra, `False` otherwise. :rtype: bool
def load_history(self) -> List["IterationRecord"]: """ Load messaging history from disk to self. :returns: List of iteration records comprising history. """ if path.isfile(self.history_filename): with open(self.history_filename, "r") as f: try: ...
Load messaging history from disk to self. :returns: List of iteration records comprising history.
def safe_unicode(e): """unicode(e) with various fallbacks. Used for exceptions, which may not be safe to call unicode() on. """ try: return unicode(e) except UnicodeError: pass try: return py3compat.str_to_unicode(str(e)) except UnicodeError: pass try: ...
unicode(e) with various fallbacks. Used for exceptions, which may not be safe to call unicode() on.
def filter(self, **search_args): """ Get a filtered list of resources :param search_args: To be translated into ?arg1=value1&arg2=value2... :return: A list of resources """ search_args = search_args or {} raw_resources = [] for url, paginator_params in se...
Get a filtered list of resources :param search_args: To be translated into ?arg1=value1&arg2=value2... :return: A list of resources
def link_android(self, path, pkg): """ Link's the android project to this library. 1. Includes this project's directory in the app's android/settings.gradle It adds: include ':<project-name>' project(':<project-name>').projectDir = new File( ...
Link's the android project to this library. 1. Includes this project's directory in the app's android/settings.gradle It adds: include ':<project-name>' project(':<project-name>').projectDir = new File( rootProject.projectDir, '../package...
def clear_cache(self): ''' Completely clear cache ''' errors = [] for rdir in (self.cache_root, self.file_list_cachedir): if os.path.exists(rdir): try: shutil.rmtree(rdir) except OSError as exc: e...
Completely clear cache
def load_pdb(self, pdb_id, mapped_chains=None, pdb_file=None, file_type=None, is_experimental=True, set_as_representative=False, representative_chain=None, force_rerun=False): """Load a structure ID and optional structure file into the structures attribute. Args: pdb_id (st...
Load a structure ID and optional structure file into the structures attribute. Args: pdb_id (str): PDB ID mapped_chains (str, list): Chain ID or list of IDs which you are interested in pdb_file (str): Path to PDB file file_type (str): Type of PDB file ...
def update_default_output_dir(self): """Update output dir if set to default.""" if self.scenario_directory_radio.isChecked(): self.output_directory.setText(self.source_directory.text())
Update output dir if set to default.
def handle_events(self): """ An event handler that processes events from stdin and calls the on_click function of the respective object. This function is run in another thread, so as to not stall the main thread. """ for event in sys.stdin: if event.startswith...
An event handler that processes events from stdin and calls the on_click function of the respective object. This function is run in another thread, so as to not stall the main thread.
def _ParsePlistKeyValue(self, knowledge_base, name, value): """Parses a plist key value. Args: knowledge_base (KnowledgeBase): to fill with preprocessing information. name (str): name of the plist key. value (str): value of the plist key. """ if not knowledge_base.GetValue('keyboard_l...
Parses a plist key value. Args: knowledge_base (KnowledgeBase): to fill with preprocessing information. name (str): name of the plist key. value (str): value of the plist key.
def make_middleware_stack(middleware, base): """ Given a list of in-order middleware callable objects `middleware` and a base function `base`, chains them together so each middleware is fed the function below, and returns the top level ready to call. :param middleware: The middleware st...
Given a list of in-order middleware callable objects `middleware` and a base function `base`, chains them together so each middleware is fed the function below, and returns the top level ready to call. :param middleware: The middleware stack :type middleware: iterable[callable] :param b...
def _log_players(self, players): """ :param players: list of catan.game.Player objects """ self._logln('players: {0}'.format(len(players))) for p in self._players: self._logln('name: {0}, color: {1}, seat: {2}'.format(p.name, p.color, p.seat))
:param players: list of catan.game.Player objects
def property_schema(self, key): """ Lookup the schema for a specific property. """ schema = self.__class__.SCHEMA # first try plain properties plain_schema = schema.get("properties", {}).get(key) if plain_schema is not None: return plain_schema ...
Lookup the schema for a specific property.
def write_collection_from_tmpfile(self, collection_id, tmpfi, parent_sha, auth_info, commit_msg=''): """Given a collection_id, temporary filename of content, branch and auth_info """ return self.write_doc_from_tmpfile(collection_id, tmpfi, ...
Given a collection_id, temporary filename of content, branch and auth_info
def rfdist_task(newick_string_a, newick_string_b, normalise, min_overlap=4, overlap_fail_value=0): """ Distributed version of tree_distance.rfdist Parameters: two valid newick strings and a boolean """ tree_a = Tree(newick_string_a) tree_b = Tree(newick_string_b) return treedist.rfdist(tree_...
Distributed version of tree_distance.rfdist Parameters: two valid newick strings and a boolean
def is_stopword(self, text): """ Determine whether a single word is a stopword, or whether a short phrase is made entirely of stopwords, disregarding context. Use of this function should be avoided; it's better to give the text in context and let the process determine which word...
Determine whether a single word is a stopword, or whether a short phrase is made entirely of stopwords, disregarding context. Use of this function should be avoided; it's better to give the text in context and let the process determine which words are the stopwords.
def get_license_manager(service_instance): ''' Returns the license manager. service_instance The Service Instance Object from which to obrain the license manager. ''' log.debug('Retrieving license manager') try: lic_manager = service_instance.content.licenseManager except v...
Returns the license manager. service_instance The Service Instance Object from which to obrain the license manager.
def page(self, number): """ Returns a Page object for the given 1-based page number. """ number = self.validate_number(number) bottom = (number - 1) * self.per_page top = bottom + self.per_page if top + self.orphans >= self.count: top = self.count ...
Returns a Page object for the given 1-based page number.
def cli_wrapper(generator): """Given a wizard, implements an interactive command-line human-friendly interface for it. Parameters ---------- generator A generator such as one created by calling :py:func:`rig.wizard.wizard_generator`. Returns ------- dict or None ...
Given a wizard, implements an interactive command-line human-friendly interface for it. Parameters ---------- generator A generator such as one created by calling :py:func:`rig.wizard.wizard_generator`. Returns ------- dict or None Returns a dictionary containing th...
def _get_files(self, attrs=None): """ Get a list of all files in this download; each entry has the attributes C{path} (relative to root), C{size} (in bytes), C{mtime}, C{prio} (0=off, 1=normal, 2=high), C{created}, and C{opened}. This is UNCACHED, use C{fetch("fi...
Get a list of all files in this download; each entry has the attributes C{path} (relative to root), C{size} (in bytes), C{mtime}, C{prio} (0=off, 1=normal, 2=high), C{created}, and C{opened}. This is UNCACHED, use C{fetch("files")} instead. @param attrs: Opt...
async def sendto(self, data, component): """ Send a datagram on the specified component. If the connection is not established, a `ConnectionError` is raised. """ active_pair = self._nominated.get(component) if active_pair: await active_pair.protocol.send_data...
Send a datagram on the specified component. If the connection is not established, a `ConnectionError` is raised.
def query_alternative_short_name(): """ Returns list of alternative short name by query query parameters --- tags: - Query functions parameters: - name: name in: query type: string required: false description: Alternative short name default: CV...
Returns list of alternative short name by query query parameters --- tags: - Query functions parameters: - name: name in: query type: string required: false description: Alternative short name default: CVAP - name: entry_name in: query ...
def _addDatasetAction(self, dataset): """ Adds an action for the inputed dataset to the toolbar :param dataset | <XChartDataset> """ # create the toolbar action action = QAction(dataset.name(), self) action.setIcon(XColorIcon(dataset.color())...
Adds an action for the inputed dataset to the toolbar :param dataset | <XChartDataset>
def add_hits_to_proteins(self, hmm_hit_list): '''Add HMMER results to Protein objects''' for org in self.organisms: print "adding SearchIO hit objects for", org.accession for hit in hmm_hit_list: hit_org_id = hit.id.split(',')[0] hit_prot_id = h...
Add HMMER results to Protein objects
def myRank(grade, badFormat, year, length): '''rank of candidateNumber in year Arguments: grade {int} -- a weighted average for a specific candidate number and year badFormat {dict} -- candNumber : [results for candidate] year {int} -- year you are in length {int} -- length of e...
rank of candidateNumber in year Arguments: grade {int} -- a weighted average for a specific candidate number and year badFormat {dict} -- candNumber : [results for candidate] year {int} -- year you are in length {int} -- length of each row in badFormat divided by 2 Returns: ...
def factory(cls, endpoint, timeout, *args, **kwargs): """ A factory function which returns connections which have succeeded in connecting and are ready for service (or raises an exception otherwise). """ start = time.time() kwargs['connect_timeout'] = timeout ...
A factory function which returns connections which have succeeded in connecting and are ready for service (or raises an exception otherwise).
def _matrix_adjust(self, X): """Adjust all values in X to encode for NaNs and infinities in the data. Parameters ---------- X : array-like, shape=(n_samples, n_feature) Input array of type int. Returns ------- X : array-like, shape=(n_samples, n_feat...
Adjust all values in X to encode for NaNs and infinities in the data. Parameters ---------- X : array-like, shape=(n_samples, n_feature) Input array of type int. Returns ------- X : array-like, shape=(n_samples, n_feature) Input array without any...
def diff(self, test_id_1, test_id_2, config=None, **kwargs): """ Create a diff report using test_id_1 as a baseline :param: test_id_1: test id to be used as baseline :param: test_id_2: test id to compare against baseline :param: config file for diff (optional) :param: **kwargs: keyword arguments...
Create a diff report using test_id_1 as a baseline :param: test_id_1: test id to be used as baseline :param: test_id_2: test id to compare against baseline :param: config file for diff (optional) :param: **kwargs: keyword arguments
def register_signals(self): """Register signals.""" from .models import Collection from .receivers import CollectionUpdater if self.app.config['COLLECTIONS_USE_PERCOLATOR']: from .percolator import collection_inserted_percolator, \ collection_removed_percolat...
Register signals.
def get_engine_from_session(dbsession: Session) -> Engine: """ Gets the SQLAlchemy :class:`Engine` from a SQLAlchemy :class:`Session`. """ engine = dbsession.bind assert isinstance(engine, Engine) return engine
Gets the SQLAlchemy :class:`Engine` from a SQLAlchemy :class:`Session`.
def computePerturbedExpectation(self, u_n, A_n, compute_uncertainty=True, uncertainty_method=None, warning_cutoff=1.0e-10, return_theta=False): """Compute the expectation of an observable of phase space function A(x) for a single new state. Parameters ---------- u_n : np.ndarray, float,...
Compute the expectation of an observable of phase space function A(x) for a single new state. Parameters ---------- u_n : np.ndarray, float, shape=(K, N_max) u_n[n] = u(x_n) - the energy of the new state at all N samples previously sampled. A_n : np.ndarray, float, shape=(K,...
def logMsg(self, msg, printMsg=True): """ logs a message and prints it to the screen """ time = datetime.datetime.now().strftime('%I:%M %p') self.log = '{0}\n{1} | {2}'.format(self.log, time, msg) if printMsg: print msg if self.addLogsToArcpyMessages:...
logs a message and prints it to the screen
def __get_all_child_accounts_as_array(self, account: Account) -> List[Account]: """ Returns the whole tree of child accounts in a list """ result = [] # ignore placeholders ? - what if a brokerage account has cash/stocks division? # if not account.placeholder: # continue ...
Returns the whole tree of child accounts in a list
def syncScrollbars(self): """ Synchronizes the various scrollbars within this chart. """ chart_hbar = self.uiChartVIEW.horizontalScrollBar() chart_vbar = self.uiChartVIEW.verticalScrollBar() x_hbar = self.uiXAxisVIEW.horizontalScrollBar() x_vbar =...
Synchronizes the various scrollbars within this chart.
def call_requests( requests: Union[Request, Iterable[Request]], methods: Methods, debug: bool ) -> Response: """ Takes a request or list of Requests and calls them. Args: requests: Request object, or a collection of them. methods: The list of methods that can be called. debug: I...
Takes a request or list of Requests and calls them. Args: requests: Request object, or a collection of them. methods: The list of methods that can be called. debug: Include more information in error responses.
def deprecated(operation=None): """ Mark an operation deprecated. """ def inner(o): o.deprecated = True return o return inner(operation) if operation else inner
Mark an operation deprecated.
def start_msstitch(exec_drivers, sysargs): """Passed all drivers of executable, checks which command is passed to the executable and then gets the options for a driver, parses them from command line and runs the driver""" parser = populate_parser(exec_drivers) args = parser.parse_args(sysargs[1:]) ...
Passed all drivers of executable, checks which command is passed to the executable and then gets the options for a driver, parses them from command line and runs the driver
def export_dist(self, args): """Copies a created dist to an output dir. This makes it easy to navigate to the dist to investigate it or call build.py, though you do not in general need to do this and can use the apk command instead. """ ctx = self.ctx dist = dist...
Copies a created dist to an output dir. This makes it easy to navigate to the dist to investigate it or call build.py, though you do not in general need to do this and can use the apk command instead.
def register_blueprint(self, blueprint: Blueprint, url_prefix: Optional[str]=None) -> None: """Register a blueprint on the app. This results in the blueprint's routes, error handlers etc... being added to the app. Arguments: blueprint: The blueprint to register. ...
Register a blueprint on the app. This results in the blueprint's routes, error handlers etc... being added to the app. Arguments: blueprint: The blueprint to register. url_prefix: Optional prefix to apply to all paths.
def version_cli(ctx, porcelain): # type: (click.Context, bool) -> None """ Show project version. Has sub commands. For this command to work you must specify where the project version is stored. You can do that with version_file conf variable. peltak supports multiple ways to store the project versi...
Show project version. Has sub commands. For this command to work you must specify where the project version is stored. You can do that with version_file conf variable. peltak supports multiple ways to store the project version. Right now you can store it in a python file using built-in __version__ vari...
def bigquery_schema(table): """Infer the schema of a BigQuery `table` object.""" fields = OrderedDict((el.name, dt.dtype(el)) for el in table.schema) partition_info = table._properties.get('timePartitioning', None) # We have a partitioned table if partition_info is not None: partition_field...
Infer the schema of a BigQuery `table` object.
def read_roi(fileobj): ''' points = read_roi(fileobj) Read ImageJ's ROI format. Points are returned in a nx2 array. Each row is in [row, column] -- that is, (y,x) -- order. ''' # This is based on: # http://rsbweb.nih.gov/ij/developer/source/ij/io/RoiDecoder.java.html # http://rsbweb.nih...
points = read_roi(fileobj) Read ImageJ's ROI format. Points are returned in a nx2 array. Each row is in [row, column] -- that is, (y,x) -- order.
def _RemoveAuthorizedKeys(self, user): """Remove a Linux user account's authorized keys file to prevent login. Args: user: string, the Linux user account to remove access. """ pw_entry = self._GetUser(user) if not pw_entry: return home_dir = pw_entry.pw_dir authorized_keys_file...
Remove a Linux user account's authorized keys file to prevent login. Args: user: string, the Linux user account to remove access.
def get_session_token(self): ''' get session token ''' # HTTP POST query to session authenticate API try: response = requests.post(self.__session_url__ + 'sessionauth/v1/authenticate', cert=(self.__crt__, self.__key__), verify=True) except...
get session token
def close_monomers(self, group, cutoff=4.0): """Returns a list of Monomers from within a cut off distance of the Monomer Parameters ---------- group: BaseAmpal or Subclass Group to be search for Monomers that are close to this Monomer. cutoff: float Dista...
Returns a list of Monomers from within a cut off distance of the Monomer Parameters ---------- group: BaseAmpal or Subclass Group to be search for Monomers that are close to this Monomer. cutoff: float Distance cut off. Returns ------- ne...
def convert(area_um, deform, emodulus, channel_width_in, channel_width_out, flow_rate_in, flow_rate_out, viscosity_in, viscosity_out, inplace=False): """convert area-deformation-emodulus triplet The conversion formula is described in :cite:`Mietke2015`. Para...
convert area-deformation-emodulus triplet The conversion formula is described in :cite:`Mietke2015`. Parameters ---------- area_um: ndarray Convex cell area [µm²] deform: ndarray Deformation emodulus: ndarray Young's Modulus [kPa] channel_width_in: float Ori...
def create_roles(apps, schema_editor): """Create the enterprise roles if they do not already exist.""" SystemWideEnterpriseRole = apps.get_model('enterprise', 'SystemWideEnterpriseRole') SystemWideEnterpriseRole.objects.update_or_create(name=ENTERPRISE_ADMIN_ROLE) SystemWideEnterpriseRole.objects.update...
Create the enterprise roles if they do not already exist.
def gettrace(self, burn=0, thin=1, chain=-1, slicing=None): """Return the trace (last by default). :Parameters: burn : integer The number of transient steps to skip. thin : integer Keep one in thin. chain : integer The index of the chain to fetch. I...
Return the trace (last by default). :Parameters: burn : integer The number of transient steps to skip. thin : integer Keep one in thin. chain : integer The index of the chain to fetch. If None, return all chains. The default is to return the last ...
def tocimxmlstr(value, indent=None): """ Return the CIM-XML representation of the CIM object or CIM data type, as a :term:`unicode string`. *New in pywbem 0.9.* The returned CIM-XML representation is consistent with :term:`DSP0201`. Parameters: value (:term:`CIM object` or :term:`CIM d...
Return the CIM-XML representation of the CIM object or CIM data type, as a :term:`unicode string`. *New in pywbem 0.9.* The returned CIM-XML representation is consistent with :term:`DSP0201`. Parameters: value (:term:`CIM object` or :term:`CIM data type` or :term:`Element`): The CIM ob...
def is_entailed_by(self, other): """ If the other is as or more specific than self""" other = BoolCell.coerce(other) if self.value == U or other.value == self.value: return True return False
If the other is as or more specific than self
def dial(self, number, timeout=5, callStatusUpdateCallbackFunc=None): """ Calls the specified phone number using a voice phone call :param number: The phone number to dial :param timeout: Maximum time to wait for the call to be established :param callStatusUpdateCallbackFunc: Callback f...
Calls the specified phone number using a voice phone call :param number: The phone number to dial :param timeout: Maximum time to wait for the call to be established :param callStatusUpdateCallbackFunc: Callback function that is executed if the call's status changes due to remote...
def get(self, key): """ Get parsed result. After :func:`parse` the argv, we can get the parsed results:: # command.option('-f', 'description of -f') command.get('-f') command.get('verbose') # we can also get ``verbose``: command.verbose ...
Get parsed result. After :func:`parse` the argv, we can get the parsed results:: # command.option('-f', 'description of -f') command.get('-f') command.get('verbose') # we can also get ``verbose``: command.verbose
def ProgramScanner(**kw): """Return a prototype Scanner instance for scanning executable files for static-lib dependencies""" kw['path_function'] = SCons.Scanner.FindPathDirs('LIBPATH') ps = SCons.Scanner.Base(scan, "ProgramScanner", **kw) return ps
Return a prototype Scanner instance for scanning executable files for static-lib dependencies
def inverse_transform(self, y, lengths=None): """Return label strings. Args: y: label id matrix. lengths: sentences length. Returns: list: list of list of strings. """ y = np.argmax(y, -1) inverse_y = [self._label_vocab.id2doc(ids) fo...
Return label strings. Args: y: label id matrix. lengths: sentences length. Returns: list: list of list of strings.
def patchproperty(*cls, **kwargs): """ class getter 함수 패치 decorator EX) class B(A): pass @patchproperty(B) def prop(self): return 'hello' :param cls: :param kwargs: """ def _patch(fun): m = kwargs.pop('property', None) or fun.__name__ p = proper...
class getter 함수 패치 decorator EX) class B(A): pass @patchproperty(B) def prop(self): return 'hello' :param cls: :param kwargs:
def text(self, selector): """Return text result that executed by given css selector :param selector: `str` css selector :return: `list` or `None` """ result = self.__bs4.select(selector) return [r.get_text() for r in result] \ if result.__len__() > 1 else \...
Return text result that executed by given css selector :param selector: `str` css selector :return: `list` or `None`
def num_samples(self): """ Return the total number of samples. """ with self.container.open_if_needed(mode='r') as cnt: return cnt.get(self.key)[0].shape[0]
Return the total number of samples.
def element_exists(self, element): """ Checks if given element exists. Usage:: >>> plist_file_parser = PlistFileParser("standard.plist") >>> plist_file_parser.parse() True >>> plist_file_parser.element_exists("String A") True ...
Checks if given element exists. Usage:: >>> plist_file_parser = PlistFileParser("standard.plist") >>> plist_file_parser.parse() True >>> plist_file_parser.element_exists("String A") True >>> plist_file_parser.element_exists("String Nemo")...
def _run__http(self, action, replace): """More complex HTTP query.""" query = action['query'] # self._debug = True url = '{type}://{host}{path}'.format(path=query['path'], **action) content = None method = query.get('method', "get").lower() self.debug("{} {} url={...
More complex HTTP query.
def hmmalign_sequences(self, hmm, sequences, output_file): '''Run hmmalign and convert output to aligned fasta format Parameters ---------- hmm: str path to hmm file sequences: str path to file of sequences to be aligned output_file: str ...
Run hmmalign and convert output to aligned fasta format Parameters ---------- hmm: str path to hmm file sequences: str path to file of sequences to be aligned output_file: str write sequences to this file Returns ------- ...
def get_write_fields(self): """ Get the list of fields used to write the header, separating record and signal specification fields. Returns the default required fields, the user defined fields, and their dependencies. Does NOT include `d_signal` or `e_d_signal`. ...
Get the list of fields used to write the header, separating record and signal specification fields. Returns the default required fields, the user defined fields, and their dependencies. Does NOT include `d_signal` or `e_d_signal`. Returns ------- rec_write_field...
def _group(self, group_data): """Return previously stored group or new group. Args: group_data (dict|obj): An Group dict or instance of Group object. Returns: dict|obj: The new Group dict/object or the previously stored dict/object. """ if isinstance(gro...
Return previously stored group or new group. Args: group_data (dict|obj): An Group dict or instance of Group object. Returns: dict|obj: The new Group dict/object or the previously stored dict/object.
def args(self, *args, **kwargs): """ Creates a ArgumentsExpectationRule and adds it to the expectation """ self._any_args = False self._arguments_rule.set_args(*args, **kwargs) return self
Creates a ArgumentsExpectationRule and adds it to the expectation
def watch(models, criterion=None, log="gradients", log_freq=100): """ Hooks into the torch model to collect gradients and the topology. Should be extended to accept arbitrary ML models. :param (torch.Module) models: The model to hook, can be a tuple :param (torch.F) criterion: An optional loss val...
Hooks into the torch model to collect gradients and the topology. Should be extended to accept arbitrary ML models. :param (torch.Module) models: The model to hook, can be a tuple :param (torch.F) criterion: An optional loss value being optimized :param (str) log: One of "gradients", "parameters", "al...
async def handle_action(self, action_type, payload, **kwds): """ The default action Handler has no action. """ # if there is a service attached to the action handler if hasattr(self, 'service'): # handle roll calls await roll_call_handler(self.service,...
The default action Handler has no action.
def get_cluster( self, project_id, region, cluster_name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Gets the resource representation for a cluster in a project. ...
Gets the resource representation for a cluster in a project. Example: >>> from google.cloud import dataproc_v1beta2 >>> >>> client = dataproc_v1beta2.ClusterControllerClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' ...
def read(self, output_tile): """ Read from written process output. Parameters ---------- output_tile : BufferedTile or tile index tuple Member of the output tile pyramid (not necessarily the process pyramid, if output has a different metatiling setting) ...
Read from written process output. Parameters ---------- output_tile : BufferedTile or tile index tuple Member of the output tile pyramid (not necessarily the process pyramid, if output has a different metatiling setting) Returns ------- data : Nu...
def download(self, content, filename=None, media_type=None, charset='UTF-8'): """Send content as attachment (downloadable file). The *content* is sent after setting Content-Disposition header such that the client prompts the user to save the content locally as a file. A...
Send content as attachment (downloadable file). The *content* is sent after setting Content-Disposition header such that the client prompts the user to save the content locally as a file. An HTTP response status code may be specified as *content*. If the status code is not ``200``, then...
def sendEmail(sender, recipients, subject, body, attachments=None, cc=None, bcc=None, contentType='text/html', server=None, useMSExchange=None, encoding='utf-8', rais...
Sends an email from the inputted email address to the list of given recipients with the inputted subject and body. This will also attach the inputted list of attachments to the email. The server value will default to mail.<sender_domain> and you can use a ':' to specify a port for the server. ...
def stopall(self, sudo=False, quiet=True): '''stop ALL instances. This command is only added to the command group as it doesn't make sense to call from a single instance Parameters ========== sudo: if the command should be done with sudo (exposes different set of instances)...
stop ALL instances. This command is only added to the command group as it doesn't make sense to call from a single instance Parameters ========== sudo: if the command should be done with sudo (exposes different set of instances)
def mstmap(args): """ %prog mstmap bcffile/vcffile > matrixfile Convert bcf/vcf format to mstmap input. """ from jcvi.assembly.geneticmap import MSTMatrix p = OptionParser(mstmap.__doc__) p.add_option("--dh", default=False, action="store_true", help="Double haploid populat...
%prog mstmap bcffile/vcffile > matrixfile Convert bcf/vcf format to mstmap input.
def nearest_neighbor(x, tSet): """[summary] Implements the nearest neighbor algorithm Arguments: x {[tupel]} -- [vector] tSet {[dict]} -- [training set] Returns: [type] -- [result of the AND-function] """ assert isinstance(x, tuple) and isinstance(tSet, dict) curren...
[summary] Implements the nearest neighbor algorithm Arguments: x {[tupel]} -- [vector] tSet {[dict]} -- [training set] Returns: [type] -- [result of the AND-function]
def loadFromTemplate(template, stim=None): """Initialized this stimulus from a saved *template* :param template: doc from a previously stored stimulus via :class:`templateDoc` :type template: dict """ stim = StimulusModel.loadFromTemplate(template, stim=stim) qstim = QSt...
Initialized this stimulus from a saved *template* :param template: doc from a previously stored stimulus via :class:`templateDoc` :type template: dict
def acceptedUser(self, logType): '''Verify enetered user name is on accepted MCC logbook list.''' from urllib2 import urlopen, URLError, HTTPError import json isApproved = False userName = str(self.logui.userName.text()) if userName == "": re...
Verify enetered user name is on accepted MCC logbook list.
def allocate_ids(self, partial_keys): """ Allocate IDs for incomplete keys. .. seealso:: https://cloud.google.com/datastore/docs/reference/rest/v1/projects/allocateIds :param partial_keys: a list of partial keys. :type partial_keys: list :return: a list of f...
Allocate IDs for incomplete keys. .. seealso:: https://cloud.google.com/datastore/docs/reference/rest/v1/projects/allocateIds :param partial_keys: a list of partial keys. :type partial_keys: list :return: a list of full keys. :rtype: list
def _prm_write_shared_table(self, key, hdf5_group, fullname, **kwargs): """Creates a new empty table""" first_row = None description = None if 'first_row' in kwargs: first_row = kwargs.pop('first_row') if not 'description' in kwargs: description = ...
Creates a new empty table
def text_(s, encoding='latin-1', errors='strict'): ''' If ``s`` is an instance of ``binary_type``, return ``s.decode(encoding, errors)``, otherwise return ``s`` ''' return s.decode(encoding, errors) if isinstance(s, binary_type) else s
If ``s`` is an instance of ``binary_type``, return ``s.decode(encoding, errors)``, otherwise return ``s``
def input_value(self, locator, text): """Sets the given value into text field identified by `locator`. This is an IOS only keyword, input value makes use of set_value See `introduction` for details about locating elements. """ self._info("Setting text '%s' into text field '%s'" % (...
Sets the given value into text field identified by `locator`. This is an IOS only keyword, input value makes use of set_value See `introduction` for details about locating elements.
def download(sess_id_or_alias, files, dest): """ Download files from a running container. \b SESSID: Session ID or its alias given when creating the session. FILES: Paths inside container. """ if len(files) < 1: return with Session() as session: try: print_wa...
Download files from a running container. \b SESSID: Session ID or its alias given when creating the session. FILES: Paths inside container.
def format_block(block, nlspaces=0): """ Format the given block of text, trimming leading/trailing empty lines and any leading whitespace that is common to all lines. The purpose is to let us list a code block as a multiline, triple-quoted Python string, taking care of indentation concerns. ...
Format the given block of text, trimming leading/trailing empty lines and any leading whitespace that is common to all lines. The purpose is to let us list a code block as a multiline, triple-quoted Python string, taking care of indentation concerns. http://code.activestate.com/recipes/145672/
def _walk_through(job_dir, display_progress=False): ''' Walk through the job dir and return jobs ''' serial = salt.payload.Serial(__opts__) for top in os.listdir(job_dir): t_path = os.path.join(job_dir, top) for final in os.listdir(t_path): load_path = os.path.join(t_pa...
Walk through the job dir and return jobs
def dump_data_peek(data, base = 0, separator = ' ', width = 16, bits = None): """ ...
Dump data from pointers guessed within the given binary data. @type data: str @param data: Dictionary mapping offsets to the data they point to. @type base: int @param base: Base offset. @type bits: int @param bits: (Optional) Number of bits of the targe...
def as_list(self, key): """ A convenience method which fetches the specified value, guaranteeing that it is a list. >>> a = ConfigObj() >>> a['a'] = 1 >>> a.as_list('a') [1] >>> a['a'] = (1,) >>> a.as_list('a') [1] >>> a['a'] = [1]...
A convenience method which fetches the specified value, guaranteeing that it is a list. >>> a = ConfigObj() >>> a['a'] = 1 >>> a.as_list('a') [1] >>> a['a'] = (1,) >>> a.as_list('a') [1] >>> a['a'] = [1] >>> a.as_list('a') [1]
def cli(env, account_id, content_url, type, cname): """Create an origin pull mapping.""" manager = SoftLayer.CDNManager(env.client) manager.add_origin(account_id, type, content_url, cname)
Create an origin pull mapping.
def split(self): """Split the phase. When a phase is exhausted, it gets split into a pair of phases to be further solved. The split happens like so: 1) Select the first unsolved package scope. 2) Find some common dependency in the first N variants of the scope. 3) Split ...
Split the phase. When a phase is exhausted, it gets split into a pair of phases to be further solved. The split happens like so: 1) Select the first unsolved package scope. 2) Find some common dependency in the first N variants of the scope. 3) Split the scope into two: [:N] and...
def remove_pane(self, pane): """ Remove a :class:`.Pane`. (Look in all windows.) """ assert isinstance(pane, Pane) for w in self.windows: w.remove_pane(pane) # No panes left in this window? if not w.has_panes: # Focus next. ...
Remove a :class:`.Pane`. (Look in all windows.)
def step(self, path=None, peer_table=None): """ Run one step of this algorithm: * find the set of missing zonefiles * try to fetch each of them * store them * update our zonefile database Fetch rarest zonefiles first, but batch whenever possible. ...
Run one step of this algorithm: * find the set of missing zonefiles * try to fetch each of them * store them * update our zonefile database Fetch rarest zonefiles first, but batch whenever possible. Return the number of zonefiles fetched
def namedb_get_all_revealed_namespace_ids( self, current_block ): """ Get all non-expired revealed namespaces. """ query = "SELECT namespace_id FROM namespaces WHERE op = ? AND reveal_block < ?;" args = (NAMESPACE_REVEAL, current_block + NAMESPACE_REVEAL_EXPIRE ) namespace_rows = namedb_qu...
Get all non-expired revealed namespaces.
def epilogue(app_name): """ Return the epilogue for the help command. """ app_name = clr.stringc(app_name, "bright blue") command = clr.stringc("command", "cyan") help = clr.stringc("--help", "green") return "\n%s %s %s for more info on a command\n" % (app_name, ...
Return the epilogue for the help command.
def fqscreen_plot (self): """ Makes a fancy custom plot which replicates the plot seen in the main FastQ Screen program. Not useful if lots of samples as gets too wide. """ categories = list() getCats = True data = list() p_types = OrderedDict() p_types['multiple...
Makes a fancy custom plot which replicates the plot seen in the main FastQ Screen program. Not useful if lots of samples as gets too wide.
def compile_and_process(self, in_path): """compile a file, save it to the ouput file if the inline flag true""" out_path = self.path_mapping[in_path] if not self.embed: pdebug("[%s::%s] %s -> %s" % ( self.compiler_name, self.name, os.p...
compile a file, save it to the ouput file if the inline flag true
def h2o_explained_variance_score(y_actual, y_predicted, weights=None): """ Explained variance regression score function. :param y_actual: H2OFrame of actual response. :param y_predicted: H2OFrame of predicted response. :param weights: (Optional) sample weights :returns: the explained variance s...
Explained variance regression score function. :param y_actual: H2OFrame of actual response. :param y_predicted: H2OFrame of predicted response. :param weights: (Optional) sample weights :returns: the explained variance score.
def _get_and_count_containers(self, custom_cgroups=False, healthchecks=False): """List all the containers from the API, filter and count them.""" # Querying the size of containers is slow, we don't do it at each run must_query_size = self.collect_container_size and self._latest_size_query == 0 ...
List all the containers from the API, filter and count them.
def _create_chrome_options(self): """Create and configure a chrome options object :returns: chrome options object """ # Create Chrome options options = webdriver.ChromeOptions() if self.config.getboolean_optional('Driver', 'headless'): self.logger.debug("Run...
Create and configure a chrome options object :returns: chrome options object
def _cldf2wld(dataset): """Make lingpy-compatible dictinary out of cldf main data.""" header = [f for f in dataset.dataset.lexeme_class.fieldnames() if f != 'ID'] D = {0: ['lid'] + [h.lower() for h in header]} for idx, row in enumerate(dataset.objects['FormTable']): row = deepcopy(row) r...
Make lingpy-compatible dictinary out of cldf main data.
def build_mine_matrix(self, w, h, minenum): """random fill cells with mines and increments nearest mines num in adiacent cells""" self.minecount = 0 matrix = [[Cell(30, 30, x, y, self) for x in range(w)] for y in range(h)] for i in range(0, minenum): x = random.randint(0, w -...
random fill cells with mines and increments nearest mines num in adiacent cells
def _l_cv_weight(self, donor_catchment): """ Return L-CV weighting for a donor catchment. Methodology source: Science Report SC050050, eqn. 6.18 and 6.22a """ try: dist = donor_catchment.similarity_dist except AttributeError: dist = self._similari...
Return L-CV weighting for a donor catchment. Methodology source: Science Report SC050050, eqn. 6.18 and 6.22a
def bait(self, maskmiddle='f', k='19'): """ Use bbduk to perform baiting :param maskmiddle: boolean argument treat the middle base of a kmer as a wildcard; increases sensitivity in the presence of errors. :param k: keyword argument for length of kmers to use in the analyses ...
Use bbduk to perform baiting :param maskmiddle: boolean argument treat the middle base of a kmer as a wildcard; increases sensitivity in the presence of errors. :param k: keyword argument for length of kmers to use in the analyses
def split_param_vec(param_vec, rows_to_alts, design, return_all_types=False): """ Parameters ---------- param_vec : 1D ndarray. Elements should all be ints, floats, or longs. Should have as many elements as there are parameters being estimated. rows_to_alts : 2D scipy sparse matrix. ...
Parameters ---------- param_vec : 1D ndarray. Elements should all be ints, floats, or longs. Should have as many elements as there are parameters being estimated. rows_to_alts : 2D scipy sparse matrix. There should be one row per observation per available alternative and one ...
def seq_site_length(self): """Calculate length of a single sequence site based upon relative positions specified in peak descriptions. :return: Length of sequence site. :rtype: :py:class:`int` """ relative_positions_set = set() for peak_descr in self: relativ...
Calculate length of a single sequence site based upon relative positions specified in peak descriptions. :return: Length of sequence site. :rtype: :py:class:`int`