code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def project_describe(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /project-xxxx/describe API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Projects#API-method%3A-%2Fproject-xxxx%2Fdescribe """ return DXHTTPRequest('/%s/describe' % object...
Invokes the /project-xxxx/describe API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Projects#API-method%3A-%2Fproject-xxxx%2Fdescribe
async def run(self): """Entrypoint to route messages between plugins.""" logging.info('Starting message router...') coroutines = set() while True: coro = self._poll_channel() coroutines.add(coro) _, coroutines = await asyncio.wait(coroutines, timeout=...
Entrypoint to route messages between plugins.
def to_json(self): """Get date time as a dictionary.""" return {'year': self.year, 'month': self.month, 'day': self.day, 'hour': self.hour, 'minute': self.minute}
Get date time as a dictionary.
def abort(self): """ Immediately close the stream, without sending remaining buffers or performing a proper shutdown. """ if self._state == _State.CLOSED: self._invalid_state("abort() called") return self._force_close(None)
Immediately close the stream, without sending remaining buffers or performing a proper shutdown.
def service_account_email(self): """The service account email.""" if self._service_account_id is None: self._service_account_id = app_identity.get_service_account_name() return self._service_account_id
The service account email.
def write_AST(wdl_file, outdir=None): ''' Writes a file with the AST for a wdl file in the outdir. ''' if outdir is None: outdir = os.getcwd() with open(os.path.join(outdir, 'AST.out'), 'w') as f: with open(wdl_file, 'r') as wdl: wdl_string = wdl.read() ast = ...
Writes a file with the AST for a wdl file in the outdir.
def _fragment_one_level(self, mol_graphs): """ Perform one step of iterative fragmentation on a list of molecule graphs. Loop through the graphs, then loop through each graph's edges and attempt to remove that edge in order to obtain two disconnected subgraphs, aka two new fragments. If ...
Perform one step of iterative fragmentation on a list of molecule graphs. Loop through the graphs, then loop through each graph's edges and attempt to remove that edge in order to obtain two disconnected subgraphs, aka two new fragments. If successful, check to see if the new fragments are alrea...
def _set_result_from_operation(self): """Set the result or exception from the operation if it is complete.""" # This must be done in a lock to prevent the polling thread # and main thread from both executing the completion logic # at the same time. with self._completion_lock: ...
Set the result or exception from the operation if it is complete.
def write_error_response(self, message): """ Writes the message as part of the response and sets 404 status. """ self.set_status(404) response = self.make_error_response(str(message)) now = time.time() spent = now - self.basehandler_starttime response[constants.RESPONSE_KEY_EXECUTION_TIM...
Writes the message as part of the response and sets 404 status.
def get_type_name_in_language(cls, type_name, sub_type, language): """ Get the type for the given language Args: type_name (str): the type to convert language (str): the language to use Returns: a type name in the given language ...
Get the type for the given language Args: type_name (str): the type to convert language (str): the language to use Returns: a type name in the given language Example: get_type_name_in_language("Varchar", "python") ...
def ftp_walk(ftpconn: FTP, rootpath=''): """Recursively traverse an ftp directory to discovery directory listing.""" current_directory = rootpath try: directories, files = directory_listing(ftpconn, current_directory) except ftplib.error_perm: return # Yield before recursion y...
Recursively traverse an ftp directory to discovery directory listing.
def populate_fw_dev(self, fw_id, mgmt_ip, new): """Populate the class after a restart. """ for cnt in self.res: used = self.res.get(cnt).get('used') if mgmt_ip == self.res[cnt].get('mgmt_ip'): if new: self.res[cnt]['used'] = used + 1 ...
Populate the class after a restart.
def create_gp(self): """ Create GnuPlot file. """ nb_bams = len(self.bams) gp_parts = [ textwrap.dedent( """\ set log x set log x2 #set format x "10^{{%L}}" set format x2 "10^{{%L}}" set x2tics unset xtics """ ), ...
Create GnuPlot file.
def parse(argv, level=0): """ Parse sub-arguments between `[` and `]` recursively. Examples -------- ``` >>> argv = ['--foo', 'bar', '--buz', '[', 'qux', '--quux', 'corge', ']'] >>> subarg.parse(argv) ['--foo', 'bar', '--buz', ['qux', '--quux', 'corge']] ``` Parameters ----...
Parse sub-arguments between `[` and `]` recursively. Examples -------- ``` >>> argv = ['--foo', 'bar', '--buz', '[', 'qux', '--quux', 'corge', ']'] >>> subarg.parse(argv) ['--foo', 'bar', '--buz', ['qux', '--quux', 'corge']] ``` Parameters ---------- argv : list of strings ...
def get_all_derivatives(self, address): """Get all targets derived directly or indirectly from the specified target. Note that the specified target itself is not returned. :API: public """ ret = [] direct = self.get_direct_derivatives(address) ret.extend(direct) for t in direct: ...
Get all targets derived directly or indirectly from the specified target. Note that the specified target itself is not returned. :API: public
def isheavy(self): """ Check if the current selection is too large. """ selection_size_bytes = self._calc_selection_size() if selection_size_bytes > self.MAX_DATA_ARRAY_SIZE: return True else: return False
Check if the current selection is too large.
def create_job(self, emails): """ Create a new bulk verification job for the list of emails. :param list emails: Email addresses to verify. :return: A Job object. """ resp = self._call(endpoint='bulk', data={'input_location': '1', 'input': '\n'.join(emails)}) retu...
Create a new bulk verification job for the list of emails. :param list emails: Email addresses to verify. :return: A Job object.
def open(self, filename=None): ''' Open a browser tab with the notebook path specified relative to the notebook directory. If no filename is specified, open the root of the notebook server. ''' if filename is None: address = self.address + 'tree' else...
Open a browser tab with the notebook path specified relative to the notebook directory. If no filename is specified, open the root of the notebook server.
def compute_kv(self, memory_antecedent): """Compute key/value Tensor kv. Args: memory_antecedent: a Tensor with dimensions {memory_input_dim} + other_dims Returns: a Tensor with dimensions memory_heads_dims + {key_dim} + other_dims """ if not self.shared_kv: raise ...
Compute key/value Tensor kv. Args: memory_antecedent: a Tensor with dimensions {memory_input_dim} + other_dims Returns: a Tensor with dimensions memory_heads_dims + {key_dim} + other_dims
def is_admin(): """ https://stackoverflow.com/a/19719292 @return: True if the current user is an 'Admin' whatever that means (root on Unix), otherwise False. Warning: The inner function fails unless you have Windows XP SP2 or higher. The failure causes a traceback to be printed and this func...
https://stackoverflow.com/a/19719292 @return: True if the current user is an 'Admin' whatever that means (root on Unix), otherwise False. Warning: The inner function fails unless you have Windows XP SP2 or higher. The failure causes a traceback to be printed and this function to return False.
def call_api(self, resource_path, method, path_params=None, query_params=None, header_params=None, body=None, post_params=None, files=None, response_type=None, auth_settings=None, asynchronous=None, _return_http_data_only=None, collection_formats=None,...
Makes the HTTP request (synchronous) and return the deserialized data. To make an async request, set the asynchronous parameter. :param resource_path: Path to method endpoint. :param method: Method to call. :param path_params: Path parameters in the url. :param query_params: Que...
def add_changes_markup(dom, ins_nodes, del_nodes): """ Add <ins> and <del> tags to the dom to show changes. """ # add markup for inserted and deleted sections for node in reversed(del_nodes): # diff algorithm deletes nodes in reverse order, so un-reverse the # order for this iteratio...
Add <ins> and <del> tags to the dom to show changes.
def reference_id(self, reference_id): """ Sets the reference_id of this Order. A client specified identifier to associate an entity in another system with this order. :param reference_id: The reference_id of this Order. :type: str """ if reference_id is None: ...
Sets the reference_id of this Order. A client specified identifier to associate an entity in another system with this order. :param reference_id: The reference_id of this Order. :type: str
def __extract_location_coordinates(self, image_size, color_segment): """! @brief Extracts coordinates of specified image segment. @param[in] image_size (list): Image size presented as a [width x height]. @param[in] color_segment (list): Image segment whose coordinates shoul...
! @brief Extracts coordinates of specified image segment. @param[in] image_size (list): Image size presented as a [width x height]. @param[in] color_segment (list): Image segment whose coordinates should be extracted. @return (list) Coordinates of each pixel.
def _parse_header(line: str) -> Tuple[str, Dict[str, str]]: r"""Parse a Content-type like header. Return the main content-type and a dictionary of options. >>> d = "form-data; foo=\"b\\\\a\\\"r\"; file*=utf-8''T%C3%A4st" >>> ct, d = _parse_header(d) >>> ct 'form-data' >>> d['file'] == r'T\...
r"""Parse a Content-type like header. Return the main content-type and a dictionary of options. >>> d = "form-data; foo=\"b\\\\a\\\"r\"; file*=utf-8''T%C3%A4st" >>> ct, d = _parse_header(d) >>> ct 'form-data' >>> d['file'] == r'T\u00e4st'.encode('ascii').decode('unicode_escape') True >...
def jaccard(seq1, seq2): """Compute the Jaccard distance between the two sequences `seq1` and `seq2`. They should contain hashable items. The return value is a float between 0 and 1, where 0 means equal, and 1 totally different. """ set1, set2 = set(seq1), set(seq2) return 1 - len(set1 & set2) / float(len(set1 ...
Compute the Jaccard distance between the two sequences `seq1` and `seq2`. They should contain hashable items. The return value is a float between 0 and 1, where 0 means equal, and 1 totally different.
def source_sum(self): """ The sum of the unmasked ``data`` values within the source segment. .. math:: F = \\sum_{i \\in S} (I_i - B_i) where :math:`F` is ``source_sum``, :math:`(I_i - B_i)` is the ``data``, and :math:`S` are the unmasked pixels in the source segment. ...
The sum of the unmasked ``data`` values within the source segment. .. math:: F = \\sum_{i \\in S} (I_i - B_i) where :math:`F` is ``source_sum``, :math:`(I_i - B_i)` is the ``data``, and :math:`S` are the unmasked pixels in the source segment. Non-finite pixel values (e.g. NaN,...
def overlap(intv1, intv2): """Overlaping of two intervals""" return max(0, min(intv1[1], intv2[1]) - max(intv1[0], intv2[0]))
Overlaping of two intervals
def search(self, initial_ids, initial_cache): """Beam search for sequences with highest scores.""" state, state_shapes = self._create_initial_state(initial_ids, initial_cache) finished_state = tf.while_loop( self._continue_search, self._search_step, loop_vars=[state], shape_invariants=[stat...
Beam search for sequences with highest scores.
def append_filter(self, structure_filter): """ Adds a filter. Args: structure_filter (StructureFilter): A filter implementating the AbstractStructureFilter API. Tells transmuter waht structures to retain. """ hdict = structure_filter.a...
Adds a filter. Args: structure_filter (StructureFilter): A filter implementating the AbstractStructureFilter API. Tells transmuter waht structures to retain.
def _get_ref_lengths(self): '''Gets the length of each reference sequence from the header of the bam. Returns dict name => length''' sam_reader = pysam.Samfile(self.bam, "rb") return dict(zip(sam_reader.references, sam_reader.lengths))
Gets the length of each reference sequence from the header of the bam. Returns dict name => length
def check(self, user, provider, permission, **kwargs): ''' user - django User or UserSocialAuth instance provider - name of publisher provider permission - if backend maintains check permissions vk - binary mask in int format ...
user - django User or UserSocialAuth instance provider - name of publisher provider permission - if backend maintains check permissions vk - binary mask in int format facebook - scope string
def encrypt(self, message): """ Encrypt the given message """ if not isinstance(message, (bytes, str)): raise TypeError return hashlib.sha1(message.encode('utf-8')).hexdigest()
Encrypt the given message
def convert_to_string(ndarr): """ Writes the contents of the numpy.ndarray ndarr to bytes in IDX format and returns it. """ with contextlib.closing(BytesIO()) as bytesio: _internal_write(bytesio, ndarr) return bytesio.getvalue()
Writes the contents of the numpy.ndarray ndarr to bytes in IDX format and returns it.
def symmetric_difference(self, that): """ Return a new set with elements in either *self* or *that* but not both. """ diff = self._set.symmetric_difference(that) return self._fromset(diff, key=self._key)
Return a new set with elements in either *self* or *that* but not both.
def commit(self, wait=False, additionalParams={}): """ Commit is called once all parts are uploaded during a multipart Add Item or Update Item operation. The parts are combined into a file, and the original file is overwritten during an Update Item operation. This is an asynchron...
Commit is called once all parts are uploaded during a multipart Add Item or Update Item operation. The parts are combined into a file, and the original file is overwritten during an Update Item operation. This is an asynchronous call and returns immediately. Status can be used to check t...
def get_parser(): """Parse command-line arguments.""" parser = ArgumentParser(description='a command-line web scraping tool') parser.add_argument('query', metavar='QUERY', type=str, nargs='*', help='URLs/files to scrape') parser.add_argument('-a', '--attributes', type=str, nargs=...
Parse command-line arguments.
def all_substrings(s): ''' yields all substrings of a string ''' join = ''.join for i in range(1, len(s) + 1): for sub in window(s, i): yield join(sub)
yields all substrings of a string
def purge_metadata(self, force=False): """Instance-based version of ProcessMetadataManager.purge_metadata_by_name() that checks for process liveness before purging metadata. :param bool force: If True, skip process liveness check before purging metadata. :raises: `ProcessManager.MetadataError` when OSE...
Instance-based version of ProcessMetadataManager.purge_metadata_by_name() that checks for process liveness before purging metadata. :param bool force: If True, skip process liveness check before purging metadata. :raises: `ProcessManager.MetadataError` when OSError is encountered on metadata dir removal.
def http_auth(self): """ Returns ``True`` if valid http auth credentials are found in the request header. """ if 'HTTP_AUTHORIZATION' in self.request.META.keys(): authmeth, auth = self.request.META['HTTP_AUTHORIZATION'].split( ' ', 1) if a...
Returns ``True`` if valid http auth credentials are found in the request header.
def _tflearn_features(train_config, args): """Builds the tf.learn feature list. All numerical features are just given real_valued_column because all the preprocessing transformations are done in preprocess_input. Categoriacl features are processed here depending if the vocab map (from string to int) was appl...
Builds the tf.learn feature list. All numerical features are just given real_valued_column because all the preprocessing transformations are done in preprocess_input. Categoriacl features are processed here depending if the vocab map (from string to int) was applied in preprocess_input. Args: train_conf...
def get_bin_hierarchy_design_session(self): """Gets the bin hierarchy design session. return: (osid.resource.BinHierarchyDesignSession) - a ``BinHierarchyDesignSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_bin_hierarchy...
Gets the bin hierarchy design session. return: (osid.resource.BinHierarchyDesignSession) - a ``BinHierarchyDesignSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_bin_hierarchy_design()`` is ``false`` *compl...
def add_comment(self, line): """Add a Comment object to the section Used during initial parsing mainly Args: line (str): one line in the comment """ if not isinstance(self.last_item, Comment): comment = Comment(self._structure) self._structur...
Add a Comment object to the section Used during initial parsing mainly Args: line (str): one line in the comment
def _process_irrational_functions(self, functions, predetermined_function_addrs, blockaddr_to_function): """ For unresolveable indirect jumps, angr marks those jump targets as individual functions. For example, usually the following pattern is seen: sub_0x400010: push ebp ...
For unresolveable indirect jumps, angr marks those jump targets as individual functions. For example, usually the following pattern is seen: sub_0x400010: push ebp mov esp, ebp ... cmp eax, 10 ja end mov eax, jumptable[eax] ...
def _resolve_source(self, source): """Resolve source to filepath if it is a directory.""" if os.path.isdir(source): sources = glob.glob(os.path.join(source, '*.sbml')) if len(sources) == 0: raise ModelLoadError('No .sbml file found in source directory') ...
Resolve source to filepath if it is a directory.
def _safe_minmax(values): """Calculate min and max of array with guards for nan and inf.""" # Nan and inf guarded min and max isfinite = np.isfinite(values) if np.any(isfinite): # Only use finite values values = values[isfinite] minval = np.min(values) maxval = np.max(values) ...
Calculate min and max of array with guards for nan and inf.
def add_text(self, text, x, y, **kws): """add text to plot""" self.panel.add_text(text, x, y, **kws)
add text to plot
def float_range(string, minimum, maximum, inf, sup): """ Requires values to be a number and range in a certain range. :param string: Value to validate :param minimum: Minimum value to accept :param maximum: Maximum value to accept :param inf: Infimum value to accept :param sup: Supremum value t...
Requires values to be a number and range in a certain range. :param string: Value to validate :param minimum: Minimum value to accept :param maximum: Maximum value to accept :param inf: Infimum value to accept :param sup: Supremum value to accept :type string: str :type minimum: float :...
def ensure_dtraj_list(dtrajs): r"""Makes sure that dtrajs is a list of discrete trajectories (array of int) """ if isinstance(dtrajs, list): # elements are ints? then wrap into a list if is_list_of_int(dtrajs): return [np.array(dtrajs, dtype=int)] else: for i...
r"""Makes sure that dtrajs is a list of discrete trajectories (array of int)
def includes_ofs(self, ofs): """:return: True if the given absolute offset is contained in the cursors current region **Note:** cursor must be valid for this to work""" # unroll methods return (self._region._b + self._ofs) <= ofs < (self._region._b + self._ofs + self._size)
:return: True if the given absolute offset is contained in the cursors current region **Note:** cursor must be valid for this to work
def main(): """ NAME plotdi_e.py DESCRIPTION plots equal area projection from dec inc data and cones of confidence (Fisher, kent or Bingham or bootstrap). INPUT FORMAT takes dec/inc as first two columns in space delimited file SYNTAX plotdi_e.py [command li...
NAME plotdi_e.py DESCRIPTION plots equal area projection from dec inc data and cones of confidence (Fisher, kent or Bingham or bootstrap). INPUT FORMAT takes dec/inc as first two columns in space delimited file SYNTAX plotdi_e.py [command line options] OPTIONS...
def unpickle(self, parent): """Sets the parent pointer references for the module *and* all of its child classes that also have pointer references.""" self.parent = parent self._unpickle_collection(self.members) self._unpickle_collection(self.executables) self._unpickle_co...
Sets the parent pointer references for the module *and* all of its child classes that also have pointer references.
def threadProfileCode(func, *args, **kwargs): 'Toplevel thread profile wrapper.' with ThreadProfiler(threading.current_thread()) as prof: try: prof.thread.status = threadProfileCode.__wrapped__(func, *args, **kwargs) except EscapeException as e: prof.thread.status = e
Toplevel thread profile wrapper.
def process_formdata(self, valuelist): """Process form data.""" if valuelist: self.data = '\n'.join([ x.strip() for x in filter(lambda x: x, '\n'.join(valuelist).splitlines()) ])
Process form data.
def start(lang, session_id, owner, env, mount, tag, resources, cluster_size): ''' Prepare and start a single compute session without executing codes. You may use the created session to execute codes using the "run" command or connect to an application service provided by the session using the "app" ...
Prepare and start a single compute session without executing codes. You may use the created session to execute codes using the "run" command or connect to an application service provided by the session using the "app" command. \b LANG: The name (and version/platform tags appended after a colon) of...
def get_bulb_state(self): """Get the relay state.""" self.get_status() try: self.state = self.data['on'] except TypeError: self.state = False return bool(self.state)
Get the relay state.
def parse(self, url_data): """Parse XML URL data.""" self.url_data = url_data self.loc = False self.url = u"" data = url_data.get_content() isfinal = True try: self.parser.Parse(data, isfinal) except ExpatError as expaterr: self.url...
Parse XML URL data.
def unproject(self, image_points): """Find (up to scale) 3D coordinate of an image point This is the inverse of the `project` function. The resulting 3D points are only valid up to an unknown scale. Parameters ---------------------- image_points : (2, N) ndarray ...
Find (up to scale) 3D coordinate of an image point This is the inverse of the `project` function. The resulting 3D points are only valid up to an unknown scale. Parameters ---------------------- image_points : (2, N) ndarray Image points Returns ---...
def cdn_set_conf(self, cname, originConf, environment, token): """ The cdn_set_conf method enables the user to update an existing origin configuration in the CDN. The cdn_get_conf returns the token in the response and the cdn_set_conf requires a token as one of the parameters. ...
The cdn_set_conf method enables the user to update an existing origin configuration in the CDN. The cdn_get_conf returns the token in the response and the cdn_set_conf requires a token as one of the parameters. The set action is valid only if the token returned is equal to the ...
def filter_ids(self): """ Return the Metrics on this shelf in the order in which they were used. """ return self._sorted_ingredients([ d.id for d in self.values() if isinstance(d, Filter) ])
Return the Metrics on this shelf in the order in which they were used.
def get_completed_or_runnning(self, id, **kwargs): """ Deprecated, use /builds/{id} This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> d...
Deprecated, use /builds/{id} This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) ...
def get_port_channel_detail_output_lacp_partner_system_id(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_port_channel_detail = ET.Element("get_port_channel_detail") config = get_port_channel_detail output = ET.SubElement(get_port_channel_det...
Auto Generated Code
def fmt_tag(cur_namespace, tag, val): """ Processes a documentation reference. """ if tag == 'type': fq_val = val if '.' not in val and cur_namespace is not None: fq_val = cur_namespace.name + '.' + fq_val return fq_val elif tag == 'route': if ':' in val: ...
Processes a documentation reference.
def new_timestamped_uid(bits=32): """ A unique id that begins with an ISO timestamp followed by fractions of seconds and bits of randomness. The advantage of this is it sorts nicely by time, while still being unique. Example: 20150912T084555Z-378465-43vtwbx """ return "%s-%s" % (re.sub('[^\w.]', '', datetim...
A unique id that begins with an ISO timestamp followed by fractions of seconds and bits of randomness. The advantage of this is it sorts nicely by time, while still being unique. Example: 20150912T084555Z-378465-43vtwbx
def transaction(self, connection=None, **kwargs): """ a simple context manager useful for when you want to wrap a bunch of db calls in a transaction http://docs.python.org/2/library/contextlib.html http://docs.python.org/release/2.5/whatsnew/pep-343.html example -- w...
a simple context manager useful for when you want to wrap a bunch of db calls in a transaction http://docs.python.org/2/library/contextlib.html http://docs.python.org/release/2.5/whatsnew/pep-343.html example -- with self.transaction() # do a bunch of calls ...
def add_header(self, key, value, **params): """ Add a header to the collection, including potential parameters. Args: key (str): The name of the header value (str): The value to store under that key params: Option parameters to be appended to the value, ...
Add a header to the collection, including potential parameters. Args: key (str): The name of the header value (str): The value to store under that key params: Option parameters to be appended to the value, automatically formatting them in a standard way
def get(self): """Get run list""" LOG.info('Returning all ansible runs') response = [] for run in self.backend_store.list_runs(): response.append(run_model.format_response(run)) return response
Get run list
def listify(generator_func): ''' Converts generator functions into list returning functions. @listify def test(): yield 1 test() # => [1] ''' def list_func(*args, **kwargs): return degenerate(generator_func(*args, **kwargs)) return list_func
Converts generator functions into list returning functions. @listify def test(): yield 1 test() # => [1]
def get_db_prep_value(self, value, connection, prepared=False): """Convert a value to DB storage. Returns the state name. """ if not prepared: value = self.get_prep_value(value) return value.state.name
Convert a value to DB storage. Returns the state name.
def copy(self): """ Return a new :class:`~pywbem.CIMInstance` object that is a copy of this CIM instance. This is a middle-deep copy; any mutable types in attributes except the following are copied, so besides these exceptions, modifications of the original object will n...
Return a new :class:`~pywbem.CIMInstance` object that is a copy of this CIM instance. This is a middle-deep copy; any mutable types in attributes except the following are copied, so besides these exceptions, modifications of the original object will not affect the returned copy, and vic...
def cv(params, dtrain, num_boost_round=10, nfold=3, metrics=(), obj=None, feval=None, fpreproc=None, as_pandas=True, show_progress=None, show_stdv=True, seed=0): # pylint: disable = invalid-name """Cross-validation with given paramaters. Parameters ---------- params : dict Boo...
Cross-validation with given paramaters. Parameters ---------- params : dict Booster params. dtrain : DMatrix Data to be trained. num_boost_round : int Number of boosting iterations. nfold : int Number of folds in CV. metrics : list of strings Evaluati...
def update_auth_settings(self, account_id, auth_settings): """ Update the authentication settings for the passed account_id. https://canvas.instructure.com/doc/api/authentication_providers.html#method.account_authorization_configs.update_sso_settings """ url = ACCOUNTS_API.forma...
Update the authentication settings for the passed account_id. https://canvas.instructure.com/doc/api/authentication_providers.html#method.account_authorization_configs.update_sso_settings
def read_csv(self, dtype=False, parse_dates=True, *args, **kwargs): """Fetch the target and pass through to pandas.read_csv Don't provide the first argument of read_csv(); it is supplied internally. """ import pandas t = self.resolved_url.get_resource().get_target() k...
Fetch the target and pass through to pandas.read_csv Don't provide the first argument of read_csv(); it is supplied internally.
def _translate_residue(self, selection, default_atomname='CA'): """Translate selection for a single res to make_ndx syntax.""" m = self.RESIDUE.match(selection) if not m: errmsg = "Selection {selection!r} is not valid.".format(**vars()) logger.error(errmsg) ra...
Translate selection for a single res to make_ndx syntax.
def data(self, message): """ Send LMTP DATA command and process the server response. The server response is stored as a list of dicts in <DspamClient>.results, keyed on the recipient name(s). Depending on the server return data, different formats are available: * LMTP mo...
Send LMTP DATA command and process the server response. The server response is stored as a list of dicts in <DspamClient>.results, keyed on the recipient name(s). Depending on the server return data, different formats are available: * LMTP mode -- Dict containing 'accepted', a bool i...
def read_host_file(path): """ Read the host file. Return a list of hostnames. """ res = [] for l in file(path).xreadlines(): hostname = l.strip() if hostname: res.append(hostname) return res
Read the host file. Return a list of hostnames.
def _can_change_or_view(model, user): """ Return True iff `user` has either change or view permission for `model`. """ model_name = model._meta.model_name app_label = model._meta.app_label can_change = user.has_perm(app_label + '.change_' + model_name) can_view = user.has_perm(app_label + '....
Return True iff `user` has either change or view permission for `model`.
def convert_mean(binaryproto_fname, output=None): """Convert caffe mean Parameters ---------- binaryproto_fname : str Filename of the mean output : str, optional Save the mean into mxnet's format Returns ------- NDArray Mean in ndarray """ mean_blob = ca...
Convert caffe mean Parameters ---------- binaryproto_fname : str Filename of the mean output : str, optional Save the mean into mxnet's format Returns ------- NDArray Mean in ndarray
def fromtimestamp(cls, t, tz=None): """Construct a datetime from a POSIX timestamp (like time.time()). A timezone info object may be passed in as well. """ _check_tzinfo_arg(tz) converter = _time.localtime if tz is None else _time.gmtime t, frac = divmod(t, 1.0) ...
Construct a datetime from a POSIX timestamp (like time.time()). A timezone info object may be passed in as well.
def setup_pod(build_file_path, manage_dir=None, local_requirements=None): """ This must be called by the project's build.py for pyntofdjango to function. You can specify it directly with the optional manage_dir kwarg. :param build_file_path: E.g. os.path.abspath(__file__) :param manage_dir: Optio...
This must be called by the project's build.py for pyntofdjango to function. You can specify it directly with the optional manage_dir kwarg. :param build_file_path: E.g. os.path.abspath(__file__) :param manage_dir: Optional, Searched for if None. :param local_requirements: Optional, pip requirements f...
def date2timestamp(dte): '''Convert a *dte* into a valid unix timestamp.''' seconds = mktime(dte.timetuple()) if isinstance(dte, datetime): return seconds + dte.microsecond / 1000000.0 else: return int(seconds)
Convert a *dte* into a valid unix timestamp.
def get_likes(self) -> Iterator['Profile']: """Iterate over all likes of the post. A :class:`Profile` instance of each likee is yielded.""" if self.likes == 0: # Avoid doing additional requests if there are no comments return likes_edges = self._field('edge_media_preview_...
Iterate over all likes of the post. A :class:`Profile` instance of each likee is yielded.
def get_gene_source_set(gtf): """ get a dictionary of the set of all sources for a gene """ gene_to_source = {} db = get_gtf_db(gtf) for feature in complete_features(db): gene_id = feature['gene_id'][0] sources = gene_to_source.get(gene_id, set([])).union(set([feature.source])) ...
get a dictionary of the set of all sources for a gene
def get_image(self, image, chunk_size=DEFAULT_DATA_CHUNK_SIZE): """ Get a tarball of an image. Similar to the ``docker save`` command. Args: image (str): Image name to get chunk_size (int): The number of bytes returned by each iteration of the generator. ...
Get a tarball of an image. Similar to the ``docker save`` command. Args: image (str): Image name to get chunk_size (int): The number of bytes returned by each iteration of the generator. If ``None``, data will be streamed as it is received. Default: 2 MB ...
def get_vnetwork_dvpgs_input_vcenter(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_vnetwork_dvpgs = ET.Element("get_vnetwork_dvpgs") config = get_vnetwork_dvpgs input = ET.SubElement(get_vnetwork_dvpgs, "input") vcenter = ET.SubElem...
Auto Generated Code
def _set_trap(self, v, load=False): """ Setter method for trap, mapped from YANG variable /snmp_server/enable/trap (container) If this variable is read-only (config: false) in the source YANG file, then _set_trap is considered as a private method. Backends looking to populate this variable should ...
Setter method for trap, mapped from YANG variable /snmp_server/enable/trap (container) If this variable is read-only (config: false) in the source YANG file, then _set_trap is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_trap() directly...
def decipher(self,string): """Decipher string using FracMorse cipher according to initialised key. Example:: plaintext = FracMorse('ROUNDTABLECFGHIJKMPQSVWXYZ').decipher(ciphertext) :param string: The string to decipher. :returns: The enciphered string. """ ...
Decipher string using FracMorse cipher according to initialised key. Example:: plaintext = FracMorse('ROUNDTABLECFGHIJKMPQSVWXYZ').decipher(ciphertext) :param string: The string to decipher. :returns: The enciphered string.
def get_entity_propnames(entity): """ Get entity property names :param entity: Entity :type entity: sqlalchemy.ext.declarative.api.DeclarativeMeta :returns: Set of entity property names :rtype: set """ ins = entity if isinstance(entity, InstanceState) else inspect(entity) ...
Get entity property names :param entity: Entity :type entity: sqlalchemy.ext.declarative.api.DeclarativeMeta :returns: Set of entity property names :rtype: set
def number_of_sections(self): """int: number of sections.""" if not self._is_parsed: self._Parse() self._is_parsed = True return len(self._sections)
int: number of sections.
def get_collection_rules(self, raw=False): """ Download the collection rules """ logger.debug("Attemping to download collection rules from %s", self.collection_rules_url) net_logger.info("GET %s", self.collection_rules_url) try: req = sel...
Download the collection rules
def _prof(self, key): '''Get _Prof object. ''' p = self._profs.get(key, None) if not p: self._profs[key] = p = _Prof() return p
Get _Prof object.
def select(self, selection_specs=None, selection_mode='edges', **selection): """ Allows selecting data by the slices, sets and scalar values along a particular dimension. The indices should be supplied as keywords mapping between the selected dimension and value. Additionally sel...
Allows selecting data by the slices, sets and scalar values along a particular dimension. The indices should be supplied as keywords mapping between the selected dimension and value. Additionally selection_specs (taking the form of a list of type.group.label strings, types or functions) ...
def backup_file(*, file, host): """ Perform backup action on set driver :param file: Name of the file to be used by the driver :param host: Corresponding host name associated with file """ if _driver: log.msg_debug("[{driver}] Backing up file '{file}'" .format(driv...
Perform backup action on set driver :param file: Name of the file to be used by the driver :param host: Corresponding host name associated with file
def _sanity_check_args(args): """Ensure dependent arguments are correctly specified """ if "scheduler" in args and "queue" in args: if args.scheduler and not args.queue: if args.scheduler != "sge": return "IPython parallel scheduler (-s) specified. This also requires a qu...
Ensure dependent arguments are correctly specified
def read(self, symbol, as_of=None): """ Return current metadata saved for `symbol` Parameters ---------- symbol : `str` symbol name for the item as_of : `datetime.datetime` return entry valid at given time Returns ------- ...
Return current metadata saved for `symbol` Parameters ---------- symbol : `str` symbol name for the item as_of : `datetime.datetime` return entry valid at given time Returns ------- metadata
def get_params(names): """Return a dictionary with params from request. TODO: I think we don't use it anymore and it should be removed before someone gets hurt. """ params = {} for name in names: value = request.form.get(name) or request.files.get(name) if value is not None: ...
Return a dictionary with params from request. TODO: I think we don't use it anymore and it should be removed before someone gets hurt.
def ports(self) -> dict: """Create a smaller dictionary containing all ports.""" return { param: self[param].raw for param in self if param.startswith(IOPORT) }
Create a smaller dictionary containing all ports.
def _edge_both_nodes(nodes: List[Node]): """Get edges where both the source and target are in the list of nodes.""" node_ids = [node.id for node in nodes] return and_( Edge.source_id.in_(node_ids), Edge.target_id.in_(node_ids), )
Get edges where both the source and target are in the list of nodes.
def _generate_noise_temporal_drift(trs, tr_duration, basis="discrete_cos", period=150, ): """Generate the drift noise Create a trend (either sine or discrete_cos), of a g...
Generate the drift noise Create a trend (either sine or discrete_cos), of a given period and random phase, to represent the drift of the signal over time Parameters ---------- trs : int How many volumes (aka TRs) are there tr_duration : float How long in seconds is each volum...
def arabic_digit_to_thai_digit(text: str) -> str: """ :param str text: Text with Arabic digits such as '1', '2', '3' :return: Text with Arabic digits being converted to Thai digits such as '๑', '๒', '๓' """ if not text or not isinstance(text, str): return "" newtext = [] for ch in t...
:param str text: Text with Arabic digits such as '1', '2', '3' :return: Text with Arabic digits being converted to Thai digits such as '๑', '๒', '๓'